@spicenet-io/spiceflow-ui 3.3.84-zerofix.0 → 3.3.84
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,7 +100,7 @@
|
|
|
100
100
|
from { transform: rotate(0deg); }
|
|
101
101
|
to { transform: rotate(360deg); }
|
|
102
102
|
}
|
|
103
|
-
`})]})},jl="0xa9059cbb";function Fl(e){const t=new Map;for(const s of e){if(s.amount<=0n)continue;const o=M.getAddress(s.token),r=M.getAddress(s.to),a=`${o.toLowerCase()}:${r.toLowerCase()}`,l=t.get(a);l?l.amount+=s.amount:t.set(a,{token:o,to:r,amount:s.amount})}return[...t.values()]}function Bl(e,t){return`0x${t}${e.slice(4)}`}function so(e,t){return kr(e,t)}function kr(e,t,s){const o=Tl(t,e),r=Math.floor(Date.now()/1e3)+60*10,a=B.hashChainBatches(o);return{user:e,...s?{chainAuthorizations:s}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:r,chainBatches:a.map((l,d)=>({hash:l.hash,chainId:l.chainId,tokenTransfers:o[d].domain==="spicenet"?[]:o[d].tokenTransfers??[],calls:l.calls}))}]}}function Tl(e,t){return e.map(s=>{if(s.domain==="spicenet"||s.calls.length===0)return s;const o=new Set((s.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&M.getAddress(a.to).toLowerCase()===t.toLowerCase()).map(a=>M.getAddress(a.token).toLowerCase()));if(o.size===0)return s;let r=0;for(const a of s.calls){if(!a.data?.startsWith(jl))break;try{const l=M.decodeFunctionData({abi:h.P,data:a.data});if(l.functionName!=="transfer")break;const[d]=l.args;if(d.toLowerCase()===t.toLowerCase()||!o.has(M.getAddress(a.to).toLowerCase()))break;r+=1}catch{break}}return r===0?s:{...s,calls:s.calls.slice(r)}})}function os(e,t,s,o){if(e.some(f=>f.domain==="spicenet"))return e;const r=s?.intents.flatMap(f=>f.batches),a=f=>f.from==="escrow",l=e.map(f=>{const p=r?.find(v=>v.chainId===f.chainId);if(!p)return f;const g=ts(p),x=g.totalFee;if(x<=0n)return f;const m=(f.tokenTransfers??[]).find(v=>a(v)&&M.getAddress(v.to).toLowerCase()===t.toLowerCase()&&!B.isNativeToken(M.getAddress(v.token)));if(!m)return f;const y=M.getAddress(m.token);let C=!1;const k=(f.tokenTransfers??[]).map(v=>C||!a(v)||M.getAddress(v.to).toLowerCase()!==t.toLowerCase()||M.getAddress(v.token).toLowerCase()!==y.toLowerCase()?v:(C=!0,{...v,amount:o?.payoutAlreadyGross?BigInt(v.amount):BigInt(v.amount)+x}));if(!C)return f;const b=[];g.spicenetFee>0n&&b.push({to:y,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[B.SPICE_PLATFORM_FEE_RECIPIENT,g.spicenetFee]})});const A=g.gasFee+g.bridgeFee;return A>0n&&b.push({to:y,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[B.SPICE_GAS_FEE_RECIPIENT,A]})}),{...f,tokenTransfers:k,calls:[...b,...f.calls]}}),d=l.flatMap(f=>(f.tokenTransfers??[]).filter(a).map(p=>{const g=M.getAddress(p.token),x=M.getAddress(p.to),m=[{token:g,to:x,amount:BigInt(p.amount)}];return{chainId:f.chainId,transfers:Fl(m)}}));if(d.length===0)return e;const u=o?.requestTimestampMs??Date.now(),c=BigInt(Math.floor(u/1e3))+3600n;return[{chainId:B.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:d.map((f,p)=>{const g=M.keccak256(M.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,f.transfers[0].token,f.transfers.reduce((m,y)=>m+y.amount,0n),BigInt(f.chainId),BigInt(u+p)])),x=Bl(g,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:M.encodeFunctionData({abi:B.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${f.chainId}`,idempotenceKey:x,nbf:0n,exp:c,metadata:"{}",transfers:f.transfers.map(m=>({token:m.token.toLowerCase(),to:m.to,amount:m.amount}))}]})}})},...l]}function fn(e,t){return t?e.some(s=>(s.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount)>=t.grossAmount)):!1}function vr(e){return!e.isSemi7702&&e.isDirectDeposit&&!e.isSourceDestToken}function no(e){const t=e.selectedAsset?.asset,s=e.selectedAsset?.amount;if(!(!t||!s))return M.parseUnits(s,t.decimals)}function Sr(e){return e.map(t=>({r:t.r,s:t.s,yParity:t.yParity,address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce)}))}function Ml(e,t){if(e.length!==t.length)return!1;const s=B.hashChainBatches(e),o=B.hashChainBatches(t);return s.every((r,a)=>r.hash===o[a]?.hash)}async function hn({user:e,batches:t,authorizations:s,adjustBatchesForEstimate:o}){let r=t;const a=Sr(s);for(let l=0;l<10;l+=1){const d=await h.relayerService.estimateActionFees(kr(e,r,a)),u=await o({feeEstimate:d,batches:r});if(!u||Ml(r,u))return r;r=u}throw new Error("Fee estimate did not converge. Please retry.")}function is(e,t){const s=e.selectedAsset?.asset;if(!s||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=M.parseUnits(e.selectedAsset.amount,s.decimals),r=t?.grossAmount??o;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:o,grossAmount:M.formatUnits(r,s.decimals),grossAmountWei:r})}async function mn(e,t,s){const o=[...new Set(s.filter(a=>a.domain!=="spicenet").map(a=>a.chainId))],r=[];for(const a of o){const l=h.getClientForChain(a),d=h.getDelegateContractAddress(a),u=await B.getAccountNonce(t,l),c=await e.actions.signAuthorization({contractAddress:d,chainId:a,nonce:Number(u)});r.push(c)}return r}async function oo(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 r=s??await mn(e,o,t),a=B.hashChainBatches(t),l=Math.floor(Date.now()/1e3)+60*10,d=a.map(x=>x.hash),u=M.keccak256(M.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(l),d])),c=await e.actions.signMessage({raw:u}),f=typeof c=="string"?c:c.signature;if(!f)throw new Error("Failed to sign intent authorization");const p={mode:"7702",signatureType:"ecdsa",signature:f,nbf:0,exp:l,chainBatches:a.map((x,m)=>{const y=t[m],C=y.domain==="spicenet";return{hash:x.hash,chainId:x.chainId,tokenTransfers:C?[]:y.tokenTransfers??[],calls:x.calls}})},g=await h.relayerService.createAction({user:o,chainAuthorizations:Sr(r),intents:[p]});if(g){const x=h.createInitialSteps(t,h.getChainName),[m,y]=g.intentIds[0].split("/"),C=parseInt(y||"0",10),k=g.intentIds[0];e.startStatusPolling(g.intentIds[0],x),await nr({actionId:m,intentIndex:C,intentId:k,totalSteps:t.length,isSpicenetStep:b=>t[b]?.domain==="spicenet",maxExecuteAttemptsForStep:b=>t[b]?.domain==="spicenet"?6:3,maxPolls:72})}}async function Rl(e){let t=is(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 mn(e,s,t),r=Date.now();let a=os([...t],s,void 0,{requestTimestampMs:r}),l;a=await hn({user:s,batches:a,authorizations:o,adjustBatchesForEstimate:({feeEstimate:d})=>{const u=vs(d,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,actionAmount:no(e)});return u?(l={grossAmount:u.grossAmount,netAmount:u.netAmount,feeAmount:u.totalFee??0n},t=is(e,l),os([...t],s,d,{payoutAlreadyGross:fn(t,l),requestTimestampMs:r})):null}}),await oo(e,a,o)}async function Dl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");const s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,r=M.parseUnits(e.selectedAsset.amount,o.decimals),a=o.chainId,l=e.escrowAddress||B.getEscrowContractAddress(a),d=B.normalizeNativeTokenAddress(o.address),u=o.isNative||B.isNativeToken(d),c=Date.now();let f;const p=s.some(k=>k.tokenTransfers?.some(b=>b.from==="escrow")),g=k=>({chainId:a,calls:u?[{to:l,value:k,data:"0x"}]:[{to:d,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[l,k]})}]}),x=(k,b,A,v)=>{const w=g(k);if(!p)return[w,...b];const R=os([...b],t,A,{payoutAlreadyGross:fn(b,v),requestTimestampMs:c});return[w,...R]};let m=is(e),y=x(r,m);const C=await mn(e,t,y);p&&(y=await hn({user:t,batches:y,authorizations:C,adjustBatchesForEstimate:({feeEstimate:k})=>{const b=vs(k,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});return b?(f={grossAmount:b.grossAmount,netAmount:b.netAmount,feeAmount:b.totalFee??0n},m=is(e,f),x(f.grossAmount,m,k,f)):null}})),await oo(e,y,C)}async function Nl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(e.onLockExecute){const T=e.resolveLockBatches();if(T.length===0)throw new Error("No lock batches configured");const F=e.selectedAsset.asset,S=M.parseUnits(e.selectedAsset.amount,F.decimals),j=await e.onLockExecute({asset:F,amount:e.selectedAsset.amount,amountWei:S,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:T});j&&e.onLockSuccess?.(j);return}const s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,r=M.parseUnits(e.selectedAsset.amount,o.decimals),a=o.chainId,l=e.escrowAddress||B.getEscrowContractAddress(a),d=B.normalizeNativeTokenAddress(o.address),u=o.isNative||B.isNativeToken(d),c=s.some(T=>T.tokenTransfers?.some(F=>F.from==="escrow")),f=Date.now();let p;const g=T=>({chainId:a,calls:u?[{to:l,value:T,data:"0x"}]:[{to:d,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[l,T]})}]}),x=(T,F,S,j)=>{const I=g(T);if(!c)return[I,...F];const N=os([...F],t,S,{payoutAlreadyGross:fn(F,j),requestTimestampMs:f});return[I,...N]};let m=is(e),y=x(r,m);const C=await mn(e,t,y);c&&(y=await hn({user:t,batches:y,authorizations:C,adjustBatchesForEstimate:({feeEstimate:T})=>{const F=vs(T,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});return F?(p={grossAmount:F.grossAmount,netAmount:F.netAmount,feeAmount:F.totalFee??0n},m=is(e,p),x(p.grossAmount,m,T,p)):null}}));const k=p?.grossAmount??r,b=await e.externalWallet.getEthereumProvider();let A=null;try{const T=await b.request({method:"eth_chainId"});A=parseInt(T,16)}catch{A=null}A!==a&&await h.ensureWalletOnChain(b,a);const v=h.getChainConfig(a),w=M.createWalletClient({account:e.externalWalletAddress,chain:v?.viemChain,transport:M.custom(b)}),R=h.getClientForChain(a),E=async T=>{if(T<=0n)return;const F=u?await w.sendTransaction({to:t,value:T,chain:v?.viemChain}):await w.sendTransaction({to:d,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[t,T]}),chain:v?.viemChain});if((await R.waitForTransactionReceipt({hash:F,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed")};await E(k);let P=k;if(c)for(let T=0;T<4;T+=1){y=await hn({user:t,batches:y,authorizations:C,adjustBatchesForEstimate:({feeEstimate:S})=>{const j=vs(S,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});return j?(p={grossAmount:j.grossAmount,netAmount:j.netAmount,feeAmount:j.totalFee??0n},m=is(e,p),x(p.grossAmount,m,S,p)):null}});const F=p?.grossAmount??r;if(F<=P)break;await E(F-P),P=F}await oo(e,y,C)}async function Pl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702||vr(e)){const l=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address;if(!l)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let d=is(e);if(d.length===0)throw new Error("No lock batches configured");const u=e.selectedAsset.asset,c=M.parseUnits(e.selectedAsset.amount,u.decimals),f=u.chainId,p=e.escrowAddress||B.getEscrowContractAddress(f),g=B.normalizeNativeTokenAddress(u.address),x=u.isNative||B.isNativeToken(g),m=d.some(v=>v.tokenTransfers?.some(w=>w.from==="escrow")),y=v=>({chainId:f,calls:x?[{to:p,value:v,data:"0x"}]:[{to:g,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[p,v]})}]}),C=(v,w,R)=>{const E=y(v);if(!m)return[E,...w];const P=os([...w],l,R,{payoutAlreadyGross:w.some(T=>(T.tokenTransfers??[]).some(F=>F.from==="escrow"&&BigInt(F.amount)>=v))});return[E,...P]};let k=C(c,d),b=null,A;for(let v=0;v<4;v+=1){const w=await h.relayerService.estimateActionFees(so(l,k)),R=vs(w,{symbol:u.symbol,decimals:u.decimals,actionAmount:c});if(!R)return b;const E={grossAmount:R.grossAmount,netAmount:R.netAmount,feeAmount:R.totalFee??0n},P=A?.grossAmount===E.grossAmount&&A?.netAmount===E.netAmount&&A?.feeAmount===E.feeAmount;if(b=R,A=E,d=is(e,E),k=C(E.grossAmount,d,w),P)break}return b}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let s=is(e);if(s.length===0)throw new Error("No lock batches configured");let o=os([...s],t),r=null;for(let l=0;l<4;l+=1){const d=await h.relayerService.estimateActionFees(so(t,o)),u=vs(d,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:no(e)});if(!u)return null;const c={grossAmount:u.grossAmount},f=r?.grossAmount===u.grossAmount&&r?.netAmount===u.netAmount&&r?.totalFee===u.totalFee;if(r=u,s=is(e,c),o=os([...s],t,d,{payoutAlreadyGross:fn(s,c)}),f)break}if(r)return r;const a=await h.relayerService.estimateActionFees(so(t,o));return vs(a,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:no(e)})}async function Wl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.activeSignerWallet??e.externalWallet,s=e.activeSignerAddress??e.externalWalletAddress;if(!s||!t)throw new Error("Please connect your wallet to continue");const o=e.resolveLockBatches();if(o.length===0)throw new Error("No lock batches configured");const r=o.find(p=>p.chainId===e.lockChainId)||o[0];if(!r)throw new Error("No lock batch for lock chain");const a=await t.getEthereumProvider();let l=null;try{const p=await a.request({method:"eth_chainId"});l=parseInt(p,16)}catch{l=null}l!==e.lockChainId&&await h.ensureWalletOnChain(a,e.lockChainId);const d=h.getChainConfig(e.lockChainId),u=M.createWalletClient({account:s,chain:d?.viemChain,transport:M.custom(a)}),c=h.getClientForChain(e.lockChainId);let f;for(const p of r.calls){const g=await u.sendTransaction({to:p.to,data:p.data,value:p.value,chain:d?.viemChain});if((await c.waitForTransactionReceipt({hash:g,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");f=g}f&&e.onLockSuccess?.(f)}async function Ul(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=h.sanitizeError(s,""),r=typeof s?.shortMessage=="string"?s.shortMessage:typeof s?.message=="string"?s.message:"";e.ui.setError(o||r||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Wl(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await Nl(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{vr(e)?await Dl(e):await Rl(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}}const Ir=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,lockBatches:o,lockTokenSymbol:r,lockTokenLogoURI:a,destinationInputHook:l,sourceAssetInputHook:d,lockDurationHook:u,lockChainId:c,durationOptions:f,votingPowerEstimate:p,escrowAddress:g,includeWalletAssets:x=!1,destinationTokenAddress:m,onLockSuccess:y,onLockExecute:C,sourceToDestinationConversionRate:k,estimatedOutputAmount:b,onAddFunds:A,buildSpicenetBatch:v,styles:w,dark:R=!1})=>{const{theme:E,dark:P,primaryColor:T,dk:F}=h.useSpiceBrand(w,R),S=E.typography.fontFamily,j=i.useContext(h.SpiceFlowProviderContext),I=j?.mode||"7702",N=!!j?.isWhitelistGateActive,D=I!=="7702",L=i.useMemo(()=>j?.supportedChainIds??[],[j?.supportedChainIds]),Q=i.useMemo(()=>{if(N)return[];const X=j?.allowedTokens;if(!X||X.length===0)return[];const be=new Set(X.map(Ke=>Ke.toLowerCase())),pt=[],wt=new Set;for(const Ke of L){const Rt=h.getChainConfig(Ke);for(const lt of Rt?.supportedTokens??[]){if(!be.has(lt.symbol.toLowerCase()))continue;const _t=`${Ke}:${lt.address.toLowerCase()}`;wt.has(_t)||(wt.add(_t),pt.push(M.getAddress(lt.address)))}}return pt},[j?.allowedTokens,L,N]),W=P?F.cardBg:w?.assetSelector?.backgroundColor||w?.secondaryBackground||"#e9e9e9",O=P?`1px solid ${F.cardBorder}`:"0.5px solid #A8A8A7",H=P?"12px":"6px",$=P?F.textPrimary:"#111827",U=P?F.textSecondary:"#6b7280",z=i.useMemo(()=>({...w,assetSelector:{...w?.assetSelector,backgroundColor:P?F.cardBg:w?.assetSelector?.backgroundColor,borderRadius:P?"12px":w?.assetSelector?.borderRadius},secondaryBackground:P?F.cardBg:w?.secondaryBackground}),[w,P]),le=i.useMemo(()=>P?{...E,colors:{...E.colors,secondary:F.cardBg,surfaceHover:F.hoverBg,border:F.cardBorder,borderHover:F.inputBorder}}:E,[P,E]),[q,_]=i.useState(null),[ce,we]=i.useState(0),de=u?.selectedDurationIdx??ce,fe=u?.setSelectedDurationIdx??we,[he,Z]=i.useState(!1),[re,J]=i.useState(null),[te,ue]=i.useState(null),[Ce,xe]=i.useState(!1),[V,oe]=i.useState(!1),[ee,Ae]=i.useState(null),[Te,$e]=i.useState(!1),rt=i.useRef(0),[jt,Ze]=i.useState(!1),[ye,Fe]=i.useState(null);Gt.useWalletClient(),Gt.useSwitchChain();const{chain:Me,address:Qe}=Gt.useAccount();Gt.useConfig();const _e=i.useRef(Me);i.useEffect(()=>{_e.current=Me},[Me]);const nt=h.useWallet(),{isReady:K,isAuthenticated:Ue,isConnected:Se,address:Ye,provider:Ve,actions:zt}=nt,{externalWallet:It,embeddedAddress:at,externalAddress:Ie,activeWallet:ft,activeAddress:At}=h.useProviderWallets(),{intentStatus:Re,startStatusPolling:Ot,clearStatus:je}=No({checkStepStatus:(X,be)=>h.relayerService.checkStepStatus(X,be),retryStep:async(X,be)=>{const[pt,wt]=X.split("/"),Ke=parseInt(wt||"0",10);await h.relayerService.executeStep(pt,Ke,be,{action:"execute"})},maxRetries:3}),{assets:Mt,refetch:Dt}=Qs({address:Ye,supportedChains:L,enabled:e&&Se&&!D&&!N,refetchInterval:3e4}),Oe=i.useMemo(()=>{if(N)return[];if(Q.length===0)return Mt;const X=new Set(Q.map(be=>be.toLowerCase()));return Mt.filter(be=>X.has(be.address.toLowerCase()))},[Mt,Q,N]),me=h.useEmbeddedWalletAddress(),Le=Ie||Qe,Ge=D?At??Le:me,Lt=i.useMemo(()=>{if(!x)return[];if(N)return m?[M.getAddress(m)]:[];const X=new Set,be=[],pt=wt=>{if(!wt)return;const Ke=wt.toLowerCase();X.has(Ke)||(X.add(Ke),be.push(M.getAddress(wt)))};m&&pt(m);for(const wt of Q)pt(wt);return be},[x,D,m,Q,N]),ke=i.useMemo(()=>Lt.map(X=>X.toLowerCase()).sort().join(","),[Lt]),Tt=i.useMemo(()=>JSON.stringify([...L||[]].sort()),[L]),[xt,dt]=i.useState([]),ze=i.useRef(0),Ht=i.useRef(async()=>{}),kt=i.useCallback(async()=>{if(!x||!Ge||Lt.length===0){ze.current++,dt([]);return}const X=++ze.current,be=M.getAddress(Ge),pt=D?L&&L.length>0?L:[c]:[c],wt=Lt.map(G=>{const Y=G.toLowerCase();if(m&&h.addressesEqual(G,m)){const pe=h.getChainConfig(c)?.supportedTokens?.find(ie=>h.addressesEqual(ie.address,Y));return{address:G,chainId:c,configToken:pe?{decimals:pe.decimals,symbol:pe.symbol,name:pe.name,logo:pe.logo}:void 0}}for(const pe of pt){const ie=h.getChainConfig(pe)?.supportedTokens?.find(Pe=>h.addressesEqual(Pe.address,Y));if(ie)return{address:G,chainId:pe,configToken:{decimals:ie.decimals,symbol:ie.symbol,name:ie.name,logo:ie.logo}}}return{address:G,chainId:c}}),Ke=new Map;for(const G of wt){const Y=Ke.get(G.chainId)||[];Y.push(G),Ke.set(G.chainId,Y)}const Rt=async(G,Y)=>{try{const pe=await $t.readContract(G,{address:Y.address,abi:h.P,functionName:"balanceOf",args:[be]});let ie,Pe,De,Je;if(Y.configToken)ie=Y.configToken.decimals,Pe=Y.configToken.symbol,De=Y.configToken.name,Je=Y.configToken.logo;else{const[Yt,Xt,Wt]=await Promise.all([$t.readContract(G,{address:Y.address,abi:h.P,functionName:"decimals",args:[]}).catch(()=>18),$t.readContract(G,{address:Y.address,abi:h.P,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),$t.readContract(G,{address:Y.address,abi:h.P,functionName:"name",args:[]}).catch(()=>"TOKEN")]);ie=Number(Yt),Pe=Xt,De=Wt}const ct=!!m&&h.addressesEqual(Y.address,m)&&Y.chainId===c;ct&&a&&(Je=a),ct&&r&&!Y.configToken&&(Pe==="TOKEN"&&(Pe=r),De==="TOKEN"&&(De=r));const Pt=parseFloat((Number(pe)/Math.pow(10,ie)).toFixed(6));return{address:Y.address,name:De,symbol:Pe,decimals:ie,balance:pe,balanceFormatted:Pt,balanceUsd:0,logoURI:Je,isNative:!1,chainId:Y.chainId}}catch{return null}},lt=await Promise.all(Array.from(Ke.entries()).map(async([G,Y])=>{let pe;try{pe=h.getClientForChain(G)}catch{return[]}const ie=[],Pe=[];for(const Je of Y){const ct=ie.length;ie.push({address:Je.address,abi:h.P,functionName:"balanceOf",args:[be]}),Je.configToken||ie.push({address:Je.address,abi:h.P,functionName:"decimals",args:[]},{address:Je.address,abi:h.P,functionName:"symbol",args:[]},{address:Je.address,abi:h.P,functionName:"name",args:[]}),Pe.push({start:ct,item:Je})}let De=null;try{De=await pe.multicall({contracts:ie})}catch{De=null}return De?Pe.map(({start:Je,item:ct})=>{const Pt=De[Je],Yt=Pt?.status==="success"?Pt.result:0n;let Xt,Wt,ss,bs;if(ct.configToken)Xt=ct.configToken.decimals,Wt=ct.configToken.symbol,ss=ct.configToken.name,bs=ct.configToken.logo;else{const Jt=De[Je+1],ns=De[Je+2],As=De[Je+3];Xt=Jt?.status==="success"?Number(Jt.result):18,Wt=ns?.status==="success"?ns.result:"TOKEN",ss=As?.status==="success"?As.result:Wt}const Ee=!!m&&h.addressesEqual(ct.address,m)&&ct.chainId===c;Ee&&a&&(bs=a),Ee&&r&&!ct.configToken&&(Wt==="TOKEN"&&(Wt=r),ss==="TOKEN"&&(ss=r));const Et=parseFloat((Number(Yt)/Math.pow(10,Xt)).toFixed(6));return{address:ct.address,name:ss,symbol:Wt,decimals:Xt,balance:Yt,balanceFormatted:Et,balanceUsd:0,logoURI:bs,isNative:!1,chainId:ct.chainId}}):(await Promise.all(Y.map(Je=>Rt(pe,Je)))).filter(Je=>Je!==null)}));if(X!==ze.current)return;const _t=lt.flat();dt(_t)},[x,D,Ge,ke,Tt,c,m,a,r]);i.useEffect(()=>{Ht.current=kt},[kt]),i.useEffect(()=>{if(!e||!x){dt([]);return}Ht.current();const X=setInterval(()=>{Ht.current()},15e3);return()=>clearInterval(X)},[x,e,Ge,ke,Tt,c,m]);const qt=i.useCallback(()=>{kt()},[kt]),Nt=i.useMemo(()=>xt.filter(X=>X.balance>0n),[xt]),Ft=i.useMemo(()=>{if(D)return Nt.map(be=>({...be,_source:"wallet"}));if(!x)return Oe;const X=[];for(const be of Nt)X.push({...be,_source:"wallet"});for(const be of Oe)X.push({...be,_source:"spice"});return X},[D,x,Nt,Oe]),yt=i.useMemo(()=>N?m?Ft.filter(X=>h.addressesEqual(X.address,m)&&X.chainId===c):[]:Ft,[Ft,N,m,c]),it=i.useRef(null),We=i.useRef(null);i.useEffect(()=>{We.current=q},[q]),i.useEffect(()=>{!N||!q?.asset||m&&h.addressesEqual(q.asset.address,m)&&q.asset.chainId===c||_(null)},[N,q?.asset,m,c]),i.useEffect(()=>{e||(_(null),J(null),ue(null),xe(!1),oe(!1),Ae(null),Z(!1),Ze(!1),Fe(null),$e(!1),je())},[e,je]),i.useEffect(()=>{l&&l.assetAmount!==(q?.amount||"")&&_(X=>X&&{...X,amount:l.assetAmount})},[l?.assetAmount]),i.useEffect(()=>{d&&d.assetAmount!==(q?.amount||"")&&_(X=>X&&{...X,amount:d.assetAmount})},[d?.assetAmount]),i.useEffect(()=>{if(!D&&Re?.overallStatus==="success"&&Re.intentId&&it.current!==Re.intentId&&Ye&&Re.steps.find(X=>X.transactionHash)?.transactionHash){it.current=Re.intentId;const X=We.current;if(!X?.asset||!X.amount||X.asset._source==="wallet"||M.parseUnits(X.amount,X.asset.decimals)===0n)return;Dt()}},[Re,Ye,c,Dt,D]);const et=parseFloat(q?.amount||"")||0,Ct=et>0&&et<us,Qt=i.useMemo(()=>q?.asset?q.asset._source==="wallet"?q.asset.balanceFormatted??0:Oe.find(X=>h.addressesEqual(X.address,q.asset.address)&&X.chainId===q.asset.chainId)?.balanceFormatted??0:0,[q?.asset,Oe]),Vt=et>0&&(ee?parseFloat(M.formatUnits(ee.grossAmount,ee.decimals))>Qt:et>Qt),vt=u?.selectedDuration??f[de]??f[0],ae=i.useMemo(()=>!q?.asset||!m?!1:h.addressesEqual(q.asset.address,m)&&q.asset.chainId===c,[q?.asset,m,c]),ot=i.useMemo(()=>et<=0?0:ae?et:!k||k<=0?0:et/k,[et,k,ae]),tt=i.useMemo(()=>ot<=0?null:ot.toLocaleString(void 0,{maximumFractionDigits:2}),[ot]),ht=p&&ot>0&&vt?p(ot,vt.months):void 0,Xe=i.useMemo(()=>et<=0?"$0.00":ae&&k?(et*k).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!k||k<=0?"$0.00":et.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[et,k,ae]),Be=i.useMemo(()=>{if(!tt)return null;const X=parseFloat(tt.replace(/,/g,""));return ae&&k?(X*k).toLocaleString(void 0,{maximumFractionDigits:2}):k?(X*k).toLocaleString(void 0,{maximumFractionDigits:2}):null},[tt,k,ae]),ut=i.useCallback(X=>{_(be=>({asset:X,amount:be?.asset?.address===X.address&&be?.asset?.chainId===X.chainId&&be.amount||""})),J(null),ue(null),oe(!1),Ae(null),d?.setSelectedAsset&&d.setSelectedAsset({symbol:X.symbol,address:X.address,decimals:X.decimals,chainId:X.chainId})},[d?.setSelectedAsset]),Zt=i.useCallback(X=>{_(be=>be&&{...be,amount:X}),J(null),ue(null),oe(!1),Ae(null),l&&l.setAssetAmount(X),d&&d.setAssetAmount(X)},[l,d]),se=i.useCallback(X=>{if(typeof o=="function"){if(!q?.asset||!q.amount)throw new Error("Select an asset and enter an amount");return o({asset:q.asset,amount:X?.amount??q.amount,amountWei:X?.amountWei??M.parseUnits(q.amount,q.asset.decimals),grossAmount:X?.grossAmount,grossAmountWei:X?.grossAmountWei,feeAdjusted:!!X})}return o},[o,q]),ne=i.useRef(null),ve=i.useMemo(()=>!q?.asset||et<=0?!1:D?!ae&&!C:!0,[q,et,D,ae,C]),He=i.useCallback(()=>Pl(ne.current),[]),st=i.useMemo(()=>!q?.asset||et<=0?null:`${q.asset.address.toLowerCase()}:${q.asset.chainId}:${q.amount??""}`,[q?.asset?.address,q?.asset?.chainId,q?.amount,et]);i.useEffect(()=>{if(!e||he)return;if(!q?.asset||et<=0){ue(null),xe(!1),oe(!1),Ae(null);return}if(!ve){ue(null),xe(!1),oe(!0),Ae(null);return}let X=!1;const be=async Ke=>{const Rt=++rt.current;Ke||(ue(null),oe(!1),xe(!0));try{const lt=await He();if(X||rt.current!==Rt)return;ue(null),oe(!0),Ae(lt)}catch(lt){if(X||rt.current!==Rt)return;Ke||(ue(h.sanitizeError(lt,"Unable to calculate fees for this lock.")),oe(!1))}finally{!X&&rt.current===Rt&&!Ke&&xe(!1)}},pt=window.setTimeout(()=>{be(!1)},250),wt=window.setInterval(()=>{be(!0)},3e4);return()=>{X=!0,clearTimeout(pt),window.clearInterval(wt)}},[e,he,st,ve,He]),i.useEffect(()=>{if(Re?.overallStatus==="success"){const X=Re.steps.find(be=>be.transactionHash);y?.(X?.transactionHash)}},[Re?.overallStatus,y]);const mt=x&&q?.asset?._source==="wallet"&&q?.asset?.chainId===c,bt=i.useCallback(()=>Ul(ne.current),[]),gt=!!q?.asset&&et>0&&!Ct&&!Vt&&!he&&(!ve||V&&!Ce&&!te),Ne=re||te,Bt=n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[n.jsx(On,{color:U}),n.jsxs("p",{style:{fontSize:"13px",color:U,margin:0,lineHeight:"1.5"},children:["Add ",r," by converting assets from your account"]})]});if(ne.current={selectedAsset:q,parsedAmount:et,selectedDuration:vt,isInsufficientBalance:Vt,isSemi7702:D,isSourceDestToken:ae,isDirectDeposit:mt,requiresRelayerFeeEstimate:ve,address:Ye,embeddedWalletAddress:me,providerEmbeddedAddress:at,externalWallet:It,externalWalletAddress:Le,activeSignerWallet:ft,activeSignerAddress:At,isConnected:Se,ready:K,authenticated:Ue,provider:Ve,actions:zt,lockChainId:c,escrowAddress:g,onLockExecute:C,onLockSuccess:y,buildSpicenetBatch:v,resolveLockBatches:se,startStatusPolling:Ot,refreshSpiceAssets:Dt,refreshWalletAssets:qt,ui:{setError:J,setIsExecuting:Z,setShowStatusPanel:$e}},!e)return null;const qe={backgroundColor:W,border:O,borderRadius:H,padding:"16px",marginBottom:"16px"};return n.jsx(cs,{isOpen:e,onClose:t,title:`Add ${r} to your account`,subtitle:Bt,styles:w,dark:P,footerLinkText:"Spicenet accounts \u2192",overlayContent:jt?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:[A&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Ln,{onClick:A,color:T,fontFamily:S})}),n.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:U,fontFamily:S},children:n.jsx(Hs,{assets:yt,selectedAsset:q??void 0,onAssetSelect:ut,onAmountChange:Zt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:le,styles:z})}),n.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:U,fontFamily:S},children:Xe})]}),n.jsxs("div",{style:qe,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:P?`1px solid ${F.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?n.jsx("img",{src:a,alt:r,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):n.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:P?F.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:$},children:r.slice(0,2)}),n.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:$,fontFamily:S},children:r})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:$,fontFamily:S,lineHeight:1.1},children:tt??"0.00"}),n.jsxs("div",{style:{fontSize:"12px",color:U,fontFamily:S,marginTop:"2px"},children:["~$",Be??"0.00"]})]})]}),n.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:P?`1px solid ${F.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:U,fontFamily:S},children:"Lock Duration"}),n.jsx(ds,{color:U})]}),n.jsx(wl,{options:f,selectedIndex:de,onSelect:fe,primaryColor:T,dark:P,textPrimary:$,textSecondary:U})]}),n.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[n.jsx(Sl,{durationMonths:vt?.months,fontFamily:S,dark:P,textPrimary:$,textSecondary:U}),p&&n.jsx(Al,{votes:ht,fontFamily:S,dark:P,textPrimary:$,textSecondary:U})]})]}),ve&&n.jsx(tn,{fontFamily:S,textPrimary:$,textSecondary:U,cardBg:W,cardBorder:O,resolvedDark:P,darkCardBorder:F.cardBorder,primaryColor:T,feePreview:ee,isLoading:Ce,errorText:te}),Ne&&n.jsx(Rs,{variant:"error",palette:F,fontFamily:S,style:{marginBottom:"12px"},children:Ne}),n.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:bt,disabled:!gt,loading:he,dark:P,styles:{...w,button:{...w?.button,backgroundColor:T}},children:he?ae?"LOCKING...":"CONVERTING...":Ct?`MINIMUM ${us}`:Ce&&ve?"CALCULATING FEES...":ae?`LOCK ${r}`:`CONVERT TO ${r}`}),n.jsx(El,{isOpen:jt,data:ye,isLocking:he,lockError:Ne,onContinue:bt,onClose:()=>Ze(!1),primaryColor:T,fontFamily:S,dark:P}),Re&&Te&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:P?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:H},children:n.jsx(Gn,{type:"lock",showStepBreakdown:!1,isOpen:!!Re&&Re.overallStatus!=="processing",isProcessing:he||Re?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{je(),$e(!1),bt()},onNewTx:()=>{je(),$e(!1),_(null),it.current=null,Dt(),qt()},onClose:()=>{je(),$e(!1)},onComplete:()=>{je(),$e(!1),_(null),it.current=null,Dt(),qt()},results:Re?.overallStatus==="success"||Re?.overallStatus==="failed"?Re.steps.map(X=>({asset:{symbol:q?.asset?.symbol||r,address:q?.asset?.address||""},txHash:X.transactionHash||"",success:X.status==="success",amount:q?.amount})):void 0,chainName:h.getChainName(c),explorerUrl:h.getExplorerUrl(c,"").replace(/\/tx\/.*$/,"")||void 0,theme:E,styles:w,dark:P})})]})})},zl="0xa9059cbb";function Ar(e,t,s){return B.isNativeToken(e)?{to:s,value:t,data:"0x"}:{to:e,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[s,t]})}}function Er(e,t,s){return{chainId:s,calls:[Ar(e,t,B.getEscrowContractAddress(s))]}}function jr(e,t,s){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===s}function Fr(e,t,s,o){return t!=="user-transfer"||!s||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(zl)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function gn(e,t,s,o){if(!t)return[e];const r=await t({...s,requestTimestampMs:o});return r?[r,e]:[e]}function Gs(e){return e.filter(t=>t.domain!=="spicenet")}function xn(e){const t=(e.tokenTransfers??[]).filter(s=>s.from==="escrow").map(s=>({token:B.normalizeNativeTokenAddress(s.token),recipient:s.to,amount:BigInt(s.amount)})).filter(s=>s.amount>0n);return t.length>0?t:void 0}function rs(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 ro(e,t){const{currentPaymentAmount:s,destinationToken:o,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:l,isNon7702:d,isPayMode:u,resolvedChainId:c,buildActionCalls:f,feeExecutionMode:p,buildSpicenetBatch:g,selectedAsset:x,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:C,requestTimestampMs:k}=e,b=M.parseUnits(s,o.decimals),A=t?.actionAmountOverride??b,v=r||a||(d?void 0:l);if(!v)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:v,chainId:c,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??b,netAmount:A,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},R=f(A,w),E={chainId:c,calls:R},P=!u&&!d?!0:x?.asset?._source==="spice",T=jr(x??null,d,c),F=P||d||T,S=(I,N)=>({token:I,from:d?"solver":"escrow",to:v,amount:N}),j=(I,N,D)=>T?[Er(I,N,c),...D]:D;if(b===0n)return[E];if(m&&y){const I=C??as(x.asset,c)??x.asset.address,N=t?.fundingAmountOverride??y.amountInMax,D=F?[S(I,N)]:[],L={to:I,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},Q={chainId:c,calls:[L,...y.calls,...R],tokenTransfers:[...D,...E.tokenTransfers??[]]};if(!F)return[Q];const W=await gn(Q,g,{userAddress:v,destinationChainId:c,deliveryToken:I,deliveryAmount:N,deliveryRecipient:v,deliveryTransfers:xn(Q),sourceAsset:x.asset},k);return j(I,N,W)}if(F){const I=C??as(x.asset,c)??o.address,N=t?.fundingAmountOverride??b,D={...E,tokenTransfers:[S(I,N),...E.tokenTransfers??[]]},L=await gn(D,g,{userAddress:v,destinationChainId:c,deliveryToken:I,deliveryAmount:N,deliveryRecipient:v,deliveryTransfers:xn(D),sourceAsset:x.asset},k);return j(I,N,L)}return[E]}async function ao(e,t){const{selectedAsset:s,embeddedWalletAddress:o,externalWalletAddress:r,recipient:a,resolvedChainId:l,destinationToken:d,buildActionCalls:u,feeExecutionMode:c,buildSpicenetBatch:f,isPayMode:p,isNon7702:g,needsSwap:x,resolvedSwap:m,quoteAmountOut:y,resolvedTokenIn:C,requestTimestampMs:k}=e,b=m?.amountOutMinimum??y;if(!s?.asset||!o)return[];const A=a??(g?r:o);if(!A)return[];const v=t?.fundingAmountOverride??t?.actionAmountOverride??M.parseUnits(s.amount,s.asset.decimals),w=t?.fundingAmountOverride??v,R=t?.sourceFundingAmountOverride??v,E=t?.deliveryAmountOverride??w,P=t?.withdrawalAmountOverride??E,T=t?.actionAmountOverride??v,F={userAddress:A,chainId:l,destinationToken:d.address,feeToken:c==="user-transfer"&&x&&C?C:d.address,grossAmount:w,netAmount:T,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},S=u(T,F),j=s.asset?._source==="wallet";if(!p&&g&&j&&s.asset.chainId===l){if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!m||b===null)throw new Error("Swap quote not available yet")}if(x&&m&&b){const U=u(t?.actionAmountOverride??b,{...F,netAmount:t?.actionAmountOverride??b}),{feeCall:z,remainingCalls:le}=Fr(U,c,x,F.feeToken);return[{chainId:l,calls:[...z?[z]:[],...m.calls,...le]}]}return[{chainId:l,calls:S}]}if(!p&&!g&&j&&s.asset.chainId!==l)throw new Error("Cross-chain wallet supplies require external wallet mode");const I=!p&&!g?s.asset?._source!=="wallet":s.asset?._source==="spice",N=g&&j,D=jr(s,g,l);if(!(I||N||D))return[{chainId:l,calls:S}];const L=D?Er(C??B.normalizeNativeTokenAddress(s.asset.address),R,l):N&&s.asset.chainId!==l?{chainId:s.asset.chainId,calls:[Ar(B.normalizeNativeTokenAddress(s.asset.address),R,B.getEscrowContractAddress(s.asset.chainId))]}:null,Q=(U,z)=>({token:U,from:N?"solver":"escrow",to:o,amount:z}),W=(U,z)=>N?[{token:U,from:"escrow",to:B.SPICE_SOLVER_ADDRESS,amount:z}]:[];if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!m||b===null)throw new Error("Swap quote not available yet")}if(x&&m&&b&&C){const U=u(t?.actionAmountOverride??b,{...F,netAmount:t?.actionAmountOverride??b}),{feeCall:z,remainingCalls:le}=Fr(U,c,x,F.feeToken),q={chainId:l,calls:[...z?[z]:[],...m.calls,...le],tokenTransfers:[...W(C,P),Q(C,E)]},_=await gn(q,f,{userAddress:o,destinationChainId:l,deliveryToken:C,deliveryAmount:E,withdrawalAmount:P,deliveryRecipient:o,deliveryTransfers:xn(q),sourceAsset:s.asset},k);return L?[L,..._]:_}const O=C??as(s.asset,l)??d.address,H={chainId:l,calls:S,tokenTransfers:[...W(O,P),Q(O,E)]},$=await gn(H,f,{userAddress:o,destinationChainId:l,deliveryToken:O,deliveryAmount:E,withdrawalAmount:P,deliveryRecipient:o,deliveryTransfers:xn(H),sourceAsset:s.asset},k);return L?[L,...$]:$}async function io(e,t,s,o,r){let a=e;for(let l=0;l<4;l++){const d=await t(a),u=await o(d,s,a,r),c=Ki(u);if(c===null||c>=e)return a;const f=a-c,p=e+f;if(p<=a)return a;a=p}return a}function Ol(e,t,s,o){if(e<=0n)return 0n;const r=e-t;if(r<=0n)return 0n;const a=o+s;return a<=0n?r:r*o/a}function Ll(e,t){const s=M.formatUnits(e,t);return s.includes(".")?s.replace(/\.?0+$/,"")||"0":s}async function Br(e){const{asset:t,isPayMode:s,isNon7702:o,needsSwap:r,isQuoting:a,embeddedWalletAddress:l,buildSupplyChainBatches:d,estimateGasless:u,executionTokenAddress:c,feeExecutionMode:f}=e;if(s||o||r||a||!l||t.balance<=0n)return null;const p=l,g=await d({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(g.length===0)return null;const x=g.some(A=>A.tokenTransfers?.length),m=await u(g,c,t.balance,x?{userOverride:p,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:p,feeExecutionMode:f}:{userOverride:p}),y=ys(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),C=y?rs(y.gasFee,y.decimals,t.decimals):0n,k=y?rs(y.spicenetFee,y.decimals,t.decimals):0n,b=Ol(t.balance,C,k,t.balance);return b>0n?Ll(b,t.decimals):null}async function lo(e){const{selectedAsset:t,isPayMode:s,parsedAmount:o,needsSwap:r,exactOutputSwap:a,isNon7702:l,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:c,feeExecutionMode:f,resolvedTokenIn:p,embeddedWalletAddress:g,providerEmbeddedAddress:x,resolvedChainId:m,isConnected:y,address:C,ready:k,authenticated:b,isDirect:A,resolvedSwap:v,isQuoting:w,executionTokenAddress:R,buildPayChainBatches:E,buildSupplyChainBatches:P,estimateGasless:T,estimateRequiredGrossFunding:F}=e;if(!t?.asset)return null;if(s){if(o<=0||r&&!a||d)return null;const W=M.parseUnits(u,c.decimals),O=p||as(t.asset,m)||t.asset.address||c.address,H={chainId:m,tokenAddress:O,symbol:B.getTokenByAddress(O,m)?.symbol??t.asset.symbol,decimals:B.getTokenByAddress(O,m)?.decimals??t.asset.decimals};if(l){const _=g||x;if(!_)return null;const ce=_,we=r?a?.amountInMax??0n:W;if(we===0n)return null;const de=await F(we,Z=>E({fundingAmountOverride:Z}).then(re=>os(Gs(re),ce)),O,{userOverride:_,useCustomTransfers:!0}),fe=os(Gs(await E({fundingAmountOverride:de})),ce),he=await T(fe,O,de,{userOverride:_,useCustomTransfers:!0,feeExecutionMode:f});return ys(he,H)}if(!y||!C||!k||!b)return null;const $=g||x||C,U=r?a?.amountInMax??0n:W;if(U===0n)return null;const z=await F(U,_=>E({fundingAmountOverride:_}).then(ce=>os(Gs(ce),$)),O,{useCustomTransfers:!0});let le=os(Gs(await E({fundingAmountOverride:z})),$);const q=await T(le,O,z,{useCustomTransfers:!0,feeExecutionMode:f});return ys(q,H)}if(o<=0||!g)return null;const S=g||x;if(!(!s&&!l&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!A&&!v&&!w||w)return null;const j=M.parseUnits(t.amount,t.asset.decimals),I=await P();if(I.length===0)return null;const N=l&&t.asset?._source==="wallet"&&t.asset.chainId===m,D={chainId:m,tokenAddress:R,symbol:B.getTokenByAddress(R,m)?.symbol??c.symbol,decimals:B.getTokenByAddress(R,m)?.decimals??c.decimals};if(N){const W=await h.relayerService.estimateBatchGas({user:S,outputToken:R,stepIndex:0,chainBatches:I}),O=cn(j,10n),H=O+W.gasFee;return{...D,grossAmount:j+H,netAmount:j,totalFee:H,gasFee:W.gasFee,spicenetFee:O,bridgeFee:0n,gasQuoteSource:W.gasQuoteSource}}const L=I.some(W=>W.tokenTransfers?.length),Q=await T(I,R,j,L?{userOverride:S,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:S,feeExecutionMode:f}:{userOverride:S});return ys(Q,D)}const Hl=10n;function Tr(e,t){const s=e.selectedAsset?.asset;if(!s||s?._source!=="wallet")return;const o=as(s,e.resolvedChainId);if(!o||!h.addressesEqual(o,e.executionTokenAddress))return;const r=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=rs(t,r?.decimals??e.destinationToken.decimals,s.decimals);if(a<=s.balance)return;const l=M.formatUnits(a,s.decimals),d=M.formatUnits(s.balance,s.decimals);throw new Error(`Insufficient ${s.symbol} for amount plus fees. Required ${l} ${s.symbol}; available ${d} ${s.symbol}.`)}function co(e){const t=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Ks(e,t,s){const o=ys(e,co(t));if(!o)return;const r=cn(s,Hl),a=o.bridgeFee??0n,l=r+o.gasFee+a;return{grossAmount:s+l,netAmount:s,combinedFeeAmount:l,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:r,gasFee:o.gasFee,bridgeFee:a}}}function Ws(e,t,s){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*s}function Mr(e,t,s){let o=0n,r=0n;const a=s.toLowerCase();for(const l of e)if(l.chainId===t){for(const d of l.calls??[])if(d.to.toLowerCase()===a)try{const u=M.decodeFunctionData({abi:M.erc20Abi,data:d.data});if(u.functionName!=="transfer")continue;const c=u.args[0].toLowerCase(),f=u.args[1];c===B.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?o+=f:c===B.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(r+=f)}catch{continue}}return{spicenetFee:o,gasFee:r}}function uo(e,t,s){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=Mr(e,t.resolvedChainId,o);return r.spicenetFee===0n&&s.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&s.feeBreakdown.gasFee>0n?!1:Ws(r.spicenetFee,s.feeBreakdown.spicenetFee,100n)&&Ws(r.gasFee,s.feeBreakdown.gasFee,100n)}function Rr(e,t){return e?Ws(e.grossAmount,t.grossAmount,100n)&&Ws(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Ws(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Ws(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function po(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const s=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!s:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const o=await yn(e);e.ui.setTxHash(o??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const o=new AbortController;e.refs.abortControllerRef.current=o,await Dr(e,o.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(o){const r=o instanceof Error?o:new Error(String(o));if(r.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const a=r.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(a),e.ui.setError(a),e.onError?.(r)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const s=M.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=s;let r=await e.gasless.buildSupplyChainBatches();const a=e.selectedAsset.asset?._source==="wallet",l=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!a&&!r.some(x=>B.isSpicenetChainId(x.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const d=r.some(x=>x.tokenTransfers?.length)?{userOverride:l,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:l,feeExecutionMode:e.feeExecutionMode}:{userOverride:l};let u=s;const c=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,f=e.feeExecutionMode==="user-transfer"&&!c?o:void 0;let p;for(let x=0;x<4;x+=1){const m=await e.gasless.estimateGasless(r,e.executionTokenAddress,u,d),y=ys(m,co(e));p=e.feeExecutionMode==="user-transfer"&&y?Ks(m,e,o):void 0;const C=p?.grossAmount??y?.grossAmount??u;if(C===u){u=C;break}u=C,r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:p})}e.feeExecutionMode==="user-transfer"&&(Tr(e,u),r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:p}));let g=p;await e.gasless.executeGasless(r,e.executionTokenAddress,u,e.gasless.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:x,chainBatches:m})=>{const y=Ks(x,e,o);if(!y)return null;const C=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;Mr(m,e.resolvedChainId,C);const k=Rr(g,y),b=uo(m,e,y);return k||b?null:(g=y,e.gasless.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:f,actionContextOverride:y}))}}:d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(s){const o=s instanceof Error?s:new Error(String(s));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const r=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function Dr(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,r=M.parseUnits(e.selectedAsset.amount,o.decimals),a=r,l=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let d=await e.gasless.buildSupplyChainBatches();const u={userOverride:s,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let c=r;const f=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!f?a:void 0;let g;if(l){const S=await h.relayerService.estimateBatchGas({user:s,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),j=cn(r,10n),I=j+S.gasFee;c=r+I,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:c,netAmount:a,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:j,gasFee:S.gasFee,bridgeFee:0n}})}else for(let S=0;S<4;S+=1){const j=await e.gasless.estimateGasless(d,e.executionTokenAddress,0n,u),I=e.feeExecutionMode==="user-transfer"?Ks(j,e,a):void 0,N=ys(j,co(e)),D=I?.grossAmount??(N?N.grossAmount>r?N.grossAmount:r:c);if(g=I,D===c){c=D;break}c=D;const L=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),Q=rs(c,L?.decimals??e.destinationToken.decimals,o.decimals);d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:Q,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I})}const x=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let m=l?c:rs(c,x?.decimals??e.destinationToken.decimals,o.decimals);Tr(e,c),d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:g});const y=o.chainId,C=s,k=await e.externalWallet.getEthereumProvider();let b=null;try{const S=await k.request({method:"eth_chainId"});b=parseInt(S,16)}catch{b=null}b!==y&&(e.ui.setStatusMsg("Switching source network..."),await h.ensureWalletOnChain(k,y));const A=h.getChainConfig(y),v=M.createWalletClient({account:e.externalWalletAddress,chain:A?.viemChain,transport:M.custom(k)}),w=B.normalizeNativeTokenAddress(o.address),R=o.isNative||B.isNativeToken(w),E=h.getClientForChain(y),P=async S=>{if(S<=0n)return;const j=R?await v.sendTransaction({to:C,value:S,chain:A?.viemChain}):await v.sendTransaction({to:w,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[C,S]}),chain:A?.viemChain});if((await E.waitForTransactionReceipt({hash:j,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed")};e.ui.setStatusMsg("Funding embedded wallet..."),await P(m);let T=m;if(e.feeExecutionMode==="user-transfer")for(let S=0;S<4;S+=1){const j=await e.gasless.estimateGasless(d,e.executionTokenAddress,0n,u),I=Ks(j,e,a);if(!I)break;const N=l?I.grossAmount:rs(I.grossAmount,x?.decimals??e.destinationToken.decimals,o.decimals);if(N>T&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await P(N-T),T=N),g=I,c=I.grossAmount,m=N,d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I}),uo(d,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let F=g;await e.gasless.executeGasless(d,e.executionTokenAddress,0n,e.gasless.onProgress,t,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:S,chainBatches:j})=>{const I=Ks(S,e,a);if(!I)return null;const N=Rr(F,I),D=uo(j,e,I);if(N||D)return null;if(I.grossAmount>c)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");F=I;const L=l?I.grossAmount:rs(I.grossAmount,x?.decimals??e.destinationToken.decimals,o.decimals);return e.gasless.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:L,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:p,actionContextOverride:I})}}:u)}async function yn(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const s=e.activeSignerWallet??e.externalWallet,o=e.activeSignerAddress??e.externalWalletAddress;if(!o||!s)throw new Error("Please connect your wallet to continue");const r=M.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),a={userAddress:o,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},l=e.buildActionCalls(r,a);if(l.length===0)throw new Error("No action calls configured");const d=await s.getEthereumProvider();let u=null;try{const x=await d.request({method:"eth_chainId"});u=parseInt(x,16)}catch{u=null}u!==e.resolvedChainId&&await h.ensureWalletOnChain(d,e.resolvedChainId);const c=h.getChainConfig(e.resolvedChainId),f=M.createWalletClient({account:o,chain:c?.viemChain,transport:M.custom(d)}),p=h.getClientForChain(e.resolvedChainId);let g;for(const x of l){const m=await f.sendTransaction({to:x.to,data:x.data,value:x.value,chain:c?.viemChain});if((await p.waitForTransactionReceipt({hash:m,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");g=m}return g}async function Nr(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,r=M.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const l=e.resolvedTokenIn||e.selectedAsset.asset.address,d={userOverride:t,useCustomTransfers:!0},u=await e.gasless.estimateRequiredGrossFunding(a,b=>e.gasless.buildPayChainBatches({fundingAmountOverride:b}),l,d),c=B.getEscrowContractAddress(o),f=await e.externalWallet.getEthereumProvider();let p=null;try{const b=await f.request({method:"eth_chainId"});p=parseInt(b,16)}catch{p=null}p!==o&&await h.ensureWalletOnChain(f,o);const g=h.getChainConfig(o),x=M.createWalletClient({account:e.externalWalletAddress,chain:g?.viemChain,transport:M.custom(f)}),m=B.normalizeNativeTokenAddress(s.address),y=s.isNative||B.isNativeToken(m)?await x.sendTransaction({to:c,value:u,chain:g?.viemChain}):await x.sendTransaction({to:m,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[c,u]}),chain:g?.viemChain});if((await h.getClientForChain(o).waitForTransactionReceipt({hash:y,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const C=await e.gasless.buildPayChainBatches({fundingAmountOverride:u}),k=C.some(b=>b.tokenTransfers?.length);return await e.gasless.executeGasless(C,l,u,b=>{b.txHash&&(e.ui.setPaymentResult(A=>({...A??{status:"processing"},txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,k?d:{userOverride:t})}async function fo(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const s=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!s:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let o;if(e.isSourceDestToken||e.parsedAmount===0)o=await yn(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,a=M.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),l=e.selectedIsEquivalent?a:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(l===0n)throw new Error("Quote not available yet");const d=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!d)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const u=e.resolvedTokenIn||r.address,c=await e.gasless.estimateRequiredGrossFunding(l,g=>e.gasless.buildPayChainBatches({fundingAmountOverride:g}),u,{userOverride:d,useCustomTransfers:!0}),f=await e.gasless.buildPayChainBatches({fundingAmountOverride:c}),p=await e.onPayExecute({asset:r,amount:e.currentPaymentAmount,amountWei:a,destinationToken:e.destinationToken,chainBatches:f,requiredNetFunding:l,grossFundingAmount:c,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:u,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});p&&(e.ui.setTxHash(p),e.ui.setPaymentResult(g=>({...g??{status:"processing"},txHash:p}))),o=p||void 0}else o=await Nr(e);e.ui.setPaymentResult(r=>({status:"success",txHash:r?.txHash||o||""}))}catch(o){const r=h.sanitizeError(o,"Payment failed. Please try again.");e.ui.setError(r),e.ui.setPaymentResult({status:"failed",error:r}),e.onError?.(o instanceof Error?o:new Error(r))}finally{e.ui.setIsExecuting(!1)}return}if(e.isSourceDestToken||t){if(!(e.activeSignerAddress??e.externalWalletAddress??e.address)){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const s=await yn(e);e.ui.setPaymentResult(o=>({status:"success",txHash:o?.txHash||s||""}))}catch(s){const o=h.sanitizeError(s,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(s instanceof Error?s:new Error(o))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const s=M.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),o={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const C=await e.gasless.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),k=await e.gasless.executeGasless(C,e.destinationToken.address,0n,b=>{b.txHash&&(e.ui.setPaymentResult(A=>({...A,txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,o);e.ui.setPaymentResult(b=>({status:"success",txHash:b?.txHash||k}));return}const r=e.selectedAsset?.asset;if(!r)throw new Error("Select a payment source");const a=e.resolvedTokenIn||r.address||e.destinationToken.address,l=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:s,d=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,u=(C,k,b)=>{const A=Gs(C),v=E=>(E.tokenTransfers??[]).some(P=>P.from==="escrow"),w=A.filter(E=>!v(E)),R=A.filter(v);return[...w,...os(R,d,k,b)]},c=await e.gasless.estimateRequiredGrossFunding(l,C=>e.gasless.buildPayChainBatches({fundingAmountOverride:C}).then(k=>u(k)),a,o);let f=c,p=u(await e.gasless.buildPayChainBatches({fundingAmountOverride:c}));const g=await e.gasless.estimateGasless(p,a,c,o),x=ys(g,{chainId:e.resolvedChainId,tokenAddress:a,symbol:B.getTokenByAddress(a,e.resolvedChainId)?.symbol??r.symbol,decimals:B.getTokenByAddress(a,e.resolvedChainId)?.decimals??r.decimals})?.grossAmount??c;x!==c&&(f=x),p=u(await e.gasless.buildPayChainBatches({fundingAmountOverride:f}),g,{payoutAlreadyGross:!0});const m=p.some(C=>C.tokenTransfers?.length),y=await e.gasless.executeGasless(p,a,m?f:0n,C=>{C.txHash&&(e.ui.setPaymentResult(k=>({...k,txHash:C.txHash})),e.ui.setTxHash(C.txHash))},void 0,o);e.ui.setPaymentResult(C=>({status:"success",txHash:C?.txHash||y}))}catch(s){const o=h.sanitizeError(s,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(s instanceof Error?s:new Error(o))}finally{e.ui.setIsExecuting(!1)}}const ql=({variant:e,destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,isQuoting:g,quoteError:x,estimatedOutput:m,paymentAmount:y,needsSwap:C,exactOutputSwap:k,adjustable:b=!1,maxAmount:A,onAmountChange:v})=>e==="supply"?n.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${c}`,borderRadius:p?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[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:a,fontSize:"17px",fontWeight:500,color:p?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),n.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,fontFamily:a,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 ${c}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[n.jsx(Wr,{symbol:t,logoURI:s,primaryColor:r,size:24}),n.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:p?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),n.jsx("div",{style:{textAlign:"right",minWidth:0},children:g?n.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:a},children:"Quoting..."}):x?n.jsx("span",{style:{fontSize:"13px",color:p?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):m?n.jsx(ws,{value:m,title:m,fontFamily:a,color:l,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):n.jsx("span",{style:{fontSize:"20px",color:d,fontFamily:a},children:"\u2014"})})]}):n.jsx(Ql,{destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:k,isQuoting:g,adjustable:b,maxAmount:A,onAmountChange:v}),Pr=i.memo(ql),Wr=({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)}),Ql=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:s,primaryColor:o,fontFamily:r,textPrimary:a,textSecondary:l,cardBg:d,cardBorder:u,dk:c,dark:f,paymentAmount:p,needsSwap:g,exactOutputSwap:x,isQuoting:m,adjustable:y,maxAmount:C,onAmountChange:k})=>{const b='"IBM Plex Mono", monospace',A=parseFloat(p||"0"),v=C?parseFloat(C):0,[w,R]=i.useState(p||""),E=i.useRef(null),[P,T]=i.useState(null),[F,S]=i.useState(null);i.useEffect(()=>{y||R(p||"")},[p,y]);const j=D=>{let L=D;L.startsWith(".")&&(L="0"+L);const Q=Ts(L);let W=Q;C&&parseFloat(Q)>parseFloat(C)&&(W=C),R(W),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>k?.(W),300)},I=D=>{if(!v)return;if(D===100){R(C||v.toString()),E.current&&clearTimeout(E.current),k?.(C||v.toString());return}const L=10**s,Q=Math.floor(v*D/100*L)/L,W=Ms(Q,s);R(W),E.current&&clearTimeout(E.current),k?.(W)},N=v>0?parseFloat(w||"0")/v*100:0;return i.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]),n.jsxs("div",{style:{backgroundColor:d,border:`1px solid ${u}`,borderRadius:f?"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(Wr,{symbol:e,logoURI:t,primaryColor:o,size:32}),n.jsxs("div",{children:[n.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:a,fontFamily:r},children:"Payment"}),n.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:r,marginTop:"2px"},children:e})]})]}),n.jsxs("div",{style:{textAlign:"right"},children:[y?n.jsx(ws,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:D=>j(D.target.value),placeholder:"0.0",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):n.jsx(ws,{element:"div",value:A>0?p:"0.00",title:A>0?p:"0.00",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),n.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:b,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((D,L)=>{const Q=Math.abs(N-D)<1,W=L===4,O=D/100,H=P===D,$=F===D;return n.jsx("button",{onClick:()=>I(D),onMouseEnter:()=>T(D),onMouseLeave:()=>{T(null),S(null)},onMouseDown:()=>S(D),onMouseUp:()=>S(null),title:`${D}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:Q?1:H?.8:.5,transform:$?"scale(0.85)":H?"scale(1.15)":"scale(1)",transition:es.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:W?o:"none",stroke:W?o:f?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!W&&O>0&&n.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${O>.5?1:0} 1 ${7+6.84375*Math.sin(O*2*Math.PI)} ${7-6.84375*Math.cos(O*2*Math.PI)} Z`,fill:f?c?.textSecondary||"#9ca3af":"#3C3E42"})]})},D)})})]})]}),g&&x&&!m&&n.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:f?`1px solid ${c?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:n.jsxs("span",{style:{fontSize:"11px",color:l,fontFamily:r,opacity:.7},children:["via ",x.venue]})})]})};function Ur(e,t,s){const o=h.addressesEqual(e.address,t),r=e.chainId===s,a=e._source==="wallet";return a&&o&&r?0:a&&r?1:!a&&o?2:!a&&r?3:4}function zr(e,t){return!t||t.length===0||t.some(s=>h.addressesEqual(s,e.address))?!0:Object.keys(e.chainTokens??{}).some(s=>{const o=Ns(s);return o?t.some(r=>h.addressesEqual(r,o.address)):!1})}function ho(e){const{destinationToken:t,supportedSourceAssets:s,sourceChains:o,enabled:r}=e,a=(i.useContext(h.SpiceFlowProviderContext)?.mode||"7702")!=="7702",l=h.useEmbeddedWalletAddress(),{externalAddress:d,embeddedAddress:u,activeAddress:c}=h.useProviderWallets(),f=l||u,{assets:p,refetch:g}=Qs({address:f,supportedChains:o,enabled:r&&!a&&!!f,refetchInterval:3e4}),x=i.useMemo(()=>a?[]:p.filter(P=>zr(P,s)),[p,s,a]),m=a?c??d:l,y=i.useMemo(()=>{const P=new Set,T=[],F=S=>{if(!S)return;const j=S.toLowerCase();P.has(j)||(P.add(j),T.push(M.getAddress(S)))};if(F(t.address),s)for(const S of s)F(S);return T},[a,t.address,s]),C=i.useMemo(()=>y.map(P=>P.toLowerCase()).sort().join(","),[y]),k=i.useMemo(()=>JSON.stringify([...o||[]].sort()),[o]),[b,A]=i.useState([]),v=i.useRef(0),w=i.useRef(async()=>{}),R=i.useCallback(async()=>{if(!r||!m||y.length===0){v.current++,A([]);return}const P=++v.current,T=M.getAddress(m),F=a?o&&o.length>0?o:[t.chainId]:[t.chainId],S=[];for(const D of y){const L=D.toLowerCase();if(L===B.ZERO_ADDRESS)continue;if(L===t.address.toLowerCase()){const W=h.getChainConfig(t.chainId)?.supportedTokens?.find(O=>h.addressesEqual(O.address,L));S.push({address:D,chainId:t.chainId,configToken:W?{decimals:W.decimals,symbol:W.symbol,name:W.name,logo:W.logo}:void 0});continue}let Q=!1;for(const W of F){const O=h.getChainConfig(W)?.supportedTokens?.find(H=>h.addressesEqual(H.address,L));if(O){S.push({address:D,chainId:W,configToken:{decimals:O.decimals,symbol:O.symbol,name:O.name,logo:O.logo}}),Q=!0;break}}Q||S.push({address:D,chainId:t.chainId})}const j=new Map;for(const D of S){const L=j.get(D.chainId)||[];L.push(D),j.set(D.chainId,L)}const I=async(D,L)=>{try{const Q=await $t.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"balanceOf",args:[T]});let W,O,H,$;if(L.configToken)W=L.configToken.decimals,O=L.configToken.symbol,H=L.configToken.name,$=L.configToken.logo;else{const[le,q,_]=await Promise.all([$t.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"decimals"}).catch(()=>18),$t.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),$t.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);W=Number(le),O=q,H=_}const U=h.addressesEqual(L.address,t.address)&&L.chainId===t.chainId;U&&t.logoURI&&($=t.logoURI),U&&!L.configToken&&O==="TOKEN"&&(O=t.symbol,H=t.symbol);const z=parseFloat((Number(Q)/Math.pow(10,W)).toFixed(6));return{address:L.address,name:H,symbol:O,decimals:W,balance:Q,balanceFormatted:z,balanceUsd:0,logoURI:$,isNative:!1,chainId:L.chainId}}catch{return null}},N=await Promise.all(Array.from(j.entries()).map(async([D,L])=>{let Q;try{Q=h.getClientForChain(D)}catch{return[]}const W=[],O=[];for(const $ of L){const U=W.length;W.push({address:$.address,abi:M.erc20Abi,functionName:"balanceOf",args:[T]}),$.configToken||W.push({address:$.address,abi:M.erc20Abi,functionName:"decimals"},{address:$.address,abi:M.erc20Abi,functionName:"symbol"},{address:$.address,abi:M.erc20Abi,functionName:"name"}),O.push({start:U,item:$})}let H=null;try{H=await Q.multicall({contracts:W})}catch{H=null}return H?O.map(({start:$,item:U})=>{const z=H[$],le=z?.status==="success"?z.result:0n;let q,_,ce,we;if(U.configToken)q=U.configToken.decimals,_=U.configToken.symbol,ce=U.configToken.name,we=U.configToken.logo;else{const he=H[$+1],Z=H[$+2],re=H[$+3];q=he?.status==="success"?Number(he.result):18,_=Z?.status==="success"?Z.result:"TOKEN",ce=re?.status==="success"?re.result:_}const de=h.addressesEqual(U.address,t.address)&&U.chainId===t.chainId;de&&t.logoURI&&(we=t.logoURI),de&&!U.configToken&&_==="TOKEN"&&(_=t.symbol,ce=t.symbol);const fe=parseFloat((Number(le)/Math.pow(10,q)).toFixed(6));return{address:U.address,name:ce,symbol:_,decimals:q,balance:le,balanceFormatted:fe,balanceUsd:0,logoURI:we,isNative:!1,chainId:U.chainId}}):(await Promise.all(L.map($=>I(Q,$)))).filter($=>$!==null)}));P===v.current&&A(N.flat())},[r,a,m,C,k,t.address,t.chainId,t.symbol,t.logoURI]);i.useEffect(()=>{w.current=R},[R]),i.useEffect(()=>{if(!r){A([]);return}w.current();const P=setInterval(()=>{w.current()},15e3);return()=>clearInterval(P)},[r,a,m,C,k,t.address,t.chainId]);const E=i.useCallback(()=>{R()},[R]);return{displayAssets:i.useMemo(()=>{const P=[],T=b.filter(S=>S.balance>0n);for(const S of T)P.push({...S,_source:"wallet"});for(const S of x)P.push({...S,_source:"spice"});const F=t.address.toLowerCase();return P.sort((S,j)=>Ur(S,F,t.chainId)-Ur(j,F,t.chainId)),P},[b,x,t.address,t.chainId]),filteredSpiceAssets:x,walletAssets:b,embeddedWalletAddress:f,externalAddress:d,isNon7702:a,refreshSpiceAssets:g,refreshWalletAssets:E}}async function Or(e){const{tokenIn:t,tokenOut:s,amountIn:o,fee:r,chainId:a,config:l}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const d=(await h.getClientForChain(a).simulateContract({address:l.quoterV2,abi:B.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:s,amountIn:o,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function Lr(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(r=>Or({...e,fee:r})));let o=null;for(let r=0;r<s.length;r++){const a=s[r];a.status==="fulfilled"&&(!o||a.value.amountOut>o.amountOut)&&(o={...a.value,fee:t[r]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const Vl=[{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 Gl(e){const{tokenIn:t,tokenOut:s,amountOut:o,fee:r,chainId:a,config:l}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const d=(await h.getClientForChain(a).simulateContract({address:l.quoterV2,abi:Vl,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:s,amount:o,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function Kl(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(r=>Gl({...e,fee:r})));let o=null;for(let r=0;r<s.length;r++){const a=s[r];a.status==="fulfilled"&&(!o||a.value.amountIn<o.amountIn)&&(o={...a.value,fee:t[r]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function Hr(e){return e.type==="swap"}const mo=.02,Zl=[1,8453,42161,10,137,43114,56],Yl="https://api.1inch.dev/swap/v6.0";function qr(e,t){return B.applySlippage(e,t)}function Qr(e){const t=e?.baseUrl??Yl;return{name:"1inch",chainIds:e?.chainIds??Zl,resolve:async(s,o,r)=>{const a=s.maxSlippage??mo,l=a*100,d=B.isNativeToken(s.tokenIn)?B.NATIVE_TOKEN_ADDRESS:s.tokenIn,u=B.isNativeToken(s.tokenOut)?B.NATIVE_TOKEN_ADDRESS:s.tokenOut,c=B.isNativeToken(s.tokenIn);try{const f=new URL(`${t}/${o}/swap`);f.searchParams.set("src",d),f.searchParams.set("dst",u),f.searchParams.set("amount",s.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",l.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const g=await fetch(f.toString(),{headers:p});if(!g.ok)throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${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=qr(m,a),C=[];return x.tx.to&&!c&&C.push({to:s.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[x.tx.to,s.amountIn]})}),C.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:C}}catch(f){if(f instanceof h.SpiceflowError)throw f;const p=f instanceof Error?f.message:String(f);throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}: ${p}`,{venue:"1inch",chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:p})}}}}const Vr=[4114,5115],go={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Gr={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Kr(e){return{name:"satsuma",chainIds:e.chainIds??Vr,resolve:async(t,s,o)=>{const r=t.maxSlippage??mo,a=B.isNativeToken(t.tokenIn);let l;try{l=await Lr({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=qr(l.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:M.encodeFunctionData({abi:B.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:l.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:l.amountOut,amountOutMinimum:d,calls:u}}}}function Zr(e){return{name:"satsuma",chainIds:e.chainIds??Vr,resolve:async(t,s,o)=>{const r=t.maxSlippage??mo,a=B.isNativeToken(t.tokenIn);let l;try{l=await Kl({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(r*1e4)),u=l.amountIn+l.amountIn*d/10000n,c=[];return c.push({to:e.swapRouter,value:a?u:0n,data:M.encodeFunctionData({abi:Xl,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:l.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:l.amountIn,amountInMax:u,amountOut:t.amountOut,calls:c}}}}const Xl=[{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 Yr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Kr(e.satsuma)),t.push(Qr(e?.oneInch));function s(r){return t.find(a=>a.chainIds.includes(r))}async function o(r,a,l){const d=[],u=[];for(const c of r){if(!Hr(c)){d.push(c);continue}const f=s(a);if(!f)throw new h.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${c.tokenIn} \u2192 ${c.tokenOut}.`,{chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});const p=await f.resolve(c,a,l);if(!p)throw new h.SpiceflowError("NO_LIQUIDITY",`${f.name} returned no quote for ${c.tokenIn} \u2192 ${c.tokenOut} on chain ${a}.`,{venue:f.name,chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});d.push(...p.calls),u.push(p)}return{calls:d,resolvedSwaps:u}}return{resolveSwapIntents:o,getVenueForChain:s,venues:t}}function Xr(e){const t=e?.customVenues??[];async function s(o,r,a){const l=t.filter(u=>u.chainIds.includes(r));if(l.length===0)throw new h.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const d=(await Promise.allSettled(l.map(u=>u.resolve(o,r,a)))).filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u!==null);if(d.length===0)throw new h.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return d.sort((u,c)=>u.amountIn<c.amountIn?-1:u.amountIn>c.amountIn?1:0),d[0]}return{getQuote:s,venues:t}}const Jr=Yr({satsuma:go});async function Jl(e){const t=Jr.getVenueForChain(e.chainId);if(!t)throw new Error(`No swap venue configured for chain ${e.chainId}.`);const s=await t.resolve({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn},e.chainId,e.recipient);if(!s)throw new Error("No liquidity for this pair.");return s}function xo(e){const{direction:t,selectedAsset:s,destinationToken:o,chainId:r,recipient:a,paymentAmount:l,resolveExactOutputSwap:d}=e,[u,c]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(null),[m,y]=i.useState(null),[C,k]=i.useState(null),[b,A]=i.useState(null),[v,w]=i.useState(null),[R,E]=i.useState(null),[P,T]=i.useState(null),F=i.useRef(null),S=i.useRef(null),j=i.useRef(0),I=i.useRef(new Map),N=i.useMemo(()=>Jr,[]),D=i.useMemo(()=>Xr({customVenues:[...d?[{name:"consumer-exact-output",chainIds:[r],resolve:d}]:[],Zr(go),Zr(Gr)]}),[d,r]),L=i.useMemo(()=>{if(!s?.asset)return null;const _=as(s.asset,r);if(_)return _;const ce=fs(s.asset.address,r,s.asset.chainId);return ce?ce.address:null},[s?.asset,r]),Q=i.useMemo(()=>s?.asset?rn(s.asset,r):[],[s?.asset,r]),W=i.useMemo(()=>Q.map(_=>_.toLowerCase()).join(","),[Q]);i.useEffect(()=>{let _=!1;if(S.current&&(clearTimeout(S.current),S.current=null),!s?.asset||Q.length<=1){T(null);return}return S.current=setTimeout(async()=>{const ce=t==="input"?s.amount:l||"0";let we=0n;try{we=t==="input"?M.parseUnits(ce,s.asset.decimals):0n}catch{we=0n}try{const de=await er(s.asset,r,{requiredAmount:we});_||T(de)}catch{_||T(null)}},400),()=>{_=!0,S.current&&(clearTimeout(S.current),S.current=null)}},[s?.asset,s?.amount,r,Q.length,W,t,l]);const O=i.useMemo(()=>P??L,[P,L]),H=i.useMemo(()=>!s?.asset||!O?[]:[O,...Q.filter(_=>_.toLowerCase()!==O.toLowerCase())],[s?.asset,O,Q]),$=i.useMemo(()=>!s?.asset||!qs(s.asset.address,s.asset.chainId,o.address,o.chainId)||!O?!1:h.addressesEqual(O,o.address),[s,o.address,o.chainId,O]),U=O?h.addressesEqual(O,o.address):!1,z=t==="output"&&parseFloat(l||"0")===0,le=!!s?.asset&&!$&&!U&&!z,q=le?R??O:O;return i.useEffect(()=>{F.current&&clearTimeout(F.current);const _=t==="input"?s?.amount:l,ce=parseFloat(_||"0");if(!le||!Number.isFinite(ce)||ce<=0||!s?.asset||!a||H.length===0){j.current++,x(null),y(null),k(null),A(null),w(null),E(null),p(null),c(!1);return}const we=s.asset.decimals;let de;try{de=t==="input"?M.parseUnits(s.amount,we):M.parseUnits(l||"0",o.decimals)}catch{j.current++,p("Invalid amount"),c(!1);return}const fe=++j.current,he=()=>fe!==j.current;c(!0);const Z=t==="output"?150:400;return F.current=setTimeout(async()=>{try{if(t==="input"){const re=N.getVenueForChain(r);if(!re)throw new Error("No swap venue for this chain");let J=null,te=null;for(const Ce of H){const xe=`${t}:${r}:${Ce.toLowerCase()}:${o.address.toLowerCase()}:${de.toString()}`,V=I.current.get(xe);if(V&&V.expiresAt>Date.now()&&V.resolvedSwap){J=V.resolvedSwap,te=Ce;break}const oe=await re.resolve({type:"swap",tokenIn:Ce,tokenOut:o.address,amountIn:de},r,a);if(he())return;if(oe){I.current.set(xe,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:oe}),J=oe,te=Ce;break}}if(!J||!te)throw new Error("No liquidity for this pair");E(te),w(J.amountOut),k(J),A(null);const ue=parseFloat(M.formatUnits(J.amountOut,o.decimals));x(ue<.01?ue.toPrecision(4):ue.toLocaleString(void 0,{maximumFractionDigits:6})),y(null),p(null)}else{let re=null,J=null;for(const te of H){const ue=`${t}:${r}:${te.toLowerCase()}:${o.address.toLowerCase()}:${de.toString()}`,Ce=I.current.get(ue);if(Ce&&Ce.expiresAt>Date.now()&&Ce.exactOutputSwap){re=Ce.exactOutputSwap,J=te;break}try{const xe=await D.getQuote({tokenIn:te,tokenOut:o.address,amountOut:de},r,a);if(he())return;I.current.set(ue,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:xe}),re=xe,J=te;break}catch{if(he())return}}if(!re||!J)throw new Error("No liquidity for this pair");E(J),A(re),k(null),w(null),y(parseFloat(M.formatUnits(re.amountIn,we)).toFixed(6)),x(null),p(null)}}catch(re){if(he())return;const J=re instanceof Error?re.message:"Failed to get quote";p(J),x(null),y(null),k(null),A(null),w(null),E(null)}finally{he()||c(!1)}},Z),()=>{F.current&&clearTimeout(F.current)}},[t,le,s?.amount,s?.asset?.address,s?.asset?.decimals,l,H,r,o.address,o.decimals,a,N,D]),{isQuoting:u,quoteError:f,estimatedOutput:g,estimatedInput:m,resolvedSwap:C,exactOutputSwap:b,quoteAmountOut:v,resolvedTokenIn:q,isDirect:U,needsSwap:le,selectedIsEquivalent:$}}const $r={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},_r=["signing-delegation","signing-intent","submitting","executing"],$l=()=>{},ea=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,destinationToken:o,sourceChains:r,supportedSourceAssets:a,buildActionCalls:l,feeExecutionMode:d="user-transfer",buildSpicenetBatch:u,onPayExecute:c,resolveExactOutputSwap:f,actionLabel:p,amountDirection:g="input",swapDescription:x,directDescription:m,paymentAmount:y,amountInputMode:C="fixed",minPaymentAmount:k,maxPaymentAmount:b,onAmountChange:A,styles:v,dark:w,title:R,subtitle:E,onAddFunds:P,onSuccess:T,onError:F})=>{const S=g==="output",{theme:j,dark:I,primaryColor:N,dk:D,palette:L,fontFamily:Q,monoFont:W,inputDark:O,cardBg:H,cardBorder:$,textPrimary:U,textSecondary:z,subtitleText:le}=h.useSpiceBrand(v,w),q=i.useMemo(()=>O?{...j,colors:{...j.colors,secondary:D.cardBg,surfaceHover:D.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:j,[O,j,D.cardBg,D.hoverBg]),_=o.chainId,ce=i.useContext(h.SpiceFlowProviderContext),we=ce?.mode||"7702",de=we!=="7702",fe=!!ce?.isWhitelistGateActive,he=!!ce?.isWhitelistConfigured&&ce?.isUserWhitelisted!==!0,Z=i.useMemo(()=>r??ce?.supportedChainIds??[],[r,ce?.supportedChainIds]),re=i.useMemo(()=>{if(fe)return[];if(a)return a;const ge=ce?.allowedTokens;if(!ge||ge.length===0)return;const St=new Set(ge.map(ms=>ms.toLowerCase())),js=[],hs=new Set;for(const ms of Z){const vn=h.getChainConfig(ms);for(const Sn of vn?.supportedTokens??[]){if(!St.has(Sn.symbol.toLowerCase()))continue;const wo=Sn.address.toLowerCase();hs.has(wo)||(hs.add(wo),js.push(Sn.address))}}return js},[a,ce?.allowedTokens,Z,fe]),J=h.useWallet(),{address:te,isConnected:ue,isReady:Ce,isAuthenticated:xe,provider:V}=J,{executeGasless:oe,estimateGasless:ee}=Ps(),{externalWallet:Ae,externalAddress:Te,embeddedAddress:$e,activeWallet:rt,activeAddress:jt}=h.useProviderWallets(),Ze=h.useEmbeddedWalletAddress()||$e,{displayAssets:ye,filteredSpiceAssets:Fe,embeddedWalletAddress:Me,refreshSpiceAssets:Qe,refreshWalletAssets:_e}=ho({destinationToken:o,supportedSourceAssets:re,sourceChains:Z,enabled:e&&(de?!!Te:!!Ze)}),nt=fe||S||de?ye:Fe;i.useEffect(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:we,walletAddressUsed:Me,count:nt.length,assets:nt.map(ge=>({symbol:ge.symbol,address:ge.address,chainId:ge.chainId,balanceFormatted:ge.balanceFormatted,source:ge?._source}))})},[e,we,Me,nt]);const[K,Ue]=i.useState(null),[Se,Ye]=i.useState(y||""),[Ve,zt]=i.useState(!1),[It,at]=i.useState(null),[Ie,ft]=i.useState("idle"),[At,Re]=i.useState(""),[Ot,je]=i.useState(null),[Mt,Dt]=i.useState(!1),[Oe,me]=i.useState(null),[Le,Ge]=i.useState(null),[Lt,ke]=i.useState(!1),[Tt,xt]=i.useState(!1),[dt,ze]=i.useState(null),Ht=i.useRef(K),kt=i.useRef(!1),qt=i.useRef(null),Nt=i.useRef(null),Ft=i.useRef(0),yt=i.useRef(null),it=i.useRef(null);i.useEffect(()=>{Ht.current=K},[K]);const We=C==="adjustable"?Se:y||"0",et=Me||$e||te,{isQuoting:Ct,quoteError:Qt,estimatedOutput:Vt,resolvedSwap:vt,exactOutputSwap:ae,quoteAmountOut:ot,resolvedTokenIn:tt,isDirect:ht,needsSwap:Xe,selectedIsEquivalent:Be}=xo({direction:g,selectedAsset:K,destinationToken:o,chainId:_,recipient:et,paymentAmount:We,resolveExactOutputSwap:f}),ut=S?parseFloat(We||"0"):parseFloat(K?.amount||"")||0,Zt=ut>0&&ut<us,se=K?.asset?._source==="wallet",ne=!!K?.asset&&se&&K.asset.chainId!==_,ve=i.useMemo(()=>K?.asset?Fe.find(ge=>h.addressesEqual(ge.address,K.asset.address))?.balanceFormatted??0:0,[K,Fe]),He=se?K?.asset.balanceFormatted??0:ve,st=i.useMemo(()=>{if(!K?.asset)return!1;if(S)return Le?rs(Le.grossAmount,Le.decimals,K.asset.decimals)>K.asset.balance:Be||ht?ut>K.asset.balanceFormatted:ae?parseFloat(M.formatUnits(ae.amountInMax,K.asset.decimals))>K.asset.balanceFormatted:!1;if(Le){const ge=rs(Le.grossAmount,Le.decimals,K.asset.decimals);return se?ge>K.asset.balance:parseFloat(M.formatUnits(ge,K.asset.decimals))>He}return ut>He},[K,S,Le,Be,ut,ae,He,se,ht]);i.useEffect(()=>{e||(Ue(null),at(null),zt(!1),ft("idle"),Re(""),je(null),Dt(!1),me(null),Ge(null),ke(!1),xt(!1),ze(null),kt.current=!1,C==="adjustable"&&Ye(y||""),qt.current&&(qt.current.abort(),qt.current=null))},[e]);const mt=i.useCallback(ge=>{Ue(St=>({asset:ge,amount:St?.asset?.address===ge.address&&St?.asset?.chainId===ge.chainId&&St.amount||""})),at(null),ze(null),xt(!1)},[]),bt=i.useCallback(ge=>{Ue(St=>St&&{...St,amount:ge}),at(null),ze(null),xt(!1)},[]),gt=i.useCallback(ge=>{let St=ge;b&&parseFloat(St)>parseFloat(b)&&(St=b),Ye(St),A?.(St),at(null),ze(null),xt(!1)},[b,A]);i.useCallback(ge=>{if(kt.current||!te)return;const St=Ht.current;!St?.asset||!St.amount||St.asset?._source==="wallet"||M.parseUnits(S?We:St.amount,St.asset.decimals)===0n||(kt.current=!0,Qe())},[te,_,Qe,S,We]);const Ne=i.useCallback(ge=>{ft({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[ge.step]||"executing"),Re(ge.message),ge.txHash&&je(ge.txHash)},[]),Bt=i.useMemo(()=>({currentPaymentAmount:We,destinationToken:o,embeddedWalletAddress:Me,providerEmbeddedAddress:$e,externalWalletAddress:Te,address:te,isNon7702:de,isPayMode:S,resolvedChainId:_,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:K,needsSwap:Xe,resolvedSwap:vt,exactOutputSwap:ae,quoteAmountOut:ot,resolvedTokenIn:tt}),[We,o,Me,$e,Te,te,de,S,_,l,d,u,K,Xe,vt,ae,ot,tt]),qe=i.useCallback(ge=>ro({...Bt,requestTimestampMs:Nt.current??Date.now()},ge),[Bt]),X=i.useCallback(ge=>ao({...Bt,requestTimestampMs:Nt.current??Date.now()},ge),[Bt]),be=i.useCallback((ge,St,js,hs)=>io(ge,St,js,ee,hs),[ee]),pt=i.useMemo(()=>K?.asset?Xe&&tt?tt:K.asset.chainId===_?K.asset.address:tt??as(K.asset,_)??o.address:o.address,[K,o.address,Xe,_,tt]),wt=i.useCallback(()=>(Nt.current=Date.now(),po(it.current)),[]),Ke=i.useMemo(()=>K?.asset?h.addressesEqual(K.asset.address,o.address)&&K.asset.chainId===o.chainId:!1,[K,o.address,o.chainId]),Rt=Ke&&(de||S),lt=Rt&&ut>0&&!!K?.asset,_t=he&&!Rt,G=i.useMemo(()=>{if(!lt)return null;let ge;try{ge=M.parseUnits(We||"0",o.decimals)}catch{return null}return{symbol:o.symbol,decimals:o.decimals,grossAmount:ge,netAmount:ge,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[lt,We,o.symbol,o.decimals]),Y=It,pe=i.useMemo(()=>!(!K?.asset||ut<=0),[K,ut,lt]),ie=i.useMemo(()=>!e||Ve||Ie!=="idle"||!pe||lt||!K?.asset?null:[S?"pay":"supply",g,K.asset.address.toLowerCase(),K.asset.chainId,K.amount,We,o.address.toLowerCase(),o.chainId,_,tt?.toLowerCase()??"",Xe?"swap":"direct",ht?"direct-token":"routed-token",de?"non7702":"7702",Ke?"source-dest":"cross-chain",Ct?"quoting":"quoted",ae?.amountIn?.toString()??"",ae?.amountInMax?.toString()??"",ae?.venue??"",vt?.amountOut?.toString()??"",ot?.toString()??"",Me??"",$e??"",te??""].join("|"),[e,Ve,Ie,pe,lt,K,S,g,We,o,_,tt,Xe,ht,de,Ke,Ct,ae,vt,ot,Me,$e,te]),Pe=i.useCallback(()=>lo({selectedAsset:K,isPayMode:S,parsedAmount:ut,needsSwap:Xe,exactOutputSwap:ae,isNon7702:de,isSourceDestToken:Ke,currentPaymentAmount:We,destinationToken:o,feeExecutionMode:d,resolvedTokenIn:tt,embeddedWalletAddress:Me,providerEmbeddedAddress:$e,resolvedChainId:_,isConnected:ue,address:te,ready:Ce,authenticated:xe,isDirect:ht,resolvedSwap:vt,isQuoting:Ct,executionTokenAddress:pt,buildPayChainBatches:qe,buildSupplyChainBatches:X,estimateGasless:ee,estimateRequiredGrossFunding:be}),[K,S,ut,Xe,ae,de,Ke,We,o,d,tt,Me,$e,be,qe,ee,_,ue,te,Ce,xe,ht,vt,Ct,X,pt]);i.useEffect(()=>{yt.current=Pe},[Pe]);const De=i.useCallback(ge=>Br({asset:ge,isPayMode:S,isNon7702:de,needsSwap:Xe,isQuoting:Ct,embeddedWalletAddress:Me,buildSupplyChainBatches:X,estimateGasless:ee,executionTokenAddress:pt,feeExecutionMode:d}),[S,de,Xe,Ct,Me,X,ee,pt,d]);i.useEffect(()=>{if(!e){ke(!1),xt(!1),ze(null),Ge(null);return}if(Ve||Ie!=="idle"){Ft.current+=1,ke(!1);return}if(!pe){Ge(null),ke(!1),xt(!1),ze(null);return}if(lt){Ge(G),ke(!1),xt(!0),ze(null);return}if(Ct){Ft.current+=1,ke(!1),xt(!1);return}if(!ie)return;let ge=!1;const St=async()=>{const hs=++Ft.current;ze(null),ke(!0);try{const ms=await yt.current?.();if(ge||Ft.current!==hs)return;ms?(Ge(ms),xt(!0)):(Ge(null),xt(!1)),ze(null)}catch(ms){if(ge||Ft.current!==hs)return;const vn=h.sanitizeError(ms,"Unable to calculate fees for this action.");Ge(null),xt(!1),ze(vn)}finally{!ge&&Ft.current===hs&&ke(!1)}},js=window.setTimeout(()=>{St()},250);return()=>{ge=!0,clearTimeout(js),ke(!1)}},[e,Ve,Ie,pe,lt,G,Ct,ie]);const Je=i.useCallback(()=>(Nt.current=Date.now(),fo(it.current)),[]);i.useEffect(()=>{!S&&Ie==="success"&&Ot&&(Qe(),T?.(Ot))},[S,Ie,Ot,Qe,T]),i.useEffect(()=>{if(!S||Oe?.status!=="success"||kt.current||!te)return;kt.current=!0;const ge=Ht.current;!ge?.asset||ge.asset?._source==="wallet"||Qe()},[S,Oe?.status,te,Qe]);const ct=i.useRef(T),Pt=i.useRef(F);i.useEffect(()=>{ct.current=T},[T]),i.useEffect(()=>{Pt.current=F},[F]),i.useEffect(()=>{e&&(Qe(),_e())},[e,Qe,_e]),i.useEffect(()=>{S&&(Oe?.status==="success"&&ct.current?.(Oe.txHash||""),Oe?.status==="failed"&&Pt.current?.(new Error("Payment execution failed")))},[S,Oe?.status]);const Yt=i.useCallback(()=>{Dt(!1),me(null),Ue(null),kt.current=!1,Qe(),_e()},[Qe,_e]);it.current={selectedAsset:K,parsedAmount:ut,currentPaymentAmount:We,isInsufficientBalance:st,isPayMode:S,isNon7702:de,isSourceDestToken:Ke,needsSwap:Xe,exactOutputSwap:ae,selectedIsEquivalent:Be,resolvedTokenIn:tt,embeddedWalletAddress:Me,providerEmbeddedAddress:$e,externalWallet:Ae,externalWalletAddress:Te,activeSignerWallet:rt,activeSignerAddress:jt,address:te,isConnected:ue,ready:Ce,authenticated:xe,provider:V,resolvedChainId:_,executionTokenAddress:pt,destinationToken:o,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:c,onSuccess:T,onError:F,gasless:{estimateGasless:ee,executeGasless:oe,buildPayChainBatches:qe,buildSupplyChainBatches:X,estimateRequiredGrossFunding:be,onProgress:Ne},ui:{setError:at,setStep:ft,setStatusMsg:Re,setTxHash:je,setIsExecuting:zt,setShowStatusPanel:Dt,setPaymentResult:me},refs:{spiceDepositSubmittedRef:kt,abortControllerRef:qt}};const Xt=y?.trim(),Wt=S&&C==="fixed"&&Xt!==void 0&&Xt!==""&&ut===0,ss=S?(Wt||!!K?.asset)&&ut>=0&&!Zt&&!st&&!Ve&&(Wt||lt||Tt)&&!dt&&(Wt||!Xe||!!ae)&&!_t:!!K?.asset&&ut>0&&!Zt&&!st&&!Ve&&(Rt||Tt)&&!dt&&(ne||ht||!!vt&&!Ct)&&!_t;i.useEffect(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:ss,isPayMode:S,hasSelectedAsset:!!K?.asset,selectedAsset:K?.asset?{symbol:K.asset.symbol,address:K.asset.address,chainId:K.asset.chainId,balanceFormatted:K.asset.balanceFormatted,source:K.asset?._source}:null,parsedAmount:ut,isZeroAmountPay:Wt,isBelowMinimum:Zt,isInsufficientBalance:st,isExecuting:Ve,directExternalAction:Rt,directExecutionFeeNote:lt,feeEstimateReady:Tt,feeEstimateError:dt,needsSwap:Xe,isDirect:ht,isSourceDestToken:Ke,hasExactOutputSwap:!!ae,isQuoting:Ct,whitelistHoldPending:he,supplyHeldForWhitelist:_t,isWhitelistGateActive:fe,destinationToken:{symbol:o.symbol,address:o.address,chainId:o.chainId}})},[e,ss,S,K,ut,Wt,Zt,st,Ve,Rt,lt,Tt,dt,Xe,ht,Ke,ae,Ct,he,_t,fe,o]);const bs=ht?m||`Your ${o.symbol} will be used directly.`:x||"Your assets will be swapped and used in a single atomic transaction.",Ee=(_?h.getChainConfig(_):void 0)?.viemChain?.blockExplorers?.default?.url??"",Et=_r.indexOf(Ie),Jt=Ve?($r[Ie]||"EXECUTING...").toUpperCase():Ie==="success"?"DONE":Zt?`MINIMUM ${us}`:st?"INSUFFICIENT BALANCE":p.toUpperCase(),ns=i.useMemo(()=>{if(Ve)return"PAYING...";if(Zt)return`MINIMUM ${us}`;if(st&&K?.asset)return`INSUFFICIENT ${K.asset.symbol}`;if(p)return p.toUpperCase();const ge=ut>0?` ${We} ${o.symbol}`:"";return Xe?`SWAP & PAY${ge}`:`PAY${ge}`},[Ve,Zt,st,K,p,ut,We,o.symbol,Xe]),As=Ie==="success"?()=>{ft("idle"),Ue(null),je(null),Qe()}:wt,Ys=Ie==="success"?!1:!ss;if(!e)return null;const Xs=S?R||`Pay ${o.symbol}`:p,Es=S?E:n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[n.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:n.jsx(On,{color:le})}),n.jsx("p",{style:{fontSize:"12px",color:le,margin:0,lineHeight:"1.4",fontFamily:Q},children:bs})]});if(S){const ge=Oe&&(Oe.status==="success"||Oe.status==="failed")?[{asset:{symbol:K?.asset?.symbol||o.symbol,address:K?.asset?.address||""},amount:We,txHash:Oe.txHash||"",success:Oe.status==="success",error:Oe.status==="failed"?Oe.error:void 0}]:void 0;return n.jsx(cs,{isOpen:e,onClose:t,title:Xs,subtitle:Es,styles:v,dark:I,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[P&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Ln,{onClick:P,color:N,fontFamily:Q})}),!Wt&&n.jsx("div",{style:{marginBottom:"12px"},children:n.jsx(Hs,{assets:nt,selectedAsset:K??void 0,onAssetSelect:mt,onAmountChange:$l,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:K?.asset?Xe?Ct?"...":ae?`~${parseFloat(M.formatUnits(ae.amountIn,K.asset.decimals)).toFixed(6)}`:void 0:We??void 0:void 0,dark:I,theme:q,styles:v})}),n.jsx(Pr,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:N,fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:$,dk:D,dark:I,isQuoting:Ct,quoteError:Qt,estimatedOutput:Vt,paymentAmount:We,needsSwap:Xe,exactOutputSwap:ae,adjustable:C==="adjustable",maxAmount:b,onAmountChange:gt}),pe&&n.jsx(tn,{fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:$,resolvedDark:I,darkCardBorder:D.cardBorder,primaryColor:N,feePreview:Le,isLoading:Lt,errorText:dt,directExecutionFeeNote:lt}),Y&&n.jsx(Rs,{variant:"error",palette:L,fontFamily:Q,style:{marginBottom:"12px"},children:Y}),n.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:Je,disabled:!ss,loading:Ve,dark:I,styles:{...v,button:{...v?.button,backgroundColor:N}},children:ns}),Oe&&Mt&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:I?D.shell:"white",borderRadius:I?"12px":"6px",padding:"16px 0"},children:n.jsx(Gn,{type:"payment",isOpen:Oe.status!=="processing",isProcessing:Ve||Oe.status==="processing",closeOnComplete:!1,chainName:h.getChainName(_),explorerUrl:h.getExplorerUrl(_,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Dt(!1),me(null),Je()},onNewTx:Yt,onClose:()=>{Dt(!1),me(null)},onComplete:Yt,results:ge,styles:v,dark:I})})]})})}return n.jsx(cs,{isOpen:e,onClose:t,title:Xs,subtitle:Es,dark:I,styles:v,theme:j,closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[n.jsx("div",{style:{marginBottom:"16px"},children:n.jsx(Hs,{assets:nt,selectedAsset:K||void 0,onAssetSelect:mt,onAmountChange:bt,disabled:Ve||Ie==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:q,styles:v,dark:O,resolveMaxAmount:De,maxAmount:He>0?Ms(He,K?.asset.decimals??o.decimals):void 0})}),K?.asset&&!ht&&n.jsx(Pr,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:N,fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:$,dark:I,isQuoting:Ct,quoteError:Qt,estimatedOutput:Vt}),pe&&n.jsx(tn,{fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:$,resolvedDark:I,darkCardBorder:D.cardBorder,primaryColor:N,feePreview:Le,isLoading:Lt,errorText:dt,directExecutionFeeNote:lt}),Ie!=="idle"&&n.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Ie==="success"?H:Ie==="error"?L.errorBg:H,border:`1px solid ${Ie==="success"?$:Ie==="error"?L.errorBorder:$}`},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:L.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:L.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):n.jsx(h.Spinner,{size:14,color:N}),n.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:Ie==="success"?U:Ie==="error"?L.errorText:U,fontFamily:Q,flex:1},children:Ie==="success"?"Deposit confirmed":Ie==="error"?At||"Transaction failed":$r[Ie]||At}),Ie==="success"&&Ot&&n.jsx("a",{href:`${Ee}/tx/${Ot}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:N,fontFamily:Q,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Ie==="error"&&n.jsx("button",{onClick:()=>{ft("idle"),at(null),setTimeout(wt,50)},style:{background:"none",border:"none",fontSize:"12px",color:N,fontFamily:Q,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),Et>=0&&Ie!=="success"&&Ie!=="error"&&n.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${z}22`,overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:N,transformOrigin:"left center",transform:`scaleX(${(Et+1)/_r.length})`,transition:"transform 400ms ease"}})})]}),It&&Ie==="idle"&&n.jsx(Rs,{variant:"error",palette:L,fontFamily:Q,style:{marginBottom:"16px"},children:It}),n.jsx(h.Button,{variant:"outline",fullWidth:!0,disabled:Ys,onClick:As,theme:j,dark:I,styles:{...v,button:{...v?.button,backgroundColor:N}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:W},children:Jt})]})})},_l=e=>n.jsx(ea,{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}),ec=({label:e="Export Wallet",style:t,className:s,onExport:o,onError:r})=>{const[a,l]=i.useState(!1),[d,u]=i.useState(!1),{primaryColor:c}=h.useSpiceBrand(),f=i.useContext(h.SpiceFlowProviderContext),{isAuthenticated:p}=h.useWallet();let g=null;try{g=An.usePrivy()}catch{}let x=null,m=null;try{x=vo.useEmbeddedReveal(),m=vo.useDynamicContext()}catch{x=null,m=null}const y=h.getDynamicEmbeddedWallet(m),C=i.useCallback(async()=>{if(!p){r?.("User is not authenticated. Please log in first.");return}try{if(f?.provider==="dynamic"){if(!x||!y){r?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await x.initExportProcess(!1),o?.();return}if(!g){r?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await g.exportWallet(),o?.()}catch(A){const v=A instanceof Error?A.message:"Failed to export wallet";console.error("Export wallet error:",A),r?.(v)}},[y,x,p,r,o,g,f?.provider]),k=!p,b={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:k?"not-allowed":"pointer",opacity:k?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:d?`${c}cc`:a?`${c}ee`:c,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return n.jsxs("button",{onClick:C,onMouseEnter:()=>l(!0),onMouseLeave:()=>{l(!1),u(!1)},onMouseDown:()=>u(!0),onMouseUp:()=>u(!1),disabled:k,className:s,style:b,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 ta(e){const t=i.useContext(h.SpiceFlowProviderContext),s=h.useEmbeddedWalletAddress(),o=e?.enabled===!1?void 0:s,r=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...Qo(o,r),embeddedWalletAddress:s}}var tc="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 sc=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:l,dark:d=!1,showModeToggle:u,isEmbeddedMode:c=!0,onModeToggle:f})=>{const[p,g]=i.useState(!1),x=async()=>{a&&await ja(a)&&(g(!0),setTimeout(()=>g(!1),2e3))},m=t==="active",y=s||(m?"Active":"Inactive"),C=m?"#10b981":"#9ca3af",k=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:l.textPrimary},children:[e," Account"]}),u?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsxs("button",{onClick:f,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?l.hoverBg:"#f3f4f6",border:d?`1px solid ${l.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',color:l.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[n.jsx("span",{children:c?"Embedded":"External"}),n.jsx("img",{src:tc,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...d?{filter:"invert(0.65)"}:{}}})]}),n.jsx(Po,{content:k,label:"Account mode info",textColor:d?l.textPrimary:"#f9fafb",backgroundColor:d?l.cardBg:"#111827",borderColor:d?l.cardBorder:"rgba(255,255,255,0.08)",accentColor:d?l.textSecondary:"#6b7280",children:n.jsx("img",{src:Qn,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?l.hoverBg:m?"#ecfdf5":"#f3f4f6",border:d?`1px solid ${l.cardBorder}`:m?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:C}}),n.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?l.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),n.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:l.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:Bs(o)}),r&&n.jsx("div",{style:{fontSize:"12px",color:l.textSecondary,marginBottom:"8px"},children:r}),a&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsx("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:d?l.textSecondary:"#9ca3af"},children:jo(a)}),n.jsx("button",{onClick:x,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:d?l.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:p?"Copied":"Copy"})]})]})},nc=i.memo(sc),oc=({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((r,a)=>{const l=h.getChainConfig(r.chainId)?.displayName||`Chain ${r.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:r.tokenSymbol.charAt(0)}),n.jsxs("div",{children:[n.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:[r.amount," ",r.tokenSymbol]}),n.jsxs("div",{style:{fontSize:"11px",color:s.warningText},children:["on ",l]})]})]}),n.jsx("button",{onClick:()=>t?.(r),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"})]},`${r.tokenAddress}-${r.chainId}-${a}`)})})]}),rc=i.memo(oc),ac=e=>`${e.tokenAddress}-${e.chainId}`,ic=({spiceAssets:e,loading:t,dk:s,dark:o=!1,canDirectWithdraw:r=!1,onDirectWithdraw:a,directWithdrawState:l})=>{const d={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s.textSecondary,marginBottom:"8px",textTransform:"uppercase"},u={backgroundColor:s.cardBg,border:o?`1px solid ${s.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?n.jsxs("div",{children:[n.jsx("div",{style:d,children:"Idle Balances"}),[1,2].map(c=>n.jsx("div",{style:{...u,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},c))]}):e.length===0?n.jsxs("div",{children:[n.jsx("div",{style:d,children:"Idle Balances"}),n.jsx("div",{style:{...u,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:d,children:"Idle Balances"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((c,f)=>{const p=h.getChainConfig(c.chainId),g=c.chainDisplayName||p?.displayName||`Chain ${c.chainId}`,x=c.tokenDisplaySymbol||c.tokenDisplayName||c.tokenSymbol,m=ac(c),y=r&&c.directWithdraw&&!!a,C=l?.key===m?l:null,k=C?.step==="pending";return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...u},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[c.logoURI?n.jsx("img",{src:c.logoURI,alt:c.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:x.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:x}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:g})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:xs(c.balanceFormatted)}),n.jsx("div",{style:{fontSize:"11px",color:C?.step==="error"?s.errorText:o?s.textSecondary:"#9ca3af"},children:C?.step==="error"?C.message||"Withdraw failed":Bs(c.usdValue)})]}),y&&n.jsx("button",{onClick:()=>!k&&a(c),disabled:k,title:"Withdraw to external wallet",style:{padding:"6px 10px",borderRadius:"6px",border:o?`1px solid ${s.cardBorder}`:"1px solid #e5e7eb",backgroundColor:o?s.hoverBg:"#ffffff",color:s.textPrimary,fontSize:"11px",fontWeight:600,cursor:k?"default":"pointer",opacity:k?.6:1,whiteSpace:"nowrap"},children:k?"Withdrawing\u2026":"Withdraw"})]})]},`${c.tokenAddress}-${c.chainId}-${f}`)})})]})},lc=i.memo(ic),cc=({section:e,dk:t,dark:s=!1})=>{const o=r=>{switch(r){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((r,a)=>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:[r.tokenLogoURI?n.jsx("img",{src:r.tokenLogoURI,alt:r.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:r.tokenSymbol.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:r.tokenSymbol}),n.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:r.label})]})]}),n.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:o(r.valueColor)},children:r.displayValue})]},a))})]})},dc=i.memo(cc),uc=({onDepositClick:e,onWithdrawClick:t,depositDisabled:s=!1,withdrawDisabled:o=!1,primaryColor:r="#EA4B4B",dark:a=!1})=>!e&&!t?null:n.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&n.jsx(h.Button,{variant:"outline",onClick:e,disabled:s,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&n.jsx(h.Button,{variant:"outline",onClick:t,disabled:o,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),pc=i.memo(uc),fc=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,spiceAssets:l,spiceAssetsLoading:d,pendingDeposits:u,customSections:c,notice:f,onDepositClick:p,onWithdrawClick:g,depositDisabled:x,onCompleteDeposit:m,primaryColor:y,dk:C,dark:k=!1,showModeToggle:b,isEmbeddedMode:A,onModeToggle:v,showConnectExternalCta:w,onConnectExternalWallet:R,connectExternalError:E,showHowItWorks:P=!0,canDirectWithdraw:T,onDirectWithdraw:F,directWithdrawState:S})=>{const[j,I]=i.useState(!1);return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[n.jsx(nc,{appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:C,dark:k,showModeToggle:b,isEmbeddedMode:A,onModeToggle:v}),f&&n.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:f.tone==="warning"?k?"rgba(245, 158, 11, 0.12)":"#fffbeb":f.tone==="success"?k?"rgba(16, 185, 129, 0.12)":"#ecfdf5":C.cardBg,border:f.tone==="warning"?k?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":f.tone==="success"?k?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":k?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",color:f.tone==="warning"?k?"#fbbf24":"#92400e":f.tone==="success"?k?"#34d399":"#047857":C.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:f.message}),w&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsx("button",{onClick:R,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:y||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),E&&n.jsx("span",{style:{fontSize:"11px",color:k?C.errorText:"#b91c1c",lineHeight:1.4},children:E})]}),n.jsx("div",{style:{height:"1px",backgroundColor:k?"#2d2d2d":"#e5e7eb"}}),n.jsx(pc,{onDepositClick:p,onWithdrawClick:g,depositDisabled:x,primaryColor:y,dark:k}),P&&n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>I(!j),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:C.cardBg,border:k?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:C.textSecondary,fontSize:"12px",fontWeight:500},children:[n.jsx("span",{children:"How It Works"}),n.jsx("span",{style:{transform:j?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),j&&n.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:k?C.cardBg:"#f0fdf4",border:k?`1px solid ${C.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:k?C.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),n.jsx(rc,{pendingDeposits:u,onCompleteDeposit:m,dk:C,dark:k}),n.jsx(lc,{spiceAssets:l,loading:d,dk:C,dark:k,canDirectWithdraw:T,onDirectWithdraw:F,directWithdrawState:S}),c.map((N,D)=>n.jsx(dc,{section:N,dk:C,dark:k},D))]})},hc=i.memo(fc);function mc(e,t,s){const o=t-s.gasBridge-s.spicenetFee;if(o<=0n)throw new Error("Balance is too small to cover the network fee.");const r=[{recipient:e,amount:o}];return s.gasBridge>0n&&r.push({recipient:B.SPICE_GAS_FEE_RECIPIENT,amount:s.gasBridge}),s.spicenetFee>0n&&r.push({recipient:B.SPICE_PLATFORM_FEE_RECIPIENT,amount:s.spicenetFee}),r}function gc(e,t,s){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*s}const xc=new Set([B.SPICE_GAS_FEE_RECIPIENT,B.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function yc(e,t){return!e||e.length!==t.length?!1:e.every((s,o)=>{const r=t[o];return s.recipient.toLowerCase()!==r.recipient.toLowerCase()?!1:xc.has(s.recipient.toLowerCase())?gc(s.amount,r.amount,100n):!0})}function sa(e,t,s){return{chainId:e,domain:"evm",tokenTransfers:[],calls:s.filter(o=>o.amount>0n).map(o=>({to:t,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[o.recipient,o.amount]})}))}}function Cc(e,t){const s=e.intents.flatMap(r=>r.batches).filter(r=>ts(r).totalFee>0n),o=s.filter(r=>r.chainId===t);return(o.length>0?o:s)[0]??null}function bc(e,t,s,o){const r=Cc(o,e),{gasFee:a,bridgeFee:l,spicenetFee:d}=r?ts(r):{gasFee:0n,bridgeFee:0n,spicenetFee:0n};return mc(t,s,{gasBridge:a+l,spicenetFee:d})}function wc(){const{executeGasless:e}=Ps(),t=h.useEmbeddedWalletAddress(),{embeddedAddress:s}=h.useProviderWallets(),o=t||s;return{withdraw:i.useCallback(async({tokenAddress:r,chainId:a,balance:l,recipient:d,onProgress:u})=>{const c=r,f=d;if(l<=0n)throw new Error("Nothing to withdraw.");const p=[sa(a,c,[{recipient:f,amount:l}])];let g=null;return e(p,c,0n,u,void 0,{useCustomTransfers:!0,userOverride:o,adjustBatchesForEstimate:({feeEstimate:x})=>{const m=bc(a,f,l,x);return yc(g,m)?null:(g=m,[sa(a,c,m)])}})},[e,o])}}function kc(e){return!!e.embeddedAddress&&!!e.externalAddress}const yo=380,Is=8,vc=[];function na(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Sc(e,t){const s=new Map;Object.entries(t).forEach(([r,a])=>{if(!Number.isFinite(a)||a<=0)return;s.set(r,a),s.set(r.toUpperCase(),a);const l=na(r);l&&s.set(l,a)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const r of o){if(!r)continue;const a=s.get(r)??s.get(r.toUpperCase());if(a!==void 0)return a;const l=na(r);if(!l)continue;const d=s.get(l);if(d!==void 0)return d}return 0}const Ic=({appName:e="Spice",status:t="active",statusLabel:s,customSections:o=vc,extraAssets:r=[],tokenPrices:a={},breakdownLabels:l=[],notice:d,styles:u,dark:c=!1,onDepositSuccess:f,onDepositClick:p,onWithdrawClick:g,onCompleteDeposit:x,showModeToggle:m=!1,defaultMode:y})=>{const C=i.useContext(h.SpiceFlowProviderContext),k=C?.mode!=="7702",b=!!C?.isWhitelistGateActive,A=!!C?.isWhitelistConfigured&&C?.isUserWhitelisted!==!0,v=i.useRef(!1);i.useEffect(()=>{if(!v.current){if(h.hasStoredSpiceFlowMode()){v.current=!0;return}y&&C?.setMode&&(C.setMode(y==="non7702"?"ondemand":"7702"),v.current=!0)}},[C,y]);const[w,R]=i.useState(!1),[E,P]=i.useState(null),[T,F]=i.useState({top:0,bottom:0,left:0,placement:"below"}),S=i.useRef(null),j=i.useRef(null),{address:I,isConnected:N}=h.useWallet(),D=h.useEmbeddedWalletAddress(),{externalAddress:L,embeddedAddress:Q}=h.useProviderWallets(),{dark:W,primaryColor:O,dk:H}=h.useSpiceBrand(u,c),$=k&&!L,U=!k||$,z=U?D||Q:I,le=i.useMemo(()=>C?.supportedChainIds??B.getChainIdsByNetwork("mainnet"),[C?.supportedChainIds]),{assets:q,loading:_}=Qs({address:z,supportedChains:le,enabled:!!z&&U,refetchInterval:3e4}),ce=i.useMemo(()=>{const K=U?q.map(Se=>{const Ye=Se.balanceUsd||0,Ve=Number.isFinite(Se.balanceFormatted)?Se.balanceFormatted:0,zt=Ye>0?Ye:Sc(Se,a)*Ve;return{tokenAddress:Se.address,tokenSymbol:Se.symbol,tokenDisplaySymbol:Pn(Se),tokenDisplayName:Da(Se),tokenDecimals:Se.decimals,chainId:Se.chainId,chainDisplayName:Wn(Se),balance:Se.balance.toString(),balanceFormatted:Se.balanceFormatted,usdValue:zt,logoURI:Se.logoURI}}):[],Ue=$?[]:r;return[...K,...Ue].filter(Se=>Se.balanceFormatted>0)},[U,$,q,a,r]),we=i.useMemo(()=>ce.reduce((K,Ue)=>K+Ue.usdValue,0),[ce]),{pendingDeposits:de}=ta({chainIds:le,enabled:!!I,discoverWalletBalances:!0}),fe=i.useMemo(()=>o.reduce((K,Ue)=>K+Ue.totalValue,0),[o]),he=we+fe,Z=i.useMemo(()=>{const K=[];we>0&&K.push(`${Bs(we)} idle`);for(const Ue of o){const Se=l.find(Ye=>Ye.sectionTitle===Ue.title)?.label||Ue.title.toLowerCase();K.push(`${Bs(Ue.totalValue)} ${Se}`)}return K.join(" \xB7 ")},[we,o,l]),re=i.useCallback(K=>{x?x(K):P(K)},[x]),J=i.useCallback(()=>{P(null)},[]),te=i.useCallback(()=>{P(null),f?.()},[f]),ue=i.useCallback(()=>{if(!S.current)return;const K=S.current.getBoundingClientRect(),Ue=window.innerHeight-K.bottom-Is,Se=K.top-Is,Ye=Ue>=400||Ue>=Se?"below":"above",Ve=Math.max(Is,Math.min(K.right-yo,window.innerWidth-yo-Is)),zt=Ye==="below"?K.bottom+Is:K.top-Is,It=Ye==="above"?window.innerHeight-zt:0;F({top:zt,bottom:It,left:Ve,placement:Ye})},[]);i.useLayoutEffect(()=>{w&&ue()},[w,ue]),i.useEffect(()=>{if(!w)return;const K=Ye=>{S.current&&!S.current.contains(Ye.target)&&j.current&&!j.current.contains(Ye.target)&&R(!1)},Ue=Ye=>{Ye.key==="Escape"&&R(!1)},Se=()=>ue();return document.addEventListener("mousedown",K),document.addEventListener("keydown",Ue),window.addEventListener("scroll",Se,{passive:!0}),window.addEventListener("resize",ue),()=>{document.removeEventListener("mousedown",K),document.removeEventListener("keydown",Ue),window.removeEventListener("scroll",Se),window.removeEventListener("resize",ue)}},[w,ue]);const Ce=U?D||Q||I:L||I,xe=i.useCallback(()=>{C?.setMode&&C.setMode(U?"ondemand":"7702")},[C,U]),[V,oe]=i.useState(null);let ee=null;try{ee=An.useConnectWallet({onSuccess:()=>oe(null),onError:K=>oe(h.sanitizeError(K,"Failed to connect wallet."))}).connectWallet}catch{ee=null}const Ae=i.useCallback(()=>{ee&&(R(!1),oe(null),ee({walletChainType:"ethereum-only"}))},[ee]),Te=!L&&!!ee,$e=i.useCallback(()=>{R(!1),p?.()},[p]),rt=i.useCallback(()=>{R(!1),g?.()},[g]),jt=i.useCallback(K=>{R(!1),re(K)},[re]),{withdraw:Ze}=wc(),[ye,Fe]=i.useState(null),Me=kc({embeddedAddress:D||Q,externalAddress:L}),Qe=i.useCallback(async K=>{if(!L)return;const Ue=`${K.tokenAddress}-${K.chainId}`;Fe({key:Ue,step:"pending"});try{await Ze({tokenAddress:K.tokenAddress,chainId:K.chainId,balance:BigInt(K.balance),recipient:L}),Fe(null)}catch(Se){Fe({key:Ue,step:"error",message:h.sanitizeError(Se,"Withdraw failed")})}},[Ze,L]);if(typeof window>"u")return null;const _e=n.jsxs("button",{ref:S,onClick:()=>R(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:W?H.hoverBg:"#ffffff",border:W?`1px solid ${H.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:W?H.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:W?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[n.jsxs("span",{children:[e," Account"]}),N&&n.jsxs("span",{style:{color:W?H.textSecondary:"#6b7280"},children:["\xB7 ",Bs(he)]}),n.jsx("span",{style:{fontSize:"10px",color:W?H.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),nt=w?Us.createPortal(n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:gs.popover},onClick:()=>R(!1)}),n.jsx("div",{ref:j,style:{position:"fixed",top:T.placement==="below"?`${T.top}px`:"auto",bottom:T.placement==="above"?`${T.bottom}px`:"auto",left:`${T.left}px`,width:`${yo}px`,maxWidth:`calc(100vw - ${Is*2}px)`,maxHeight:"80vh",backgroundColor:W?H.shell:"#ffffff",border:W?`1px solid ${H.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:W?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:gs.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${Ut.out}`},children:n.jsx(hc,{appName:e,status:t,statusLabel:s,totalUsdValue:he,breakdownSubtitle:Z,address:U?Ce:I,spiceAssets:ce,spiceAssetsLoading:_,pendingDeposits:de,customSections:o,notice:d,onDepositClick:p?$e:void 0,onWithdrawClick:g?rt:void 0,depositDisabled:A,onCompleteDeposit:jt,primaryColor:O,dk:H,dark:W,showModeToggle:m,isEmbeddedMode:U,onModeToggle:xe,showConnectExternalCta:Te,onConnectExternalWallet:Ae,connectExternalError:V,showHowItWorks:!b,canDirectWithdraw:Me,onDirectWithdraw:Qe,directWithdrawState:ye})}),n.jsx("style",{children:`
|
|
103
|
+
`})]})},jl="0xa9059cbb";function Fl(e){const t=new Map;for(const s of e){if(s.amount<=0n)continue;const o=M.getAddress(s.token),r=M.getAddress(s.to),a=`${o.toLowerCase()}:${r.toLowerCase()}`,l=t.get(a);l?l.amount+=s.amount:t.set(a,{token:o,to:r,amount:s.amount})}return[...t.values()]}function Bl(e,t){return`0x${t}${e.slice(4)}`}function so(e,t){return kr(e,t)}function kr(e,t,s){const o=Tl(t,e),r=Math.floor(Date.now()/1e3)+60*10,a=B.hashChainBatches(o);return{user:e,...s?{chainAuthorizations:s}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:r,chainBatches:a.map((l,d)=>({hash:l.hash,chainId:l.chainId,tokenTransfers:o[d].domain==="spicenet"?[]:o[d].tokenTransfers??[],calls:l.calls}))}]}}function Tl(e,t){return e.map(s=>{if(s.domain==="spicenet"||s.calls.length===0)return s;const o=new Set((s.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&M.getAddress(a.to).toLowerCase()===t.toLowerCase()).map(a=>M.getAddress(a.token).toLowerCase()));if(o.size===0)return s;let r=0;for(const a of s.calls){if(!a.data?.startsWith(jl))break;try{const l=M.decodeFunctionData({abi:h.P,data:a.data});if(l.functionName!=="transfer")break;const[d]=l.args;if(d.toLowerCase()===t.toLowerCase()||!o.has(M.getAddress(a.to).toLowerCase()))break;r+=1}catch{break}}return r===0?s:{...s,calls:s.calls.slice(r)}})}function os(e,t,s,o){if(e.some(f=>f.domain==="spicenet"))return e;const r=s?.intents.flatMap(f=>f.batches),a=f=>f.from==="escrow",l=e.map(f=>{const p=r?.find(v=>v.chainId===f.chainId);if(!p)return f;const g=ts(p),x=g.totalFee;if(x<=0n)return f;const m=(f.tokenTransfers??[]).find(v=>a(v)&&M.getAddress(v.to).toLowerCase()===t.toLowerCase()&&!B.isNativeToken(M.getAddress(v.token)));if(!m)return f;const y=M.getAddress(m.token);let C=!1;const k=(f.tokenTransfers??[]).map(v=>C||!a(v)||M.getAddress(v.to).toLowerCase()!==t.toLowerCase()||M.getAddress(v.token).toLowerCase()!==y.toLowerCase()?v:(C=!0,{...v,amount:o?.payoutAlreadyGross?BigInt(v.amount):BigInt(v.amount)+x}));if(!C)return f;const b=[];g.spicenetFee>0n&&b.push({to:y,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[B.SPICE_PLATFORM_FEE_RECIPIENT,g.spicenetFee]})});const A=g.gasFee+g.bridgeFee;return A>0n&&b.push({to:y,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[B.SPICE_GAS_FEE_RECIPIENT,A]})}),{...f,tokenTransfers:k,calls:[...b,...f.calls]}}),d=l.flatMap(f=>(f.tokenTransfers??[]).filter(a).map(p=>{const g=M.getAddress(p.token),x=M.getAddress(p.to),m=[{token:g,to:x,amount:BigInt(p.amount)}];return{chainId:f.chainId,transfers:Fl(m)}}));if(d.length===0)return e;const u=o?.requestTimestampMs??Date.now(),c=BigInt(Math.floor(u/1e3))+3600n;return[{chainId:B.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:d.map((f,p)=>{const g=M.keccak256(M.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,f.transfers[0].token,f.transfers.reduce((m,y)=>m+y.amount,0n),BigInt(f.chainId),BigInt(u+p)])),x=Bl(g,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:M.encodeFunctionData({abi:B.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${f.chainId}`,idempotenceKey:x,nbf:0n,exp:c,metadata:"{}",transfers:f.transfers.map(m=>({token:m.token.toLowerCase(),to:m.to,amount:m.amount}))}]})}})},...l]}function fn(e,t){return t?e.some(s=>(s.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount)>=t.grossAmount)):!1}function vr(e){return!e.isSemi7702&&e.isDirectDeposit&&!e.isSourceDestToken}function no(e){const t=e.selectedAsset?.asset,s=e.selectedAsset?.amount;if(!(!t||!s))return M.parseUnits(s,t.decimals)}function Sr(e){return e.map(t=>({r:t.r,s:t.s,yParity:t.yParity,address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce)}))}function Ml(e,t){if(e.length!==t.length)return!1;const s=B.hashChainBatches(e),o=B.hashChainBatches(t);return s.every((r,a)=>r.hash===o[a]?.hash)}async function hn({user:e,batches:t,authorizations:s,adjustBatchesForEstimate:o}){let r=t;const a=Sr(s);for(let l=0;l<10;l+=1){const d=await h.relayerService.estimateActionFees(kr(e,r,a)),u=await o({feeEstimate:d,batches:r});if(!u||Ml(r,u))return r;r=u}throw new Error("Fee estimate did not converge. Please retry.")}function is(e,t){const s=e.selectedAsset?.asset;if(!s||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=M.parseUnits(e.selectedAsset.amount,s.decimals),r=t?.grossAmount??o;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:o,grossAmount:M.formatUnits(r,s.decimals),grossAmountWei:r})}async function mn(e,t,s){const o=[...new Set(s.filter(a=>a.domain!=="spicenet").map(a=>a.chainId))],r=[];for(const a of o){const l=h.getClientForChain(a),d=h.getDelegateContractAddress(a),u=await B.getAccountNonce(t,l),c=await e.actions.signAuthorization({contractAddress:d,chainId:a,nonce:Number(u)});r.push(c)}return r}async function oo(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 r=s??await mn(e,o,t),a=B.hashChainBatches(t),l=Math.floor(Date.now()/1e3)+60*10,d=a.map(x=>x.hash),u=M.keccak256(M.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(l),d])),c=await e.actions.signMessage({raw:u}),f=typeof c=="string"?c:c.signature;if(!f)throw new Error("Failed to sign intent authorization");const p={mode:"7702",signatureType:"ecdsa",signature:f,nbf:0,exp:l,chainBatches:a.map((x,m)=>{const y=t[m],C=y.domain==="spicenet";return{hash:x.hash,chainId:x.chainId,tokenTransfers:C?[]:y.tokenTransfers??[],calls:x.calls}})},g=await h.relayerService.createAction({user:o,chainAuthorizations:Sr(r),intents:[p]});if(g){const x=h.createInitialSteps(t,h.getChainName),[m,y]=g.intentIds[0].split("/"),C=parseInt(y||"0",10),k=g.intentIds[0];e.startStatusPolling(g.intentIds[0],x),await nr({actionId:m,intentIndex:C,intentId:k,totalSteps:t.length,isSpicenetStep:b=>t[b]?.domain==="spicenet",maxExecuteAttemptsForStep:b=>t[b]?.domain==="spicenet"?6:3,maxPolls:72})}}async function Rl(e){let t=is(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 mn(e,s,t),r=Date.now();let a=os([...t],s,void 0,{requestTimestampMs:r}),l;a=await hn({user:s,batches:a,authorizations:o,adjustBatchesForEstimate:({feeEstimate:d})=>{const u=vs(d,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,actionAmount:no(e)});return u?(l={grossAmount:u.grossAmount,netAmount:u.netAmount,feeAmount:u.totalFee??0n},t=is(e,l),os([...t],s,d,{payoutAlreadyGross:fn(t,l),requestTimestampMs:r})):null}}),await oo(e,a,o)}async function Dl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");const s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,r=M.parseUnits(e.selectedAsset.amount,o.decimals),a=o.chainId,l=e.escrowAddress||B.getEscrowContractAddress(a),d=B.normalizeNativeTokenAddress(o.address),u=o.isNative||B.isNativeToken(d),c=Date.now();let f;const p=s.some(k=>k.tokenTransfers?.some(b=>b.from==="escrow")),g=k=>({chainId:a,calls:u?[{to:l,value:k,data:"0x"}]:[{to:d,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[l,k]})}]}),x=(k,b,A,v)=>{const w=g(k);if(!p)return[w,...b];const R=os([...b],t,A,{payoutAlreadyGross:fn(b,v),requestTimestampMs:c});return[w,...R]};let m=is(e),y=x(r,m);const C=await mn(e,t,y);p&&(y=await hn({user:t,batches:y,authorizations:C,adjustBatchesForEstimate:({feeEstimate:k})=>{const b=vs(k,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});return b?(f={grossAmount:b.grossAmount,netAmount:b.netAmount,feeAmount:b.totalFee??0n},m=is(e,f),x(f.grossAmount,m,k,f)):null}})),await oo(e,y,C)}async function Nl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(e.onLockExecute){const T=e.resolveLockBatches();if(T.length===0)throw new Error("No lock batches configured");const F=e.selectedAsset.asset,S=M.parseUnits(e.selectedAsset.amount,F.decimals),j=await e.onLockExecute({asset:F,amount:e.selectedAsset.amount,amountWei:S,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:T});j&&e.onLockSuccess?.(j);return}const s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,r=M.parseUnits(e.selectedAsset.amount,o.decimals),a=o.chainId,l=e.escrowAddress||B.getEscrowContractAddress(a),d=B.normalizeNativeTokenAddress(o.address),u=o.isNative||B.isNativeToken(d),c=s.some(T=>T.tokenTransfers?.some(F=>F.from==="escrow")),f=Date.now();let p;const g=T=>({chainId:a,calls:u?[{to:l,value:T,data:"0x"}]:[{to:d,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[l,T]})}]}),x=(T,F,S,j)=>{const I=g(T);if(!c)return[I,...F];const N=os([...F],t,S,{payoutAlreadyGross:fn(F,j),requestTimestampMs:f});return[I,...N]};let m=is(e),y=x(r,m);const C=await mn(e,t,y);c&&(y=await hn({user:t,batches:y,authorizations:C,adjustBatchesForEstimate:({feeEstimate:T})=>{const F=vs(T,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});return F?(p={grossAmount:F.grossAmount,netAmount:F.netAmount,feeAmount:F.totalFee??0n},m=is(e,p),x(p.grossAmount,m,T,p)):null}}));const k=p?.grossAmount??r,b=await e.externalWallet.getEthereumProvider();let A=null;try{const T=await b.request({method:"eth_chainId"});A=parseInt(T,16)}catch{A=null}A!==a&&await h.ensureWalletOnChain(b,a);const v=h.getChainConfig(a),w=M.createWalletClient({account:e.externalWalletAddress,chain:v?.viemChain,transport:M.custom(b)}),R=h.getClientForChain(a),E=async T=>{if(T<=0n)return;const F=u?await w.sendTransaction({to:t,value:T,chain:v?.viemChain}):await w.sendTransaction({to:d,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[t,T]}),chain:v?.viemChain});if((await R.waitForTransactionReceipt({hash:F,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed")};await E(k);let P=k;if(c)for(let T=0;T<4;T+=1){y=await hn({user:t,batches:y,authorizations:C,adjustBatchesForEstimate:({feeEstimate:S})=>{const j=vs(S,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});return j?(p={grossAmount:j.grossAmount,netAmount:j.netAmount,feeAmount:j.totalFee??0n},m=is(e,p),x(p.grossAmount,m,S,p)):null}});const F=p?.grossAmount??r;if(F<=P)break;await E(F-P),P=F}await oo(e,y,C)}async function Pl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702||vr(e)){const l=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address;if(!l)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let d=is(e);if(d.length===0)throw new Error("No lock batches configured");const u=e.selectedAsset.asset,c=M.parseUnits(e.selectedAsset.amount,u.decimals),f=u.chainId,p=e.escrowAddress||B.getEscrowContractAddress(f),g=B.normalizeNativeTokenAddress(u.address),x=u.isNative||B.isNativeToken(g),m=d.some(v=>v.tokenTransfers?.some(w=>w.from==="escrow")),y=v=>({chainId:f,calls:x?[{to:p,value:v,data:"0x"}]:[{to:g,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[p,v]})}]}),C=(v,w,R)=>{const E=y(v);if(!m)return[E,...w];const P=os([...w],l,R,{payoutAlreadyGross:w.some(T=>(T.tokenTransfers??[]).some(F=>F.from==="escrow"&&BigInt(F.amount)>=v))});return[E,...P]};let k=C(c,d),b=null,A;for(let v=0;v<4;v+=1){const w=await h.relayerService.estimateActionFees(so(l,k)),R=vs(w,{symbol:u.symbol,decimals:u.decimals,actionAmount:c});if(!R)return b;const E={grossAmount:R.grossAmount,netAmount:R.netAmount,feeAmount:R.totalFee??0n},P=A?.grossAmount===E.grossAmount&&A?.netAmount===E.netAmount&&A?.feeAmount===E.feeAmount;if(b=R,A=E,d=is(e,E),k=C(E.grossAmount,d,w),P)break}return b}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let s=is(e);if(s.length===0)throw new Error("No lock batches configured");let o=os([...s],t),r=null;for(let l=0;l<4;l+=1){const d=await h.relayerService.estimateActionFees(so(t,o)),u=vs(d,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:no(e)});if(!u)return null;const c={grossAmount:u.grossAmount},f=r?.grossAmount===u.grossAmount&&r?.netAmount===u.netAmount&&r?.totalFee===u.totalFee;if(r=u,s=is(e,c),o=os([...s],t,d,{payoutAlreadyGross:fn(s,c)}),f)break}if(r)return r;const a=await h.relayerService.estimateActionFees(so(t,o));return vs(a,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:no(e)})}async function Wl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.activeSignerWallet??e.externalWallet,s=e.activeSignerAddress??e.externalWalletAddress;if(!s||!t)throw new Error("Please connect your wallet to continue");const o=e.resolveLockBatches();if(o.length===0)throw new Error("No lock batches configured");const r=o.find(p=>p.chainId===e.lockChainId)||o[0];if(!r)throw new Error("No lock batch for lock chain");const a=await t.getEthereumProvider();let l=null;try{const p=await a.request({method:"eth_chainId"});l=parseInt(p,16)}catch{l=null}l!==e.lockChainId&&await h.ensureWalletOnChain(a,e.lockChainId);const d=h.getChainConfig(e.lockChainId),u=M.createWalletClient({account:s,chain:d?.viemChain,transport:M.custom(a)}),c=h.getClientForChain(e.lockChainId);let f;for(const p of r.calls){const g=await u.sendTransaction({to:p.to,data:p.data,value:p.value,chain:d?.viemChain});if((await c.waitForTransactionReceipt({hash:g,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");f=g}f&&e.onLockSuccess?.(f)}async function Ul(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=h.sanitizeError(s,""),r=typeof s?.shortMessage=="string"?s.shortMessage:typeof s?.message=="string"?s.message:"";e.ui.setError(o||r||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Wl(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await Nl(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{vr(e)?await Dl(e):await Rl(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}}const Ir=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,lockBatches:o,lockTokenSymbol:r,lockTokenLogoURI:a,destinationInputHook:l,sourceAssetInputHook:d,lockDurationHook:u,lockChainId:c,durationOptions:f,votingPowerEstimate:p,escrowAddress:g,includeWalletAssets:x=!1,destinationTokenAddress:m,onLockSuccess:y,onLockExecute:C,sourceToDestinationConversionRate:k,estimatedOutputAmount:b,onAddFunds:A,buildSpicenetBatch:v,styles:w,dark:R=!1})=>{const{theme:E,dark:P,primaryColor:T,dk:F}=h.useSpiceBrand(w,R),S=E.typography.fontFamily,j=i.useContext(h.SpiceFlowProviderContext),I=j?.mode||"7702",N=!!j?.isWhitelistGateActive,D=I!=="7702",L=i.useMemo(()=>j?.supportedChainIds??[],[j?.supportedChainIds]),Q=i.useMemo(()=>{if(N)return[];const X=j?.allowedTokens;if(!X||X.length===0)return[];const be=new Set(X.map(Ke=>Ke.toLowerCase())),pt=[],wt=new Set;for(const Ke of L){const Rt=h.getChainConfig(Ke);for(const lt of Rt?.supportedTokens??[]){if(!be.has(lt.symbol.toLowerCase()))continue;const _t=`${Ke}:${lt.address.toLowerCase()}`;wt.has(_t)||(wt.add(_t),pt.push(M.getAddress(lt.address)))}}return pt},[j?.allowedTokens,L,N]),W=P?F.cardBg:w?.assetSelector?.backgroundColor||w?.secondaryBackground||"#e9e9e9",O=P?`1px solid ${F.cardBorder}`:"0.5px solid #A8A8A7",H=P?"12px":"6px",$=P?F.textPrimary:"#111827",U=P?F.textSecondary:"#6b7280",z=i.useMemo(()=>({...w,assetSelector:{...w?.assetSelector,backgroundColor:P?F.cardBg:w?.assetSelector?.backgroundColor,borderRadius:P?"12px":w?.assetSelector?.borderRadius},secondaryBackground:P?F.cardBg:w?.secondaryBackground}),[w,P]),le=i.useMemo(()=>P?{...E,colors:{...E.colors,secondary:F.cardBg,surfaceHover:F.hoverBg,border:F.cardBorder,borderHover:F.inputBorder}}:E,[P,E]),[q,_]=i.useState(null),[ce,we]=i.useState(0),de=u?.selectedDurationIdx??ce,fe=u?.setSelectedDurationIdx??we,[he,Z]=i.useState(!1),[re,J]=i.useState(null),[te,ue]=i.useState(null),[Ce,xe]=i.useState(!1),[V,oe]=i.useState(!1),[ee,Ae]=i.useState(null),[Te,$e]=i.useState(!1),rt=i.useRef(0),[jt,Ze]=i.useState(!1),[ye,Fe]=i.useState(null);Gt.useWalletClient(),Gt.useSwitchChain();const{chain:Me,address:Qe}=Gt.useAccount();Gt.useConfig();const _e=i.useRef(Me);i.useEffect(()=>{_e.current=Me},[Me]);const nt=h.useWallet(),{isReady:K,isAuthenticated:Ue,isConnected:Se,address:Ye,provider:Ve,actions:zt}=nt,{externalWallet:It,embeddedAddress:at,externalAddress:Ie,activeWallet:ft,activeAddress:At}=h.useProviderWallets(),{intentStatus:Re,startStatusPolling:Ot,clearStatus:je}=No({checkStepStatus:(X,be)=>h.relayerService.checkStepStatus(X,be),retryStep:async(X,be)=>{const[pt,wt]=X.split("/"),Ke=parseInt(wt||"0",10);await h.relayerService.executeStep(pt,Ke,be,{action:"execute"})},maxRetries:3}),{assets:Mt,refetch:Dt}=Qs({address:Ye,supportedChains:L,enabled:e&&Se&&!D&&!N,refetchInterval:3e4}),Oe=i.useMemo(()=>{if(N)return[];if(Q.length===0)return Mt;const X=new Set(Q.map(be=>be.toLowerCase()));return Mt.filter(be=>X.has(be.address.toLowerCase()))},[Mt,Q,N]),me=h.useEmbeddedWalletAddress(),Le=Ie||Qe,Ge=D?At??Le:me,Lt=i.useMemo(()=>{if(!x)return[];if(N)return m?[M.getAddress(m)]:[];const X=new Set,be=[],pt=wt=>{if(!wt)return;const Ke=wt.toLowerCase();X.has(Ke)||(X.add(Ke),be.push(M.getAddress(wt)))};m&&pt(m);for(const wt of Q)pt(wt);return be},[x,D,m,Q,N]),ke=i.useMemo(()=>Lt.map(X=>X.toLowerCase()).sort().join(","),[Lt]),Tt=i.useMemo(()=>JSON.stringify([...L||[]].sort()),[L]),[xt,dt]=i.useState([]),ze=i.useRef(0),Ht=i.useRef(async()=>{}),kt=i.useCallback(async()=>{if(!x||!Ge||Lt.length===0){ze.current++,dt([]);return}const X=++ze.current,be=M.getAddress(Ge),pt=D?L&&L.length>0?L:[c]:[c],wt=Lt.map(G=>{const Y=G.toLowerCase();if(m&&h.addressesEqual(G,m)){const pe=h.getChainConfig(c)?.supportedTokens?.find(ie=>h.addressesEqual(ie.address,Y));return{address:G,chainId:c,configToken:pe?{decimals:pe.decimals,symbol:pe.symbol,name:pe.name,logo:pe.logo}:void 0}}for(const pe of pt){const ie=h.getChainConfig(pe)?.supportedTokens?.find(Pe=>h.addressesEqual(Pe.address,Y));if(ie)return{address:G,chainId:pe,configToken:{decimals:ie.decimals,symbol:ie.symbol,name:ie.name,logo:ie.logo}}}return{address:G,chainId:c}}),Ke=new Map;for(const G of wt){const Y=Ke.get(G.chainId)||[];Y.push(G),Ke.set(G.chainId,Y)}const Rt=async(G,Y)=>{try{const pe=await $t.readContract(G,{address:Y.address,abi:h.P,functionName:"balanceOf",args:[be]});let ie,Pe,De,Je;if(Y.configToken)ie=Y.configToken.decimals,Pe=Y.configToken.symbol,De=Y.configToken.name,Je=Y.configToken.logo;else{const[Yt,Xt,Wt]=await Promise.all([$t.readContract(G,{address:Y.address,abi:h.P,functionName:"decimals",args:[]}).catch(()=>18),$t.readContract(G,{address:Y.address,abi:h.P,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),$t.readContract(G,{address:Y.address,abi:h.P,functionName:"name",args:[]}).catch(()=>"TOKEN")]);ie=Number(Yt),Pe=Xt,De=Wt}const ct=!!m&&h.addressesEqual(Y.address,m)&&Y.chainId===c;ct&&a&&(Je=a),ct&&r&&!Y.configToken&&(Pe==="TOKEN"&&(Pe=r),De==="TOKEN"&&(De=r));const Pt=parseFloat((Number(pe)/Math.pow(10,ie)).toFixed(6));return{address:Y.address,name:De,symbol:Pe,decimals:ie,balance:pe,balanceFormatted:Pt,balanceUsd:0,logoURI:Je,isNative:!1,chainId:Y.chainId}}catch{return null}},lt=await Promise.all(Array.from(Ke.entries()).map(async([G,Y])=>{let pe;try{pe=h.getClientForChain(G)}catch{return[]}const ie=[],Pe=[];for(const Je of Y){const ct=ie.length;ie.push({address:Je.address,abi:h.P,functionName:"balanceOf",args:[be]}),Je.configToken||ie.push({address:Je.address,abi:h.P,functionName:"decimals",args:[]},{address:Je.address,abi:h.P,functionName:"symbol",args:[]},{address:Je.address,abi:h.P,functionName:"name",args:[]}),Pe.push({start:ct,item:Je})}let De=null;try{De=await pe.multicall({contracts:ie})}catch{De=null}return De?Pe.map(({start:Je,item:ct})=>{const Pt=De[Je],Yt=Pt?.status==="success"?Pt.result:0n;let Xt,Wt,ss,bs;if(ct.configToken)Xt=ct.configToken.decimals,Wt=ct.configToken.symbol,ss=ct.configToken.name,bs=ct.configToken.logo;else{const Jt=De[Je+1],ns=De[Je+2],As=De[Je+3];Xt=Jt?.status==="success"?Number(Jt.result):18,Wt=ns?.status==="success"?ns.result:"TOKEN",ss=As?.status==="success"?As.result:Wt}const Ee=!!m&&h.addressesEqual(ct.address,m)&&ct.chainId===c;Ee&&a&&(bs=a),Ee&&r&&!ct.configToken&&(Wt==="TOKEN"&&(Wt=r),ss==="TOKEN"&&(ss=r));const Et=parseFloat((Number(Yt)/Math.pow(10,Xt)).toFixed(6));return{address:ct.address,name:ss,symbol:Wt,decimals:Xt,balance:Yt,balanceFormatted:Et,balanceUsd:0,logoURI:bs,isNative:!1,chainId:ct.chainId}}):(await Promise.all(Y.map(Je=>Rt(pe,Je)))).filter(Je=>Je!==null)}));if(X!==ze.current)return;const _t=lt.flat();dt(_t)},[x,D,Ge,ke,Tt,c,m,a,r]);i.useEffect(()=>{Ht.current=kt},[kt]),i.useEffect(()=>{if(!e||!x){dt([]);return}Ht.current();const X=setInterval(()=>{Ht.current()},15e3);return()=>clearInterval(X)},[x,e,Ge,ke,Tt,c,m]);const qt=i.useCallback(()=>{kt()},[kt]),Nt=i.useMemo(()=>xt.filter(X=>X.balance>0n),[xt]),Ft=i.useMemo(()=>{if(D)return Nt.map(be=>({...be,_source:"wallet"}));if(!x)return Oe;const X=[];for(const be of Nt)X.push({...be,_source:"wallet"});for(const be of Oe)X.push({...be,_source:"spice"});return X},[D,x,Nt,Oe]),yt=i.useMemo(()=>N?m?Ft.filter(X=>h.addressesEqual(X.address,m)&&X.chainId===c):[]:Ft,[Ft,N,m,c]),it=i.useRef(null),We=i.useRef(null);i.useEffect(()=>{We.current=q},[q]),i.useEffect(()=>{!N||!q?.asset||m&&h.addressesEqual(q.asset.address,m)&&q.asset.chainId===c||_(null)},[N,q?.asset,m,c]),i.useEffect(()=>{e||(_(null),J(null),ue(null),xe(!1),oe(!1),Ae(null),Z(!1),Ze(!1),Fe(null),$e(!1),je())},[e,je]),i.useEffect(()=>{l&&l.assetAmount!==(q?.amount||"")&&_(X=>X&&{...X,amount:l.assetAmount})},[l?.assetAmount]),i.useEffect(()=>{d&&d.assetAmount!==(q?.amount||"")&&_(X=>X&&{...X,amount:d.assetAmount})},[d?.assetAmount]),i.useEffect(()=>{if(!D&&Re?.overallStatus==="success"&&Re.intentId&&it.current!==Re.intentId&&Ye&&Re.steps.find(X=>X.transactionHash)?.transactionHash){it.current=Re.intentId;const X=We.current;if(!X?.asset||!X.amount||X.asset._source==="wallet"||M.parseUnits(X.amount,X.asset.decimals)===0n)return;Dt()}},[Re,Ye,c,Dt,D]);const et=parseFloat(q?.amount||"")||0,Ct=et>0&&et<us,Qt=i.useMemo(()=>q?.asset?q.asset._source==="wallet"?q.asset.balanceFormatted??0:Oe.find(X=>h.addressesEqual(X.address,q.asset.address)&&X.chainId===q.asset.chainId)?.balanceFormatted??0:0,[q?.asset,Oe]),Vt=et>0&&(ee?parseFloat(M.formatUnits(ee.grossAmount,ee.decimals))>Qt:et>Qt),vt=u?.selectedDuration??f[de]??f[0],ae=i.useMemo(()=>!q?.asset||!m?!1:h.addressesEqual(q.asset.address,m)&&q.asset.chainId===c,[q?.asset,m,c]),ot=i.useMemo(()=>et<=0?0:ae?et:!k||k<=0?0:et/k,[et,k,ae]),tt=i.useMemo(()=>ot<=0?null:ot.toLocaleString(void 0,{maximumFractionDigits:2}),[ot]),ht=p&&ot>0&&vt?p(ot,vt.months):void 0,Xe=i.useMemo(()=>et<=0?"$0.00":ae&&k?(et*k).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!k||k<=0?"$0.00":et.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[et,k,ae]),Be=i.useMemo(()=>{if(!tt)return null;const X=parseFloat(tt.replace(/,/g,""));return ae&&k?(X*k).toLocaleString(void 0,{maximumFractionDigits:2}):k?(X*k).toLocaleString(void 0,{maximumFractionDigits:2}):null},[tt,k,ae]),ut=i.useCallback(X=>{_(be=>({asset:X,amount:be?.asset?.address===X.address&&be?.asset?.chainId===X.chainId&&be.amount||""})),J(null),ue(null),oe(!1),Ae(null),d?.setSelectedAsset&&d.setSelectedAsset({symbol:X.symbol,address:X.address,decimals:X.decimals,chainId:X.chainId})},[d?.setSelectedAsset]),Zt=i.useCallback(X=>{_(be=>be&&{...be,amount:X}),J(null),ue(null),oe(!1),Ae(null),l&&l.setAssetAmount(X),d&&d.setAssetAmount(X)},[l,d]),se=i.useCallback(X=>{if(typeof o=="function"){if(!q?.asset||!q.amount)throw new Error("Select an asset and enter an amount");return o({asset:q.asset,amount:X?.amount??q.amount,amountWei:X?.amountWei??M.parseUnits(q.amount,q.asset.decimals),grossAmount:X?.grossAmount,grossAmountWei:X?.grossAmountWei,feeAdjusted:!!X})}return o},[o,q]),ne=i.useRef(null),ve=i.useMemo(()=>!q?.asset||et<=0?!1:D?!ae&&!C:!0,[q,et,D,ae,C]),He=i.useCallback(()=>Pl(ne.current),[]),st=i.useMemo(()=>!q?.asset||et<=0?null:`${q.asset.address.toLowerCase()}:${q.asset.chainId}:${q.amount??""}`,[q?.asset?.address,q?.asset?.chainId,q?.amount,et]);i.useEffect(()=>{if(!e||he)return;if(!q?.asset||et<=0){ue(null),xe(!1),oe(!1),Ae(null);return}if(!ve){ue(null),xe(!1),oe(!0),Ae(null);return}let X=!1;const be=async Ke=>{const Rt=++rt.current;Ke||(ue(null),oe(!1),xe(!0));try{const lt=await He();if(X||rt.current!==Rt)return;ue(null),oe(!0),Ae(lt)}catch(lt){if(X||rt.current!==Rt)return;Ke||(ue(h.sanitizeError(lt,"Unable to calculate fees for this lock.")),oe(!1))}finally{!X&&rt.current===Rt&&!Ke&&xe(!1)}},pt=window.setTimeout(()=>{be(!1)},250),wt=window.setInterval(()=>{be(!0)},3e4);return()=>{X=!0,clearTimeout(pt),window.clearInterval(wt)}},[e,he,st,ve,He]),i.useEffect(()=>{if(Re?.overallStatus==="success"){const X=Re.steps.find(be=>be.transactionHash);y?.(X?.transactionHash)}},[Re?.overallStatus,y]);const mt=x&&q?.asset?._source==="wallet"&&q?.asset?.chainId===c,bt=i.useCallback(()=>Ul(ne.current),[]),gt=!!q?.asset&&et>0&&!Ct&&!Vt&&!he&&(!ve||V&&!Ce&&!te),Ne=re||te,Bt=n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[n.jsx(On,{color:U}),n.jsxs("p",{style:{fontSize:"13px",color:U,margin:0,lineHeight:"1.5"},children:["Add ",r," by converting assets from your account"]})]});if(ne.current={selectedAsset:q,parsedAmount:et,selectedDuration:vt,isInsufficientBalance:Vt,isSemi7702:D,isSourceDestToken:ae,isDirectDeposit:mt,requiresRelayerFeeEstimate:ve,address:Ye,embeddedWalletAddress:me,providerEmbeddedAddress:at,externalWallet:It,externalWalletAddress:Le,activeSignerWallet:ft,activeSignerAddress:At,isConnected:Se,ready:K,authenticated:Ue,provider:Ve,actions:zt,lockChainId:c,escrowAddress:g,onLockExecute:C,onLockSuccess:y,buildSpicenetBatch:v,resolveLockBatches:se,startStatusPolling:Ot,refreshSpiceAssets:Dt,refreshWalletAssets:qt,ui:{setError:J,setIsExecuting:Z,setShowStatusPanel:$e}},!e)return null;const qe={backgroundColor:W,border:O,borderRadius:H,padding:"16px",marginBottom:"16px"};return n.jsx(cs,{isOpen:e,onClose:t,title:`Add ${r} to your account`,subtitle:Bt,styles:w,dark:P,footerLinkText:"Spicenet accounts \u2192",overlayContent:jt?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:[A&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Ln,{onClick:A,color:T,fontFamily:S})}),n.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:U,fontFamily:S},children:n.jsx(Hs,{assets:yt,selectedAsset:q??void 0,onAssetSelect:ut,onAmountChange:Zt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:le,styles:z})}),n.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:U,fontFamily:S},children:Xe})]}),n.jsxs("div",{style:qe,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:P?`1px solid ${F.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?n.jsx("img",{src:a,alt:r,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):n.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:P?F.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:$},children:r.slice(0,2)}),n.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:$,fontFamily:S},children:r})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:$,fontFamily:S,lineHeight:1.1},children:tt??"0.00"}),n.jsxs("div",{style:{fontSize:"12px",color:U,fontFamily:S,marginTop:"2px"},children:["~$",Be??"0.00"]})]})]}),n.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:P?`1px solid ${F.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:U,fontFamily:S},children:"Lock Duration"}),n.jsx(ds,{color:U})]}),n.jsx(wl,{options:f,selectedIndex:de,onSelect:fe,primaryColor:T,dark:P,textPrimary:$,textSecondary:U})]}),n.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[n.jsx(Sl,{durationMonths:vt?.months,fontFamily:S,dark:P,textPrimary:$,textSecondary:U}),p&&n.jsx(Al,{votes:ht,fontFamily:S,dark:P,textPrimary:$,textSecondary:U})]})]}),ve&&n.jsx(tn,{fontFamily:S,textPrimary:$,textSecondary:U,cardBg:W,cardBorder:O,resolvedDark:P,darkCardBorder:F.cardBorder,primaryColor:T,feePreview:ee,isLoading:Ce,errorText:te}),Ne&&n.jsx(Rs,{variant:"error",palette:F,fontFamily:S,style:{marginBottom:"12px"},children:Ne}),n.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:bt,disabled:!gt,loading:he,dark:P,styles:{...w,button:{...w?.button,backgroundColor:T}},children:he?ae?"LOCKING...":"CONVERTING...":Ct?`MINIMUM ${us}`:Ce&&ve?"CALCULATING FEES...":ae?`LOCK ${r}`:`CONVERT TO ${r}`}),n.jsx(El,{isOpen:jt,data:ye,isLocking:he,lockError:Ne,onContinue:bt,onClose:()=>Ze(!1),primaryColor:T,fontFamily:S,dark:P}),Re&&Te&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:P?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:H},children:n.jsx(Gn,{type:"lock",showStepBreakdown:!1,isOpen:!!Re&&Re.overallStatus!=="processing",isProcessing:he||Re?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{je(),$e(!1),bt()},onNewTx:()=>{je(),$e(!1),_(null),it.current=null,Dt(),qt()},onClose:()=>{je(),$e(!1)},onComplete:()=>{je(),$e(!1),_(null),it.current=null,Dt(),qt()},results:Re?.overallStatus==="success"||Re?.overallStatus==="failed"?Re.steps.map(X=>({asset:{symbol:q?.asset?.symbol||r,address:q?.asset?.address||""},txHash:X.transactionHash||"",success:X.status==="success",amount:q?.amount})):void 0,chainName:h.getChainName(c),explorerUrl:h.getExplorerUrl(c,"").replace(/\/tx\/.*$/,"")||void 0,theme:E,styles:w,dark:P})})]})})},zl="0xa9059cbb";function Ar(e,t,s){return B.isNativeToken(e)?{to:s,value:t,data:"0x"}:{to:e,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[s,t]})}}function Er(e,t,s){return{chainId:s,calls:[Ar(e,t,B.getEscrowContractAddress(s))]}}function jr(e,t,s){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===s}function Fr(e,t,s,o){return t!=="user-transfer"||!s||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(zl)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function gn(e,t,s,o){if(!t)return[e];const r=await t({...s,requestTimestampMs:o});return r?[r,e]:[e]}function Gs(e){return e.filter(t=>t.domain!=="spicenet")}function xn(e){const t=(e.tokenTransfers??[]).filter(s=>s.from==="escrow").map(s=>({token:B.normalizeNativeTokenAddress(s.token),recipient:s.to,amount:BigInt(s.amount)})).filter(s=>s.amount>0n);return t.length>0?t:void 0}function rs(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 ro(e,t){const{currentPaymentAmount:s,destinationToken:o,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:l,isNon7702:d,isPayMode:u,resolvedChainId:c,buildActionCalls:f,feeExecutionMode:p,buildSpicenetBatch:g,selectedAsset:x,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:C,requestTimestampMs:k}=e,b=M.parseUnits(s,o.decimals),A=t?.actionAmountOverride??b,v=r||a||(d?void 0:l);if(!v)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:v,chainId:c,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??b,netAmount:A,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},R=f(A,w),E={chainId:c,calls:R},P=!u&&!d?!0:x?.asset?._source==="spice",T=jr(x??null,d,c),F=P||d||T,S=(I,N)=>({token:I,from:d?"solver":"escrow",to:v,amount:N}),j=(I,N,D)=>T?[Er(I,N,c),...D]:D;if(b===0n)return[E];if(m&&y){const I=C??as(x.asset,c)??x.asset.address,N=t?.fundingAmountOverride??y.amountInMax,D=F?[S(I,N)]:[],L={to:I,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},Q={chainId:c,calls:[L,...y.calls,...R],tokenTransfers:[...D,...E.tokenTransfers??[]]};if(!F)return[Q];const W=await gn(Q,g,{userAddress:v,destinationChainId:c,deliveryToken:I,deliveryAmount:N,deliveryRecipient:v,deliveryTransfers:xn(Q),sourceAsset:x.asset},k);return j(I,N,W)}if(F){const I=C??as(x.asset,c)??o.address,N=t?.fundingAmountOverride??b,D={...E,tokenTransfers:[S(I,N),...E.tokenTransfers??[]]},L=await gn(D,g,{userAddress:v,destinationChainId:c,deliveryToken:I,deliveryAmount:N,deliveryRecipient:v,deliveryTransfers:xn(D),sourceAsset:x.asset},k);return j(I,N,L)}return[E]}async function ao(e,t){const{selectedAsset:s,embeddedWalletAddress:o,externalWalletAddress:r,recipient:a,resolvedChainId:l,destinationToken:d,buildActionCalls:u,feeExecutionMode:c,buildSpicenetBatch:f,isPayMode:p,isNon7702:g,needsSwap:x,resolvedSwap:m,quoteAmountOut:y,resolvedTokenIn:C,requestTimestampMs:k}=e,b=m?.amountOutMinimum??y;if(!s?.asset||!o)return[];const A=a??(g?r:o);if(!A)return[];const v=t?.fundingAmountOverride??t?.actionAmountOverride??M.parseUnits(s.amount,s.asset.decimals),w=t?.fundingAmountOverride??v,R=t?.sourceFundingAmountOverride??v,E=t?.deliveryAmountOverride??w,P=t?.withdrawalAmountOverride??E,T=t?.actionAmountOverride??v,F={userAddress:A,chainId:l,destinationToken:d.address,feeToken:c==="user-transfer"&&x&&C?C:d.address,grossAmount:w,netAmount:T,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},S=u(T,F),j=s.asset?._source==="wallet";if(!p&&g&&j&&s.asset.chainId===l){if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!m||b===null)throw new Error("Swap quote not available yet")}if(x&&m&&b){const U=u(t?.actionAmountOverride??b,{...F,netAmount:t?.actionAmountOverride??b}),{feeCall:z,remainingCalls:le}=Fr(U,c,x,F.feeToken);return[{chainId:l,calls:[...z?[z]:[],...m.calls,...le]}]}return[{chainId:l,calls:S}]}if(!p&&!g&&j&&s.asset.chainId!==l)throw new Error("Cross-chain wallet supplies require external wallet mode");const I=!p&&!g?s.asset?._source!=="wallet":s.asset?._source==="spice",N=g&&j,D=jr(s,g,l);if(!(I||N||D))return[{chainId:l,calls:S}];const L=D?Er(C??B.normalizeNativeTokenAddress(s.asset.address),R,l):N&&s.asset.chainId!==l?{chainId:s.asset.chainId,calls:[Ar(B.normalizeNativeTokenAddress(s.asset.address),R,B.getEscrowContractAddress(s.asset.chainId))]}:null,Q=(U,z)=>({token:U,from:N?"solver":"escrow",to:o,amount:z}),W=(U,z)=>N?[{token:U,from:"escrow",to:B.SPICE_SOLVER_ADDRESS,amount:z}]:[];if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!m||b===null)throw new Error("Swap quote not available yet")}if(x&&m&&b&&C){const U=u(t?.actionAmountOverride??b,{...F,netAmount:t?.actionAmountOverride??b}),{feeCall:z,remainingCalls:le}=Fr(U,c,x,F.feeToken),q={chainId:l,calls:[...z?[z]:[],...m.calls,...le],tokenTransfers:[...W(C,P),Q(C,E)]},_=await gn(q,f,{userAddress:o,destinationChainId:l,deliveryToken:C,deliveryAmount:E,withdrawalAmount:P,deliveryRecipient:o,deliveryTransfers:xn(q),sourceAsset:s.asset},k);return L?[L,..._]:_}const O=C??as(s.asset,l)??d.address,H={chainId:l,calls:S,tokenTransfers:[...W(O,P),Q(O,E)]},$=await gn(H,f,{userAddress:o,destinationChainId:l,deliveryToken:O,deliveryAmount:E,withdrawalAmount:P,deliveryRecipient:o,deliveryTransfers:xn(H),sourceAsset:s.asset},k);return L?[L,...$]:$}async function io(e,t,s,o,r){let a=e;for(let l=0;l<4;l++){const d=await t(a),u=await o(d,s,a,r),c=Ki(u);if(c===null||c>=e)return a;const f=a-c,p=e+f;if(p<=a)return a;a=p}return a}function Ol(e,t,s,o){if(e<=0n)return 0n;const r=e-t;if(r<=0n)return 0n;const a=o+s;return a<=0n?r:r*o/a}function Ll(e,t){const s=M.formatUnits(e,t);return s.includes(".")?s.replace(/\.?0+$/,"")||"0":s}async function Br(e){const{asset:t,isPayMode:s,isNon7702:o,needsSwap:r,isQuoting:a,embeddedWalletAddress:l,buildSupplyChainBatches:d,estimateGasless:u,executionTokenAddress:c,feeExecutionMode:f}=e;if(s||o||r||a||!l||t.balance<=0n)return null;const p=l,g=await d({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(g.length===0)return null;const x=g.some(A=>A.tokenTransfers?.length),m=await u(g,c,t.balance,x?{userOverride:p,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:p,feeExecutionMode:f}:{userOverride:p}),y=ys(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),C=y?rs(y.gasFee,y.decimals,t.decimals):0n,k=y?rs(y.spicenetFee,y.decimals,t.decimals):0n,b=Ol(t.balance,C,k,t.balance);return b>0n?Ll(b,t.decimals):null}async function lo(e){const{selectedAsset:t,isPayMode:s,parsedAmount:o,needsSwap:r,exactOutputSwap:a,isNon7702:l,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:c,feeExecutionMode:f,resolvedTokenIn:p,embeddedWalletAddress:g,providerEmbeddedAddress:x,resolvedChainId:m,isConnected:y,address:C,ready:k,authenticated:b,isDirect:A,resolvedSwap:v,isQuoting:w,executionTokenAddress:R,buildPayChainBatches:E,buildSupplyChainBatches:P,estimateGasless:T,estimateRequiredGrossFunding:F}=e;if(!t?.asset)return null;if(s){if(o<=0||r&&!a||d)return null;const W=M.parseUnits(u,c.decimals),O=p||as(t.asset,m)||t.asset.address||c.address,H={chainId:m,tokenAddress:O,symbol:B.getTokenByAddress(O,m)?.symbol??t.asset.symbol,decimals:B.getTokenByAddress(O,m)?.decimals??t.asset.decimals};if(l){const _=g||x;if(!_)return null;const ce=_,we=r?a?.amountInMax??0n:W;if(we===0n)return null;const de=await F(we,Z=>E({fundingAmountOverride:Z}).then(re=>os(Gs(re),ce)),O,{userOverride:_,useCustomTransfers:!0}),fe=os(Gs(await E({fundingAmountOverride:de})),ce),he=await T(fe,O,de,{userOverride:_,useCustomTransfers:!0,feeExecutionMode:f});return ys(he,H)}if(!y||!C||!k||!b)return null;const $=g||x||C,U=r?a?.amountInMax??0n:W;if(U===0n)return null;const z=await F(U,_=>E({fundingAmountOverride:_}).then(ce=>os(Gs(ce),$)),O,{useCustomTransfers:!0});let le=os(Gs(await E({fundingAmountOverride:z})),$);const q=await T(le,O,z,{useCustomTransfers:!0,feeExecutionMode:f});return ys(q,H)}if(o<=0||!g)return null;const S=g||x;if(!(!s&&!l&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!A&&!v&&!w||w)return null;const j=M.parseUnits(t.amount,t.asset.decimals),I=await P();if(I.length===0)return null;const N=l&&t.asset?._source==="wallet"&&t.asset.chainId===m,D={chainId:m,tokenAddress:R,symbol:B.getTokenByAddress(R,m)?.symbol??c.symbol,decimals:B.getTokenByAddress(R,m)?.decimals??c.decimals};if(N){const W=await h.relayerService.estimateBatchGas({user:S,outputToken:R,stepIndex:0,chainBatches:I}),O=cn(j,10n),H=O+W.gasFee;return{...D,grossAmount:j+H,netAmount:j,totalFee:H,gasFee:W.gasFee,spicenetFee:O,bridgeFee:0n,gasQuoteSource:W.gasQuoteSource}}const L=I.some(W=>W.tokenTransfers?.length),Q=await T(I,R,j,L?{userOverride:S,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:S,feeExecutionMode:f}:{userOverride:S});return ys(Q,D)}const Hl=10n;function Tr(e,t){const s=e.selectedAsset?.asset;if(!s||s?._source!=="wallet")return;const o=as(s,e.resolvedChainId);if(!o||!h.addressesEqual(o,e.executionTokenAddress))return;const r=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=rs(t,r?.decimals??e.destinationToken.decimals,s.decimals);if(a<=s.balance)return;const l=M.formatUnits(a,s.decimals),d=M.formatUnits(s.balance,s.decimals);throw new Error(`Insufficient ${s.symbol} for amount plus fees. Required ${l} ${s.symbol}; available ${d} ${s.symbol}.`)}function co(e){const t=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Ks(e,t,s){const o=ys(e,co(t));if(!o)return;const r=cn(s,Hl),a=o.bridgeFee??0n,l=r+o.gasFee+a;return{grossAmount:s+l,netAmount:s,combinedFeeAmount:l,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:r,gasFee:o.gasFee,bridgeFee:a}}}function Ws(e,t,s){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*s}function Mr(e,t,s){let o=0n,r=0n;const a=s.toLowerCase();for(const l of e)if(l.chainId===t){for(const d of l.calls??[])if(d.to.toLowerCase()===a)try{const u=M.decodeFunctionData({abi:M.erc20Abi,data:d.data});if(u.functionName!=="transfer")continue;const c=u.args[0].toLowerCase(),f=u.args[1];c===B.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?o+=f:c===B.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(r+=f)}catch{continue}}return{spicenetFee:o,gasFee:r}}function uo(e,t,s){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=Mr(e,t.resolvedChainId,o);return r.spicenetFee===0n&&s.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&s.feeBreakdown.gasFee>0n?!1:Ws(r.spicenetFee,s.feeBreakdown.spicenetFee,100n)&&Ws(r.gasFee,s.feeBreakdown.gasFee,100n)}function Rr(e,t){return e?Ws(e.grossAmount,t.grossAmount,100n)&&Ws(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Ws(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Ws(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function po(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const s=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!s:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const o=await yn(e);e.ui.setTxHash(o??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const o=new AbortController;e.refs.abortControllerRef.current=o,await Dr(e,o.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(o){const r=o instanceof Error?o:new Error(String(o));if(r.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const a=r.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(a),e.ui.setError(a),e.onError?.(r)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const s=M.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=s;let r=await e.gasless.buildSupplyChainBatches();const a=e.selectedAsset.asset?._source==="wallet",l=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!a&&!r.some(x=>B.isSpicenetChainId(x.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const d=r.some(x=>x.tokenTransfers?.length)?{userOverride:l,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:l,feeExecutionMode:e.feeExecutionMode}:{userOverride:l};let u=s;const c=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,f=e.feeExecutionMode==="user-transfer"&&!c?o:void 0;let p;for(let x=0;x<4;x+=1){const m=await e.gasless.estimateGasless(r,e.executionTokenAddress,u,d),y=ys(m,co(e));p=e.feeExecutionMode==="user-transfer"&&y?Ks(m,e,o):void 0;const C=p?.grossAmount??y?.grossAmount??u;if(C===u){u=C;break}u=C,r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:p})}e.feeExecutionMode==="user-transfer"&&(Tr(e,u),r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:p}));let g=p;await e.gasless.executeGasless(r,e.executionTokenAddress,u,e.gasless.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:x,chainBatches:m})=>{const y=Ks(x,e,o);if(!y)return null;const C=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;Mr(m,e.resolvedChainId,C);const k=Rr(g,y),b=uo(m,e,y);return k||b?null:(g=y,e.gasless.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:f,actionContextOverride:y}))}}:d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(s){const o=s instanceof Error?s:new Error(String(s));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const r=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function Dr(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,r=M.parseUnits(e.selectedAsset.amount,o.decimals),a=r,l=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let d=await e.gasless.buildSupplyChainBatches();const u={userOverride:s,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let c=r;const f=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!f?a:void 0;let g;if(l){const S=await h.relayerService.estimateBatchGas({user:s,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),j=cn(r,10n),I=j+S.gasFee;c=r+I,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:c,netAmount:a,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:j,gasFee:S.gasFee,bridgeFee:0n}})}else for(let S=0;S<4;S+=1){const j=await e.gasless.estimateGasless(d,e.executionTokenAddress,0n,u),I=e.feeExecutionMode==="user-transfer"?Ks(j,e,a):void 0,N=ys(j,co(e)),D=I?.grossAmount??(N?N.grossAmount>r?N.grossAmount:r:c);if(g=I,D===c){c=D;break}c=D;const L=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),Q=rs(c,L?.decimals??e.destinationToken.decimals,o.decimals);d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:Q,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I})}const x=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let m=l?c:rs(c,x?.decimals??e.destinationToken.decimals,o.decimals);Tr(e,c),d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:g});const y=o.chainId,C=s,k=await e.externalWallet.getEthereumProvider();let b=null;try{const S=await k.request({method:"eth_chainId"});b=parseInt(S,16)}catch{b=null}b!==y&&(e.ui.setStatusMsg("Switching source network..."),await h.ensureWalletOnChain(k,y));const A=h.getChainConfig(y),v=M.createWalletClient({account:e.externalWalletAddress,chain:A?.viemChain,transport:M.custom(k)}),w=B.normalizeNativeTokenAddress(o.address),R=o.isNative||B.isNativeToken(w),E=h.getClientForChain(y),P=async S=>{if(S<=0n)return;const j=R?await v.sendTransaction({to:C,value:S,chain:A?.viemChain}):await v.sendTransaction({to:w,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[C,S]}),chain:A?.viemChain});if((await E.waitForTransactionReceipt({hash:j,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed")};e.ui.setStatusMsg("Funding embedded wallet..."),await P(m);let T=m;if(e.feeExecutionMode==="user-transfer")for(let S=0;S<4;S+=1){const j=await e.gasless.estimateGasless(d,e.executionTokenAddress,0n,u),I=Ks(j,e,a);if(!I)break;const N=l?I.grossAmount:rs(I.grossAmount,x?.decimals??e.destinationToken.decimals,o.decimals);if(N>T&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await P(N-T),T=N),g=I,c=I.grossAmount,m=N,d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I}),uo(d,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let F=g;await e.gasless.executeGasless(d,e.executionTokenAddress,0n,e.gasless.onProgress,t,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:S,chainBatches:j})=>{const I=Ks(S,e,a);if(!I)return null;const N=Rr(F,I),D=uo(j,e,I);if(N||D)return null;if(I.grossAmount>c)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");F=I;const L=l?I.grossAmount:rs(I.grossAmount,x?.decimals??e.destinationToken.decimals,o.decimals);return e.gasless.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:L,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:p,actionContextOverride:I})}}:u)}async function yn(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const s=e.activeSignerWallet??e.externalWallet,o=e.activeSignerAddress??e.externalWalletAddress;if(!o||!s)throw new Error("Please connect your wallet to continue");const r=M.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),a={userAddress:o,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},l=e.buildActionCalls(r,a);if(l.length===0)throw new Error("No action calls configured");const d=await s.getEthereumProvider();let u=null;try{const x=await d.request({method:"eth_chainId"});u=parseInt(x,16)}catch{u=null}u!==e.resolvedChainId&&await h.ensureWalletOnChain(d,e.resolvedChainId);const c=h.getChainConfig(e.resolvedChainId),f=M.createWalletClient({account:o,chain:c?.viemChain,transport:M.custom(d)}),p=h.getClientForChain(e.resolvedChainId);let g;for(const x of l){const m=await f.sendTransaction({to:x.to,data:x.data,value:x.value,chain:c?.viemChain});if((await p.waitForTransactionReceipt({hash:m,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");g=m}return g}async function Nr(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,r=M.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const l=e.resolvedTokenIn||e.selectedAsset.asset.address,d={userOverride:t,useCustomTransfers:!0},u=await e.gasless.estimateRequiredGrossFunding(a,b=>e.gasless.buildPayChainBatches({fundingAmountOverride:b}),l,d),c=B.getEscrowContractAddress(o),f=await e.externalWallet.getEthereumProvider();let p=null;try{const b=await f.request({method:"eth_chainId"});p=parseInt(b,16)}catch{p=null}p!==o&&await h.ensureWalletOnChain(f,o);const g=h.getChainConfig(o),x=M.createWalletClient({account:e.externalWalletAddress,chain:g?.viemChain,transport:M.custom(f)}),m=B.normalizeNativeTokenAddress(s.address),y=s.isNative||B.isNativeToken(m)?await x.sendTransaction({to:c,value:u,chain:g?.viemChain}):await x.sendTransaction({to:m,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[c,u]}),chain:g?.viemChain});if((await h.getClientForChain(o).waitForTransactionReceipt({hash:y,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const C=await e.gasless.buildPayChainBatches({fundingAmountOverride:u}),k=C.some(b=>b.tokenTransfers?.length);return await e.gasless.executeGasless(C,l,u,b=>{b.txHash&&(e.ui.setPaymentResult(A=>({...A??{status:"processing"},txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,k?d:{userOverride:t})}async function fo(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const s=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!s:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let o;if(e.isSourceDestToken||e.parsedAmount===0)o=await yn(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,a=M.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),l=e.selectedIsEquivalent?a:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(l===0n)throw new Error("Quote not available yet");const d=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!d)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const u=e.resolvedTokenIn||r.address,c=await e.gasless.estimateRequiredGrossFunding(l,g=>e.gasless.buildPayChainBatches({fundingAmountOverride:g}),u,{userOverride:d,useCustomTransfers:!0}),f=await e.gasless.buildPayChainBatches({fundingAmountOverride:c}),p=await e.onPayExecute({asset:r,amount:e.currentPaymentAmount,amountWei:a,destinationToken:e.destinationToken,chainBatches:f,requiredNetFunding:l,grossFundingAmount:c,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:u,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});p&&(e.ui.setTxHash(p),e.ui.setPaymentResult(g=>({...g??{status:"processing"},txHash:p}))),o=p||void 0}else o=await Nr(e);e.ui.setPaymentResult(r=>({status:"success",txHash:r?.txHash||o||""}))}catch(o){const r=h.sanitizeError(o,"Payment failed. Please try again.");e.ui.setError(r),e.ui.setPaymentResult({status:"failed",error:r}),e.onError?.(o instanceof Error?o:new Error(r))}finally{e.ui.setIsExecuting(!1)}return}if(e.isSourceDestToken){if(!(e.activeSignerAddress??e.externalWalletAddress??e.address)){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const s=await yn(e);e.ui.setPaymentResult(o=>({status:"success",txHash:o?.txHash||s||""}))}catch(s){const o=h.sanitizeError(s,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(s instanceof Error?s:new Error(o))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const s=M.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),o={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const C=await e.gasless.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),k=await e.gasless.executeGasless(C,e.destinationToken.address,0n,b=>{b.txHash&&(e.ui.setPaymentResult(A=>({...A,txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,o);e.ui.setPaymentResult(b=>({status:"success",txHash:b?.txHash||k}));return}const r=e.selectedAsset?.asset;if(!r)throw new Error("Select a payment source");const a=e.resolvedTokenIn||r.address||e.destinationToken.address,l=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:s,d=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,u=(C,k,b)=>{const A=Gs(C),v=E=>(E.tokenTransfers??[]).some(P=>P.from==="escrow"),w=A.filter(E=>!v(E)),R=A.filter(v);return[...w,...os(R,d,k,b)]},c=await e.gasless.estimateRequiredGrossFunding(l,C=>e.gasless.buildPayChainBatches({fundingAmountOverride:C}).then(k=>u(k)),a,o);let f=c,p=u(await e.gasless.buildPayChainBatches({fundingAmountOverride:c}));const g=await e.gasless.estimateGasless(p,a,c,o),x=ys(g,{chainId:e.resolvedChainId,tokenAddress:a,symbol:B.getTokenByAddress(a,e.resolvedChainId)?.symbol??r.symbol,decimals:B.getTokenByAddress(a,e.resolvedChainId)?.decimals??r.decimals})?.grossAmount??c;x!==c&&(f=x),p=u(await e.gasless.buildPayChainBatches({fundingAmountOverride:f}),g,{payoutAlreadyGross:!0});const m=p.some(C=>C.tokenTransfers?.length),y=await e.gasless.executeGasless(p,a,m?f:0n,C=>{C.txHash&&(e.ui.setPaymentResult(k=>({...k,txHash:C.txHash})),e.ui.setTxHash(C.txHash))},void 0,o);e.ui.setPaymentResult(C=>({status:"success",txHash:C?.txHash||y}))}catch(s){const o=h.sanitizeError(s,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(s instanceof Error?s:new Error(o))}finally{e.ui.setIsExecuting(!1)}}const ql=({variant:e,destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,isQuoting:g,quoteError:x,estimatedOutput:m,paymentAmount:y,needsSwap:C,exactOutputSwap:k,adjustable:b=!1,maxAmount:A,onAmountChange:v})=>e==="supply"?n.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${c}`,borderRadius:p?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[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:a,fontSize:"17px",fontWeight:500,color:p?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),n.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,fontFamily:a,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 ${c}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[n.jsx(Wr,{symbol:t,logoURI:s,primaryColor:r,size:24}),n.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:p?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),n.jsx("div",{style:{textAlign:"right",minWidth:0},children:g?n.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:a},children:"Quoting..."}):x?n.jsx("span",{style:{fontSize:"13px",color:p?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):m?n.jsx(ws,{value:m,title:m,fontFamily:a,color:l,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):n.jsx("span",{style:{fontSize:"20px",color:d,fontFamily:a},children:"\u2014"})})]}):n.jsx(Ql,{destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:k,isQuoting:g,adjustable:b,maxAmount:A,onAmountChange:v}),Pr=i.memo(ql),Wr=({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)}),Ql=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:s,primaryColor:o,fontFamily:r,textPrimary:a,textSecondary:l,cardBg:d,cardBorder:u,dk:c,dark:f,paymentAmount:p,needsSwap:g,exactOutputSwap:x,isQuoting:m,adjustable:y,maxAmount:C,onAmountChange:k})=>{const b='"IBM Plex Mono", monospace',A=parseFloat(p||"0"),v=C?parseFloat(C):0,[w,R]=i.useState(p||""),E=i.useRef(null),[P,T]=i.useState(null),[F,S]=i.useState(null);i.useEffect(()=>{y||R(p||"")},[p,y]);const j=D=>{let L=D;L.startsWith(".")&&(L="0"+L);const Q=Ts(L);let W=Q;C&&parseFloat(Q)>parseFloat(C)&&(W=C),R(W),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>k?.(W),300)},I=D=>{if(!v)return;if(D===100){R(C||v.toString()),E.current&&clearTimeout(E.current),k?.(C||v.toString());return}const L=10**s,Q=Math.floor(v*D/100*L)/L,W=Ms(Q,s);R(W),E.current&&clearTimeout(E.current),k?.(W)},N=v>0?parseFloat(w||"0")/v*100:0;return i.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]),n.jsxs("div",{style:{backgroundColor:d,border:`1px solid ${u}`,borderRadius:f?"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(Wr,{symbol:e,logoURI:t,primaryColor:o,size:32}),n.jsxs("div",{children:[n.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:a,fontFamily:r},children:"Payment"}),n.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:r,marginTop:"2px"},children:e})]})]}),n.jsxs("div",{style:{textAlign:"right"},children:[y?n.jsx(ws,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:D=>j(D.target.value),placeholder:"0.0",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):n.jsx(ws,{element:"div",value:A>0?p:"0.00",title:A>0?p:"0.00",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),n.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:b,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((D,L)=>{const Q=Math.abs(N-D)<1,W=L===4,O=D/100,H=P===D,$=F===D;return n.jsx("button",{onClick:()=>I(D),onMouseEnter:()=>T(D),onMouseLeave:()=>{T(null),S(null)},onMouseDown:()=>S(D),onMouseUp:()=>S(null),title:`${D}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:Q?1:H?.8:.5,transform:$?"scale(0.85)":H?"scale(1.15)":"scale(1)",transition:es.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:W?o:"none",stroke:W?o:f?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!W&&O>0&&n.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${O>.5?1:0} 1 ${7+6.84375*Math.sin(O*2*Math.PI)} ${7-6.84375*Math.cos(O*2*Math.PI)} Z`,fill:f?c?.textSecondary||"#9ca3af":"#3C3E42"})]})},D)})})]})]}),g&&x&&!m&&n.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:f?`1px solid ${c?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:n.jsxs("span",{style:{fontSize:"11px",color:l,fontFamily:r,opacity:.7},children:["via ",x.venue]})})]})};function Ur(e,t,s){const o=h.addressesEqual(e.address,t),r=e.chainId===s,a=e._source==="wallet";return a&&o&&r?0:a&&r?1:!a&&o?2:!a&&r?3:4}function zr(e,t){return!t||t.length===0||t.some(s=>h.addressesEqual(s,e.address))?!0:Object.keys(e.chainTokens??{}).some(s=>{const o=Ns(s);return o?t.some(r=>h.addressesEqual(r,o.address)):!1})}function ho(e){const{destinationToken:t,supportedSourceAssets:s,sourceChains:o,enabled:r}=e,a=(i.useContext(h.SpiceFlowProviderContext)?.mode||"7702")!=="7702",l=h.useEmbeddedWalletAddress(),{externalAddress:d,embeddedAddress:u,activeAddress:c}=h.useProviderWallets(),f=l||u,{assets:p,refetch:g}=Qs({address:f,supportedChains:o,enabled:r&&!a&&!!f,refetchInterval:3e4}),x=i.useMemo(()=>a?[]:p.filter(P=>zr(P,s)),[p,s,a]),m=a?c??d:l,y=i.useMemo(()=>{const P=new Set,T=[],F=S=>{if(!S)return;const j=S.toLowerCase();P.has(j)||(P.add(j),T.push(M.getAddress(S)))};if(F(t.address),s)for(const S of s)F(S);return T},[a,t.address,s]),C=i.useMemo(()=>y.map(P=>P.toLowerCase()).sort().join(","),[y]),k=i.useMemo(()=>JSON.stringify([...o||[]].sort()),[o]),[b,A]=i.useState([]),v=i.useRef(0),w=i.useRef(async()=>{}),R=i.useCallback(async()=>{if(!r||!m||y.length===0){v.current++,A([]);return}const P=++v.current,T=M.getAddress(m),F=a?o&&o.length>0?o:[t.chainId]:[t.chainId],S=[];for(const D of y){const L=D.toLowerCase();if(L===B.ZERO_ADDRESS)continue;if(L===t.address.toLowerCase()){const W=h.getChainConfig(t.chainId)?.supportedTokens?.find(O=>h.addressesEqual(O.address,L));S.push({address:D,chainId:t.chainId,configToken:W?{decimals:W.decimals,symbol:W.symbol,name:W.name,logo:W.logo}:void 0});continue}let Q=!1;for(const W of F){const O=h.getChainConfig(W)?.supportedTokens?.find(H=>h.addressesEqual(H.address,L));if(O){S.push({address:D,chainId:W,configToken:{decimals:O.decimals,symbol:O.symbol,name:O.name,logo:O.logo}}),Q=!0;break}}Q||S.push({address:D,chainId:t.chainId})}const j=new Map;for(const D of S){const L=j.get(D.chainId)||[];L.push(D),j.set(D.chainId,L)}const I=async(D,L)=>{try{const Q=await $t.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"balanceOf",args:[T]});let W,O,H,$;if(L.configToken)W=L.configToken.decimals,O=L.configToken.symbol,H=L.configToken.name,$=L.configToken.logo;else{const[le,q,_]=await Promise.all([$t.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"decimals"}).catch(()=>18),$t.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),$t.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);W=Number(le),O=q,H=_}const U=h.addressesEqual(L.address,t.address)&&L.chainId===t.chainId;U&&t.logoURI&&($=t.logoURI),U&&!L.configToken&&O==="TOKEN"&&(O=t.symbol,H=t.symbol);const z=parseFloat((Number(Q)/Math.pow(10,W)).toFixed(6));return{address:L.address,name:H,symbol:O,decimals:W,balance:Q,balanceFormatted:z,balanceUsd:0,logoURI:$,isNative:!1,chainId:L.chainId}}catch{return null}},N=await Promise.all(Array.from(j.entries()).map(async([D,L])=>{let Q;try{Q=h.getClientForChain(D)}catch{return[]}const W=[],O=[];for(const $ of L){const U=W.length;W.push({address:$.address,abi:M.erc20Abi,functionName:"balanceOf",args:[T]}),$.configToken||W.push({address:$.address,abi:M.erc20Abi,functionName:"decimals"},{address:$.address,abi:M.erc20Abi,functionName:"symbol"},{address:$.address,abi:M.erc20Abi,functionName:"name"}),O.push({start:U,item:$})}let H=null;try{H=await Q.multicall({contracts:W})}catch{H=null}return H?O.map(({start:$,item:U})=>{const z=H[$],le=z?.status==="success"?z.result:0n;let q,_,ce,we;if(U.configToken)q=U.configToken.decimals,_=U.configToken.symbol,ce=U.configToken.name,we=U.configToken.logo;else{const he=H[$+1],Z=H[$+2],re=H[$+3];q=he?.status==="success"?Number(he.result):18,_=Z?.status==="success"?Z.result:"TOKEN",ce=re?.status==="success"?re.result:_}const de=h.addressesEqual(U.address,t.address)&&U.chainId===t.chainId;de&&t.logoURI&&(we=t.logoURI),de&&!U.configToken&&_==="TOKEN"&&(_=t.symbol,ce=t.symbol);const fe=parseFloat((Number(le)/Math.pow(10,q)).toFixed(6));return{address:U.address,name:ce,symbol:_,decimals:q,balance:le,balanceFormatted:fe,balanceUsd:0,logoURI:we,isNative:!1,chainId:U.chainId}}):(await Promise.all(L.map($=>I(Q,$)))).filter($=>$!==null)}));P===v.current&&A(N.flat())},[r,a,m,C,k,t.address,t.chainId,t.symbol,t.logoURI]);i.useEffect(()=>{w.current=R},[R]),i.useEffect(()=>{if(!r){A([]);return}w.current();const P=setInterval(()=>{w.current()},15e3);return()=>clearInterval(P)},[r,a,m,C,k,t.address,t.chainId]);const E=i.useCallback(()=>{R()},[R]);return{displayAssets:i.useMemo(()=>{const P=[],T=b.filter(S=>S.balance>0n);for(const S of T)P.push({...S,_source:"wallet"});for(const S of x)P.push({...S,_source:"spice"});const F=t.address.toLowerCase();return P.sort((S,j)=>Ur(S,F,t.chainId)-Ur(j,F,t.chainId)),P},[b,x,t.address,t.chainId]),filteredSpiceAssets:x,walletAssets:b,embeddedWalletAddress:f,externalAddress:d,isNon7702:a,refreshSpiceAssets:g,refreshWalletAssets:E}}async function Or(e){const{tokenIn:t,tokenOut:s,amountIn:o,fee:r,chainId:a,config:l}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const d=(await h.getClientForChain(a).simulateContract({address:l.quoterV2,abi:B.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:s,amountIn:o,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function Lr(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(r=>Or({...e,fee:r})));let o=null;for(let r=0;r<s.length;r++){const a=s[r];a.status==="fulfilled"&&(!o||a.value.amountOut>o.amountOut)&&(o={...a.value,fee:t[r]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const Vl=[{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 Gl(e){const{tokenIn:t,tokenOut:s,amountOut:o,fee:r,chainId:a,config:l}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const d=(await h.getClientForChain(a).simulateContract({address:l.quoterV2,abi:Vl,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:s,amount:o,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function Kl(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(r=>Gl({...e,fee:r})));let o=null;for(let r=0;r<s.length;r++){const a=s[r];a.status==="fulfilled"&&(!o||a.value.amountIn<o.amountIn)&&(o={...a.value,fee:t[r]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function Hr(e){return e.type==="swap"}const mo=.02,Zl=[1,8453,42161,10,137,43114,56],Yl="https://api.1inch.dev/swap/v6.0";function qr(e,t){return B.applySlippage(e,t)}function Qr(e){const t=e?.baseUrl??Yl;return{name:"1inch",chainIds:e?.chainIds??Zl,resolve:async(s,o,r)=>{const a=s.maxSlippage??mo,l=a*100,d=B.isNativeToken(s.tokenIn)?B.NATIVE_TOKEN_ADDRESS:s.tokenIn,u=B.isNativeToken(s.tokenOut)?B.NATIVE_TOKEN_ADDRESS:s.tokenOut,c=B.isNativeToken(s.tokenIn);try{const f=new URL(`${t}/${o}/swap`);f.searchParams.set("src",d),f.searchParams.set("dst",u),f.searchParams.set("amount",s.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",l.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const g=await fetch(f.toString(),{headers:p});if(!g.ok)throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${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=qr(m,a),C=[];return x.tx.to&&!c&&C.push({to:s.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[x.tx.to,s.amountIn]})}),C.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:C}}catch(f){if(f instanceof h.SpiceflowError)throw f;const p=f instanceof Error?f.message:String(f);throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}: ${p}`,{venue:"1inch",chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:p})}}}}const Vr=[4114,5115],go={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Gr={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Kr(e){return{name:"satsuma",chainIds:e.chainIds??Vr,resolve:async(t,s,o)=>{const r=t.maxSlippage??mo,a=B.isNativeToken(t.tokenIn);let l;try{l=await Lr({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=qr(l.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:M.encodeFunctionData({abi:B.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:l.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:l.amountOut,amountOutMinimum:d,calls:u}}}}function Zr(e){return{name:"satsuma",chainIds:e.chainIds??Vr,resolve:async(t,s,o)=>{const r=t.maxSlippage??mo,a=B.isNativeToken(t.tokenIn);let l;try{l=await Kl({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(r*1e4)),u=l.amountIn+l.amountIn*d/10000n,c=[];return c.push({to:e.swapRouter,value:a?u:0n,data:M.encodeFunctionData({abi:Xl,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:l.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:l.amountIn,amountInMax:u,amountOut:t.amountOut,calls:c}}}}const Xl=[{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 Yr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Kr(e.satsuma)),t.push(Qr(e?.oneInch));function s(r){return t.find(a=>a.chainIds.includes(r))}async function o(r,a,l){const d=[],u=[];for(const c of r){if(!Hr(c)){d.push(c);continue}const f=s(a);if(!f)throw new h.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${c.tokenIn} \u2192 ${c.tokenOut}.`,{chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});const p=await f.resolve(c,a,l);if(!p)throw new h.SpiceflowError("NO_LIQUIDITY",`${f.name} returned no quote for ${c.tokenIn} \u2192 ${c.tokenOut} on chain ${a}.`,{venue:f.name,chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});d.push(...p.calls),u.push(p)}return{calls:d,resolvedSwaps:u}}return{resolveSwapIntents:o,getVenueForChain:s,venues:t}}function Xr(e){const t=e?.customVenues??[];async function s(o,r,a){const l=t.filter(u=>u.chainIds.includes(r));if(l.length===0)throw new h.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const d=(await Promise.allSettled(l.map(u=>u.resolve(o,r,a)))).filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u!==null);if(d.length===0)throw new h.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return d.sort((u,c)=>u.amountIn<c.amountIn?-1:u.amountIn>c.amountIn?1:0),d[0]}return{getQuote:s,venues:t}}const Jr=Yr({satsuma:go});async function Jl(e){const t=Jr.getVenueForChain(e.chainId);if(!t)throw new Error(`No swap venue configured for chain ${e.chainId}.`);const s=await t.resolve({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn},e.chainId,e.recipient);if(!s)throw new Error("No liquidity for this pair.");return s}function xo(e){const{direction:t,selectedAsset:s,destinationToken:o,chainId:r,recipient:a,paymentAmount:l,resolveExactOutputSwap:d}=e,[u,c]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(null),[m,y]=i.useState(null),[C,k]=i.useState(null),[b,A]=i.useState(null),[v,w]=i.useState(null),[R,E]=i.useState(null),[P,T]=i.useState(null),F=i.useRef(null),S=i.useRef(null),j=i.useRef(0),I=i.useRef(new Map),N=i.useMemo(()=>Jr,[]),D=i.useMemo(()=>Xr({customVenues:[...d?[{name:"consumer-exact-output",chainIds:[r],resolve:d}]:[],Zr(go),Zr(Gr)]}),[d,r]),L=i.useMemo(()=>{if(!s?.asset)return null;const _=as(s.asset,r);if(_)return _;const ce=fs(s.asset.address,r,s.asset.chainId);return ce?ce.address:null},[s?.asset,r]),Q=i.useMemo(()=>s?.asset?rn(s.asset,r):[],[s?.asset,r]),W=i.useMemo(()=>Q.map(_=>_.toLowerCase()).join(","),[Q]);i.useEffect(()=>{let _=!1;if(S.current&&(clearTimeout(S.current),S.current=null),!s?.asset||Q.length<=1){T(null);return}return S.current=setTimeout(async()=>{const ce=t==="input"?s.amount:l||"0";let we=0n;try{we=t==="input"?M.parseUnits(ce,s.asset.decimals):0n}catch{we=0n}try{const de=await er(s.asset,r,{requiredAmount:we});_||T(de)}catch{_||T(null)}},400),()=>{_=!0,S.current&&(clearTimeout(S.current),S.current=null)}},[s?.asset,s?.amount,r,Q.length,W,t,l]);const O=i.useMemo(()=>P??L,[P,L]),H=i.useMemo(()=>!s?.asset||!O?[]:[O,...Q.filter(_=>_.toLowerCase()!==O.toLowerCase())],[s?.asset,O,Q]),$=i.useMemo(()=>!s?.asset||!qs(s.asset.address,s.asset.chainId,o.address,o.chainId)||!O?!1:h.addressesEqual(O,o.address),[s,o.address,o.chainId,O]),U=O?h.addressesEqual(O,o.address):!1,z=t==="output"&&parseFloat(l||"0")===0,le=!!s?.asset&&!$&&!U&&!z,q=le?R??O:O;return i.useEffect(()=>{F.current&&clearTimeout(F.current);const _=t==="input"?s?.amount:l,ce=parseFloat(_||"0");if(!le||!Number.isFinite(ce)||ce<=0||!s?.asset||!a||H.length===0){j.current++,x(null),y(null),k(null),A(null),w(null),E(null),p(null),c(!1);return}const we=s.asset.decimals;let de;try{de=t==="input"?M.parseUnits(s.amount,we):M.parseUnits(l||"0",o.decimals)}catch{j.current++,p("Invalid amount"),c(!1);return}const fe=++j.current,he=()=>fe!==j.current;c(!0);const Z=t==="output"?150:400;return F.current=setTimeout(async()=>{try{if(t==="input"){const re=N.getVenueForChain(r);if(!re)throw new Error("No swap venue for this chain");let J=null,te=null;for(const Ce of H){const xe=`${t}:${r}:${Ce.toLowerCase()}:${o.address.toLowerCase()}:${de.toString()}`,V=I.current.get(xe);if(V&&V.expiresAt>Date.now()&&V.resolvedSwap){J=V.resolvedSwap,te=Ce;break}const oe=await re.resolve({type:"swap",tokenIn:Ce,tokenOut:o.address,amountIn:de},r,a);if(he())return;if(oe){I.current.set(xe,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:oe}),J=oe,te=Ce;break}}if(!J||!te)throw new Error("No liquidity for this pair");E(te),w(J.amountOut),k(J),A(null);const ue=parseFloat(M.formatUnits(J.amountOut,o.decimals));x(ue<.01?ue.toPrecision(4):ue.toLocaleString(void 0,{maximumFractionDigits:6})),y(null),p(null)}else{let re=null,J=null;for(const te of H){const ue=`${t}:${r}:${te.toLowerCase()}:${o.address.toLowerCase()}:${de.toString()}`,Ce=I.current.get(ue);if(Ce&&Ce.expiresAt>Date.now()&&Ce.exactOutputSwap){re=Ce.exactOutputSwap,J=te;break}try{const xe=await D.getQuote({tokenIn:te,tokenOut:o.address,amountOut:de},r,a);if(he())return;I.current.set(ue,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:xe}),re=xe,J=te;break}catch{if(he())return}}if(!re||!J)throw new Error("No liquidity for this pair");E(J),A(re),k(null),w(null),y(parseFloat(M.formatUnits(re.amountIn,we)).toFixed(6)),x(null),p(null)}}catch(re){if(he())return;const J=re instanceof Error?re.message:"Failed to get quote";p(J),x(null),y(null),k(null),A(null),w(null),E(null)}finally{he()||c(!1)}},Z),()=>{F.current&&clearTimeout(F.current)}},[t,le,s?.amount,s?.asset?.address,s?.asset?.decimals,l,H,r,o.address,o.decimals,a,N,D]),{isQuoting:u,quoteError:f,estimatedOutput:g,estimatedInput:m,resolvedSwap:C,exactOutputSwap:b,quoteAmountOut:v,resolvedTokenIn:q,isDirect:U,needsSwap:le,selectedIsEquivalent:$}}const $r={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},_r=["signing-delegation","signing-intent","submitting","executing"],$l=()=>{},ea=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,destinationToken:o,sourceChains:r,supportedSourceAssets:a,buildActionCalls:l,feeExecutionMode:d="user-transfer",buildSpicenetBatch:u,onPayExecute:c,resolveExactOutputSwap:f,actionLabel:p,amountDirection:g="input",swapDescription:x,directDescription:m,paymentAmount:y,amountInputMode:C="fixed",minPaymentAmount:k,maxPaymentAmount:b,onAmountChange:A,styles:v,dark:w,title:R,subtitle:E,onAddFunds:P,onSuccess:T,onError:F})=>{const S=g==="output",{theme:j,dark:I,primaryColor:N,dk:D,palette:L,fontFamily:Q,monoFont:W,inputDark:O,cardBg:H,cardBorder:$,textPrimary:U,textSecondary:z,subtitleText:le}=h.useSpiceBrand(v,w),q=i.useMemo(()=>O?{...j,colors:{...j.colors,secondary:D.cardBg,surfaceHover:D.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:j,[O,j,D.cardBg,D.hoverBg]),_=o.chainId,ce=i.useContext(h.SpiceFlowProviderContext),we=ce?.mode||"7702",de=we!=="7702",fe=!!ce?.isWhitelistGateActive,he=!!ce?.isWhitelistConfigured&&ce?.isUserWhitelisted!==!0,Z=i.useMemo(()=>r??ce?.supportedChainIds??[],[r,ce?.supportedChainIds]),re=i.useMemo(()=>{if(fe)return[];if(a)return a;const ge=ce?.allowedTokens;if(!ge||ge.length===0)return;const St=new Set(ge.map(ms=>ms.toLowerCase())),js=[],hs=new Set;for(const ms of Z){const vn=h.getChainConfig(ms);for(const Sn of vn?.supportedTokens??[]){if(!St.has(Sn.symbol.toLowerCase()))continue;const wo=Sn.address.toLowerCase();hs.has(wo)||(hs.add(wo),js.push(Sn.address))}}return js},[a,ce?.allowedTokens,Z,fe]),J=h.useWallet(),{address:te,isConnected:ue,isReady:Ce,isAuthenticated:xe,provider:V}=J,{executeGasless:oe,estimateGasless:ee}=Ps(),{externalWallet:Ae,externalAddress:Te,embeddedAddress:$e,activeWallet:rt,activeAddress:jt}=h.useProviderWallets(),Ze=h.useEmbeddedWalletAddress()||$e,{displayAssets:ye,filteredSpiceAssets:Fe,embeddedWalletAddress:Me,refreshSpiceAssets:Qe,refreshWalletAssets:_e}=ho({destinationToken:o,supportedSourceAssets:re,sourceChains:Z,enabled:e&&(de?!!Te:!!Ze)}),nt=fe||S||de?ye:Fe;i.useEffect(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:we,walletAddressUsed:Me,count:nt.length,assets:nt.map(ge=>({symbol:ge.symbol,address:ge.address,chainId:ge.chainId,balanceFormatted:ge.balanceFormatted,source:ge?._source}))})},[e,we,Me,nt]);const[K,Ue]=i.useState(null),[Se,Ye]=i.useState(y||""),[Ve,zt]=i.useState(!1),[It,at]=i.useState(null),[Ie,ft]=i.useState("idle"),[At,Re]=i.useState(""),[Ot,je]=i.useState(null),[Mt,Dt]=i.useState(!1),[Oe,me]=i.useState(null),[Le,Ge]=i.useState(null),[Lt,ke]=i.useState(!1),[Tt,xt]=i.useState(!1),[dt,ze]=i.useState(null),Ht=i.useRef(K),kt=i.useRef(!1),qt=i.useRef(null),Nt=i.useRef(null),Ft=i.useRef(0),yt=i.useRef(null),it=i.useRef(null);i.useEffect(()=>{Ht.current=K},[K]);const We=C==="adjustable"?Se:y||"0",et=Me||$e||te,{isQuoting:Ct,quoteError:Qt,estimatedOutput:Vt,resolvedSwap:vt,exactOutputSwap:ae,quoteAmountOut:ot,resolvedTokenIn:tt,isDirect:ht,needsSwap:Xe,selectedIsEquivalent:Be}=xo({direction:g,selectedAsset:K,destinationToken:o,chainId:_,recipient:et,paymentAmount:We,resolveExactOutputSwap:f}),ut=S?parseFloat(We||"0"):parseFloat(K?.amount||"")||0,Zt=ut>0&&ut<us,se=K?.asset?._source==="wallet",ne=!!K?.asset&&se&&K.asset.chainId!==_,ve=i.useMemo(()=>K?.asset?Fe.find(ge=>h.addressesEqual(ge.address,K.asset.address))?.balanceFormatted??0:0,[K,Fe]),He=se?K?.asset.balanceFormatted??0:ve,st=i.useMemo(()=>{if(!K?.asset)return!1;if(S)return Le?rs(Le.grossAmount,Le.decimals,K.asset.decimals)>K.asset.balance:Be||ht?ut>K.asset.balanceFormatted:ae?parseFloat(M.formatUnits(ae.amountInMax,K.asset.decimals))>K.asset.balanceFormatted:!1;if(Le){const ge=rs(Le.grossAmount,Le.decimals,K.asset.decimals);return se?ge>K.asset.balance:parseFloat(M.formatUnits(ge,K.asset.decimals))>He}return ut>He},[K,S,Le,Be,ut,ae,He,se,ht]);i.useEffect(()=>{e||(Ue(null),at(null),zt(!1),ft("idle"),Re(""),je(null),Dt(!1),me(null),Ge(null),ke(!1),xt(!1),ze(null),kt.current=!1,C==="adjustable"&&Ye(y||""),qt.current&&(qt.current.abort(),qt.current=null))},[e]);const mt=i.useCallback(ge=>{Ue(St=>({asset:ge,amount:St?.asset?.address===ge.address&&St?.asset?.chainId===ge.chainId&&St.amount||""})),at(null),ze(null),xt(!1)},[]),bt=i.useCallback(ge=>{Ue(St=>St&&{...St,amount:ge}),at(null),ze(null),xt(!1)},[]),gt=i.useCallback(ge=>{let St=ge;b&&parseFloat(St)>parseFloat(b)&&(St=b),Ye(St),A?.(St),at(null),ze(null),xt(!1)},[b,A]);i.useCallback(ge=>{if(kt.current||!te)return;const St=Ht.current;!St?.asset||!St.amount||St.asset?._source==="wallet"||M.parseUnits(S?We:St.amount,St.asset.decimals)===0n||(kt.current=!0,Qe())},[te,_,Qe,S,We]);const Ne=i.useCallback(ge=>{ft({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[ge.step]||"executing"),Re(ge.message),ge.txHash&&je(ge.txHash)},[]),Bt=i.useMemo(()=>({currentPaymentAmount:We,destinationToken:o,embeddedWalletAddress:Me,providerEmbeddedAddress:$e,externalWalletAddress:Te,address:te,isNon7702:de,isPayMode:S,resolvedChainId:_,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:K,needsSwap:Xe,resolvedSwap:vt,exactOutputSwap:ae,quoteAmountOut:ot,resolvedTokenIn:tt}),[We,o,Me,$e,Te,te,de,S,_,l,d,u,K,Xe,vt,ae,ot,tt]),qe=i.useCallback(ge=>ro({...Bt,requestTimestampMs:Nt.current??Date.now()},ge),[Bt]),X=i.useCallback(ge=>ao({...Bt,requestTimestampMs:Nt.current??Date.now()},ge),[Bt]),be=i.useCallback((ge,St,js,hs)=>io(ge,St,js,ee,hs),[ee]),pt=i.useMemo(()=>K?.asset?Xe&&tt?tt:K.asset.chainId===_?K.asset.address:tt??as(K.asset,_)??o.address:o.address,[K,o.address,Xe,_,tt]),wt=i.useCallback(()=>(Nt.current=Date.now(),po(it.current)),[]),Ke=i.useMemo(()=>K?.asset?h.addressesEqual(K.asset.address,o.address)&&K.asset.chainId===o.chainId:!1,[K,o.address,o.chainId]),Rt=Ke&&(de||S),lt=Rt&&ut>0&&!!K?.asset,_t=he&&!Rt,G=i.useMemo(()=>{if(!lt)return null;let ge;try{ge=M.parseUnits(We||"0",o.decimals)}catch{return null}return{symbol:o.symbol,decimals:o.decimals,grossAmount:ge,netAmount:ge,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[lt,We,o.symbol,o.decimals]),Y=It,pe=i.useMemo(()=>!(!K?.asset||ut<=0),[K,ut,lt]),ie=i.useMemo(()=>!e||Ve||Ie!=="idle"||!pe||lt||!K?.asset?null:[S?"pay":"supply",g,K.asset.address.toLowerCase(),K.asset.chainId,K.amount,We,o.address.toLowerCase(),o.chainId,_,tt?.toLowerCase()??"",Xe?"swap":"direct",ht?"direct-token":"routed-token",de?"non7702":"7702",Ke?"source-dest":"cross-chain",Ct?"quoting":"quoted",ae?.amountIn?.toString()??"",ae?.amountInMax?.toString()??"",ae?.venue??"",vt?.amountOut?.toString()??"",ot?.toString()??"",Me??"",$e??"",te??""].join("|"),[e,Ve,Ie,pe,lt,K,S,g,We,o,_,tt,Xe,ht,de,Ke,Ct,ae,vt,ot,Me,$e,te]),Pe=i.useCallback(()=>lo({selectedAsset:K,isPayMode:S,parsedAmount:ut,needsSwap:Xe,exactOutputSwap:ae,isNon7702:de,isSourceDestToken:Ke,currentPaymentAmount:We,destinationToken:o,feeExecutionMode:d,resolvedTokenIn:tt,embeddedWalletAddress:Me,providerEmbeddedAddress:$e,resolvedChainId:_,isConnected:ue,address:te,ready:Ce,authenticated:xe,isDirect:ht,resolvedSwap:vt,isQuoting:Ct,executionTokenAddress:pt,buildPayChainBatches:qe,buildSupplyChainBatches:X,estimateGasless:ee,estimateRequiredGrossFunding:be}),[K,S,ut,Xe,ae,de,Ke,We,o,d,tt,Me,$e,be,qe,ee,_,ue,te,Ce,xe,ht,vt,Ct,X,pt]);i.useEffect(()=>{yt.current=Pe},[Pe]);const De=i.useCallback(ge=>Br({asset:ge,isPayMode:S,isNon7702:de,needsSwap:Xe,isQuoting:Ct,embeddedWalletAddress:Me,buildSupplyChainBatches:X,estimateGasless:ee,executionTokenAddress:pt,feeExecutionMode:d}),[S,de,Xe,Ct,Me,X,ee,pt,d]);i.useEffect(()=>{if(!e){ke(!1),xt(!1),ze(null),Ge(null);return}if(Ve||Ie!=="idle"){Ft.current+=1,ke(!1);return}if(!pe){Ge(null),ke(!1),xt(!1),ze(null);return}if(lt){Ge(G),ke(!1),xt(!0),ze(null);return}if(Ct){Ft.current+=1,ke(!1),xt(!1);return}if(!ie)return;let ge=!1;const St=async()=>{const hs=++Ft.current;ze(null),ke(!0);try{const ms=await yt.current?.();if(ge||Ft.current!==hs)return;ms?(Ge(ms),xt(!0)):(Ge(null),xt(!1)),ze(null)}catch(ms){if(ge||Ft.current!==hs)return;const vn=h.sanitizeError(ms,"Unable to calculate fees for this action.");Ge(null),xt(!1),ze(vn)}finally{!ge&&Ft.current===hs&&ke(!1)}},js=window.setTimeout(()=>{St()},250);return()=>{ge=!0,clearTimeout(js),ke(!1)}},[e,Ve,Ie,pe,lt,G,Ct,ie]);const Je=i.useCallback(()=>(Nt.current=Date.now(),fo(it.current)),[]);i.useEffect(()=>{!S&&Ie==="success"&&Ot&&(Qe(),T?.(Ot))},[S,Ie,Ot,Qe,T]),i.useEffect(()=>{if(!S||Oe?.status!=="success"||kt.current||!te)return;kt.current=!0;const ge=Ht.current;!ge?.asset||ge.asset?._source==="wallet"||Qe()},[S,Oe?.status,te,Qe]);const ct=i.useRef(T),Pt=i.useRef(F);i.useEffect(()=>{ct.current=T},[T]),i.useEffect(()=>{Pt.current=F},[F]),i.useEffect(()=>{e&&(Qe(),_e())},[e,Qe,_e]),i.useEffect(()=>{S&&(Oe?.status==="success"&&ct.current?.(Oe.txHash||""),Oe?.status==="failed"&&Pt.current?.(new Error("Payment execution failed")))},[S,Oe?.status]);const Yt=i.useCallback(()=>{Dt(!1),me(null),Ue(null),kt.current=!1,Qe(),_e()},[Qe,_e]);it.current={selectedAsset:K,parsedAmount:ut,currentPaymentAmount:We,isInsufficientBalance:st,isPayMode:S,isNon7702:de,isSourceDestToken:Ke,needsSwap:Xe,exactOutputSwap:ae,selectedIsEquivalent:Be,resolvedTokenIn:tt,embeddedWalletAddress:Me,providerEmbeddedAddress:$e,externalWallet:Ae,externalWalletAddress:Te,activeSignerWallet:rt,activeSignerAddress:jt,address:te,isConnected:ue,ready:Ce,authenticated:xe,provider:V,resolvedChainId:_,executionTokenAddress:pt,destinationToken:o,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:c,onSuccess:T,onError:F,gasless:{estimateGasless:ee,executeGasless:oe,buildPayChainBatches:qe,buildSupplyChainBatches:X,estimateRequiredGrossFunding:be,onProgress:Ne},ui:{setError:at,setStep:ft,setStatusMsg:Re,setTxHash:je,setIsExecuting:zt,setShowStatusPanel:Dt,setPaymentResult:me},refs:{spiceDepositSubmittedRef:kt,abortControllerRef:qt}};const Xt=y?.trim(),Wt=S&&C==="fixed"&&Xt!==void 0&&Xt!==""&&ut===0,ss=S?(Wt||!!K?.asset)&&ut>=0&&!Zt&&!st&&!Ve&&(Wt||lt||Tt)&&!dt&&(Wt||!Xe||!!ae)&&!_t:!!K?.asset&&ut>0&&!Zt&&!st&&!Ve&&(Rt||Tt)&&!dt&&(ne||ht||!!vt&&!Ct)&&!_t;i.useEffect(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:ss,isPayMode:S,hasSelectedAsset:!!K?.asset,selectedAsset:K?.asset?{symbol:K.asset.symbol,address:K.asset.address,chainId:K.asset.chainId,balanceFormatted:K.asset.balanceFormatted,source:K.asset?._source}:null,parsedAmount:ut,isZeroAmountPay:Wt,isBelowMinimum:Zt,isInsufficientBalance:st,isExecuting:Ve,directExternalAction:Rt,directExecutionFeeNote:lt,feeEstimateReady:Tt,feeEstimateError:dt,needsSwap:Xe,isDirect:ht,isSourceDestToken:Ke,hasExactOutputSwap:!!ae,isQuoting:Ct,whitelistHoldPending:he,supplyHeldForWhitelist:_t,isWhitelistGateActive:fe,destinationToken:{symbol:o.symbol,address:o.address,chainId:o.chainId}})},[e,ss,S,K,ut,Wt,Zt,st,Ve,Rt,lt,Tt,dt,Xe,ht,Ke,ae,Ct,he,_t,fe,o]);const bs=ht?m||`Your ${o.symbol} will be used directly.`:x||"Your assets will be swapped and used in a single atomic transaction.",Ee=(_?h.getChainConfig(_):void 0)?.viemChain?.blockExplorers?.default?.url??"",Et=_r.indexOf(Ie),Jt=Ve?($r[Ie]||"EXECUTING...").toUpperCase():Ie==="success"?"DONE":Zt?`MINIMUM ${us}`:st?"INSUFFICIENT BALANCE":p.toUpperCase(),ns=i.useMemo(()=>{if(Ve)return"PAYING...";if(Zt)return`MINIMUM ${us}`;if(st&&K?.asset)return`INSUFFICIENT ${K.asset.symbol}`;if(p)return p.toUpperCase();const ge=ut>0?` ${We} ${o.symbol}`:"";return Xe?`SWAP & PAY${ge}`:`PAY${ge}`},[Ve,Zt,st,K,p,ut,We,o.symbol,Xe]),As=Ie==="success"?()=>{ft("idle"),Ue(null),je(null),Qe()}:wt,Ys=Ie==="success"?!1:!ss;if(!e)return null;const Xs=S?R||`Pay ${o.symbol}`:p,Es=S?E:n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[n.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:n.jsx(On,{color:le})}),n.jsx("p",{style:{fontSize:"12px",color:le,margin:0,lineHeight:"1.4",fontFamily:Q},children:bs})]});if(S){const ge=Oe&&(Oe.status==="success"||Oe.status==="failed")?[{asset:{symbol:K?.asset?.symbol||o.symbol,address:K?.asset?.address||""},amount:We,txHash:Oe.txHash||"",success:Oe.status==="success",error:Oe.status==="failed"?Oe.error:void 0}]:void 0;return n.jsx(cs,{isOpen:e,onClose:t,title:Xs,subtitle:Es,styles:v,dark:I,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[P&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Ln,{onClick:P,color:N,fontFamily:Q})}),!Wt&&n.jsx("div",{style:{marginBottom:"12px"},children:n.jsx(Hs,{assets:nt,selectedAsset:K??void 0,onAssetSelect:mt,onAmountChange:$l,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:K?.asset?Xe?Ct?"...":ae?`~${parseFloat(M.formatUnits(ae.amountIn,K.asset.decimals)).toFixed(6)}`:void 0:We??void 0:void 0,dark:I,theme:q,styles:v})}),n.jsx(Pr,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:N,fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:$,dk:D,dark:I,isQuoting:Ct,quoteError:Qt,estimatedOutput:Vt,paymentAmount:We,needsSwap:Xe,exactOutputSwap:ae,adjustable:C==="adjustable",maxAmount:b,onAmountChange:gt}),pe&&n.jsx(tn,{fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:$,resolvedDark:I,darkCardBorder:D.cardBorder,primaryColor:N,feePreview:Le,isLoading:Lt,errorText:dt,directExecutionFeeNote:lt}),Y&&n.jsx(Rs,{variant:"error",palette:L,fontFamily:Q,style:{marginBottom:"12px"},children:Y}),n.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:Je,disabled:!ss,loading:Ve,dark:I,styles:{...v,button:{...v?.button,backgroundColor:N}},children:ns}),Oe&&Mt&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:I?D.shell:"white",borderRadius:I?"12px":"6px",padding:"16px 0"},children:n.jsx(Gn,{type:"payment",isOpen:Oe.status!=="processing",isProcessing:Ve||Oe.status==="processing",closeOnComplete:!1,chainName:h.getChainName(_),explorerUrl:h.getExplorerUrl(_,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Dt(!1),me(null),Je()},onNewTx:Yt,onClose:()=>{Dt(!1),me(null)},onComplete:Yt,results:ge,styles:v,dark:I})})]})})}return n.jsx(cs,{isOpen:e,onClose:t,title:Xs,subtitle:Es,dark:I,styles:v,theme:j,closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[n.jsx("div",{style:{marginBottom:"16px"},children:n.jsx(Hs,{assets:nt,selectedAsset:K||void 0,onAssetSelect:mt,onAmountChange:bt,disabled:Ve||Ie==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:q,styles:v,dark:O,resolveMaxAmount:De,maxAmount:He>0?Ms(He,K?.asset.decimals??o.decimals):void 0})}),K?.asset&&!ht&&n.jsx(Pr,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:N,fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:$,dark:I,isQuoting:Ct,quoteError:Qt,estimatedOutput:Vt}),pe&&n.jsx(tn,{fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:$,resolvedDark:I,darkCardBorder:D.cardBorder,primaryColor:N,feePreview:Le,isLoading:Lt,errorText:dt,directExecutionFeeNote:lt}),Ie!=="idle"&&n.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Ie==="success"?H:Ie==="error"?L.errorBg:H,border:`1px solid ${Ie==="success"?$:Ie==="error"?L.errorBorder:$}`},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:L.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:L.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):n.jsx(h.Spinner,{size:14,color:N}),n.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:Ie==="success"?U:Ie==="error"?L.errorText:U,fontFamily:Q,flex:1},children:Ie==="success"?"Deposit confirmed":Ie==="error"?At||"Transaction failed":$r[Ie]||At}),Ie==="success"&&Ot&&n.jsx("a",{href:`${Ee}/tx/${Ot}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:N,fontFamily:Q,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Ie==="error"&&n.jsx("button",{onClick:()=>{ft("idle"),at(null),setTimeout(wt,50)},style:{background:"none",border:"none",fontSize:"12px",color:N,fontFamily:Q,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),Et>=0&&Ie!=="success"&&Ie!=="error"&&n.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${z}22`,overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:N,transformOrigin:"left center",transform:`scaleX(${(Et+1)/_r.length})`,transition:"transform 400ms ease"}})})]}),It&&Ie==="idle"&&n.jsx(Rs,{variant:"error",palette:L,fontFamily:Q,style:{marginBottom:"16px"},children:It}),n.jsx(h.Button,{variant:"outline",fullWidth:!0,disabled:Ys,onClick:As,theme:j,dark:I,styles:{...v,button:{...v?.button,backgroundColor:N}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:W},children:Jt})]})})},_l=e=>n.jsx(ea,{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}),ec=({label:e="Export Wallet",style:t,className:s,onExport:o,onError:r})=>{const[a,l]=i.useState(!1),[d,u]=i.useState(!1),{primaryColor:c}=h.useSpiceBrand(),f=i.useContext(h.SpiceFlowProviderContext),{isAuthenticated:p}=h.useWallet();let g=null;try{g=An.usePrivy()}catch{}let x=null,m=null;try{x=vo.useEmbeddedReveal(),m=vo.useDynamicContext()}catch{x=null,m=null}const y=h.getDynamicEmbeddedWallet(m),C=i.useCallback(async()=>{if(!p){r?.("User is not authenticated. Please log in first.");return}try{if(f?.provider==="dynamic"){if(!x||!y){r?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await x.initExportProcess(!1),o?.();return}if(!g){r?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await g.exportWallet(),o?.()}catch(A){const v=A instanceof Error?A.message:"Failed to export wallet";console.error("Export wallet error:",A),r?.(v)}},[y,x,p,r,o,g,f?.provider]),k=!p,b={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:k?"not-allowed":"pointer",opacity:k?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:d?`${c}cc`:a?`${c}ee`:c,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return n.jsxs("button",{onClick:C,onMouseEnter:()=>l(!0),onMouseLeave:()=>{l(!1),u(!1)},onMouseDown:()=>u(!0),onMouseUp:()=>u(!1),disabled:k,className:s,style:b,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 ta(e){const t=i.useContext(h.SpiceFlowProviderContext),s=h.useEmbeddedWalletAddress(),o=e?.enabled===!1?void 0:s,r=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...Qo(o,r),embeddedWalletAddress:s}}var tc="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 sc=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:l,dark:d=!1,showModeToggle:u,isEmbeddedMode:c=!0,onModeToggle:f})=>{const[p,g]=i.useState(!1),x=async()=>{a&&await ja(a)&&(g(!0),setTimeout(()=>g(!1),2e3))},m=t==="active",y=s||(m?"Active":"Inactive"),C=m?"#10b981":"#9ca3af",k=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:l.textPrimary},children:[e," Account"]}),u?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsxs("button",{onClick:f,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?l.hoverBg:"#f3f4f6",border:d?`1px solid ${l.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',color:l.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[n.jsx("span",{children:c?"Embedded":"External"}),n.jsx("img",{src:tc,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...d?{filter:"invert(0.65)"}:{}}})]}),n.jsx(Po,{content:k,label:"Account mode info",textColor:d?l.textPrimary:"#f9fafb",backgroundColor:d?l.cardBg:"#111827",borderColor:d?l.cardBorder:"rgba(255,255,255,0.08)",accentColor:d?l.textSecondary:"#6b7280",children:n.jsx("img",{src:Qn,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?l.hoverBg:m?"#ecfdf5":"#f3f4f6",border:d?`1px solid ${l.cardBorder}`:m?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:C}}),n.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?l.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),n.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:l.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:Bs(o)}),r&&n.jsx("div",{style:{fontSize:"12px",color:l.textSecondary,marginBottom:"8px"},children:r}),a&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsx("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:d?l.textSecondary:"#9ca3af"},children:jo(a)}),n.jsx("button",{onClick:x,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:d?l.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:p?"Copied":"Copy"})]})]})},nc=i.memo(sc),oc=({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((r,a)=>{const l=h.getChainConfig(r.chainId)?.displayName||`Chain ${r.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:r.tokenSymbol.charAt(0)}),n.jsxs("div",{children:[n.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:[r.amount," ",r.tokenSymbol]}),n.jsxs("div",{style:{fontSize:"11px",color:s.warningText},children:["on ",l]})]})]}),n.jsx("button",{onClick:()=>t?.(r),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"})]},`${r.tokenAddress}-${r.chainId}-${a}`)})})]}),rc=i.memo(oc),ac=e=>`${e.tokenAddress}-${e.chainId}`,ic=({spiceAssets:e,loading:t,dk:s,dark:o=!1,canDirectWithdraw:r=!1,onDirectWithdraw:a,directWithdrawState:l})=>{const d={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s.textSecondary,marginBottom:"8px",textTransform:"uppercase"},u={backgroundColor:s.cardBg,border:o?`1px solid ${s.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?n.jsxs("div",{children:[n.jsx("div",{style:d,children:"Idle Balances"}),[1,2].map(c=>n.jsx("div",{style:{...u,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},c))]}):e.length===0?n.jsxs("div",{children:[n.jsx("div",{style:d,children:"Idle Balances"}),n.jsx("div",{style:{...u,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:d,children:"Idle Balances"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((c,f)=>{const p=h.getChainConfig(c.chainId),g=c.chainDisplayName||p?.displayName||`Chain ${c.chainId}`,x=c.tokenDisplaySymbol||c.tokenDisplayName||c.tokenSymbol,m=ac(c),y=r&&c.directWithdraw&&!!a,C=l?.key===m?l:null,k=C?.step==="pending";return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...u},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[c.logoURI?n.jsx("img",{src:c.logoURI,alt:c.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:x.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:x}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:g})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:xs(c.balanceFormatted)}),n.jsx("div",{style:{fontSize:"11px",color:C?.step==="error"?s.errorText:o?s.textSecondary:"#9ca3af"},children:C?.step==="error"?C.message||"Withdraw failed":Bs(c.usdValue)})]}),y&&n.jsx("button",{onClick:()=>!k&&a(c),disabled:k,title:"Withdraw to external wallet",style:{padding:"6px 10px",borderRadius:"6px",border:o?`1px solid ${s.cardBorder}`:"1px solid #e5e7eb",backgroundColor:o?s.hoverBg:"#ffffff",color:s.textPrimary,fontSize:"11px",fontWeight:600,cursor:k?"default":"pointer",opacity:k?.6:1,whiteSpace:"nowrap"},children:k?"Withdrawing\u2026":"Withdraw"})]})]},`${c.tokenAddress}-${c.chainId}-${f}`)})})]})},lc=i.memo(ic),cc=({section:e,dk:t,dark:s=!1})=>{const o=r=>{switch(r){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((r,a)=>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:[r.tokenLogoURI?n.jsx("img",{src:r.tokenLogoURI,alt:r.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:r.tokenSymbol.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:r.tokenSymbol}),n.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:r.label})]})]}),n.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:o(r.valueColor)},children:r.displayValue})]},a))})]})},dc=i.memo(cc),uc=({onDepositClick:e,onWithdrawClick:t,depositDisabled:s=!1,withdrawDisabled:o=!1,primaryColor:r="#EA4B4B",dark:a=!1})=>!e&&!t?null:n.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&n.jsx(h.Button,{variant:"outline",onClick:e,disabled:s,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&n.jsx(h.Button,{variant:"outline",onClick:t,disabled:o,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),pc=i.memo(uc),fc=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,spiceAssets:l,spiceAssetsLoading:d,pendingDeposits:u,customSections:c,notice:f,onDepositClick:p,onWithdrawClick:g,depositDisabled:x,onCompleteDeposit:m,primaryColor:y,dk:C,dark:k=!1,showModeToggle:b,isEmbeddedMode:A,onModeToggle:v,showConnectExternalCta:w,onConnectExternalWallet:R,connectExternalError:E,showHowItWorks:P=!0,canDirectWithdraw:T,onDirectWithdraw:F,directWithdrawState:S})=>{const[j,I]=i.useState(!1);return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[n.jsx(nc,{appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:C,dark:k,showModeToggle:b,isEmbeddedMode:A,onModeToggle:v}),f&&n.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:f.tone==="warning"?k?"rgba(245, 158, 11, 0.12)":"#fffbeb":f.tone==="success"?k?"rgba(16, 185, 129, 0.12)":"#ecfdf5":C.cardBg,border:f.tone==="warning"?k?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":f.tone==="success"?k?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":k?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",color:f.tone==="warning"?k?"#fbbf24":"#92400e":f.tone==="success"?k?"#34d399":"#047857":C.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:f.message}),w&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsx("button",{onClick:R,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:y||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),E&&n.jsx("span",{style:{fontSize:"11px",color:k?C.errorText:"#b91c1c",lineHeight:1.4},children:E})]}),n.jsx("div",{style:{height:"1px",backgroundColor:k?"#2d2d2d":"#e5e7eb"}}),n.jsx(pc,{onDepositClick:p,onWithdrawClick:g,depositDisabled:x,primaryColor:y,dark:k}),P&&n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>I(!j),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:C.cardBg,border:k?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:C.textSecondary,fontSize:"12px",fontWeight:500},children:[n.jsx("span",{children:"How It Works"}),n.jsx("span",{style:{transform:j?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),j&&n.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:k?C.cardBg:"#f0fdf4",border:k?`1px solid ${C.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:k?C.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),n.jsx(rc,{pendingDeposits:u,onCompleteDeposit:m,dk:C,dark:k}),n.jsx(lc,{spiceAssets:l,loading:d,dk:C,dark:k,canDirectWithdraw:T,onDirectWithdraw:F,directWithdrawState:S}),c.map((N,D)=>n.jsx(dc,{section:N,dk:C,dark:k},D))]})},hc=i.memo(fc);function mc(e,t,s){const o=t-s.gasBridge-s.spicenetFee;if(o<=0n)throw new Error("Balance is too small to cover the network fee.");const r=[{recipient:e,amount:o}];return s.gasBridge>0n&&r.push({recipient:B.SPICE_GAS_FEE_RECIPIENT,amount:s.gasBridge}),s.spicenetFee>0n&&r.push({recipient:B.SPICE_PLATFORM_FEE_RECIPIENT,amount:s.spicenetFee}),r}function gc(e,t,s){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*s}const xc=new Set([B.SPICE_GAS_FEE_RECIPIENT,B.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function yc(e,t){return!e||e.length!==t.length?!1:e.every((s,o)=>{const r=t[o];return s.recipient.toLowerCase()!==r.recipient.toLowerCase()?!1:xc.has(s.recipient.toLowerCase())?gc(s.amount,r.amount,100n):!0})}function sa(e,t,s){return{chainId:e,domain:"evm",tokenTransfers:[],calls:s.filter(o=>o.amount>0n).map(o=>({to:t,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[o.recipient,o.amount]})}))}}function Cc(e,t){const s=e.intents.flatMap(r=>r.batches).filter(r=>ts(r).totalFee>0n),o=s.filter(r=>r.chainId===t);return(o.length>0?o:s)[0]??null}function bc(e,t,s,o){const r=Cc(o,e),{gasFee:a,bridgeFee:l,spicenetFee:d}=r?ts(r):{gasFee:0n,bridgeFee:0n,spicenetFee:0n};return mc(t,s,{gasBridge:a+l,spicenetFee:d})}function wc(){const{executeGasless:e}=Ps(),t=h.useEmbeddedWalletAddress(),{embeddedAddress:s}=h.useProviderWallets(),o=t||s;return{withdraw:i.useCallback(async({tokenAddress:r,chainId:a,balance:l,recipient:d,onProgress:u})=>{const c=r,f=d;if(l<=0n)throw new Error("Nothing to withdraw.");const p=[sa(a,c,[{recipient:f,amount:l}])];let g=null;return e(p,c,0n,u,void 0,{useCustomTransfers:!0,userOverride:o,adjustBatchesForEstimate:({feeEstimate:x})=>{const m=bc(a,f,l,x);return yc(g,m)?null:(g=m,[sa(a,c,m)])}})},[e,o])}}function kc(e){return!!e.embeddedAddress&&!!e.externalAddress}const yo=380,Is=8,vc=[];function na(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Sc(e,t){const s=new Map;Object.entries(t).forEach(([r,a])=>{if(!Number.isFinite(a)||a<=0)return;s.set(r,a),s.set(r.toUpperCase(),a);const l=na(r);l&&s.set(l,a)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const r of o){if(!r)continue;const a=s.get(r)??s.get(r.toUpperCase());if(a!==void 0)return a;const l=na(r);if(!l)continue;const d=s.get(l);if(d!==void 0)return d}return 0}const Ic=({appName:e="Spice",status:t="active",statusLabel:s,customSections:o=vc,extraAssets:r=[],tokenPrices:a={},breakdownLabels:l=[],notice:d,styles:u,dark:c=!1,onDepositSuccess:f,onDepositClick:p,onWithdrawClick:g,onCompleteDeposit:x,showModeToggle:m=!1,defaultMode:y})=>{const C=i.useContext(h.SpiceFlowProviderContext),k=C?.mode!=="7702",b=!!C?.isWhitelistGateActive,A=!!C?.isWhitelistConfigured&&C?.isUserWhitelisted!==!0,v=i.useRef(!1);i.useEffect(()=>{if(!v.current){if(h.hasStoredSpiceFlowMode()){v.current=!0;return}y&&C?.setMode&&(C.setMode(y==="non7702"?"ondemand":"7702"),v.current=!0)}},[C,y]);const[w,R]=i.useState(!1),[E,P]=i.useState(null),[T,F]=i.useState({top:0,bottom:0,left:0,placement:"below"}),S=i.useRef(null),j=i.useRef(null),{address:I,isConnected:N}=h.useWallet(),D=h.useEmbeddedWalletAddress(),{externalAddress:L,embeddedAddress:Q}=h.useProviderWallets(),{dark:W,primaryColor:O,dk:H}=h.useSpiceBrand(u,c),$=k&&!L,U=!k||$,z=U?D||Q:I,le=i.useMemo(()=>C?.supportedChainIds??B.getChainIdsByNetwork("mainnet"),[C?.supportedChainIds]),{assets:q,loading:_}=Qs({address:z,supportedChains:le,enabled:!!z&&U,refetchInterval:3e4}),ce=i.useMemo(()=>{const K=U?q.map(Se=>{const Ye=Se.balanceUsd||0,Ve=Number.isFinite(Se.balanceFormatted)?Se.balanceFormatted:0,zt=Ye>0?Ye:Sc(Se,a)*Ve;return{tokenAddress:Se.address,tokenSymbol:Se.symbol,tokenDisplaySymbol:Pn(Se),tokenDisplayName:Da(Se),tokenDecimals:Se.decimals,chainId:Se.chainId,chainDisplayName:Wn(Se),balance:Se.balance.toString(),balanceFormatted:Se.balanceFormatted,usdValue:zt,logoURI:Se.logoURI}}):[],Ue=$?[]:r;return[...K,...Ue].filter(Se=>Se.balanceFormatted>0)},[U,$,q,a,r]),we=i.useMemo(()=>ce.reduce((K,Ue)=>K+Ue.usdValue,0),[ce]),{pendingDeposits:de}=ta({chainIds:le,enabled:!!I,discoverWalletBalances:!0}),fe=i.useMemo(()=>o.reduce((K,Ue)=>K+Ue.totalValue,0),[o]),he=we+fe,Z=i.useMemo(()=>{const K=[];we>0&&K.push(`${Bs(we)} idle`);for(const Ue of o){const Se=l.find(Ye=>Ye.sectionTitle===Ue.title)?.label||Ue.title.toLowerCase();K.push(`${Bs(Ue.totalValue)} ${Se}`)}return K.join(" \xB7 ")},[we,o,l]),re=i.useCallback(K=>{x?x(K):P(K)},[x]),J=i.useCallback(()=>{P(null)},[]),te=i.useCallback(()=>{P(null),f?.()},[f]),ue=i.useCallback(()=>{if(!S.current)return;const K=S.current.getBoundingClientRect(),Ue=window.innerHeight-K.bottom-Is,Se=K.top-Is,Ye=Ue>=400||Ue>=Se?"below":"above",Ve=Math.max(Is,Math.min(K.right-yo,window.innerWidth-yo-Is)),zt=Ye==="below"?K.bottom+Is:K.top-Is,It=Ye==="above"?window.innerHeight-zt:0;F({top:zt,bottom:It,left:Ve,placement:Ye})},[]);i.useLayoutEffect(()=>{w&&ue()},[w,ue]),i.useEffect(()=>{if(!w)return;const K=Ye=>{S.current&&!S.current.contains(Ye.target)&&j.current&&!j.current.contains(Ye.target)&&R(!1)},Ue=Ye=>{Ye.key==="Escape"&&R(!1)},Se=()=>ue();return document.addEventListener("mousedown",K),document.addEventListener("keydown",Ue),window.addEventListener("scroll",Se,{passive:!0}),window.addEventListener("resize",ue),()=>{document.removeEventListener("mousedown",K),document.removeEventListener("keydown",Ue),window.removeEventListener("scroll",Se),window.removeEventListener("resize",ue)}},[w,ue]);const Ce=U?D||Q||I:L||I,xe=i.useCallback(()=>{C?.setMode&&C.setMode(U?"ondemand":"7702")},[C,U]),[V,oe]=i.useState(null);let ee=null;try{ee=An.useConnectWallet({onSuccess:()=>oe(null),onError:K=>oe(h.sanitizeError(K,"Failed to connect wallet."))}).connectWallet}catch{ee=null}const Ae=i.useCallback(()=>{ee&&(R(!1),oe(null),ee({walletChainType:"ethereum-only"}))},[ee]),Te=!L&&!!ee,$e=i.useCallback(()=>{R(!1),p?.()},[p]),rt=i.useCallback(()=>{R(!1),g?.()},[g]),jt=i.useCallback(K=>{R(!1),re(K)},[re]),{withdraw:Ze}=wc(),[ye,Fe]=i.useState(null),Me=kc({embeddedAddress:D||Q,externalAddress:L}),Qe=i.useCallback(async K=>{if(!L)return;const Ue=`${K.tokenAddress}-${K.chainId}`;Fe({key:Ue,step:"pending"});try{await Ze({tokenAddress:K.tokenAddress,chainId:K.chainId,balance:BigInt(K.balance),recipient:L}),Fe(null)}catch(Se){Fe({key:Ue,step:"error",message:h.sanitizeError(Se,"Withdraw failed")})}},[Ze,L]);if(typeof window>"u")return null;const _e=n.jsxs("button",{ref:S,onClick:()=>R(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:W?H.hoverBg:"#ffffff",border:W?`1px solid ${H.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:W?H.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:W?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[n.jsxs("span",{children:[e," Account"]}),N&&n.jsxs("span",{style:{color:W?H.textSecondary:"#6b7280"},children:["\xB7 ",Bs(he)]}),n.jsx("span",{style:{fontSize:"10px",color:W?H.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),nt=w?Us.createPortal(n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:gs.popover},onClick:()=>R(!1)}),n.jsx("div",{ref:j,style:{position:"fixed",top:T.placement==="below"?`${T.top}px`:"auto",bottom:T.placement==="above"?`${T.bottom}px`:"auto",left:`${T.left}px`,width:`${yo}px`,maxWidth:`calc(100vw - ${Is*2}px)`,maxHeight:"80vh",backgroundColor:W?H.shell:"#ffffff",border:W?`1px solid ${H.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:W?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:gs.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${Ut.out}`},children:n.jsx(hc,{appName:e,status:t,statusLabel:s,totalUsdValue:he,breakdownSubtitle:Z,address:U?Ce:I,spiceAssets:ce,spiceAssetsLoading:_,pendingDeposits:de,customSections:o,notice:d,onDepositClick:p?$e:void 0,onWithdrawClick:g?rt:void 0,depositDisabled:A,onCompleteDeposit:jt,primaryColor:O,dk:H,dark:W,showModeToggle:m,isEmbeddedMode:U,onModeToggle:xe,showConnectExternalCta:Te,onConnectExternalWallet:Ae,connectExternalError:V,showHowItWorks:!b,canDirectWithdraw:Me,onDirectWithdraw:Qe,directWithdrawState:ye})}),n.jsx("style",{children:`
|
|
104
104
|
@keyframes accountDisplayFadeIn {
|
|
105
105
|
from { opacity: 0; transform: translateY(-4px); }
|
|
106
106
|
to { opacity: 1; transform: translateY(0); }
|