@spicenet-io/spiceflow-ui 4.10.0-dev.20260909.3 → 4.10.0-dev.20260909.4

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
@@ -27,7 +27,7 @@
27
27
  transform: translateY(0);
28
28
  }
29
29
  }
30
- `})]})};async function _c(e,t,n){let s=null;try{const o=await e.request({method:"eth_chainId"});s=parseInt(o,16)}catch{s=null}s!==t&&(n?.(),await g.ensureWalletOnChain(e,t))}async function Ns(e){let t=e.hash,n=!1;const s=await e.client.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1,onReplaced:o=>{const r=o.transaction,i=o.replacedTransaction;if(!(o.reason==="repriced"&&i?.from&&i.nonce!==void 0&&/^0x[0-9a-f]{64}$/i.test(r?.hash??"")&&r?.to?.toLowerCase()===e.call.to.toLowerCase()&&(r.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(r.value??0)===e.call.value&&r.from?.toLowerCase()===i?.from?.toLowerCase()&&r.nonce===i?.nonce)){n=!0,e.onCancelled?.();return}t=r.hash,e.onRepriced?.(t)}});if(n)throw new Error("Transaction was cancelled or replaced with a different action; retry the unfinished action");if(s.transactionHash&&s.transactionHash.toLowerCase()!==t.toLowerCase())throw new Error("Unexpected transaction receipt; recover the submitted transaction before retrying");return{receipt:s,hash:t}}function pa(e){let t=e;const n=new Set;for(;t&&typeof t=="object"&&!n.has(t);){if(n.add(t),t.code===4001)return!0;t=t.cause}return!1}async function On(e){const t=e.provider??await e.wallet?.getEthereumProvider();if(!t)throw new Error("External wallet provider not available");await _c(t,e.chainId,e.onSwitch);const n=g.getChainConfig(e.chainId)?.viemChain;return{extWc:I.createWalletClient({account:e.account,chain:n,transport:I.custom(t)}),viemChain:n}}async function Mo(e){let t;for(const[n,s]of e.calls.entries()){await e.observer?.onSending?.(n);let o;try{o=await e.extWc.sendTransaction({to:s.to,data:s.data,value:s.value,chain:e.viemChain})}catch(i){throw pa(i)&&e.observer?.onRejected?.(n),i}e.observer?.onSubmitted?.(n,o);const r=await Ns({client:e.client,hash:o,call:s,onRepriced:i=>e.observer?.onSubmitted?.(n,i),onCancelled:()=>e.observer?.onReverted?.(n,o)});if(o=r.hash,r.receipt.status!=="success")throw e.observer?.onReverted?.(n,o),new Error(e.errorMessage);e.observer?.onConfirmed?.(n,o),t=o}return t}function fa(e,t,n,s){return n?{to:e,value:s,data:"0x"}:{to:t,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[e,s]})}}function ma(e,t){return t.isNative?e.sendTransaction({to:t.recipient,value:t.amount,chain:t.viemChain}):e.sendTransaction({to:t.tokenAddr,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[t.recipient,t.amount]}),chain:t.viemChain})}async function ha(e){const{extWc:t,sourceClient:n,recipient:s,tokenAddr:o,isNative:r,amount:i}=e;if(i<=0n)return;await e.observer?.onSending?.(0);let l;try{l=await ma(t,{recipient:s,tokenAddr:o,isNative:r,amount:i,viemChain:e.viemChain})}catch(c){throw pa(c)&&e.observer?.onRejected?.(0),c}e.observer?.onSubmitted?.(0,l);const d=await Ns({client:n,hash:l,call:fa(s,o,r,i),onRepriced:c=>e.observer?.onSubmitted?.(0,c),onCancelled:()=>e.observer?.onReverted?.(0,l)});if(l=d.hash,d.receipt.status!=="success")throw e.observer?.onReverted?.(0,l),new Error("Embedded wallet funding failed");e.observer?.onConfirmed?.(0,l)}const ga="spiceflow:pendingDeposit",Ms="spiceflow:pendingDepositChanged";function xa(e,t,n){return`${ga}:${e.toLowerCase()}:${t}:${n.toLowerCase()}`}function Oo(){try{const e="__spiceflow_storage_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}function ed(e){if(!Oo())return;const t=xa(e.embeddedWalletAddress,e.chainId,e.tokenAddress);try{localStorage.setItem(t,JSON.stringify(e)),window.dispatchEvent(new Event(Ms))}catch(n){console.error("[pendingDeposit] Failed to save:",n)}}function td(e){if(!Oo())return[];const t=`${ga}:${e.toLowerCase()}:`,n=[],s=Date.now();for(let o=0;o<localStorage.length;o++){const r=localStorage.key(o);if(!(!r||!r.startsWith(t)))try{const i=localStorage.getItem(r);if(!i)continue;const l=JSON.parse(i);if(s-l.timestamp>6048e5){localStorage.removeItem(r);continue}n.push(l)}catch{localStorage.removeItem(r)}}return n}function Po(e,t,n){if(!Oo())return;const s=xa(e,t,n);localStorage.removeItem(s),window.dispatchEvent(new Event(Ms))}function nd({sourceChainId:e,selectedAsset:t,destinationChainId:n,destinationTokenAddress:s,isCrossDenomination:o,convertedUsdAmount:r}){const i=A.normalizeNativeTokenAddress(t.asset.address),l=s;let d,c;if(l&&n)if(d=g.CHAIN_CONFIGS[n]?.supportedTokens?.find(m=>g.addressesEqual(m.address,l))?.decimals??t.asset.decimals,o){if(!r)throw new Error("Destination amount is still being calculated. Please retry in a moment.");c=r}else{const m=I.parseUnits(t.amount,t.asset.decimals);c=A.convertAmountBetweenDecimals(m,t.asset.decimals,d)}return{sourceChainId:e,depositTokenAddress:i,depositAmount:t.amount,depositTokenDecimals:t.asset.decimals,destinationChainId:n,destinationTokenAddress:l,destinationAmount:c,destinationTokenDecimals:d}}async function sd(e,t){if(!e)return[];if(Array.isArray(e))return e;const n=e;return e.length>=2?n(t.depositAmount,t.depositTokenAddress):n(t)}function ya(e,t){return!!e&&e.quotedAmount===t.amount&&e.chainId===t.chainId&&g.addressesEqual(e.token,t.token)}async function Wo(e,t){const n=await ma(e,{recipient:t.recipient,tokenAddr:t.tokenAddr,isNative:t.isNative,amount:t.amount});t.afterSend?.(n);const s=g.getClientForChain(t.chainId),o=await s.waitForTransactionReceipt({hash:n,timeout:12e4,pollingInterval:2e3,confirmations:2});if(o.status!=="success")throw new Error(t.failureMessage);return t.settle&&await s.getBlockNumber()-o.blockNumber<2n&&await hn(3e3),o.transactionHash}async function od(e){const t=e.selectedDepositAssets.filter(o=>o.asset&&o.amount&&parseFloat(o.amount)>0);if(t.length===0){console.error("[DepositModal] No valid assets for deposit"),e.setError("Please select an asset and enter an amount");return}const n=t[0];if(!e.escrowOnly&&!e.sourceAddress){e.setError("External wallet not connected. Please connect your wallet in the previous step.");return}if(!e.isNon7702){if(!e.address||!e.embeddedWalletAddress){e.setError("Couldn't find your account wallet. Try reconnecting.");return}if(!e.isReady||!e.isAuthenticated){e.setError("Sign in to continue.");return}}if(e.zeroCreditError){e.setError(e.zeroCreditError);return}if(e.depositBalanceError){e.setError(e.depositBalanceError);return}if(e.isNon7702&&e.sponsorGas&&e.nativeChainId&&n.asset.chainId!==e.nativeChainId&&e.destinationTokenAddress){e.setError("Gas sponsorship is not supported for this deposit route. Disable sponsorGas to continue.");return}e.setIsExecuting(!0),e.setError(null);let s=!1;try{const o=n.asset.chainId,r=A.getEscrowContractAddress(o),i=I.parseUnits(n.amount,n.asset.decimals),l=t.length===1&&ya(e.effectiveDepositFee,{amount:i,token:A.normalizeNativeTokenAddress(n.asset.address),chainId:o});if(!e.isNon7702&&t.length===1&&!l)throw new Error("Fee quote is out of date. Please wait for it to refresh.");let d=e.externalWalletClient;if(!e.escrowOnly){if(!d)throw new Error("External wallet not connected");if(e.externalProvider){const c=await On({provider:e.externalProvider,account:e.sourceAddress,chainId:o});c.viemChain&&(d=c.extWc)}}if(e.isNon7702){if(!d)throw new Error("External wallet not connected");if(!e.sourceAddress)throw new Error("External wallet address not available");if(e.nativeChainId&&o===e.nativeChainId){const c=g.getChainConfig(o),m=t.map(f=>`${f.amount} ${f.asset.symbol}`).join(", ");e.setConfirmationData({network:c?.displayName||`Chain ${o}`,amount:m,symbol:"",chainId:o}),e.setShowConfirmation(!0);let p=null;e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(o);for(const f of t){const h=I.parseUnits(f.amount,f.asset.decimals),x=A.normalizeNativeTokenAddress(f.asset.address),b=f.asset.isNative||A.isNativeToken(x),y=await Wo(d,{chainId:o,recipient:r,tokenAddr:x,isNative:b,amount:h,failureMessage:`Escrow deposit failed for ${f.asset.symbol}`});p=y,e.setDirectDepositTxHash(y)}if(t[0]?.amount){const f=t[0].amount;if(e.onDepositExecute){e.setPostDepositStatus("executing");try{await e.onDepositExecute(f),e.setPostDepositStatus("success")}catch(x){console.error("ctx.onDepositExecute failed:",x),e.setPostDepositStatus("error"),e.setPostDepositError(x?.message||"Post-deposit instruction failed")}}else e.setPostDepositStatus("success");e.setDirectDepositStatus("success"),e.setPostDepositAmount(f),e.setPostDepositSuccess(!0);const h={type:"deposit",status:"success",amount:f,asset:t[0].asset.symbol,sourceChain:c?.displayName||`Chain ${o}`,txHash:p??void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:h})),e.onDepositSuccess?.(h)}e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset)}else{const c=e.destinationChainId||e.nativeChainId;if(!c)throw new Error("Destination chain ID is required for non-7702 mode. Either pass ctx.destinationChainId to <SpiceDeposit> or set ctx.nativeChainId on <SpiceFlowProvider>.");const m=g.getDelegateContractAddress(o),p=r,f=[];let h=null;for(const x of t){const b=I.parseUnits(x.amount,x.asset.decimals),y=A.normalizeNativeTokenAddress(x.asset.address),w=x.asset.isNative||A.isNativeToken(y),S=await Wo(d,{chainId:o,recipient:p,tokenAddr:y,isNative:w,amount:b,failureMessage:`Transfer failed for ${x.asset.symbol}`,afterSend:v=>{h||(h=v)},settle:!0});e.depositDataRef.current||(e.depositDataRef.current=[]),e.depositDataRef.current.push({txHash:S,sender:e.sourceAddress,tokenAddress:y,chainId:o,amount:b.toString(),user:e.spiceBalanceUser}),f.push({tokenAddress:y,tokenAmount:b.toString(),sender:e.sourceAddress,receiver:p})}if(!h)throw new Error("No transaction hash generated");if(!e.destinationTokenAddress){const x={type:"deposit",status:"success",amount:t[0]?.amount,asset:t[0]?.asset?.symbol,sourceChain:g.getChainName(o),txHash:h};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:x})),e.onDepositSuccess?.(x),e.depositDataRef.current=null,e.bridgedAmountRef.current=t[0]?.amount||null,e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1);return}if(e.mode==="ondemand"){const x={to:m,value:BigInt(0),data:"0x"},b=await g.getTokenDecimals(c,e.destinationTokenAddress);let y=BigInt(0);for(const j of f){const T=BigInt(j.tokenAmount),R=A.normalizeNativeTokenAddress(j.tokenAddress),D=t.find(P=>{const q=A.normalizeNativeTokenAddress(P.asset.address);return g.addressesEqual(q,R)}),M=D?D.asset.decimals:await g.getTokenDecimals(o,A.ZERO_ADDRESS);y+=A.convertAmountBetweenDecimals(T,M,b)}e.isCrossDenomination&&e.convertedUsdAmount&&(y=e.convertedUsdAmount);const w={chainId:o,tokenTransfers:f.map(j=>({from:j.sender,to:j.receiver,token:j.tokenAddress,amount:BigInt(j.tokenAmount)})),call:x},S=e.isCrossDenomination&&e.convertedUsdAmount?[{from:e.sourceAddress,to:r,token:A.normalizeNativeTokenAddress(t[0].asset.address),amount:I.parseUnits(t[0].amount,t[0].asset.decimals)}]:[],v={chainId:c,tokenTransfers:[...S,{from:"escrow",to:e.sourceAddress,token:e.destinationTokenAddress,amount:y}],call:{to:e.destinationTokenAddress,value:BigInt(0),data:"0x"}},k={mode:"non-7702:on-demand",chainBatches:[w,v]},C={user:e.sourceAddress,intents:[k]},E=await g.relayerService.createAction(C),F=E.actionId,B=E.intentIds[0];if(!h)throw new Error("No transaction hash available");e.startStatusPolling(B,g.createInitialSteps([{chainId:o,calls:[x]},{chainId:c,calls:[v.call]}],j=>g.getChainName(j))),await g.relayerService.executeStep(F,0,0,{action:"execute",hash:h}),t[0]?.amount&&(e.bridgedAmountRef.current=t[0].amount),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1)}else throw new Error("Presign mode not yet fully supported for cross-chain deposits")}}else{const c=[],m=l&&e.effectiveDepositFee?I.formatUnits(e.effectiveDepositFee.net,n.asset.decimals):n?.amount;for(const k of t){const C=I.parseUnits(k.amount,k.asset.decimals),E=l&&k===n,F=E?e.effectiveDepositFee.fee:0n,B=E?e.effectiveDepositFee.net:C,j=e.escrowOnly?C:C+F,T=A.normalizeNativeTokenAddress(k.asset.address),R=k.asset.isNative||A.isNativeToken(T);e.escrowOnly||await Wo(d,{chainId:o,recipient:e.address,tokenAddr:T,isNative:R,amount:j,failureMessage:`Transfer to embedded wallet failed for ${k.asset.symbol}`,afterSend:()=>ed({chainId:o,tokenAddress:A.normalizeNativeTokenAddress(k.asset.address),tokenSymbol:k.asset.symbol,tokenDecimals:k.asset.decimals,amount:k.amount,rawAmount:C.toString(),embeddedWalletAddress:e.address,externalWalletAddress:e.sourceAddress,timestamp:Date.now(),isNative:R}),settle:!0}),c.push(R?{to:r,value:B,data:"0x"}:{to:T,value:BigInt(0),data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[r,B]})}),F>0n&&c.push(R?{to:A.SPICE_GAS_FEE_RECIPIENT,value:F,data:"0x"}:{to:T,value:BigInt(0),data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[A.SPICE_GAS_FEE_RECIPIENT,F]})})}const p=await g.getClientForChain(o).getBlockNumber(),f=c.map(k=>({...k,to:I.getAddress(k.to)})),h={chainId:o,recentBlock:p,calls:f,tokenTransfers:[]},x=nd({sourceChainId:o,selectedAsset:n&&m?{...n,amount:m}:t[0],destinationChainId:e.destinationChainId,destinationTokenAddress:e.destinationTokenAddress,isCrossDenomination:e.isCrossDenomination,convertedUsdAmount:e.convertedUsdAmount}),b=await sd(e.depositBatches,x),y=[h,...b];if(!e.address)throw new Error("Address not available");const w=[];if(e.isCrossDenomination&&e.convertedUsdAmount&&e.destinationTokenAddress){const k=e.selectedDepositAssets[0]?.asset;if(k){const C=I.parseUnits(e.selectedDepositAssets[0].amount,k.decimals);w.push({from:e.address,to:r,token:A.normalizeNativeTokenAddress(k.address),amount:C}),w.push({from:"escrow",to:e.address,token:e.destinationTokenAddress,amount:e.convertedUsdAmount})}}w.length>0&&y[1]&&(y[1].tokenTransfers=w);const S=g.createInitialSteps(y,k=>g.getChainName(k));let v=!1;if(await e.execution.execute(y,A.ZERO_ADDRESS,0n,k=>{if(k.intentId&&!v){v=!0;for(const C of t)Po(e.address,o,A.normalizeNativeTokenAddress(C.asset.address));e.startStatusPolling(k.intentId,S)}},void 0,{userOverride:e.address,useCustomTransfers:!0,skipPreSubmitFeeEstimate:!0,skipUserFundingPreflight:!0}),e.refreshAssets(),e.onDepositExecute&&t[0]?.amount)try{e.setPostDepositStatus("executing"),await e.onDepositExecute(m||t[0].amount),e.setPostDepositStatus("success"),e.setPostDepositAmount(m||t[0].amount),e.setPostDepositSuccess(!0)}catch(k){console.error("ctx.onDepositExecute failed (7702):",k),e.setPostDepositStatus("error"),e.setPostDepositError(k?.message||"Post-deposit instruction failed")}e.onDepositSelect&&e.onDepositSelect(t[0].asset)}}catch(o){s=!0,console.error("[DepositModal] executeDeposit CAUGHT ERROR:",o),console.error("[DepositModal] Error details:",{message:o?.message,code:o?.code,name:o?.name,stack:o?.stack?.slice(0,500)}),e.setError(g.sanitizeError(o,"Deposit failed")),e.clearStatus()}finally{e.setIsExecuting(!1),s&&e.setDirectDepositStatus("idle"),s||!e.getCurrentIntentStatus()&&e.getCurrentPostDepositStatus()!=="idle"||e.setShowConfirmation(!1)}}async function rd(e){const{asset:t,assetIndex:n,selectedAssetCount:s,address:o,escrowOnly:r,isNon7702:i}=e;if(n!==0||i||s>1||!o||t.balance<=0n)return null;const l=await ba({address:o,depositQuote:{asset:t,amount:t.balance,token:A.normalizeNativeTokenAddress(t.address),chainId:t.chainId},escrowOnly:r}),d=r?t.balance:t.balance>l.fee?t.balance-l.fee:0n;return ra(d,t.decimals)}async function ba(e){const{address:t,depositQuote:n,escrowOnly:s}=e,{asset:o,amount:r,token:i,chainId:l}=n,d=A.getEscrowContractAddress(l),c=o.isNative||A.isNativeToken(i),m=r>1n?1n:0n,p=[c?{to:d,value:r,data:"0x"}:{to:i,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[d,r]})}];m>0n&&p.push(c?{to:A.SPICE_GAS_FEE_RECIPIENT,value:m,data:"0x"}:{to:i,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[A.SPICE_GAS_FEE_RECIPIENT,m]})});const f={chainId:l,tokenTransfers:[],calls:p},h=(await g.relayerService.estimateBatchGas({user:t,outputToken:i,chainBatches:[{...f,hash:A.hashChainBatches([f])[0].hash}],signal:e.signal})).gasFee,x=s&&h<r?r-h:r;return{fee:h,net:x,quotedAmount:r,token:i,chainId:l}}const ad=({selectedDepositAssets:e,depositAssets:t,secondAssetOptions:n,loadingAssets:s,allowSecondAsset:o,theme:r,styles:i,dark:l,dk:d,onSelect:c,onAmountChange:m,onAdd:p,onRemove:f,resolveMaxAmount:h,onViewAllAssets:x})=>a.jsxs(a.Fragment,{children:[e.map((b,y)=>{const w=e.length===1?"Deposit":`Asset ${y+1}`;return a.jsxs("div",{style:{marginBottom:r.spacing.md,position:"relative"},children:[a.jsx(os,{assets:y===0?t:n,selectedAsset:b||void 0,onAssetSelect:S=>c(S,y),onAmountChange:S=>m(S,y),loading:s,label:w,showBalance:!0,theme:r,styles:i,allowSecondAsset:o&&y===0,onAddAsset:p,canAddAsset:e.length===1&&!!e[0]?.asset,resolveMaxAmount:h?S=>h(S,y):void 0,onViewAllAssets:y===0?x:void 0}),y===1&&a.jsx("button",{onClick:()=>f(y),style:{position:"absolute",top:"-2px",right:"-2px",background:l?`${d.cardBg}ee`:"rgba(255, 255, 255, 0.9)",border:`1px solid ${d.cardBorder}`,borderRadius:"50%",cursor:"pointer",color:r.colors.textMuted,fontSize:"16px",padding:"2px",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",transition:g.transition.interactive,boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)"},onMouseEnter:S=>{S.currentTarget.style.color=l?d.errorText:"#ef4444",S.currentTarget.style.background=l?d.cardBg:"#fff",S.currentTarget.style.borderColor=l?d.errorBorder:"#fecaca"},onMouseLeave:S=>{S.currentTarget.style.color=r.colors.textMuted,S.currentTarget.style.background=l?`${d.cardBg}ee`:"rgba(255, 255, 255, 0.9)",S.currentTarget.style.borderColor=l?d.cardBorder:"#e5e7eb"},title:"Remove asset",children:"\xD7"})]},`asset-${y}`)}),e.length===0&&a.jsx("div",{style:{marginBottom:r.spacing.md},children:a.jsx(os,{assets:t,selectedAsset:void 0,onAssetSelect:b=>c(b,0),onAmountChange:b=>m(b,0),loading:s,label:"Deposit",showBalance:!0,theme:r,styles:i,allowSecondAsset:o,onAddAsset:p,canAddAsset:!1,resolveMaxAmount:h?b=>h(b,0):void 0},"initial-selector")})]}),id=u.memo(ad);var Uo="data:image/svg+xml,%3csvg width='10' height='10' viewBox='0 0 10 10' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M5 4.99995V6.99995M5 3.31245V3.31189M9.5 5C9.5 7.48528 7.48528 9.5 5 9.5C2.51472 9.5 0.5 7.48528 0.5 5C0.5 2.51472 2.51472 0.5 5 0.5C7.48528 0.5 9.5 2.51472 9.5 5Z' stroke='black' stroke-opacity='0.4' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e";const wa=u.memo(({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,onDepositSelect:s,depositBatches:o,supportedChains:r,title:i,styles:l,onDepositAssetChange:d,assetInputHook:c,externalWalletAddress:m,onDepositAmountChange:p,allowSecondAsset:f=!1,destinationChainId:h,destinationTokenAddress:x,onDepositExecute:b,depositActionLabel:y,nativeChainId:w,sponsorGas:S=!1,preSelectedAsset:v,escrowOnly:k=!1,escrowTokenAddress:C,escrowAmount:E,escrowTokenDecimals:F,escrowTokenSymbol:B,onDepositSuccess:j,onDepositError:T,embeddedWalletAddress:R,onViewAllAssets:D})=>{const M=u.useContext(g.SpiceFlowProviderContext),P=M?.mode||"7702",q=M?.allowedTokens,z=!!M?.isWhitelistGateActive,X=!k&&!!M?.isWhitelistConfigured&&M?.isUserWhitelisted!==!0,N=c?.assetAmount||"",{theme:H,dark:V,appName:G,primaryColor:J,dk:U}=g.useSpiceBrand(l),L=g.useWallet(),{isReady:O,isAuthenticated:ee}=L,{externalWallet:ue}=g.useProviderWallets(),re=M?.embeddedWalletAddress||R,se=P!="7702",ie=se?!!m:O&&ee&&!!re,ce=re,_=m,Ce=ce??_,{data:W}=pn.useWalletClient(),[ae,he]=u.useState(W),ne=u.useRef(null),Q=u.useRef(ue);Q.current=ue;const te=ue?.address;u.useEffect(()=>{const Z=Q.current;if(!Z||!_){ne.current=null,he(W);return}if(Z.address?.toLowerCase()!==_?.toLowerCase()){ne.current=null,he(W);return}Z.getEthereumProvider().then(async le=>{ne.current=le;const We=await le.request({method:"eth_chainId"}),ke=parseInt(We,16),gt=g.getChainConfig(ke),wt=await Z.getWalletClient(ke);he(gt?I.createWalletClient({account:_,chain:gt.viemChain,transport:I.custom(le)}):wt)}).catch(()=>{ne.current=null,he(W)})},[te,_,W]);const be=u.useRef(null),[$,Se]=u.useState([]),{assets:ct,loading:xe,error:pt,refreshAssets:Me}=mn({address:k?ce:_||ce,supportedChains:r,fetchBalances:fn,enabled:e,refreshInterval:e?5e3:0}),Ue=u.useMemo(()=>{if(z)return[];const Z=r.flatMap(le=>g.getAllAssetsForChain(le,ct));return q&&q.length>0?Z.filter(le=>q.includes(le.symbol.toLowerCase())||le.isNative&&q.includes("native")).sort((le,We)=>{const ke=le.balance>BigInt(0)?1:0;return(We.balance>BigInt(0)?1:0)-ke}):Z.filter(le=>le.balance>BigInt(0))},[r,ct,q,z]),Xe=u.useMemo(()=>{if(!$[0]?.asset)return[];const Z=$[0].asset.chainId;return Ue.filter(le=>le.chainId===Z)},[Ue,$]),[Ae,nt]=u.useState(!1),[st,ft]=u.useState(null),ot=u.useRef(T);ot.current=T;const _e=u.useCallback(Z=>{ft(Z),typeof Z=="string"&&Z&&ot.current?.(Z,g.getRelayerErrorDetail(Z))},[]),[Be,Ct]=u.useState("idle"),mt=u.useCallback(Z=>{typeof Z=="string"&&Z&&ot.current?.(Z,g.getRelayerErrorDetail(Z))},[]),[Te,Ke]=u.useState(!1),[Oe,Y]=u.useState(null),[Ee,ye]=u.useState("idle"),[Re,dt]=u.useState(null),[Qe,yt]=u.useState(null),[lt,qt]=u.useState(null),[Lt,Nt]=u.useState(null),[Je,pe]=u.useState(null),{intentStatus:Pe,startStatusPolling:at,clearStatus:ut,execute:ve}=ds(),fe=u.useCallback((Z,le)=>{const We=g.CHAIN_CONFIGS[le];return We?We.supportedTokens?.find(ke=>g.addressesEqual(ke.address,Z))?.symbol??null:null},[]),He=u.useMemo(()=>{const Z=$[0]?.asset;if(!Z||!x||!h)return!1;const le=fe(x,h);return rc(Z.symbol)&&!!le&&ac(le)},[$,x,h,fe]);u.useEffect(()=>{$.length>0&&N!==$[0]?.amount&&Se(Z=>{if(Z.length===0)return Z;const le=[...Z];return le[0]={...le[0],amount:N||""},le})},[N]),u.useEffect(()=>{$.length!==0&&Se(Z=>{let le=!1;const We=Z.map(ke=>{if(!ke.asset)return ke;const gt=Ue.find(wt=>wt.chainId===ke.asset.chainId&&g.addressesEqual(wt.address,ke.asset.address));return gt?gt===ke.asset||gt.balance===ke.asset.balance?ke:(le=!0,{...ke,asset:gt,amount:ke.amount}):ke});return le?We:Z})},[Ue,$.length]),u.useEffect(()=>{if(!v||$.length>0||Ue.length===0)return;const Z=Ue.find(le=>le.chainId===v.chainId&&g.addressesEqual(le.address,v.address));Z&&(Se([{asset:Z,amount:""}]),d?.(Z))},[v,Ue,$.length]);const it=u.useRef(null);u.useEffect(()=>{if(se&&Pe?.overallStatus==="success"&&b&&Be==="idle"){const Z=it.current,le=be.current;Z&&(async()=>{try{Ct("executing"),await b(Z),Ct("success"),Y(Z),Ke(!0);const We=Array.isArray(le)?le[0]:void 0,ke={type:"deposit",status:"success",amount:Z,asset:We?.tokenAddress,sourceChain:We?String(We.chainId):void 0,txHash:We?.txHash};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:ke})),j?.(ke)}catch(We){console.error("onDepositExecute failed:",We),Ct("error"),mt(g.sanitizeError(We,"Post-deposit instruction failed"))}finally{it.current=null,be.current=null}})()}},[Pe?.overallStatus,se,Be]);const Ge=u.useCallback(()=>{_e(null)},[]);u.useEffect(()=>{e||(Ke(!1),Y(null),ye("idle"),dt(null),yt(null))},[e]);const Ie=u.useCallback((Z,le)=>{Se(We=>{const ke=[...We];return ke[le]={asset:Z,amount:ke[le]?.amount||""},ke}),le===0&&d?.(Z),Ge()},[d,Ge]),Et=u.useCallback(async(Z,le)=>{if(Se(We=>{const ke=[...We];return ke[le]&&(ke[le]={...ke[le],amount:Z}),ke}),Ge(),le===0)if(c?.setAssetAmount(Z),He&&Z&&parseFloat(Z)>0)try{const We=lt??await oc();lt||qt(We);const ke=$[0]?.asset;if(!ke)return;const gt=I.parseUnits(Z,ke.decimals),wt=x?fe(x,h):null,Tt=g.CHAIN_CONFIGS[h]?.supportedTokens?.find(At=>g.addressesEqual(At.address,x))?.decimals??6,dn=ic(gt,ke.decimals,Tt,We);Nt(dn);const ln=I.formatUnits(dn,Tt),un=We.toLocaleString("en-US",{maximumFractionDigits:0});pe(`${Z} ${ke.symbol} \u2248 $${parseFloat(ln).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})} ${wt??"USD"} (rate: $${un}/BTC)`),p?.(ln)}catch(We){console.error("Failed to fetch BTC/USD price:",We),pe(null),Nt(null),p?.(Z)}else pe(null),Nt(null),p?.(Z)},[Ge,c,p,He,lt,$,x,h,fe]),De=u.useCallback(()=>{$.length<2&&Se(Z=>[...Z,{asset:null,amount:""}])},[$.length]),bt=u.useCallback(Z=>{Se(le=>le.filter((We,ke)=>ke!==Z)),Ge()},[Ge]),jt=u.useRef(!1),Ht=u.useRef(!1);u.useEffect(()=>{e||(jt.current=!1,Ht.current=!1,Yt(null),Ft(null))},[e]);const[zt,Pt]=u.useState(!1),[$e,et]=u.useState(null),[Rt,Yt]=u.useState(null),[tn,Ft]=u.useState(null),[ge,qe]=u.useState(!1),[xt,Wt]=u.useState(null),Fe=u.useMemo(()=>{const Z=$[0];if($.length!==1||!Z?.asset||!Z.amount||parseFloat(Z.amount)<=0)return null;try{return{asset:Z.asset,amount:I.parseUnits(Z.amount,Z.asset.decimals),token:A.normalizeNativeTokenAddress(Z.asset.address),chainId:Z.asset.chainId}}catch{return null}},[$]),Ut=u.useMemo(()=>Fe?[Fe.chainId,Fe.token.toLowerCase(),Fe.amount.toString(),k?"escrow":"normal"].join("|"):null,[Fe,k]),Ze=u.useCallback(async(Z,le)=>ce?ba({address:ce,depositQuote:Z,escrowOnly:k,signal:le}):null,[ce,k]),Xt=u.useCallback(async Z=>Fe?Ze(Fe,Z):null,[Fe,Ze]),tt=u.useRef(Xt);tt.current=Xt,as({shouldRun:e&&!se&&!!Ut&&!zt&&!Ae,deps:[e,se,Ut,zt,Ae],delayMs:500,backgroundIntervalMs:1e4,onSkip:()=>{Yt(null),Wt(null),qe(!1)},onCleanup:()=>qe(!1),run:async({isBackground:Z,isCurrent:le,signal:We})=>{Z||(Wt(null),qe(!0));try{const ke=await tt.current(We);le()&&Yt(ke)}catch(ke){if(!le())return;Yt(null),Wt(ke instanceof Error?ke.message:"Failed to estimate gas fee")}finally{le()&&qe(!1)}}}),u.useEffect(()=>{zt||Ae||Ft(null)},[zt,Ae,Ut]);const Mt=async()=>{if($.length===0||!$[0]?.asset)return;const Z=$.filter(wt=>wt.asset&&wt.amount&&parseFloat(wt.amount)>0);if(Z.length===0)return;const le=Z[0],We=g.getChainConfig(le.asset.chainId),ke=Z.map(wt=>{const Tt=parseFloat(wt.amount);return`${isNaN(Tt)?wt.amount:Tt.toPrecision(6).replace(/\.?0+$/,"")} ${wt.asset.symbol}`}).join(", "),gt={network:We?.displayName||`Chain ${le.asset.chainId}`,amount:ke,symbol:"",chainId:le.asset.chainId};if(!se&&Z.length===1&&Rt){Ft(Rt);const wt=Z[0];gt.creditedAmount=`${I.formatUnits(Rt.net,wt.asset.decimals)} ${wt.asset.symbol}`,gt.networkFee=`${I.formatUnits(Rt.fee,wt.asset.decimals)} ${wt.asset.symbol}`}et(gt),Pt(!0)},vt=u.useRef(Pe);vt.current=Pe;const Jt=u.useRef(Be);Jt.current=Be;const oe=async()=>{await od({selectedDepositAssets:$,escrowOnly:k,sourceAddress:_,isNon7702:se,address:ce,embeddedWalletAddress:re,isReady:O,isAuthenticated:ee,zeroCreditError:Le,depositBalanceError:nn,externalWalletClient:ae,externalProvider:ne.current,effectiveDepositFee:Ve,depositBatches:o,destinationChainId:h,destinationTokenAddress:x,isCrossDenomination:He,convertedUsdAmount:Lt,mode:P,sponsorGas:S,nativeChainId:w,spiceBalanceUser:Ce,depositDataRef:be,bridgedAmountRef:it,setIsExecuting:nt,setError:_e,setConfirmationData:et,setShowConfirmation:Pt,setDirectDepositStatus:ye,setDirectDepositChainId:yt,setDirectDepositTxHash:dt,setPostDepositStatus:Ct,setPostDepositError:mt,setPostDepositAmount:Y,setPostDepositSuccess:Ke,startStatusPolling:at,clearStatus:ut,refreshAssets:Me,onDepositExecute:b,onDepositSelect:s,onDepositSuccess:j,execution:{execute:ve},getCurrentIntentStatus:()=>vt.current,getCurrentPostDepositStatus:()=>Jt.current})},Le=u.useMemo(()=>{for(const Z of $)if(!(!Z?.asset||!Z.amount||parseFloat(Z.amount)<=0))try{const le=Z.asset.decimals,We=I.parseUnits(Z.amount,le);if(We<=0n)continue;const ke=A.getEquivalenceGroup(A.normalizeNativeTokenAddress(Z.asset.address)),gt=Z.asset.receiptTokenDecimals??(ke==="ETH"||ke==="ARB"?18:ke==="USDC"||ke==="SUSD"||ke==="WBTC"||ke==="CBTC"?6:void 0);if(gt===void 0||le<=gt||A.convertAmountBetweenDecimals(We,le,gt)>0n)continue;return`Amount too small. Minimum deposit for this asset is ${I.formatUnits(10n**BigInt(le-gt),le)} ${Z.asset.symbol}.`}catch{continue}return null},[$]),Ot=!se&&!!Fe,Ve=tn??Rt,kt=!!Fe&&ya(Ve,Fe),nn=u.useMemo(()=>{if(!Ot||!Fe||!kt)return null;const Z=k?Fe.amount:Fe.amount+Ve.fee;return Fe.asset.balance>=Z?null:`Insufficient ${Fe.asset.symbol}. Need ${I.formatUnits(Z,Fe.asset.decimals)} ${Fe.asset.symbol} including gas.`},[Ot,Fe,kt,Ve,k]),[de,me]=u.useState(!1),ze=$[0]?.asset?.chainId,je=ct.find(Z=>Z.isNative&&Z.chainId===ze)?.balance??0n;u.useEffect(()=>{if(!e||!ze){me(!1);return}let Z=!1;return(async()=>{try{const le=await g.getClientForChain(ze).getGasPrice()*150000n;Z||me(je<le)}catch{Z||me(!1)}})(),()=>{Z=!0}},[e,ze,je]);const St=!Ot||kt&&!ge&&!xt&&!nn,Dt=u.useCallback((Z,le)=>rd({asset:Z,assetIndex:le,selectedAssetCount:$.length,address:ce,escrowOnly:k,isNon7702:se}),[se,$.length,ce,k]),Gt=u.useMemo(()=>{if(!Fe||!Ve||!kt)return null;const Z=k?Fe.amount:Fe.amount+Ve.fee;return{symbol:Fe.asset.symbol,decimals:Fe.asset.decimals,grossAmount:Z,netAmount:Ve.net,totalFee:Ve.fee,gasFee:Ve.fee,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"estimated"}},[Fe,Ve,kt,k]),rt=parseFloat($[0]?.amount||"")||0,ht=$.length>0&&$[0]?.asset&&$[0]?.amount&&rt>0&&ie&&!Ae&&!Le&&!nn&&St&&!X;u.useEffect(()=>{if(!k||!C||!E||jt.current||!ie)return;const Z=r[0];if(!Z)return;const le=g.getAllAssetsForChain(Z,[]).find(ke=>g.addressesEqual(ke.address,C));let We;if(le)We=le;else if(F!==void 0&&B)We={address:C,symbol:B,name:B,decimals:F,chainId:Z,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,isNative:A.isNativeToken(C)};else{console.warn("[DepositModal] escrowOnly: no matching asset and missing escrowTokenDecimals/escrowTokenSymbol for",C);return}jt.current=!0,Se([{asset:We,amount:E}])},[k,C,E,F,B,ie,r]),u.useEffect(()=>{!k||!ht||Ht.current||Ae||(Ht.current=!0,oe())},[k,ht,Ae]);const Vt=pt||st||Le||nn,sn=()=>{if(Ae)return"Executing Deposit...";if(!ie)return"Wallet Not Connected";if(P==="7702"){if(!O)return"Loading...";if(!ee)return"Authentication Required"}return $[0]?.asset?$[0]?.amount?Le?"AMOUNT TOO SMALL":nn?"INSUFFICIENT BALANCE":Ot&&!St?xt?"GAS UNAVAILABLE":"ESTIMATING GAS":"DEPOSIT":"ENTER AMOUNT":"SELECT TOKEN"};return e?a.jsx(rn,{isOpen:e,onClose:t,closeOnBackdropClick:n,title:i||`Deposit to your ${G} account`,subtitle:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[a.jsx("img",{src:Uo,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...V?{filter:"invert(0.6)"}:{}}}),a.jsx("p",{style:{fontSize:"12px",color:U.textSecondary,margin:"0",lineHeight:"1.4",fontFamily:g.font.ui},children:`Deposit collateral to your ${G} Account from any supported network.`})]}),dark:V,overlayContent:zt||Pe||Be!=="idle"&&b?a.jsx("div",{}):void 0,styles:l,theme:H,children:a.jsxs("div",{style:{padding:"24px 24px 5px 24px"},children:[a.jsx(id,{selectedDepositAssets:$,depositAssets:Ue,secondAssetOptions:Xe,loadingAssets:xe,allowSecondAsset:f,theme:H,styles:l,dark:V,dk:U,onSelect:Ie,onAmountChange:Et,onAdd:De,onRemove:bt,resolveMaxAmount:Dt,onViewAllAssets:D}),Ot&&Fe&&a.jsx(Do,{fontFamily:l?.fontFamily||H.typography.fontFamily,textPrimary:U.textPrimary,textSecondary:U.textSecondary,cardBg:V?U.inputBg:"#ffffff",cardBorder:U.cardBorder,resolvedDark:V,darkCardBorder:U.cardBorder,primaryColor:J,feePreview:Gt,isLoading:ge||Ot&&!kt,errorText:xt}),a.jsx($c,{intentStatus:Pe,postDepositSuccess:Te,postDepositAmount:Oe,postDepositStatus:Be,depositActionLabel:y,sourceChainName:$[0]?.asset?.chainId?g.getChainName($[0].asset.chainId):"Destination Chain",directDepositStatus:Ee,directDepositTxHash:Re,directDepositChainId:Qe,styles:l}),a.jsx(Jc,{isOpen:zt||!!Pe||Be!=="idle"&&!!b,onClose:()=>{Pt(!1),Pe&&ut();const Z=Be==="success"&&!Pe,le=Pe?.overallStatus==="success"&&(b?Be==="success":!0);(Z||le)&&t()},onConfirm:oe,data:$e,isExecuting:Ae,error:st,theme:H,styles:l,intentStatus:Pe,postDepositStatus:Be,hasPostDepositInstruction:!!b}),Je&&a.jsxs(Gr,{dk:U,dark:V,borderRadius:H.borderRadius.md,children:["\u26A1 ",Je]}),de&&a.jsx(Gr,{dk:U,dark:V,borderRadius:H.borderRadius.md,children:"Low native balance in the external wallet. The deposit to spicenet account might fail."}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:0,marginBottom:0,margin:0,padding:0},children:[Vt?a.jsx("div",{style:{marginBottom:"10px",fontSize:"12px",lineHeight:"1.45",color:U.errorText,fontFamily:l?.fontFamily||H.typography.fontFamily},children:Vt}):null,a.jsx(g.Button,{variant:"outline",fullWidth:!0,onClick:Mt,disabled:!ht||!ie||Ae,theme:H,dark:V,styles:l,children:sn()})]})]})}):null}),ld=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,deposits:s,onComplete:o,onCancel:r,onSkip:i,onChangeWallet:l,isProcessing:d,error:c,styles:m})=>{const{dark:p,dk:f,theme:h}=g.useSpiceBrand(m);if(!e||s.length===0)return null;const x=s[0],b=m?.fontFamily||g.font.ui,y=g.font.mono,w=g.getChainName(x.chainId),S=parseFloat(x.amount).toPrecision(6).replace(/\.?0+$/,""),v=I.formatUnits(x.verifiedBalance,x.tokenDecimals);return a.jsx(rn,{isOpen:e,onClose:t,title:"Incomplete Deposit",styles:m,closeOnBackdropClick:n,children:a.jsxs("div",{style:{padding:"18px 24px 24px",fontFamily:b},children:[a.jsx("p",{style:{fontSize:"14px",color:f.textSecondary,lineHeight:"1.6",margin:"0 0 18px 0"},children:"Your funds reached your wallet, but the deposit didn't finish."}),a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"14px 18px",marginBottom:"24px",padding:"16px 18px",backgroundColor:p?f.cardBg:"#f8fafc",border:`1px solid ${f.cardBorder}`,borderRadius:p?"14px":"10px",boxShadow:p?"inset 0 1px 0 rgba(255,255,255,0.03)":"0 1px 2px rgba(16,24,40,0.04)"},children:[a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[a.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:f.textSecondary,fontFamily:y,letterSpacing:"0.8px"},children:"NETWORK"}),a.jsx("span",{style:{fontSize:"18px",fontWeight:600,color:f.textPrimary,fontFamily:b,lineHeight:1.2},children:w})]}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px",alignItems:"flex-end",textAlign:"right"},children:[a.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:f.textSecondary,fontFamily:y,letterSpacing:"0.8px"},children:"DEPOSITED AMOUNT"}),a.jsxs("span",{style:{fontSize:"24px",fontWeight:700,color:f.successText,fontFamily:y,lineHeight:1.1},children:[S," ",x.tokenSymbol]}),a.jsx("span",{style:{fontSize:"12px",color:f.textSecondary,fontWeight:500,fontFamily:b},children:"Sent to embedded wallet"})]})]}),!x.hasFullBalance&&x.verifiedBalance>0n&&a.jsxs("div",{style:{marginBottom:"16px",padding:"8px 12px",backgroundColor:f.warningBg,border:`1px solid ${p?f.warningBorder:"#fcd34d"}`,borderRadius:"8px",fontSize:"13px",color:f.warningText,lineHeight:"1.4"},children:["Partial balance \u2014 only ",parseFloat(v).toFixed(4)," ",x.tokenSymbol," available."]}),c&&a.jsx("div",{style:{marginBottom:"16px",padding:"10px 12px",backgroundColor:f.errorBg,border:`1px solid ${p?f.errorBorder:"#fca5a5"}`,borderRadius:"8px",fontSize:"13px",color:p?f.errorText:"#991b1b",lineHeight:"1.4"},children:c}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[a.jsx(g.Button,{variant:"outline",fullWidth:!0,disabled:d,onClick:()=>o(x),theme:h,dark:p,styles:m,children:"CONFIRM DEPOSIT"}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[a.jsx(g.Button,{variant:"ghost",fullWidth:!0,disabled:d,onClick:()=>r(x),theme:h,dark:p,style:{height:"48px",fontSize:"13px",letterSpacing:"0.4px",color:p?f.textPrimary:"#374151",border:`1px solid ${p?f.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:p?"rgba(255,255,255,0.02)":"#ffffff"},children:d?"RETURNING...":"RETURN FUNDS"}),a.jsxs("div",{style:{display:"grid",gridTemplateColumns:l?"1fr 1fr":"1fr",gap:"10px"},children:[a.jsx(g.Button,{variant:"ghost",fullWidth:!0,disabled:d,onClick:i,theme:h,dark:p,style:{height:"44px",fontSize:"12px",letterSpacing:"0.4px",color:f.textSecondary,border:`1px solid ${p?f.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:"transparent"},children:"START OVER"}),l&&a.jsx(g.Button,{variant:"ghost",fullWidth:!0,disabled:d,onClick:l,theme:h,dark:p,style:{height:"44px",fontSize:"12px",letterSpacing:"0.4px",color:f.textSecondary,border:`1px solid ${p?f.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:"transparent"},children:"CHANGE WALLET"})]})]})]}),s.length>1&&a.jsxs("p",{style:{fontSize:"12px",color:f.textSecondary,textAlign:"center",marginTop:"14px",marginBottom:0,lineHeight:"1.5"},children:[s.length," incomplete deposits found \u2014 resolving one at a time."]})]})})},cd=[{source:"wallet",title:"From Wallet",description:"Deposit crypto you already hold in a connected wallet"},{source:"card",title:"With Card",description:"Buy and deposit using a debit or credit card"},{source:"exchange",title:"From Exchange",description:"Transfer from Coinbase, Binance, or any exchange"}],dd=({isOpen:e,onClose:t,closeOnBackdropClick:n,onSelect:s,styles:o})=>{const{dark:r,dk:i}=g.useSpiceBrand(o),[l,d]=u.useState(null);return a.jsx(rn,{isOpen:e,onClose:t,title:"Deposit",subtitle:"Choose how you want to add funds",styles:o,dark:r,closeOnBackdropClick:n,children:a.jsx("div",{style:{padding:"0 24px 25px",display:"flex",flexDirection:"column",gap:"12px",marginTop:"20px"},children:cd.map(({source:c,title:m,description:p})=>a.jsxs("button",{onClick:()=>s(c),onMouseEnter:()=>d(c),onMouseLeave:()=>d(null),style:{width:"100%",display:"flex",flexDirection:"column",alignItems:"flex-start",gap:"4px",padding:"14px 16px",borderRadius:"8px",border:`1px solid ${r?i.cardBorder:"#e5e7eb"}`,backgroundColor:l===c?r?i.hoverBg:"#f9fafb":r?i.cardBg:"white",cursor:"pointer",textAlign:"left",transition:g.transition.color},children:[a.jsx("span",{style:{fontSize:"15px",fontWeight:600,fontFamily:g.font.ui,color:r?i.textPrimary:"#111827"},children:m}),a.jsx("span",{style:{fontSize:"13px",fontFamily:g.font.ui,color:r?i.textSecondary:"#6b7280"},children:p})]},c))})})},ud=({isOpen:e,onClose:t,onBack:n,closeOnBackdropClick:s,source:o,destinationChainId:r,onShowWidget:i,onHideWidget:l,verifying:d,verifyError:c,onRetryVerify:m,funded:p,styles:f})=>{const{dark:h,dk:x,primaryColor:b,theme:y}=g.useSpiceBrand(f),w=g.getChainName(r),S=u.useRef(null),v=u.useRef(i);v.current=i;const k=u.useRef(l);k.current=l;const C=d||!!c||!!p;return u.useEffect(()=>{if(!e)return;const E=S.current;if(E){if(C){k.current();return}return v.current(E,o),()=>k.current()}},[e,o,C]),a.jsx(rn,{isOpen:e,onClose:t,title:o==="card"?"Deposit with Card":"Deposit from Exchange",styles:f,dark:h,closeOnBackdropClick:s,children:a.jsxs("div",{style:{padding:"0 24px 25px",display:"flex",flexDirection:"column",gap:"12px",marginTop:"12px"},children:[a.jsx("button",{onClick:n,disabled:d,style:{alignSelf:"flex-start",padding:0,border:"none",background:"none",fontSize:"13px",fontFamily:g.font.ui,color:h?x.textSecondary:"#6b7280",cursor:d?"default":"pointer",opacity:d?.5:1},children:"\u2190 Back"}),a.jsxs("div",{style:{position:"relative",width:"100%"},children:[a.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center"},children:a.jsx(g.Spinner,{size:28,color:b})}),a.jsx("div",{ref:S,style:{position:"relative",width:"100%",height:"560px"}}),C&&a.jsx("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"16px",padding:"24px",borderRadius:"9px",backgroundColor:h?"rgba(0, 0, 0, 0.82)":"rgba(255, 255, 255, 0.94)"},children:d?a.jsxs(a.Fragment,{children:[a.jsx(g.Spinner,{size:28,color:b}),a.jsxs("p",{style:{margin:0,fontSize:"14px",fontFamily:g.font.ui,color:h?x.textPrimary:"#111827",textAlign:"center"},children:["Confirming your deposit arrived on ",w,"\u2026"]})]}):p?a.jsxs(a.Fragment,{children:[a.jsxs("p",{style:{margin:0,fontSize:"14px",fontFamily:g.font.ui,color:h?x.textPrimary:"#111827",textAlign:"center"},children:[p.amount," ",p.symbol," is in your wallet on"," ",w,"."]}),a.jsx(g.Button,{variant:"outline",onClick:t,theme:y,dark:h,styles:f,children:"DONE"})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{style:{margin:0,fontSize:"14px",fontFamily:g.font.ui,color:h?x.textPrimary:"#111827",textAlign:"center"},children:c}),a.jsx(g.Button,{variant:"outline",onClick:m,theme:y,dark:h,styles:f,children:"RETRY"}),a.jsx("button",{onClick:t,style:{padding:0,border:"none",background:"none",fontSize:"13px",fontFamily:g.font.ui,color:h?x.textSecondary:"#6b7280",cursor:"pointer",textDecoration:"underline"},children:"Close \u2014 we'll detect your funds later"})]})})]})]})})},pd="692fb8af264069ca12a9",Vn=42161,fd=[8453,Vn];function md(e){const{targetKind:t,appChainId:n}=e;return t!=="external"||n===void 0||!fd.includes(n)?Vn:A.getTokenBySymbol("USDC",n)?n:Vn}function Os(e=Vn){return A.getTokenBySymbol("USDC",e)}function hd(e){const t=e?.integratorId??pd;return{integratorId:t,enabled:e?.enabled===!0&&t!=="",embedFactory:e?.embedFactory}}const gd=e=>import("@swapper-finance/deposit-sdk").then(t=>new t.SwapperEmbed(e));function xd(e,t,n){return{themeMode:t?"dark":"light",componentStyles:{width:"100%",primaryColor:n,accentColor:n,borderRadius:"9px",...t?{backgroundColor:e.shell,surfaceColor:e.cardBg,surfaceAltColor:e.inputBg,textColor:e.textPrimary,border:`1px solid ${e.cardBorder}`}:{}}}}function Ca(e){return e==="card"?["depositWithCash"]:e==="exchange"?["transferCrypto"]:["depositWithCash","transferCrypto"]}function yd(e){const t=e.destinationChainId??Vn,n=Os(t);if(!n)throw new Error("USDC is not configured for the Swapper destination chain");return{iframeUrl:"https://swapper-deposit-sdk.web.app/",integratorId:e.integratorId,dstChainId:String(t),dstTokenAddr:n.address,depositWalletAddress:e.depositWalletAddress,supportedDepositOptions:Ca(e.source),styles:e.styles,actionLabel:"deposit",flexibleHeight:!0,iframeAttributes:{borderRadius:"9px"}}}async function va(e,t=Vn){const n=Os(t);if(!n)throw new Error("USDC is not configured for the Swapper destination chain");return g.getClientForChain(t).readContract({address:n.address,abi:I.erc20Abi,functionName:"balanceOf",args:[e]})}async function bd(e,t,n){const s=n?.timeoutMs??12e4,o=n?.intervalMs??3e3,r=Date.now()+s;for(;Date.now()<r;){if(n?.signal?.aborted)return null;try{const i=await va(e,n?.chainId);if(i>t)return i}catch{}await new Promise(i=>setTimeout(i,o))}return null}const Lo=e=>{const[t,n]=u.useState(!1),s=u.useContext(g.SpiceFlowProviderContext),{dark:o,dk:r}=g.useSpiceBrand();if(u.useEffect(()=>{n(!0)},[]),!t)return a.jsx("div",{className:e.className,children:a.jsx("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:o?r.hoverBg:"#ccc",color:o?r.textSecondary:"white",border:o?`1px solid ${r.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!s){const i='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return a.jsx("div",{className:e.className,children:a.jsx("button",{onClick:()=>{e.onAuthError&&e.onAuthError(i)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:o?r.errorBg:"#dc2626",color:o?r.errorText:"white",border:o?`1px solid ${r.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return a.jsx(g.PrivyLogin,{...e})},wd=.01,Cd=5*60*1e3;function vd(e){const t=Number(I.formatUnits(e.verifiedBalance,e.tokenDecimals));return Number.isFinite(t)?t:0}async function kd(e){const t=Sd(e);let n;try{n=await yo(t.map(s=>s.tokenSymbol))}catch{return t}return t.filter(s=>{const o=vd(s);if(o<=0)return!0;const r=n[s.tokenSymbol.toUpperCase()]??0;return!Number.isFinite(r)||r<=0?!0:o*r>=wd})}function Sd(e){const t=new Map;for(const n of e){const s=`${n.chainId}:${n.tokenAddress.toLowerCase()}`;t.get(s)||t.set(s,{...n,amount:n.timestamp===0?I.formatUnits(n.verifiedBalance,n.tokenDecimals):n.amount,rawAmount:n.timestamp===0?n.verifiedBalance.toString():n.rawAmount,hasFullBalance:n.timestamp===0?!0:n.hasFullBalance})}return Array.from(t.values())}function ka(e,t){const[n,s]=u.useState([]),[o,r]=u.useState(!1),i=u.useRef(t);i.current=t;const l=u.useRef(0),d=u.useRef(0),c=u.useCallback(async({forceDiscovery:m=!1}={})=>{if(!e){s([]),r(!1);return}const p=++d.current,f=()=>p!==d.current;r(!0);try{const h=[],x=td(e);for(const S of x){if(f())return;try{const v=g.getClientForChain(S.chainId);let k;if(S.isNative||A.isNativeToken(S.tokenAddress)?k=await on.getBalance(v,{address:e}):k=await on.readContract(v,{address:I.getAddress(S.tokenAddress),abi:I.erc20Abi,functionName:"balanceOf",args:[e]}),f())return;k>0n?h.push({...S,verifiedBalance:k,hasFullBalance:k>=BigInt(S.rawAmount)}):Date.now()-S.timestamp>15*60*1e3&&Po(e,S.chainId,S.tokenAddress)}catch(v){console.warn(`[usePendingDeposit] Failed to verify balance for ${S.tokenSymbol} on chain ${S.chainId}:`,v),h.push({...S,verifiedBalance:0n,hasFullBalance:!1})}}if(f())return;const b=i.current,y=Date.now(),w=(b?.discoverWalletBalances??!0)&&(m||y-l.current>=Cd);if(b?.network&&w){l.current=y;const S=b.chainIds??A.getChainIdsByNetwork(b.network),v=new Set(h.map(C=>`${C.chainId}:${C.tokenAddress.toLowerCase()}`)),k=[];for(const C of S){const E=g.getChainConfig(C);if(E?.supportedTokens)for(const F of E.supportedTokens){if(A.isNativeToken(F.address))continue;const B=`${C}:${F.address.toLowerCase()}`;v.has(B)||k.push((async()=>{try{const j=g.getClientForChain(C),T=await on.readContract(j,{address:I.getAddress(F.address),abi:I.erc20Abi,functionName:"balanceOf",args:[e]});return T>0n?{chainId:C,tokenAddress:F.address,tokenSymbol:F.symbol,tokenDecimals:F.decimals,amount:I.formatUnits(T,F.decimals),rawAmount:T.toString(),embeddedWalletAddress:e,externalWalletAddress:"",timestamp:0,isNative:!1,verifiedBalance:T,hasFullBalance:!0}:null}catch{return null}})())}}if(k.length>0){const C=await Promise.allSettled(k);if(f())return;for(const E of C)E.status==="fulfilled"&&E.value&&h.push(E.value)}}if(!f()){const S=await kd(h);if(f())return;s(S)}}catch(h){console.error("[usePendingDeposit] Verification error:",h),f()||s([])}finally{f()||r(!1)}},[e]);return u.useEffect(()=>{if(!i.current?.enabled){d.current++,s([]),r(!1);return}c({forceDiscovery:!0});const m=i.current?.pollIntervalMs??3e4;if(m<=0||!e)return()=>{d.current++};const p=setInterval(()=>{c({forceDiscovery:!1})},m),f=()=>c({forceDiscovery:!0});return window.addEventListener(Ms,f),()=>{d.current++,window.removeEventListener(Ms,f),clearInterval(p)}},[c,e]),{pendingDeposits:n,loading:o,refresh:()=>c({forceDiscovery:!0})}}function Ad({enabled:e,integratorId:t,depositWalletAddress:n,destinationChainId:s,brand:o,embedFactory:r,onTransactionSuccess:i,onCloseRequest:l}){const d=u.useRef(null),c=u.useRef(null),m=u.useRef(i);m.current=i;const p=u.useRef(l);p.current=l;const f=u.useRef(o);f.current=o;const h=u.useRef(r);h.current=r;const x=u.useCallback((w,S,v)=>{if(!S.isConnected)return;const k=w.getIframe();k.updateConfig({supportedDepositOptions:Ca(v)}),k.sendConfig(),w.showIn(S)},[]);u.useEffect(()=>{if(!e||!n)return;let w=!1;return Promise.resolve().then(()=>{const{dk:S,dark:v,primaryColor:k}=f.current;return(h.current??gd)(yd({integratorId:t,depositWalletAddress:n,destinationChainId:s,source:null,styles:xd(S,v,k)}))}).then(S=>{if(w){S.destroy();return}const v=S.getIframe();v.on("transaction_success",C=>m.current(C)),v.on("close_request",()=>p.current()),d.current=S;const k=c.current;k&&x(S,k.placeholder,k.source)}).catch(S=>{console.error("[useSwapperEmbed] Failed to preload Swapper widget:",S)}),()=>{w=!0,c.current=null,d.current?.destroy(),d.current=null}},[e,t,n,s,x]);const b=u.useCallback((w,S)=>{c.current={placeholder:w,source:S};const v=d.current;v&&x(v,w,S)},[x]),y=u.useCallback(()=>{c.current=null,d.current?.hide()},[]);return{showWidget:b,hideWidget:y}}function Id(e,t,n,s,o){return{address:t,symbol:n||"UNKNOWN",name:n||"Unknown Token",decimals:s||18,chainId:e,balance:0n,balanceFormatted:o?parseFloat(o):0,balanceUsd:0,isNative:A.isNativeToken(t)}}function Ed(e,t){const n=e?.data;if(!n||typeof n!="object")return null;const s=n;if(s.__spiceflowPlaygroundMock!==!0)return null;try{if(typeof s.amountReceivedRaw=="string")return BigInt(s.amountReceivedRaw);if(typeof s.amountReceived=="string"||typeof s.amountReceived=="number")return I.parseUnits(String(s.amountReceived),t)}catch{return null}return null}const Fd=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:s,depositBatches:o,onDepositAmountChange:r,destinationChainId:i,destinationTokenAddress:l,onDepositExecute:d,depositActionLabel:c,sponsorGas:m=!1,escrowRecovery:p,skipTokenSelection:f=!1,onDepositSuccess:h,onDepositError:x,skipRecovery:b=!1})=>{const y=u.useContext(g.SpiceFlowProviderContext);if(!y)return a.jsx("div",{children:"Error: SpiceDeposit must be used within SpiceFlowProvider"});const w=(y.mode||"7702")!="7702",S=w,v=y.nativeChainId,k=y.network||"testnet",{dark:C,dk:E,primaryColor:F}=g.useSpiceBrand(s),B=!!p,j=g.useWallet(),{isReady:T,isAuthenticated:R,actions:D}=j,M=y?.embeddedWalletAddress,{address:P}=pn.useAccount(),q=y?.externalWalletAddress??P,z=!!q,X=hd(y.swapper),N=S?{address:q,kind:"external"}:{address:M,kind:"embedded"},H=md({targetKind:N.kind,appChainId:i||v}),V=X.enabled&&!B&&k==="mainnet"&&!!Os(H),G=()=>f?"deposit":"select-token",J=()=>V?"select-source":S?z?G():"connect-wallet":"provider-login",[U,L]=u.useState(J()),[O,ee]=u.useState(null),[ue,re]=u.useState(!1),[se,ie]=u.useState(null),[ce,_]=u.useState(!1),[Ce,W]=u.useState(null),[ae,he]=u.useState(null),[ne,Q]=u.useState(null),te=u.useRef(null),be=u.useRef(null),{pendingDeposits:$,loading:Se,refresh:ct}=ka(M,{enabled:e,network:k,chainIds:y.supportedChainIds}),[xe,pt]=u.useState(null),[Me,Ue]=u.useState(!1),[Xe,Ae]=u.useState(null),[nt,st]=u.useState(!1),[ft,ot]=u.useState("idle");u.useEffect(()=>{e&&!b&&!B&&!xe&&!nt&&ft==="idle"&&R&&M&&z&&q&&!Se&&$.length>0&&U!=="recovery"&&U!=="deposit"&&U!=="swapper"&&L("recovery")},[e,b,B,R,M,z,q,Se,$,U,xe,nt,ft]);const _e=u.useCallback(pe=>{const Pe={address:pe.tokenAddress,symbol:pe.tokenSymbol,name:pe.tokenSymbol,decimals:pe.tokenDecimals,chainId:pe.chainId,balance:pe.verifiedBalance,balanceFormatted:parseFloat(pe.amount),balanceUsd:0,isNative:pe.isNative};ee(Pe),pt(pe),L("deposit")},[]),Be=u.useCallback(pe=>{if(ie(pe),S){L(z?pe==="wallet"?G():"swapper":"connect-wallet");return}const Pe=R&&!!M;L(pe==="wallet"?Pe?z?G():"connect-wallet":"provider-login":Pe?"swapper":"provider-login")},[S,R,M,z,f]),Ct=u.useCallback(()=>{be.current?.abort(),_(!1),W(null),he(null),ie(null),te.current=null,Q(null),L("select-source")},[]);u.useEffect(()=>{U==="swapper"&&(ne||!N.address||Q({address:N.address,kind:N.kind}))},[U,ne,N.address,N.kind]);const mt=ne??N,Te=mt.address,Ke=mt.kind,Oe=u.useCallback(async pe=>{if(!Te)return;be.current?.abort();const Pe=new AbortController;be.current=Pe,W(null),_(!0);const at=Os(H);if(!at){_(!1);return}const ut=He=>{_(!1);const it=I.formatUnits(He,at.decimals);if(Ke==="external"){he({amount:it,symbol:at.symbol});const Ge={type:"wallet-funding",status:"success",amount:it,asset:at.address,sourceChain:String(H)};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:Ge})),h?.(Ge);return}_e({chainId:H,tokenAddress:at.address,tokenSymbol:at.symbol,tokenDecimals:at.decimals,amount:it,rawAmount:He.toString(),embeddedWalletAddress:Te,externalWalletAddress:"",timestamp:0,isNative:!1,verifiedBalance:He,hasFullBalance:!0})},ve=Ed(pe,at.decimals);if(ve!==null){ut(ve);return}const fe=await bd(Te,te.current??0n,{signal:Pe.signal,chainId:H});if(!Pe.signal.aborted){if(fe===null){_(!1);const He=g.getChainConfig(H)?.viemChain?.name??`chain ${H}`;W(`We haven't seen your funds arrive on ${He} yet \u2014 they may still be in transit.`);return}ut(fe)}},[Te,Ke,H,_e,h]);u.useEffect(()=>{if(U!=="swapper"||!Te||te.current!==null)return;let pe=!1;return va(Te,H).then(Pe=>{pe||(te.current=Pe)}).catch(()=>{pe||(te.current=0n)}),()=>{pe=!0}},[U,Te,H]);const{showWidget:Y,hideWidget:Ee}=Ad({enabled:e&&V,integratorId:X.integratorId,depositWalletAddress:Te,destinationChainId:H,brand:{dk:E,dark:C,primaryColor:F},embedFactory:X.embedFactory,onTransactionSuccess:Oe,onCloseRequest:()=>{ce||Ct()}}),ye=u.useCallback(()=>{st(!0),L(R&&M&&z&&q?f?"deposit":"select-token":R&&M?"connect-wallet":"provider-login")},[R,M,z,q,f]),Re=u.useCallback(()=>{Ae(null),ot("awaiting-disconnect"),L("connect-wallet")},[]),dt=u.useCallback(async pe=>{Ue(!0),Ae(null);try{if(!M)throw new Error("Embedded wallet not available");const Pe=await D.getEthereumProvider(),at=g.getChainConfig(pe.chainId);await g.ensureWalletOnChain(Pe,pe.chainId);const ut=g.getClientForChain(pe.chainId),ve=await on.getBalance(ut,{address:M}),fe=at?.viemChain?.name||`chain ${pe.chainId}`;if(ve===0n)throw new Error(`Your embedded wallet has no ETH on ${fe} to pay for gas. We recommend completing the deposit instead \u2014 it doesn't require gas.`);const He=I.createWalletClient({account:M,transport:I.custom(Pe),chain:at?.viemChain}),it=pe.externalWalletAddress&&I.isAddress(pe.externalWalletAddress)?pe.externalWalletAddress:q;if(!it||!I.isAddress(it))throw new Error("Connect the external wallet that should receive these funds, then try again.");let Ge;pe.isNative||A.isNativeToken(pe.tokenAddress)?Ge=await He.sendTransaction({to:it,value:pe.verifiedBalance,chain:at?.viemChain}):Ge=await He.sendTransaction({to:pe.tokenAddress,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[it,pe.verifiedBalance]}),chain:at?.viemChain}),await ut.waitForTransactionReceipt({hash:Ge,confirmations:1}),Po(pe.embeddedWalletAddress,pe.chainId,pe.tokenAddress),ct(),$.length<=1&&L(J())}catch(Pe){const at=Pe?.message||"Couldn't return your funds. Please try again.",ut=/insufficient funds for gas/i.test(at);Ae(ut?"Not enough ETH in your embedded wallet to cover gas fees. Complete the deposit instead \u2014 it doesn't require gas.":at)}finally{Ue(!1)}},[D,M,q,$,ct]);u.useEffect(()=>{e||(pt(null),Ae(null),Ue(!1),st(!1),ot("idle"),be.current?.abort(),ie(null),_(!1),W(null),he(null),te.current=null,Q(null))},[e]),u.useEffect(()=>{if(ft!=="idle"){if(ft==="awaiting-disconnect"){(!z||!q)&&ot("awaiting-reconnect");return}e&&!Se&&$.length>0&&R&&M&&(ot("idle"),L("recovery"))}},[ft,z,q,e,Se,$,R,M]),u.useEffect(()=>{!B||!e||(R&&M?(re(!0),!O&&p?.chainId&&p?.tokenAddress&&ee(Id(p.chainId,p.tokenAddress,p.tokenSymbol,p.tokenDecimals,p.amount)),L("deposit")):L("provider-login"))},[B,e,U,R,M]);const{assets:Qe,loading:yt}=mn({address:q,supportedChains:y.supportedChainIds,fetchBalances:fn,enabled:e&&!!q,refreshInterval:e?5e3:0}),lt=u.useCallback(()=>{re(!0),L(B?"deposit":se==="card"||se==="exchange"?"swapper":z?f?"deposit":"select-token":"connect-wallet")},[B,se,z,f]),qt=u.useCallback(async()=>{if((!z||!q)&&(await hn(500),!z||!q)){alert("Please connect your wallet first");return}L(f?"deposit":"select-token")},[z,q,f]),Lt=u.useCallback(pe=>{ee(pe),L("deposit")},[]),Nt=u.useCallback(()=>{if(ee(null),r?.(""),!q){L("connect-wallet");return}L("select-token")},[q,r]),Je=u.useCallback(()=>{t()},[t]);if(u.useEffect(()=>{if(!e){const pe=setTimeout(()=>{B||(L(J()),ee(null)),re(!1)},300);return()=>clearTimeout(pe)}},[e,B,p?.chainId]),u.useEffect(()=>{e&&U==="deposit"&&!O&&!B&&!xe&&!f&&L("select-token")},[e,U,O,B,xe,f]),u.useEffect(()=>{if(e&&U==="connect-wallet"&&z&&q&&ft==="idle"){if(V&&!se){L("select-source");return}if(V&&se&&se!=="wallet"){L("swapper");return}L(f?"deposit":"select-token")}},[e,U,z,q,ft,f,V,se]),u.useEffect(()=>{if(!S&&e&&U==="provider-login"&&T&&R&&M&&!ue){const pe=setTimeout(()=>{re(!0),L(se==="card"||se==="exchange"?"swapper":z?f?"deposit":"select-token":"connect-wallet")},100);return()=>clearTimeout(pe)}},[S,e,U,T,R,M,se,z,f,ue]),!e)return null;if(U==="recovery")return a.jsx(ld,{isOpen:e,onClose:Je,closeOnBackdropClick:n,deposits:$,onComplete:_e,onCancel:dt,onSkip:ye,onChangeWallet:Re,isProcessing:Me,error:Xe,styles:s});if(U==="select-source")return V?a.jsx(dd,{isOpen:e,onClose:Je,closeOnBackdropClick:n,onSelect:Be,styles:s}):(L("provider-login"),null);if(U==="swapper")return se!=="card"&&se!=="exchange"?(L(J()),null):Te?a.jsx(ud,{isOpen:e,onClose:Je,onBack:Ct,closeOnBackdropClick:n,source:se,destinationChainId:H,onShowWidget:Y,onHideWidget:Ee,verifying:ce,verifyError:Ce,onRetryVerify:Oe,funded:ae,styles:s}):a.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",zIndex:50},children:a.jsx("div",{style:{backgroundColor:C?E.cardBg:"white",borderRadius:"9px",padding:"32px 24px",maxWidth:"400px",width:"100%",textAlign:"center",fontFamily:'"Helvetica Neue", sans-serif',fontSize:"14px",color:C?E.textPrimary:"#111827"},children:"Preparing your account..."})});if(U==="provider-login"&&!S)return a.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",zIndex:50},children:a.jsx("div",{style:{backgroundColor:C?E.cardBg:"white",borderRadius:"9px",padding:"32px 24px",maxWidth:"400px",width:"100%"},children:a.jsx(Lo,{onAuthSuccess:lt,autoTrigger:!0})})});if(U==="connect-wallet")return a.jsx(gc,{isOpen:e,onClose:Je,closeOnBackdropClick:n,onContinue:qt,requiredChainId:w?v:void 0,styles:s});if(U==="select-token")return q?a.jsx(fc,{isOpen:e,onClose:Je,closeOnBackdropClick:n,onTokenSelect:Lt,walletAddress:q,supportedChainIds:y.supportedChainIds,network:k,prefetchedAssets:yt?null:Qe??null,styles:s,dark:C}):(L("connect-wallet"),null);if(U==="deposit"){if(!O&&!f)return null;const pe=!!xe;return a.jsx(wa,{isOpen:e,onClose:Je,closeOnBackdropClick:n,supportedChains:O?[O.chainId]:y.supportedChainIds??[],styles:s,externalWalletAddress:q,depositBatches:pe?void 0:o,onDepositAmountChange:r,destinationChainId:i,destinationTokenAddress:l,onDepositExecute:d,depositActionLabel:c,nativeChainId:v,sponsorGas:m,preSelectedAsset:O??void 0,escrowOnly:B||pe,escrowTokenAddress:pe?xe.tokenAddress:p?.tokenAddress,escrowAmount:pe?xe.amount:p?.amount,escrowTokenDecimals:pe?xe.tokenDecimals:p?.tokenDecimals,escrowTokenSymbol:pe?xe.tokenSymbol:p?.tokenSymbol,onDepositSuccess:h,onDepositError:x,embeddedWalletAddress:M,onViewAllAssets:f?void 0:Nt})}return null},Td=e=>u.useContext(g.SpiceFlowProviderContext)?a.jsx(Fd,{...e}):a.jsx("div",{children:"Error: SpiceDeposit must be used within SpiceFlowProvider"}),Bd=({isOpen:e,onClose:t,onChainSelect:n,supportedChains:s,closeOnSelect:o=!0,styles:r})=>{const{theme:i,dark:l,primaryColor:d,dk:c}=g.useSpiceBrand(r),[m,p]=u.useState(""),[f,h]=u.useState(null),[x,b]=u.useState(null),[y,w]=u.useState(!1),[S,v]=u.useState(null),{switchChainAsync:k}=pn.useSwitchChain(),C=u.useMemo(()=>new Set(s||[]),[s]),E=u.useMemo(()=>{if(!s||s.length===0)return[];const T=[];return s.forEach((R,D)=>{if(typeof R!="number")return;const M=g.getChainConfig(R);M&&T.push({id:R.toString(),name:M.displayName,icon:Sn[R]||ns,chainId:R,verified:!0,order:D})}),T},[s]);u.useEffect(()=>{f&&!C.has(parseInt(f,10))&&h(null)},[f,C]);const F=u.useMemo(()=>E.filter(T=>T.name.toLowerCase().includes(m.toLowerCase())).sort((T,R)=>T.order-R.order),[E,m]),B=async()=>{if(!f)return;const T=parseInt(f,10);w(!0),v(null);try{await k({chainId:T}),n&&n(f),o&&t()}catch(R){console.error("Failed to switch chain:",R),v(g.sanitizeError(R,"Failed to switch chain."))}finally{w(!1)}},j=!f||y;return a.jsxs(rn,{isOpen:e,onClose:t,title:"Select Chain",styles:r,theme:i,dark:l,children:[a.jsx("div",{style:{padding:"24px 20px"},children:a.jsx(co,{value:m,onChange:p,ariaLabel:"Search chains",placeholder:"Search chain name, symbol or address",size:"md",dark:l,styles:r,endAdornment:a.jsx("div",{style:{padding:"5px 5px",borderRadius:"3px",fontSize:"13px",backgroundColor:l?c.cardBg:"#E9E9E9",color:l?c.textSecondary:"#485066",fontWeight:500,flexShrink:0},"aria-hidden":"true",children:"\u2318F"})})}),a.jsx("div",{style:{padding:"0 32px 20px",display:"flex",flexDirection:"column",gap:"12px"},children:F.map(T=>{const R=f===T.id,D=x===T.id;return a.jsxs("button",{onClick:()=>h(T.id),onMouseEnter:()=>b(T.id),onMouseLeave:()=>b(null),style:{width:"100%",display:"flex",alignItems:"center",gap:"16px",padding:"8px",borderRadius:"8px",backgroundColor:R?l?`${d}15`:`${d}12`:"transparent",border:R?l?`1px solid ${d}66`:`1px solid ${d}88`:D?l?`1px solid ${d}44`:`1px solid ${d}66`:"1px solid transparent",cursor:"pointer",transition:g.transition.interactive},children:[a.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"30px"},children:a.jsx("img",{src:T.icon,alt:T.name,loading:"lazy",decoding:"async",style:{width:"100%",height:"100%",borderRadius:"50%"}})}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",flex:1},children:[a.jsx("span",{style:{fontFamily:g.font.mono,fontSize:"17px",fontWeight:500,letterSpacing:"0.4px",color:c.textPrimary,textAlign:"left"},children:T.name}),T.verified&&a.jsx("img",{src:Qr,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:16,height:16,style:{width:"16px",height:"16px",filter:l?"brightness(0) invert(1)":"none"}})]})]},T.id)})}),S&&a.jsx("div",{style:{padding:"0 25px 12px"},children:a.jsx(yn,{variant:"error",size:"compact",palette:c,children:S})}),a.jsx("div",{style:{padding:"0 25px 25px"},children:a.jsxs(g.Button,{variant:"outline",onClick:B,disabled:j,fullWidth:!0,theme:i,styles:r,dark:l,children:["SELECT",a.jsx(Ol,{size:20})]})})]})},jd={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",84532:"0x4200000000000000000000000000000000000006"},Sa=I.parseAbi(["function deposit() payable","function withdraw(uint256 wad)"]);function Ps(e){return g.getChainConfig(e)?.wrappedNativeTokenAddress??jd[e]}const zo=(e,t)=>({to:e,value:t,data:I.encodeFunctionData({abi:Sa,functionName:"deposit"})}),qo=(e,t)=>({to:e,value:0n,data:I.encodeFunctionData({abi:Sa,functionName:"withdraw",args:[t]})});function Ho(e,t,n){const s=A.isNativeToken(t),o=A.isNativeToken(n);if(!s&&!o)return null;const r=Ps(e);return r?{weth:r,wrapIn:s,unwrapOut:o}:null}function Vo(e,t,n){return A.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[n,t]})}}function Aa(e,t,n,s,o,r){const i=Ho(e,t,n);if(!i||s<=0n)return null;const l=i.wrapIn&&g.addressesEqual(n,i.weth),d=i.unwrapOut&&g.addressesEqual(t,i.weth);return!l&&!d?null:[l?zo(i.weth,s):qo(i.weth,s),...g.addressesEqual(r,o)?[]:[Vo(n,s,o)]]}function Rd(e,t){return{...e,resolve:async(n,s,o)=>{const r=t??o,i=Aa(s,n.tokenIn,n.tokenOut,n.amountIn,o,r);if(i)return{venue:"native-wrap",amountOut:n.amountIn,amountOutMinimum:n.amountIn,calls:i};const l=await e.resolve(n,s,o);if(l)return l;const d=Ho(s,n.tokenIn,n.tokenOut);if(!d)return null;const c=await e.resolve({...n,tokenIn:d.wrapIn?d.weth:n.tokenIn,tokenOut:d.unwrapOut?d.weth:n.tokenOut},s,r);return c?{...c,calls:[...d.wrapIn?[zo(d.weth,n.amountIn)]:[],...c.calls,...d.unwrapOut?[qo(d.weth,c.amountOutMinimum)]:[],...g.addressesEqual(r,o)?[]:[Vo(n.tokenOut,c.amountOutMinimum,o)]]}:null}}}function Dd(e,t){return{...e,resolve:async(n,s,o)=>{const r=t??o,i=Aa(s,n.tokenIn,n.tokenOut,n.amountOut,o,r);if(i)return{venue:"native-wrap",amountIn:n.amountOut,amountInMax:n.amountOut,amountOut:n.amountOut,calls:i};const l=await e.resolve(n,s,o);if(l)return l;const d=Ho(s,n.tokenIn,n.tokenOut);if(!d)return null;const c=await e.resolve({...n,tokenIn:d.wrapIn?d.weth:n.tokenIn,tokenOut:d.unwrapOut?d.weth:n.tokenOut},s,r);return c?{...c,calls:[...d.wrapIn?[zo(d.weth,c.amountInMax)]:[],...c.calls,...d.unwrapOut?[qo(d.weth,c.amountOut)]:[],...g.addressesEqual(r,o)?[]:[Vo(n.tokenOut,c.amountOut,o)]]}:null}}}function Nd(e){return{...e,resolve:async(t,n,s)=>{const o=await e.resolve(t,n,s),r=o?.calls[0]?.to;return!o||!r||A.isNativeToken(t.tokenIn)?o:{...o,calls:[{to:t.tokenIn,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"approve",args:[r,o.amountInMax]})},...o.calls]}}}}function Ws(e){const t=(e?.customVenues??[]).map(s=>Dd(Nd(s),e?.executorAddress));async function n(s,o,r){const i=t.filter(c=>c.chainIds.includes(o));if(i.length===0)throw new g.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const l=(await Promise.allSettled(i.map(async c=>({venue:c,quote:await c.resolve(s,o,r)})))).filter(c=>c.status==="fulfilled").map(c=>c.value).filter(c=>c.quote!==null);if(l.length===0)throw new g.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut.toString()});const d=l.find(c=>c.venue.preferred);return d?d.quote:(l.sort((c,m)=>c.quote.amountIn<m.quote.amountIn?-1:c.quote.amountIn>m.quote.amountIn?1:0),l[0].quote)}return{getQuote:n,venues:t}}const Ia=[100,500,3e3,1e4],Ea=(e,t)=>e.toLowerCase()===t.toLowerCase();function Us(e,t,n,s,o){const r=[];for(const i of n)if(!(Ea(i,e)||Ea(i,t)))for(const l of s)for(const d of s)r.push(o==="in"?I.encodePacked(["address","uint24","address","uint24","address"],[e,l,i,d,t]):I.encodePacked(["address","uint24","address","uint24","address"],[t,d,i,l,e]));return r}function Md(e){const t=e.slice(2),n=[];for(let s=0;s<t.length;){const o=n.length%2===0?40:6;n.push(t.slice(s,s+o)),s+=o}return`0x${n.reverse().join("")}`}const Od=I.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),Pd=I.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),Wd=1800;function Fa(e){const{config:t,route:n,tokenIn:s,tokenOut:o,recipient:r,amountOut:i}=e,l=e.amountInMaximum,d=e.routerHasDeadline?Pd:Od,c=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+Wd)}:{},m=n.path?I.encodeFunctionData({abi:d,functionName:"exactOutput",args:[{path:n.path,recipient:r,...c,amountOut:i,amountInMaximum:l}]}):I.encodeFunctionData({abi:d,functionName:"exactOutputSingle",args:[{tokenIn:s,tokenOut:o,fee:n.fee,recipient:r,...c,amountOut:i,amountInMaximum:l,sqrtPriceLimitX96:0n}]});return{to:t.swapRouter,value:0n,data:m}}const Ud=I.parseAbi(["function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)","function quoteExactOutput(bytes path, uint256 amountOut) returns (uint256 amountIn, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]);async function Ls(e,t,n,s,o){const r=g.getClientForChain(e),{result:i}=await r.simulateContract({address:t.quoterV2,abi:Ud,functionName:o==="in"?"quoteExactInput":"quoteExactOutput",args:[n,s]}),[l,,,d]=i;if(l<=0n)throw new Error("No liquidity along this path.");return{amount:l,gasEstimate:d}}async function Ld(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:o,chainId:r,config:i}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const l=(await g.getClientForChain(r).simulateContract({address:i.quoterV2,abi:A.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:o,sqrtPriceLimitX96:0n}]})).result;if(l[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:l[0],sqrtPriceX96After:l[1],gasEstimate:l[3]}}async function Ta(e){const t=e.feeTiers??Ia,n=Us(e.tokenIn,e.tokenOut,e.hubs??[],t,"in"),s=await Promise.allSettled([...t.map(async r=>({...await Ld({...e,fee:r}),fee:r})),...n.map(async r=>{const i=await Ls(e.chainId,e.config,r,e.amountIn,"in");return{amountOut:i.amount,sqrtPriceX96After:0n,gasEstimate:i.gasEstimate,fee:0,path:r}})]);let o=null;for(const r of s)r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o=r.value);if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const zd=[{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 qd(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:o,chainId:r,config:i}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const l=(await g.getClientForChain(r).simulateContract({address:i.quoterV2,abi:zd,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:o,sqrtPriceLimitX96:0n}]})).result;if(l[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:l[0],sqrtPriceX96After:l[1],gasEstimate:l[3]}}async function Ba(e){const t=e.feeTiers??Ia,n=Us(e.tokenIn,e.tokenOut,e.hubs??[],t,"out"),s=await Promise.allSettled([...t.map(async r=>({...await qd({...e,fee:r}),fee:r})),...n.map(async r=>{const i=await Ls(e.chainId,e.config,r,e.amountOut,"out");return{amountIn:i.amount,sqrtPriceX96After:0n,gasEstimate:i.gasEstimate,fee:0,path:r}})]);let o=null;for(const r of s)r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o=r.value);if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const ja=3,Ra=8,Hd=30,Vd=[{name:"quoteExactInput",stateMutability:"nonpayable",inputs:[{name:"path",type:"bytes"},{name:"amountInRequired",type:"uint256"}],outputs:[{name:"amountOutList",type:"uint256[]"},{name:"amountInList",type:"uint256[]"},{name:"sqrtPriceX96AfterList",type:"uint160[]"},{name:"initializedTicksCrossedList",type:"uint32[]"},{name:"gasEstimate",type:"uint256"},{name:"feeList",type:"uint16[]"}],type:"function"}],Qd=[{name:"exactInput",stateMutability:"payable",inputs:[{name:"params",type:"tuple",components:[{name:"path",type:"bytes"},{name:"recipient",type:"address"},{name:"deadline",type:"uint256"},{name:"amountIn",type:"uint256"},{name:"amountOutMinimum",type:"uint256"}]}],outputs:[{name:"amountOut",type:"uint256"}],type:"function"}];function Da(e){const{tokens:t,deployers:n}=e;if(t.length<2||n.length!==t.length-1)throw new Error("Invalid Algebra path");const s=[];for(let o=0;o<t.length;o++)s.push(I.pad(t[o],{size:20})),o<n.length&&s.push(I.pad(n[o],{size:20}));return I.concat(s)}async function Kd(e,t){const n=t.toLowerCase(),s=`{ pools(first: 500, where: { or: [ { token0: "${n}" }, { token1: "${n}" } ] }) { deployer token0 { id } token1 { id } } }`,o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:s})});if(!o.ok)throw new Error(`Algebra subgraph returned ${o.status}`);const r=await o.json();if(r.errors||!r.data?.pools)throw new Error("Algebra subgraph query failed");const i=new Map;for(const l of r.data.pools){const d=l.token0.id.toLowerCase(),c=l.token1.id.toLowerCase(),m={token:d===n?c:d,deployer:l.deployer.toLowerCase()};i.set(`${m.token}:${m.deployer}`,m)}return Array.from(i.values())}async function Yd(e,t,n){const s=t.toLowerCase(),o=n.toLowerCase(),r=new Map,i=async c=>{const m=r.get(c);if(m)return m;if(r.size>=Hd)return[];const p=await Kd(e,c);return r.set(c,p),p},l=[],d=[{tokens:[s],deployers:[]}];for(;d.length>0&&l.length<Ra;){const c=d.shift();if(c.tokens.length-1>=ja)continue;const m=c.tokens[c.tokens.length-1];for(const p of await i(m)){if(c.tokens.includes(p.token))continue;const f={tokens:[...c.tokens,p.token],deployers:[...c.deployers,p.deployer]};if(p.token===o){if(l.push(f),l.length>=Ra)break}else c.tokens.length-1<ja-1&&d.push(f)}}return l}async function Gd(e,t,n,s){const o=g.getClientForChain(t),{result:r}=await o.simulateContract({address:e,abi:Vd,functionName:"quoteExactInput",args:[Da(n),s]}),i=r[0],l=i[i.length-1]??0n;if(l<=0n)throw new Error("Algebra quote returned zero output");return l}async function Zd(e){const{tokenIn:t,tokenOut:n,amountIn:s,chainId:o,config:r}=e,i=await Yd(r.subgraphUrl,t,n),l=await Promise.allSettled(i.map(async c=>({path:c,amountOut:await Gd(r.quoterV2,o,c,s)})));let d=null;for(const c of l)c.status==="fulfilled"&&(!d||c.value.amountOut>d.amountOut)&&(d=c.value);return d}function Xd(e){return e.type==="swap"}const Qn=.02,Jd=[1,8453,42161,10,137,43114,56],Na="https://api.1inch.dev/swap/v6.0";function zs(e,t){return A.applySlippage(e,t)}function $d(e){const t=e?.baseUrl??Na;return{name:"1inch",chainIds:e?.chainIds??Jd,resolve:async(n,s,o)=>{const r=n.maxSlippage??Qn,i=r*100,l=A.isNativeToken(n.tokenIn)?A.NATIVE_TOKEN_ADDRESS:n.tokenIn,d=A.isNativeToken(n.tokenOut)?A.NATIVE_TOKEN_ADDRESS:n.tokenOut,c=A.isNativeToken(n.tokenIn);try{const m=new URL(`${t}/${s}/swap`);m.searchParams.set("src",l),m.searchParams.set("dst",d),m.searchParams.set("amount",n.amountIn.toString()),m.searchParams.set("from",o),m.searchParams.set("slippage",i.toString()),m.searchParams.set("disableEstimate","true"),m.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const f=await fetch(m.toString(),{headers:p});if(!f.ok)throw new g.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${f.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${f.status}`});const h=await f.json();if(!h.dstAmount||!h.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const x=BigInt(h.dstAmount);if(x<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const b=zs(x,r),y=[];return h.tx.to&&!c&&y.push({to:n.tokenIn,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"approve",args:[h.tx.to,n.amountIn]})}),y.push({to:h.tx.to,value:BigInt(h.tx.value||"0"),data:h.tx.data}),{venue:"1inch",amountOut:x,amountOutMinimum:b,calls:y}}catch(m){if(m instanceof g.SpiceflowError)throw m;const p=m instanceof Error?m.message:String(m);throw new g.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${p}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:p})}}}}const Ma=[4114,5115],Qo={name:"Satsuma",swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},_d={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[1],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]},Oa={name:"Uniswap v3",swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Pa={name:"Uniswap v3",swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Wa={name:"SushiSwap",swapRouter:"0x1e406484F1F204b23cE84B9901C0171a738fd406",quoterV2:"0x3E290e5E01818002A0b672148BdC7514D861C7B3",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"],routerHasDeadline:!0},eu=I.parseAbi(["function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),tu=I.parseAbi(["function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),nu=I.parseAbi(["function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),Ua=1800,La=[1,50,100,200,2e3],Ko={name:"Aerodrome",swapRouter:"0xcbBb8035cAc7D4B3Ca7aBb74cF7BdF900215Ce0D",quoterV2:"0x3d4C22254F86f64B7eC90ab8F7aeC1FBFD271c6C",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]};function Yo(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??La;return{name:t,chainIds:n,resolve:async(o,r,i)=>{if(A.isNativeToken(o.tokenIn)||A.isNativeToken(o.tokenOut))return null;const l=o.maxSlippage??Qn,d=[...s.map(y=>I.encodePacked(["address","uint24","address"],[o.tokenIn,y,o.tokenOut])),...Us(o.tokenIn,o.tokenOut,e.hubCurrencies??[],s,"in")],c={quoterV2:e.quoterV2},m=await Promise.allSettled(d.map(async y=>({path:y,amountOut:(await Ls(r,c,y,o.amountIn,"in")).amount})));let p=null;for(const y of m)y.status==="fulfilled"&&(!p||y.value.amountOut>p.amountOut)&&(p=y.value);if(!p)return console.warn(`[AerodromeVenue] No viable route for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}.`),null;const f=zs(p.amountOut,l),h=BigInt(Math.floor(Date.now()/1e3)+Ua),x=I.encodeFunctionData({abi:tu,functionName:"exactInput",args:[{path:p.path,recipient:i,deadline:h,amountIn:o.amountIn,amountOutMinimum:f}]}),b=[{to:o.tokenIn,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"approve",args:[e.swapRouter,o.amountIn]})},{to:e.swapRouter,value:0n,data:x}];return{venue:t,amountOut:p.amountOut,amountOutMinimum:f,calls:b}}}}function za(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??La;return{name:t,chainIds:n,resolve:async(o,r,i)=>{if(A.isNativeToken(o.tokenIn)||A.isNativeToken(o.tokenOut))return null;const l=o.maxSlippage??Qn,d=[...s.map(b=>I.encodePacked(["address","uint24","address"],[o.tokenOut,b,o.tokenIn])),...Us(o.tokenIn,o.tokenOut,e.hubCurrencies??[],s,"out")],c={quoterV2:e.quoterV2},m=await Promise.allSettled(d.map(async b=>({path:b,amountIn:(await Ls(r,c,b,o.amountOut,"out")).amount})));let p=null;for(const b of m)b.status==="fulfilled"&&(!p||b.value.amountIn<p.amountIn)&&(p=b.value);if(!p)return console.warn(`[AerodromeExactOutputVenue] No viable route for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}.`),null;const f=BigInt(Math.round(l*1e4)),h=p.amountIn+p.amountIn*f/10000n,x=BigInt(Math.floor(Date.now()/1e3)+Ua);return{venue:t,amountIn:p.amountIn,amountInMax:h,amountOut:o.amountOut,calls:[{to:e.swapRouter,value:0n,data:I.encodeFunctionData({abi:nu,functionName:"exactOutput",args:[{path:p.path,recipient:i,deadline:x,amountOut:o.amountOut,amountInMaximum:h}]})}]}}}}function us(e){const t=e.name??"Uniswap v3",n=e.chainIds??Ma;return{name:t,chainIds:n,resolve:async(s,o,r)=>{if(A.isNativeToken(s.tokenIn)||A.isNativeToken(s.tokenOut))return null;const i=s.maxSlippage??Qn;let l;try{l=await Ta({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn,chainId:o,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:e.hubCurrencies})}catch{return console.warn(`[UniV3Venue] No viable route for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}.`),null}const d=zs(l.amountOut,i),c=l.path?I.encodeFunctionData({abi:eu,functionName:"exactInput",args:[{path:l.path,recipient:r,amountIn:s.amountIn,amountOutMinimum:d}]}):I.encodeFunctionData({abi:A.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:l.fee,recipient:r,amountIn:s.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]}),m=[{to:s.tokenIn,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"approve",args:[e.swapRouter,s.amountIn]})},{to:e.swapRouter,value:0n,data:c}];return{venue:t,amountOut:l.amountOut,amountOutMinimum:d,calls:m}}}}function Go(e){const t=e.name??"Uniswap v3",n=e.chainIds??Ma;return{name:t,chainIds:n,resolve:async(s,o,r)=>{if(A.isNativeToken(s.tokenIn)||A.isNativeToken(s.tokenOut))return null;const i=s.maxSlippage??Qn;let l;try{l=await Ba({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut,chainId:o,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:e.hubCurrencies})}catch{return null}const d=BigInt(Math.round(i*1e4)),c=l.amountIn+l.amountIn*d/10000n;return{venue:t,amountIn:l.amountIn,amountInMax:c,amountOut:s.amountOut,calls:[Fa({config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},routerHasDeadline:e.routerHasDeadline,route:l,tokenIn:s.tokenIn,tokenOut:s.tokenOut,recipient:r,amountOut:s.amountOut,amountInMaximum:c})]}}}}const su=[4114],ou={swapRouter:"0x3012E9049d05B4B5369D690114D5A5861EbB85cb",quoterV2:"0xa77aD9f635a3FB3bCCC5E6d1A87cB269746Aba17",subgraphUrl:"https://api.goldsky.com/api/public/project_cmamb6kkls0v2010932jjhxj4/subgraphs/analytics-mainnet/v1.0.1/gn",maxSlippage:.005};function qa(e){return{name:"algebra",chainIds:e.chainIds??su,resolve:async(t,n,s)=>{const o=A.isNativeToken(t.tokenIn),r=await Zd({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:e}).catch(()=>null);if(!r)return null;const i=zs(r.amountOut,t.maxSlippage??e.maxSlippage??Qn),l=[];return o||l.push({to:t.tokenIn,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),l.push({to:e.swapRouter,value:o?t.amountIn:0n,data:I.encodeFunctionData({abi:Qd,functionName:"exactInput",args:[{path:Da(r.path),recipient:s,deadline:I.maxUint256,amountIn:t.amountIn,amountOutMinimum:i}]})}),{venue:"algebra",amountOut:r.amountOut,amountOutMinimum:i,calls:l}}}}function Zo(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.algebra&&t.push(qa(e.algebra)),e?.satsuma&&t.push(us(e.satsuma)),e?.aerodrome!==!1&&t.push(Yo(e?.aerodrome??Ko));let n=!1;if(e?.oneInch?.baseUrl)try{const l=new URL(e.oneInch.baseUrl);n=["http:","https:"].includes(l.protocol)&&l.hostname!==new URL(Na).hostname}catch{}(e?.oneInch?.apiKey?.trim()||n)&&t.push($d(e?.oneInch));const s=t.map(l=>Rd(l,e?.executorAddress));function o(l){return s.find(d=>d.chainIds.includes(l))}async function r(l,d,c){const m=s.filter(x=>x.chainIds.includes(d));if(m.length===0)throw new g.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${d}. Cannot resolve swap ${l.tokenIn} \u2192 ${l.tokenOut}.`,{chainId:d,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});const p=await Promise.allSettled(m.map(x=>x.resolve(l,d,c)));let f=null;for(const x of p)x.status==="fulfilled"&&x.value&&(!f||x.value.amountOut>f.amountOut)&&(f=x.value);if(f)return f;const h=p.find(x=>x.status==="rejected");if(h)throw h.reason;return null}async function i(l,d,c){const m=[],p=[];for(const f of l){if(!Xd(f)){m.push(f);continue}const h=await r(f,d,c);if(!h)throw new g.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${f.tokenIn} \u2192 ${f.tokenOut} on chain ${d}.`,{chainId:d,tokenIn:f.tokenIn,tokenOut:f.tokenOut,amountIn:f.amountIn.toString()});m.push(...h.calls),p.push(h)}return{calls:m,resolvedSwaps:p}}return{resolveSwapIntents:i,resolveSwap:r,getVenueForChain:o,venues:t}}const cn="0x0000000000000000000000000000000000000000",Xo=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],Ha=cn,Va=.02,ru=1800,Qa={name:"Uniswap v4",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",cn,"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Ka={name:"Uniswap v4",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",cn,"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Ya=I.parseAbi(["struct PoolKey { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }","struct PathKey { address intermediateCurrency; uint24 fee; int24 tickSpacing; address hooks; bytes hookData; }","struct QuoteExactSingleParams { PoolKey poolKey; bool zeroForOne; uint128 exactAmount; bytes hookData; }","struct QuoteExactParams { address exactCurrency; PathKey[] path; uint128 exactAmount; }","function quoteExactInputSingle(QuoteExactSingleParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactInput(QuoteExactParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(QuoteExactSingleParams params) returns (uint256 amountIn, uint256 gasEstimate)","function quoteExactOutput(QuoteExactParams params) returns (uint256 amountIn, uint256 gasEstimate)"]),au=I.parseAbi(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),iu=I.parseAbi(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),Ga="0x10",lu="04",cu="06",du="07",uu="08",pu="09",qs="0c",Hs="0e",fu=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],mu=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],wn=(e,t)=>e.toLowerCase()===t.toLowerCase();function Vs(e){return A.isNativeToken(e)?cn:e}function hu(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function Za(e,t,n,s,o){const r=[],[i,l]=hu(e,t);for(const{fee:c,tickSpacing:m}of Xo)r.push({kind:"single",poolKey:{currency0:i,currency1:l,fee:c,tickSpacing:m,hooks:Ha},zeroForOne:wn(e,i)});const d=(c,m)=>!!o&&(wn(c,cn)&&wn(m,o)||wn(c,o)&&wn(m,cn));for(const c of n)if(!(wn(c,e)||wn(c,t))&&!(d(c,e)||d(c,t)))for(const m of Xo)for(const p of Xo){const f=(h,x)=>({intermediateCurrency:h,fee:x.fee,tickSpacing:x.tickSpacing,hooks:Ha,hookData:"0x"});r.push({kind:"multi",path:s==="in"?[f(c,m),f(t,p)]:[f(e,m),f(c,p)]})}return r}async function Xa(e,t,n,s,o,r){const i=g.getClientForChain(e),l=(await Promise.allSettled(n.map(async d=>{const{result:c}=d.kind==="single"?await i.simulateContract({address:t.quoter,abi:Ya,functionName:r==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:d.poolKey,zeroForOne:d.zeroForOne,exactAmount:o,hookData:"0x"}]}):await i.simulateContract({address:t.quoter,abi:Ya,functionName:r==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:s,path:d.path,exactAmount:o}]}),m=c[0];if(m<=0n)throw new Error("zero quote");return{candidate:d,amount:m}}))).filter(d=>d.status==="fulfilled").map(d=>d.value);return l.length===0?null:(l.sort((d,c)=>d.amount<c.amount?-1:d.amount>c.amount?1:0),r==="in"?l[l.length-1]:l[0])}function Ja(e){const{candidate:t,direction:n,currencyIn:s,currencyOut:o,recipient:r,exactAmount:i,limitAmount:l,deadline:d,sweepNativeTo:c}=e;let m,p;t.kind==="single"?(m=n==="in"?`0x${cu}${qs}${Hs}`:`0x${uu}${qs}${Hs}`,p=I.encodeAbiParameters([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:fu},{name:"zeroForOne",type:"bool"},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"},{name:"hookData",type:"bytes"}]}],[{poolKey:t.poolKey,zeroForOne:t.zeroForOne,[n==="in"?"amountIn":"amountOut"]:i,[n==="in"?"amountOutMinimum":"amountInMaximum"]:l,hookData:"0x"}])):(m=n==="in"?`0x${du}${qs}${Hs}`:`0x${pu}${qs}${Hs}`,p=I.encodeAbiParameters([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:mu},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"}]}],[{[n==="in"?"currencyIn":"currencyOut"]:n==="in"?s:o,path:t.path,[n==="in"?"amountIn":"amountOut"]:i,[n==="in"?"amountOutMinimum":"amountInMaximum"]:l}]));const f=I.encodeAbiParameters([{type:"address"},{type:"uint256"}],[s,n==="in"?i:l]),h=I.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[o,r,0n]),x=I.encodeAbiParameters([{type:"bytes"},{type:"bytes[]"}],[m,[p,f,h]]),b=c?`${Ga}${lu}`:Ga,y=c?[x,I.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[cn,c,0n])]:[x];return I.encodeFunctionData({abi:iu,functionName:"execute",args:[b,y,d]})}function $a(){return BigInt(Math.floor(Date.now()/1e3)+ru)}function _a(e,t,n,s){return{to:e.permit2,value:0n,data:I.encodeFunctionData({abi:au,functionName:"approve",args:[t,e.universalRouter,n,Number(s)]})}}function ei(e){const t=e.name??"Uniswap v4",n=e.v3?us({...e.v3,chainIds:e.chainIds}):null;return{name:t,chainIds:e.chainIds,resolve:async(s,o,r)=>{const i=s.maxSlippage??Va,l=Vs(s.tokenIn),d=Vs(s.tokenOut),c=A.isNativeToken(s.tokenIn),m=e.hubCurrencies??[cn];let p=null;if(!wn(l,d)&&s.amountIn>0n){const f=await Xa(o,e,Za(l,d,m,"in",Ps(o)),l,s.amountIn,"in").catch(()=>null);if(f){const h=A.applySlippage(f.amount,i),x=$a(),b=[];c||(b.push({to:s.tokenIn,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"approve",args:[e.permit2,s.amountIn]})}),b.push(_a(e,s.tokenIn,s.amountIn,x))),b.push({to:e.universalRouter,value:c?s.amountIn:0n,data:Ja({candidate:f.candidate,direction:"in",currencyIn:l,currencyOut:d,recipient:r,exactAmount:s.amountIn,limitAmount:h,deadline:x})}),p={venue:t,amountOut:f.amount,amountOutMinimum:h,calls:b}}}return!p&&n?n.resolve(s,o,r):p}}}function ti(e){const t=e.name??"Uniswap v4";return{name:t,chainIds:e.chainIds,resolve:async(n,s,o)=>{const r=A.isNativeToken(n.tokenIn),i=Vs(n.tokenIn),l=Vs(n.tokenOut);if(wn(i,l)||n.amountOut<=0n)return null;const d=n.maxSlippage??Va,c=e.hubCurrencies??[cn],m=await Xa(s,e,Za(i,l,c,"out",Ps(s)),l,n.amountOut,"out").catch(()=>null);if(!m)return null;const p=BigInt(Math.round(d*1e4)),f=m.amount+m.amount*p/10000n,h=$a();return{venue:t,amountIn:m.amount,amountInMax:f,amountOut:n.amountOut,calls:[...r?[]:[_a(e,n.tokenIn,f,h)],{to:e.universalRouter,value:r?f:0n,data:Ja({candidate:m.candidate,direction:"out",currencyIn:i,currencyOut:l,recipient:o,exactAmount:n.amountOut,limitAmount:f,deadline:h,sweepNativeTo:r?o:void 0})}]}}}}const ni=[{..._d,protocol:"uniswap-v3",chainId:1},{...Qo,protocol:"uniswap-v3",chainId:4114},{...Qo,protocol:"uniswap-v3",chainId:5115},{...Oa,protocol:"uniswap-v3",chainId:8453},{...Pa,protocol:"uniswap-v3",chainId:4663},{...Wa,protocol:"uniswap-v3",chainId:4663},{...Qa,protocol:"uniswap-v4",chainId:8453},{...Ka,protocol:"uniswap-v4",chainId:4663},{...Ko,protocol:"aerodrome-slipstream",chainId:8453}];function Kn(e){const t=e?.includeDefaults===!1?e.venues??[]:[...ni,...e?.venues??[]],n=[],s=[];for(const o of t){const r=[o.chainId];switch(o.protocol){case"uniswap-v3":{const i={...o,chainIds:r};n.push(us(i)),s.push(Go(i));break}case"uniswap-v4":{const i={...o,chainIds:r};n.push(ei(i)),s.push(ti(i));break}case"aerodrome-slipstream":{const i={...o,chainIds:r};n.push(Yo(i)),s.push(za(i));break}default:{const i=o;throw new g.SpiceflowError("INVALID_PARAMS",`Unsupported liquidity venue protocol: ${i.protocol}`,{protocol:i.protocol})}}}return{input:n,output:s}}function Bt(e,t,n,s){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return s==="ceil"?(e+o-1n)/o:e/o}const gu="0xa9059cbb";function si(e,t,n){return A.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[n,t]})}}function Qs(e,t,n){return{chainId:n,calls:[si(e,t,A.getEscrowContractAddress(n))]}}function en(e,t){if(!e||e._source!=="wallet")return!1;const n=e._fundingWallet;return n==="external"||t&&n!=="embedded"}function oi(e,t,n){return e?.asset._source==="wallet"&&!en(e.asset,t)}function ri(e){return e.isNative||A.isNativeToken(e.address)?!0:!A.getTokenByAddress(e.address,e.chainId)}function ai(e,t,n,s){const o=l=>A.isNativeToken(s)?l.data==="0x"&&l.value>0n&&[A.SPICE_GAS_FEE_RECIPIENT,A.SPICE_PLATFORM_FEE_RECIPIENT].some(d=>g.addressesEqual(l.to,d)):g.addressesEqual(l.to,s)&&l.data.startsWith(gu);if(t!=="user-transfer"||!n||e.length===0||!o(e[0]))return{feeCalls:[],remainingCalls:e};const r=e.findIndex(l=>!o(l)),i=r===-1?e.length:r;return{feeCalls:e.slice(0,i),remainingCalls:e.slice(i)}}async function Ks(e,t,n,s){if(!t)return[e];const o=await t({...n,requestTimestampMs:s});return o?[o,e]:[e]}function Ys(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:A.normalizeNativeTokenAddress(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function Kt(e,t,n){return Bt(e,t,n,"ceil")}async function Yn(e,t,n){if(e.chainId!==t.chainId&&!Ss(e,n,t.chainId)&&!Dn(e,t.chainId).some(s=>g.addressesEqual(s,n)))throw new Error("No supported bridge route for this source asset");return g.addressesEqual(n,t.address)?t.decimals:e.chainId===t.chainId&&g.addressesEqual(n,e.address)?e.decimals:g.getTokenDecimals(t.chainId,n)}async function ii(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:o,providerEmbeddedAddress:r,address:i,isNon7702:l,isPayMode:d,resolvedChainId:c,buildActionCalls:m,feeExecutionMode:p,buildSpicenetBatch:f,selectedAsset:h,needsSwap:x,exactOutputSwap:b,resolvedTokenIn:y,requestTimestampMs:w}=e,S=t?.fundingTokenOverride??y,v=I.parseUnits(n,s.decimals),k=e.feeOnlyAction?0n:t?.actionAmountOverride??v,C=!!e.feeOnlyAction&&(t?.fundingAmountOverride??0n)>0n;if(C&&h?.asset._source==="wallet"&&h.asset.chainId===c&&!A.isNativeToken(h.asset.address)&&!A.getTokenByAddress(h.asset.address,c))throw new Error("Choose a registered token or native asset to fund action fees");const E=o||r||(l?void 0:i);if(!E)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const F={userAddress:E,executorAddress:E,outputRecipient:!e.feeOnlyAction&&x&&b?e.swapOutputRecipient??E:void 0,chainId:c,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??v,netAmount:k,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},B=await m(k,F),j={chainId:c,calls:B},T=!d&&!l?!0:h?.asset._source==="spice",R=oi(h??null,l);if(e.feeOnlyAction&&t?.fundingTokenOverride&&R&&h?.asset.chainId===c&&g.addressesEqual(t.fundingTokenOverride,h.asset.address))return[j];const D=C||T||en(h?.asset,l)&&h?.asset.chainId!==c||R&&!!h&&(h.asset.chainId!==c||!ri(h.asset)),M=(X,N)=>({token:A.normalizeNativeTokenAddress(X),from:"escrow",to:E,amount:N}),P=(X,N)=>R||en(h?.asset,l)&&(h?.asset.chainId!==c||C)?[Qs(h.asset.address,t?.sourceFundingAmountOverride??Kt(X,z,h.asset.decimals),h.asset.chainId),...N]:N;if(v===0n&&!C)return[j];const q=S??(h?Qt(h.asset,c):null)??s.address,z=h?await Yn(h.asset,s,q):s.decimals;if(!e.feeOnlyAction&&x&&b){const X=S??Qt(h.asset,c)??h.asset.address,N=t?.fundingAmountOverride??b.amountInMax,H=D?[M(X,N)]:[],V={chainId:c,calls:[...b.calls,...B],tokenTransfers:[...H,...j.tokenTransfers??[]]};if(!D)return[V];const G=await Ks(V,f,{userAddress:E,destinationChainId:c,deliveryToken:X,deliveryAmount:N,deliveryRecipient:E,deliveryTransfers:Ys(V),sourceAsset:h.asset},w);return P(N,G)}if(D){const X=S??(h?Qt(h.asset,c):null)??s.address;if(!C&&R&&h?.asset.chainId===c&&X.toLowerCase()===s.address.toLowerCase())return[j];const N=t?.fundingAmountOverride??v,H={...j,tokenTransfers:[M(X,N),...j.tokenTransfers??[]]},V=await Ks(H,f,{userAddress:E,destinationChainId:c,deliveryToken:X,deliveryAmount:N,deliveryRecipient:E,deliveryTransfers:Ys(H),sourceAsset:h?.asset},w);return P(N,V)}return[j]}async function li(e,t){const{selectedAsset:n,embeddedWalletAddress:s,externalWalletAddress:o,recipient:r,resolvedChainId:i,destinationToken:l,buildActionCalls:d,feeExecutionMode:c,buildSpicenetBatch:m,isPayMode:p,isNon7702:f,needsSwap:h,resolvedSwap:x,quoteAmountOut:b,resolvedTokenIn:y,requestTimestampMs:w}=e,S=x?.amountOutMinimum??b;if(!n?.asset||!s)return[];const v=r??(f?o:s);if(!v)return[];const k=I.parseUnits(n.amount,n.asset.decimals),C=y??Qt(n.asset,i)??l.address,E=await Yn(n.asset,l,C),F=t?.fundingAmountOverride??Bt(k,n.asset.decimals,E,"floor");if(F<=0n)throw new Error("Amount is below the destination token's precision");const B=t?.fundingAmountOverride??F,j=t?.sourceFundingAmountOverride??(t?.fundingAmountOverride===void 0?k:Kt(B,E,n.asset.decimals)),T=t?.deliveryAmountOverride??B,R=t?.withdrawalAmountOverride??T,D=t?.actionAmountOverride??F,M=t?.actionContextOverride?.feeBreakdown;if(e.isFeeInclusiveInput&&h&&e.swapInputAmount!=null&&M){const ee=Bt(k,n.asset.decimals,E,"floor");if(e.swapInputAmount+M.gasFee+M.spicenetFee+M.bridgeFee>ee)throw new Error("Swap input plus fees exceeds the entered amount. Refresh the quote before retrying.")}const P={userAddress:v,executorAddress:s,outputRecipient:h&&x?e.swapOutputRecipient??s:void 0,chainId:i,destinationToken:l.address,feeToken:c==="user-transfer"&&h&&y?y:l.address,grossAmount:B,netAmount:D,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},q=()=>d(D,P),z=n.asset._source==="wallet",X=n.asset._fundingWallet,N=z&&(X==="external"||f&&X!=="embedded");if(!p&&z&&n.asset.chainId===i&&(f||X==="external"||ri(n.asset))){if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!x||S===null)throw new Error("Swap quote not available yet")}if(h&&x&&S){const ee=await d(t?.actionAmountOverride??S,{...P,netAmount:t?.actionAmountOverride??S}),{feeCalls:ue,remainingCalls:re}=ai(ee,c,h,P.feeToken);return[{chainId:i,calls:[...ue,...x.calls,...re]}]}return[{chainId:i,calls:await q()}]}const H=!p&&!f?n.asset._source!=="wallet":n.asset._source==="spice",V=oi(n,f);if(!(H||N||V))return[{chainId:i,calls:await q()}];const G=V?Qs(A.normalizeNativeTokenAddress(n.asset.address),j,n.asset.chainId):N&&n.asset.chainId!==i?{chainId:n.asset.chainId,calls:[si(A.normalizeNativeTokenAddress(n.asset.address),j,A.getEscrowContractAddress(n.asset.chainId))]}:null,J=(ee,ue)=>({token:A.normalizeNativeTokenAddress(ee),from:"escrow",to:s,amount:ue});if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!x||S===null)throw new Error("Swap quote not available yet")}if(h&&x&&S&&y){const ee=await d(t?.actionAmountOverride??S,{...P,netAmount:t?.actionAmountOverride??S}),{feeCalls:ue,remainingCalls:re}=ai(ee,c,h,P.feeToken),se={chainId:i,calls:[...ue,...x.calls,...re],tokenTransfers:[J(y,T)]},ie=await Ks(se,m,{userAddress:s,destinationChainId:i,deliveryToken:y,deliveryAmount:T,withdrawalAmount:R,deliveryRecipient:s,deliveryTransfers:Ys(se),sourceAsset:n.asset},w);return G?[G,...ie]:ie}const U=y??Qt(n.asset,i)??l.address,L={chainId:i,calls:await q(),tokenTransfers:[J(U,T)]},O=await Ks(L,m,{userAddress:s,destinationChainId:i,deliveryToken:U,deliveryAmount:T,withdrawalAmount:R,deliveryRecipient:s,deliveryTransfers:Ys(L),sourceAsset:n.asset},w);return G?[G,...O]:O}async function xu(e,t,n,s,o){let r=e;for(let i=0;i<4;i++){const l=await t(r),d=await s(l,n,r,o),c=Pc(d);if(c===null||c>=e)return r;const m=r-c,p=e+m;if(p<=r)return r;r=p}return r}function ci(e,t){return e._source!=="wallet"||e.chainId!==t?!1:e.isNative||A.isNativeToken(e.address)||!A.getTokenByAddress(e.address,e.chainId)}function yu(e,t){const n=e[0];if(e.length!==1||!n||n.chainId!==t.chainId||n.domain==="spicenet"||n.tokenTransfers?.length||n.calls.length===0)throw new Error("SpiceLock requires one lock-chain action batch. Return only lock approval and action calls, without funding transfers.");if(t.amountIn<=0n)throw new Error("Enter a positive amount to lock.");if(t.swap&&(t.swap.amountOutMinimum<=0n||t.swap.amountOutMinimum>t.swap.amountOut||t.swap.calls.length===0))throw new Error("A valid swap quote is required before locking. Please retry.");return[{...n,calls:[...t.swap?.calls??[],...n.calls],...t.escrowFunded?{tokenTransfers:[{token:A.normalizeNativeTokenAddress(t.tokenIn),from:"escrow",to:t.recipient,amount:t.amountIn}]}:{}}]}function bu(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=I.getAddress(n.token),o=I.getAddress(n.to),r=`${s.toLowerCase()}:${o.toLowerCase()}`,i=t.get(r);i?i.amount+=n.amount:t.set(r,{token:s,to:o,amount:n.amount})}return[...t.values()]}function wu(e,t){return`0x${t}${e.slice(4)}`}function di(e,t){return ui(e,t)}function ui(e,t,n){const s=Es(t,e),o=Math.floor(Date.now()/1e3)+60*10,r=A.hashChainBatches(s);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:o,chainBatches:r.map((i,l)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:s[l].domain==="spicenet"?[]:s[l].tokenTransfers??[],calls:i.calls}))}]}}function Gn(e,t,n,s){if(e.some(m=>m.domain==="spicenet"))return e;const o=n?.intents.flatMap(m=>m.batches),r=m=>m.from==="escrow",i=e.map(m=>{const p=o?.find(F=>F.chainId===m.chainId);if(!p)return m;const f=an(p),h=f.totalFee;if(h<=0n)return m;const x=(m.tokenTransfers??[]).filter(F=>r(F)&&I.getAddress(F.to).toLowerCase()===t.toLowerCase()),b=x.find(F=>!A.isNativeToken(I.getAddress(F.token)))??x[0];if(!b)return m;const y=I.getAddress(b.token),w=A.isNativeToken(y);let S=!1;const v=(m.tokenTransfers??[]).map(F=>S||!r(F)||I.getAddress(F.to).toLowerCase()!==t.toLowerCase()||I.getAddress(F.token).toLowerCase()!==y.toLowerCase()?F:(S=!0,{...F,amount:s?.payoutAlreadyGross?BigInt(F.amount):BigInt(F.amount)+h}));if(!S)return m;const k=(F,B)=>w?{to:F,value:B,data:"0x"}:{to:y,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[F,B]})},C=[];f.spicenetFee>0n&&C.push(k(A.SPICE_PLATFORM_FEE_RECIPIENT,f.spicenetFee));const E=f.gasFee+f.bridgeFee;return E>0n&&C.push(k(A.SPICE_GAS_FEE_RECIPIENT,E)),{...m,tokenTransfers:v,calls:[...C,...m.calls]}}),l=i.flatMap(m=>(m.tokenTransfers??[]).filter(r).map(p=>{const f=I.getAddress(p.token),h=I.getAddress(p.to),x=[{token:f,to:h,amount:BigInt(p.amount)}];return{chainId:m.chainId,transfers:bu(x)}}));if(l.length===0)return e;const d=s?.requestTimestampMs??Date.now(),c=BigInt(Math.floor(d/1e3))+3600n;return[{chainId:A.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:l.map((m,p)=>{const f=I.keccak256(I.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,m.transfers[0].token,m.transfers.reduce((x,b)=>x+b.amount,0n),BigInt(m.chainId),BigInt(d+p)])),h=wu(f,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:I.encodeFunctionData({abi:A.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${m.chainId}`,idempotenceKey:h,nbf:0n,exp:c,metadata:"{}",transfers:m.transfers.map(x=>({token:x.token.toLowerCase(),to:x.to,amount:x.amount}))}]})}})},...i]}function An(e,t,n,s){const o=e.filter(i=>i.domain!=="spicenet"),r=i=>(i.tokenTransfers??[]).some(l=>l.from==="escrow");return[...o.filter(i=>!r(i)),...Gn(o.filter(r),t,n,s)]}function Jo(e,t,n,s,o){const r=e[e.length-1];if(!r?.calls.length||r.domain==="spicenet")throw new Error("Proceeds fees require a final destination action");const i=[{to:A.SPICE_PLATFORM_FEE_RECIPIENT,amount:o},{to:A.SPICE_GAS_FEE_RECIPIENT,amount:s}].filter(l=>l.amount>0n);return e.map(l=>l===r?{...l,calls:[...l.calls,...i.map(d=>({to:n,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[d.to,d.amount]})}))],tokenTransfers:[...l.tokenTransfers??[],...i.map(d=>({from:t,to:d.to,token:n,amount:d.amount}))]}:l)}async function pi(e,t,n,s,o){const r=A.hashChainBatches(e),i=await g.relayerService.estimateBatchGas({user:t,outputToken:n,signal:s,requireSimulation:!0,includePlatformFee:o!==void 0,chainBatches:e.map((l,d)=>({...l,hash:r[d].hash}))});if(i.gasQuoteSource!=="estimated"||!i.simulationVerified)throw new Error("Action proceeds require a successful live batch simulation; fallback gas pricing is not sufficient");if(o!==void 0&&(i.platformFee===void 0||i.platformFee>o))throw new Error("Fee conversion platform price changed; refresh before retrying");return i.gasFee}async function Cu(e){if(e.proceeds.token.toLowerCase()!==e.token.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const t=await e.proceeds.resolve(e.signal);if(e.signal?.aborted)throw new Error("Action proceeds quote was cancelled");if(t<0n)throw new Error("Action proceeds cannot be negative");const n=await e.baseline();if(!n?.feeEstimate)throw new Error("Action fee quote is unavailable");let s=n.preview.gasFee;const o=n.preview.spicenetFee,r=n.preview.bridgeFee??0n;for(let i=0;i<5;i++){const l=s+o+r,d=t<l?t:l,c=l-d,m=c>0n?(c*110n+99n)/100n+2n:0n,p=An(await e.buildBatches(m),e.owner),f=Jo(p,e.owner,e.token,s+r,o),h=await pi(f,e.owner,e.token,e.signal);if(h===s)return{preview:{...n.preview,grossAmount:m,netAmount:0n,gasFee:s,totalFee:l,gasQuoteSource:"estimated"},feeEstimate:n.feeEstimate,grossFundingAmount:m,proceedsAvailable:t,proceedsUsed:d};s=h}throw new Error("Action proceeds fee estimate did not converge")}function fi(e,t,n){if(e._source==="wallet")return e._fundingWallet==="embedded"&&e.chainId===t&&A.getTokenByAddress(e.address,t)?e.address:null;const s=Dn(e,t);return s.find(o=>o.toLowerCase()===n.toLowerCase())??s[0]??null}class mi extends Error{constructor(t,n){super("The selected balance cannot cover the fee funding amount"),this.requiredAmount=t,this.balance=n,this.name="InsufficientFeeFundingBalanceError"}}async function vu(e){const t=e.selectedAsset?.asset,n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t||!n||t._source!=="spice"&&!(t._source==="wallet"&&t._fundingWallet==="embedded"&&t.chainId===e.resolvedChainId))throw new Error("A local embedded or Spice balance is required for fee conversion");const s=fi(t,e.resolvedChainId,e.destinationToken.address);if(!s)throw new Error("This receipt has no registered destination withdrawal token");const o=A.getTokenByAddress(s,e.resolvedChainId);if(!o)throw new Error("Fee funding token metadata is unavailable");const r=e.destinationToken.address;if(e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==r.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const i=e.actionProceeds?await e.actionProceeds.resolve(e.signal):0n;if(i<0n||e.signal?.aborted)throw new Error("Action proceeds quote was cancelled or invalid");const l=Ws({executorAddress:n,customVenues:[...e.resolveExactOutputSwap?[{name:"consumer-exact-output",chainIds:[e.resolvedChainId],preferred:!0,resolve:e.resolveExactOutputSwap}]:[],...Kn(e.liquidityVenues).output]}),d=async m=>{const p=A.hashChainBatches(m),f=await g.relayerService.estimateBatchGas({user:n,outputToken:r,requireSimulation:!0,includePlatformFee:!0,signal:e.signal,chainBatches:m.map((h,x)=>({...h,hash:p[x].hash}))});if(!f.simulationVerified||f.gasQuoteSource!=="estimated"||f.platformFee===void 0||f.gasFee<=0n)throw new Error("Fee conversion requires verified gas and platform pricing");return f};let c=await d(await e.buildPayChainBatches({fundingAmountOverride:0n}));for(let m=0;m<8;m++){const p=c.gasFee+c.platformFee,f=i<p?i:p,h=p-f,x=h>0n?(h*110n+99n)/100n+2n:0n,b=x>0n?await l.getQuote({tokenIn:s,tokenOut:r,amountOut:x,maxSlippage:e.maxSlippage},e.resolvedChainId,n):null;if(e.signal?.aborted)throw new Error("Fee conversion quote was cancelled");if(b&&(b.amountOut!==x||b.amountInMax<=0n||b.amountInMax<b.amountIn||!b.calls.length))throw new Error("Invalid exact-output fee conversion quote");const y=b?.amountInMax??0n,w=Kt(y,o.decimals,t.decimals);if(w>t.balance)throw new mi(w,t.balance);let S=An(await e.buildPayChainBatches({fundingAmountOverride:y,fundingTokenOverride:s}),n);if(b){const k=S.length-1;S=S.map((C,E)=>E===k?{...C,calls:[...C.calls,...b.calls]}:C)}S=Jo(S,n,r,c.gasFee,c.platformFee);const v=await d(S);if(v.gasFee<=c.gasFee&&(c.gasFee-v.gasFee)*100n<=v.gasFee*15n&&v.platformFee===c.platformFee){const k={tokenIn:s,tokenOut:r,amountInMax:y,amountOut:x,sourceAmountMax:w};return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,grossAmount:x,netAmount:0n,gasFee:c.gasFee,spicenetFee:c.platformFee,totalFee:p,gasQuoteSource:"estimated"},grossFundingAmount:y,proceedsAvailable:i,proceedsUsed:f,fundingConversion:k,fundingBatches:S}}c=v}throw new Error("Fee conversion pricing did not converge")}function Zn(e){return JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString():n)}async function hi(e,t,n){const s=e.sourceConversion,o=e.selectedAsset?.asset,r=e.embeddedWalletAddress??e.providerEmbeddedAddress;try{if(!o||!r||o._source!=="wallet")throw new Error("Select a wallet source for source-chain conversion");if(!e.isPayMode&&!e.isFeeInclusiveInput)throw new Error("Source-chain conversion requires input-inclusive or exact-output mode");const i=s.virtualSelectedAsset,l=i.asset.chainId===e.resolvedChainId&&g.addressesEqual(i.asset.address,e.destinationToken.address);await t({...e,sourceConversion:void 0,sourceConversionRequired:!1,sourceFunding:void 0,selectedAsset:i,parsedAmount:e.isPayMode?e.parsedAmount:Number(i.amount),isInsufficientBalance:!1,isSourceDestToken:l,executionTokenDecimals:i.asset.decimals,execution:{...e.execution,execute:async(d,c,m,p,f,h)=>{let x;const b=(v,k)=>{const C=x??s.getPlan(v);if(!s.isCurrent()||!C||C.expiresAt<=Date.now())throw new Error("Source funding quote expired or changed; refresh it before retrying");const E=C.quote.plan.source;if(E.chainId!==o.chainId||E.decimals!==o.decimals||!g.addressesEqual(E.address,o.address)||!g.addressesEqual(C.quote.executorAddress,r))throw new Error("The source funding quote does not belong to this wallet and asset");if(!e.isPayMode&&C.quote.sourceAmountInMax!==I.parseUnits(e.selectedAsset.amount,o.decimals))throw new Error("The source quote exceeds the entered input-inclusive budget");if(C.quote.sourceAmountInMax>s.acceptedSourceAmountInMax)throw new Error("The source quote exceeds the displayed maximum; review the refreshed quote before retrying");if(k!==void 0&&C.quote.sourceAmountInMax>k)throw new Error("The refreshed source quote exceeds this operation's funded amount");if(!C.chainBatches.every((F,B)=>v[B]&&Zn(v[B])===Zn(F)))throw new Error("The source conversion calls changed after quoting");return C},y=b(d),w=y.quote.sourceAmountInMax,S=v=>{const k=C=>C.chainBatches.every((E,F)=>v[F]&&Zn(v[F])===Zn(E));if(!x||k(x))return v;if(!k(y))throw new Error("The source conversion calls changed after quoting");return[...x.chainBatches,...v.slice(y.chainBatches.length)]};if(en(o,e.isNon7702)){const v=BigInt(e.sourceFunding?.confirmedAmount??"0")+BigInt(e.sourceFunding?.pending?.amount??"0");if(w>o.balance+v)throw new Error("Insufficient selected-source balance for the quoted amount and fees");await n(w)}else{const v=g.getClientForChain(o.chainId);if((o.isNative||A.isNativeToken(o.address)?await v.getBalance({address:r}):await v.readContract({address:o.address,abi:I.erc20Abi,functionName:"balanceOf",args:[r]}))<w)throw new Error("Insufficient embedded source balance for this conversion")}return b(d,w),e.execution.execute(d,c,m,p,f,{...h,skipUserFundingPreflight:!0,prepareAfterAuthorization:async v=>{if(!s.isCurrent())throw new Error("Source funding wallet or destination quote changed; refresh before retrying");const k=await s.refreshPlan(y);if(k.bridgeDestinationNet<y.bridgeDestinationNet)throw new Error("Refreshed source funding cannot cover the accepted destination; review the new quote");const C=y.quote.plan,E=k.quote.plan;for(const B of["bridgeSource","bridgeDestination"])if(C[B].chainId!==E[B].chainId||C[B].decimals!==E[B].decimals||!g.addressesEqual(C[B].address,E[B].address))throw new Error("The source funding route changed; review the new quote");x=k;const F=S(v);return b(F,w),h?.prepareAfterAuthorization?h.prepareAfterAuthorization(F):F},adjustBatchesForEstimate:async v=>{const k=await h?.adjustBatchesForEstimate?.(v),C=S(k??v.chainBatches);return b(C,w),k?C:null},validateBeforeSubmit:async v=>{await h?.validateBeforeSubmit?.(v),b(v,w)}})}}})}catch(i){const l=g.sanitizeError(i,"Source funding conversion failed");e.ui.setError(l),e.ui.setStep("error"),e.isPayMode&&e.ui.setPaymentResult({status:"failed",error:l})}}function gi(e,t){let n,s;if(A.isNativeToken(t)){if(e.data!=="0x")return null;n=e.to,s=e.value}else{if(!g.addressesEqual(e.to,t))return null;try{const o=I.decodeFunctionData({abi:I.erc20Abi,data:e.data});if(o.functionName!=="transfer")return null;[n,s]=o.args}catch{return null}}return g.addressesEqual(n,A.SPICE_GAS_FEE_RECIPIENT)?{gas:s,platform:0n}:g.addressesEqual(n,A.SPICE_PLATFORM_FEE_RECIPIENT)?{gas:0n,platform:s}:null}function ps(e,t,n){return e.map(s=>s.chainId===t?{...s,calls:s.calls.filter(o=>!gi(o,n))}:s)}function xi(e,t,n){if(!e.feeOnlyAction)return{};const s=e.embeddedWalletAddress??e.providerEmbeddedAddress;if(e.actionProceeds||e.feeQuote?.fundingConversion){const l=e.feeQuote?.fundingConversion,d=e.actionProceeds??{token:t,resolve:async()=>0n},c=e.feeQuote?.preview,m=e.feeQuote?.proceedsUsed;if(!c||m===void 0||d.token.toLowerCase()!==t.toLowerCase())throw new Error("Refresh the action proceeds quote");const p=c.gasFee+(c.bridgeFee??0n),f=c.spicenetFee,h=async()=>{e.validateFeeQuote?.();const b=await d.resolve(e.signal);if(e.validateFeeQuote?.(),e.signal?.aborted||b<m||b+(l?.amountOut??n)<p+f)throw new Error("Action proceeds changed; refresh before retrying");return[{chainId:e.resolvedChainId,token:t,amount:m+(l?.amountOut??0n)}]},x=async b=>{await h();const y=await pi(b,s,t,e.signal,l?f:void 0);if(await h(),(y>c.gasFee?y-c.gasFee:c.gasFee-y)*100n>y*15n)throw new Error("Action gas quote changed; refresh before retrying")};return{resolveActionOutputCredits:h,prepareForSigning:async b=>{const y=ps(b,e.resolvedChainId,t).map(S=>({...S,tokenTransfers:S.tokenTransfers?.filter(v=>!(typeof v.from=="string"&&g.addressesEqual(v.from,s)&&(g.addressesEqual(v.to,A.SPICE_GAS_FEE_RECIPIENT)||g.addressesEqual(v.to,A.SPICE_PLATFORM_FEE_RECIPIENT))))})),w=Jo(y,s,t,p,f);return await x(w),w},validateBeforeSubmit:x}}const o=A.getTokenByAddress(t,e.resolvedChainId),r={chainId:e.resolvedChainId,tokenAddress:t,symbol:o?.symbol??e.destinationToken.symbol,decimals:e.executionTokenDecimals??o?.decimals??e.destinationToken.decimals},i=async l=>{e.validateFeeQuote?.();const d=ps(l,e.resolvedChainId,t),c=await e.execution.estimate(d,t,n,{userOverride:s,useCustomTransfers:!0,feeExecutionMode:"backend-transfer"});e.validateFeeQuote?.();const m=xn(c,r);if(!m||m.chainId!==e.resolvedChainId)throw new Error("The fee service did not return the destination action's fee quote");if(m.gasFee+m.spicenetFee+(m.bridgeFee??0n)+2n>n)throw new Error("Fees exceed the displayed maximum funding; refresh the quote before retrying");return{raw:d,feeEstimate:c,fees:m}};return{prepareForSigning:async l=>{const{raw:d,feeEstimate:c}=await i(l);return An(d,s,c,{payoutAlreadyGross:!0})},validateBeforeSubmit:async l=>{const{fees:d}=await i(l);let c=0n,m=0n;for(const f of l)if(f.chainId===e.resolvedChainId)for(const h of f.calls){const x=gi(h,t);x&&(c+=x.gas,m+=x.platform)}if(c+m+2n>n)throw new Error("Signed fees exceed the displayed maximum funding");const p=d.gasFee+(d.bridgeFee??0n);if((c>p?c-p:p-c)*100n>p*15n||m!==d.spicenetFee)throw new Error("The signed gas quote changed materially; refresh before retrying")}}}const yi=(e,t)=>(e+t-1n)/t;function ku(e,t){const n=e.spicenetFee+(e.bridgeFee??0n);return e.grossAmount<=n?t+e.gasFee+n:yi((t+e.gasFee)*e.grossAmount,e.grossAmount-n)+2n}function bi(e,t,n){return e.every(s=>s.domain!=="spicenet"&&!s.tokenTransfers?.length)?{...t,grossAmount:n,netAmount:n,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}:null}async function $o(e){const{requiredNetFunding:t}=e;if(e.feeOnlyAction){const m=e.executionOptions?.userOverride;if(!m||t!==0n)throw new Error("Fee-only estimates require a zero action amount and its embedded executor");let p=1n,f;for(let h=0;h<8;h++){const x=An(await e.buildBatches(p),m,f,{payoutAlreadyGross:!0}),b=await e.estimate(ps(x,e.tokenDescriptor.chainId,e.fundingToken),e.fundingToken,p,{...e.executionOptions,feeExecutionMode:"backend-transfer"}),y=xn(b,e.tokenDescriptor);if(!y)throw new Error("The fee service did not return a fee quote for this action");const w=y.gasFee+y.spicenetFee+(y.bridgeFee??0n);if(f&&w+2n<=p)return{preview:{...y,grossAmount:p,netAmount:0n},feeEstimate:b,grossFundingAmount:p};p=(w*110n+99n)/100n+2n,f=b}throw new Error("Fee-only funding did not converge; refresh the fee quote before retrying")}const n=t,s=await e.buildBatches(n),o=await e.estimate(s,e.fundingToken,n,e.executionOptions),r=xn(o,e.tokenDescriptor);if(!r)return{preview:bi(s,e.tokenDescriptor,t),feeEstimate:o,grossFundingAmount:t};const i=ku(r,t),l=m=>r.grossAmount>0n?yi(m*i,r.grossAmount):m,d=l(r.spicenetFee),c=l(r.bridgeFee??0n);return{preview:{...r,grossAmount:i,netAmount:t,spicenetFee:d,bridgeFee:c,totalFee:r.gasFee+d+c},feeEstimate:o,grossFundingAmount:i}}function Su(e,t,n,s){if(e<=0n)return 0n;const o=e-t;if(o<=0n)return 0n;const r=s+n;return r<=0n?o:o*s/r}async function wi(e){const{asset:t,isPayMode:n,isNon7702:s,needsSwap:o,isQuoting:r,embeddedWalletAddress:i,buildSupplyChainBatches:l,estimate:d,executionTokenAddress:c,feeExecutionMode:m}=e;if(n||s||o||r||!i||t.balance<=0n)return null;const p=i,f=await l({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(f.length===0)return null;const h=f.some(v=>v.tokenTransfers?.length),x=await d(f,c,t.balance,h?{userOverride:p,useCustomTransfers:!0,feeExecutionMode:m}:m?{userOverride:p,feeExecutionMode:m}:{userOverride:p}),b=xn(x,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),y=b?Kt(b.gasFee,b.decimals,t.decimals):0n,w=b?Kt(b.spicenetFee,b.decimals,t.decimals):0n,S=Su(t.balance,y,w,t.balance);return S>0n?ra(S,t.decimals):null}async function _o(e){const{signal:t,selectedAsset:n,isPayMode:s,isFeeInclusiveInput:o=!1,parsedAmount:r,needsSwap:i,exactOutputSwap:l,isNon7702:d,isSourceDestToken:c,currentPaymentAmount:m,destinationToken:p,feeExecutionMode:f,resolvedTokenIn:h,embeddedWalletAddress:x,providerEmbeddedAddress:b,resolvedChainId:y,isConnected:w,address:S,ready:v,authenticated:k,isDirect:C,resolvedSwap:E,isQuoting:F,executionTokenAddress:B,buildPayChainBatches:j,buildSupplyChainBatches:T,estimate:R}=e;if(e.feeOnlyAction&&n&&(n.asset._source==="spice"||n.asset._source==="wallet"&&n.asset._fundingWallet==="embedded"&&n.asset.chainId===y)&&(h?h.toLowerCase()!==p.address.toLowerCase():n.asset.receiptTokenId||n.asset.chainTokens))return vu(e);if(e.actionProceeds&&e.feeOnlyAction){const O=x||b;if(!O||!v||!k)return null;if(h&&h.toLowerCase()!==p.address.toLowerCase())throw new Error("Action proceeds require a matching fee-token source");return Cu({proceeds:e.actionProceeds,owner:O,token:p.address,signal:t,buildBatches:ee=>j({fundingAmountOverride:ee}),baseline:()=>_o({...e,actionProceeds:void 0,selectedAsset:n??{amount:"0",asset:{...p,name:p.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"spice"}}})})}if(!n?.asset)return null;if(s){if(r<=0&&!e.feeOnlyAction||i&&!l&&!e.feeOnlyAction||c&&n.asset._source==="wallet"&&!e.feeOnlyAction||d&&!x&&!b)return null;const O=I.parseUnits(m,p.decimals),ee=h||Qt(n.asset,y)||n.asset.address||p.address,ue={chainId:y,tokenAddress:ee,symbol:A.getTokenByAddress(ee,y)?.symbol??n.asset.symbol,decimals:await Yn(n.asset,p,ee)};if(en(n.asset,d)){const ce=x||b;if(!ce)return null;const _=i?l?.amountInMax??0n:O;if(_===0n&&!e.feeOnlyAction)return null;const Ce=await $o({requiredNetFunding:_,feeOnlyAction:e.feeOnlyAction,buildBatches:W=>j({fundingAmountOverride:W}),fundingToken:ee,estimate:R,executionOptions:{userOverride:ce,useCustomTransfers:!0,feeExecutionMode:f,signal:t},tokenDescriptor:ue});return Ce.preview?{...Ce,preview:Ce.preview}:null}if(!w||!S||!v||!k)return null;const re=x||b||S,se=i?l?.amountInMax??0n:O;if(se===0n&&!e.feeOnlyAction)return null;const ie=await $o({requiredNetFunding:se,feeOnlyAction:e.feeOnlyAction,buildBatches:ce=>j({fundingAmountOverride:ce}).then(_=>An(_,re)),fundingToken:ee,estimate:R,executionOptions:{userOverride:re,useCustomTransfers:!0,feeExecutionMode:f,signal:t},tokenDescriptor:ue});return ie.preview?{...ie,preview:ie.preview}:null}if(r<=0||!x)return null;const D=x||b;if(!(!s&&!d&&n.asset._source==="wallet"&&n.asset.chainId!==y)&&!C&&!E&&!F||F)return null;const M=await Yn(n.asset,p,B),P=Bt(I.parseUnits(n.amount,n.asset.decimals),n.asset.decimals,M,"floor"),q=await T();if(q.length===0)return null;const z=n.asset._source==="wallet",X=z&&(n.asset._fundingWallet==="external"||d&&n.asset._fundingWallet!=="embedded")&&z&&n.asset.chainId===y,N={chainId:y,tokenAddress:B,symbol:A.getTokenByAddress(B,y)?.symbol??p.symbol,decimals:M};if(X){const O=await g.relayerService.estimateBatchGas({user:D,outputToken:B,stepIndex:0,chainBatches:q,signal:t}),ee=o?Ts(P,O.gasFee,Mn):(()=>{const ue=Hn(P,Mn),re=ue+O.gasFee;return{netAmount:P,spicenetFee:ue,totalFee:re,grossAmount:P+re}})();return{preview:{...N,grossAmount:ee.grossAmount,netAmount:ee.netAmount,totalFee:ee.totalFee,gasFee:O.gasFee,spicenetFee:ee.spicenetFee,bridgeFee:0n,gasQuoteSource:O.gasQuoteSource},feeEstimate:null}}const H=q.some(O=>O.tokenTransfers?.length),V=await R(q,B,P,H?{userOverride:D,useCustomTransfers:!0,feeExecutionMode:f,signal:t}:f?{userOverride:D,feeExecutionMode:f,signal:t}:{userOverride:D,signal:t}),G=xn(V,N),J=G??bi(q,N,P);if(!J)return null;if(!o||!G)return{preview:J,feeEstimate:V};const U=J.gasFee+(J.bridgeFee??0n),L=Ts(P,U,Mn);return{preview:{...J,grossAmount:L.grossAmount,netAmount:L.netAmount,totalFee:L.totalFee,spicenetFee:L.spicenetFee},feeEstimate:V}}function Ci(e){if(!e||typeof e!="object")return!1;const t=e;return t.version===1&&typeof t.identity=="string"&&/^[0-9]+$/.test(t.baseline)&&/^[0-9]+$/.test(t.confirmedAmount)&&(!t.pending||/^[1-9][0-9]*$/.test(t.pending.amount)&&(!t.pending.hash||/^0x[0-9a-f]{64}$/i.test(t.pending.hash)))}async function er(e){const t=()=>e.isNative?e.sourceClient.getBalance({address:e.recipient}):e.sourceClient.readContract({address:e.tokenAddr,abi:I.erc20Abi,functionName:"balanceOf",args:[e.recipient]});let n=e.state;if(n&&(!Ci(n)||n.identity!==e.identity))throw new Error("Restore the pending funding operation's original source, wallets and amount before retrying");n||(n={version:1,identity:e.identity,baseline:(await t()).toString(),confirmedAmount:"0"});const s=()=>e.onState({...n,pending:n.pending&&{...n.pending}}),o=()=>{delete n.pending,s()},r=()=>{n.confirmedAmount=(BigInt(n.confirmedAmount)+BigInt(n.pending.amount)).toString(),delete n.pending,s()};if(n.pending){if(!n.pending.hash)throw new Error("Source funding submission is unconfirmed; recover it before retrying to avoid spending twice");const{receipt:p}=await Ns({client:e.sourceClient,hash:n.pending.hash,call:fa(e.recipient,e.tokenAddr,e.isNative,BigInt(n.pending.amount)),onRepriced:f=>{n.pending.hash=f,s()},onCancelled:o});if(p.status!=="success")throw o(),new Error("Source funding reverted; retry when ready");r()}if(e.reconcileOnly)return;const i=BigInt(n.confirmedAmount),l=async()=>{if(BigInt(n.confirmedAmount)>0n&&await t()<BigInt(n.baseline)+BigInt(n.confirmedAmount))throw new Error("Previously funded assets are no longer reserved in the embedded wallet; recover this operation before funding again")};await l();const d=e.requiredAmount>i?e.requiredAmount-i:0n;if(d===0n)return;const{extWc:c,viemChain:m}=await e.createWallet();await ha({extWc:c,sourceClient:e.sourceClient,recipient:e.recipient,tokenAddr:e.tokenAddr,isNative:e.isNative,amount:d,viemChain:m,observer:{onSending:async()=>{await e.observer?.onSending?.(0)},onSubmitted:(p,f)=>{n.pending={amount:d.toString(),hash:f},s(),e.observer?.onSubmitted?.(0,f)},onConfirmed:(p,f)=>{r(),e.observer?.onConfirmed?.(0,f)},onRejected:()=>{o(),e.observer?.onRejected?.(0)},onReverted:(p,f)=>{o(),e.observer?.onReverted?.(0,f)}}}),await l()}function Au(e){return e.selectedAsset||!e.feeOnlyAction||!e.actionProceeds?e.selectedAsset:{amount:"0",asset:{...e.destinationToken,name:e.destinationToken.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"wallet",_fundingWallet:"embedded"}}}function tr(e){const t=Au(e),n=t?.asset;return JSON.stringify([e.externalWalletAddress?.toLowerCase(),(e.embeddedWalletAddress??e.providerEmbeddedAddress)?.toLowerCase(),n?.address.toLowerCase(),n?.chainId,n?.decimals,n?._source,n?._fundingWallet,t?.amount,e.resolvedChainId,e.destinationToken.address.toLowerCase(),e.recipient?.toLowerCase(),e.isPayMode,e.currentPaymentAmount??"0",e.isFeeInclusiveInput??!1,e.sourceFundingRecoveryKey??"generic",e.destinationToken.decimals,n?n.isNative??A.isNativeToken(n.address):null,...e.feeOnlyAction?[!0]:[]])}async function Gs(e,t){const n=e.selectedAsset.asset,s=A.normalizeNativeTokenAddress(n.address);await er({identity:tr(e),state:e.sourceFunding,onState:o=>{e.sourceFunding=o,e.onSourceFundingChange?.(o)},createWallet:()=>On({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:n.chainId,onSwitch:()=>e.ui.setStatusMsg("Switching source network...")}),sourceClient:g.getClientForChain(n.chainId),recipient:e.embeddedWalletAddress??e.providerEmbeddedAddress,tokenAddr:s,isNative:n.isNative||A.isNativeToken(s),requiredAmount:t,observer:e.fundingObserver})}function vi(e,t){const n=e.selectedAsset?.asset;if(!n||n._source!=="wallet")return;const s=Qt(n,e.resolvedChainId);if(!s||!g.addressesEqual(s,e.executionTokenAddress))return;const o=A.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),r=Kt(t,e.executionTokenDecimals??o?.decimals??e.destinationToken.decimals,n.decimals),i=n.balance+BigInt(e.sourceFunding?.confirmedAmount??"0");if(r<=i)return;const l=I.formatUnits(r,n.decimals),d=I.formatUnits(i,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${l} ${n.symbol}; available ${d} ${n.symbol}.`)}function In(e){const t=A.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:e.executionTokenDecimals??t?.decimals??e.destinationToken.decimals}}function fs(e,t,n){const s=xn(e,In(t));if(!s)return;const o=s.bridgeFee??0n,r=s.gasFee+o;if(t.isFeeInclusiveInput){const c=Ts(n,r,Mn);if(!c.coversFees){const{symbol:m,decimals:p}=In(t);throw new Error(`Amount too small: fees are ${I.formatUnits(r,p)} ${m}.`)}if(t.needsSwap&&!t.exactOutputSwap&&(t.swapInputAmount??t.feeQuote?.preview?.netAmount)!=null&&c.netAmount<(t.swapInputAmount??t.feeQuote.preview.netAmount))throw new Error("Fees changed. Refresh the swap quote before retrying so the total stays within your entered amount.");return{grossAmount:c.grossAmount,netAmount:c.netAmount,combinedFeeAmount:c.totalFee,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:c.spicenetFee,gasFee:s.gasFee,bridgeFee:o}}}const i=n,l=Hn(n,Mn),d=l+r;return{grossAmount:i+d,netAmount:i,combinedFeeAmount:d,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:l,gasFee:s.gasFee,bridgeFee:o}}}function ki(e,t,n){let s=0n,o=0n;const r=n.toLowerCase();for(const i of e)if(i.chainId===t)for(const l of i.calls??[]){if(A.isNativeToken(n)&&l.data==="0x"&&l.value>0n){g.addressesEqual(l.to,A.SPICE_PLATFORM_FEE_RECIPIENT)?s+=l.value:g.addressesEqual(l.to,A.SPICE_GAS_FEE_RECIPIENT)&&(o+=l.value);continue}if(l.to.toLowerCase()===r)try{const d=I.decodeFunctionData({abi:I.erc20Abi,data:l.data});if(d.functionName!=="transfer")continue;const c=d.args[0].toLowerCase(),m=d.args[1];c===A.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=m:c===A.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(o+=m)}catch{continue}}return{spicenetFee:s,gasFee:o}}function nr(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,o=ki(e,t.resolvedChainId,s);return o.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||o.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Nn(o.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Nn(o.gasFee,n.feeBreakdown.gasFee,100n)}function Si(e,t){if(!e.isFeeInclusiveInput||!e.needsSwap||e.swapInputAmount==null||!e.selectedAsset)return;const n=In(e),s=Bt(I.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),e.selectedAsset.asset.decimals,n.decimals,"floor"),o=ki(t,e.resolvedChainId,e.resolvedTokenIn??e.executionTokenAddress);if(e.swapInputAmount+o.gasFee+o.spicenetFee>s)throw new Error("Swap input plus fees exceeds the entered amount. Refresh the quote before retrying.")}function Ai(e,t){return e?Nn(e.grossAmount,t.grossAmount,100n)&&Nn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Nn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Nn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}function Ii(e,t){const n=A.getTokenByAddress(t,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:t,symbol:n?.symbol??e.selectedAsset?.asset.symbol??"",decimals:e.executionTokenDecimals??n?.decimals??e.selectedAsset?.asset.decimals??e.destinationToken.decimals}}async function sr(e,t){const n=e.feeQuote;return n?.feeEstimate&&n.grossFundingAmount!==void 0?{grossFundingAmount:n.grossFundingAmount,feeEstimate:n.feeEstimate}:$o({...t,feeOnlyAction:e.feeOnlyAction,estimate:e.execution.estimate,tokenDescriptor:Ii(e,t.fundingToken)})}function Ei(e,t){if(e.feeOnlyAction)return 0n;const n=e.selectedIsEquivalent?t:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(n===0n)throw new Error("Quote not available yet");return n}function or(e,t,n){const s=t instanceof Error?t:new Error(String(t));if(s.name==="AbortError"||n){e.ui.setStep("idle");return}const o=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(o),e.ui.setError(o)}function rr(e,t){const n=g.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}function Iu(e){if(!e.isFeeInclusiveInput||e.feeExecutionMode==="user-transfer")return e;const t=A.normalizeNativeTokenAddress(e.executionTokenAddress);let n=!1;const s=(o,r)=>A.isNativeToken(t)?{to:o,value:r,data:"0x"}:{to:t,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[o,r]})};return{...e,feeExecutionMode:"user-transfer",execution:{...e.execution,execute:(...o)=>{if(!n)throw new Error("Inclusive supply requires a destination fee quote");return e.execution.execute(...o)},estimate:async(o,r,i,l)=>{const d=await e.execution.estimate(ps(o,e.resolvedChainId,t),r,i,{...l,feeExecutionMode:"backend-transfer"});if(!xn(d,In(e)))throw new Error("Inclusive supply requires a destination fee quote");return d},buildSupplyChainBatches:async o=>{const r=o?.actionContextOverride,i=await e.execution.buildSupplyChainBatches({...o,actionContextOverride:r?{...r,feeExecutionMode:"backend-transfer"}:void 0});if(!r?.feeBreakdown)return i;n=!0;const{spicenetFee:l,gasFee:d,bridgeFee:c}=r.feeBreakdown,m=[...l>0n?[s(A.SPICE_PLATFORM_FEE_RECIPIENT,l)]:[],...d+c>0n?[s(A.SPICE_GAS_FEE_RECIPIENT,d+c)]:[]],p=ps(i,e.resolvedChainId,t),f=p[p.length-1];if(f?.chainId!==e.resolvedChainId)throw new Error("Inclusive supply requires a final destination action batch");return p.map(h=>h===f?{...h,calls:[...m,...h.calls]}:h)}}}}async function Zs(e){if(e.feeOnlyAction){e.ui.setError("Fee-only actions require output mode and a zero action amount");return}if(e.sourceConversion)return hi(e,Zs,s=>Gs(e,s));if(e.sourceConversionRequired){e.ui.setError("Wait for the source funding quote before continuing");return}if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance&&!e.sourceFunding){e.ui.setError("Insufficient balance");return}const t=e.selectedAsset;try{e={...e,executionTokenDecimals:await Yn(t.asset,e.destinationToken,e.executionTokenAddress)}}catch(s){or(e,s,!1);return}if(e=Iu(e),en(t.asset,e.isNon7702)){const s=e.isNon7702&&e.isSourceDestToken,o=e.externalWalletAddress;if(s?!o:!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(s){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const r=await Fi({...e,activeSignerAddress:e.externalWalletAddress,activeSignerWallet:e.externalWallet});e.ui.setTxHash(r??null)}else{e.ui.setStep("building"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const r=new AbortController;e.refs.abortControllerRef.current=r,await Eu(e,r.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(s?"Transaction confirmed":"Deposit confirmed")}catch(r){or(e,r,!!e.refs.abortControllerRef.current?.signal.aborted)}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("building"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const n=new AbortController;e.refs.abortControllerRef.current=n;try{const s=Bt(I.parseUnits(t.amount,t.asset.decimals),t.asset.decimals,In(e).decimals,"floor"),o=s;let r=await e.execution.buildSupplyChainBatches();const i=t.asset._source==="wallet",l=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!i&&!r.some(b=>A.isSpicenetChainId(b.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const d=r.some(b=>b.tokenTransfers?.length),c=d?{userOverride:l,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:l,feeExecutionMode:e.feeExecutionMode}:{userOverride:l};let m=s;const p=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap;let f,h=e.feeExecutionMode==="user-transfer"&&!p?o:void 0;for(let b=0;b<4;b+=1){const y=b===0&&e.feeQuote?.feeEstimate||await e.execution.estimate(r,e.executionTokenAddress,d?m:0n,c),w=xn(y,In(e));f=e.feeExecutionMode==="user-transfer"&&w?fs(y,e,o):void 0,e.isFeeInclusiveInput&&f&&!p&&(h=f.netAmount);const S=f?.grossAmount??w?.grossAmount??m;if(S===m){m=S;break}m=S,r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:m,actionAmountOverride:h,actionContextOverride:f})}e.feeExecutionMode==="user-transfer"&&(vi(e,m),r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:m,actionAmountOverride:h,actionContextOverride:f}));let x=f;await e.execution.execute(r,e.executionTokenAddress,d?m:0n,e.execution.onProgress,n.signal,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,validateBeforeSubmit:async b=>Si(e,b),adjustBatchesForEstimate:({feeEstimate:b,chainBatches:y})=>{const w=fs(b,e,o);if(!w)return null;const S=Ai(x,w),v=nr(y,e,w);return S||v?null:(x=w,e.isFeeInclusiveInput&&!p&&(h=w.netAmount),e.execution.buildSupplyChainBatches({fundingAmountOverride:w.grossAmount,actionAmountOverride:h,actionContextOverride:w}))}}:{...c,skipPreSubmitFeeEstimate:!0}),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(s){or(e,s,n.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function Eu(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const s=e.selectedAsset.asset,o=en(s,e.isNon7702);if(o&&!e.externalWallet)throw new Error("Please connect your external wallet to continue");const r=Bt(I.parseUnits(e.selectedAsset.amount,s.decimals),s.decimals,In(e).decimals,"floor"),i=r,l=s._source==="wallet"&&s.chainId===e.resolvedChainId;let d=await e.execution.buildSupplyChainBatches();const c={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let m=r;const p=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap;let f=e.feeExecutionMode==="user-transfer"&&!p?i:void 0,h;if(l){const v=e.feeQuote?.preview.gasFee??(await g.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d})).gasFee,k=e.isFeeInclusiveInput&&e.feeExecutionMode==="user-transfer"?Ts(r,v,Mn):null;if(k&&!k.coversFees)throw new Error("Amount too small to cover supply fees");const C=k?.spicenetFee??Hn(r,10n),E=C+v;m=k?.grossAmount??r+E,k&&!p&&(f=k.netAmount),e.feeExecutionMode==="user-transfer"&&(h={grossAmount:m,netAmount:k?.netAmount??i,combinedFeeAmount:E,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:C,gasFee:v,bridgeFee:0n}})}else for(let v=0;v<4;v+=1){const k=await e.execution.estimate(d,e.executionTokenAddress,0n,c),C=e.feeExecutionMode==="user-transfer"?fs(k,e,i):void 0,E=xn(k,In(e)),F=C?.grossAmount??(E?E.grossAmount>r?E.grossAmount:r:m);if(h=C,e.isFeeInclusiveInput&&!p&&C&&(f=C.netAmount),F===m){m=F;break}m=F;const B=A.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),j=Kt(m,e.executionTokenDecimals??B?.decimals??e.destinationToken.decimals,s.decimals);d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:m,sourceFundingAmountOverride:j,withdrawalAmountOverride:m,actionAmountOverride:f,actionContextOverride:C})}const x=A.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let b=l?m:Kt(m,e.executionTokenDecimals??x?.decimals??e.destinationToken.decimals,s.decimals);vi(e,m),d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:m,sourceFundingAmountOverride:b,withdrawalAmountOverride:m,actionAmountOverride:f,actionContextOverride:h});const y=async v=>{o&&await Gs(e,v)};o&&(e.ui.setStatusMsg("Funding embedded wallet..."),await y(b));let w=b;if(e.feeExecutionMode==="user-transfer")for(let v=0;v<4;v+=1){const k=await e.execution.estimate(d,e.executionTokenAddress,0n,c),C=fs(k,e,i);if(!C)break;const E=l?C.grossAmount:Kt(C.grossAmount,e.executionTokenDecimals??x?.decimals??e.destinationToken.decimals,s.decimals);if(o&&E>w&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await y(E),w=E),h=C,e.isFeeInclusiveInput&&!p&&C&&(f=C.netAmount),m=C.grossAmount,b=E,d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:m,sourceFundingAmountOverride:b,withdrawalAmountOverride:m,actionAmountOverride:f,actionContextOverride:C}),nr(d,e,C))break}e.ui.setStatusMsg("Preparing transaction...");let S=h;await e.execution.execute(d,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,validateBeforeSubmit:async v=>Si(e,v),adjustBatchesForEstimate:({feeEstimate:v,chainBatches:k})=>{const C=fs(v,e,i);if(!C)return null;const E=Ai(S,C),F=nr(k,e,C);if(E||F)return null;if(C.grossAmount>m)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");S=C,e.isFeeInclusiveInput&&!p&&(f=C.netAmount);const B=l?C.grossAmount:Kt(C.grossAmount,e.executionTokenDecimals??x?.decimals??e.destinationToken.decimals,s.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:C.grossAmount,sourceFundingAmountOverride:B,withdrawalAmountOverride:C.grossAmount,actionAmountOverride:f,actionContextOverride:C})}}:{...c,skipPreSubmitFeeEstimate:!0})}async function Fi(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,s=e.activeSignerAddress??e.externalWalletAddress;if(!s||!n)throw new Error("Please connect your wallet to continue");const o=I.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),r={userAddress:s,executorAddress:s,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},i=await e.buildActionCalls(o,r);if(i.length===0)throw new Error("No action calls configured");const{extWc:l,viemChain:d}=await On({wallet:n,account:s,chainId:e.resolvedChainId}),c=g.getClientForChain(e.resolvedChainId);return Mo({extWc:l,client:c,calls:i,viemChain:d,errorMessage:"Transaction failed"})}async function Fu(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,s=I.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),o=Ei(e,s),r=e.resolvedTokenIn||Qt(n,e.resolvedChainId)||n.address,i=Ii(e,r).decimals,l=w=>Kt(w,i,n.decimals),d={userOverride:t,useCustomTransfers:!0,requireDestinationReceipt:e.feeOnlyAction},c=t,m=async(w,S,v)=>An(await e.execution.buildPayChainBatches({fundingAmountOverride:w}),c,S,v),{grossFundingAmount:p,feeEstimate:f}=await sr(e,{requiredNetFunding:o,buildBatches:w=>m(w),fundingToken:r,executionOptions:{...d,feeExecutionMode:e.feeExecutionMode}});let h=await m(p,e.actionProceeds?void 0:f,{payoutAlreadyGross:!0});const x=xi(e,r,p);x.prepareForSigning&&(h=await x.prepareForSigning(h)),await Gs(e,l(p));const b=h.some(w=>w.tokenTransfers?.length),y={...d,...x,skipUserFundingPreflight:!e.actionProceeds,skipPreSubmitFeeEstimate:!0};return await e.execution.execute(h,r,b?p:0n,w=>{w.txHash&&(e.ui.setPaymentResult(S=>({...S??{status:"processing"},txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,b?y:{userOverride:t,skipUserFundingPreflight:!0,skipPreSubmitFeeEstimate:!0})}async function ar(e){if(e.feeOnlyAction&&(e.parsedAmount!==0||!e.selectedAsset&&!e.actionProceeds||e.onPayExecute||!e.feeQuote?.feeEstimate&&!e.feeQuote?.fundingConversion||e.feeQuote.grossFundingAmount===void 0||!e.actionProceeds&&e.feeQuote.grossFundingAmount===0n)){e.ui.setError("Select a fee source and wait for its fee quote before continuing");return}if(e.sourceConversion)return hi(e,ar,s=>Gs(e,s));if(e.sourceConversionRequired){e.ui.setError("Wait for the source funding quote before continuing");return}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.sourceFunding){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.selectedAsset)try{e={...e,executionTokenDecimals:await Yn(e.selectedAsset.asset,e.destinationToken,e.executionTokenAddress)}}catch(s){rr(e,s);return}const n=(e.feeQuote?.grossFundingAmount!==0n||!e.actionProceeds)&&en(e.selectedAsset?.asset,e.isNon7702);if(n||e.isNon7702&&t&&!e.feeOnlyAction){const s=n?e.externalWalletAddress: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)&&!e.feeOnlyAction)o=await Fi(n?{...e,activeSignerAddress:e.externalWalletAddress,activeSignerWallet:e.externalWallet}:e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,i=I.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),l=Ei(e,i),d=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!d)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const c=e.resolvedTokenIn||r.address,{grossFundingAmount:m}=await sr(e,{requiredNetFunding:l,buildBatches:h=>e.execution.buildPayChainBatches({fundingAmountOverride:h}),fundingToken:c,executionOptions:{userOverride:d,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}}),p=await e.execution.buildPayChainBatches({fundingAmountOverride:m}),f=await e.onPayExecute({asset:r,amount:e.currentPaymentAmount,amountWei:i,destinationToken:e.destinationToken,chainBatches:p,requiredNetFunding:l,grossFundingAmount:m,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:c,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});f&&(e.ui.setTxHash(f),e.ui.setPaymentResult(h=>({...h??{status:"processing"},txHash:f}))),o=f||void 0}else o=await Fu(e);e.ui.setPaymentResult(r=>({status:"success",txHash:r?.txHash||o||""}))}catch(o){rr(e,o)}finally{e.ui.setIsExecuting(!1)}return}if(e.isNon7702&&!e.embeddedWalletAddress&&!e.providerEmbeddedAddress){e.ui.setError("Embedded wallet is not ready for this payment source");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=I.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),o={userOverride:e.embeddedWalletAddress??e.providerEmbeddedAddress??e.address,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,requireDestinationReceipt:e.feeOnlyAction};if(t&&!e.feeOnlyAction){const b=await e.execution.buildPayChainBatches(),y=await e.execution.execute(b,e.executionTokenAddress,0n,w=>{w.txHash&&(e.ui.setPaymentResult(S=>({...S??{status:"processing"},txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,o);e.ui.setPaymentResult(w=>({status:"success",txHash:w?.txHash||y}));return}const r=e.selectedAsset?.asset;if(!r&&!e.actionProceeds)throw new Error("Select a payment source");const i=e.feeQuote?.fundingConversion?.tokenIn||e.resolvedTokenIn||r?.address||e.destinationToken.address,l=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:s,d=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,{grossFundingAmount:c,feeEstimate:m}=e.feeQuote?.fundingConversion?{grossFundingAmount:e.feeQuote.grossFundingAmount,feeEstimate:void 0}:await sr(e,{requiredNetFunding:l,buildBatches:b=>e.execution.buildPayChainBatches({fundingAmountOverride:b}).then(y=>An(y,d)),fundingToken:i,executionOptions:o}),p=e.feeQuote?.fundingBatches??An(await e.execution.buildPayChainBatches({fundingAmountOverride:c}),d,e.actionProceeds?void 0:m,{payoutAlreadyGross:!0}),f=xi(e,e.feeQuote?.fundingConversion?.tokenOut??i,c),h=e.feeOnlyAction||p.some(b=>b.tokenTransfers?.length),x=await e.execution.execute(p,i,h?c:0n,b=>{b.txHash&&(e.ui.setPaymentResult(y=>({...y,txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,{...o,...f,skipPreSubmitFeeEstimate:!0});e.ui.setPaymentResult(b=>({status:"success",txHash:b?.txHash||x}))}catch(s){rr(e,s)}finally{e.ui.setIsExecuting(!1)}}const Ti="spiceflow:source-funding";async function Tu(e){const t=()=>{if(!e.isCurrent())throw new Error("The source, amount or account changed. Review the form before retrying.")};t();const n=e.ctx;await e.run({...n,sourceFunding:void 0,onSourceFundingChange:void 0,fundingObserver:{onSending:t},execution:{...n.execution,execute:async(s,o,r,i,l,d)=>(t(),n.execution.execute(s,o,r,i,l,{...d,validateBeforeSubmit:async c=>{t(),await d?.validateBeforeSubmit?.(c),t()}}))}})}function Bu(e,t,n,s,o){if(!o.trim()||o.length>128||!I.isAddress(n)||!I.isAddress(s))throw new Error("External action recovery requires valid wallet addresses and a stable recovery key");return`spiceflow:externalSupply:${JSON.stringify([e,t,n.toLowerCase(),s.toLowerCase(),o])}`}function Xs(e){const t=localStorage.getItem(e);if(!t)return null;const n=JSON.parse(t),s=o=>!o||Number.isSafeInteger(o.chainId)&&o.chainId>0&&(!o.hash||/^0x[0-9a-f]{64}$/i.test(o.hash));if(n.version!==2||n.scope!==e||!I.isAddress(n.destinationToken)||!Number.isInteger(n.destinationDecimals)||n.destinationDecimals<0||n.destinationDecimals>255||typeof n.sourceKey!="string"||typeof n.routeSubmitted!="boolean"||n.sourceFunding!==void 0&&!Ci(n.sourceFunding)||!["funding","routing","action","complete"].includes(n.phase)||!Number.isInteger(n.confirmedCalls)||n.confirmedCalls<0||n.amount!==void 0&&!/^[1-9][0-9]*$/.test(n.amount)||!s(n.pendingCall)||n.calls!==void 0&&(!Array.isArray(n.calls)||n.calls.length===0||n.calls.some(o=>!I.isAddress(o.to)||!/^[0-9]+$/.test(o.value)||!/^0x(?:[0-9a-f]{2})*$/i.test(o.data)))||n.confirmedCalls>(n.calls?.length??0)||n.phase==="complete"&&(n.confirmedCalls!==n.calls?.length||n.pendingCall||n.sourceFunding?.pending)||n.pendingCall&&(n.phase!=="action"||n.confirmedCalls>=(n.calls?.length??0))||["action","complete"].includes(n.phase)&&(!n.amount||!n.calls)||n.route&&(typeof n.route.actionId!="string"||!/^[a-zA-Z0-9_-]+$/.test(n.route.actionId)||n.route.intentId!==`${n.route.actionId}/${n.route.intentIndex}`||!Number.isInteger(n.route.intentIndex)||n.route.intentIndex<0||!Array.isArray(n.route.spicenetSteps)||n.route.spicenetSteps.length===0||n.route.spicenetSteps.some(o=>typeof o!="boolean")))throw new Error("Saved external action is invalid or unsupported; recovery is required before starting another supply");return n}function ir(e){return{destinationToken:e.destinationToken,destinationDecimals:e.destinationDecimals,phase:e.phase,confirmedCalls:e.confirmedCalls,totalCalls:e.calls?.length??0,amount:e.amount,requiresRecovery:!!(e.sourceFunding?.pending&&!e.sourceFunding.pending.hash||e.pendingCall&&!e.pendingCall.hash||e.routeSubmitted&&!e.route&&e.phase==="routing")}}function Bi(e,t){return!t||t.routeSubmitted||t.route||t.pendingCall||t.confirmedCalls||t.sourceFunding?.pending||!["funding","routing"].includes(t.phase)?!1:(localStorage.setItem(`spiceflow:archivedSourceSupply:${Date.now()}:${crypto.randomUUID()}`,JSON.stringify(t)),localStorage.removeItem(e),window.dispatchEvent(new Event("spiceflow:source-funding")),!0)}async function ju(e){return navigator.locks?navigator.locks.request(e,{ifAvailable:!0},async t=>{if(!t)return!1;const n=Xs(e);if(!n||n.routeSubmitted||n.route||n.pendingCall||n.confirmedCalls||!["funding","routing"].includes(n.phase))return!1;if(n.sourceFunding?.pending){if(!n.sourceFunding.pending.hash)return!1;const s=JSON.parse(n.sourceFunding.identity),o=JSON.parse(e.slice(25));if(!Array.isArray(s)||!g.addressesEqual(s[0],o[2])||!g.addressesEqual(s[1],o[3])||!I.isAddress(s[2])||!Number.isSafeInteger(s[3]))throw new Error("Saved funding identity is invalid");await er({identity:n.sourceFunding.identity,state:n.sourceFunding,reconcileOnly:!0,recipient:o[3],tokenAddr:s[2],isNative:s[16]===!0||A.isNativeToken(s[2]),sourceClient:g.getClientForChain(s[3]),requiredAmount:0n,createWallet:async()=>{throw new Error("Reconciliation cannot request funding")},onState:r=>{n.sourceFunding=r,localStorage.setItem(e,JSON.stringify(n))}})}return Bi(e,n)}):!1}function Ru(e){const t=Xs(e);if(t&&t.phase!=="complete")throw new Error("Finish the pending external action before starting another supply");localStorage.removeItem(e)}function Du(e,t,n){const s=[],o=(r,i,l)=>{l>0n&&s.push(A.isNativeToken(r)?{to:i,value:l,data:"0x"}:{to:r,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[i,l]})})};return t.feeExecutionMode==="user-transfer"&&t.feeBreakdown&&(o(t.feeToken??t.destinationToken,A.SPICE_PLATFORM_FEE_RECIPIENT,t.feeBreakdown.spicenetFee),o(t.feeToken??t.destinationToken,A.SPICE_GAS_FEE_RECIPIENT,t.feeBreakdown.gasFee+t.feeBreakdown.bridgeFee)),o(t.destinationToken,n,e),s}const lr=e=>e.map(t=>({to:t.to.toLowerCase(),data:t.data.toLowerCase(),value:t.value.toString()})),ji=e=>JSON.stringify([e.selectedAsset?.asset.address.toLowerCase(),e.selectedAsset?.asset.chainId,e.selectedAsset?.asset.decimals,e.selectedAsset?.asset._source,e.selectedAsset?.asset._fundingWallet,e.selectedAsset?.amount]);async function Nu(e){if(!navigator.locks)throw new Error("This browser cannot safely resume external wallet actions");await navigator.locks.request(e.scope,{ifAvailable:!0},async t=>{if(!t)throw new Error("This external action is already running in another tab");const{ctx:n,scope:s,buildActionCalls:o,onRecord:r}=e,i=()=>{if(e.isCurrent?.()===!1)throw new Error("Restore the original account before resuming this action")};i();const l=n.externalWalletAddress,d=n.embeddedWalletAddress??n.providerEmbeddedAddress,c=JSON.parse(s.slice(25));if(!s.startsWith("spiceflow:externalSupply:")||!Array.isArray(c)||c.length!==5||c[1]!==n.resolvedChainId||!g.addressesEqual(c[2],l)||!g.addressesEqual(c[3],d))throw new Error("Restore the pending action's original wallets and network before resuming");if(!l||!d||!n.externalWallet)throw new Error("Connect the external wallet and its Spicenet account");const m=Xs(s);if(n.isPayMode||A.isNativeToken(n.destinationToken.address))throw new Error("External action execution currently supports exact-input supplies into ERC20 destination actions");let p=m;const f=b=>o(BigInt(b),{userAddress:l,executorAddress:l,chainId:n.resolvedChainId,destinationToken:n.destinationToken.address}),h=()=>{localStorage.setItem(s,JSON.stringify(p)),r({...p})};if(p){if(!g.addressesEqual(p.destinationToken,n.destinationToken.address)||p.destinationDecimals!==n.destinationToken.decimals)throw new Error("Restore the pending action's destination token before resuming");if(p.calls&&JSON.stringify(lr(await f(p.amount)))!==JSON.stringify(p.calls))throw new Error("The intended action changed; restore its original configuration before resuming");if(ir(p).requiresRecovery)throw new Error("A transaction submission is unconfirmed; recover it before retrying to avoid spending twice");if(p.pendingCall&&p.pendingCall.chainId!==n.resolvedChainId)throw new Error("Saved external action chain is invalid");if(p.phase==="complete"){n.ui.setTxHash(p.lastHash??null),n.ui.setStep("success");return}if(!p.routeSubmitted&&p.phase!=="action"&&p.sourceKey!==ji(n))throw new Error("Restore the pending action's source and amount before resuming")}else{if(!n.selectedAsset||n.parsedAmount<=0)throw new Error("Select an asset and enter an amount");p={version:2,scope:s,destinationToken:n.destinationToken.address,destinationDecimals:n.destinationToken.decimals,sourceKey:ji(n),phase:"funding",confirmedCalls:0,routeSubmitted:!1},h()}const x=async b=>{if(b<=0n)throw new Error("The route did not fund a positive action amount");const y=lr(await f(b.toString()));if(!y.length)throw new Error("No external action calls configured");p.amount=b.toString(),p.calls=y,h()};try{if(p.phase!=="action")if(p.route){n.ui.setStatusMsg("Resuming the existing funding route...");const y=p.route;await Ao({...y,totalSteps:y.spicenetSteps.length,isSpicenetStep:w=>y.spicenetSteps[w],maxPolls:180}),p.phase="action",h()}else if(n.selectedAsset&&en(n.selectedAsset.asset,n.isNon7702)&&n.isSourceDestToken)await x(I.parseUnits(n.selectedAsset.amount,n.destinationToken.decimals)),p.phase="action",h();else{let y;const w={onSending:async()=>{if(i(),!(await(await n.externalWallet.getEthereumProvider()).request({method:"eth_accounts"})).some(v=>g.addressesEqual(v,l)))throw new Error("Restore the original external wallet before funding");p.phase="funding",h()}},S=async v=>{let k=0n;for(const C of v)if(C.chainId===n.resolvedChainId){for(const E of C.calls)if(g.addressesEqual(E.to,n.destinationToken.address))try{const F=I.decodeFunctionData({abi:I.erc20Abi,data:E.data});F.functionName==="transfer"&&g.addressesEqual(F.args[0],l)&&(k+=F.args[1])}catch{}}await x(k)};if(await Zs({...n,sourceFunding:p.sourceFunding,onSourceFundingChange:v=>{p.sourceFunding=v,h()},fundingObserver:w,ui:{...n.ui,setIsExecuting:()=>{},setStep:v=>{v!=="success"&&n.ui.setStep(v)},setError:v=>{typeof v=="string"&&v&&(y=v)}},execution:{...n.execution,execute:async(v,k,C,E,F,B)=>{i(),await S(v),p.phase="routing",h();const j=await n.execution.execute(v,k,C,T=>{T.step==="submitting"&&(p.routeSubmitted=!0,h()),T.actionId&&T.intentId&&T.intentIndex!==void 0&&(p.route={actionId:T.actionId,intentId:T.intentId,intentIndex:T.intentIndex,spicenetSteps:v.map(R=>R.domain==="spicenet")},h()),n.execution.onProgress({...T,step:T.step==="success"?"executing":T.step})},F,{...B,adjustBatchesForEstimate:B?.adjustBatchesForEstimate?async T=>{const R=await B.adjustBatchesForEstimate(T);return R&&await S(R),R}:void 0});return p.phase="action",h(),j}}}),y)throw new Error(y);if(ir(p).phase!=="action")throw new Error("Funding route has not completed; resume it before continuing")}const b=await f(p.amount);if(JSON.stringify(lr(b))!==JSON.stringify(p.calls))throw new Error("The intended external action changed during funding");if(p.pendingCall){const y=await Ns({client:g.getClientForChain(p.pendingCall.chainId),hash:p.pendingCall.hash,call:b[p.confirmedCalls],onRepriced:v=>{p.pendingCall.hash=v,h()},onCancelled:()=>{delete p.pendingCall,h()}}),w=y.receipt,S=y.hash;if(delete p.pendingCall,w.status==="success"&&(p.confirmedCalls++,p.lastHash=S),h(),w.status!=="success")throw new Error("External action transaction reverted; retry when ready")}if(p.confirmedCalls<b.length){const{extWc:y,viemChain:w}=await On({wallet:n.externalWallet,account:l,chainId:n.resolvedChainId}),S=p.confirmedCalls;n.ui.setStatusMsg(`Confirm the remaining ${b.length-S} action transactions in your external wallet`),await Mo({extWc:y,client:g.getClientForChain(n.resolvedChainId),calls:b.slice(S),viemChain:w,errorMessage:"External action transaction reverted",observer:{onSending:async()=>{if(i(),!(await y.getAddresses()).some(v=>g.addressesEqual(v,l)))throw new Error("Restore the original external wallet before resuming");p.pendingCall={chainId:n.resolvedChainId},h()},onSubmitted:(v,k)=>{p.pendingCall.hash=k,h()},onConfirmed:(v,k)=>{p.confirmedCalls=S+v+1,p.lastHash=k,delete p.pendingCall,h()},onRejected:()=>{delete p.pendingCall,h()},onReverted:()=>{delete p.pendingCall,h()}}})}p.phase="complete",h(),n.ui.setTxHash(p.lastHash??null),n.ui.setStep("success"),n.ui.setStatusMsg("External wallet action confirmed")}finally{e.recovery==="balance"&&Bi(s,p)&&r(null)}})}function Mu(e){const t=e.chainTokens??e.chainTokenConfig;if(Array.isArray(t))return t.filter(n=>typeof n=="string");if(t&&typeof t=="object")return t}const ms=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:s})=>{const o=u.useContext(g.SpiceFlowProviderContext),r=o?.apiUrl||g.RELAYER_API_URL,[i,l]=u.useState([]),[d,c]=u.useState(!1),[m,p]=u.useState(null),[f,h]=u.useState(!1),x=u.useRef(!1),b=u.useRef(!1),y=t??o?.supportedChainIds,w=y?JSON.stringify([...y].sort()):"",S=u.useCallback(async(C=!1)=>{if(!e||!n){l([]),h(!1),x.current=!1;return}if(!b.current){b.current=!0,!x.current&&!C&&c(!0),p(null);try{const E=await g.relayerFetch(`${r}/wallets/${e}/balance`,{cache:"no-store"});if(!E.ok)throw new Error(`Failed to fetch balance: ${E.status}`);const F=await E.json();if(F.balances&&Array.isArray(F.balances)){const B=F.balances.map(j=>Ec({receiptToken:typeof j.receiptToken=="string"?j.receiptToken:void 0,tokenName:String(j.tokenName??""),balanceAvailable:String(j.balanceAvailable??"0"),chainTokens:Mu(j),decimals:typeof j.decimals=="number"?j.decimals:void 0,balanceUsd:typeof j.balanceUsd=="number"||typeof j.balanceUsd=="string"?j.balanceUsd:null},y)).filter(j=>j!==null);l(B),h(B.length>0),x.current=!0}else l([]),h(!1)}catch(E){const F=E instanceof Error?E.message:"Failed to fetch balance";p(F),console.error("Error fetching Spice assets:",E),x.current||(l([]),h(!1))}finally{c(!1),b.current=!1}}},[e,n,w,r]);u.useEffect(()=>{n&&e&&(x.current=!1,S(!1))},[e,n,w]),u.useEffect(()=>{if(!n||!e||!s)return;const C=setInterval(()=>{S(!0)},s);return()=>clearInterval(C)},[e,n,s,w]);const v=u.useCallback(C=>i.filter(E=>E.chainId===C),[i]),k=u.useCallback(async()=>{await S(!0)},[S]);return{assets:i,loading:d,error:m,hasBalance:f,refetch:k,getAssetsByChain:v}};async function Ri(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[s,o,r]=await Promise.all([on.readContract(e,{address:t,abi:I.erc20Abi,functionName:"decimals"}).catch(()=>18),on.readContract(e,{address:t,abi:I.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),on.readContract(e,{address:t,abi:I.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);return{decimals:Number(s),symbol:o,name:r,logoURI:void 0}}function Di(e,t,n){const s=g.addressesEqual(e.address,t),o=e.chainId===n,r=e._source==="wallet";return r&&s&&o?0:r&&o?1:!r&&s?2:!r&&o?3:4}function Xn(e,t){return!t||t.length===0||e.isNative&&t.some(A.isNativeToken)||t.some(n=>g.addressesEqual(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const s=Rn(n);return s?t.some(o=>g.addressesEqual(o,s.address)):!1})}function Ou(e,t,n){return e._source!=="wallet"?!0:e.chainId===t&&Xn(e,n)}function cr(e,t,n){let{symbol:s,name:o,logoURI:r}=t;const i=g.addressesEqual(e.address,n.address)&&e.chainId===n.chainId;i&&n.logoURI&&(r=n.logoURI),i&&!e.configToken&&s==="TOKEN"&&(s=n.symbol,o=n.symbol);const l=parseFloat((Number(t.balance)/Math.pow(10,t.decimals)).toFixed(6));return{address:e.address,name:o,symbol:s,decimals:t.decimals,balance:t.balance,balanceFormatted:l,balanceUsd:0,logoURI:r,isNative:A.isNativeToken(e.address),chainId:e.chainId}}function Ni(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:s,enabled:o,includeExternalWalletAssets:r=!1,includeCrossChainEmbeddedAssets:i=!1}=e,l=u.useContext(g.SpiceFlowProviderContext),d=(l?.mode||"7702")!=="7702",c=l?.embeddedWalletAddress,{externalAddress:m,embeddedAddress:p}=g.useProviderWallets(),f=c||p,{assets:h,refreshAssets:x,loading:b,error:y}=mn({address:m,supportedChains:s??[],fetchBalances:fn,enabled:o&&r&&!!m,refreshInterval:15e3}),{assets:w,refetch:S}=ms({address:f,supportedChains:s,enabled:o&&(!d||i)&&!!f,refetchInterval:3e4}),v=u.useMemo(()=>d&&!i?[]:w.filter(V=>Xn(V,n)),[w,n,d,i]),k=d?m:f,C=u.useMemo(()=>i?Array.from(new Set([t.chainId,...s??[]])):[t.chainId],[t.chainId,s,i]),E=o&&(!d||i)&&!!f&&!l?.isWhitelistGateActive,{assets:F,refreshAssets:B,loading:j,error:T}=mn({address:E?f:void 0,supportedChains:C,fetchBalances:fn,enabled:E,refreshInterval:3e4}),R=u.useMemo(()=>{const V=new Set,G=[],J=U=>{if(!U)return;const L=U.toLowerCase();V.has(L)||(V.add(L),G.push(I.getAddress(U)))};if(J(t.address),n)for(const U of n)J(U);return G},[d,t.address,n]),D=u.useMemo(()=>R.map(V=>V.toLowerCase()).sort().join(","),[R]),M=u.useMemo(()=>JSON.stringify([...s||[]].sort()),[s]),[P,q]=u.useState([]),z=u.useRef(0),X=u.useRef(async()=>{}),N=u.useCallback(async()=>{if(!o||!k||R.length===0){z.current++,q([]);return}const V=++z.current,G=I.getAddress(k),J=d?s&&s.length>0?s:[t.chainId]:[t.chainId],U=[];for(const ue of R){const re=ue.toLowerCase();if(re===A.ZERO_ADDRESS)continue;if(A.isNativeToken(re)){const ie=g.addressesEqual(re,t.address)&&!J.includes(t.chainId)?[t.chainId,...J]:J;for(const ce of ie){const _=g.getChainConfig(ce)?.supportedTokens?.find(Ce=>A.isNativeToken(Ce.address));_&&U.push({address:ue,chainId:ce,configToken:{decimals:_.decimals,symbol:_.symbol,name:_.name,logo:_.logo}})}continue}if(re===t.address.toLowerCase()){const ie=g.getChainConfig(t.chainId)?.supportedTokens?.find(ce=>g.addressesEqual(ce.address,re));U.push({address:ue,chainId:t.chainId,configToken:ie?{decimals:ie.decimals,symbol:ie.symbol,name:ie.name,logo:ie.logo}:void 0});continue}let se=!1;for(const ie of J){const ce=g.getChainConfig(ie)?.supportedTokens?.find(_=>g.addressesEqual(_.address,re));if(ce){U.push({address:ue,chainId:ie,configToken:{decimals:ce.decimals,symbol:ce.symbol,name:ce.name,logo:ce.logo}}),se=!0;break}}se||U.push({address:ue,chainId:t.chainId})}const L=new Map;for(const ue of U){const re=L.get(ue.chainId)||[];re.push(ue),L.set(ue.chainId,re)}const O=async(ue,re)=>{try{const se=await on.readContract(ue,{address:re.address,abi:I.erc20Abi,functionName:"balanceOf",args:[G]}),{decimals:ie,symbol:ce,name:_,logoURI:Ce}=await Ri(ue,re.address,re.configToken);return cr(re,{decimals:ie,symbol:ce,name:_,logoURI:Ce,balance:se},t)}catch{return null}},ee=await Promise.all(Array.from(L.entries()).map(async([ue,re])=>{let se;try{se=g.getClientForChain(ue)}catch{return[]}const ie=re.filter(ne=>A.isNativeToken(ne.address)),ce=re.filter(ne=>!A.isNativeToken(ne.address)),_=await Promise.all(ie.map(async ne=>{const Q=await se.getBalance({address:G}).catch(()=>0n),te=g.getChainConfig(ue)?.nativeCurrency;return cr(ne,{decimals:ne.configToken?.decimals??te?.decimals??18,symbol:ne.configToken?.symbol??te?.symbol??"ETH",name:ne.configToken?.name??te?.name??"Ether",logoURI:ne.configToken?.logo,balance:Q},t)}));if(ce.length===0)return _;const Ce=[],W=[];for(const ne of ce){const Q=Ce.length;Ce.push({address:ne.address,abi:I.erc20Abi,functionName:"balanceOf",args:[G]}),ne.configToken||Ce.push({address:ne.address,abi:I.erc20Abi,functionName:"decimals"},{address:ne.address,abi:I.erc20Abi,functionName:"symbol"},{address:ne.address,abi:I.erc20Abi,functionName:"name"}),W.push({start:Q,item:ne})}let ae=null;try{ae=await se.multicall({contracts:Ce})}catch{ae=null}if(ae){const ne=W.map(({start:Q,item:te})=>{const be=ae[Q],$=be?.status==="success"?be.result:0n;let Se,ct,xe,pt;if(te.configToken)Se=te.configToken.decimals,ct=te.configToken.symbol,xe=te.configToken.name,pt=te.configToken.logo;else{const Me=ae[Q+1],Ue=ae[Q+2],Xe=ae[Q+3];Se=Me?.status==="success"?Number(Me.result):18,ct=Ue?.status==="success"?Ue.result:"TOKEN",xe=Xe?.status==="success"?Xe.result:ct}return cr(te,{decimals:Se,symbol:ct,name:xe,logoURI:pt,balance:$},t)});return[..._,...ne]}const he=await Promise.all(ce.map(ne=>O(se,ne)));return[..._,...he.filter(ne=>ne!==null)]}));V===z.current&&q(ee.flat())},[o,d,k,D,M,t.address,t.chainId,t.symbol,t.logoURI]);u.useEffect(()=>{X.current=N},[N]),u.useEffect(()=>{if(!o){q([]);return}X.current();const V=setInterval(()=>{X.current()},15e3);return()=>clearInterval(V)},[o,d,k,D,M,t.address,t.chainId]);const H=u.useCallback(()=>{N(),B(),r&&x()},[N,r,x,B]);return{displayAssets:u.useMemo(()=>{const V=[],G=new Set,J=(L,O)=>{const ee=`${O}:${L.chainId}:${A.normalizeNativeTokenAddress(L.address).toLowerCase()}`;G.has(ee)||(G.add(ee),V.push({...L,_source:"wallet",_fundingWallet:O,displayChainName:`${g.getChainName(L.chainId)} \xB7 ${O==="external"?"Wallet":"Embedded wallet"}`}))};for(const L of P)L.balance>0n&&J(L,g.addressesEqual(k,f)?"embedded":"external");for(const L of F)L.balance>0n&&Xn(L,n)&&J(L,"embedded");if(r)for(const L of h)L.balance>0n&&Xn(L,n)&&J(L,"external");for(const L of v)V.push({...L,_source:"spice"});const U=t.address.toLowerCase();return V.sort((L,O)=>Di(L,U,t.chainId)-Di(O,U,t.chainId)),V},[P,k,f,F,h,v,r,d,n,t.address,t.chainId]),loading:b||j,error:y||T,filteredSpiceAssets:v,walletAssets:P,embeddedWalletAddress:f,externalAddress:m,isNon7702:d,refreshSpiceAssets:S,refreshWalletAssets:H}}function dr(e,t,n){return Zo({executorAddress:n,aerodrome:!1,oneInch:e?.includeDefaults===!1?{chainIds:[]}:void 0,customVenues:t})}const Mi=Kn(),Pu=dr(void 0,Mi.input);async function Wu(e){const t=await(e.liquidityVenues||e.executorAddress?dr(e.liquidityVenues,Kn(e.liquidityVenues).input,e.executorAddress):Pu).resolveSwap({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn,maxSlippage:e.maxSlippage},e.chainId,e.recipient);if(!t)throw new Error("No liquidity for this pair.");return t}function Js(e){const{direction:t,selectedAsset:n,destinationToken:s,chainId:o,recipient:r,executorAddress:i,fixedInputToken:l,paymentAmount:d,maxSlippage:c,refreshIntervalMs:m,resolveInputSwap:p,resolveExactOutputSwap:f}=e,h=u.useContext(g.SpiceFlowProviderContext)?.liquidityVenues,[x,b]=u.useState(!1),[y,w]=u.useState(null),[S,v]=u.useState(null),[k,C]=u.useState(null),[E,F]=u.useState(null),[B,j]=u.useState(null),[T,R]=u.useState(null),[D,M]=u.useState(null),[P,q]=u.useState(null),[z,X]=u.useState(null),[N,H]=u.useState(null),[V,G]=u.useState(0),[J,U]=u.useState(null),[L,O]=u.useState(null),ee=u.useRef(null),ue=u.useRef(null),re=u.useRef(0),se=u.useRef(new Map),ie=u.useCallback(()=>{re.current++,se.current.clear(),O(null),G(Ae=>Ae+1)},[]),ce=m&&m>0?m:null,_=h?JSON.stringify(h):"",Ce=u.useMemo(()=>h?Kn(h):Mi,[_]),W=u.useMemo(()=>dr(h,Ce.input,i),[Ce,i]),ae=u.useMemo(()=>Ws({executorAddress:i,customVenues:[...f?[{name:"consumer-exact-output",chainIds:[o],preferred:!0,resolve:f}]:[],...Ce.output]}),[f,o,Ce,i]);u.useEffect(()=>{se.current.clear()},[W,ae,p]);const he=u.useMemo(()=>n?.asset?l||Qt(n.asset,o):null,[n?.asset,o,l]),ne=u.useMemo(()=>n?.asset?l?[l]:Dn(n.asset,o):[],[n?.asset,o,l]),Q=u.useMemo(()=>ne.map(Ae=>Ae.toLowerCase()).join(","),[ne]),te=JSON.stringify([n?.asset.address,n?.asset.chainId,n?.asset.decimals,n?.amount,o,Q,l?.toLowerCase(),t,d]);u.useEffect(()=>{let Ae=!1;if(ue.current&&(clearTimeout(ue.current),ue.current=null),!n?.asset||ne.length<=1){X(null),H(null);return}return ue.current=setTimeout(async()=>{const nt=t==="input"?n.amount:d||"0";let st=0n;try{st=t==="input"?I.parseUnits(nt,n.asset.decimals):0n}catch{st=0n}try{const ft=await ko(n.asset,o,{requiredAmount:st,requiredAmountDecimals:n.asset.decimals});Ae||(X(ft),H(te))}catch{Ae||X(null)}},400),()=>{Ae=!0,ue.current&&(clearTimeout(ue.current),ue.current=null)}},[te]);const be=u.useMemo(()=>(N===te?z:null)??he,[z,N,te,he]),$=u.useMemo(()=>!n?.asset||!be?[]:[be,...ne.filter(Ae=>Ae.toLowerCase()!==be.toLowerCase())],[n?.asset,be,ne]),Se=u.useMemo(()=>!n?.asset||!is(n.asset.address,n.asset.chainId,s.address,s.chainId)||!be?!1:g.addressesEqual(A.normalizeNativeTokenAddress(be),A.normalizeNativeTokenAddress(s.address)),[n,s.address,s.chainId,be]),ct=be?g.addressesEqual(A.normalizeNativeTokenAddress(be),A.normalizeNativeTokenAddress(s.address)):!1,xe=t==="output"&&parseFloat(d||"0")===0,pt=!!n?.asset&&!Se&&!ct&&!xe,Me=JSON.stringify([_,t,pt,n?.asset.address,n?.asset.chainId,n?.asset.decimals,t==="input"?n?.amount:d,$.map(Ae=>Ae.toLowerCase()),o,s.address.toLowerCase(),s.chainId,s.decimals,r?.toLowerCase(),i?.toLowerCase(),l?.toLowerCase(),c,ce]),Ue=u.useMemo(()=>({}),[Me,W,ae,p,V]),Xe=L?.request===Ue&&(!ce||L.expiresAt>Date.now());return u.useEffect(()=>{if(!ce||L?.request!==Ue)return;const Ae=setTimeout(ie,Math.max(0,L.expiresAt-Date.now()));return()=>clearTimeout(Ae)},[ce,L,Ue,ie]),u.useEffect(()=>{ee.current&&clearTimeout(ee.current),U(Ue),O(null),w(null);const Ae=t==="input"?n?.amount:d,nt=parseFloat(Ae||"0");if(!pt||!Number.isFinite(nt)||nt<=0||!n?.asset||!r||$.length===0){re.current++,v(null),C(null),F(null),j(null),R(null),M(null),w(null),b(!1);return}const st=n.asset.decimals;let ft;try{ft=t==="input"?I.parseUnits(n.amount,st):I.parseUnits(d||"0",s.decimals)}catch{re.current++,w("Invalid amount"),b(!1);return}const ot=++re.current,_e=()=>ot!==re.current,Be=Te=>n.asset.chainId===o&&g.addressesEqual(n.asset.address,Te)?Promise.resolve(st):g.getTokenDecimals(o,Te);b(!0);const Ct=l?0:t==="output"?150:400,mt=async(Te,Ke,Oe)=>{for(const Y of $){const Ee=`${_}:${t}:${o}:${Y.toLowerCase()}:${s.address.toLowerCase()}:${st}:${ft.toString()}:${r.toLowerCase()}:${i?.toLowerCase()??"recipient"}:${c??"default"}:${ce??"default"}`,ye=se.current.get(Ee),Re=ye&&ye.expiresAt>Date.now()?Te(ye):void 0;if(Re)return{quote:Re,tokenIn:Y,expiresAt:ye.expiresAt};const dt=await Oe(Y);if(_e())return"stale";if(!dt)continue;const Qe=Date.now()+Math.min(ce??3e4,3e4);return se.current.set(Ee,{expiresAt:Qe,direction:t,...Ke(dt)}),{quote:dt,tokenIn:Y,expiresAt:Qe}}return null};return ee.current=setTimeout(async()=>{try{if(t==="input"){let Te=!1;const Ke=await mt(Y=>Y.resolvedSwap&&Y.inputAmount!==void 0?{swap:Y.resolvedSwap,inputAmount:Y.inputAmount}:void 0,Y=>({resolvedSwap:Y.swap,inputAmount:Y.inputAmount}),async Y=>{const Ee=Bt(ft,st,await Be(Y),"floor");if(_e()||Ee<=0n)return null;Te=!0;const ye={type:"swap",tokenIn:Y,tokenOut:s.address,amountIn:Ee,maxSlippage:c};if(p){const dt=await p(ye,o,r);if(dt)return{swap:dt,inputAmount:Ee}}const Re=await W.resolveSwap(ye,o,r);return Re?{swap:Re,inputAmount:Ee}:null});if(Ke==="stale"||_e())return;if(!Ke)throw new Error(Te?"No liquidity for this pair":"Amount is below the destination token's precision");q(Ke.quote.inputAmount),M(Ke.tokenIn),O({request:Ue,key:`${Me}:${ot}`,expiresAt:Ke.expiresAt}),R(Ke.quote.swap.amountOut),F(Ke.quote.swap),j(null);const Oe=parseFloat(I.formatUnits(Ke.quote.swap.amountOut,s.decimals));v(Oe<.01?Oe.toPrecision(4):Oe.toLocaleString(void 0,{maximumFractionDigits:6})),C(null),w(null)}else{const Te=await mt(Oe=>Oe.exactOutputSwap,Oe=>({exactOutputSwap:Oe}),async Oe=>{try{return await ae.getQuote({tokenIn:Oe,tokenOut:s.address,amountOut:ft,maxSlippage:c},o,r)}catch{return null}});if(Te==="stale"||_e())return;if(!Te)throw new Error("No liquidity for this pair");const Ke=await Be(Te.tokenIn);if(_e())return;M(Te.tokenIn),O({request:Ue,key:`${Me}:${ot}`,expiresAt:Te.expiresAt}),j(Te.quote),F(null),R(null),C(I.formatUnits(Te.quote.amountIn,Ke)),v(null),w(null)}}catch(Te){if(_e())return;const Ke=Te instanceof Error?Te.message:"Failed to get quote";w(Ke),v(null),C(null),F(null),j(null),R(null),M(null)}finally{_e()||b(!1)}},Ct),()=>{re.current++,ee.current&&clearTimeout(ee.current)}},[Ue]),{inputAmount:Xe&&t==="input"?P:null,quoteKey:Xe?L.key:null,quoteExpiresAt:Xe?L.expiresAt:null,refreshQuote:ie,isQuoting:J===Ue?x:pt,quoteError:J===Ue?y:null,estimatedOutput:Xe?S:null,estimatedInput:Xe?k:null,resolvedSwap:Xe?E:null,exactOutputSwap:Xe?B:null,quoteAmountOut:Xe?T:null,resolvedTokenIn:pt&&Xe?D??be:be,isDirect:ct,needsSwap:pt,selectedIsEquivalent:Se}}function Oi(e){const t=new Set(A.getEquivalentAddresses(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const Uu=["USDC","USDT","WETH","WBTC"];function Pi(e,t){const n=g.getChainConfig(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:A.ZERO_ADDRESS,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:t};const s=n.supportedTokens?.find(o=>o.symbol.toUpperCase()===e.toUpperCase());if(s)return{address:s.address.toLowerCase(),symbol:s.symbol,decimals:s.decimals,chainId:t}}function Cn(e,t,n){const s=g.getChainConfig(t);if(!s)return;if(n!==void 0){if(A.isNativeToken(e)&&!A.getTokenByAddress(e,n))return;const i=Jr(e,n,t);return i?{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:t}:void 0}if(A.isNativeToken(e))return;const o=Oi(e),r=s.supportedTokens?.find(i=>o.has(i.address.toLowerCase()));if(r)return{address:r.address.toLowerCase(),symbol:r.symbol,decimals:r.decimals,chainId:t}}function Wi(e){const{sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,intermediaryCandidates:r=Uu}=e;if(As(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} fronted directly`};if(s===o&&(A.isNativeToken(t.address)||!A.getTokenByAddress(t.address,s)))return{strategy:"direct-swap",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${n.symbol} on chain ${s}, no escrow`};if(Cn(t.address,o,s))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} fronted on destination, swapped to ${n.symbol}`};if(Cn(n.address,s,o))return{strategy:"source-swap",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${n.symbol} on source chain, then fronted`};for(const i of r){const l=Pi(i,s);if(!l||As(t,l)||As(n,l))continue;const d=Pi(i,o);if(d&&As(l,d))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:d,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${i} on source, fronted, then ${i} \u2192 ${n.symbol} on destination`}}throw new g.SpiceflowError("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${s}) to ${n.symbol} (chain ${o}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:n.symbol,sourceChainId:s,destinationChainId:o,candidatesChecked:r})}async function Lu(e){const{route:t,sourceAmount:n,userAddress:s,registry:o,actionCalls:r,slippage:i}=e;async function l(d,c,m,p){const f=await o.resolveSwap({type:"swap",tokenIn:c,tokenOut:m,amountIn:p,maxSlippage:i},d,s);if(!f)throw new g.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${c} \u2192 ${m} on chain ${d}. No liquidity available for this pair.`,{chainId:d,tokenIn:c,tokenOut:m,amountIn:p.toString()});return f}switch(t.strategy){case"direct-swap":{const d=await l(t.destinationChainId,t.sourceAsset.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...d.calls,...r]}],solverFrontToken:t.outputAsset,solverFrontAmount:0n,resolvedSwaps:{sourceSwap:d}}}case"direct":{const d=Cn(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(Oi(d.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:r}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{}};const c=await l(t.destinationChainId,d.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...c.calls,...r]}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{destinationSwap:c}}}case"source-swap":{const d=Cn(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!d)throw new g.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.sourceChainId,side:"source"});const c=Cn(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!c)throw new g.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on destination chain ${t.destinationChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.destinationChainId,side:"destination"});const m=await l(t.sourceChainId,t.sourceAsset.address,d.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:m.calls},{chainId:t.destinationChainId,calls:r}],solverFrontToken:c,solverFrontAmount:m.amountOutMinimum,resolvedSwaps:{sourceSwap:m}}}case"intermediary":{if(!t.intermediaryAsset)throw new g.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const d=Cn(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!d)throw new g.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${t.intermediaryAsset.symbol} (${t.intermediaryAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.intermediaryAsset.symbol,address:t.intermediaryAsset.address,chainId:t.sourceChainId,side:"source"});const c=await l(t.sourceChainId,t.sourceAsset.address,d.address,n),m=await l(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,c.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:c.calls},{chainId:t.destinationChainId,calls:[...m.calls,...r]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:c.amountOutMinimum,resolvedSwaps:{sourceSwap:c,destinationSwap:m}}}default:throw new g.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}function zu(e,t){const n=Wi({sourceAsset:e,outputAsset:t,sourceChainId:e.chainId,destinationChainId:t.chainId});if(n.strategy==="direct"||n.strategy==="direct-swap")return null;let s=n.strategy==="source-swap"?t:n.intermediaryAsset;if(!s)throw new Error("No bridge token exists for this route");if(A.isNativeToken(s.address)){const r=Ps(s.chainId),i=r&&A.getTokenByAddress(r,s.chainId);if(!i)throw new Error("No registered wrapped bridge token exists for native output");s={address:i.address,symbol:i.symbol,decimals:i.decimals,chainId:s.chainId}}const o=Cn(s.address,e.chainId,t.chainId);if(!o)throw new Error("No source-chain equivalent exists for the bridge token");return{source:e,bridgeSource:o,bridgeDestination:s}}function Ui(e,t){if(e.sourceAmountIn<=0n||e.sourceAmountInMax<e.sourceAmountIn||e.bridgeSourceMinimum<=0n||e.bridgeDestinationMinimum<=0n||e.sourceCalls.length===0)throw new Error("Invalid source funding quote");return{...e,quoteKey:JSON.stringify(e,(n,s)=>typeof s=="bigint"?s.toString():s),expiresAt:t+3e4}}async function qu(e){if(e.sourceAmountIn<=0n)throw new Error("Enter a positive source amount");const{plan:t}=e,n=await e.registry.resolveSwap({type:"swap",tokenIn:t.source.address,tokenOut:t.bridgeSource.address,amountIn:e.sourceAmountIn,maxSlippage:e.maxSlippage},t.source.chainId,e.executorAddress);if(!n||n.amountOutMinimum>n.amountOut)throw new Error("No valid source-chain swap quote");return Ui({plan:t,executorAddress:e.executorAddress,direction:"input",sourceAmountIn:e.sourceAmountIn,sourceAmountInMax:e.sourceAmountIn,bridgeSourceMinimum:n.amountOutMinimum,bridgeDestinationMinimum:Bt(n.amountOutMinimum,t.bridgeSource.decimals,t.bridgeDestination.decimals,"floor"),sourceCalls:n.calls},e.nowMs??Date.now())}async function Hu(e){if(e.bridgeDestinationAmount<=0n)throw new Error("Enter a positive bridge amount");const{plan:t}=e,n=e.nowMs??Date.now(),s=Bt(e.bridgeDestinationAmount,t.bridgeDestination.decimals,t.bridgeSource.decimals,"ceil"),o=await e.registry.getQuote({tokenIn:t.source.address,tokenOut:t.bridgeSource.address,amountOut:s,maxSlippage:e.maxSlippage},t.source.chainId,e.executorAddress);if(o.amountOut!==s)throw new Error("Source quote does not match the required bridge output");return Ui({plan:t,executorAddress:e.executorAddress,direction:"output",sourceAmountIn:o.amountIn,sourceAmountInMax:o.amountInMax,bridgeSourceMinimum:s,bridgeDestinationMinimum:Bt(s,t.bridgeSource.decimals,t.bridgeDestination.decimals,"floor"),sourceCalls:o.calls},n)}async function Li(e,t){const n=()=>{if(e.expiresAt<=(t?.nowMs??Date.now()))throw new Error("Source funding quote expired; request a fresh quote")};n();const s=e.plan.bridgeSource;if(A.isNativeToken(s.address))throw new Error("Source conversion requires a wrapped ERC20 bridge token");const o=await Fo({chainBatches:[{chainId:s.chainId,calls:e.sourceCalls}],user:e.executorAddress,token:s.address,grossAmount:e.bridgeSourceMinimum,chainAuthorizations:t?.chainAuthorizations});n();const r=Bt(o.netEscrowAmount,s.decimals,e.plan.bridgeDestination.decimals,"floor");if(r<=0n)throw new Error("Source output after fees is below the destination token's precision");return{quote:e,chainBatches:o.chainBatches,sourceGasFee:o.gasFee,sourceSpicenetFee:o.spicenetFee,bridgeSourceNet:o.netEscrowAmount,bridgeDestinationNet:r,outputCredit:o.outputCredit,quoteKey:`${e.quoteKey}:${o.gasFee}:${o.spicenetFee}:${o.netEscrowAmount}`,expiresAt:e.expiresAt}}async function Vu(e){let t=e.bridgeDestinationAmount;for(let n=0;n<5;n++){const s=await Hu({...e,bridgeDestinationAmount:t});let o;try{o=await Li(s,{nowMs:e.nowMs,chainAuthorizations:e.chainAuthorizations})}catch(r){if(!(r instanceof g.SpiceflowError)||r.code!=="INVALID_PARAMS"||r.message!=="Borrow amount is too small after gas and Spicenet fees.")throw r;const{grossAmount:i,gasFee:l,spicenetFee:d}=r.context;if(![i,l,d].every(h=>typeof h=="string"&&/^(0|[1-9][0-9]*)$/.test(h)))throw r;const c=BigInt(i),m=BigInt(l)+BigInt(d);if(c!==s.bridgeSourceMinimum||m<c)throw r;const p=Bt(e.bridgeDestinationAmount,e.plan.bridgeDestination.decimals,e.plan.bridgeSource.decimals,"ceil"),f=Bt(p+m,e.plan.bridgeSource.decimals,e.plan.bridgeDestination.decimals,"ceil");if(f<=t)throw r;t=f;continue}if(o.bridgeDestinationNet>=e.bridgeDestinationAmount)return o;t+=e.bridgeDestinationAmount-o.bridgeDestinationNet}throw new Error("Source funding fees did not converge; request a fresh quote")}function Qu(e){const t=u.useContext(g.SpiceFlowProviderContext),n=e.selectedAsset?.asset,s=!!n&&n._source==="wallet"&&n.chainId!==e.destinationToken.chainId&&!Qt(n,e.destinationToken.chainId),o=u.useMemo(()=>{if(!s||!n)return{plan:null,error:null};try{if(e.direction==="input")throw new Error("Source-chain conversion requires input-inclusive or exact-output mode");const w=v=>({name:v.symbol,equivalenceGroup:"",logo:"",swapContracts:[],network:"mainnet",...A.getTokenByAddress(v.address,v.chainId),...v}),S=zu(w(n),w(e.destinationToken));if(!S)throw new Error("No source-chain conversion route is available");return{plan:S,error:null}}catch(w){return{plan:null,error:w instanceof Error?w.message:"Source route unavailable"}}},[s,n?.address,n?.chainId,n?.decimals,e.destinationToken,e.direction]),r=u.useMemo(()=>{const w=Kn(t?.liquidityVenues);return{input:Zo({executorAddress:e.executorAddress,aerodrome:!1,oneInch:t?.liquidityVenues?.includeDefaults===!1?{chainIds:[]}:void 0,customVenues:w.input}),output:Ws({executorAddress:e.executorAddress,customVenues:w.output})}},[t?.liquidityVenues,e.executorAddress]),i=JSON.stringify([t?.network,t?.liquidityVenues,s,n?.address,n?.chainId,n?.decimals,n?._source,n?._fundingWallet,e.direction==="output"?"output":e.selectedAsset?.amount,e.destinationToken.address,e.destinationToken.chainId,e.destinationToken.decimals,e.executorAddress,e.direction,e.maxSlippage]),l=u.useRef({key:i,plans:new Map,pending:new Map,latestOutput:void 0});l.current.key!==i&&(l.current={key:i,plans:new Map,pending:new Map,latestOutput:void 0});const d=l.current,[c,m]=u.useState(0),[p,f]=u.useState(null),h=u.useCallback(async(w,S=!1)=>{if(!e.enabled||!o.plan||!e.executorAddress)throw new Error("Source funding route is not ready");const v=e.direction==="output"?String(w??0n):"input";e.direction==="output"&&w&&w>0n&&(d.latestOutput=w);const k=d.plans.get(v);if(!S&&k&&k.expiresAt>Date.now()){if(w&&k.bridgeDestinationNet<w)throw new Error("The source budget cannot cover destination funding; refresh the quote");return k}const C=d.pending.get(v);if(C)return C;const E=(async()=>{try{const F=e.direction==="output"?await Vu({plan:o.plan,executorAddress:e.executorAddress,bridgeDestinationAmount:w??0n,registry:r.output,maxSlippage:e.maxSlippage}):await Li(await qu({plan:o.plan,executorAddress:e.executorAddress,sourceAmountIn:I.parseUnits(e.selectedAsset.amount,n.decimals),registry:r.input,maxSlippage:e.maxSlippage}));if(l.current!==d)throw new Error("Source quote changed before funding completed");return d.plans.set(v,F),f(null),m(B=>B+1),F}catch(F){throw l.current===d&&f({key:i,message:F instanceof Error?F.message:"Unable to quote source funding"}),F}finally{d.pending.delete(v)}})();return d.pending.set(v,E),E},[e.enabled,o.plan,e.executorAddress,e.direction,e.selectedAsset?.amount,e.maxSlippage,r,d]);u.useEffect(()=>{if(!s||!e.enabled||!o.plan)return;const w=()=>{const v=e.direction==="output"?e.outputAmount??d.latestOutput:void 0;if(e.direction==="output"&&v===void 0)return;const k=e.direction==="output"?String(v):"input",C=d.plans.get(k);h(v,!!C&&C.expiresAt-Date.now()<=(e.direction==="input-inclusive"?2e4:1e4)).catch(()=>{})};w();const S=setInterval(w,5e3);return()=>clearInterval(S)},[s,e.enabled,e.direction,e.outputAmount,o.plan,h]),u.useEffect(()=>{if(!e.enabled)return;const w=e.direction==="output"?String(e.outputAmount??d.latestOutput??0n):"input",S=d.plans.get(w)?.expiresAt;if(!S||S<=Date.now())return;const v=setTimeout(()=>m(k=>k+1),S-Date.now());return()=>clearTimeout(v)},[e.enabled,e.direction,e.outputAmount,d,c]);const x=w=>{const S=d.plans.get(e.direction==="output"?String(w??0n):"input");return S&&S.expiresAt>Date.now()?S:null},b=d.plans.get("input")??null,y=u.useMemo(()=>{if(!o.plan||e.direction!=="output"&&!b)return null;const w=o.plan.bridgeDestination;return{amount:b?I.formatUnits(b.bridgeDestinationNet,w.decimals):"1",asset:{address:w.address,chainId:w.chainId,decimals:w.decimals,symbol:w.symbol,name:w.symbol,isNative:A.isNativeToken(w.address),_source:"spice",balance:b?.bridgeDestinationNet??0n,balanceFormatted:0,balanceUsd:0}}},[o.plan,e.direction,b?.quoteKey]);return{required:s,plan:o.plan,key:i,virtualSelectedAsset:y,prepare:h,getPrepared:x,error:o.error??(p?.key===i?p.message:null),isCurrent:()=>l.current===d}}function ur(e){const{enabled:t,actionExecution:n,destinationToken:s,selectedAsset:o,paymentAmount:r="0",amountDirection:i="input",sourceChains:l,supportedSourceAssets:d,includeExternalWalletAssets:c=!1,includeCrossChainEmbeddedAssets:m=!1,sourceFundingRecoveryKey:p="generic",sourceFundingRecovery:f="resume",feeOnlyAction:h=!1,actionProceeds:x,buildActionCalls:b,feeExecutionMode:y=e.feeOnlyAction?"backend-transfer":"user-transfer",buildSpicenetBatch:w,onPayExecute:S,recipient:v,maxSlippage:k,resolveInputSwap:C,resolveExactOutputSwap:E,prependSourceEscrow:F=!1,isZeroAmountPay:B=!1,onSuccess:j,onError:T}=e,R=i==="output",D=x&&(!h||A.isNativeToken(s.address))?"Action proceeds require a fee-only ERC20 action":h&&(!R||Number(r)!==0||n||S||F)?"Fee-only actions require zero-output mode and SDK-managed embedded execution":null,M=u.useRef(D);M.current=D;const P=i==="input-inclusive",q=R?"output":"input",z=s.chainId,X=u.useRef(t);X.current=t;const N=u.useContext(g.SpiceFlowProviderContext),H=(N?.mode||"7702")!=="7702",V=!!N?.isWhitelistGateActive,G=!!N?.isWhitelistConfigured&&N?.isUserWhitelisted!==!0,{address:J,isConnected:U,isReady:L,isAuthenticated:O,provider:ee}=g.useWallet(),{execute:ue,estimate:re}=ds(),{externalWallet:se,embeddedAddress:ie,activeWallet:ce,activeAddress:_}=g.useProviderWallets(),Ce=N?.externalWalletAddress,W=N?.embeddedWalletAddress||ie,ae=u.useRef({resolve:x?.resolve,token:x?.token,owner:W,buildActionCalls:b,resolver:E,revision:0});(ae.current.owner!==W||ae.current.resolve!==x?.resolve||ae.current.token!==x?.token||ae.current.buildActionCalls!==b||ae.current.resolver!==E)&&(ae.current={resolve:x?.resolve,token:x?.token,owner:W,buildActionCalls:b,resolver:E,revision:ae.current.revision+1});const he=ae.current.revision,ne=JSON.stringify([he,s.address,s.chainId,s.decimals,r,i,v,h,y,o?.asset.decimals,o?.asset.address,o?.asset.chainId,o?.asset.receiptTokenId,o?.asset._source,o?.asset._fundingWallet,o?.asset.chainTokens,k,N?.liquidityVenues]),Q=u.useRef(ne);Q.current=ne;const te=u.useMemo(()=>l??N?.supportedChainIds??[],[l,N?.supportedChainIds]),be=u.useMemo(()=>{if(V)return[];if(d)return d;const K=N?.allowedTokens;if(!K||K.length===0)return;const we=new Set(K.map(It=>It.toLowerCase())),Ye=[],Ne=new Set;for(const It of te){const _t=g.getChainConfig(It);for(const Tn of _t?.supportedTokens??[]){if(!we.has(Tn.symbol.toLowerCase()))continue;const jr=Tn.address.toLowerCase();Ne.has(jr)||(Ne.add(jr),Ye.push(Tn.address))}}return Ye},[d,N?.allowedTokens,te,V]),$=Ni({destinationToken:s,supportedSourceAssets:be,sourceChains:te,includeExternalWalletAssets:c,includeCrossChainEmbeddedAssets:m,enabled:t&&(H?!!Ce:!!W)}),{displayAssets:Se,filteredSpiceAssets:ct,embeddedWalletAddress:xe}=$,pt=u.useMemo(()=>V||R||H?Se:Se.filter(K=>c&&K._fundingWallet==="external"||m&&K._fundingWallet==="embedded"&&Xn(K,be)||Ou(K,z,be)),[Se,V,R,H,c,m,z,be]),[Me,Ue]=u.useState(!1),[Xe,Ae]=u.useState(null),[nt,st]=u.useState("idle"),[ft,ot]=u.useState(""),[_e,Be]=u.useState(null),[Ct,mt]=u.useState(!1),[Te,Ke]=u.useState(null),[Oe,Y]=u.useState(null),Ee=Oe,[ye,Re]=u.useState(!1),[dt,Qe]=u.useState(!1),[yt,lt]=u.useState(null),[qt,Lt]=u.useState(null),Nt=u.useRef(T);Nt.current=T;const Je=u.useCallback(K=>{Ae(K),typeof K=="string"&&K&&Nt.current?.(new Error(K),g.getRelayerErrorDetail(K))},[]),pe=u.useRef(o);pe.current=o;const Pe=u.useRef(!1),at=u.useRef(null),ut=u.useRef(null),ve=u.useRef(null),fe=u.useRef(null),He=u.useRef(null),it=u.useRef(null),Ge=u.useRef(null),[,Ie]=u.useState(0),Et=u.useMemo(()=>{if(!n)return{scope:null,error:null};if(R||F||A.isNativeToken(s.address))return{scope:null,error:"External action execution requires an ERC20 input supply with SDK-managed funding"};const K=xe??ie;if(!Ce||!K)return{scope:null,error:null};try{return{scope:Bu(N?.network??"testnet",z,Ce,K,n.recoveryKey),error:null}}catch(we){return{scope:null,error:g.sanitizeError(we,"External action recovery is unavailable")}}},[n?.recoveryKey,!!n,R,F,s.address,xe,ie,Ce,N?.network,z]),De=Et.scope,[bt,jt]=u.useState({scope:null,record:null,error:null});u.useEffect(()=>{const K=()=>{try{jt({scope:De,record:De?Xs(De):null,error:null})}catch(Ne){jt({scope:De,record:null,error:g.sanitizeError(Ne,"Saved action needs recovery")})}},we=()=>{K(),f==="balance"&&De&&ju(De).then(Ne=>{Ne&&(K(),$.refreshWalletAssets(),$.refreshSpiceAssets())}).catch(Ne=>console.warn("[useSpiceSupply] external funding reconciliation pending",Ne))};we(),st("idle"),ot(""),Be(null),Ae(null),window.addEventListener("storage",we),window.addEventListener(Ti,we);const Ye=f==="balance"?setInterval(we,15e3):void 0;return()=>{clearInterval(Ye),window.removeEventListener("storage",we),window.removeEventListener(Ti,we)}},[De,f]);const Ht=bt.scope===De,zt=Ht?bt.record:null,Pt=zt?ir(zt):null,$e=Et.error??(Ht?bt.error:null),et=u.useRef({actionExecution:n,scope:De,error:$e,buildActionCalls:b});et.current={actionExecution:n,scope:De,error:$e,buildActionCalls:b};const Rt=u.useCallback((K,we)=>{if(!n)return b(K,we);if(!Ce)throw new Error("Connect the external wallet before supplying");return Du(K,we,Ce)},[!!n,b,Ce]),Yt=u.useCallback(()=>{fe.current=null,Je(null),lt(null),Qe(!1)},[Je]),tn=o?`${o.asset.address}:${o.asset.chainId}:${o.asset._source}:${o.asset._fundingWallet}:${o.amount}`:"";u.useEffect(()=>{Yt()},[tn,r,Yt]);const Ft=(n?void 0:v)??xe??ie??J,ge=Qu({enabled:t&&!Me,selectedAsset:o,destinationToken:s,executorAddress:xe??ie,direction:i,outputAmount:R?Oe?.grossAmount:void 0,maxSlippage:k}),qe=u.useMemo(()=>({}),[ne,tn,ge.key,Ft,C,E,w,_,Ce]),xt=u.useRef(qe);xt.current=qe;const Wt=ge.getPrepared(R?Oe?.grossAmount:void 0),Fe=u.useRef(null),Ut=P&&ge.required;(!Ut||Fe.current?.scope!==qe)&&(Fe.current=null),Ut&&(!Fe.current||Fe.current.plan.expiresAt<=Date.now()||it.current?.sourcePlan===Fe.current.plan)&&(Fe.current=Wt&&ge.virtualSelectedAsset?{scope:qe,plan:Wt,selection:ge.virtualSelectedAsset}:null);const Ze=Ut?Fe.current?.plan??null:Wt,Xt=Ut&&Ze&&Ze.expiresAt>Date.now()?null:ge.error,tt=Ut?Fe.current?.selection??null:ge.required?ge.virtualSelectedAsset:o,Mt=u.useRef(new Map),vt=Js({direction:q,selectedAsset:h?null:tt,destinationToken:s,chainId:z,recipient:Ft,executorAddress:xe??ie,fixedInputToken:ge.plan?.bridgeDestination.address,paymentAmount:r,maxSlippage:k,resolveInputSwap:C,resolveExactOutputSwap:E}),Jt=u.useMemo(()=>{if(P&&ge.required&&tt&&(!Oe||Oe.grossAmount!==Bt(I.parseUnits(tt.amount,tt.asset.decimals),tt.asset.decimals,Oe.decimals,"floor")))return null;if(!P||!tt||!Oe)return tt;if(Oe.netAmount<=0n)return null;const K=Bt(Oe.netAmount,Oe.decimals,tt.asset.decimals,"floor");return{...tt,amount:I.formatUnits(K,tt.asset.decimals)}},[P,ge.required,tt,Oe]),oe=Js({direction:q,selectedAsset:h?null:Jt,destinationToken:s,chainId:z,recipient:Ft,executorAddress:xe??ie,fixedInputToken:ge.plan?.bridgeDestination.address,paymentAmount:r,maxSlippage:k,resolveInputSwap:C,resolveExactOutputSwap:E}),Le=P?oe:vt,Ot=ge.plan?.bridgeDestination.address??(tt?tt.asset._source==="spice"?fi(tt.asset,z,s.address):Qt(tt.asset,z):null),Ve=h?{...Le,needsSwap:!1,isDirect:!0,selectedIsEquivalent:!0,isQuoting:!1,resolvedTokenIn:Ot,exactOutputSwap:null,resolvedSwap:null}:Le,{isQuoting:kt,resolvedSwap:nn,exactOutputSwap:de,resolvedTokenIn:me,isDirect:ze,needsSwap:je,selectedIsEquivalent:St}=Ve,Dt=kt||P&&vt.isQuoting||ge.required&&!tt;u.useEffect(()=>{ge.required&&R&&Oe?.grossAmount&&t&&!Me&&ge.prepare(Oe.grossAmount).catch(()=>{})},[ge.key,ge.prepare,R,Oe?.grossAmount,t,Me]);const Gt=ge.required?Ze?.quote.sourceAmountInMax??null:o&&Oe?Kt(Oe.grossAmount,Oe.decimals,o.asset.decimals):null,rt=P?vt:Ve,ht=R?parseFloat(r||"0"):parseFloat(o?.amount||"")||0,Vt=o?.asset?._source==="wallet",sn=!!o?.asset&&Vt&&o.asset.chainId!==z,Z=u.useMemo(()=>o?.asset?ct.find(K=>g.addressesEqual(K.address,o.asset.address))?.balanceFormatted??0:0,[o,ct]),le=Vt?o?.asset.balanceFormatted??0:Z,We=u.useMemo(()=>{if(!o?.asset)return!1;if(ge.required)return Gt!==null&&Gt>o.asset.balance;if(R)return Ee?Kt(Ee.grossAmount,Ee.decimals,o.asset.decimals)>o.asset.balance:St||ze?ht>o.asset.balanceFormatted:de?parseFloat(I.formatUnits(de.amountInMax,o.asset.decimals))>o.asset.balanceFormatted:!1;if(Ee){const K=Kt(Ee.grossAmount,Ee.decimals,o.asset.decimals);return Vt?K>o.asset.balance:parseFloat(I.formatUnits(K,o.asset.decimals))>le}return ht>le},[o,ge.required,Gt,R,Ee,St,ht,de,le,Vt,ze]),ke=P&&!!Ee&&Ee.netAmount===0n,gt=u.useMemo(()=>o?.asset?g.addressesEqual(o.asset.address,s.address)&&o.asset.chainId===s.chainId:!1,[o,s.address,s.chainId]),wt=!h&&gt&&o?.asset._source==="wallet"&&en(o.asset,H)&&(R||H||!!n),Tt=wt&&ht>0&&!!o?.asset,dn=G&&!wt,ln=u.useMemo(()=>ge.plan?ge.plan.bridgeDestination.address:o?.asset?je&&me?me:o.asset.chainId===z?o.asset.address:me??Qt(o.asset,z)??s.address:s.address,[o,ge.plan,s.address,je,z,me]),un=u.useCallback((K,we)=>({currentPaymentAmount:r,destinationToken:s,embeddedWalletAddress:xe,providerEmbeddedAddress:ie,externalWalletAddress:Ce,address:J,recipient:v,swapOutputRecipient:Ft,isNon7702:H,isPayMode:R,isFeeInclusiveInput:P,swapInputAmount:we.inputAmount,feeOnlyAction:h,resolvedChainId:z,buildActionCalls:Rt,feeExecutionMode:y,buildSpicenetBatch:w,selectedAsset:K&&F?{...K,asset:{...K.asset,_source:"spice",_fundingWallet:void 0}}:K,needsSwap:we.needsSwap,resolvedSwap:we.resolvedSwap,exactOutputSwap:we.exactOutputSwap,quoteAmountOut:we.quoteAmountOut,resolvedTokenIn:we.resolvedTokenIn}),[r,s,xe,ie,Ce,J,v,Ft,H,R,P,h,z,Rt,y,w,F]),At=u.useMemo(()=>un(tt,Ve),[un,tt,Ve.needsSwap,Ve.resolvedSwap,Ve.exactOutputSwap,Ve.quoteAmountOut,Ve.resolvedTokenIn,Ve.inputAmount]),Wn=u.useMemo(()=>P?un(tt,vt):At,[P,At,un,tt,vt.needsSwap,vt.resolvedSwap,vt.exactOutputSwap,vt.quoteAmountOut,vt.resolvedTokenIn,vt.inputAmount]),xs=u.useCallback(async(K,we)=>{if(!ge.required||!K.length)return K;const Ye=P&&Ze?Ze:await ge.prepare(we);if(!ge.isCurrent())throw new Error("Source funding quote expired or changed; refresh before retrying");if(Ye.bridgeDestinationNet<we)throw new Error("Source funding no longer covers the quoted destination amount");for(const[Ne,It]of Mt.current)It.expiresAt<=Date.now()&&Mt.current.delete(Ne);return Mt.current.set(Zn(Ye.chainBatches[0]),Ye),[...Ye.chainBatches,...K]},[ge.required,ge.prepare,P,Ze]),no=u.useCallback(async K=>{const we=await ii({...At,requestTimestampMs:ut.current??Date.now()},K),Ye=K?.fundingAmountOverride??At.exactOutputSwap?.amountInMax??I.parseUnits(r||"0",s.decimals);return xs(we,Ye)},[At,xs,r,s.decimals]),ys=u.useCallback(async(K,we)=>{const Ye={...K,requestTimestampMs:ut.current??Date.now()},Ne=await li(Ye,we);if(ge.required){const Tn=we?.fundingAmountOverride??I.parseUnits(K.selectedAsset?.amount||"0",K.selectedAsset?.asset.decimals??18);return xs(Ne,Tn)}if(!F||!o||Ne.length===0)return Ne;const It=R?Ye.currentPaymentAmount:o.amount;let _t=we?.fundingAmountOverride;if(_t===void 0)try{_t=I.parseUnits(It||"0",o.asset.decimals)}catch{return Ne}return _t<=0n?Ne:[Qs(o.asset.address,_t,o.asset.chainId),...Ne]},[F,o,R,ge.required,xs]),so=u.useCallback(K=>ys(At,K),[ys,At]),vr=u.useCallback(K=>ys(Wn,K),[ys,Wn]),kr=u.useCallback(K=>_o({signal:K,liquidityVenues:N?.liquidityVenues,maxSlippage:k,resolveExactOutputSwap:E,selectedAsset:Wn.selectedAsset,isPayMode:R,isFeeInclusiveInput:P,feeOnlyAction:h,actionProceeds:x,parsedAmount:ht,needsSwap:rt.needsSwap,exactOutputSwap:rt.exactOutputSwap,isNon7702:H,isSourceDestToken:gt,currentPaymentAmount:r,destinationToken:s,feeExecutionMode:y,resolvedTokenIn:rt.resolvedTokenIn,embeddedWalletAddress:xe,providerEmbeddedAddress:ie,resolvedChainId:z,isConnected:U,address:J,ready:L,authenticated:O,isDirect:rt.isDirect,resolvedSwap:rt.resolvedSwap,isQuoting:rt.isQuoting,executionTokenAddress:ln,buildPayChainBatches:no,buildSupplyChainBatches:vr,estimate:re}),[Wn,N?.liquidityVenues,k,E,R,P,h,x,ht,rt,H,gt,r,s,y,xe,ie,no,re,z,U,J,L,O,vr,ln]);u.useEffect(()=>{ve.current=kr},[kr]);const Sr=u.useMemo(()=>{if(!Tt)return null;let K;try{K=I.parseUnits(r||"0",s.decimals)}catch{return null}return{symbol:s.symbol,decimals:s.decimals,grossAmount:K,netAmount:K,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[Tt,r,s.symbol,s.decimals]),vn=(!!o?.asset||!!x)&&(ht>0||h),$t=u.useMemo(()=>!t||Me||nt!=="idle"&&nt!=="error"||!vn||Tt||!o?.asset&&!x?null:[R?"pay":"supply",i,h?"fee-only":"supply",o?.asset.address.toLowerCase()??"proceeds",o?.asset.chainId,o?.asset._source,o?.asset.receiptTokenId,o?.asset.decimals,o?.asset._fundingWallet,o?.amount,h?he:"",h?o?.asset.balance.toString():"",h?JSON.stringify(o?.asset.chainTokens??{}):"",h?JSON.stringify(N?.liquidityVenues??{}):"",h?k:"",ge.key,tt?.amount??"",r,s.address.toLowerCase(),s.chainId,s.decimals,z,rt.resolvedTokenIn?.toLowerCase()??"",rt.needsSwap?"swap":"direct",rt.isDirect?"direct-token":"routed-token",H?"non7702":"7702",gt?"source-dest":"cross-chain",rt.isQuoting?"quoting":"quoted",rt.exactOutputSwap?.amountIn?.toString()??"",rt.exactOutputSwap?.amountInMax?.toString()??"",rt.exactOutputSwap?.venue??"",rt.resolvedSwap?.amountOut?.toString()??"",rt.quoteAmountOut?.toString()??"",xe??"",ie??"",J??"",Ft??""].join("|"),[t,Me,nt,vn,x,he,N?.liquidityVenues,k,Tt,o,o?.asset.balance,ge.key,tt?.amount,R,i,h,r,s,z,rt,H,gt,xe,ie,J,Ft]),Un=!!$t&&fe.current?.key===$t,bs=qt?.key===$t?qt:null,fl=bs?bs.requiredAmount:h&&!Un?null:fe.current?.quote.fundingConversion?.sourceAmountMax??Gt,ws=!!bs||(!h||Un)&&(fe.current?.quote.fundingConversion&&o?fe.current.quote.fundingConversion.sourceAmountMax>o.asset.balance:We);as({shouldRun:t&&!Me&&(nt==="idle"||nt==="error")&&vn&&!Tt&&!rt.isQuoting&&!!$t,deps:[t,Me,nt,vn,Tt,Sr,rt.isQuoting,$t],onSkip:()=>{if(Lt(null),!t){fe.current=null,Re(!1),Qe(!1),lt(null),Y(null);return}if(Me||nt!=="idle"&&nt!=="error"){Re(!1);return}if(!vn){fe.current=null,Y(null),Re(!1),Qe(!1),lt(null);return}if(Tt){Y(Sr),Re(!1),Qe(!0),lt(null);return}rt.isQuoting&&(Re(!1),Qe(!1))},onCleanup:()=>{Re(!1),Lt(null)},delayMs:500,backgroundIntervalMs:P&&ge.required?void 0:5e3,run:async({isBackground:K,isCurrent:we,signal:Ye})=>{const Ne=$t;Lt(null),K||(lt(null),Re(!0));try{const It=await ve.current?.(Ye);if(!we())return;It&&Ne?(fe.current={key:Ne,quote:It},Y(It.preview),Qe(!0)):(fe.current=null,Y(null),Qe(!1)),lt(null)}catch(It){if(!we())return;if(It instanceof mi&&Ne){fe.current=null,Y(null),Qe(!1),Lt({key:Ne,requiredAmount:It.requiredAmount}),lt(null);return}if(K&&fe.current?.key===Ne){console.warn("[useSpiceSupply] fee refresh failed:",It),Qe(!1),lt("Fees could not be refreshed. Waiting for a new estimate.");return}const _t=g.sanitizeError(It,"Unable to calculate fees for this action.");fe.current=null,Y(null),Qe(!1),lt(_t)}finally{we()&&Re(!1)}}});const ml=u.useCallback(K=>{st({building:"building","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[K.step]||"executing"),ot(K.message),K.txHash&&Be(K.txHash)},[]);u.useEffect(()=>{t||(Je(null),Ue(!1),st("idle"),ot(""),Be(null),mt(!1),Ke(null),Y(null),Re(!1),Qe(!1),lt(null),Pe.current=!1,at.current&&(at.current.abort(),at.current=null))},[t,Je]),u.useEffect(()=>()=>{at.current?.abort(),ae.current.revision++},[]),u.useEffect(()=>{if(!R||Te?.status!=="success"||Pe.current||!J)return;Pe.current=!0;const K=pe.current;!K?.asset||K.asset._source==="wallet"||$.refreshSpiceAssets()},[R,Te?.status,J,$]),He.current={selectedAsset:ge.required?o:At.selectedAsset,sourceConversionRequired:ge.required,sourceConversion:ge.required&&tt?{virtualSelectedAsset:tt,acceptedSourceAmountInMax:Ze?.quote.sourceAmountInMax??0n,getPlan:K=>K[0]?Mt.current.get(Zn(K[0])):void 0,refreshPlan:K=>ge.prepare(K.bridgeDestinationNet,!0),isCurrent:ge.isCurrent}:void 0,parsedAmount:ht,currentPaymentAmount:r,isInsufficientBalance:ws,isPayMode:R,isFeeInclusiveInput:P,feeOnlyAction:h,validateFeeQuote:()=>{if(!X.current||Q.current!==ne)throw new Error("The fee action or route changed; refresh before retrying")},actionProceeds:x?{token:x.token,resolve:async K=>{if(!X.current||ae.current.revision!==he)throw new Error("Action proceeds quote is stale");const we=await x.resolve(K);if(!X.current||ae.current.revision!==he)throw new Error("Action proceeds quote is stale");return we}}:void 0,isNon7702:H,isSourceDestToken:gt,needsSwap:je,swapInputAmount:Ve.inputAmount,exactOutputSwap:de,selectedIsEquivalent:St,resolvedTokenIn:me,embeddedWalletAddress:xe,providerEmbeddedAddress:ie,externalWallet:se,externalWalletAddress:Ce,activeSignerWallet:ce,activeSignerAddress:_,address:J,isConnected:U,ready:L,authenticated:O,provider:ee,resolvedChainId:z,executionTokenAddress:ln,destinationToken:s,sourceFundingRecoveryKey:p,recipient:v,buildActionCalls:Rt,feeExecutionMode:y,buildSpicenetBatch:w,onPayExecute:S,onSuccess:j,feeQuote:$t&&fe.current?.key===$t?fe.current.quote:null,execution:{estimate:re,execute:ue,buildPayChainBatches:no,buildSupplyChainBatches:so,onProgress:ml},ui:{setError:Je,setStep:st,setStatusMsg:ot,setTxHash:Be,setIsExecuting:Ue,setShowStatusPanel:mt,setPaymentResult:Ke},refs:{spiceDepositSubmittedRef:Pe,abortControllerRef:at}};const Ln=u.useRef(!1),Jn=u.useRef({scope:"",identity:""});Jn.current={scope:xe??ie?`spiceflow:sourceSupply:${JSON.stringify([N?.network??"testnet",z,(Ce??xe??ie).toLowerCase(),(xe??ie).toLowerCase()])}`:"",identity:tr(He.current)};const zn=u.useCallback(async K=>{if(Ln.current)return;Ln.current=!0;const we=He.current,Ye=Jn.current;try{if(M.current)throw new Error(M.current);if(Ge.current?.(),!Ye.scope)return await K(we);await Tu({scope:Ye.scope,ctx:we,run:K,isCurrent:()=>X.current&&Jn.current.scope===Ye.scope&&Jn.current.identity===Ye.identity})}catch(Ne){if(Jn.current.scope===Ye.scope){const It=g.sanitizeError(Ne,"Supply funding failed");Je(It),st("error"),we.isPayMode&&Ke({status:"failed",error:It})}}finally{Ln.current=!1,$.refreshWalletAssets(),$.refreshSpiceAssets()}},[Je]),oo=u.useCallback(async()=>{if(!X.current||Ln.current)return;ut.current=Date.now();const K=et.current;if(!K.actionExecution)return zn(Zs);Ln.current=!0,Ue(!0),Je(null),st("executing");try{if(K.error)throw new Error(K.error);if(!K.scope)throw new Error("Connect the external wallet and its Spicenet account");const we=()=>X.current&&et.current.scope===K.scope,Ye=He.current;await Nu({scope:K.scope,recovery:f,ctx:{...Ye,execution:{...Ye.execution,onProgress:Ne=>{we()&&Ye.execution.onProgress(Ne)}},ui:{setError:Ne=>{we()&&Ye.ui.setError(Ne)},setStep:Ne=>{we()&&Ye.ui.setStep(Ne)},setStatusMsg:Ne=>{we()&&Ye.ui.setStatusMsg(Ne)},setTxHash:Ne=>{we()&&Ye.ui.setTxHash(Ne)},setIsExecuting:Ne=>{we()&&Ye.ui.setIsExecuting(Ne)},setShowStatusPanel:Ne=>{we()&&Ye.ui.setShowStatusPanel(Ne)},setPaymentResult:Ne=>{we()&&Ye.ui.setPaymentResult(Ne)}}},buildActionCalls:K.buildActionCalls,isCurrent:we,onRecord:Ne=>{we()&&jt({scope:K.scope,record:Ne,error:null})}})}catch(we){et.current.scope===K.scope&&(Je(g.sanitizeError(we,"External wallet action failed")),st("error"))}finally{Ln.current=!1,Ue(!1)}},[Je,zn,f]),hl=u.useCallback(()=>X.current?(ut.current=Date.now(),et.current.actionExecution?(Je("External action execution currently supports exact-input supplies"),Promise.resolve()):zn(ar)):Promise.resolve(),[zn]),gl=u.useCallback(async K=>{if(!X.current)throw new Error("Supply is disabled");if(et.current.actionExecution)throw new Error("submitSupply manages external action funding");const we=pe.current?.asset;if(!we)throw new Error("No source asset selected");if(!xe)throw new Error("Your Spicenet account is not ready yet");const Ye=A.normalizeNativeTokenAddress(we.address),Ne=we.isNative||A.isNativeToken(Ye),It=g.getClientForChain(we.chainId);await zn(async _t=>{await er({identity:tr(_t),state:_t.sourceFunding,onState:Tn=>_t.onSourceFundingChange?.(Tn),sourceClient:It,recipient:xe,tokenAddr:Ye,isNative:Ne,requiredAmount:K,createWallet:()=>On({wallet:se,account:Ce,chainId:we.chainId,onSwitch:()=>ot("Switching source network...")})})})},[xe,Ce,se,zn]),xl=u.useCallback(K=>P?Promise.resolve(en(K,H)&&(K.isNative||A.isNativeToken(K.address))?null:I.formatUnits(K.balance,K.decimals)):wi({asset:K,isPayMode:R,isNon7702:H,needsSwap:je,isQuoting:Dt,embeddedWalletAddress:xe,buildSupplyChainBatches:so,estimate:re,executionTokenAddress:ln,feeExecutionMode:y}),[P,R,H,je,Dt,xe,so,re,ln,y]),yl=u.useCallback(()=>{const K=et.current.scope;K&&(Ru(K),jt({scope:K,record:null,error:null})),st("idle"),Be(null),Ke(null),mt(!1),$.refreshSpiceAssets()},[$]),bl=u.useCallback(()=>{mt(!1),Ke(null)},[]),wl=u.useCallback(()=>{X.current&&(st("idle"),Je(null),setTimeout(()=>{X.current&&(ut.current=Date.now(),oo())},50))},[Je,oo]),Cl=u.useCallback(()=>{mt(!1),Ke(null),Pe.current=!1,$.refreshSpiceAssets(),$.refreshWalletAssets()},[$]),Ar=!!$t&&fe.current?.key===$t,Ir=!!x&&Ar&&Ee?.grossAmount===0n&&dt,Er=(!vn||Tt||Un)&&(!(x||h)||Ar)&&t&&(!h||R&&ht===0&&(!!o||Ir)&&!n&&!S&&!F)&&(!ge.required||!!Ze&&!Xt)&&(R?(B||!!o?.asset||Ir)&&ht>=0&&!ws&&!Me&&(B&&!h||Tt||dt)&&!yt&&(B||!je||!!de)&&!dn:!!o?.asset&&ht>0&&!ws&&!Me&&(wt||dt)&&!yt&&!ke&&(sn||ze||!!nn&&!Dt)&&!dn),Fr=n?t&&!!De&&Ht&&!$e&&!Me&&!dn&&(Pt?Pt.phase!=="complete"&&!Pt.requiresRecovery:Er):Er,kn={assets:{...$,selectable:pt},quote:{...Ve,isQuoting:Dt||ge.required&&!Ze&&!Xt,quoteError:Xt??Ve.quoteError,hasSourceConversion:ge.required,executionInput:ge.plan?{address:ge.plan.bridgeDestination.address,chainId:z,decimals:ge.plan.bridgeDestination.decimals,amount:Ee?.netAmount??0n}:null},fees:{preview:Ee,fundingConversion:Un?fe.current?.quote.fundingConversion:void 0,proceedsUsed:fe.current?.key===$t?fe.current?.quote.proceedsUsed:void 0,fundingShortfall:(x||fe.current?.quote.fundingConversion)&&fe.current?.key===$t?fe.current?.quote.fundingConversion?.amountOut??fe.current?.quote.grossFundingAmount:void 0,source:Ze?{address:Ze.quote.plan.bridgeSource.address,chainId:Ze.quote.plan.bridgeSource.chainId,symbol:Ze.quote.plan.bridgeSource.symbol,decimals:Ze.quote.plan.bridgeSource.decimals,gasFee:Ze.sourceGasFee,spicenetFee:Ze.sourceSpicenetFee}:null,isLoading:ye||t&&!Me&&(nt==="idle"||nt==="error")&&vn&&!Tt&&!rt.isQuoting&&!Un&&!bs&&!yt,ready:dt&&(!vn||Tt||Un),error:yt},amount:{parsed:ht,isInsufficientBalance:ws,sourceBalance:le,feesExceedAmount:ke,sourceRequiredAmount:fl},status:{step:nt,statusMsg:ft,txHash:_e,isExecuting:Me,error:D??$e??Xe,showStatusPanel:Ct,paymentResult:Te,externalAction:Pt,sourceFunding:null},flags:{directExecutionFeeNote:Tt},canExecute:Fr,submitSupply:oo,submitPay:hl,fundEmbeddedSource:gl,retrySupply:wl,dismissPaymentStatus:bl,resolveMaxAmount:xl,resetAfterSuccess:yl,resetPaymentState:Cl},$n=P&&(ge.required||je)&&!h&&!n,_n=o&&$.displayAssets.find(K=>K.chainId===o.asset.chainId&&g.addressesEqual(A.normalizeNativeTokenAddress(K.address),A.normalizeNativeTokenAddress(o.asset.address))&&K._source===o.asset._source&&K._fundingWallet===o.asset._fundingWallet),ro=(()=>{try{return o?I.parseUnits(o.amount||"0",o.asset.decimals):null}catch{return null}})(),Tr=$n&&t&&!Me&&(nt==="idle"||nt==="error")&&U&&L&&O&&!dn&&!!_n&&ro!==null&&ro>0n&&ro<=_n.balance;(!Tr||it.current?.scope!==qe)&&(it.current=null);const Br=Math.min((ge.required?Ze?.expiresAt:1/0)??0,je?Ve.quoteExpiresAt??0:1/0);if(Tr&&Fr&&!kn.quote.isQuoting&&!kn.fees.isLoading&&(!je||Ve.resolvedSwap&&Ve.inputAmount!=null)&&Br>Date.now()){const K=He.current;it.current={scope:qe,expiresAt:Br,context:K,sourcePlan:Ze,quote:kn.quote,fees:kn.fees,amount:kn.amount}}const Zt=it.current;u.useEffect(()=>{const K=Fe.current;Ut&&Wt&&K&&K.plan===Zt?.sourcePlan&&K.plan!==Wt&&Ie(we=>we+1)},[Ut,Wt,Zt?.sourcePlan]);const ao=!!Zt&&Zt.scope===qe&&Zt.expiresAt>Date.now();if(Ge.current=$n?()=>{if(!X.current||!ao||xt.current!==Zt.scope||Zt.expiresAt<=Date.now())throw new Error("Swap quote expired or changed; wait for a complete quote before retrying")}:null,ao){const K=Ge.current,we=Zt.context;He.current={...we,selectedAsset:o&&_n?{...o,asset:_n}:o,validateFeeQuote:()=>{K(),we.validateFeeQuote?.()},sourceConversion:we.sourceConversion?{...we.sourceConversion,isCurrent:()=>X.current&&xt.current===Zt.scope&&(!we.needsSwap||(Zt.quote.quoteExpiresAt??0)>Date.now())&&we.sourceConversion.isCurrent()}:void 0}}const io=Math.min(...[Zt?.expiresAt,Ze?.expiresAt].filter(K=>K!==void 0&&K>Date.now()));u.useEffect(()=>{if(!Number.isFinite(io))return;const K=setTimeout(()=>Ie(we=>we+1),io-Date.now());return()=>clearTimeout(K)},[io]);const Cs=Math.min(vt.quoteExpiresAt??1/0,Ve.quoteExpiresAt??1/0);return u.useEffect(()=>{if(!$n||!t||Me||!Number.isFinite(Cs)||ge.required&&!Ze||Ze&&Ze.expiresAt<Cs)return;const K=setTimeout(()=>{vt.refreshQuote(),oe.refreshQuote()},Math.max(0,Cs-Date.now()-1e4));return()=>clearTimeout(K)},[$n,t,Me,ge.required,Ze?.expiresAt,Cs,vt.refreshQuote,oe.refreshQuote]),$n?ao?{...kn,quote:Zt.quote,fees:Zt.fees,amount:{...Zt.amount,sourceBalance:_n?.balanceFormatted??le,isInsufficientBalance:!1},canExecute:!0}:{...kn,canExecute:!1}:kn}function Ku(e){return!!e.embeddedAddress&&!!e.externalAddress}function Yu(e,t,n){const s=n.filter(o=>o.amount>0n);return{chainId:e,domain:"evm",tokenTransfers:[],calls:A.isNativeToken(t)?s.map(o=>({to:o.recipient,value:o.amount,data:"0x"})):s.map(o=>({to:t,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[o.recipient,o.amount]})}))}}new Set([A.SPICE_GAS_FEE_RECIPIENT,A.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function Gu(e){return`0x77${e.slice(4)}`}function zi({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:s,withdrawalAmount:o,deliveryRecipient:r,deliveryTransfers:i,requestTimestampMs:l}){const d=i?.length?i:[{token:n,recipient:r,amount:o??s}],c=d.reduce((h,x)=>h+x.amount,0n);if(c<=0n)return null;const m=l??Date.now(),p=BigInt(Math.floor(m/1e3)),f=Gu(I.keccak256(I.encodeAbiParameters([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[e??r,n,r,c,BigInt(t),BigInt(m)])));return{chainId:A.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:[{to:A.ZERO_ADDRESS,value:0n,data:I.encodeFunctionData({abi:A.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:f,nbf:0n,exp:p+3600n,metadata:"{}",transfers:d.map(h=>({token:I.getAddress(h.token).toLowerCase(),to:I.getAddress(h.recipient).toLowerCase(),amount:h.amount}))}]})}]}}const hs=e=>`${e._source}:${e.chainId}:${e.receiptTokenId??e.address.toLowerCase()}`;function Zu(e){const{asset:t,amount:n,recipient:s,owner:o,onSuccess:r}=e,i=t?.chainId??e.sourceChains?.[0]??0,l=u.useMemo(()=>A.getTokensForChain(i).find(y=>y.equivalenceGroup==="USDC"),[i]),[d,c]=u.useState(null),m=u.useCallback((y,w)=>{if(!t||n<=0n||n>t.balance||!s||!o||g.addressesEqual(o,s))throw new Error("Enter a valid withdrawal amount and recipient.");if(w.chainId!==t.chainId||!g.addressesEqual(w.executorAddress??w.userAddress,o))throw new Error("The withdrawal wallet or network changed. Review the withdrawal again.");return Yu(t.chainId,t.address,[{recipient:s,amount:n}]).calls},[t?.address,t?.chainId,t?.balance,n,s,o]),p=u.useMemo(()=>d?{asset:d,amount:"0"}:null,[d]),f=ur({enabled:e.enabled&&!!l&&!!t&&n>0n&&!!s&&!!o&&!g.addressesEqual(o,s),feeOnlyAction:!0,isZeroAmountPay:!0,amountDirection:"output",paymentAmount:"0",destinationToken:{address:l?.address??A.ZERO_ADDRESS,symbol:l?.symbol??"USDC",decimals:l?.decimals??6,chainId:i},recipient:o,selectedAsset:p,sourceChains:e.sourceChains,includeCrossChainEmbeddedAssets:!0,includeExternalWalletAssets:!1,feeExecutionMode:"backend-transfer",buildActionCalls:m,buildSpicenetBatch:zi,onError:(y,w)=>e.onError?.(y.message,w),onSuccess:()=>{t&&(window.dispatchEvent(new CustomEvent("withdraw-completed")),r?.({token:t.symbol,amount:I.formatUnits(n,t.decimals),chainId:i}))}}),h=`${e.enabled}:${t?.chainId}:${t?.address}:${n}:${s}`,x=u.useRef(h);u.useEffect(()=>{x.current===h||f.status.isExecuting||(x.current=h,(f.status.step==="success"||f.status.paymentResult?.status==="success")&&f.resetAfterSuccess())},[h,f.status.isExecuting,f.status.step,f.status.paymentResult?.status,f.resetAfterSuccess]);const b=u.useMemo(()=>l?f.assets.displayAssets.flatMap(y=>{if(y._fundingWallet==="external"||y.isNative)return[];if(!(y._source==="spice"?Dn(y,i).some(v=>g.addressesEqual(v,l.address)):y._fundingWallet==="embedded"&&A.getTokensForChain(y.chainId).some(v=>v.equivalenceGroup==="USDC"&&g.addressesEqual(v.address,y.address))))return[];const w=t&&y._source==="wallet"&&y.chainId===t.chainId&&g.addressesEqual(y.address,t.address)?n:0n,S=y.balance-w;return S>0n?[{...y,balance:S,balanceFormatted:Number(I.formatUnits(S,y.decimals))}]:[]}).sort((y,w)=>{const S=v=>v._source==="wallet"&&v.chainId===i?0:v._source==="spice"?1:2;return S(y)-S(w)||w.balanceFormatted-y.balanceFormatted}):[],[f.assets.displayAssets,l,i,t?.address,t?.chainId,n]);return u.useEffect(()=>{if(!e.enabled||f.status.isExecuting)return;const y=(d&&b.find(w=>hs(w)===hs(d)))??b[0]??null;(!d||!y||hs(d)!==hs(y)||d.balance!==y.balance)&&c(y)},[e.enabled,f.status.isExecuting,b,d]),{supply:f,candidates:b,source:d,setSource:c,feeToken:l,sourceKey:hs}}const qi=({isSuccess:e,type:t,chainName:n,explorerUrl:s,txHash:o,dark:r=!1,successBg:i="#d1fae5",successBorder:l="#6ee7b7",successText:d="#065f46",errorBg:c="#fee2e2",errorBorder:m="#fca5a5",errorText:p="#dc2626",textSecondary:f="#6b7280"})=>a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?i:c,border:e?`1px solid ${l}`:`1px solid ${m}`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[a.jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:a.jsx("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:a.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),a.jsxs("div",{children:[a.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:g.font.mono,letterSpacing:"0.5px",color:e?d:p},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),a.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:f},children:["on ",n]})]})]}),s&&o&&a.jsxs("a",{href:`${s}/tx/${o}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:f,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[a.jsx("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),a.jsx("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),a.jsx("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),Hi=`
30
+ `})]})};async function _c(e,t,n){let s=null;try{const o=await e.request({method:"eth_chainId"});s=parseInt(o,16)}catch{s=null}s!==t&&(n?.(),await g.ensureWalletOnChain(e,t))}async function Ns(e){let t=e.hash,n=!1;const s=await e.client.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1,onReplaced:o=>{const r=o.transaction,i=o.replacedTransaction;if(!(o.reason==="repriced"&&i?.from&&i.nonce!==void 0&&/^0x[0-9a-f]{64}$/i.test(r?.hash??"")&&r?.to?.toLowerCase()===e.call.to.toLowerCase()&&(r.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(r.value??0)===e.call.value&&r.from?.toLowerCase()===i?.from?.toLowerCase()&&r.nonce===i?.nonce)){n=!0,e.onCancelled?.();return}t=r.hash,e.onRepriced?.(t)}});if(n)throw new Error("Transaction was cancelled or replaced with a different action; retry the unfinished action");if(s.transactionHash&&s.transactionHash.toLowerCase()!==t.toLowerCase())throw new Error("Unexpected transaction receipt; recover the submitted transaction before retrying");return{receipt:s,hash:t}}function pa(e){let t=e;const n=new Set;for(;t&&typeof t=="object"&&!n.has(t);){if(n.add(t),t.code===4001)return!0;t=t.cause}return!1}async function On(e){const t=e.provider??await e.wallet?.getEthereumProvider();if(!t)throw new Error("External wallet provider not available");await _c(t,e.chainId,e.onSwitch);const n=g.getChainConfig(e.chainId)?.viemChain;return{extWc:I.createWalletClient({account:e.account,chain:n,transport:I.custom(t)}),viemChain:n}}async function Mo(e){let t;for(const[n,s]of e.calls.entries()){await e.observer?.onSending?.(n);let o;try{o=await e.extWc.sendTransaction({to:s.to,data:s.data,value:s.value,chain:e.viemChain})}catch(i){throw pa(i)&&e.observer?.onRejected?.(n),i}e.observer?.onSubmitted?.(n,o);const r=await Ns({client:e.client,hash:o,call:s,onRepriced:i=>e.observer?.onSubmitted?.(n,i),onCancelled:()=>e.observer?.onReverted?.(n,o)});if(o=r.hash,r.receipt.status!=="success")throw e.observer?.onReverted?.(n,o),new Error(e.errorMessage);e.observer?.onConfirmed?.(n,o),t=o}return t}function fa(e,t,n,s){return n?{to:e,value:s,data:"0x"}:{to:t,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[e,s]})}}function ma(e,t){return t.isNative?e.sendTransaction({to:t.recipient,value:t.amount,chain:t.viemChain}):e.sendTransaction({to:t.tokenAddr,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[t.recipient,t.amount]}),chain:t.viemChain})}async function ha(e){const{extWc:t,sourceClient:n,recipient:s,tokenAddr:o,isNative:r,amount:i}=e;if(i<=0n)return;await e.observer?.onSending?.(0);let l;try{l=await ma(t,{recipient:s,tokenAddr:o,isNative:r,amount:i,viemChain:e.viemChain})}catch(c){throw pa(c)&&e.observer?.onRejected?.(0),c}e.observer?.onSubmitted?.(0,l);const d=await Ns({client:n,hash:l,call:fa(s,o,r,i),onRepriced:c=>e.observer?.onSubmitted?.(0,c),onCancelled:()=>e.observer?.onReverted?.(0,l)});if(l=d.hash,d.receipt.status!=="success")throw e.observer?.onReverted?.(0,l),new Error("Embedded wallet funding failed");e.observer?.onConfirmed?.(0,l)}const ga="spiceflow:pendingDeposit",Ms="spiceflow:pendingDepositChanged";function xa(e,t,n){return`${ga}:${e.toLowerCase()}:${t}:${n.toLowerCase()}`}function Oo(){try{const e="__spiceflow_storage_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}function ed(e){if(!Oo())return;const t=xa(e.embeddedWalletAddress,e.chainId,e.tokenAddress);try{localStorage.setItem(t,JSON.stringify(e)),window.dispatchEvent(new Event(Ms))}catch(n){console.error("[pendingDeposit] Failed to save:",n)}}function td(e){if(!Oo())return[];const t=`${ga}:${e.toLowerCase()}:`,n=[],s=Date.now();for(let o=0;o<localStorage.length;o++){const r=localStorage.key(o);if(!(!r||!r.startsWith(t)))try{const i=localStorage.getItem(r);if(!i)continue;const l=JSON.parse(i);if(s-l.timestamp>6048e5){localStorage.removeItem(r);continue}n.push(l)}catch{localStorage.removeItem(r)}}return n}function Po(e,t,n){if(!Oo())return;const s=xa(e,t,n);localStorage.removeItem(s),window.dispatchEvent(new Event(Ms))}function nd({sourceChainId:e,selectedAsset:t,destinationChainId:n,destinationTokenAddress:s,isCrossDenomination:o,convertedUsdAmount:r}){const i=A.normalizeNativeTokenAddress(t.asset.address),l=s;let d,c;if(l&&n)if(d=g.CHAIN_CONFIGS[n]?.supportedTokens?.find(m=>g.addressesEqual(m.address,l))?.decimals??t.asset.decimals,o){if(!r)throw new Error("Destination amount is still being calculated. Please retry in a moment.");c=r}else{const m=I.parseUnits(t.amount,t.asset.decimals);c=A.convertAmountBetweenDecimals(m,t.asset.decimals,d)}return{sourceChainId:e,depositTokenAddress:i,depositAmount:t.amount,depositTokenDecimals:t.asset.decimals,destinationChainId:n,destinationTokenAddress:l,destinationAmount:c,destinationTokenDecimals:d}}async function sd(e,t){if(!e)return[];if(Array.isArray(e))return e;const n=e;return e.length>=2?n(t.depositAmount,t.depositTokenAddress):n(t)}function ya(e,t){return!!e&&e.quotedAmount===t.amount&&e.chainId===t.chainId&&g.addressesEqual(e.token,t.token)}async function Wo(e,t){const n=await ma(e,{recipient:t.recipient,tokenAddr:t.tokenAddr,isNative:t.isNative,amount:t.amount});t.afterSend?.(n);const s=g.getClientForChain(t.chainId),o=await s.waitForTransactionReceipt({hash:n,timeout:12e4,pollingInterval:2e3,confirmations:2});if(o.status!=="success")throw new Error(t.failureMessage);return t.settle&&await s.getBlockNumber()-o.blockNumber<2n&&await hn(3e3),o.transactionHash}async function od(e){const t=e.selectedDepositAssets.filter(o=>o.asset&&o.amount&&parseFloat(o.amount)>0);if(t.length===0){console.error("[DepositModal] No valid assets for deposit"),e.setError("Please select an asset and enter an amount");return}const n=t[0];if(!e.escrowOnly&&!e.sourceAddress){e.setError("External wallet not connected. Please connect your wallet in the previous step.");return}if(!e.isNon7702){if(!e.address||!e.embeddedWalletAddress){e.setError("Couldn't find your account wallet. Try reconnecting.");return}if(!e.isReady||!e.isAuthenticated){e.setError("Sign in to continue.");return}}if(e.zeroCreditError){e.setError(e.zeroCreditError);return}if(e.depositBalanceError){e.setError(e.depositBalanceError);return}if(e.isNon7702&&e.sponsorGas&&e.nativeChainId&&n.asset.chainId!==e.nativeChainId&&e.destinationTokenAddress){e.setError("Gas sponsorship is not supported for this deposit route. Disable sponsorGas to continue.");return}e.setIsExecuting(!0),e.setError(null);let s=!1;try{const o=n.asset.chainId,r=A.getEscrowContractAddress(o),i=I.parseUnits(n.amount,n.asset.decimals),l=t.length===1&&ya(e.effectiveDepositFee,{amount:i,token:A.normalizeNativeTokenAddress(n.asset.address),chainId:o});if(!e.isNon7702&&t.length===1&&!l)throw new Error("Fee quote is out of date. Please wait for it to refresh.");let d=e.externalWalletClient;if(!e.escrowOnly){if(!d)throw new Error("External wallet not connected");if(e.externalProvider){const c=await On({provider:e.externalProvider,account:e.sourceAddress,chainId:o});c.viemChain&&(d=c.extWc)}}if(e.isNon7702){if(!d)throw new Error("External wallet not connected");if(!e.sourceAddress)throw new Error("External wallet address not available");if(e.nativeChainId&&o===e.nativeChainId){const c=g.getChainConfig(o),m=t.map(f=>`${f.amount} ${f.asset.symbol}`).join(", ");e.setConfirmationData({network:c?.displayName||`Chain ${o}`,amount:m,symbol:"",chainId:o}),e.setShowConfirmation(!0);let p=null;e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(o);for(const f of t){const h=I.parseUnits(f.amount,f.asset.decimals),x=A.normalizeNativeTokenAddress(f.asset.address),b=f.asset.isNative||A.isNativeToken(x),y=await Wo(d,{chainId:o,recipient:r,tokenAddr:x,isNative:b,amount:h,failureMessage:`Escrow deposit failed for ${f.asset.symbol}`});p=y,e.setDirectDepositTxHash(y)}if(t[0]?.amount){const f=t[0].amount;if(e.onDepositExecute){e.setPostDepositStatus("executing");try{await e.onDepositExecute(f),e.setPostDepositStatus("success")}catch(x){console.error("ctx.onDepositExecute failed:",x),e.setPostDepositStatus("error"),e.setPostDepositError(x?.message||"Post-deposit instruction failed")}}else e.setPostDepositStatus("success");e.setDirectDepositStatus("success"),e.setPostDepositAmount(f),e.setPostDepositSuccess(!0);const h={type:"deposit",status:"success",amount:f,asset:t[0].asset.symbol,sourceChain:c?.displayName||`Chain ${o}`,txHash:p??void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:h})),e.onDepositSuccess?.(h)}e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset)}else{const c=e.destinationChainId||e.nativeChainId;if(!c)throw new Error("Destination chain ID is required for non-7702 mode. Either pass ctx.destinationChainId to <SpiceDeposit> or set ctx.nativeChainId on <SpiceFlowProvider>.");const m=g.getDelegateContractAddress(o),p=r,f=[];let h=null;for(const x of t){const b=I.parseUnits(x.amount,x.asset.decimals),y=A.normalizeNativeTokenAddress(x.asset.address),w=x.asset.isNative||A.isNativeToken(y),S=await Wo(d,{chainId:o,recipient:p,tokenAddr:y,isNative:w,amount:b,failureMessage:`Transfer failed for ${x.asset.symbol}`,afterSend:v=>{h||(h=v)},settle:!0});e.depositDataRef.current||(e.depositDataRef.current=[]),e.depositDataRef.current.push({txHash:S,sender:e.sourceAddress,tokenAddress:y,chainId:o,amount:b.toString(),user:e.spiceBalanceUser}),f.push({tokenAddress:y,tokenAmount:b.toString(),sender:e.sourceAddress,receiver:p})}if(!h)throw new Error("No transaction hash generated");if(!e.destinationTokenAddress){const x={type:"deposit",status:"success",amount:t[0]?.amount,asset:t[0]?.asset?.symbol,sourceChain:g.getChainName(o),txHash:h};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:x})),e.onDepositSuccess?.(x),e.depositDataRef.current=null,e.bridgedAmountRef.current=t[0]?.amount||null,e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1);return}if(e.mode==="ondemand"){const x={to:m,value:BigInt(0),data:"0x"},b=await g.getTokenDecimals(c,e.destinationTokenAddress);let y=BigInt(0);for(const j of f){const T=BigInt(j.tokenAmount),R=A.normalizeNativeTokenAddress(j.tokenAddress),D=t.find(P=>{const q=A.normalizeNativeTokenAddress(P.asset.address);return g.addressesEqual(q,R)}),M=D?D.asset.decimals:await g.getTokenDecimals(o,A.ZERO_ADDRESS);y+=A.convertAmountBetweenDecimals(T,M,b)}e.isCrossDenomination&&e.convertedUsdAmount&&(y=e.convertedUsdAmount);const w={chainId:o,tokenTransfers:f.map(j=>({from:j.sender,to:j.receiver,token:j.tokenAddress,amount:BigInt(j.tokenAmount)})),call:x},S=e.isCrossDenomination&&e.convertedUsdAmount?[{from:e.sourceAddress,to:r,token:A.normalizeNativeTokenAddress(t[0].asset.address),amount:I.parseUnits(t[0].amount,t[0].asset.decimals)}]:[],v={chainId:c,tokenTransfers:[...S,{from:"escrow",to:e.sourceAddress,token:e.destinationTokenAddress,amount:y}],call:{to:e.destinationTokenAddress,value:BigInt(0),data:"0x"}},k={mode:"non-7702:on-demand",chainBatches:[w,v]},C={user:e.sourceAddress,intents:[k]},E=await g.relayerService.createAction(C),F=E.actionId,B=E.intentIds[0];if(!h)throw new Error("No transaction hash available");e.startStatusPolling(B,g.createInitialSteps([{chainId:o,calls:[x]},{chainId:c,calls:[v.call]}],j=>g.getChainName(j))),await g.relayerService.executeStep(F,0,0,{action:"execute",hash:h}),t[0]?.amount&&(e.bridgedAmountRef.current=t[0].amount),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1)}else throw new Error("Presign mode not yet fully supported for cross-chain deposits")}}else{const c=[],m=l&&e.effectiveDepositFee?I.formatUnits(e.effectiveDepositFee.net,n.asset.decimals):n?.amount;for(const k of t){const C=I.parseUnits(k.amount,k.asset.decimals),E=l&&k===n,F=E?e.effectiveDepositFee.fee:0n,B=E?e.effectiveDepositFee.net:C,j=e.escrowOnly?C:C+F,T=A.normalizeNativeTokenAddress(k.asset.address),R=k.asset.isNative||A.isNativeToken(T);e.escrowOnly||await Wo(d,{chainId:o,recipient:e.address,tokenAddr:T,isNative:R,amount:j,failureMessage:`Transfer to embedded wallet failed for ${k.asset.symbol}`,afterSend:()=>ed({chainId:o,tokenAddress:A.normalizeNativeTokenAddress(k.asset.address),tokenSymbol:k.asset.symbol,tokenDecimals:k.asset.decimals,amount:k.amount,rawAmount:C.toString(),embeddedWalletAddress:e.address,externalWalletAddress:e.sourceAddress,timestamp:Date.now(),isNative:R}),settle:!0}),c.push(R?{to:r,value:B,data:"0x"}:{to:T,value:BigInt(0),data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[r,B]})}),F>0n&&c.push(R?{to:A.SPICE_GAS_FEE_RECIPIENT,value:F,data:"0x"}:{to:T,value:BigInt(0),data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[A.SPICE_GAS_FEE_RECIPIENT,F]})})}const p=await g.getClientForChain(o).getBlockNumber(),f=c.map(k=>({...k,to:I.getAddress(k.to)})),h={chainId:o,recentBlock:p,calls:f,tokenTransfers:[]},x=nd({sourceChainId:o,selectedAsset:n&&m?{...n,amount:m}:t[0],destinationChainId:e.destinationChainId,destinationTokenAddress:e.destinationTokenAddress,isCrossDenomination:e.isCrossDenomination,convertedUsdAmount:e.convertedUsdAmount}),b=await sd(e.depositBatches,x),y=[h,...b];if(!e.address)throw new Error("Address not available");const w=[];if(e.isCrossDenomination&&e.convertedUsdAmount&&e.destinationTokenAddress){const k=e.selectedDepositAssets[0]?.asset;if(k){const C=I.parseUnits(e.selectedDepositAssets[0].amount,k.decimals);w.push({from:e.address,to:r,token:A.normalizeNativeTokenAddress(k.address),amount:C}),w.push({from:"escrow",to:e.address,token:e.destinationTokenAddress,amount:e.convertedUsdAmount})}}w.length>0&&y[1]&&(y[1].tokenTransfers=w);const S=g.createInitialSteps(y,k=>g.getChainName(k));let v=!1;if(await e.execution.execute(y,A.ZERO_ADDRESS,0n,k=>{if(k.intentId&&!v){v=!0;for(const C of t)Po(e.address,o,A.normalizeNativeTokenAddress(C.asset.address));e.startStatusPolling(k.intentId,S)}},void 0,{userOverride:e.address,useCustomTransfers:!0,skipPreSubmitFeeEstimate:!0,skipUserFundingPreflight:!0}),e.refreshAssets(),e.onDepositExecute&&t[0]?.amount)try{e.setPostDepositStatus("executing"),await e.onDepositExecute(m||t[0].amount),e.setPostDepositStatus("success"),e.setPostDepositAmount(m||t[0].amount),e.setPostDepositSuccess(!0)}catch(k){console.error("ctx.onDepositExecute failed (7702):",k),e.setPostDepositStatus("error"),e.setPostDepositError(k?.message||"Post-deposit instruction failed")}e.onDepositSelect&&e.onDepositSelect(t[0].asset)}}catch(o){s=!0,console.error("[DepositModal] executeDeposit CAUGHT ERROR:",o),console.error("[DepositModal] Error details:",{message:o?.message,code:o?.code,name:o?.name,stack:o?.stack?.slice(0,500)}),e.setError(g.sanitizeError(o,"Deposit failed")),e.clearStatus()}finally{e.setIsExecuting(!1),s&&e.setDirectDepositStatus("idle"),s||!e.getCurrentIntentStatus()&&e.getCurrentPostDepositStatus()!=="idle"||e.setShowConfirmation(!1)}}async function rd(e){const{asset:t,assetIndex:n,selectedAssetCount:s,address:o,escrowOnly:r,isNon7702:i}=e;if(n!==0||i||s>1||!o||t.balance<=0n)return null;const l=await ba({address:o,depositQuote:{asset:t,amount:t.balance,token:A.normalizeNativeTokenAddress(t.address),chainId:t.chainId},escrowOnly:r}),d=r?t.balance:t.balance>l.fee?t.balance-l.fee:0n;return ra(d,t.decimals)}async function ba(e){const{address:t,depositQuote:n,escrowOnly:s}=e,{asset:o,amount:r,token:i,chainId:l}=n,d=A.getEscrowContractAddress(l),c=o.isNative||A.isNativeToken(i),m=r>1n?1n:0n,p=[c?{to:d,value:r,data:"0x"}:{to:i,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[d,r]})}];m>0n&&p.push(c?{to:A.SPICE_GAS_FEE_RECIPIENT,value:m,data:"0x"}:{to:i,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[A.SPICE_GAS_FEE_RECIPIENT,m]})});const f={chainId:l,tokenTransfers:[],calls:p},h=(await g.relayerService.estimateBatchGas({user:t,outputToken:i,chainBatches:[{...f,hash:A.hashChainBatches([f])[0].hash}],signal:e.signal})).gasFee,x=s&&h<r?r-h:r;return{fee:h,net:x,quotedAmount:r,token:i,chainId:l}}const ad=({selectedDepositAssets:e,depositAssets:t,secondAssetOptions:n,loadingAssets:s,allowSecondAsset:o,theme:r,styles:i,dark:l,dk:d,onSelect:c,onAmountChange:m,onAdd:p,onRemove:f,resolveMaxAmount:h,onViewAllAssets:x})=>a.jsxs(a.Fragment,{children:[e.map((b,y)=>{const w=e.length===1?"Deposit":`Asset ${y+1}`;return a.jsxs("div",{style:{marginBottom:r.spacing.md,position:"relative"},children:[a.jsx(os,{assets:y===0?t:n,selectedAsset:b||void 0,onAssetSelect:S=>c(S,y),onAmountChange:S=>m(S,y),loading:s,label:w,showBalance:!0,theme:r,styles:i,allowSecondAsset:o&&y===0,onAddAsset:p,canAddAsset:e.length===1&&!!e[0]?.asset,resolveMaxAmount:h?S=>h(S,y):void 0,onViewAllAssets:y===0?x:void 0}),y===1&&a.jsx("button",{onClick:()=>f(y),style:{position:"absolute",top:"-2px",right:"-2px",background:l?`${d.cardBg}ee`:"rgba(255, 255, 255, 0.9)",border:`1px solid ${d.cardBorder}`,borderRadius:"50%",cursor:"pointer",color:r.colors.textMuted,fontSize:"16px",padding:"2px",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",transition:g.transition.interactive,boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)"},onMouseEnter:S=>{S.currentTarget.style.color=l?d.errorText:"#ef4444",S.currentTarget.style.background=l?d.cardBg:"#fff",S.currentTarget.style.borderColor=l?d.errorBorder:"#fecaca"},onMouseLeave:S=>{S.currentTarget.style.color=r.colors.textMuted,S.currentTarget.style.background=l?`${d.cardBg}ee`:"rgba(255, 255, 255, 0.9)",S.currentTarget.style.borderColor=l?d.cardBorder:"#e5e7eb"},title:"Remove asset",children:"\xD7"})]},`asset-${y}`)}),e.length===0&&a.jsx("div",{style:{marginBottom:r.spacing.md},children:a.jsx(os,{assets:t,selectedAsset:void 0,onAssetSelect:b=>c(b,0),onAmountChange:b=>m(b,0),loading:s,label:"Deposit",showBalance:!0,theme:r,styles:i,allowSecondAsset:o,onAddAsset:p,canAddAsset:!1,resolveMaxAmount:h?b=>h(b,0):void 0},"initial-selector")})]}),id=u.memo(ad);var Uo="data:image/svg+xml,%3csvg width='10' height='10' viewBox='0 0 10 10' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M5 4.99995V6.99995M5 3.31245V3.31189M9.5 5C9.5 7.48528 7.48528 9.5 5 9.5C2.51472 9.5 0.5 7.48528 0.5 5C0.5 2.51472 2.51472 0.5 5 0.5C7.48528 0.5 9.5 2.51472 9.5 5Z' stroke='black' stroke-opacity='0.4' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e";const wa=u.memo(({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,onDepositSelect:s,depositBatches:o,supportedChains:r,title:i,styles:l,onDepositAssetChange:d,assetInputHook:c,externalWalletAddress:m,onDepositAmountChange:p,allowSecondAsset:f=!1,destinationChainId:h,destinationTokenAddress:x,onDepositExecute:b,depositActionLabel:y,nativeChainId:w,sponsorGas:S=!1,preSelectedAsset:v,escrowOnly:k=!1,escrowTokenAddress:C,escrowAmount:E,escrowTokenDecimals:F,escrowTokenSymbol:B,onDepositSuccess:j,onDepositError:T,embeddedWalletAddress:R,onViewAllAssets:D})=>{const M=u.useContext(g.SpiceFlowProviderContext),P=M?.mode||"7702",q=M?.allowedTokens,z=!!M?.isWhitelistGateActive,X=!k&&!!M?.isWhitelistConfigured&&M?.isUserWhitelisted!==!0,N=c?.assetAmount||"",{theme:H,dark:V,appName:G,primaryColor:J,dk:U}=g.useSpiceBrand(l),L=g.useWallet(),{isReady:O,isAuthenticated:ee}=L,{externalWallet:ue}=g.useProviderWallets(),re=M?.embeddedWalletAddress||R,se=P!="7702",ie=se?!!m:O&&ee&&!!re,ce=re,_=m,Ce=ce??_,{data:W}=pn.useWalletClient(),[ae,he]=u.useState(W),ne=u.useRef(null),Q=u.useRef(ue);Q.current=ue;const te=ue?.address;u.useEffect(()=>{const Z=Q.current;if(!Z||!_){ne.current=null,he(W);return}if(Z.address?.toLowerCase()!==_?.toLowerCase()){ne.current=null,he(W);return}Z.getEthereumProvider().then(async le=>{ne.current=le;const We=await le.request({method:"eth_chainId"}),ke=parseInt(We,16),gt=g.getChainConfig(ke),wt=await Z.getWalletClient(ke);he(gt?I.createWalletClient({account:_,chain:gt.viemChain,transport:I.custom(le)}):wt)}).catch(()=>{ne.current=null,he(W)})},[te,_,W]);const be=u.useRef(null),[$,Se]=u.useState([]),{assets:ct,loading:xe,error:pt,refreshAssets:Me}=mn({address:k?ce:_||ce,supportedChains:r,fetchBalances:fn,enabled:e,refreshInterval:e?5e3:0}),Ue=u.useMemo(()=>{if(z)return[];const Z=r.flatMap(le=>g.getAllAssetsForChain(le,ct));return q&&q.length>0?Z.filter(le=>q.includes(le.symbol.toLowerCase())||le.isNative&&q.includes("native")).sort((le,We)=>{const ke=le.balance>BigInt(0)?1:0;return(We.balance>BigInt(0)?1:0)-ke}):Z.filter(le=>le.balance>BigInt(0))},[r,ct,q,z]),Xe=u.useMemo(()=>{if(!$[0]?.asset)return[];const Z=$[0].asset.chainId;return Ue.filter(le=>le.chainId===Z)},[Ue,$]),[Ae,nt]=u.useState(!1),[st,ft]=u.useState(null),ot=u.useRef(T);ot.current=T;const _e=u.useCallback(Z=>{ft(Z),typeof Z=="string"&&Z&&ot.current?.(Z,g.getRelayerErrorDetail(Z))},[]),[Be,Ct]=u.useState("idle"),mt=u.useCallback(Z=>{typeof Z=="string"&&Z&&ot.current?.(Z,g.getRelayerErrorDetail(Z))},[]),[Te,Ke]=u.useState(!1),[Oe,Y]=u.useState(null),[Ee,ye]=u.useState("idle"),[Re,dt]=u.useState(null),[Qe,yt]=u.useState(null),[lt,qt]=u.useState(null),[Lt,Nt]=u.useState(null),[Je,pe]=u.useState(null),{intentStatus:Pe,startStatusPolling:at,clearStatus:ut,execute:ve}=ds(),fe=u.useCallback((Z,le)=>{const We=g.CHAIN_CONFIGS[le];return We?We.supportedTokens?.find(ke=>g.addressesEqual(ke.address,Z))?.symbol??null:null},[]),He=u.useMemo(()=>{const Z=$[0]?.asset;if(!Z||!x||!h)return!1;const le=fe(x,h);return rc(Z.symbol)&&!!le&&ac(le)},[$,x,h,fe]);u.useEffect(()=>{$.length>0&&N!==$[0]?.amount&&Se(Z=>{if(Z.length===0)return Z;const le=[...Z];return le[0]={...le[0],amount:N||""},le})},[N]),u.useEffect(()=>{$.length!==0&&Se(Z=>{let le=!1;const We=Z.map(ke=>{if(!ke.asset)return ke;const gt=Ue.find(wt=>wt.chainId===ke.asset.chainId&&g.addressesEqual(wt.address,ke.asset.address));return gt?gt===ke.asset||gt.balance===ke.asset.balance?ke:(le=!0,{...ke,asset:gt,amount:ke.amount}):ke});return le?We:Z})},[Ue,$.length]),u.useEffect(()=>{if(!v||$.length>0||Ue.length===0)return;const Z=Ue.find(le=>le.chainId===v.chainId&&g.addressesEqual(le.address,v.address));Z&&(Se([{asset:Z,amount:""}]),d?.(Z))},[v,Ue,$.length]);const it=u.useRef(null);u.useEffect(()=>{if(se&&Pe?.overallStatus==="success"&&b&&Be==="idle"){const Z=it.current,le=be.current;Z&&(async()=>{try{Ct("executing"),await b(Z),Ct("success"),Y(Z),Ke(!0);const We=Array.isArray(le)?le[0]:void 0,ke={type:"deposit",status:"success",amount:Z,asset:We?.tokenAddress,sourceChain:We?String(We.chainId):void 0,txHash:We?.txHash};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:ke})),j?.(ke)}catch(We){console.error("onDepositExecute failed:",We),Ct("error"),mt(g.sanitizeError(We,"Post-deposit instruction failed"))}finally{it.current=null,be.current=null}})()}},[Pe?.overallStatus,se,Be]);const Ge=u.useCallback(()=>{_e(null)},[]);u.useEffect(()=>{e||(Ke(!1),Y(null),ye("idle"),dt(null),yt(null))},[e]);const Ie=u.useCallback((Z,le)=>{Se(We=>{const ke=[...We];return ke[le]={asset:Z,amount:ke[le]?.amount||""},ke}),le===0&&d?.(Z),Ge()},[d,Ge]),Et=u.useCallback(async(Z,le)=>{if(Se(We=>{const ke=[...We];return ke[le]&&(ke[le]={...ke[le],amount:Z}),ke}),Ge(),le===0)if(c?.setAssetAmount(Z),He&&Z&&parseFloat(Z)>0)try{const We=lt??await oc();lt||qt(We);const ke=$[0]?.asset;if(!ke)return;const gt=I.parseUnits(Z,ke.decimals),wt=x?fe(x,h):null,Tt=g.CHAIN_CONFIGS[h]?.supportedTokens?.find(At=>g.addressesEqual(At.address,x))?.decimals??6,dn=ic(gt,ke.decimals,Tt,We);Nt(dn);const ln=I.formatUnits(dn,Tt),un=We.toLocaleString("en-US",{maximumFractionDigits:0});pe(`${Z} ${ke.symbol} \u2248 $${parseFloat(ln).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})} ${wt??"USD"} (rate: $${un}/BTC)`),p?.(ln)}catch(We){console.error("Failed to fetch BTC/USD price:",We),pe(null),Nt(null),p?.(Z)}else pe(null),Nt(null),p?.(Z)},[Ge,c,p,He,lt,$,x,h,fe]),De=u.useCallback(()=>{$.length<2&&Se(Z=>[...Z,{asset:null,amount:""}])},[$.length]),bt=u.useCallback(Z=>{Se(le=>le.filter((We,ke)=>ke!==Z)),Ge()},[Ge]),jt=u.useRef(!1),Ht=u.useRef(!1);u.useEffect(()=>{e||(jt.current=!1,Ht.current=!1,Yt(null),Ft(null))},[e]);const[zt,Pt]=u.useState(!1),[$e,et]=u.useState(null),[Rt,Yt]=u.useState(null),[tn,Ft]=u.useState(null),[ge,qe]=u.useState(!1),[xt,Wt]=u.useState(null),Fe=u.useMemo(()=>{const Z=$[0];if($.length!==1||!Z?.asset||!Z.amount||parseFloat(Z.amount)<=0)return null;try{return{asset:Z.asset,amount:I.parseUnits(Z.amount,Z.asset.decimals),token:A.normalizeNativeTokenAddress(Z.asset.address),chainId:Z.asset.chainId}}catch{return null}},[$]),Ut=u.useMemo(()=>Fe?[Fe.chainId,Fe.token.toLowerCase(),Fe.amount.toString(),k?"escrow":"normal"].join("|"):null,[Fe,k]),Ze=u.useCallback(async(Z,le)=>ce?ba({address:ce,depositQuote:Z,escrowOnly:k,signal:le}):null,[ce,k]),Xt=u.useCallback(async Z=>Fe?Ze(Fe,Z):null,[Fe,Ze]),tt=u.useRef(Xt);tt.current=Xt,as({shouldRun:e&&!se&&!!Ut&&!zt&&!Ae,deps:[e,se,Ut,zt,Ae],delayMs:500,backgroundIntervalMs:1e4,onSkip:()=>{Yt(null),Wt(null),qe(!1)},onCleanup:()=>qe(!1),run:async({isBackground:Z,isCurrent:le,signal:We})=>{Z||(Wt(null),qe(!0));try{const ke=await tt.current(We);le()&&Yt(ke)}catch(ke){if(!le())return;Yt(null),Wt(ke instanceof Error?ke.message:"Failed to estimate gas fee")}finally{le()&&qe(!1)}}}),u.useEffect(()=>{zt||Ae||Ft(null)},[zt,Ae,Ut]);const Mt=async()=>{if($.length===0||!$[0]?.asset)return;const Z=$.filter(wt=>wt.asset&&wt.amount&&parseFloat(wt.amount)>0);if(Z.length===0)return;const le=Z[0],We=g.getChainConfig(le.asset.chainId),ke=Z.map(wt=>{const Tt=parseFloat(wt.amount);return`${isNaN(Tt)?wt.amount:Tt.toPrecision(6).replace(/\.?0+$/,"")} ${wt.asset.symbol}`}).join(", "),gt={network:We?.displayName||`Chain ${le.asset.chainId}`,amount:ke,symbol:"",chainId:le.asset.chainId};if(!se&&Z.length===1&&Rt){Ft(Rt);const wt=Z[0];gt.creditedAmount=`${I.formatUnits(Rt.net,wt.asset.decimals)} ${wt.asset.symbol}`,gt.networkFee=`${I.formatUnits(Rt.fee,wt.asset.decimals)} ${wt.asset.symbol}`}et(gt),Pt(!0)},vt=u.useRef(Pe);vt.current=Pe;const Jt=u.useRef(Be);Jt.current=Be;const oe=async()=>{await od({selectedDepositAssets:$,escrowOnly:k,sourceAddress:_,isNon7702:se,address:ce,embeddedWalletAddress:re,isReady:O,isAuthenticated:ee,zeroCreditError:Le,depositBalanceError:nn,externalWalletClient:ae,externalProvider:ne.current,effectiveDepositFee:Ve,depositBatches:o,destinationChainId:h,destinationTokenAddress:x,isCrossDenomination:He,convertedUsdAmount:Lt,mode:P,sponsorGas:S,nativeChainId:w,spiceBalanceUser:Ce,depositDataRef:be,bridgedAmountRef:it,setIsExecuting:nt,setError:_e,setConfirmationData:et,setShowConfirmation:Pt,setDirectDepositStatus:ye,setDirectDepositChainId:yt,setDirectDepositTxHash:dt,setPostDepositStatus:Ct,setPostDepositError:mt,setPostDepositAmount:Y,setPostDepositSuccess:Ke,startStatusPolling:at,clearStatus:ut,refreshAssets:Me,onDepositExecute:b,onDepositSelect:s,onDepositSuccess:j,execution:{execute:ve},getCurrentIntentStatus:()=>vt.current,getCurrentPostDepositStatus:()=>Jt.current})},Le=u.useMemo(()=>{for(const Z of $)if(!(!Z?.asset||!Z.amount||parseFloat(Z.amount)<=0))try{const le=Z.asset.decimals,We=I.parseUnits(Z.amount,le);if(We<=0n)continue;const ke=A.getEquivalenceGroup(A.normalizeNativeTokenAddress(Z.asset.address)),gt=Z.asset.receiptTokenDecimals??(ke==="ETH"||ke==="ARB"?18:ke==="USDC"||ke==="SUSD"||ke==="WBTC"||ke==="CBTC"?6:void 0);if(gt===void 0||le<=gt||A.convertAmountBetweenDecimals(We,le,gt)>0n)continue;return`Amount too small. Minimum deposit for this asset is ${I.formatUnits(10n**BigInt(le-gt),le)} ${Z.asset.symbol}.`}catch{continue}return null},[$]),Ot=!se&&!!Fe,Ve=tn??Rt,kt=!!Fe&&ya(Ve,Fe),nn=u.useMemo(()=>{if(!Ot||!Fe||!kt)return null;const Z=k?Fe.amount:Fe.amount+Ve.fee;return Fe.asset.balance>=Z?null:`Insufficient ${Fe.asset.symbol}. Need ${I.formatUnits(Z,Fe.asset.decimals)} ${Fe.asset.symbol} including gas.`},[Ot,Fe,kt,Ve,k]),[de,me]=u.useState(!1),ze=$[0]?.asset?.chainId,je=ct.find(Z=>Z.isNative&&Z.chainId===ze)?.balance??0n;u.useEffect(()=>{if(!e||!ze){me(!1);return}let Z=!1;return(async()=>{try{const le=await g.getClientForChain(ze).getGasPrice()*150000n;Z||me(je<le)}catch{Z||me(!1)}})(),()=>{Z=!0}},[e,ze,je]);const St=!Ot||kt&&!ge&&!xt&&!nn,Dt=u.useCallback((Z,le)=>rd({asset:Z,assetIndex:le,selectedAssetCount:$.length,address:ce,escrowOnly:k,isNon7702:se}),[se,$.length,ce,k]),Gt=u.useMemo(()=>{if(!Fe||!Ve||!kt)return null;const Z=k?Fe.amount:Fe.amount+Ve.fee;return{symbol:Fe.asset.symbol,decimals:Fe.asset.decimals,grossAmount:Z,netAmount:Ve.net,totalFee:Ve.fee,gasFee:Ve.fee,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"estimated"}},[Fe,Ve,kt,k]),rt=parseFloat($[0]?.amount||"")||0,ht=$.length>0&&$[0]?.asset&&$[0]?.amount&&rt>0&&ie&&!Ae&&!Le&&!nn&&St&&!X;u.useEffect(()=>{if(!k||!C||!E||jt.current||!ie)return;const Z=r[0];if(!Z)return;const le=g.getAllAssetsForChain(Z,[]).find(ke=>g.addressesEqual(ke.address,C));let We;if(le)We=le;else if(F!==void 0&&B)We={address:C,symbol:B,name:B,decimals:F,chainId:Z,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,isNative:A.isNativeToken(C)};else{console.warn("[DepositModal] escrowOnly: no matching asset and missing escrowTokenDecimals/escrowTokenSymbol for",C);return}jt.current=!0,Se([{asset:We,amount:E}])},[k,C,E,F,B,ie,r]),u.useEffect(()=>{!k||!ht||Ht.current||Ae||(Ht.current=!0,oe())},[k,ht,Ae]);const Vt=pt||st||Le||nn,sn=()=>{if(Ae)return"Executing Deposit...";if(!ie)return"Wallet Not Connected";if(P==="7702"){if(!O)return"Loading...";if(!ee)return"Authentication Required"}return $[0]?.asset?$[0]?.amount?Le?"AMOUNT TOO SMALL":nn?"INSUFFICIENT BALANCE":Ot&&!St?xt?"GAS UNAVAILABLE":"ESTIMATING GAS":"DEPOSIT":"ENTER AMOUNT":"SELECT TOKEN"};return e?a.jsx(rn,{isOpen:e,onClose:t,closeOnBackdropClick:n,title:i||`Deposit to your ${G} account`,subtitle:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[a.jsx("img",{src:Uo,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...V?{filter:"invert(0.6)"}:{}}}),a.jsx("p",{style:{fontSize:"12px",color:U.textSecondary,margin:"0",lineHeight:"1.4",fontFamily:g.font.ui},children:`Deposit collateral to your ${G} Account from any supported network.`})]}),dark:V,overlayContent:zt||Pe||Be!=="idle"&&b?a.jsx("div",{}):void 0,styles:l,theme:H,children:a.jsxs("div",{style:{padding:"24px 24px 5px 24px"},children:[a.jsx(id,{selectedDepositAssets:$,depositAssets:Ue,secondAssetOptions:Xe,loadingAssets:xe,allowSecondAsset:f,theme:H,styles:l,dark:V,dk:U,onSelect:Ie,onAmountChange:Et,onAdd:De,onRemove:bt,resolveMaxAmount:Dt,onViewAllAssets:D}),Ot&&Fe&&a.jsx(Do,{fontFamily:l?.fontFamily||H.typography.fontFamily,textPrimary:U.textPrimary,textSecondary:U.textSecondary,cardBg:V?U.inputBg:"#ffffff",cardBorder:U.cardBorder,resolvedDark:V,darkCardBorder:U.cardBorder,primaryColor:J,feePreview:Gt,isLoading:ge||Ot&&!kt,errorText:xt}),a.jsx($c,{intentStatus:Pe,postDepositSuccess:Te,postDepositAmount:Oe,postDepositStatus:Be,depositActionLabel:y,sourceChainName:$[0]?.asset?.chainId?g.getChainName($[0].asset.chainId):"Destination Chain",directDepositStatus:Ee,directDepositTxHash:Re,directDepositChainId:Qe,styles:l}),a.jsx(Jc,{isOpen:zt||!!Pe||Be!=="idle"&&!!b,onClose:()=>{Pt(!1),Pe&&ut();const Z=Be==="success"&&!Pe,le=Pe?.overallStatus==="success"&&(b?Be==="success":!0);(Z||le)&&t()},onConfirm:oe,data:$e,isExecuting:Ae,error:st,theme:H,styles:l,intentStatus:Pe,postDepositStatus:Be,hasPostDepositInstruction:!!b}),Je&&a.jsxs(Gr,{dk:U,dark:V,borderRadius:H.borderRadius.md,children:["\u26A1 ",Je]}),de&&a.jsx(Gr,{dk:U,dark:V,borderRadius:H.borderRadius.md,children:"Low native balance in the external wallet. The deposit to spicenet account might fail."}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:0,marginBottom:0,margin:0,padding:0},children:[Vt?a.jsx("div",{style:{marginBottom:"10px",fontSize:"12px",lineHeight:"1.45",color:U.errorText,fontFamily:l?.fontFamily||H.typography.fontFamily},children:Vt}):null,a.jsx(g.Button,{variant:"outline",fullWidth:!0,onClick:Mt,disabled:!ht||!ie||Ae,theme:H,dark:V,styles:l,children:sn()})]})]})}):null}),ld=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,deposits:s,onComplete:o,onCancel:r,onSkip:i,onChangeWallet:l,isProcessing:d,error:c,styles:m})=>{const{dark:p,dk:f,theme:h}=g.useSpiceBrand(m);if(!e||s.length===0)return null;const x=s[0],b=m?.fontFamily||g.font.ui,y=g.font.mono,w=g.getChainName(x.chainId),S=parseFloat(x.amount).toPrecision(6).replace(/\.?0+$/,""),v=I.formatUnits(x.verifiedBalance,x.tokenDecimals);return a.jsx(rn,{isOpen:e,onClose:t,title:"Incomplete Deposit",styles:m,closeOnBackdropClick:n,children:a.jsxs("div",{style:{padding:"18px 24px 24px",fontFamily:b},children:[a.jsx("p",{style:{fontSize:"14px",color:f.textSecondary,lineHeight:"1.6",margin:"0 0 18px 0"},children:"Your funds reached your wallet, but the deposit didn't finish."}),a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"14px 18px",marginBottom:"24px",padding:"16px 18px",backgroundColor:p?f.cardBg:"#f8fafc",border:`1px solid ${f.cardBorder}`,borderRadius:p?"14px":"10px",boxShadow:p?"inset 0 1px 0 rgba(255,255,255,0.03)":"0 1px 2px rgba(16,24,40,0.04)"},children:[a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[a.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:f.textSecondary,fontFamily:y,letterSpacing:"0.8px"},children:"NETWORK"}),a.jsx("span",{style:{fontSize:"18px",fontWeight:600,color:f.textPrimary,fontFamily:b,lineHeight:1.2},children:w})]}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px",alignItems:"flex-end",textAlign:"right"},children:[a.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:f.textSecondary,fontFamily:y,letterSpacing:"0.8px"},children:"DEPOSITED AMOUNT"}),a.jsxs("span",{style:{fontSize:"24px",fontWeight:700,color:f.successText,fontFamily:y,lineHeight:1.1},children:[S," ",x.tokenSymbol]}),a.jsx("span",{style:{fontSize:"12px",color:f.textSecondary,fontWeight:500,fontFamily:b},children:"Sent to embedded wallet"})]})]}),!x.hasFullBalance&&x.verifiedBalance>0n&&a.jsxs("div",{style:{marginBottom:"16px",padding:"8px 12px",backgroundColor:f.warningBg,border:`1px solid ${p?f.warningBorder:"#fcd34d"}`,borderRadius:"8px",fontSize:"13px",color:f.warningText,lineHeight:"1.4"},children:["Partial balance \u2014 only ",parseFloat(v).toFixed(4)," ",x.tokenSymbol," available."]}),c&&a.jsx("div",{style:{marginBottom:"16px",padding:"10px 12px",backgroundColor:f.errorBg,border:`1px solid ${p?f.errorBorder:"#fca5a5"}`,borderRadius:"8px",fontSize:"13px",color:p?f.errorText:"#991b1b",lineHeight:"1.4"},children:c}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[a.jsx(g.Button,{variant:"outline",fullWidth:!0,disabled:d,onClick:()=>o(x),theme:h,dark:p,styles:m,children:"CONFIRM DEPOSIT"}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[a.jsx(g.Button,{variant:"ghost",fullWidth:!0,disabled:d,onClick:()=>r(x),theme:h,dark:p,style:{height:"48px",fontSize:"13px",letterSpacing:"0.4px",color:p?f.textPrimary:"#374151",border:`1px solid ${p?f.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:p?"rgba(255,255,255,0.02)":"#ffffff"},children:d?"RETURNING...":"RETURN FUNDS"}),a.jsxs("div",{style:{display:"grid",gridTemplateColumns:l?"1fr 1fr":"1fr",gap:"10px"},children:[a.jsx(g.Button,{variant:"ghost",fullWidth:!0,disabled:d,onClick:i,theme:h,dark:p,style:{height:"44px",fontSize:"12px",letterSpacing:"0.4px",color:f.textSecondary,border:`1px solid ${p?f.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:"transparent"},children:"START OVER"}),l&&a.jsx(g.Button,{variant:"ghost",fullWidth:!0,disabled:d,onClick:l,theme:h,dark:p,style:{height:"44px",fontSize:"12px",letterSpacing:"0.4px",color:f.textSecondary,border:`1px solid ${p?f.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:"transparent"},children:"CHANGE WALLET"})]})]})]}),s.length>1&&a.jsxs("p",{style:{fontSize:"12px",color:f.textSecondary,textAlign:"center",marginTop:"14px",marginBottom:0,lineHeight:"1.5"},children:[s.length," incomplete deposits found \u2014 resolving one at a time."]})]})})},cd=[{source:"wallet",title:"From Wallet",description:"Deposit crypto you already hold in a connected wallet"},{source:"card",title:"With Card",description:"Buy and deposit using a debit or credit card"},{source:"exchange",title:"From Exchange",description:"Transfer from Coinbase, Binance, or any exchange"}],dd=({isOpen:e,onClose:t,closeOnBackdropClick:n,onSelect:s,styles:o})=>{const{dark:r,dk:i}=g.useSpiceBrand(o),[l,d]=u.useState(null);return a.jsx(rn,{isOpen:e,onClose:t,title:"Deposit",subtitle:"Choose how you want to add funds",styles:o,dark:r,closeOnBackdropClick:n,children:a.jsx("div",{style:{padding:"0 24px 25px",display:"flex",flexDirection:"column",gap:"12px",marginTop:"20px"},children:cd.map(({source:c,title:m,description:p})=>a.jsxs("button",{onClick:()=>s(c),onMouseEnter:()=>d(c),onMouseLeave:()=>d(null),style:{width:"100%",display:"flex",flexDirection:"column",alignItems:"flex-start",gap:"4px",padding:"14px 16px",borderRadius:"8px",border:`1px solid ${r?i.cardBorder:"#e5e7eb"}`,backgroundColor:l===c?r?i.hoverBg:"#f9fafb":r?i.cardBg:"white",cursor:"pointer",textAlign:"left",transition:g.transition.color},children:[a.jsx("span",{style:{fontSize:"15px",fontWeight:600,fontFamily:g.font.ui,color:r?i.textPrimary:"#111827"},children:m}),a.jsx("span",{style:{fontSize:"13px",fontFamily:g.font.ui,color:r?i.textSecondary:"#6b7280"},children:p})]},c))})})},ud=({isOpen:e,onClose:t,onBack:n,closeOnBackdropClick:s,source:o,destinationChainId:r,onShowWidget:i,onHideWidget:l,verifying:d,verifyError:c,onRetryVerify:m,funded:p,styles:f})=>{const{dark:h,dk:x,primaryColor:b,theme:y}=g.useSpiceBrand(f),w=g.getChainName(r),S=u.useRef(null),v=u.useRef(i);v.current=i;const k=u.useRef(l);k.current=l;const C=d||!!c||!!p;return u.useEffect(()=>{if(!e)return;const E=S.current;if(E){if(C){k.current();return}return v.current(E,o),()=>k.current()}},[e,o,C]),a.jsx(rn,{isOpen:e,onClose:t,title:o==="card"?"Deposit with Card":"Deposit from Exchange",styles:f,dark:h,closeOnBackdropClick:s,children:a.jsxs("div",{style:{padding:"0 24px 25px",display:"flex",flexDirection:"column",gap:"12px",marginTop:"12px"},children:[a.jsx("button",{onClick:n,disabled:d,style:{alignSelf:"flex-start",padding:0,border:"none",background:"none",fontSize:"13px",fontFamily:g.font.ui,color:h?x.textSecondary:"#6b7280",cursor:d?"default":"pointer",opacity:d?.5:1},children:"\u2190 Back"}),a.jsxs("div",{style:{position:"relative",width:"100%"},children:[a.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center"},children:a.jsx(g.Spinner,{size:28,color:b})}),a.jsx("div",{ref:S,style:{position:"relative",width:"100%",height:"560px"}}),C&&a.jsx("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"16px",padding:"24px",borderRadius:"9px",backgroundColor:h?"rgba(0, 0, 0, 0.82)":"rgba(255, 255, 255, 0.94)"},children:d?a.jsxs(a.Fragment,{children:[a.jsx(g.Spinner,{size:28,color:b}),a.jsxs("p",{style:{margin:0,fontSize:"14px",fontFamily:g.font.ui,color:h?x.textPrimary:"#111827",textAlign:"center"},children:["Confirming your deposit arrived on ",w,"\u2026"]})]}):p?a.jsxs(a.Fragment,{children:[a.jsxs("p",{style:{margin:0,fontSize:"14px",fontFamily:g.font.ui,color:h?x.textPrimary:"#111827",textAlign:"center"},children:[p.amount," ",p.symbol," is in your wallet on"," ",w,"."]}),a.jsx(g.Button,{variant:"outline",onClick:t,theme:y,dark:h,styles:f,children:"DONE"})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{style:{margin:0,fontSize:"14px",fontFamily:g.font.ui,color:h?x.textPrimary:"#111827",textAlign:"center"},children:c}),a.jsx(g.Button,{variant:"outline",onClick:m,theme:y,dark:h,styles:f,children:"RETRY"}),a.jsx("button",{onClick:t,style:{padding:0,border:"none",background:"none",fontSize:"13px",fontFamily:g.font.ui,color:h?x.textSecondary:"#6b7280",cursor:"pointer",textDecoration:"underline"},children:"Close \u2014 we'll detect your funds later"})]})})]})]})})},pd="692fb8af264069ca12a9",Vn=42161,fd=[8453,Vn];function md(e){const{targetKind:t,appChainId:n}=e;return t!=="external"||n===void 0||!fd.includes(n)?Vn:A.getTokenBySymbol("USDC",n)?n:Vn}function Os(e=Vn){return A.getTokenBySymbol("USDC",e)}function hd(e){const t=e?.integratorId??pd;return{integratorId:t,enabled:e?.enabled===!0&&t!=="",embedFactory:e?.embedFactory}}const gd=e=>import("@swapper-finance/deposit-sdk").then(t=>new t.SwapperEmbed(e));function xd(e,t,n){return{themeMode:t?"dark":"light",componentStyles:{width:"100%",primaryColor:n,accentColor:n,borderRadius:"9px",...t?{backgroundColor:e.shell,surfaceColor:e.cardBg,surfaceAltColor:e.inputBg,textColor:e.textPrimary,border:`1px solid ${e.cardBorder}`}:{}}}}function Ca(e){return e==="card"?["depositWithCash"]:e==="exchange"?["transferCrypto"]:["depositWithCash","transferCrypto"]}function yd(e){const t=e.destinationChainId??Vn,n=Os(t);if(!n)throw new Error("USDC is not configured for the Swapper destination chain");return{iframeUrl:"https://swapper-deposit-sdk.web.app/",integratorId:e.integratorId,dstChainId:String(t),dstTokenAddr:n.address,depositWalletAddress:e.depositWalletAddress,supportedDepositOptions:Ca(e.source),styles:e.styles,actionLabel:"deposit",flexibleHeight:!0,iframeAttributes:{borderRadius:"9px"}}}async function va(e,t=Vn){const n=Os(t);if(!n)throw new Error("USDC is not configured for the Swapper destination chain");return g.getClientForChain(t).readContract({address:n.address,abi:I.erc20Abi,functionName:"balanceOf",args:[e]})}async function bd(e,t,n){const s=n?.timeoutMs??12e4,o=n?.intervalMs??3e3,r=Date.now()+s;for(;Date.now()<r;){if(n?.signal?.aborted)return null;try{const i=await va(e,n?.chainId);if(i>t)return i}catch{}await new Promise(i=>setTimeout(i,o))}return null}const Lo=e=>{const[t,n]=u.useState(!1),s=u.useContext(g.SpiceFlowProviderContext),{dark:o,dk:r}=g.useSpiceBrand();if(u.useEffect(()=>{n(!0)},[]),!t)return a.jsx("div",{className:e.className,children:a.jsx("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:o?r.hoverBg:"#ccc",color:o?r.textSecondary:"white",border:o?`1px solid ${r.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!s){const i='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return a.jsx("div",{className:e.className,children:a.jsx("button",{onClick:()=>{e.onAuthError&&e.onAuthError(i)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:o?r.errorBg:"#dc2626",color:o?r.errorText:"white",border:o?`1px solid ${r.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return a.jsx(g.PrivyLogin,{...e})},wd=.01,Cd=5*60*1e3;function vd(e){const t=Number(I.formatUnits(e.verifiedBalance,e.tokenDecimals));return Number.isFinite(t)?t:0}async function kd(e){const t=Sd(e);let n;try{n=await yo(t.map(s=>s.tokenSymbol))}catch{return t}return t.filter(s=>{const o=vd(s);if(o<=0)return!0;const r=n[s.tokenSymbol.toUpperCase()]??0;return!Number.isFinite(r)||r<=0?!0:o*r>=wd})}function Sd(e){const t=new Map;for(const n of e){const s=`${n.chainId}:${n.tokenAddress.toLowerCase()}`;t.get(s)||t.set(s,{...n,amount:n.timestamp===0?I.formatUnits(n.verifiedBalance,n.tokenDecimals):n.amount,rawAmount:n.timestamp===0?n.verifiedBalance.toString():n.rawAmount,hasFullBalance:n.timestamp===0?!0:n.hasFullBalance})}return Array.from(t.values())}function ka(e,t){const[n,s]=u.useState([]),[o,r]=u.useState(!1),i=u.useRef(t);i.current=t;const l=u.useRef(0),d=u.useRef(0),c=u.useCallback(async({forceDiscovery:m=!1}={})=>{if(!e){s([]),r(!1);return}const p=++d.current,f=()=>p!==d.current;r(!0);try{const h=[],x=td(e);for(const S of x){if(f())return;try{const v=g.getClientForChain(S.chainId);let k;if(S.isNative||A.isNativeToken(S.tokenAddress)?k=await on.getBalance(v,{address:e}):k=await on.readContract(v,{address:I.getAddress(S.tokenAddress),abi:I.erc20Abi,functionName:"balanceOf",args:[e]}),f())return;k>0n?h.push({...S,verifiedBalance:k,hasFullBalance:k>=BigInt(S.rawAmount)}):Date.now()-S.timestamp>15*60*1e3&&Po(e,S.chainId,S.tokenAddress)}catch(v){console.warn(`[usePendingDeposit] Failed to verify balance for ${S.tokenSymbol} on chain ${S.chainId}:`,v),h.push({...S,verifiedBalance:0n,hasFullBalance:!1})}}if(f())return;const b=i.current,y=Date.now(),w=(b?.discoverWalletBalances??!0)&&(m||y-l.current>=Cd);if(b?.network&&w){l.current=y;const S=b.chainIds??A.getChainIdsByNetwork(b.network),v=new Set(h.map(C=>`${C.chainId}:${C.tokenAddress.toLowerCase()}`)),k=[];for(const C of S){const E=g.getChainConfig(C);if(E?.supportedTokens)for(const F of E.supportedTokens){if(A.isNativeToken(F.address))continue;const B=`${C}:${F.address.toLowerCase()}`;v.has(B)||k.push((async()=>{try{const j=g.getClientForChain(C),T=await on.readContract(j,{address:I.getAddress(F.address),abi:I.erc20Abi,functionName:"balanceOf",args:[e]});return T>0n?{chainId:C,tokenAddress:F.address,tokenSymbol:F.symbol,tokenDecimals:F.decimals,amount:I.formatUnits(T,F.decimals),rawAmount:T.toString(),embeddedWalletAddress:e,externalWalletAddress:"",timestamp:0,isNative:!1,verifiedBalance:T,hasFullBalance:!0}:null}catch{return null}})())}}if(k.length>0){const C=await Promise.allSettled(k);if(f())return;for(const E of C)E.status==="fulfilled"&&E.value&&h.push(E.value)}}if(!f()){const S=await kd(h);if(f())return;s(S)}}catch(h){console.error("[usePendingDeposit] Verification error:",h),f()||s([])}finally{f()||r(!1)}},[e]);return u.useEffect(()=>{if(!i.current?.enabled){d.current++,s([]),r(!1);return}c({forceDiscovery:!0});const m=i.current?.pollIntervalMs??3e4;if(m<=0||!e)return()=>{d.current++};const p=setInterval(()=>{c({forceDiscovery:!1})},m),f=()=>c({forceDiscovery:!0});return window.addEventListener(Ms,f),()=>{d.current++,window.removeEventListener(Ms,f),clearInterval(p)}},[c,e]),{pendingDeposits:n,loading:o,refresh:()=>c({forceDiscovery:!0})}}function Ad({enabled:e,integratorId:t,depositWalletAddress:n,destinationChainId:s,brand:o,embedFactory:r,onTransactionSuccess:i,onCloseRequest:l}){const d=u.useRef(null),c=u.useRef(null),m=u.useRef(i);m.current=i;const p=u.useRef(l);p.current=l;const f=u.useRef(o);f.current=o;const h=u.useRef(r);h.current=r;const x=u.useCallback((w,S,v)=>{if(!S.isConnected)return;const k=w.getIframe();k.updateConfig({supportedDepositOptions:Ca(v)}),k.sendConfig(),w.showIn(S)},[]);u.useEffect(()=>{if(!e||!n)return;let w=!1;return Promise.resolve().then(()=>{const{dk:S,dark:v,primaryColor:k}=f.current;return(h.current??gd)(yd({integratorId:t,depositWalletAddress:n,destinationChainId:s,source:null,styles:xd(S,v,k)}))}).then(S=>{if(w){S.destroy();return}const v=S.getIframe();v.on("transaction_success",C=>m.current(C)),v.on("close_request",()=>p.current()),d.current=S;const k=c.current;k&&x(S,k.placeholder,k.source)}).catch(S=>{console.error("[useSwapperEmbed] Failed to preload Swapper widget:",S)}),()=>{w=!0,c.current=null,d.current?.destroy(),d.current=null}},[e,t,n,s,x]);const b=u.useCallback((w,S)=>{c.current={placeholder:w,source:S};const v=d.current;v&&x(v,w,S)},[x]),y=u.useCallback(()=>{c.current=null,d.current?.hide()},[]);return{showWidget:b,hideWidget:y}}function Id(e,t,n,s,o){return{address:t,symbol:n||"UNKNOWN",name:n||"Unknown Token",decimals:s||18,chainId:e,balance:0n,balanceFormatted:o?parseFloat(o):0,balanceUsd:0,isNative:A.isNativeToken(t)}}function Ed(e,t){const n=e?.data;if(!n||typeof n!="object")return null;const s=n;if(s.__spiceflowPlaygroundMock!==!0)return null;try{if(typeof s.amountReceivedRaw=="string")return BigInt(s.amountReceivedRaw);if(typeof s.amountReceived=="string"||typeof s.amountReceived=="number")return I.parseUnits(String(s.amountReceived),t)}catch{return null}return null}const Fd=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:s,depositBatches:o,onDepositAmountChange:r,destinationChainId:i,destinationTokenAddress:l,onDepositExecute:d,depositActionLabel:c,sponsorGas:m=!1,escrowRecovery:p,skipTokenSelection:f=!1,onDepositSuccess:h,onDepositError:x,skipRecovery:b=!1})=>{const y=u.useContext(g.SpiceFlowProviderContext);if(!y)return a.jsx("div",{children:"Error: SpiceDeposit must be used within SpiceFlowProvider"});const w=(y.mode||"7702")!="7702",S=w,v=y.nativeChainId,k=y.network||"testnet",{dark:C,dk:E,primaryColor:F}=g.useSpiceBrand(s),B=!!p,j=g.useWallet(),{isReady:T,isAuthenticated:R,actions:D}=j,M=y?.embeddedWalletAddress,{address:P}=pn.useAccount(),q=y?.externalWalletAddress??P,z=!!q,X=hd(y.swapper),N=S?{address:q,kind:"external"}:{address:M,kind:"embedded"},H=md({targetKind:N.kind,appChainId:i||v}),V=X.enabled&&!B&&k==="mainnet"&&!!Os(H),G=()=>f?"deposit":"select-token",J=()=>V?"select-source":S?z?G():"connect-wallet":"provider-login",[U,L]=u.useState(J()),[O,ee]=u.useState(null),[ue,re]=u.useState(!1),[se,ie]=u.useState(null),[ce,_]=u.useState(!1),[Ce,W]=u.useState(null),[ae,he]=u.useState(null),[ne,Q]=u.useState(null),te=u.useRef(null),be=u.useRef(null),{pendingDeposits:$,loading:Se,refresh:ct}=ka(M,{enabled:e,network:k,chainIds:y.supportedChainIds}),[xe,pt]=u.useState(null),[Me,Ue]=u.useState(!1),[Xe,Ae]=u.useState(null),[nt,st]=u.useState(!1),[ft,ot]=u.useState("idle");u.useEffect(()=>{e&&!b&&!B&&!xe&&!nt&&ft==="idle"&&R&&M&&z&&q&&!Se&&$.length>0&&U!=="recovery"&&U!=="deposit"&&U!=="swapper"&&L("recovery")},[e,b,B,R,M,z,q,Se,$,U,xe,nt,ft]);const _e=u.useCallback(pe=>{const Pe={address:pe.tokenAddress,symbol:pe.tokenSymbol,name:pe.tokenSymbol,decimals:pe.tokenDecimals,chainId:pe.chainId,balance:pe.verifiedBalance,balanceFormatted:parseFloat(pe.amount),balanceUsd:0,isNative:pe.isNative};ee(Pe),pt(pe),L("deposit")},[]),Be=u.useCallback(pe=>{if(ie(pe),S){L(z?pe==="wallet"?G():"swapper":"connect-wallet");return}const Pe=R&&!!M;L(pe==="wallet"?Pe?z?G():"connect-wallet":"provider-login":Pe?"swapper":"provider-login")},[S,R,M,z,f]),Ct=u.useCallback(()=>{be.current?.abort(),_(!1),W(null),he(null),ie(null),te.current=null,Q(null),L("select-source")},[]);u.useEffect(()=>{U==="swapper"&&(ne||!N.address||Q({address:N.address,kind:N.kind}))},[U,ne,N.address,N.kind]);const mt=ne??N,Te=mt.address,Ke=mt.kind,Oe=u.useCallback(async pe=>{if(!Te)return;be.current?.abort();const Pe=new AbortController;be.current=Pe,W(null),_(!0);const at=Os(H);if(!at){_(!1);return}const ut=He=>{_(!1);const it=I.formatUnits(He,at.decimals);if(Ke==="external"){he({amount:it,symbol:at.symbol});const Ge={type:"wallet-funding",status:"success",amount:it,asset:at.address,sourceChain:String(H)};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:Ge})),h?.(Ge);return}_e({chainId:H,tokenAddress:at.address,tokenSymbol:at.symbol,tokenDecimals:at.decimals,amount:it,rawAmount:He.toString(),embeddedWalletAddress:Te,externalWalletAddress:"",timestamp:0,isNative:!1,verifiedBalance:He,hasFullBalance:!0})},ve=Ed(pe,at.decimals);if(ve!==null){ut(ve);return}const fe=await bd(Te,te.current??0n,{signal:Pe.signal,chainId:H});if(!Pe.signal.aborted){if(fe===null){_(!1);const He=g.getChainConfig(H)?.viemChain?.name??`chain ${H}`;W(`We haven't seen your funds arrive on ${He} yet \u2014 they may still be in transit.`);return}ut(fe)}},[Te,Ke,H,_e,h]);u.useEffect(()=>{if(U!=="swapper"||!Te||te.current!==null)return;let pe=!1;return va(Te,H).then(Pe=>{pe||(te.current=Pe)}).catch(()=>{pe||(te.current=0n)}),()=>{pe=!0}},[U,Te,H]);const{showWidget:Y,hideWidget:Ee}=Ad({enabled:e&&V,integratorId:X.integratorId,depositWalletAddress:Te,destinationChainId:H,brand:{dk:E,dark:C,primaryColor:F},embedFactory:X.embedFactory,onTransactionSuccess:Oe,onCloseRequest:()=>{ce||Ct()}}),ye=u.useCallback(()=>{st(!0),L(R&&M&&z&&q?f?"deposit":"select-token":R&&M?"connect-wallet":"provider-login")},[R,M,z,q,f]),Re=u.useCallback(()=>{Ae(null),ot("awaiting-disconnect"),L("connect-wallet")},[]),dt=u.useCallback(async pe=>{Ue(!0),Ae(null);try{if(!M)throw new Error("Embedded wallet not available");const Pe=await D.getEthereumProvider(),at=g.getChainConfig(pe.chainId);await g.ensureWalletOnChain(Pe,pe.chainId);const ut=g.getClientForChain(pe.chainId),ve=await on.getBalance(ut,{address:M}),fe=at?.viemChain?.name||`chain ${pe.chainId}`;if(ve===0n)throw new Error(`Your embedded wallet has no ETH on ${fe} to pay for gas. We recommend completing the deposit instead \u2014 it doesn't require gas.`);const He=I.createWalletClient({account:M,transport:I.custom(Pe),chain:at?.viemChain}),it=pe.externalWalletAddress&&I.isAddress(pe.externalWalletAddress)?pe.externalWalletAddress:q;if(!it||!I.isAddress(it))throw new Error("Connect the external wallet that should receive these funds, then try again.");let Ge;pe.isNative||A.isNativeToken(pe.tokenAddress)?Ge=await He.sendTransaction({to:it,value:pe.verifiedBalance,chain:at?.viemChain}):Ge=await He.sendTransaction({to:pe.tokenAddress,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[it,pe.verifiedBalance]}),chain:at?.viemChain}),await ut.waitForTransactionReceipt({hash:Ge,confirmations:1}),Po(pe.embeddedWalletAddress,pe.chainId,pe.tokenAddress),ct(),$.length<=1&&L(J())}catch(Pe){const at=Pe?.message||"Couldn't return your funds. Please try again.",ut=/insufficient funds for gas/i.test(at);Ae(ut?"Not enough ETH in your embedded wallet to cover gas fees. Complete the deposit instead \u2014 it doesn't require gas.":at)}finally{Ue(!1)}},[D,M,q,$,ct]);u.useEffect(()=>{e||(pt(null),Ae(null),Ue(!1),st(!1),ot("idle"),be.current?.abort(),ie(null),_(!1),W(null),he(null),te.current=null,Q(null))},[e]),u.useEffect(()=>{if(ft!=="idle"){if(ft==="awaiting-disconnect"){(!z||!q)&&ot("awaiting-reconnect");return}e&&!Se&&$.length>0&&R&&M&&(ot("idle"),L("recovery"))}},[ft,z,q,e,Se,$,R,M]),u.useEffect(()=>{!B||!e||(R&&M?(re(!0),!O&&p?.chainId&&p?.tokenAddress&&ee(Id(p.chainId,p.tokenAddress,p.tokenSymbol,p.tokenDecimals,p.amount)),L("deposit")):L("provider-login"))},[B,e,U,R,M]);const{assets:Qe,loading:yt}=mn({address:q,supportedChains:y.supportedChainIds,fetchBalances:fn,enabled:e&&!!q,refreshInterval:e?5e3:0}),lt=u.useCallback(()=>{re(!0),L(B?"deposit":se==="card"||se==="exchange"?"swapper":z?f?"deposit":"select-token":"connect-wallet")},[B,se,z,f]),qt=u.useCallback(async()=>{if((!z||!q)&&(await hn(500),!z||!q)){alert("Please connect your wallet first");return}L(f?"deposit":"select-token")},[z,q,f]),Lt=u.useCallback(pe=>{ee(pe),L("deposit")},[]),Nt=u.useCallback(()=>{if(ee(null),r?.(""),!q){L("connect-wallet");return}L("select-token")},[q,r]),Je=u.useCallback(()=>{t()},[t]);if(u.useEffect(()=>{if(!e){const pe=setTimeout(()=>{B||(L(J()),ee(null)),re(!1)},300);return()=>clearTimeout(pe)}},[e,B,p?.chainId]),u.useEffect(()=>{e&&U==="deposit"&&!O&&!B&&!xe&&!f&&L("select-token")},[e,U,O,B,xe,f]),u.useEffect(()=>{if(e&&U==="connect-wallet"&&z&&q&&ft==="idle"){if(V&&!se){L("select-source");return}if(V&&se&&se!=="wallet"){L("swapper");return}L(f?"deposit":"select-token")}},[e,U,z,q,ft,f,V,se]),u.useEffect(()=>{if(!S&&e&&U==="provider-login"&&T&&R&&M&&!ue){const pe=setTimeout(()=>{re(!0),L(se==="card"||se==="exchange"?"swapper":z?f?"deposit":"select-token":"connect-wallet")},100);return()=>clearTimeout(pe)}},[S,e,U,T,R,M,se,z,f,ue]),!e)return null;if(U==="recovery")return a.jsx(ld,{isOpen:e,onClose:Je,closeOnBackdropClick:n,deposits:$,onComplete:_e,onCancel:dt,onSkip:ye,onChangeWallet:Re,isProcessing:Me,error:Xe,styles:s});if(U==="select-source")return V?a.jsx(dd,{isOpen:e,onClose:Je,closeOnBackdropClick:n,onSelect:Be,styles:s}):(L("provider-login"),null);if(U==="swapper")return se!=="card"&&se!=="exchange"?(L(J()),null):Te?a.jsx(ud,{isOpen:e,onClose:Je,onBack:Ct,closeOnBackdropClick:n,source:se,destinationChainId:H,onShowWidget:Y,onHideWidget:Ee,verifying:ce,verifyError:Ce,onRetryVerify:Oe,funded:ae,styles:s}):a.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",zIndex:50},children:a.jsx("div",{style:{backgroundColor:C?E.cardBg:"white",borderRadius:"9px",padding:"32px 24px",maxWidth:"400px",width:"100%",textAlign:"center",fontFamily:'"Helvetica Neue", sans-serif',fontSize:"14px",color:C?E.textPrimary:"#111827"},children:"Preparing your account..."})});if(U==="provider-login"&&!S)return a.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",zIndex:50},children:a.jsx("div",{style:{backgroundColor:C?E.cardBg:"white",borderRadius:"9px",padding:"32px 24px",maxWidth:"400px",width:"100%"},children:a.jsx(Lo,{onAuthSuccess:lt,autoTrigger:!0})})});if(U==="connect-wallet")return a.jsx(gc,{isOpen:e,onClose:Je,closeOnBackdropClick:n,onContinue:qt,requiredChainId:w?v:void 0,styles:s});if(U==="select-token")return q?a.jsx(fc,{isOpen:e,onClose:Je,closeOnBackdropClick:n,onTokenSelect:Lt,walletAddress:q,supportedChainIds:y.supportedChainIds,network:k,prefetchedAssets:yt?null:Qe??null,styles:s,dark:C}):(L("connect-wallet"),null);if(U==="deposit"){if(!O&&!f)return null;const pe=!!xe;return a.jsx(wa,{isOpen:e,onClose:Je,closeOnBackdropClick:n,supportedChains:O?[O.chainId]:y.supportedChainIds??[],styles:s,externalWalletAddress:q,depositBatches:pe?void 0:o,onDepositAmountChange:r,destinationChainId:i,destinationTokenAddress:l,onDepositExecute:d,depositActionLabel:c,nativeChainId:v,sponsorGas:m,preSelectedAsset:O??void 0,escrowOnly:B||pe,escrowTokenAddress:pe?xe.tokenAddress:p?.tokenAddress,escrowAmount:pe?xe.amount:p?.amount,escrowTokenDecimals:pe?xe.tokenDecimals:p?.tokenDecimals,escrowTokenSymbol:pe?xe.tokenSymbol:p?.tokenSymbol,onDepositSuccess:h,onDepositError:x,embeddedWalletAddress:M,onViewAllAssets:f?void 0:Nt})}return null},Td=e=>u.useContext(g.SpiceFlowProviderContext)?a.jsx(Fd,{...e}):a.jsx("div",{children:"Error: SpiceDeposit must be used within SpiceFlowProvider"}),Bd=({isOpen:e,onClose:t,onChainSelect:n,supportedChains:s,closeOnSelect:o=!0,styles:r})=>{const{theme:i,dark:l,primaryColor:d,dk:c}=g.useSpiceBrand(r),[m,p]=u.useState(""),[f,h]=u.useState(null),[x,b]=u.useState(null),[y,w]=u.useState(!1),[S,v]=u.useState(null),{switchChainAsync:k}=pn.useSwitchChain(),C=u.useMemo(()=>new Set(s||[]),[s]),E=u.useMemo(()=>{if(!s||s.length===0)return[];const T=[];return s.forEach((R,D)=>{if(typeof R!="number")return;const M=g.getChainConfig(R);M&&T.push({id:R.toString(),name:M.displayName,icon:Sn[R]||ns,chainId:R,verified:!0,order:D})}),T},[s]);u.useEffect(()=>{f&&!C.has(parseInt(f,10))&&h(null)},[f,C]);const F=u.useMemo(()=>E.filter(T=>T.name.toLowerCase().includes(m.toLowerCase())).sort((T,R)=>T.order-R.order),[E,m]),B=async()=>{if(!f)return;const T=parseInt(f,10);w(!0),v(null);try{await k({chainId:T}),n&&n(f),o&&t()}catch(R){console.error("Failed to switch chain:",R),v(g.sanitizeError(R,"Failed to switch chain."))}finally{w(!1)}},j=!f||y;return a.jsxs(rn,{isOpen:e,onClose:t,title:"Select Chain",styles:r,theme:i,dark:l,children:[a.jsx("div",{style:{padding:"24px 20px"},children:a.jsx(co,{value:m,onChange:p,ariaLabel:"Search chains",placeholder:"Search chain name, symbol or address",size:"md",dark:l,styles:r,endAdornment:a.jsx("div",{style:{padding:"5px 5px",borderRadius:"3px",fontSize:"13px",backgroundColor:l?c.cardBg:"#E9E9E9",color:l?c.textSecondary:"#485066",fontWeight:500,flexShrink:0},"aria-hidden":"true",children:"\u2318F"})})}),a.jsx("div",{style:{padding:"0 32px 20px",display:"flex",flexDirection:"column",gap:"12px"},children:F.map(T=>{const R=f===T.id,D=x===T.id;return a.jsxs("button",{onClick:()=>h(T.id),onMouseEnter:()=>b(T.id),onMouseLeave:()=>b(null),style:{width:"100%",display:"flex",alignItems:"center",gap:"16px",padding:"8px",borderRadius:"8px",backgroundColor:R?l?`${d}15`:`${d}12`:"transparent",border:R?l?`1px solid ${d}66`:`1px solid ${d}88`:D?l?`1px solid ${d}44`:`1px solid ${d}66`:"1px solid transparent",cursor:"pointer",transition:g.transition.interactive},children:[a.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"30px"},children:a.jsx("img",{src:T.icon,alt:T.name,loading:"lazy",decoding:"async",style:{width:"100%",height:"100%",borderRadius:"50%"}})}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",flex:1},children:[a.jsx("span",{style:{fontFamily:g.font.mono,fontSize:"17px",fontWeight:500,letterSpacing:"0.4px",color:c.textPrimary,textAlign:"left"},children:T.name}),T.verified&&a.jsx("img",{src:Qr,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:16,height:16,style:{width:"16px",height:"16px",filter:l?"brightness(0) invert(1)":"none"}})]})]},T.id)})}),S&&a.jsx("div",{style:{padding:"0 25px 12px"},children:a.jsx(yn,{variant:"error",size:"compact",palette:c,children:S})}),a.jsx("div",{style:{padding:"0 25px 25px"},children:a.jsxs(g.Button,{variant:"outline",onClick:B,disabled:j,fullWidth:!0,theme:i,styles:r,dark:l,children:["SELECT",a.jsx(Ol,{size:20})]})})]})},jd={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",84532:"0x4200000000000000000000000000000000000006"},Sa=I.parseAbi(["function deposit() payable","function withdraw(uint256 wad)"]);function Ps(e){return g.getChainConfig(e)?.wrappedNativeTokenAddress??jd[e]}const zo=(e,t)=>({to:e,value:t,data:I.encodeFunctionData({abi:Sa,functionName:"deposit"})}),qo=(e,t)=>({to:e,value:0n,data:I.encodeFunctionData({abi:Sa,functionName:"withdraw",args:[t]})});function Ho(e,t,n){const s=A.isNativeToken(t),o=A.isNativeToken(n);if(!s&&!o)return null;const r=Ps(e);return r?{weth:r,wrapIn:s,unwrapOut:o}:null}function Vo(e,t,n){return A.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[n,t]})}}function Aa(e,t,n,s,o,r){const i=Ho(e,t,n);if(!i||s<=0n)return null;const l=i.wrapIn&&g.addressesEqual(n,i.weth),d=i.unwrapOut&&g.addressesEqual(t,i.weth);return!l&&!d?null:[l?zo(i.weth,s):qo(i.weth,s),...g.addressesEqual(r,o)?[]:[Vo(n,s,o)]]}function Rd(e,t){return{...e,resolve:async(n,s,o)=>{const r=t??o,i=Aa(s,n.tokenIn,n.tokenOut,n.amountIn,o,r);if(i)return{venue:"native-wrap",amountOut:n.amountIn,amountOutMinimum:n.amountIn,calls:i};const l=await e.resolve(n,s,o);if(l)return l;const d=Ho(s,n.tokenIn,n.tokenOut);if(!d)return null;const c=await e.resolve({...n,tokenIn:d.wrapIn?d.weth:n.tokenIn,tokenOut:d.unwrapOut?d.weth:n.tokenOut},s,r);return c?{...c,calls:[...d.wrapIn?[zo(d.weth,n.amountIn)]:[],...c.calls,...d.unwrapOut?[qo(d.weth,c.amountOutMinimum)]:[],...g.addressesEqual(r,o)?[]:[Vo(n.tokenOut,c.amountOutMinimum,o)]]}:null}}}function Dd(e,t){return{...e,resolve:async(n,s,o)=>{const r=t??o,i=Aa(s,n.tokenIn,n.tokenOut,n.amountOut,o,r);if(i)return{venue:"native-wrap",amountIn:n.amountOut,amountInMax:n.amountOut,amountOut:n.amountOut,calls:i};const l=await e.resolve(n,s,o);if(l)return l;const d=Ho(s,n.tokenIn,n.tokenOut);if(!d)return null;const c=await e.resolve({...n,tokenIn:d.wrapIn?d.weth:n.tokenIn,tokenOut:d.unwrapOut?d.weth:n.tokenOut},s,r);return c?{...c,calls:[...d.wrapIn?[zo(d.weth,c.amountInMax)]:[],...c.calls,...d.unwrapOut?[qo(d.weth,c.amountOut)]:[],...g.addressesEqual(r,o)?[]:[Vo(n.tokenOut,c.amountOut,o)]]}:null}}}function Nd(e){return{...e,resolve:async(t,n,s)=>{const o=await e.resolve(t,n,s),r=o?.calls[0]?.to;return!o||!r||A.isNativeToken(t.tokenIn)?o:{...o,calls:[{to:t.tokenIn,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"approve",args:[r,o.amountInMax]})},...o.calls]}}}}function Ws(e){const t=(e?.customVenues??[]).map(s=>Dd(Nd(s),e?.executorAddress));async function n(s,o,r){const i=t.filter(c=>c.chainIds.includes(o));if(i.length===0)throw new g.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const l=(await Promise.allSettled(i.map(async c=>({venue:c,quote:await c.resolve(s,o,r)})))).filter(c=>c.status==="fulfilled").map(c=>c.value).filter(c=>c.quote!==null);if(l.length===0)throw new g.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut.toString()});const d=l.find(c=>c.venue.preferred);return d?d.quote:(l.sort((c,m)=>c.quote.amountIn<m.quote.amountIn?-1:c.quote.amountIn>m.quote.amountIn?1:0),l[0].quote)}return{getQuote:n,venues:t}}const Ia=[100,500,3e3,1e4],Ea=(e,t)=>e.toLowerCase()===t.toLowerCase();function Us(e,t,n,s,o){const r=[];for(const i of n)if(!(Ea(i,e)||Ea(i,t)))for(const l of s)for(const d of s)r.push(o==="in"?I.encodePacked(["address","uint24","address","uint24","address"],[e,l,i,d,t]):I.encodePacked(["address","uint24","address","uint24","address"],[t,d,i,l,e]));return r}function Md(e){const t=e.slice(2),n=[];for(let s=0;s<t.length;){const o=n.length%2===0?40:6;n.push(t.slice(s,s+o)),s+=o}return`0x${n.reverse().join("")}`}const Od=I.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),Pd=I.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),Wd=1800;function Fa(e){const{config:t,route:n,tokenIn:s,tokenOut:o,recipient:r,amountOut:i}=e,l=e.amountInMaximum,d=e.routerHasDeadline?Pd:Od,c=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+Wd)}:{},m=n.path?I.encodeFunctionData({abi:d,functionName:"exactOutput",args:[{path:n.path,recipient:r,...c,amountOut:i,amountInMaximum:l}]}):I.encodeFunctionData({abi:d,functionName:"exactOutputSingle",args:[{tokenIn:s,tokenOut:o,fee:n.fee,recipient:r,...c,amountOut:i,amountInMaximum:l,sqrtPriceLimitX96:0n}]});return{to:t.swapRouter,value:0n,data:m}}const Ud=I.parseAbi(["function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)","function quoteExactOutput(bytes path, uint256 amountOut) returns (uint256 amountIn, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]);async function Ls(e,t,n,s,o){const r=g.getClientForChain(e),{result:i}=await r.simulateContract({address:t.quoterV2,abi:Ud,functionName:o==="in"?"quoteExactInput":"quoteExactOutput",args:[n,s]}),[l,,,d]=i;if(l<=0n)throw new Error("No liquidity along this path.");return{amount:l,gasEstimate:d}}async function Ld(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:o,chainId:r,config:i}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const l=(await g.getClientForChain(r).simulateContract({address:i.quoterV2,abi:A.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:o,sqrtPriceLimitX96:0n}]})).result;if(l[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:l[0],sqrtPriceX96After:l[1],gasEstimate:l[3]}}async function Ta(e){const t=e.feeTiers??Ia,n=Us(e.tokenIn,e.tokenOut,e.hubs??[],t,"in"),s=await Promise.allSettled([...t.map(async r=>({...await Ld({...e,fee:r}),fee:r})),...n.map(async r=>{const i=await Ls(e.chainId,e.config,r,e.amountIn,"in");return{amountOut:i.amount,sqrtPriceX96After:0n,gasEstimate:i.gasEstimate,fee:0,path:r}})]);let o=null;for(const r of s)r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o=r.value);if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const zd=[{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 qd(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:o,chainId:r,config:i}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const l=(await g.getClientForChain(r).simulateContract({address:i.quoterV2,abi:zd,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:o,sqrtPriceLimitX96:0n}]})).result;if(l[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:l[0],sqrtPriceX96After:l[1],gasEstimate:l[3]}}async function Ba(e){const t=e.feeTiers??Ia,n=Us(e.tokenIn,e.tokenOut,e.hubs??[],t,"out"),s=await Promise.allSettled([...t.map(async r=>({...await qd({...e,fee:r}),fee:r})),...n.map(async r=>{const i=await Ls(e.chainId,e.config,r,e.amountOut,"out");return{amountIn:i.amount,sqrtPriceX96After:0n,gasEstimate:i.gasEstimate,fee:0,path:r}})]);let o=null;for(const r of s)r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o=r.value);if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const ja=3,Ra=8,Hd=30,Vd=[{name:"quoteExactInput",stateMutability:"nonpayable",inputs:[{name:"path",type:"bytes"},{name:"amountInRequired",type:"uint256"}],outputs:[{name:"amountOutList",type:"uint256[]"},{name:"amountInList",type:"uint256[]"},{name:"sqrtPriceX96AfterList",type:"uint160[]"},{name:"initializedTicksCrossedList",type:"uint32[]"},{name:"gasEstimate",type:"uint256"},{name:"feeList",type:"uint16[]"}],type:"function"}],Qd=[{name:"exactInput",stateMutability:"payable",inputs:[{name:"params",type:"tuple",components:[{name:"path",type:"bytes"},{name:"recipient",type:"address"},{name:"deadline",type:"uint256"},{name:"amountIn",type:"uint256"},{name:"amountOutMinimum",type:"uint256"}]}],outputs:[{name:"amountOut",type:"uint256"}],type:"function"}];function Da(e){const{tokens:t,deployers:n}=e;if(t.length<2||n.length!==t.length-1)throw new Error("Invalid Algebra path");const s=[];for(let o=0;o<t.length;o++)s.push(I.pad(t[o],{size:20})),o<n.length&&s.push(I.pad(n[o],{size:20}));return I.concat(s)}async function Kd(e,t){const n=t.toLowerCase(),s=`{ pools(first: 500, where: { or: [ { token0: "${n}" }, { token1: "${n}" } ] }) { deployer token0 { id } token1 { id } } }`,o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:s})});if(!o.ok)throw new Error(`Algebra subgraph returned ${o.status}`);const r=await o.json();if(r.errors||!r.data?.pools)throw new Error("Algebra subgraph query failed");const i=new Map;for(const l of r.data.pools){const d=l.token0.id.toLowerCase(),c=l.token1.id.toLowerCase(),m={token:d===n?c:d,deployer:l.deployer.toLowerCase()};i.set(`${m.token}:${m.deployer}`,m)}return Array.from(i.values())}async function Yd(e,t,n){const s=t.toLowerCase(),o=n.toLowerCase(),r=new Map,i=async c=>{const m=r.get(c);if(m)return m;if(r.size>=Hd)return[];const p=await Kd(e,c);return r.set(c,p),p},l=[],d=[{tokens:[s],deployers:[]}];for(;d.length>0&&l.length<Ra;){const c=d.shift();if(c.tokens.length-1>=ja)continue;const m=c.tokens[c.tokens.length-1];for(const p of await i(m)){if(c.tokens.includes(p.token))continue;const f={tokens:[...c.tokens,p.token],deployers:[...c.deployers,p.deployer]};if(p.token===o){if(l.push(f),l.length>=Ra)break}else c.tokens.length-1<ja-1&&d.push(f)}}return l}async function Gd(e,t,n,s){const o=g.getClientForChain(t),{result:r}=await o.simulateContract({address:e,abi:Vd,functionName:"quoteExactInput",args:[Da(n),s]}),i=r[0],l=i[i.length-1]??0n;if(l<=0n)throw new Error("Algebra quote returned zero output");return l}async function Zd(e){const{tokenIn:t,tokenOut:n,amountIn:s,chainId:o,config:r}=e,i=await Yd(r.subgraphUrl,t,n),l=await Promise.allSettled(i.map(async c=>({path:c,amountOut:await Gd(r.quoterV2,o,c,s)})));let d=null;for(const c of l)c.status==="fulfilled"&&(!d||c.value.amountOut>d.amountOut)&&(d=c.value);return d}function Xd(e){return e.type==="swap"}const Qn=.02,Jd=[1,8453,42161,10,137,43114,56],Na="https://api.1inch.dev/swap/v6.0";function zs(e,t){return A.applySlippage(e,t)}function $d(e){const t=e?.baseUrl??Na;return{name:"1inch",chainIds:e?.chainIds??Jd,resolve:async(n,s,o)=>{const r=n.maxSlippage??Qn,i=r*100,l=A.isNativeToken(n.tokenIn)?A.NATIVE_TOKEN_ADDRESS:n.tokenIn,d=A.isNativeToken(n.tokenOut)?A.NATIVE_TOKEN_ADDRESS:n.tokenOut,c=A.isNativeToken(n.tokenIn);try{const m=new URL(`${t}/${s}/swap`);m.searchParams.set("src",l),m.searchParams.set("dst",d),m.searchParams.set("amount",n.amountIn.toString()),m.searchParams.set("from",o),m.searchParams.set("slippage",i.toString()),m.searchParams.set("disableEstimate","true"),m.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const f=await fetch(m.toString(),{headers:p});if(!f.ok)throw new g.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${f.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${f.status}`});const h=await f.json();if(!h.dstAmount||!h.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const x=BigInt(h.dstAmount);if(x<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const b=zs(x,r),y=[];return h.tx.to&&!c&&y.push({to:n.tokenIn,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"approve",args:[h.tx.to,n.amountIn]})}),y.push({to:h.tx.to,value:BigInt(h.tx.value||"0"),data:h.tx.data}),{venue:"1inch",amountOut:x,amountOutMinimum:b,calls:y}}catch(m){if(m instanceof g.SpiceflowError)throw m;const p=m instanceof Error?m.message:String(m);throw new g.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${p}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:p})}}}}const Ma=[4114,5115],Qo={name:"Satsuma",swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},_d={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[1],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]},Oa={name:"Uniswap v3",swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Pa={name:"Uniswap v3",swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Wa={name:"SushiSwap",swapRouter:"0x1e406484F1F204b23cE84B9901C0171a738fd406",quoterV2:"0x3E290e5E01818002A0b672148BdC7514D861C7B3",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"],routerHasDeadline:!0},eu=I.parseAbi(["function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),tu=I.parseAbi(["function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),nu=I.parseAbi(["function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),Ua=1800,La=[1,50,100,200,2e3],Ko={name:"Aerodrome",swapRouter:"0xcbBb8035cAc7D4B3Ca7aBb74cF7BdF900215Ce0D",quoterV2:"0x3d4C22254F86f64B7eC90ab8F7aeC1FBFD271c6C",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]};function Yo(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??La;return{name:t,chainIds:n,resolve:async(o,r,i)=>{if(A.isNativeToken(o.tokenIn)||A.isNativeToken(o.tokenOut))return null;const l=o.maxSlippage??Qn,d=[...s.map(y=>I.encodePacked(["address","uint24","address"],[o.tokenIn,y,o.tokenOut])),...Us(o.tokenIn,o.tokenOut,e.hubCurrencies??[],s,"in")],c={quoterV2:e.quoterV2},m=await Promise.allSettled(d.map(async y=>({path:y,amountOut:(await Ls(r,c,y,o.amountIn,"in")).amount})));let p=null;for(const y of m)y.status==="fulfilled"&&(!p||y.value.amountOut>p.amountOut)&&(p=y.value);if(!p)return console.warn(`[AerodromeVenue] No viable route for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}.`),null;const f=zs(p.amountOut,l),h=BigInt(Math.floor(Date.now()/1e3)+Ua),x=I.encodeFunctionData({abi:tu,functionName:"exactInput",args:[{path:p.path,recipient:i,deadline:h,amountIn:o.amountIn,amountOutMinimum:f}]}),b=[{to:o.tokenIn,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"approve",args:[e.swapRouter,o.amountIn]})},{to:e.swapRouter,value:0n,data:x}];return{venue:t,amountOut:p.amountOut,amountOutMinimum:f,calls:b}}}}function za(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??La;return{name:t,chainIds:n,resolve:async(o,r,i)=>{if(A.isNativeToken(o.tokenIn)||A.isNativeToken(o.tokenOut))return null;const l=o.maxSlippage??Qn,d=[...s.map(b=>I.encodePacked(["address","uint24","address"],[o.tokenOut,b,o.tokenIn])),...Us(o.tokenIn,o.tokenOut,e.hubCurrencies??[],s,"out")],c={quoterV2:e.quoterV2},m=await Promise.allSettled(d.map(async b=>({path:b,amountIn:(await Ls(r,c,b,o.amountOut,"out")).amount})));let p=null;for(const b of m)b.status==="fulfilled"&&(!p||b.value.amountIn<p.amountIn)&&(p=b.value);if(!p)return console.warn(`[AerodromeExactOutputVenue] No viable route for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}.`),null;const f=BigInt(Math.round(l*1e4)),h=p.amountIn+p.amountIn*f/10000n,x=BigInt(Math.floor(Date.now()/1e3)+Ua);return{venue:t,amountIn:p.amountIn,amountInMax:h,amountOut:o.amountOut,calls:[{to:e.swapRouter,value:0n,data:I.encodeFunctionData({abi:nu,functionName:"exactOutput",args:[{path:p.path,recipient:i,deadline:x,amountOut:o.amountOut,amountInMaximum:h}]})}]}}}}function us(e){const t=e.name??"Uniswap v3",n=e.chainIds??Ma;return{name:t,chainIds:n,resolve:async(s,o,r)=>{if(A.isNativeToken(s.tokenIn)||A.isNativeToken(s.tokenOut))return null;const i=s.maxSlippage??Qn;let l;try{l=await Ta({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn,chainId:o,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:e.hubCurrencies})}catch{return console.warn(`[UniV3Venue] No viable route for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}.`),null}const d=zs(l.amountOut,i),c=l.path?I.encodeFunctionData({abi:eu,functionName:"exactInput",args:[{path:l.path,recipient:r,amountIn:s.amountIn,amountOutMinimum:d}]}):I.encodeFunctionData({abi:A.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:l.fee,recipient:r,amountIn:s.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]}),m=[{to:s.tokenIn,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"approve",args:[e.swapRouter,s.amountIn]})},{to:e.swapRouter,value:0n,data:c}];return{venue:t,amountOut:l.amountOut,amountOutMinimum:d,calls:m}}}}function Go(e){const t=e.name??"Uniswap v3",n=e.chainIds??Ma;return{name:t,chainIds:n,resolve:async(s,o,r)=>{if(A.isNativeToken(s.tokenIn)||A.isNativeToken(s.tokenOut))return null;const i=s.maxSlippage??Qn;let l;try{l=await Ba({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut,chainId:o,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:e.hubCurrencies})}catch{return null}const d=BigInt(Math.round(i*1e4)),c=l.amountIn+l.amountIn*d/10000n;return{venue:t,amountIn:l.amountIn,amountInMax:c,amountOut:s.amountOut,calls:[Fa({config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},routerHasDeadline:e.routerHasDeadline,route:l,tokenIn:s.tokenIn,tokenOut:s.tokenOut,recipient:r,amountOut:s.amountOut,amountInMaximum:c})]}}}}const su=[4114],ou={swapRouter:"0x3012E9049d05B4B5369D690114D5A5861EbB85cb",quoterV2:"0xa77aD9f635a3FB3bCCC5E6d1A87cB269746Aba17",subgraphUrl:"https://api.goldsky.com/api/public/project_cmamb6kkls0v2010932jjhxj4/subgraphs/analytics-mainnet/v1.0.1/gn",maxSlippage:.005};function qa(e){return{name:"algebra",chainIds:e.chainIds??su,resolve:async(t,n,s)=>{const o=A.isNativeToken(t.tokenIn),r=await Zd({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:e}).catch(()=>null);if(!r)return null;const i=zs(r.amountOut,t.maxSlippage??e.maxSlippage??Qn),l=[];return o||l.push({to:t.tokenIn,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),l.push({to:e.swapRouter,value:o?t.amountIn:0n,data:I.encodeFunctionData({abi:Qd,functionName:"exactInput",args:[{path:Da(r.path),recipient:s,deadline:I.maxUint256,amountIn:t.amountIn,amountOutMinimum:i}]})}),{venue:"algebra",amountOut:r.amountOut,amountOutMinimum:i,calls:l}}}}function Zo(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.algebra&&t.push(qa(e.algebra)),e?.satsuma&&t.push(us(e.satsuma)),e?.aerodrome!==!1&&t.push(Yo(e?.aerodrome??Ko));let n=!1;if(e?.oneInch?.baseUrl)try{const l=new URL(e.oneInch.baseUrl);n=["http:","https:"].includes(l.protocol)&&l.hostname!==new URL(Na).hostname}catch{}(e?.oneInch?.apiKey?.trim()||n)&&t.push($d(e?.oneInch));const s=t.map(l=>Rd(l,e?.executorAddress));function o(l){return s.find(d=>d.chainIds.includes(l))}async function r(l,d,c){const m=s.filter(x=>x.chainIds.includes(d));if(m.length===0)throw new g.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${d}. Cannot resolve swap ${l.tokenIn} \u2192 ${l.tokenOut}.`,{chainId:d,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});const p=await Promise.allSettled(m.map(x=>x.resolve(l,d,c)));let f=null;for(const x of p)x.status==="fulfilled"&&x.value&&(!f||x.value.amountOut>f.amountOut)&&(f=x.value);if(f)return f;const h=p.find(x=>x.status==="rejected");if(h)throw h.reason;return null}async function i(l,d,c){const m=[],p=[];for(const f of l){if(!Xd(f)){m.push(f);continue}const h=await r(f,d,c);if(!h)throw new g.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${f.tokenIn} \u2192 ${f.tokenOut} on chain ${d}.`,{chainId:d,tokenIn:f.tokenIn,tokenOut:f.tokenOut,amountIn:f.amountIn.toString()});m.push(...h.calls),p.push(h)}return{calls:m,resolvedSwaps:p}}return{resolveSwapIntents:i,resolveSwap:r,getVenueForChain:o,venues:t}}const cn="0x0000000000000000000000000000000000000000",Xo=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],Ha=cn,Va=.02,ru=1800,Qa={name:"Uniswap v4",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",cn,"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Ka={name:"Uniswap v4",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",cn,"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Ya=I.parseAbi(["struct PoolKey { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }","struct PathKey { address intermediateCurrency; uint24 fee; int24 tickSpacing; address hooks; bytes hookData; }","struct QuoteExactSingleParams { PoolKey poolKey; bool zeroForOne; uint128 exactAmount; bytes hookData; }","struct QuoteExactParams { address exactCurrency; PathKey[] path; uint128 exactAmount; }","function quoteExactInputSingle(QuoteExactSingleParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactInput(QuoteExactParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(QuoteExactSingleParams params) returns (uint256 amountIn, uint256 gasEstimate)","function quoteExactOutput(QuoteExactParams params) returns (uint256 amountIn, uint256 gasEstimate)"]),au=I.parseAbi(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),iu=I.parseAbi(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),Ga="0x10",lu="04",cu="06",du="07",uu="08",pu="09",qs="0c",Hs="0e",fu=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],mu=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],wn=(e,t)=>e.toLowerCase()===t.toLowerCase();function Vs(e){return A.isNativeToken(e)?cn:e}function hu(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function Za(e,t,n,s,o){const r=[],[i,l]=hu(e,t);for(const{fee:c,tickSpacing:m}of Xo)r.push({kind:"single",poolKey:{currency0:i,currency1:l,fee:c,tickSpacing:m,hooks:Ha},zeroForOne:wn(e,i)});const d=(c,m)=>!!o&&(wn(c,cn)&&wn(m,o)||wn(c,o)&&wn(m,cn));for(const c of n)if(!(wn(c,e)||wn(c,t))&&!(d(c,e)||d(c,t)))for(const m of Xo)for(const p of Xo){const f=(h,x)=>({intermediateCurrency:h,fee:x.fee,tickSpacing:x.tickSpacing,hooks:Ha,hookData:"0x"});r.push({kind:"multi",path:s==="in"?[f(c,m),f(t,p)]:[f(e,m),f(c,p)]})}return r}async function Xa(e,t,n,s,o,r){const i=g.getClientForChain(e),l=(await Promise.allSettled(n.map(async d=>{const{result:c}=d.kind==="single"?await i.simulateContract({address:t.quoter,abi:Ya,functionName:r==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:d.poolKey,zeroForOne:d.zeroForOne,exactAmount:o,hookData:"0x"}]}):await i.simulateContract({address:t.quoter,abi:Ya,functionName:r==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:s,path:d.path,exactAmount:o}]}),m=c[0];if(m<=0n)throw new Error("zero quote");return{candidate:d,amount:m}}))).filter(d=>d.status==="fulfilled").map(d=>d.value);return l.length===0?null:(l.sort((d,c)=>d.amount<c.amount?-1:d.amount>c.amount?1:0),r==="in"?l[l.length-1]:l[0])}function Ja(e){const{candidate:t,direction:n,currencyIn:s,currencyOut:o,recipient:r,exactAmount:i,limitAmount:l,deadline:d,sweepNativeTo:c}=e;let m,p;t.kind==="single"?(m=n==="in"?`0x${cu}${qs}${Hs}`:`0x${uu}${qs}${Hs}`,p=I.encodeAbiParameters([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:fu},{name:"zeroForOne",type:"bool"},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"},{name:"hookData",type:"bytes"}]}],[{poolKey:t.poolKey,zeroForOne:t.zeroForOne,[n==="in"?"amountIn":"amountOut"]:i,[n==="in"?"amountOutMinimum":"amountInMaximum"]:l,hookData:"0x"}])):(m=n==="in"?`0x${du}${qs}${Hs}`:`0x${pu}${qs}${Hs}`,p=I.encodeAbiParameters([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:mu},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"}]}],[{[n==="in"?"currencyIn":"currencyOut"]:n==="in"?s:o,path:t.path,[n==="in"?"amountIn":"amountOut"]:i,[n==="in"?"amountOutMinimum":"amountInMaximum"]:l}]));const f=I.encodeAbiParameters([{type:"address"},{type:"uint256"}],[s,n==="in"?i:l]),h=I.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[o,r,0n]),x=I.encodeAbiParameters([{type:"bytes"},{type:"bytes[]"}],[m,[p,f,h]]),b=c?`${Ga}${lu}`:Ga,y=c?[x,I.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[cn,c,0n])]:[x];return I.encodeFunctionData({abi:iu,functionName:"execute",args:[b,y,d]})}function $a(){return BigInt(Math.floor(Date.now()/1e3)+ru)}function _a(e,t,n,s){return{to:e.permit2,value:0n,data:I.encodeFunctionData({abi:au,functionName:"approve",args:[t,e.universalRouter,n,Number(s)]})}}function ei(e){const t=e.name??"Uniswap v4",n=e.v3?us({...e.v3,chainIds:e.chainIds}):null;return{name:t,chainIds:e.chainIds,resolve:async(s,o,r)=>{const i=s.maxSlippage??Va,l=Vs(s.tokenIn),d=Vs(s.tokenOut),c=A.isNativeToken(s.tokenIn),m=e.hubCurrencies??[cn];let p=null;if(!wn(l,d)&&s.amountIn>0n){const f=await Xa(o,e,Za(l,d,m,"in",Ps(o)),l,s.amountIn,"in").catch(()=>null);if(f){const h=A.applySlippage(f.amount,i),x=$a(),b=[];c||(b.push({to:s.tokenIn,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"approve",args:[e.permit2,s.amountIn]})}),b.push(_a(e,s.tokenIn,s.amountIn,x))),b.push({to:e.universalRouter,value:c?s.amountIn:0n,data:Ja({candidate:f.candidate,direction:"in",currencyIn:l,currencyOut:d,recipient:r,exactAmount:s.amountIn,limitAmount:h,deadline:x})}),p={venue:t,amountOut:f.amount,amountOutMinimum:h,calls:b}}}return!p&&n?n.resolve(s,o,r):p}}}function ti(e){const t=e.name??"Uniswap v4";return{name:t,chainIds:e.chainIds,resolve:async(n,s,o)=>{const r=A.isNativeToken(n.tokenIn),i=Vs(n.tokenIn),l=Vs(n.tokenOut);if(wn(i,l)||n.amountOut<=0n)return null;const d=n.maxSlippage??Va,c=e.hubCurrencies??[cn],m=await Xa(s,e,Za(i,l,c,"out",Ps(s)),l,n.amountOut,"out").catch(()=>null);if(!m)return null;const p=BigInt(Math.round(d*1e4)),f=m.amount+m.amount*p/10000n,h=$a();return{venue:t,amountIn:m.amount,amountInMax:f,amountOut:n.amountOut,calls:[...r?[]:[_a(e,n.tokenIn,f,h)],{to:e.universalRouter,value:r?f:0n,data:Ja({candidate:m.candidate,direction:"out",currencyIn:i,currencyOut:l,recipient:o,exactAmount:n.amountOut,limitAmount:f,deadline:h,sweepNativeTo:r?o:void 0})}]}}}}const ni=[{..._d,protocol:"uniswap-v3",chainId:1},{...Qo,protocol:"uniswap-v3",chainId:4114},{...Qo,protocol:"uniswap-v3",chainId:5115},{...Oa,protocol:"uniswap-v3",chainId:8453},{...Pa,protocol:"uniswap-v3",chainId:4663},{...Wa,protocol:"uniswap-v3",chainId:4663},{...Qa,protocol:"uniswap-v4",chainId:8453},{...Ka,protocol:"uniswap-v4",chainId:4663},{...Ko,protocol:"aerodrome-slipstream",chainId:8453}];function Kn(e){const t=e?.includeDefaults===!1?e.venues??[]:[...ni,...e?.venues??[]],n=[],s=[];for(const o of t){const r=[o.chainId];switch(o.protocol){case"uniswap-v3":{const i={...o,chainIds:r};n.push(us(i)),s.push(Go(i));break}case"uniswap-v4":{const i={...o,chainIds:r};n.push(ei(i)),s.push(ti(i));break}case"aerodrome-slipstream":{const i={...o,chainIds:r};n.push(Yo(i)),s.push(za(i));break}default:{const i=o;throw new g.SpiceflowError("INVALID_PARAMS",`Unsupported liquidity venue protocol: ${i.protocol}`,{protocol:i.protocol})}}}return{input:n,output:s}}function Bt(e,t,n,s){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return s==="ceil"?(e+o-1n)/o:e/o}const gu="0xa9059cbb";function si(e,t,n){return A.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[n,t]})}}function Qs(e,t,n){return{chainId:n,calls:[si(e,t,A.getEscrowContractAddress(n))]}}function en(e,t){if(!e||e._source!=="wallet")return!1;const n=e._fundingWallet;return n==="external"||t&&n!=="embedded"}function oi(e,t,n){return e?.asset._source==="wallet"&&!en(e.asset,t)}function ri(e){return e.isNative||A.isNativeToken(e.address)?!0:!A.getTokenByAddress(e.address,e.chainId)}function ai(e,t,n,s){const o=l=>A.isNativeToken(s)?l.data==="0x"&&l.value>0n&&[A.SPICE_GAS_FEE_RECIPIENT,A.SPICE_PLATFORM_FEE_RECIPIENT].some(d=>g.addressesEqual(l.to,d)):g.addressesEqual(l.to,s)&&l.data.startsWith(gu);if(t!=="user-transfer"||!n||e.length===0||!o(e[0]))return{feeCalls:[],remainingCalls:e};const r=e.findIndex(l=>!o(l)),i=r===-1?e.length:r;return{feeCalls:e.slice(0,i),remainingCalls:e.slice(i)}}async function Ks(e,t,n,s){if(!t)return[e];const o=await t({...n,requestTimestampMs:s});return o?[o,e]:[e]}function Ys(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:A.normalizeNativeTokenAddress(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function Kt(e,t,n){return Bt(e,t,n,"ceil")}async function Yn(e,t,n){if(e.chainId!==t.chainId&&!Ss(e,n,t.chainId)&&!Dn(e,t.chainId).some(s=>g.addressesEqual(s,n)))throw new Error("No supported bridge route for this source asset");return g.addressesEqual(n,t.address)?t.decimals:e.chainId===t.chainId&&g.addressesEqual(n,e.address)?e.decimals:g.getTokenDecimals(t.chainId,n)}async function ii(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:o,providerEmbeddedAddress:r,address:i,isNon7702:l,isPayMode:d,resolvedChainId:c,buildActionCalls:m,feeExecutionMode:p,buildSpicenetBatch:f,selectedAsset:h,needsSwap:x,exactOutputSwap:b,resolvedTokenIn:y,requestTimestampMs:w}=e,S=t?.fundingTokenOverride??y,v=I.parseUnits(n,s.decimals),k=e.feeOnlyAction?0n:t?.actionAmountOverride??v,C=!!e.feeOnlyAction&&(t?.fundingAmountOverride??0n)>0n;if(C&&h?.asset._source==="wallet"&&h.asset.chainId===c&&!A.isNativeToken(h.asset.address)&&!A.getTokenByAddress(h.asset.address,c))throw new Error("Choose a registered token or native asset to fund action fees");const E=o||r||(l?void 0:i);if(!E)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const F={userAddress:E,executorAddress:E,outputRecipient:!e.feeOnlyAction&&x&&b?e.swapOutputRecipient??E:void 0,chainId:c,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??v,netAmount:k,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},B=await m(k,F),j={chainId:c,calls:B},T=!d&&!l?!0:h?.asset._source==="spice",R=oi(h??null,l);if(e.feeOnlyAction&&t?.fundingTokenOverride&&R&&h?.asset.chainId===c&&g.addressesEqual(t.fundingTokenOverride,h.asset.address))return[j];const D=C||T||en(h?.asset,l)&&h?.asset.chainId!==c||R&&!!h&&(h.asset.chainId!==c||!ri(h.asset)),M=(X,N)=>({token:A.normalizeNativeTokenAddress(X),from:"escrow",to:E,amount:N}),P=(X,N)=>R||en(h?.asset,l)&&(h?.asset.chainId!==c||C)?[Qs(h.asset.address,t?.sourceFundingAmountOverride??Kt(X,z,h.asset.decimals),h.asset.chainId),...N]:N;if(v===0n&&!C)return[j];const q=S??(h?Qt(h.asset,c):null)??s.address,z=h?await Yn(h.asset,s,q):s.decimals;if(!e.feeOnlyAction&&x&&b){const X=S??Qt(h.asset,c)??h.asset.address,N=t?.fundingAmountOverride??b.amountInMax,H=D?[M(X,N)]:[],V={chainId:c,calls:[...b.calls,...B],tokenTransfers:[...H,...j.tokenTransfers??[]]};if(!D)return[V];const G=await Ks(V,f,{userAddress:E,destinationChainId:c,deliveryToken:X,deliveryAmount:N,deliveryRecipient:E,deliveryTransfers:Ys(V),sourceAsset:h.asset},w);return P(N,G)}if(D){const X=S??(h?Qt(h.asset,c):null)??s.address;if(!C&&R&&h?.asset.chainId===c&&X.toLowerCase()===s.address.toLowerCase())return[j];const N=t?.fundingAmountOverride??v,H={...j,tokenTransfers:[M(X,N),...j.tokenTransfers??[]]},V=await Ks(H,f,{userAddress:E,destinationChainId:c,deliveryToken:X,deliveryAmount:N,deliveryRecipient:E,deliveryTransfers:Ys(H),sourceAsset:h?.asset},w);return P(N,V)}return[j]}async function li(e,t){const{selectedAsset:n,embeddedWalletAddress:s,externalWalletAddress:o,recipient:r,resolvedChainId:i,destinationToken:l,buildActionCalls:d,feeExecutionMode:c,buildSpicenetBatch:m,isPayMode:p,isNon7702:f,needsSwap:h,resolvedSwap:x,quoteAmountOut:b,resolvedTokenIn:y,requestTimestampMs:w}=e,S=x?.amountOutMinimum??b;if(!n?.asset||!s)return[];const v=r??(f?o:s);if(!v)return[];const k=I.parseUnits(n.amount,n.asset.decimals),C=y??Qt(n.asset,i)??l.address,E=await Yn(n.asset,l,C),F=t?.fundingAmountOverride??Bt(k,n.asset.decimals,E,"floor");if(F<=0n)throw new Error("Amount is below the destination token's precision");const B=t?.fundingAmountOverride??F,j=t?.sourceFundingAmountOverride??(t?.fundingAmountOverride===void 0?k:Kt(B,E,n.asset.decimals)),T=t?.deliveryAmountOverride??B,R=t?.withdrawalAmountOverride??T,D=t?.actionAmountOverride??F,M=t?.actionContextOverride?.feeBreakdown;if(e.isFeeInclusiveInput&&h&&e.swapInputAmount!=null&&M){const ee=Bt(k,n.asset.decimals,E,"floor");if(e.swapInputAmount+M.gasFee+M.spicenetFee+M.bridgeFee>ee)throw new Error("Swap input plus fees exceeds the entered amount. Refresh the quote before retrying.")}const P={userAddress:v,executorAddress:s,outputRecipient:h&&x?e.swapOutputRecipient??s:void 0,chainId:i,destinationToken:l.address,feeToken:c==="user-transfer"&&h&&y?y:l.address,grossAmount:B,netAmount:D,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},q=()=>d(D,P),z=n.asset._source==="wallet",X=n.asset._fundingWallet,N=z&&(X==="external"||f&&X!=="embedded");if(!p&&z&&n.asset.chainId===i&&(f||X==="external"||ri(n.asset))){if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!x||S===null)throw new Error("Swap quote not available yet")}if(h&&x&&S){const ee=await d(t?.actionAmountOverride??S,{...P,netAmount:t?.actionAmountOverride??S}),{feeCalls:ue,remainingCalls:re}=ai(ee,c,h,P.feeToken);return[{chainId:i,calls:[...ue,...x.calls,...re]}]}return[{chainId:i,calls:await q()}]}const H=!p&&!f?n.asset._source!=="wallet":n.asset._source==="spice",V=oi(n,f);if(!(H||N||V))return[{chainId:i,calls:await q()}];const G=V?Qs(A.normalizeNativeTokenAddress(n.asset.address),j,n.asset.chainId):N&&n.asset.chainId!==i?{chainId:n.asset.chainId,calls:[si(A.normalizeNativeTokenAddress(n.asset.address),j,A.getEscrowContractAddress(n.asset.chainId))]}:null,J=(ee,ue)=>({token:A.normalizeNativeTokenAddress(ee),from:"escrow",to:s,amount:ue});if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!x||S===null)throw new Error("Swap quote not available yet")}if(h&&x&&S&&y){const ee=await d(t?.actionAmountOverride??S,{...P,netAmount:t?.actionAmountOverride??S}),{feeCalls:ue,remainingCalls:re}=ai(ee,c,h,P.feeToken),se={chainId:i,calls:[...ue,...x.calls,...re],tokenTransfers:[J(y,T)]},ie=await Ks(se,m,{userAddress:s,destinationChainId:i,deliveryToken:y,deliveryAmount:T,withdrawalAmount:R,deliveryRecipient:s,deliveryTransfers:Ys(se),sourceAsset:n.asset},w);return G?[G,...ie]:ie}const U=y??Qt(n.asset,i)??l.address,L={chainId:i,calls:await q(),tokenTransfers:[J(U,T)]},O=await Ks(L,m,{userAddress:s,destinationChainId:i,deliveryToken:U,deliveryAmount:T,withdrawalAmount:R,deliveryRecipient:s,deliveryTransfers:Ys(L),sourceAsset:n.asset},w);return G?[G,...O]:O}async function xu(e,t,n,s,o){let r=e;for(let i=0;i<4;i++){const l=await t(r),d=await s(l,n,r,o),c=Pc(d);if(c===null||c>=e)return r;const m=r-c,p=e+m;if(p<=r)return r;r=p}return r}function ci(e,t){return e._source!=="wallet"||e.chainId!==t?!1:e.isNative||A.isNativeToken(e.address)||!A.getTokenByAddress(e.address,e.chainId)}function yu(e,t){const n=e[0];if(e.length!==1||!n||n.chainId!==t.chainId||n.domain==="spicenet"||n.tokenTransfers?.length||n.calls.length===0)throw new Error("SpiceLock requires one lock-chain action batch. Return only lock approval and action calls, without funding transfers.");if(t.amountIn<=0n)throw new Error("Enter a positive amount to lock.");if(t.swap&&(t.swap.amountOutMinimum<=0n||t.swap.amountOutMinimum>t.swap.amountOut||t.swap.calls.length===0))throw new Error("A valid swap quote is required before locking. Please retry.");return[{...n,calls:[...t.swap?.calls??[],...n.calls],...t.escrowFunded?{tokenTransfers:[{token:A.normalizeNativeTokenAddress(t.tokenIn),from:"escrow",to:t.recipient,amount:t.amountIn}]}:{}}]}function bu(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=I.getAddress(n.token),o=I.getAddress(n.to),r=`${s.toLowerCase()}:${o.toLowerCase()}`,i=t.get(r);i?i.amount+=n.amount:t.set(r,{token:s,to:o,amount:n.amount})}return[...t.values()]}function wu(e,t){return`0x${t}${e.slice(4)}`}function di(e,t){return ui(e,t)}function ui(e,t,n){const s=Es(t,e),o=Math.floor(Date.now()/1e3)+60*10,r=A.hashChainBatches(s);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:o,chainBatches:r.map((i,l)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:s[l].domain==="spicenet"?[]:s[l].tokenTransfers??[],calls:i.calls}))}]}}function Gn(e,t,n,s){if(e.some(m=>m.domain==="spicenet"))return e;const o=n?.intents.flatMap(m=>m.batches),r=m=>m.from==="escrow",i=e.map(m=>{const p=o?.find(F=>F.chainId===m.chainId);if(!p)return m;const f=an(p),h=f.totalFee;if(h<=0n)return m;const x=(m.tokenTransfers??[]).filter(F=>r(F)&&I.getAddress(F.to).toLowerCase()===t.toLowerCase()),b=x.find(F=>!A.isNativeToken(I.getAddress(F.token)))??x[0];if(!b)return m;const y=I.getAddress(b.token),w=A.isNativeToken(y);let S=!1;const v=(m.tokenTransfers??[]).map(F=>S||!r(F)||I.getAddress(F.to).toLowerCase()!==t.toLowerCase()||I.getAddress(F.token).toLowerCase()!==y.toLowerCase()?F:(S=!0,{...F,amount:s?.payoutAlreadyGross?BigInt(F.amount):BigInt(F.amount)+h}));if(!S)return m;const k=(F,B)=>w?{to:F,value:B,data:"0x"}:{to:y,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[F,B]})},C=[];f.spicenetFee>0n&&C.push(k(A.SPICE_PLATFORM_FEE_RECIPIENT,f.spicenetFee));const E=f.gasFee+f.bridgeFee;return E>0n&&C.push(k(A.SPICE_GAS_FEE_RECIPIENT,E)),{...m,tokenTransfers:v,calls:[...C,...m.calls]}}),l=i.flatMap(m=>(m.tokenTransfers??[]).filter(r).map(p=>{const f=I.getAddress(p.token),h=I.getAddress(p.to),x=[{token:f,to:h,amount:BigInt(p.amount)}];return{chainId:m.chainId,transfers:bu(x)}}));if(l.length===0)return e;const d=s?.requestTimestampMs??Date.now(),c=BigInt(Math.floor(d/1e3))+3600n;return[{chainId:A.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:l.map((m,p)=>{const f=I.keccak256(I.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,m.transfers[0].token,m.transfers.reduce((x,b)=>x+b.amount,0n),BigInt(m.chainId),BigInt(d+p)])),h=wu(f,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:I.encodeFunctionData({abi:A.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${m.chainId}`,idempotenceKey:h,nbf:0n,exp:c,metadata:"{}",transfers:m.transfers.map(x=>({token:x.token.toLowerCase(),to:x.to,amount:x.amount}))}]})}})},...i]}function An(e,t,n,s){const o=e.filter(i=>i.domain!=="spicenet"),r=i=>(i.tokenTransfers??[]).some(l=>l.from==="escrow");return[...o.filter(i=>!r(i)),...Gn(o.filter(r),t,n,s)]}function Jo(e,t,n,s,o){const r=e[e.length-1];if(!r?.calls.length||r.domain==="spicenet")throw new Error("Proceeds fees require a final destination action");const i=[{to:A.SPICE_PLATFORM_FEE_RECIPIENT,amount:o},{to:A.SPICE_GAS_FEE_RECIPIENT,amount:s}].filter(l=>l.amount>0n);return e.map(l=>l===r?{...l,calls:[...l.calls,...i.map(d=>({to:n,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[d.to,d.amount]})}))],tokenTransfers:[...l.tokenTransfers??[],...i.map(d=>({from:t,to:d.to,token:n,amount:d.amount}))]}:l)}async function pi(e,t,n,s,o){const r=A.hashChainBatches(e),i=await g.relayerService.estimateBatchGas({user:t,outputToken:n,signal:s,requireSimulation:!0,includePlatformFee:o!==void 0,chainBatches:e.map((l,d)=>({...l,hash:r[d].hash}))});if(i.gasQuoteSource!=="estimated"||!i.simulationVerified)throw new Error("Action proceeds require a successful live batch simulation; fallback gas pricing is not sufficient");if(o!==void 0&&(i.platformFee===void 0||i.platformFee>o))throw new Error("Fee conversion platform price changed; refresh before retrying");return i.gasFee}async function Cu(e){if(e.proceeds.token.toLowerCase()!==e.token.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const t=await e.proceeds.resolve(e.signal);if(e.signal?.aborted)throw new Error("Action proceeds quote was cancelled");if(t<0n)throw new Error("Action proceeds cannot be negative");const n=await e.baseline();if(!n?.feeEstimate)throw new Error("Action fee quote is unavailable");let s=n.preview.gasFee;const o=n.preview.spicenetFee,r=n.preview.bridgeFee??0n;for(let i=0;i<5;i++){const l=s+o+r,d=t<l?t:l,c=l-d,m=c>0n?(c*110n+99n)/100n+2n:0n,p=An(await e.buildBatches(m),e.owner),f=Jo(p,e.owner,e.token,s+r,o),h=await pi(f,e.owner,e.token,e.signal);if(h===s)return{preview:{...n.preview,grossAmount:m,netAmount:0n,gasFee:s,totalFee:l,gasQuoteSource:"estimated"},feeEstimate:n.feeEstimate,grossFundingAmount:m,proceedsAvailable:t,proceedsUsed:d};s=h}throw new Error("Action proceeds fee estimate did not converge")}function fi(e,t,n){if(e._source==="wallet")return e._fundingWallet==="embedded"&&e.chainId===t&&A.getTokenByAddress(e.address,t)?e.address:null;const s=Dn(e,t);return s.find(o=>o.toLowerCase()===n.toLowerCase())??s[0]??null}class mi extends Error{constructor(t,n){super("The selected balance cannot cover the fee funding amount"),this.requiredAmount=t,this.balance=n,this.name="InsufficientFeeFundingBalanceError"}}async function vu(e){const t=e.selectedAsset?.asset,n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t||!n||t._source!=="spice"&&!(t._source==="wallet"&&t._fundingWallet==="embedded"&&t.chainId===e.resolvedChainId))throw new Error("A local embedded or Spice balance is required for fee conversion");const s=fi(t,e.resolvedChainId,e.destinationToken.address);if(!s)throw new Error("This receipt has no registered destination withdrawal token");const o=A.getTokenByAddress(s,e.resolvedChainId);if(!o)throw new Error("Fee funding token metadata is unavailable");const r=e.destinationToken.address;if(e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==r.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const i=e.actionProceeds?await e.actionProceeds.resolve(e.signal):0n;if(i<0n||e.signal?.aborted)throw new Error("Action proceeds quote was cancelled or invalid");const l=Ws({executorAddress:n,customVenues:[...e.resolveExactOutputSwap?[{name:"consumer-exact-output",chainIds:[e.resolvedChainId],preferred:!0,resolve:e.resolveExactOutputSwap}]:[],...Kn(e.liquidityVenues).output]}),d=async m=>{const p=A.hashChainBatches(m),f=await g.relayerService.estimateBatchGas({user:n,outputToken:r,requireSimulation:!0,includePlatformFee:!0,signal:e.signal,chainBatches:m.map((h,x)=>({...h,hash:p[x].hash}))});if(!f.simulationVerified||f.gasQuoteSource!=="estimated"||f.platformFee===void 0||f.gasFee<=0n)throw new Error("Fee conversion requires verified gas and platform pricing");return f};let c=await d(await e.buildPayChainBatches({fundingAmountOverride:0n}));for(let m=0;m<8;m++){const p=c.gasFee+c.platformFee,f=i<p?i:p,h=p-f,x=h>0n?(h*110n+99n)/100n+2n:0n,b=x>0n?await l.getQuote({tokenIn:s,tokenOut:r,amountOut:x,maxSlippage:e.maxSlippage},e.resolvedChainId,n):null;if(e.signal?.aborted)throw new Error("Fee conversion quote was cancelled");if(b&&(b.amountOut!==x||b.amountInMax<=0n||b.amountInMax<b.amountIn||!b.calls.length))throw new Error("Invalid exact-output fee conversion quote");const y=b?.amountInMax??0n,w=Kt(y,o.decimals,t.decimals);if(w>t.balance)throw new mi(w,t.balance);let S=An(await e.buildPayChainBatches({fundingAmountOverride:y,fundingTokenOverride:s}),n);if(b){const k=S.length-1;S=S.map((C,E)=>E===k?{...C,calls:[...C.calls,...b.calls]}:C)}S=Jo(S,n,r,c.gasFee,c.platformFee);const v=await d(S);if(v.gasFee<=c.gasFee&&(c.gasFee-v.gasFee)*100n<=v.gasFee*15n&&v.platformFee===c.platformFee){const k={tokenIn:s,tokenOut:r,amountInMax:y,amountOut:x,sourceAmountMax:w};return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,grossAmount:x,netAmount:0n,gasFee:c.gasFee,spicenetFee:c.platformFee,totalFee:p,gasQuoteSource:"estimated"},grossFundingAmount:y,proceedsAvailable:i,proceedsUsed:f,fundingConversion:k,fundingBatches:S}}c=v}throw new Error("Fee conversion pricing did not converge")}function Zn(e){return JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString():n)}async function hi(e,t,n){const s=e.sourceConversion,o=e.selectedAsset?.asset,r=e.embeddedWalletAddress??e.providerEmbeddedAddress;try{if(!o||!r||o._source!=="wallet")throw new Error("Select a wallet source for source-chain conversion");if(!e.isPayMode&&!e.isFeeInclusiveInput)throw new Error("Source-chain conversion requires input-inclusive or exact-output mode");const i=s.virtualSelectedAsset,l=i.asset.chainId===e.resolvedChainId&&g.addressesEqual(i.asset.address,e.destinationToken.address);await t({...e,sourceConversion:void 0,sourceConversionRequired:!1,sourceFunding:void 0,selectedAsset:i,parsedAmount:e.isPayMode?e.parsedAmount:Number(i.amount),isInsufficientBalance:!1,isSourceDestToken:l,executionTokenDecimals:i.asset.decimals,execution:{...e.execution,execute:async(d,c,m,p,f,h)=>{let x;const b=(v,k)=>{const C=x??s.getPlan(v);if(!s.isCurrent()||!C||C.expiresAt<=Date.now())throw new Error("Source funding quote expired or changed; refresh it before retrying");const E=C.quote.plan.source;if(E.chainId!==o.chainId||E.decimals!==o.decimals||!g.addressesEqual(E.address,o.address)||!g.addressesEqual(C.quote.executorAddress,r))throw new Error("The source funding quote does not belong to this wallet and asset");if(!e.isPayMode&&C.quote.sourceAmountInMax!==I.parseUnits(e.selectedAsset.amount,o.decimals))throw new Error("The source quote exceeds the entered input-inclusive budget");if(C.quote.sourceAmountInMax>s.acceptedSourceAmountInMax)throw new Error("The source quote exceeds the displayed maximum; review the refreshed quote before retrying");if(k!==void 0&&C.quote.sourceAmountInMax>k)throw new Error("The refreshed source quote exceeds this operation's funded amount");if(!C.chainBatches.every((F,B)=>v[B]&&Zn(v[B])===Zn(F)))throw new Error("The source conversion calls changed after quoting");return C},y=b(d),w=y.quote.sourceAmountInMax,S=v=>{const k=C=>C.chainBatches.every((E,F)=>v[F]&&Zn(v[F])===Zn(E));if(!x||k(x))return v;if(!k(y))throw new Error("The source conversion calls changed after quoting");return[...x.chainBatches,...v.slice(y.chainBatches.length)]};if(en(o,e.isNon7702)){const v=BigInt(e.sourceFunding?.confirmedAmount??"0")+BigInt(e.sourceFunding?.pending?.amount??"0");if(w>o.balance+v)throw new Error("Insufficient selected-source balance for the quoted amount and fees");await n(w)}else{const v=g.getClientForChain(o.chainId);if((o.isNative||A.isNativeToken(o.address)?await v.getBalance({address:r}):await v.readContract({address:o.address,abi:I.erc20Abi,functionName:"balanceOf",args:[r]}))<w)throw new Error("Insufficient embedded source balance for this conversion")}return b(d,w),e.execution.execute(d,c,m,p,f,{...h,skipUserFundingPreflight:!0,prepareAfterAuthorization:async v=>{if(!s.isCurrent())throw new Error("Source funding wallet or destination quote changed; refresh before retrying");if(y.expiresAt>Date.now())return b(v,w),h?.prepareAfterAuthorization?h.prepareAfterAuthorization(v):v;const k=await s.refreshPlan(y);if(k.bridgeDestinationNet<y.bridgeDestinationNet)throw new Error("Refreshed source funding cannot cover the accepted destination; review the new quote");const C=y.quote.plan,E=k.quote.plan;for(const B of["bridgeSource","bridgeDestination"])if(C[B].chainId!==E[B].chainId||C[B].decimals!==E[B].decimals||!g.addressesEqual(C[B].address,E[B].address))throw new Error("The source funding route changed; review the new quote");x=k;const F=S(v);return b(F,w),h?.prepareAfterAuthorization?h.prepareAfterAuthorization(F):F},adjustBatchesForEstimate:async v=>{const k=await h?.adjustBatchesForEstimate?.(v),C=S(k??v.chainBatches);return b(C,w),k?C:null},validateBeforeSubmit:async v=>{await h?.validateBeforeSubmit?.(v),b(v,w)}})}}})}catch(i){const l=g.sanitizeError(i,"Source funding conversion failed");e.ui.setError(l),e.ui.setStep("error"),e.isPayMode&&e.ui.setPaymentResult({status:"failed",error:l})}}function gi(e,t){let n,s;if(A.isNativeToken(t)){if(e.data!=="0x")return null;n=e.to,s=e.value}else{if(!g.addressesEqual(e.to,t))return null;try{const o=I.decodeFunctionData({abi:I.erc20Abi,data:e.data});if(o.functionName!=="transfer")return null;[n,s]=o.args}catch{return null}}return g.addressesEqual(n,A.SPICE_GAS_FEE_RECIPIENT)?{gas:s,platform:0n}:g.addressesEqual(n,A.SPICE_PLATFORM_FEE_RECIPIENT)?{gas:0n,platform:s}:null}function ps(e,t,n){return e.map(s=>s.chainId===t?{...s,calls:s.calls.filter(o=>!gi(o,n))}:s)}function xi(e,t,n){if(!e.feeOnlyAction)return{};const s=e.embeddedWalletAddress??e.providerEmbeddedAddress;if(e.actionProceeds||e.feeQuote?.fundingConversion){const l=e.feeQuote?.fundingConversion,d=e.actionProceeds??{token:t,resolve:async()=>0n},c=e.feeQuote?.preview,m=e.feeQuote?.proceedsUsed;if(!c||m===void 0||d.token.toLowerCase()!==t.toLowerCase())throw new Error("Refresh the action proceeds quote");const p=c.gasFee+(c.bridgeFee??0n),f=c.spicenetFee,h=async()=>{e.validateFeeQuote?.();const b=await d.resolve(e.signal);if(e.validateFeeQuote?.(),e.signal?.aborted||b<m||b+(l?.amountOut??n)<p+f)throw new Error("Action proceeds changed; refresh before retrying");return[{chainId:e.resolvedChainId,token:t,amount:m+(l?.amountOut??0n)}]},x=async b=>{await h();const y=await pi(b,s,t,e.signal,l?f:void 0);if(await h(),(y>c.gasFee?y-c.gasFee:c.gasFee-y)*100n>y*15n)throw new Error("Action gas quote changed; refresh before retrying")};return{resolveActionOutputCredits:h,prepareForSigning:async b=>{const y=ps(b,e.resolvedChainId,t).map(S=>({...S,tokenTransfers:S.tokenTransfers?.filter(v=>!(typeof v.from=="string"&&g.addressesEqual(v.from,s)&&(g.addressesEqual(v.to,A.SPICE_GAS_FEE_RECIPIENT)||g.addressesEqual(v.to,A.SPICE_PLATFORM_FEE_RECIPIENT))))})),w=Jo(y,s,t,p,f);return await x(w),w},validateBeforeSubmit:x}}const o=A.getTokenByAddress(t,e.resolvedChainId),r={chainId:e.resolvedChainId,tokenAddress:t,symbol:o?.symbol??e.destinationToken.symbol,decimals:e.executionTokenDecimals??o?.decimals??e.destinationToken.decimals},i=async l=>{e.validateFeeQuote?.();const d=ps(l,e.resolvedChainId,t),c=await e.execution.estimate(d,t,n,{userOverride:s,useCustomTransfers:!0,feeExecutionMode:"backend-transfer"});e.validateFeeQuote?.();const m=xn(c,r);if(!m||m.chainId!==e.resolvedChainId)throw new Error("The fee service did not return the destination action's fee quote");if(m.gasFee+m.spicenetFee+(m.bridgeFee??0n)+2n>n)throw new Error("Fees exceed the displayed maximum funding; refresh the quote before retrying");return{raw:d,feeEstimate:c,fees:m}};return{prepareForSigning:async l=>{const{raw:d,feeEstimate:c}=await i(l);return An(d,s,c,{payoutAlreadyGross:!0})},validateBeforeSubmit:async l=>{const{fees:d}=await i(l);let c=0n,m=0n;for(const f of l)if(f.chainId===e.resolvedChainId)for(const h of f.calls){const x=gi(h,t);x&&(c+=x.gas,m+=x.platform)}if(c+m+2n>n)throw new Error("Signed fees exceed the displayed maximum funding");const p=d.gasFee+(d.bridgeFee??0n);if((c>p?c-p:p-c)*100n>p*15n||m!==d.spicenetFee)throw new Error("The signed gas quote changed materially; refresh before retrying")}}}const yi=(e,t)=>(e+t-1n)/t;function ku(e,t){const n=e.spicenetFee+(e.bridgeFee??0n);return e.grossAmount<=n?t+e.gasFee+n:yi((t+e.gasFee)*e.grossAmount,e.grossAmount-n)+2n}function bi(e,t,n){return e.every(s=>s.domain!=="spicenet"&&!s.tokenTransfers?.length)?{...t,grossAmount:n,netAmount:n,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}:null}async function $o(e){const{requiredNetFunding:t}=e;if(e.feeOnlyAction){const m=e.executionOptions?.userOverride;if(!m||t!==0n)throw new Error("Fee-only estimates require a zero action amount and its embedded executor");let p=1n,f;for(let h=0;h<8;h++){const x=An(await e.buildBatches(p),m,f,{payoutAlreadyGross:!0}),b=await e.estimate(ps(x,e.tokenDescriptor.chainId,e.fundingToken),e.fundingToken,p,{...e.executionOptions,feeExecutionMode:"backend-transfer"}),y=xn(b,e.tokenDescriptor);if(!y)throw new Error("The fee service did not return a fee quote for this action");const w=y.gasFee+y.spicenetFee+(y.bridgeFee??0n);if(f&&w+2n<=p)return{preview:{...y,grossAmount:p,netAmount:0n},feeEstimate:b,grossFundingAmount:p};p=(w*110n+99n)/100n+2n,f=b}throw new Error("Fee-only funding did not converge; refresh the fee quote before retrying")}const n=t,s=await e.buildBatches(n),o=await e.estimate(s,e.fundingToken,n,e.executionOptions),r=xn(o,e.tokenDescriptor);if(!r)return{preview:bi(s,e.tokenDescriptor,t),feeEstimate:o,grossFundingAmount:t};const i=ku(r,t),l=m=>r.grossAmount>0n?yi(m*i,r.grossAmount):m,d=l(r.spicenetFee),c=l(r.bridgeFee??0n);return{preview:{...r,grossAmount:i,netAmount:t,spicenetFee:d,bridgeFee:c,totalFee:r.gasFee+d+c},feeEstimate:o,grossFundingAmount:i}}function Su(e,t,n,s){if(e<=0n)return 0n;const o=e-t;if(o<=0n)return 0n;const r=s+n;return r<=0n?o:o*s/r}async function wi(e){const{asset:t,isPayMode:n,isNon7702:s,needsSwap:o,isQuoting:r,embeddedWalletAddress:i,buildSupplyChainBatches:l,estimate:d,executionTokenAddress:c,feeExecutionMode:m}=e;if(n||s||o||r||!i||t.balance<=0n)return null;const p=i,f=await l({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(f.length===0)return null;const h=f.some(v=>v.tokenTransfers?.length),x=await d(f,c,t.balance,h?{userOverride:p,useCustomTransfers:!0,feeExecutionMode:m}:m?{userOverride:p,feeExecutionMode:m}:{userOverride:p}),b=xn(x,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),y=b?Kt(b.gasFee,b.decimals,t.decimals):0n,w=b?Kt(b.spicenetFee,b.decimals,t.decimals):0n,S=Su(t.balance,y,w,t.balance);return S>0n?ra(S,t.decimals):null}async function _o(e){const{signal:t,selectedAsset:n,isPayMode:s,isFeeInclusiveInput:o=!1,parsedAmount:r,needsSwap:i,exactOutputSwap:l,isNon7702:d,isSourceDestToken:c,currentPaymentAmount:m,destinationToken:p,feeExecutionMode:f,resolvedTokenIn:h,embeddedWalletAddress:x,providerEmbeddedAddress:b,resolvedChainId:y,isConnected:w,address:S,ready:v,authenticated:k,isDirect:C,resolvedSwap:E,isQuoting:F,executionTokenAddress:B,buildPayChainBatches:j,buildSupplyChainBatches:T,estimate:R}=e;if(e.feeOnlyAction&&n&&(n.asset._source==="spice"||n.asset._source==="wallet"&&n.asset._fundingWallet==="embedded"&&n.asset.chainId===y)&&(h?h.toLowerCase()!==p.address.toLowerCase():n.asset.receiptTokenId||n.asset.chainTokens))return vu(e);if(e.actionProceeds&&e.feeOnlyAction){const O=x||b;if(!O||!v||!k)return null;if(h&&h.toLowerCase()!==p.address.toLowerCase())throw new Error("Action proceeds require a matching fee-token source");return Cu({proceeds:e.actionProceeds,owner:O,token:p.address,signal:t,buildBatches:ee=>j({fundingAmountOverride:ee}),baseline:()=>_o({...e,actionProceeds:void 0,selectedAsset:n??{amount:"0",asset:{...p,name:p.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"spice"}}})})}if(!n?.asset)return null;if(s){if(r<=0&&!e.feeOnlyAction||i&&!l&&!e.feeOnlyAction||c&&n.asset._source==="wallet"&&!e.feeOnlyAction||d&&!x&&!b)return null;const O=I.parseUnits(m,p.decimals),ee=h||Qt(n.asset,y)||n.asset.address||p.address,ue={chainId:y,tokenAddress:ee,symbol:A.getTokenByAddress(ee,y)?.symbol??n.asset.symbol,decimals:await Yn(n.asset,p,ee)};if(en(n.asset,d)){const ce=x||b;if(!ce)return null;const _=i?l?.amountInMax??0n:O;if(_===0n&&!e.feeOnlyAction)return null;const Ce=await $o({requiredNetFunding:_,feeOnlyAction:e.feeOnlyAction,buildBatches:W=>j({fundingAmountOverride:W}),fundingToken:ee,estimate:R,executionOptions:{userOverride:ce,useCustomTransfers:!0,feeExecutionMode:f,signal:t},tokenDescriptor:ue});return Ce.preview?{...Ce,preview:Ce.preview}:null}if(!w||!S||!v||!k)return null;const re=x||b||S,se=i?l?.amountInMax??0n:O;if(se===0n&&!e.feeOnlyAction)return null;const ie=await $o({requiredNetFunding:se,feeOnlyAction:e.feeOnlyAction,buildBatches:ce=>j({fundingAmountOverride:ce}).then(_=>An(_,re)),fundingToken:ee,estimate:R,executionOptions:{userOverride:re,useCustomTransfers:!0,feeExecutionMode:f,signal:t},tokenDescriptor:ue});return ie.preview?{...ie,preview:ie.preview}:null}if(r<=0||!x)return null;const D=x||b;if(!(!s&&!d&&n.asset._source==="wallet"&&n.asset.chainId!==y)&&!C&&!E&&!F||F)return null;const M=await Yn(n.asset,p,B),P=Bt(I.parseUnits(n.amount,n.asset.decimals),n.asset.decimals,M,"floor"),q=await T();if(q.length===0)return null;const z=n.asset._source==="wallet",X=z&&(n.asset._fundingWallet==="external"||d&&n.asset._fundingWallet!=="embedded")&&z&&n.asset.chainId===y,N={chainId:y,tokenAddress:B,symbol:A.getTokenByAddress(B,y)?.symbol??p.symbol,decimals:M};if(X){const O=await g.relayerService.estimateBatchGas({user:D,outputToken:B,stepIndex:0,chainBatches:q,signal:t}),ee=o?Ts(P,O.gasFee,Mn):(()=>{const ue=Hn(P,Mn),re=ue+O.gasFee;return{netAmount:P,spicenetFee:ue,totalFee:re,grossAmount:P+re}})();return{preview:{...N,grossAmount:ee.grossAmount,netAmount:ee.netAmount,totalFee:ee.totalFee,gasFee:O.gasFee,spicenetFee:ee.spicenetFee,bridgeFee:0n,gasQuoteSource:O.gasQuoteSource},feeEstimate:null}}const H=q.some(O=>O.tokenTransfers?.length),V=await R(q,B,P,H?{userOverride:D,useCustomTransfers:!0,feeExecutionMode:f,signal:t}:f?{userOverride:D,feeExecutionMode:f,signal:t}:{userOverride:D,signal:t}),G=xn(V,N),J=G??bi(q,N,P);if(!J)return null;if(!o||!G)return{preview:J,feeEstimate:V};const U=J.gasFee+(J.bridgeFee??0n),L=Ts(P,U,Mn);return{preview:{...J,grossAmount:L.grossAmount,netAmount:L.netAmount,totalFee:L.totalFee,spicenetFee:L.spicenetFee},feeEstimate:V}}function Ci(e){if(!e||typeof e!="object")return!1;const t=e;return t.version===1&&typeof t.identity=="string"&&/^[0-9]+$/.test(t.baseline)&&/^[0-9]+$/.test(t.confirmedAmount)&&(!t.pending||/^[1-9][0-9]*$/.test(t.pending.amount)&&(!t.pending.hash||/^0x[0-9a-f]{64}$/i.test(t.pending.hash)))}async function er(e){const t=()=>e.isNative?e.sourceClient.getBalance({address:e.recipient}):e.sourceClient.readContract({address:e.tokenAddr,abi:I.erc20Abi,functionName:"balanceOf",args:[e.recipient]});let n=e.state;if(n&&(!Ci(n)||n.identity!==e.identity))throw new Error("Restore the pending funding operation's original source, wallets and amount before retrying");n||(n={version:1,identity:e.identity,baseline:(await t()).toString(),confirmedAmount:"0"});const s=()=>e.onState({...n,pending:n.pending&&{...n.pending}}),o=()=>{delete n.pending,s()},r=()=>{n.confirmedAmount=(BigInt(n.confirmedAmount)+BigInt(n.pending.amount)).toString(),delete n.pending,s()};if(n.pending){if(!n.pending.hash)throw new Error("Source funding submission is unconfirmed; recover it before retrying to avoid spending twice");const{receipt:p}=await Ns({client:e.sourceClient,hash:n.pending.hash,call:fa(e.recipient,e.tokenAddr,e.isNative,BigInt(n.pending.amount)),onRepriced:f=>{n.pending.hash=f,s()},onCancelled:o});if(p.status!=="success")throw o(),new Error("Source funding reverted; retry when ready");r()}if(e.reconcileOnly)return;const i=BigInt(n.confirmedAmount),l=async()=>{if(BigInt(n.confirmedAmount)>0n&&await t()<BigInt(n.baseline)+BigInt(n.confirmedAmount))throw new Error("Previously funded assets are no longer reserved in the embedded wallet; recover this operation before funding again")};await l();const d=e.requiredAmount>i?e.requiredAmount-i:0n;if(d===0n)return;const{extWc:c,viemChain:m}=await e.createWallet();await ha({extWc:c,sourceClient:e.sourceClient,recipient:e.recipient,tokenAddr:e.tokenAddr,isNative:e.isNative,amount:d,viemChain:m,observer:{onSending:async()=>{await e.observer?.onSending?.(0)},onSubmitted:(p,f)=>{n.pending={amount:d.toString(),hash:f},s(),e.observer?.onSubmitted?.(0,f)},onConfirmed:(p,f)=>{r(),e.observer?.onConfirmed?.(0,f)},onRejected:()=>{o(),e.observer?.onRejected?.(0)},onReverted:(p,f)=>{o(),e.observer?.onReverted?.(0,f)}}}),await l()}function Au(e){return e.selectedAsset||!e.feeOnlyAction||!e.actionProceeds?e.selectedAsset:{amount:"0",asset:{...e.destinationToken,name:e.destinationToken.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"wallet",_fundingWallet:"embedded"}}}function tr(e){const t=Au(e),n=t?.asset;return JSON.stringify([e.externalWalletAddress?.toLowerCase(),(e.embeddedWalletAddress??e.providerEmbeddedAddress)?.toLowerCase(),n?.address.toLowerCase(),n?.chainId,n?.decimals,n?._source,n?._fundingWallet,t?.amount,e.resolvedChainId,e.destinationToken.address.toLowerCase(),e.recipient?.toLowerCase(),e.isPayMode,e.currentPaymentAmount??"0",e.isFeeInclusiveInput??!1,e.sourceFundingRecoveryKey??"generic",e.destinationToken.decimals,n?n.isNative??A.isNativeToken(n.address):null,...e.feeOnlyAction?[!0]:[]])}async function Gs(e,t){const n=e.selectedAsset.asset,s=A.normalizeNativeTokenAddress(n.address);await er({identity:tr(e),state:e.sourceFunding,onState:o=>{e.sourceFunding=o,e.onSourceFundingChange?.(o)},createWallet:()=>On({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:n.chainId,onSwitch:()=>e.ui.setStatusMsg("Switching source network...")}),sourceClient:g.getClientForChain(n.chainId),recipient:e.embeddedWalletAddress??e.providerEmbeddedAddress,tokenAddr:s,isNative:n.isNative||A.isNativeToken(s),requiredAmount:t,observer:e.fundingObserver})}function vi(e,t){const n=e.selectedAsset?.asset;if(!n||n._source!=="wallet")return;const s=Qt(n,e.resolvedChainId);if(!s||!g.addressesEqual(s,e.executionTokenAddress))return;const o=A.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),r=Kt(t,e.executionTokenDecimals??o?.decimals??e.destinationToken.decimals,n.decimals),i=n.balance+BigInt(e.sourceFunding?.confirmedAmount??"0");if(r<=i)return;const l=I.formatUnits(r,n.decimals),d=I.formatUnits(i,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${l} ${n.symbol}; available ${d} ${n.symbol}.`)}function In(e){const t=A.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:e.executionTokenDecimals??t?.decimals??e.destinationToken.decimals}}function fs(e,t,n){const s=xn(e,In(t));if(!s)return;const o=s.bridgeFee??0n,r=s.gasFee+o;if(t.isFeeInclusiveInput){const c=Ts(n,r,Mn);if(!c.coversFees){const{symbol:m,decimals:p}=In(t);throw new Error(`Amount too small: fees are ${I.formatUnits(r,p)} ${m}.`)}if(t.needsSwap&&!t.exactOutputSwap&&(t.swapInputAmount??t.feeQuote?.preview?.netAmount)!=null&&c.netAmount<(t.swapInputAmount??t.feeQuote.preview.netAmount))throw new Error("Fees changed. Refresh the swap quote before retrying so the total stays within your entered amount.");return{grossAmount:c.grossAmount,netAmount:c.netAmount,combinedFeeAmount:c.totalFee,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:c.spicenetFee,gasFee:s.gasFee,bridgeFee:o}}}const i=n,l=Hn(n,Mn),d=l+r;return{grossAmount:i+d,netAmount:i,combinedFeeAmount:d,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:l,gasFee:s.gasFee,bridgeFee:o}}}function ki(e,t,n){let s=0n,o=0n;const r=n.toLowerCase();for(const i of e)if(i.chainId===t)for(const l of i.calls??[]){if(A.isNativeToken(n)&&l.data==="0x"&&l.value>0n){g.addressesEqual(l.to,A.SPICE_PLATFORM_FEE_RECIPIENT)?s+=l.value:g.addressesEqual(l.to,A.SPICE_GAS_FEE_RECIPIENT)&&(o+=l.value);continue}if(l.to.toLowerCase()===r)try{const d=I.decodeFunctionData({abi:I.erc20Abi,data:l.data});if(d.functionName!=="transfer")continue;const c=d.args[0].toLowerCase(),m=d.args[1];c===A.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=m:c===A.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(o+=m)}catch{continue}}return{spicenetFee:s,gasFee:o}}function nr(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,o=ki(e,t.resolvedChainId,s);return o.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||o.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Nn(o.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Nn(o.gasFee,n.feeBreakdown.gasFee,100n)}function Si(e,t){if(!e.isFeeInclusiveInput||!e.needsSwap||e.swapInputAmount==null||!e.selectedAsset)return;const n=In(e),s=Bt(I.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),e.selectedAsset.asset.decimals,n.decimals,"floor"),o=ki(t,e.resolvedChainId,e.resolvedTokenIn??e.executionTokenAddress);if(e.swapInputAmount+o.gasFee+o.spicenetFee>s)throw new Error("Swap input plus fees exceeds the entered amount. Refresh the quote before retrying.")}function Ai(e,t){return e?Nn(e.grossAmount,t.grossAmount,100n)&&Nn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Nn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Nn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}function Ii(e,t){const n=A.getTokenByAddress(t,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:t,symbol:n?.symbol??e.selectedAsset?.asset.symbol??"",decimals:e.executionTokenDecimals??n?.decimals??e.selectedAsset?.asset.decimals??e.destinationToken.decimals}}async function sr(e,t){const n=e.feeQuote;return n?.feeEstimate&&n.grossFundingAmount!==void 0?{grossFundingAmount:n.grossFundingAmount,feeEstimate:n.feeEstimate}:$o({...t,feeOnlyAction:e.feeOnlyAction,estimate:e.execution.estimate,tokenDescriptor:Ii(e,t.fundingToken)})}function Ei(e,t){if(e.feeOnlyAction)return 0n;const n=e.selectedIsEquivalent?t:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(n===0n)throw new Error("Quote not available yet");return n}function or(e,t,n){const s=t instanceof Error?t:new Error(String(t));if(s.name==="AbortError"||n){e.ui.setStep("idle");return}const o=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(o),e.ui.setError(o)}function rr(e,t){const n=g.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}function Iu(e){if(!e.isFeeInclusiveInput||e.feeExecutionMode==="user-transfer")return e;const t=A.normalizeNativeTokenAddress(e.executionTokenAddress);let n=!1;const s=(o,r)=>A.isNativeToken(t)?{to:o,value:r,data:"0x"}:{to:t,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[o,r]})};return{...e,feeExecutionMode:"user-transfer",execution:{...e.execution,execute:(...o)=>{if(!n)throw new Error("Inclusive supply requires a destination fee quote");return e.execution.execute(...o)},estimate:async(o,r,i,l)=>{const d=await e.execution.estimate(ps(o,e.resolvedChainId,t),r,i,{...l,feeExecutionMode:"backend-transfer"});if(!xn(d,In(e)))throw new Error("Inclusive supply requires a destination fee quote");return d},buildSupplyChainBatches:async o=>{const r=o?.actionContextOverride,i=await e.execution.buildSupplyChainBatches({...o,actionContextOverride:r?{...r,feeExecutionMode:"backend-transfer"}:void 0});if(!r?.feeBreakdown)return i;n=!0;const{spicenetFee:l,gasFee:d,bridgeFee:c}=r.feeBreakdown,m=[...l>0n?[s(A.SPICE_PLATFORM_FEE_RECIPIENT,l)]:[],...d+c>0n?[s(A.SPICE_GAS_FEE_RECIPIENT,d+c)]:[]],p=ps(i,e.resolvedChainId,t),f=p[p.length-1];if(f?.chainId!==e.resolvedChainId)throw new Error("Inclusive supply requires a final destination action batch");return p.map(h=>h===f?{...h,calls:[...m,...h.calls]}:h)}}}}async function Zs(e){if(e.feeOnlyAction){e.ui.setError("Fee-only actions require output mode and a zero action amount");return}if(e.sourceConversion)return hi(e,Zs,s=>Gs(e,s));if(e.sourceConversionRequired){e.ui.setError("Wait for the source funding quote before continuing");return}if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance&&!e.sourceFunding){e.ui.setError("Insufficient balance");return}const t=e.selectedAsset;try{e={...e,executionTokenDecimals:await Yn(t.asset,e.destinationToken,e.executionTokenAddress)}}catch(s){or(e,s,!1);return}if(e=Iu(e),en(t.asset,e.isNon7702)){const s=e.isNon7702&&e.isSourceDestToken,o=e.externalWalletAddress;if(s?!o:!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(s){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const r=await Fi({...e,activeSignerAddress:e.externalWalletAddress,activeSignerWallet:e.externalWallet});e.ui.setTxHash(r??null)}else{e.ui.setStep("building"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const r=new AbortController;e.refs.abortControllerRef.current=r,await Eu(e,r.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(s?"Transaction confirmed":"Deposit confirmed")}catch(r){or(e,r,!!e.refs.abortControllerRef.current?.signal.aborted)}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("building"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const n=new AbortController;e.refs.abortControllerRef.current=n;try{const s=Bt(I.parseUnits(t.amount,t.asset.decimals),t.asset.decimals,In(e).decimals,"floor"),o=s;let r=await e.execution.buildSupplyChainBatches();const i=t.asset._source==="wallet",l=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!i&&!r.some(b=>A.isSpicenetChainId(b.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const d=r.some(b=>b.tokenTransfers?.length),c=d?{userOverride:l,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:l,feeExecutionMode:e.feeExecutionMode}:{userOverride:l};let m=s;const p=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap;let f,h=e.feeExecutionMode==="user-transfer"&&!p?o:void 0;for(let b=0;b<4;b+=1){const y=b===0&&e.feeQuote?.feeEstimate||await e.execution.estimate(r,e.executionTokenAddress,d?m:0n,c),w=xn(y,In(e));f=e.feeExecutionMode==="user-transfer"&&w?fs(y,e,o):void 0,e.isFeeInclusiveInput&&f&&!p&&(h=f.netAmount);const S=f?.grossAmount??w?.grossAmount??m;if(S===m){m=S;break}m=S,r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:m,actionAmountOverride:h,actionContextOverride:f})}e.feeExecutionMode==="user-transfer"&&(vi(e,m),r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:m,actionAmountOverride:h,actionContextOverride:f}));let x=f;await e.execution.execute(r,e.executionTokenAddress,d?m:0n,e.execution.onProgress,n.signal,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,validateBeforeSubmit:async b=>Si(e,b),adjustBatchesForEstimate:({feeEstimate:b,chainBatches:y})=>{const w=fs(b,e,o);if(!w)return null;const S=Ai(x,w),v=nr(y,e,w);return S||v?null:(x=w,e.isFeeInclusiveInput&&!p&&(h=w.netAmount),e.execution.buildSupplyChainBatches({fundingAmountOverride:w.grossAmount,actionAmountOverride:h,actionContextOverride:w}))}}:{...c,skipPreSubmitFeeEstimate:!0}),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(s){or(e,s,n.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function Eu(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const s=e.selectedAsset.asset,o=en(s,e.isNon7702);if(o&&!e.externalWallet)throw new Error("Please connect your external wallet to continue");const r=Bt(I.parseUnits(e.selectedAsset.amount,s.decimals),s.decimals,In(e).decimals,"floor"),i=r,l=s._source==="wallet"&&s.chainId===e.resolvedChainId;let d=await e.execution.buildSupplyChainBatches();const c={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let m=r;const p=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap;let f=e.feeExecutionMode==="user-transfer"&&!p?i:void 0,h;if(l){const v=e.feeQuote?.preview.gasFee??(await g.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d})).gasFee,k=e.isFeeInclusiveInput&&e.feeExecutionMode==="user-transfer"?Ts(r,v,Mn):null;if(k&&!k.coversFees)throw new Error("Amount too small to cover supply fees");const C=k?.spicenetFee??Hn(r,10n),E=C+v;m=k?.grossAmount??r+E,k&&!p&&(f=k.netAmount),e.feeExecutionMode==="user-transfer"&&(h={grossAmount:m,netAmount:k?.netAmount??i,combinedFeeAmount:E,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:C,gasFee:v,bridgeFee:0n}})}else for(let v=0;v<4;v+=1){const k=await e.execution.estimate(d,e.executionTokenAddress,0n,c),C=e.feeExecutionMode==="user-transfer"?fs(k,e,i):void 0,E=xn(k,In(e)),F=C?.grossAmount??(E?E.grossAmount>r?E.grossAmount:r:m);if(h=C,e.isFeeInclusiveInput&&!p&&C&&(f=C.netAmount),F===m){m=F;break}m=F;const B=A.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),j=Kt(m,e.executionTokenDecimals??B?.decimals??e.destinationToken.decimals,s.decimals);d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:m,sourceFundingAmountOverride:j,withdrawalAmountOverride:m,actionAmountOverride:f,actionContextOverride:C})}const x=A.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let b=l?m:Kt(m,e.executionTokenDecimals??x?.decimals??e.destinationToken.decimals,s.decimals);vi(e,m),d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:m,sourceFundingAmountOverride:b,withdrawalAmountOverride:m,actionAmountOverride:f,actionContextOverride:h});const y=async v=>{o&&await Gs(e,v)};o&&(e.ui.setStatusMsg("Funding embedded wallet..."),await y(b));let w=b;if(e.feeExecutionMode==="user-transfer")for(let v=0;v<4;v+=1){const k=await e.execution.estimate(d,e.executionTokenAddress,0n,c),C=fs(k,e,i);if(!C)break;const E=l?C.grossAmount:Kt(C.grossAmount,e.executionTokenDecimals??x?.decimals??e.destinationToken.decimals,s.decimals);if(o&&E>w&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await y(E),w=E),h=C,e.isFeeInclusiveInput&&!p&&C&&(f=C.netAmount),m=C.grossAmount,b=E,d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:m,sourceFundingAmountOverride:b,withdrawalAmountOverride:m,actionAmountOverride:f,actionContextOverride:C}),nr(d,e,C))break}e.ui.setStatusMsg("Preparing transaction...");let S=h;await e.execution.execute(d,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,validateBeforeSubmit:async v=>Si(e,v),adjustBatchesForEstimate:({feeEstimate:v,chainBatches:k})=>{const C=fs(v,e,i);if(!C)return null;const E=Ai(S,C),F=nr(k,e,C);if(E||F)return null;if(C.grossAmount>m)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");S=C,e.isFeeInclusiveInput&&!p&&(f=C.netAmount);const B=l?C.grossAmount:Kt(C.grossAmount,e.executionTokenDecimals??x?.decimals??e.destinationToken.decimals,s.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:C.grossAmount,sourceFundingAmountOverride:B,withdrawalAmountOverride:C.grossAmount,actionAmountOverride:f,actionContextOverride:C})}}:{...c,skipPreSubmitFeeEstimate:!0})}async function Fi(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,s=e.activeSignerAddress??e.externalWalletAddress;if(!s||!n)throw new Error("Please connect your wallet to continue");const o=I.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),r={userAddress:s,executorAddress:s,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},i=await e.buildActionCalls(o,r);if(i.length===0)throw new Error("No action calls configured");const{extWc:l,viemChain:d}=await On({wallet:n,account:s,chainId:e.resolvedChainId}),c=g.getClientForChain(e.resolvedChainId);return Mo({extWc:l,client:c,calls:i,viemChain:d,errorMessage:"Transaction failed"})}async function Fu(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,s=I.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),o=Ei(e,s),r=e.resolvedTokenIn||Qt(n,e.resolvedChainId)||n.address,i=Ii(e,r).decimals,l=w=>Kt(w,i,n.decimals),d={userOverride:t,useCustomTransfers:!0,requireDestinationReceipt:e.feeOnlyAction},c=t,m=async(w,S,v)=>An(await e.execution.buildPayChainBatches({fundingAmountOverride:w}),c,S,v),{grossFundingAmount:p,feeEstimate:f}=await sr(e,{requiredNetFunding:o,buildBatches:w=>m(w),fundingToken:r,executionOptions:{...d,feeExecutionMode:e.feeExecutionMode}});let h=await m(p,e.actionProceeds?void 0:f,{payoutAlreadyGross:!0});const x=xi(e,r,p);x.prepareForSigning&&(h=await x.prepareForSigning(h)),await Gs(e,l(p));const b=h.some(w=>w.tokenTransfers?.length),y={...d,...x,skipUserFundingPreflight:!e.actionProceeds,skipPreSubmitFeeEstimate:!0};return await e.execution.execute(h,r,b?p:0n,w=>{w.txHash&&(e.ui.setPaymentResult(S=>({...S??{status:"processing"},txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,b?y:{userOverride:t,skipUserFundingPreflight:!0,skipPreSubmitFeeEstimate:!0})}async function ar(e){if(e.feeOnlyAction&&(e.parsedAmount!==0||!e.selectedAsset&&!e.actionProceeds||e.onPayExecute||!e.feeQuote?.feeEstimate&&!e.feeQuote?.fundingConversion||e.feeQuote.grossFundingAmount===void 0||!e.actionProceeds&&e.feeQuote.grossFundingAmount===0n)){e.ui.setError("Select a fee source and wait for its fee quote before continuing");return}if(e.sourceConversion)return hi(e,ar,s=>Gs(e,s));if(e.sourceConversionRequired){e.ui.setError("Wait for the source funding quote before continuing");return}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.sourceFunding){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.selectedAsset)try{e={...e,executionTokenDecimals:await Yn(e.selectedAsset.asset,e.destinationToken,e.executionTokenAddress)}}catch(s){rr(e,s);return}const n=(e.feeQuote?.grossFundingAmount!==0n||!e.actionProceeds)&&en(e.selectedAsset?.asset,e.isNon7702);if(n||e.isNon7702&&t&&!e.feeOnlyAction){const s=n?e.externalWalletAddress: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)&&!e.feeOnlyAction)o=await Fi(n?{...e,activeSignerAddress:e.externalWalletAddress,activeSignerWallet:e.externalWallet}:e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,i=I.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),l=Ei(e,i),d=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!d)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const c=e.resolvedTokenIn||r.address,{grossFundingAmount:m}=await sr(e,{requiredNetFunding:l,buildBatches:h=>e.execution.buildPayChainBatches({fundingAmountOverride:h}),fundingToken:c,executionOptions:{userOverride:d,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}}),p=await e.execution.buildPayChainBatches({fundingAmountOverride:m}),f=await e.onPayExecute({asset:r,amount:e.currentPaymentAmount,amountWei:i,destinationToken:e.destinationToken,chainBatches:p,requiredNetFunding:l,grossFundingAmount:m,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:c,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});f&&(e.ui.setTxHash(f),e.ui.setPaymentResult(h=>({...h??{status:"processing"},txHash:f}))),o=f||void 0}else o=await Fu(e);e.ui.setPaymentResult(r=>({status:"success",txHash:r?.txHash||o||""}))}catch(o){rr(e,o)}finally{e.ui.setIsExecuting(!1)}return}if(e.isNon7702&&!e.embeddedWalletAddress&&!e.providerEmbeddedAddress){e.ui.setError("Embedded wallet is not ready for this payment source");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=I.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),o={userOverride:e.embeddedWalletAddress??e.providerEmbeddedAddress??e.address,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,requireDestinationReceipt:e.feeOnlyAction};if(t&&!e.feeOnlyAction){const b=await e.execution.buildPayChainBatches(),y=await e.execution.execute(b,e.executionTokenAddress,0n,w=>{w.txHash&&(e.ui.setPaymentResult(S=>({...S??{status:"processing"},txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,o);e.ui.setPaymentResult(w=>({status:"success",txHash:w?.txHash||y}));return}const r=e.selectedAsset?.asset;if(!r&&!e.actionProceeds)throw new Error("Select a payment source");const i=e.feeQuote?.fundingConversion?.tokenIn||e.resolvedTokenIn||r?.address||e.destinationToken.address,l=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:s,d=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,{grossFundingAmount:c,feeEstimate:m}=e.feeQuote?.fundingConversion?{grossFundingAmount:e.feeQuote.grossFundingAmount,feeEstimate:void 0}:await sr(e,{requiredNetFunding:l,buildBatches:b=>e.execution.buildPayChainBatches({fundingAmountOverride:b}).then(y=>An(y,d)),fundingToken:i,executionOptions:o}),p=e.feeQuote?.fundingBatches??An(await e.execution.buildPayChainBatches({fundingAmountOverride:c}),d,e.actionProceeds?void 0:m,{payoutAlreadyGross:!0}),f=xi(e,e.feeQuote?.fundingConversion?.tokenOut??i,c),h=e.feeOnlyAction||p.some(b=>b.tokenTransfers?.length),x=await e.execution.execute(p,i,h?c:0n,b=>{b.txHash&&(e.ui.setPaymentResult(y=>({...y,txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,{...o,...f,skipPreSubmitFeeEstimate:!0});e.ui.setPaymentResult(b=>({status:"success",txHash:b?.txHash||x}))}catch(s){rr(e,s)}finally{e.ui.setIsExecuting(!1)}}const Ti="spiceflow:source-funding";async function Tu(e){const t=()=>{if(!e.isCurrent())throw new Error("The source, amount or account changed. Review the form before retrying.")};t();const n=e.ctx;await e.run({...n,sourceFunding:void 0,onSourceFundingChange:void 0,fundingObserver:{onSending:t},execution:{...n.execution,execute:async(s,o,r,i,l,d)=>(t(),n.execution.execute(s,o,r,i,l,{...d,validateBeforeSubmit:async c=>{t(),await d?.validateBeforeSubmit?.(c),t()}}))}})}function Bu(e,t,n,s,o){if(!o.trim()||o.length>128||!I.isAddress(n)||!I.isAddress(s))throw new Error("External action recovery requires valid wallet addresses and a stable recovery key");return`spiceflow:externalSupply:${JSON.stringify([e,t,n.toLowerCase(),s.toLowerCase(),o])}`}function Xs(e){const t=localStorage.getItem(e);if(!t)return null;const n=JSON.parse(t),s=o=>!o||Number.isSafeInteger(o.chainId)&&o.chainId>0&&(!o.hash||/^0x[0-9a-f]{64}$/i.test(o.hash));if(n.version!==2||n.scope!==e||!I.isAddress(n.destinationToken)||!Number.isInteger(n.destinationDecimals)||n.destinationDecimals<0||n.destinationDecimals>255||typeof n.sourceKey!="string"||typeof n.routeSubmitted!="boolean"||n.sourceFunding!==void 0&&!Ci(n.sourceFunding)||!["funding","routing","action","complete"].includes(n.phase)||!Number.isInteger(n.confirmedCalls)||n.confirmedCalls<0||n.amount!==void 0&&!/^[1-9][0-9]*$/.test(n.amount)||!s(n.pendingCall)||n.calls!==void 0&&(!Array.isArray(n.calls)||n.calls.length===0||n.calls.some(o=>!I.isAddress(o.to)||!/^[0-9]+$/.test(o.value)||!/^0x(?:[0-9a-f]{2})*$/i.test(o.data)))||n.confirmedCalls>(n.calls?.length??0)||n.phase==="complete"&&(n.confirmedCalls!==n.calls?.length||n.pendingCall||n.sourceFunding?.pending)||n.pendingCall&&(n.phase!=="action"||n.confirmedCalls>=(n.calls?.length??0))||["action","complete"].includes(n.phase)&&(!n.amount||!n.calls)||n.route&&(typeof n.route.actionId!="string"||!/^[a-zA-Z0-9_-]+$/.test(n.route.actionId)||n.route.intentId!==`${n.route.actionId}/${n.route.intentIndex}`||!Number.isInteger(n.route.intentIndex)||n.route.intentIndex<0||!Array.isArray(n.route.spicenetSteps)||n.route.spicenetSteps.length===0||n.route.spicenetSteps.some(o=>typeof o!="boolean")))throw new Error("Saved external action is invalid or unsupported; recovery is required before starting another supply");return n}function ir(e){return{destinationToken:e.destinationToken,destinationDecimals:e.destinationDecimals,phase:e.phase,confirmedCalls:e.confirmedCalls,totalCalls:e.calls?.length??0,amount:e.amount,requiresRecovery:!!(e.sourceFunding?.pending&&!e.sourceFunding.pending.hash||e.pendingCall&&!e.pendingCall.hash||e.routeSubmitted&&!e.route&&e.phase==="routing")}}function Bi(e,t){return!t||t.routeSubmitted||t.route||t.pendingCall||t.confirmedCalls||t.sourceFunding?.pending||!["funding","routing"].includes(t.phase)?!1:(localStorage.setItem(`spiceflow:archivedSourceSupply:${Date.now()}:${crypto.randomUUID()}`,JSON.stringify(t)),localStorage.removeItem(e),window.dispatchEvent(new Event("spiceflow:source-funding")),!0)}async function ju(e){return navigator.locks?navigator.locks.request(e,{ifAvailable:!0},async t=>{if(!t)return!1;const n=Xs(e);if(!n||n.routeSubmitted||n.route||n.pendingCall||n.confirmedCalls||!["funding","routing"].includes(n.phase))return!1;if(n.sourceFunding?.pending){if(!n.sourceFunding.pending.hash)return!1;const s=JSON.parse(n.sourceFunding.identity),o=JSON.parse(e.slice(25));if(!Array.isArray(s)||!g.addressesEqual(s[0],o[2])||!g.addressesEqual(s[1],o[3])||!I.isAddress(s[2])||!Number.isSafeInteger(s[3]))throw new Error("Saved funding identity is invalid");await er({identity:n.sourceFunding.identity,state:n.sourceFunding,reconcileOnly:!0,recipient:o[3],tokenAddr:s[2],isNative:s[16]===!0||A.isNativeToken(s[2]),sourceClient:g.getClientForChain(s[3]),requiredAmount:0n,createWallet:async()=>{throw new Error("Reconciliation cannot request funding")},onState:r=>{n.sourceFunding=r,localStorage.setItem(e,JSON.stringify(n))}})}return Bi(e,n)}):!1}function Ru(e){const t=Xs(e);if(t&&t.phase!=="complete")throw new Error("Finish the pending external action before starting another supply");localStorage.removeItem(e)}function Du(e,t,n){const s=[],o=(r,i,l)=>{l>0n&&s.push(A.isNativeToken(r)?{to:i,value:l,data:"0x"}:{to:r,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[i,l]})})};return t.feeExecutionMode==="user-transfer"&&t.feeBreakdown&&(o(t.feeToken??t.destinationToken,A.SPICE_PLATFORM_FEE_RECIPIENT,t.feeBreakdown.spicenetFee),o(t.feeToken??t.destinationToken,A.SPICE_GAS_FEE_RECIPIENT,t.feeBreakdown.gasFee+t.feeBreakdown.bridgeFee)),o(t.destinationToken,n,e),s}const lr=e=>e.map(t=>({to:t.to.toLowerCase(),data:t.data.toLowerCase(),value:t.value.toString()})),ji=e=>JSON.stringify([e.selectedAsset?.asset.address.toLowerCase(),e.selectedAsset?.asset.chainId,e.selectedAsset?.asset.decimals,e.selectedAsset?.asset._source,e.selectedAsset?.asset._fundingWallet,e.selectedAsset?.amount]);async function Nu(e){if(!navigator.locks)throw new Error("This browser cannot safely resume external wallet actions");await navigator.locks.request(e.scope,{ifAvailable:!0},async t=>{if(!t)throw new Error("This external action is already running in another tab");const{ctx:n,scope:s,buildActionCalls:o,onRecord:r}=e,i=()=>{if(e.isCurrent?.()===!1)throw new Error("Restore the original account before resuming this action")};i();const l=n.externalWalletAddress,d=n.embeddedWalletAddress??n.providerEmbeddedAddress,c=JSON.parse(s.slice(25));if(!s.startsWith("spiceflow:externalSupply:")||!Array.isArray(c)||c.length!==5||c[1]!==n.resolvedChainId||!g.addressesEqual(c[2],l)||!g.addressesEqual(c[3],d))throw new Error("Restore the pending action's original wallets and network before resuming");if(!l||!d||!n.externalWallet)throw new Error("Connect the external wallet and its Spicenet account");const m=Xs(s);if(n.isPayMode||A.isNativeToken(n.destinationToken.address))throw new Error("External action execution currently supports exact-input supplies into ERC20 destination actions");let p=m;const f=b=>o(BigInt(b),{userAddress:l,executorAddress:l,chainId:n.resolvedChainId,destinationToken:n.destinationToken.address}),h=()=>{localStorage.setItem(s,JSON.stringify(p)),r({...p})};if(p){if(!g.addressesEqual(p.destinationToken,n.destinationToken.address)||p.destinationDecimals!==n.destinationToken.decimals)throw new Error("Restore the pending action's destination token before resuming");if(p.calls&&JSON.stringify(lr(await f(p.amount)))!==JSON.stringify(p.calls))throw new Error("The intended action changed; restore its original configuration before resuming");if(ir(p).requiresRecovery)throw new Error("A transaction submission is unconfirmed; recover it before retrying to avoid spending twice");if(p.pendingCall&&p.pendingCall.chainId!==n.resolvedChainId)throw new Error("Saved external action chain is invalid");if(p.phase==="complete"){n.ui.setTxHash(p.lastHash??null),n.ui.setStep("success");return}if(!p.routeSubmitted&&p.phase!=="action"&&p.sourceKey!==ji(n))throw new Error("Restore the pending action's source and amount before resuming")}else{if(!n.selectedAsset||n.parsedAmount<=0)throw new Error("Select an asset and enter an amount");p={version:2,scope:s,destinationToken:n.destinationToken.address,destinationDecimals:n.destinationToken.decimals,sourceKey:ji(n),phase:"funding",confirmedCalls:0,routeSubmitted:!1},h()}const x=async b=>{if(b<=0n)throw new Error("The route did not fund a positive action amount");const y=lr(await f(b.toString()));if(!y.length)throw new Error("No external action calls configured");p.amount=b.toString(),p.calls=y,h()};try{if(p.phase!=="action")if(p.route){n.ui.setStatusMsg("Resuming the existing funding route...");const y=p.route;await Ao({...y,totalSteps:y.spicenetSteps.length,isSpicenetStep:w=>y.spicenetSteps[w],maxPolls:180}),p.phase="action",h()}else if(n.selectedAsset&&en(n.selectedAsset.asset,n.isNon7702)&&n.isSourceDestToken)await x(I.parseUnits(n.selectedAsset.amount,n.destinationToken.decimals)),p.phase="action",h();else{let y;const w={onSending:async()=>{if(i(),!(await(await n.externalWallet.getEthereumProvider()).request({method:"eth_accounts"})).some(v=>g.addressesEqual(v,l)))throw new Error("Restore the original external wallet before funding");p.phase="funding",h()}},S=async v=>{let k=0n;for(const C of v)if(C.chainId===n.resolvedChainId){for(const E of C.calls)if(g.addressesEqual(E.to,n.destinationToken.address))try{const F=I.decodeFunctionData({abi:I.erc20Abi,data:E.data});F.functionName==="transfer"&&g.addressesEqual(F.args[0],l)&&(k+=F.args[1])}catch{}}await x(k)};if(await Zs({...n,sourceFunding:p.sourceFunding,onSourceFundingChange:v=>{p.sourceFunding=v,h()},fundingObserver:w,ui:{...n.ui,setIsExecuting:()=>{},setStep:v=>{v!=="success"&&n.ui.setStep(v)},setError:v=>{typeof v=="string"&&v&&(y=v)}},execution:{...n.execution,execute:async(v,k,C,E,F,B)=>{i(),await S(v),p.phase="routing",h();const j=await n.execution.execute(v,k,C,T=>{T.step==="submitting"&&(p.routeSubmitted=!0,h()),T.actionId&&T.intentId&&T.intentIndex!==void 0&&(p.route={actionId:T.actionId,intentId:T.intentId,intentIndex:T.intentIndex,spicenetSteps:v.map(R=>R.domain==="spicenet")},h()),n.execution.onProgress({...T,step:T.step==="success"?"executing":T.step})},F,{...B,adjustBatchesForEstimate:B?.adjustBatchesForEstimate?async T=>{const R=await B.adjustBatchesForEstimate(T);return R&&await S(R),R}:void 0});return p.phase="action",h(),j}}}),y)throw new Error(y);if(ir(p).phase!=="action")throw new Error("Funding route has not completed; resume it before continuing")}const b=await f(p.amount);if(JSON.stringify(lr(b))!==JSON.stringify(p.calls))throw new Error("The intended external action changed during funding");if(p.pendingCall){const y=await Ns({client:g.getClientForChain(p.pendingCall.chainId),hash:p.pendingCall.hash,call:b[p.confirmedCalls],onRepriced:v=>{p.pendingCall.hash=v,h()},onCancelled:()=>{delete p.pendingCall,h()}}),w=y.receipt,S=y.hash;if(delete p.pendingCall,w.status==="success"&&(p.confirmedCalls++,p.lastHash=S),h(),w.status!=="success")throw new Error("External action transaction reverted; retry when ready")}if(p.confirmedCalls<b.length){const{extWc:y,viemChain:w}=await On({wallet:n.externalWallet,account:l,chainId:n.resolvedChainId}),S=p.confirmedCalls;n.ui.setStatusMsg(`Confirm the remaining ${b.length-S} action transactions in your external wallet`),await Mo({extWc:y,client:g.getClientForChain(n.resolvedChainId),calls:b.slice(S),viemChain:w,errorMessage:"External action transaction reverted",observer:{onSending:async()=>{if(i(),!(await y.getAddresses()).some(v=>g.addressesEqual(v,l)))throw new Error("Restore the original external wallet before resuming");p.pendingCall={chainId:n.resolvedChainId},h()},onSubmitted:(v,k)=>{p.pendingCall.hash=k,h()},onConfirmed:(v,k)=>{p.confirmedCalls=S+v+1,p.lastHash=k,delete p.pendingCall,h()},onRejected:()=>{delete p.pendingCall,h()},onReverted:()=>{delete p.pendingCall,h()}}})}p.phase="complete",h(),n.ui.setTxHash(p.lastHash??null),n.ui.setStep("success"),n.ui.setStatusMsg("External wallet action confirmed")}finally{e.recovery==="balance"&&Bi(s,p)&&r(null)}})}function Mu(e){const t=e.chainTokens??e.chainTokenConfig;if(Array.isArray(t))return t.filter(n=>typeof n=="string");if(t&&typeof t=="object")return t}const ms=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:s})=>{const o=u.useContext(g.SpiceFlowProviderContext),r=o?.apiUrl||g.RELAYER_API_URL,[i,l]=u.useState([]),[d,c]=u.useState(!1),[m,p]=u.useState(null),[f,h]=u.useState(!1),x=u.useRef(!1),b=u.useRef(!1),y=t??o?.supportedChainIds,w=y?JSON.stringify([...y].sort()):"",S=u.useCallback(async(C=!1)=>{if(!e||!n){l([]),h(!1),x.current=!1;return}if(!b.current){b.current=!0,!x.current&&!C&&c(!0),p(null);try{const E=await g.relayerFetch(`${r}/wallets/${e}/balance`,{cache:"no-store"});if(!E.ok)throw new Error(`Failed to fetch balance: ${E.status}`);const F=await E.json();if(F.balances&&Array.isArray(F.balances)){const B=F.balances.map(j=>Ec({receiptToken:typeof j.receiptToken=="string"?j.receiptToken:void 0,tokenName:String(j.tokenName??""),balanceAvailable:String(j.balanceAvailable??"0"),chainTokens:Mu(j),decimals:typeof j.decimals=="number"?j.decimals:void 0,balanceUsd:typeof j.balanceUsd=="number"||typeof j.balanceUsd=="string"?j.balanceUsd:null},y)).filter(j=>j!==null);l(B),h(B.length>0),x.current=!0}else l([]),h(!1)}catch(E){const F=E instanceof Error?E.message:"Failed to fetch balance";p(F),console.error("Error fetching Spice assets:",E),x.current||(l([]),h(!1))}finally{c(!1),b.current=!1}}},[e,n,w,r]);u.useEffect(()=>{n&&e&&(x.current=!1,S(!1))},[e,n,w]),u.useEffect(()=>{if(!n||!e||!s)return;const C=setInterval(()=>{S(!0)},s);return()=>clearInterval(C)},[e,n,s,w]);const v=u.useCallback(C=>i.filter(E=>E.chainId===C),[i]),k=u.useCallback(async()=>{await S(!0)},[S]);return{assets:i,loading:d,error:m,hasBalance:f,refetch:k,getAssetsByChain:v}};async function Ri(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[s,o,r]=await Promise.all([on.readContract(e,{address:t,abi:I.erc20Abi,functionName:"decimals"}).catch(()=>18),on.readContract(e,{address:t,abi:I.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),on.readContract(e,{address:t,abi:I.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);return{decimals:Number(s),symbol:o,name:r,logoURI:void 0}}function Di(e,t,n){const s=g.addressesEqual(e.address,t),o=e.chainId===n,r=e._source==="wallet";return r&&s&&o?0:r&&o?1:!r&&s?2:!r&&o?3:4}function Xn(e,t){return!t||t.length===0||e.isNative&&t.some(A.isNativeToken)||t.some(n=>g.addressesEqual(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const s=Rn(n);return s?t.some(o=>g.addressesEqual(o,s.address)):!1})}function Ou(e,t,n){return e._source!=="wallet"?!0:e.chainId===t&&Xn(e,n)}function cr(e,t,n){let{symbol:s,name:o,logoURI:r}=t;const i=g.addressesEqual(e.address,n.address)&&e.chainId===n.chainId;i&&n.logoURI&&(r=n.logoURI),i&&!e.configToken&&s==="TOKEN"&&(s=n.symbol,o=n.symbol);const l=parseFloat((Number(t.balance)/Math.pow(10,t.decimals)).toFixed(6));return{address:e.address,name:o,symbol:s,decimals:t.decimals,balance:t.balance,balanceFormatted:l,balanceUsd:0,logoURI:r,isNative:A.isNativeToken(e.address),chainId:e.chainId}}function Ni(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:s,enabled:o,includeExternalWalletAssets:r=!1,includeCrossChainEmbeddedAssets:i=!1}=e,l=u.useContext(g.SpiceFlowProviderContext),d=(l?.mode||"7702")!=="7702",c=l?.embeddedWalletAddress,{externalAddress:m,embeddedAddress:p}=g.useProviderWallets(),f=c||p,{assets:h,refreshAssets:x,loading:b,error:y}=mn({address:m,supportedChains:s??[],fetchBalances:fn,enabled:o&&r&&!!m,refreshInterval:15e3}),{assets:w,refetch:S}=ms({address:f,supportedChains:s,enabled:o&&(!d||i)&&!!f,refetchInterval:3e4}),v=u.useMemo(()=>d&&!i?[]:w.filter(V=>Xn(V,n)),[w,n,d,i]),k=d?m:f,C=u.useMemo(()=>i?Array.from(new Set([t.chainId,...s??[]])):[t.chainId],[t.chainId,s,i]),E=o&&(!d||i)&&!!f&&!l?.isWhitelistGateActive,{assets:F,refreshAssets:B,loading:j,error:T}=mn({address:E?f:void 0,supportedChains:C,fetchBalances:fn,enabled:E,refreshInterval:3e4}),R=u.useMemo(()=>{const V=new Set,G=[],J=U=>{if(!U)return;const L=U.toLowerCase();V.has(L)||(V.add(L),G.push(I.getAddress(U)))};if(J(t.address),n)for(const U of n)J(U);return G},[d,t.address,n]),D=u.useMemo(()=>R.map(V=>V.toLowerCase()).sort().join(","),[R]),M=u.useMemo(()=>JSON.stringify([...s||[]].sort()),[s]),[P,q]=u.useState([]),z=u.useRef(0),X=u.useRef(async()=>{}),N=u.useCallback(async()=>{if(!o||!k||R.length===0){z.current++,q([]);return}const V=++z.current,G=I.getAddress(k),J=d?s&&s.length>0?s:[t.chainId]:[t.chainId],U=[];for(const ue of R){const re=ue.toLowerCase();if(re===A.ZERO_ADDRESS)continue;if(A.isNativeToken(re)){const ie=g.addressesEqual(re,t.address)&&!J.includes(t.chainId)?[t.chainId,...J]:J;for(const ce of ie){const _=g.getChainConfig(ce)?.supportedTokens?.find(Ce=>A.isNativeToken(Ce.address));_&&U.push({address:ue,chainId:ce,configToken:{decimals:_.decimals,symbol:_.symbol,name:_.name,logo:_.logo}})}continue}if(re===t.address.toLowerCase()){const ie=g.getChainConfig(t.chainId)?.supportedTokens?.find(ce=>g.addressesEqual(ce.address,re));U.push({address:ue,chainId:t.chainId,configToken:ie?{decimals:ie.decimals,symbol:ie.symbol,name:ie.name,logo:ie.logo}:void 0});continue}let se=!1;for(const ie of J){const ce=g.getChainConfig(ie)?.supportedTokens?.find(_=>g.addressesEqual(_.address,re));if(ce){U.push({address:ue,chainId:ie,configToken:{decimals:ce.decimals,symbol:ce.symbol,name:ce.name,logo:ce.logo}}),se=!0;break}}se||U.push({address:ue,chainId:t.chainId})}const L=new Map;for(const ue of U){const re=L.get(ue.chainId)||[];re.push(ue),L.set(ue.chainId,re)}const O=async(ue,re)=>{try{const se=await on.readContract(ue,{address:re.address,abi:I.erc20Abi,functionName:"balanceOf",args:[G]}),{decimals:ie,symbol:ce,name:_,logoURI:Ce}=await Ri(ue,re.address,re.configToken);return cr(re,{decimals:ie,symbol:ce,name:_,logoURI:Ce,balance:se},t)}catch{return null}},ee=await Promise.all(Array.from(L.entries()).map(async([ue,re])=>{let se;try{se=g.getClientForChain(ue)}catch{return[]}const ie=re.filter(ne=>A.isNativeToken(ne.address)),ce=re.filter(ne=>!A.isNativeToken(ne.address)),_=await Promise.all(ie.map(async ne=>{const Q=await se.getBalance({address:G}).catch(()=>0n),te=g.getChainConfig(ue)?.nativeCurrency;return cr(ne,{decimals:ne.configToken?.decimals??te?.decimals??18,symbol:ne.configToken?.symbol??te?.symbol??"ETH",name:ne.configToken?.name??te?.name??"Ether",logoURI:ne.configToken?.logo,balance:Q},t)}));if(ce.length===0)return _;const Ce=[],W=[];for(const ne of ce){const Q=Ce.length;Ce.push({address:ne.address,abi:I.erc20Abi,functionName:"balanceOf",args:[G]}),ne.configToken||Ce.push({address:ne.address,abi:I.erc20Abi,functionName:"decimals"},{address:ne.address,abi:I.erc20Abi,functionName:"symbol"},{address:ne.address,abi:I.erc20Abi,functionName:"name"}),W.push({start:Q,item:ne})}let ae=null;try{ae=await se.multicall({contracts:Ce})}catch{ae=null}if(ae){const ne=W.map(({start:Q,item:te})=>{const be=ae[Q],$=be?.status==="success"?be.result:0n;let Se,ct,xe,pt;if(te.configToken)Se=te.configToken.decimals,ct=te.configToken.symbol,xe=te.configToken.name,pt=te.configToken.logo;else{const Me=ae[Q+1],Ue=ae[Q+2],Xe=ae[Q+3];Se=Me?.status==="success"?Number(Me.result):18,ct=Ue?.status==="success"?Ue.result:"TOKEN",xe=Xe?.status==="success"?Xe.result:ct}return cr(te,{decimals:Se,symbol:ct,name:xe,logoURI:pt,balance:$},t)});return[..._,...ne]}const he=await Promise.all(ce.map(ne=>O(se,ne)));return[..._,...he.filter(ne=>ne!==null)]}));V===z.current&&q(ee.flat())},[o,d,k,D,M,t.address,t.chainId,t.symbol,t.logoURI]);u.useEffect(()=>{X.current=N},[N]),u.useEffect(()=>{if(!o){q([]);return}X.current();const V=setInterval(()=>{X.current()},15e3);return()=>clearInterval(V)},[o,d,k,D,M,t.address,t.chainId]);const H=u.useCallback(()=>{N(),B(),r&&x()},[N,r,x,B]);return{displayAssets:u.useMemo(()=>{const V=[],G=new Set,J=(L,O)=>{const ee=`${O}:${L.chainId}:${A.normalizeNativeTokenAddress(L.address).toLowerCase()}`;G.has(ee)||(G.add(ee),V.push({...L,_source:"wallet",_fundingWallet:O,displayChainName:`${g.getChainName(L.chainId)} \xB7 ${O==="external"?"Wallet":"Embedded wallet"}`}))};for(const L of P)L.balance>0n&&J(L,g.addressesEqual(k,f)?"embedded":"external");for(const L of F)L.balance>0n&&Xn(L,n)&&J(L,"embedded");if(r)for(const L of h)L.balance>0n&&Xn(L,n)&&J(L,"external");for(const L of v)V.push({...L,_source:"spice"});const U=t.address.toLowerCase();return V.sort((L,O)=>Di(L,U,t.chainId)-Di(O,U,t.chainId)),V},[P,k,f,F,h,v,r,d,n,t.address,t.chainId]),loading:b||j,error:y||T,filteredSpiceAssets:v,walletAssets:P,embeddedWalletAddress:f,externalAddress:m,isNon7702:d,refreshSpiceAssets:S,refreshWalletAssets:H}}function dr(e,t,n){return Zo({executorAddress:n,aerodrome:!1,oneInch:e?.includeDefaults===!1?{chainIds:[]}:void 0,customVenues:t})}const Mi=Kn(),Pu=dr(void 0,Mi.input);async function Wu(e){const t=await(e.liquidityVenues||e.executorAddress?dr(e.liquidityVenues,Kn(e.liquidityVenues).input,e.executorAddress):Pu).resolveSwap({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn,maxSlippage:e.maxSlippage},e.chainId,e.recipient);if(!t)throw new Error("No liquidity for this pair.");return t}function Js(e){const{direction:t,selectedAsset:n,destinationToken:s,chainId:o,recipient:r,executorAddress:i,fixedInputToken:l,paymentAmount:d,maxSlippage:c,refreshIntervalMs:m,resolveInputSwap:p,resolveExactOutputSwap:f}=e,h=u.useContext(g.SpiceFlowProviderContext)?.liquidityVenues,[x,b]=u.useState(!1),[y,w]=u.useState(null),[S,v]=u.useState(null),[k,C]=u.useState(null),[E,F]=u.useState(null),[B,j]=u.useState(null),[T,R]=u.useState(null),[D,M]=u.useState(null),[P,q]=u.useState(null),[z,X]=u.useState(null),[N,H]=u.useState(null),[V,G]=u.useState(0),[J,U]=u.useState(null),[L,O]=u.useState(null),ee=u.useRef(null),ue=u.useRef(null),re=u.useRef(0),se=u.useRef(new Map),ie=u.useCallback(()=>{re.current++,se.current.clear(),O(null),G(Ae=>Ae+1)},[]),ce=m&&m>0?m:null,_=h?JSON.stringify(h):"",Ce=u.useMemo(()=>h?Kn(h):Mi,[_]),W=u.useMemo(()=>dr(h,Ce.input,i),[Ce,i]),ae=u.useMemo(()=>Ws({executorAddress:i,customVenues:[...f?[{name:"consumer-exact-output",chainIds:[o],preferred:!0,resolve:f}]:[],...Ce.output]}),[f,o,Ce,i]);u.useEffect(()=>{se.current.clear()},[W,ae,p]);const he=u.useMemo(()=>n?.asset?l||Qt(n.asset,o):null,[n?.asset,o,l]),ne=u.useMemo(()=>n?.asset?l?[l]:Dn(n.asset,o):[],[n?.asset,o,l]),Q=u.useMemo(()=>ne.map(Ae=>Ae.toLowerCase()).join(","),[ne]),te=JSON.stringify([n?.asset.address,n?.asset.chainId,n?.asset.decimals,n?.amount,o,Q,l?.toLowerCase(),t,d]);u.useEffect(()=>{let Ae=!1;if(ue.current&&(clearTimeout(ue.current),ue.current=null),!n?.asset||ne.length<=1){X(null),H(null);return}return ue.current=setTimeout(async()=>{const nt=t==="input"?n.amount:d||"0";let st=0n;try{st=t==="input"?I.parseUnits(nt,n.asset.decimals):0n}catch{st=0n}try{const ft=await ko(n.asset,o,{requiredAmount:st,requiredAmountDecimals:n.asset.decimals});Ae||(X(ft),H(te))}catch{Ae||X(null)}},400),()=>{Ae=!0,ue.current&&(clearTimeout(ue.current),ue.current=null)}},[te]);const be=u.useMemo(()=>(N===te?z:null)??he,[z,N,te,he]),$=u.useMemo(()=>!n?.asset||!be?[]:[be,...ne.filter(Ae=>Ae.toLowerCase()!==be.toLowerCase())],[n?.asset,be,ne]),Se=u.useMemo(()=>!n?.asset||!is(n.asset.address,n.asset.chainId,s.address,s.chainId)||!be?!1:g.addressesEqual(A.normalizeNativeTokenAddress(be),A.normalizeNativeTokenAddress(s.address)),[n,s.address,s.chainId,be]),ct=be?g.addressesEqual(A.normalizeNativeTokenAddress(be),A.normalizeNativeTokenAddress(s.address)):!1,xe=t==="output"&&parseFloat(d||"0")===0,pt=!!n?.asset&&!Se&&!ct&&!xe,Me=JSON.stringify([_,t,pt,n?.asset.address,n?.asset.chainId,n?.asset.decimals,t==="input"?n?.amount:d,$.map(Ae=>Ae.toLowerCase()),o,s.address.toLowerCase(),s.chainId,s.decimals,r?.toLowerCase(),i?.toLowerCase(),l?.toLowerCase(),c,ce]),Ue=u.useMemo(()=>({}),[Me,W,ae,p,V]),Xe=L?.request===Ue&&(!ce||L.expiresAt>Date.now());return u.useEffect(()=>{if(!ce||L?.request!==Ue)return;const Ae=setTimeout(ie,Math.max(0,L.expiresAt-Date.now()));return()=>clearTimeout(Ae)},[ce,L,Ue,ie]),u.useEffect(()=>{ee.current&&clearTimeout(ee.current),U(Ue),O(null),w(null);const Ae=t==="input"?n?.amount:d,nt=parseFloat(Ae||"0");if(!pt||!Number.isFinite(nt)||nt<=0||!n?.asset||!r||$.length===0){re.current++,v(null),C(null),F(null),j(null),R(null),M(null),w(null),b(!1);return}const st=n.asset.decimals;let ft;try{ft=t==="input"?I.parseUnits(n.amount,st):I.parseUnits(d||"0",s.decimals)}catch{re.current++,w("Invalid amount"),b(!1);return}const ot=++re.current,_e=()=>ot!==re.current,Be=Te=>n.asset.chainId===o&&g.addressesEqual(n.asset.address,Te)?Promise.resolve(st):g.getTokenDecimals(o,Te);b(!0);const Ct=l?0:t==="output"?150:400,mt=async(Te,Ke,Oe)=>{for(const Y of $){const Ee=`${_}:${t}:${o}:${Y.toLowerCase()}:${s.address.toLowerCase()}:${st}:${ft.toString()}:${r.toLowerCase()}:${i?.toLowerCase()??"recipient"}:${c??"default"}:${ce??"default"}`,ye=se.current.get(Ee),Re=ye&&ye.expiresAt>Date.now()?Te(ye):void 0;if(Re)return{quote:Re,tokenIn:Y,expiresAt:ye.expiresAt};const dt=await Oe(Y);if(_e())return"stale";if(!dt)continue;const Qe=Date.now()+Math.min(ce??3e4,3e4);return se.current.set(Ee,{expiresAt:Qe,direction:t,...Ke(dt)}),{quote:dt,tokenIn:Y,expiresAt:Qe}}return null};return ee.current=setTimeout(async()=>{try{if(t==="input"){let Te=!1;const Ke=await mt(Y=>Y.resolvedSwap&&Y.inputAmount!==void 0?{swap:Y.resolvedSwap,inputAmount:Y.inputAmount}:void 0,Y=>({resolvedSwap:Y.swap,inputAmount:Y.inputAmount}),async Y=>{const Ee=Bt(ft,st,await Be(Y),"floor");if(_e()||Ee<=0n)return null;Te=!0;const ye={type:"swap",tokenIn:Y,tokenOut:s.address,amountIn:Ee,maxSlippage:c};if(p){const dt=await p(ye,o,r);if(dt)return{swap:dt,inputAmount:Ee}}const Re=await W.resolveSwap(ye,o,r);return Re?{swap:Re,inputAmount:Ee}:null});if(Ke==="stale"||_e())return;if(!Ke)throw new Error(Te?"No liquidity for this pair":"Amount is below the destination token's precision");q(Ke.quote.inputAmount),M(Ke.tokenIn),O({request:Ue,key:`${Me}:${ot}`,expiresAt:Ke.expiresAt}),R(Ke.quote.swap.amountOut),F(Ke.quote.swap),j(null);const Oe=parseFloat(I.formatUnits(Ke.quote.swap.amountOut,s.decimals));v(Oe<.01?Oe.toPrecision(4):Oe.toLocaleString(void 0,{maximumFractionDigits:6})),C(null),w(null)}else{const Te=await mt(Oe=>Oe.exactOutputSwap,Oe=>({exactOutputSwap:Oe}),async Oe=>{try{return await ae.getQuote({tokenIn:Oe,tokenOut:s.address,amountOut:ft,maxSlippage:c},o,r)}catch{return null}});if(Te==="stale"||_e())return;if(!Te)throw new Error("No liquidity for this pair");const Ke=await Be(Te.tokenIn);if(_e())return;M(Te.tokenIn),O({request:Ue,key:`${Me}:${ot}`,expiresAt:Te.expiresAt}),j(Te.quote),F(null),R(null),C(I.formatUnits(Te.quote.amountIn,Ke)),v(null),w(null)}}catch(Te){if(_e())return;const Ke=Te instanceof Error?Te.message:"Failed to get quote";w(Ke),v(null),C(null),F(null),j(null),R(null),M(null)}finally{_e()||b(!1)}},Ct),()=>{re.current++,ee.current&&clearTimeout(ee.current)}},[Ue]),{inputAmount:Xe&&t==="input"?P:null,quoteKey:Xe?L.key:null,quoteExpiresAt:Xe?L.expiresAt:null,refreshQuote:ie,isQuoting:J===Ue?x:pt,quoteError:J===Ue?y:null,estimatedOutput:Xe?S:null,estimatedInput:Xe?k:null,resolvedSwap:Xe?E:null,exactOutputSwap:Xe?B:null,quoteAmountOut:Xe?T:null,resolvedTokenIn:pt&&Xe?D??be:be,isDirect:ct,needsSwap:pt,selectedIsEquivalent:Se}}function Oi(e){const t=new Set(A.getEquivalentAddresses(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const Uu=["USDC","USDT","WETH","WBTC"];function Pi(e,t){const n=g.getChainConfig(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:A.ZERO_ADDRESS,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:t};const s=n.supportedTokens?.find(o=>o.symbol.toUpperCase()===e.toUpperCase());if(s)return{address:s.address.toLowerCase(),symbol:s.symbol,decimals:s.decimals,chainId:t}}function Cn(e,t,n){const s=g.getChainConfig(t);if(!s)return;if(n!==void 0){if(A.isNativeToken(e)&&!A.getTokenByAddress(e,n))return;const i=Jr(e,n,t);return i?{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:t}:void 0}if(A.isNativeToken(e))return;const o=Oi(e),r=s.supportedTokens?.find(i=>o.has(i.address.toLowerCase()));if(r)return{address:r.address.toLowerCase(),symbol:r.symbol,decimals:r.decimals,chainId:t}}function Wi(e){const{sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,intermediaryCandidates:r=Uu}=e;if(As(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} fronted directly`};if(s===o&&(A.isNativeToken(t.address)||!A.getTokenByAddress(t.address,s)))return{strategy:"direct-swap",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${n.symbol} on chain ${s}, no escrow`};if(Cn(t.address,o,s))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} fronted on destination, swapped to ${n.symbol}`};if(Cn(n.address,s,o))return{strategy:"source-swap",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${n.symbol} on source chain, then fronted`};for(const i of r){const l=Pi(i,s);if(!l||As(t,l)||As(n,l))continue;const d=Pi(i,o);if(d&&As(l,d))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:d,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${i} on source, fronted, then ${i} \u2192 ${n.symbol} on destination`}}throw new g.SpiceflowError("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${s}) to ${n.symbol} (chain ${o}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:n.symbol,sourceChainId:s,destinationChainId:o,candidatesChecked:r})}async function Lu(e){const{route:t,sourceAmount:n,userAddress:s,registry:o,actionCalls:r,slippage:i}=e;async function l(d,c,m,p){const f=await o.resolveSwap({type:"swap",tokenIn:c,tokenOut:m,amountIn:p,maxSlippage:i},d,s);if(!f)throw new g.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${c} \u2192 ${m} on chain ${d}. No liquidity available for this pair.`,{chainId:d,tokenIn:c,tokenOut:m,amountIn:p.toString()});return f}switch(t.strategy){case"direct-swap":{const d=await l(t.destinationChainId,t.sourceAsset.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...d.calls,...r]}],solverFrontToken:t.outputAsset,solverFrontAmount:0n,resolvedSwaps:{sourceSwap:d}}}case"direct":{const d=Cn(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(Oi(d.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:r}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{}};const c=await l(t.destinationChainId,d.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...c.calls,...r]}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{destinationSwap:c}}}case"source-swap":{const d=Cn(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!d)throw new g.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.sourceChainId,side:"source"});const c=Cn(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!c)throw new g.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on destination chain ${t.destinationChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.destinationChainId,side:"destination"});const m=await l(t.sourceChainId,t.sourceAsset.address,d.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:m.calls},{chainId:t.destinationChainId,calls:r}],solverFrontToken:c,solverFrontAmount:m.amountOutMinimum,resolvedSwaps:{sourceSwap:m}}}case"intermediary":{if(!t.intermediaryAsset)throw new g.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const d=Cn(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!d)throw new g.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${t.intermediaryAsset.symbol} (${t.intermediaryAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.intermediaryAsset.symbol,address:t.intermediaryAsset.address,chainId:t.sourceChainId,side:"source"});const c=await l(t.sourceChainId,t.sourceAsset.address,d.address,n),m=await l(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,c.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:c.calls},{chainId:t.destinationChainId,calls:[...m.calls,...r]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:c.amountOutMinimum,resolvedSwaps:{sourceSwap:c,destinationSwap:m}}}default:throw new g.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}function zu(e,t){const n=Wi({sourceAsset:e,outputAsset:t,sourceChainId:e.chainId,destinationChainId:t.chainId});if(n.strategy==="direct"||n.strategy==="direct-swap")return null;let s=n.strategy==="source-swap"?t:n.intermediaryAsset;if(!s)throw new Error("No bridge token exists for this route");if(A.isNativeToken(s.address)){const r=Ps(s.chainId),i=r&&A.getTokenByAddress(r,s.chainId);if(!i)throw new Error("No registered wrapped bridge token exists for native output");s={address:i.address,symbol:i.symbol,decimals:i.decimals,chainId:s.chainId}}const o=Cn(s.address,e.chainId,t.chainId);if(!o)throw new Error("No source-chain equivalent exists for the bridge token");return{source:e,bridgeSource:o,bridgeDestination:s}}function Ui(e,t){if(e.sourceAmountIn<=0n||e.sourceAmountInMax<e.sourceAmountIn||e.bridgeSourceMinimum<=0n||e.bridgeDestinationMinimum<=0n||e.sourceCalls.length===0)throw new Error("Invalid source funding quote");return{...e,quoteKey:JSON.stringify(e,(n,s)=>typeof s=="bigint"?s.toString():s),expiresAt:t+3e4}}async function qu(e){if(e.sourceAmountIn<=0n)throw new Error("Enter a positive source amount");const{plan:t}=e,n=await e.registry.resolveSwap({type:"swap",tokenIn:t.source.address,tokenOut:t.bridgeSource.address,amountIn:e.sourceAmountIn,maxSlippage:e.maxSlippage},t.source.chainId,e.executorAddress);if(!n||n.amountOutMinimum>n.amountOut)throw new Error("No valid source-chain swap quote");return Ui({plan:t,executorAddress:e.executorAddress,direction:"input",sourceAmountIn:e.sourceAmountIn,sourceAmountInMax:e.sourceAmountIn,bridgeSourceMinimum:n.amountOutMinimum,bridgeDestinationMinimum:Bt(n.amountOutMinimum,t.bridgeSource.decimals,t.bridgeDestination.decimals,"floor"),sourceCalls:n.calls},e.nowMs??Date.now())}async function Hu(e){if(e.bridgeDestinationAmount<=0n)throw new Error("Enter a positive bridge amount");const{plan:t}=e,n=e.nowMs??Date.now(),s=Bt(e.bridgeDestinationAmount,t.bridgeDestination.decimals,t.bridgeSource.decimals,"ceil"),o=await e.registry.getQuote({tokenIn:t.source.address,tokenOut:t.bridgeSource.address,amountOut:s,maxSlippage:e.maxSlippage},t.source.chainId,e.executorAddress);if(o.amountOut!==s)throw new Error("Source quote does not match the required bridge output");return Ui({plan:t,executorAddress:e.executorAddress,direction:"output",sourceAmountIn:o.amountIn,sourceAmountInMax:o.amountInMax,bridgeSourceMinimum:s,bridgeDestinationMinimum:Bt(s,t.bridgeSource.decimals,t.bridgeDestination.decimals,"floor"),sourceCalls:o.calls},n)}async function Li(e,t){const n=()=>{if(e.expiresAt<=(t?.nowMs??Date.now()))throw new Error("Source funding quote expired; request a fresh quote")};n();const s=e.plan.bridgeSource;if(A.isNativeToken(s.address))throw new Error("Source conversion requires a wrapped ERC20 bridge token");const o=await Fo({chainBatches:[{chainId:s.chainId,calls:e.sourceCalls}],user:e.executorAddress,token:s.address,grossAmount:e.bridgeSourceMinimum,chainAuthorizations:t?.chainAuthorizations});n();const r=Bt(o.netEscrowAmount,s.decimals,e.plan.bridgeDestination.decimals,"floor");if(r<=0n)throw new Error("Source output after fees is below the destination token's precision");return{quote:e,chainBatches:o.chainBatches,sourceGasFee:o.gasFee,sourceSpicenetFee:o.spicenetFee,bridgeSourceNet:o.netEscrowAmount,bridgeDestinationNet:r,outputCredit:o.outputCredit,quoteKey:`${e.quoteKey}:${o.gasFee}:${o.spicenetFee}:${o.netEscrowAmount}`,expiresAt:e.expiresAt}}async function Vu(e){let t=e.bridgeDestinationAmount;for(let n=0;n<5;n++){const s=await Hu({...e,bridgeDestinationAmount:t});let o;try{o=await Li(s,{nowMs:e.nowMs,chainAuthorizations:e.chainAuthorizations})}catch(r){if(!(r instanceof g.SpiceflowError)||r.code!=="INVALID_PARAMS"||r.message!=="Borrow amount is too small after gas and Spicenet fees.")throw r;const{grossAmount:i,gasFee:l,spicenetFee:d}=r.context;if(![i,l,d].every(h=>typeof h=="string"&&/^(0|[1-9][0-9]*)$/.test(h)))throw r;const c=BigInt(i),m=BigInt(l)+BigInt(d);if(c!==s.bridgeSourceMinimum||m<c)throw r;const p=Bt(e.bridgeDestinationAmount,e.plan.bridgeDestination.decimals,e.plan.bridgeSource.decimals,"ceil"),f=Bt(p+m,e.plan.bridgeSource.decimals,e.plan.bridgeDestination.decimals,"ceil");if(f<=t)throw r;t=f;continue}if(o.bridgeDestinationNet>=e.bridgeDestinationAmount)return o;t+=e.bridgeDestinationAmount-o.bridgeDestinationNet}throw new Error("Source funding fees did not converge; request a fresh quote")}function Qu(e){const t=u.useContext(g.SpiceFlowProviderContext),n=e.selectedAsset?.asset,s=!!n&&n._source==="wallet"&&n.chainId!==e.destinationToken.chainId&&!Qt(n,e.destinationToken.chainId),o=u.useMemo(()=>{if(!s||!n)return{plan:null,error:null};try{if(e.direction==="input")throw new Error("Source-chain conversion requires input-inclusive or exact-output mode");const w=v=>({name:v.symbol,equivalenceGroup:"",logo:"",swapContracts:[],network:"mainnet",...A.getTokenByAddress(v.address,v.chainId),...v}),S=zu(w(n),w(e.destinationToken));if(!S)throw new Error("No source-chain conversion route is available");return{plan:S,error:null}}catch(w){return{plan:null,error:w instanceof Error?w.message:"Source route unavailable"}}},[s,n?.address,n?.chainId,n?.decimals,e.destinationToken,e.direction]),r=u.useMemo(()=>{const w=Kn(t?.liquidityVenues);return{input:Zo({executorAddress:e.executorAddress,aerodrome:!1,oneInch:t?.liquidityVenues?.includeDefaults===!1?{chainIds:[]}:void 0,customVenues:w.input}),output:Ws({executorAddress:e.executorAddress,customVenues:w.output})}},[t?.liquidityVenues,e.executorAddress]),i=JSON.stringify([t?.network,t?.liquidityVenues,s,n?.address,n?.chainId,n?.decimals,n?._source,n?._fundingWallet,e.direction==="output"?"output":e.selectedAsset?.amount,e.destinationToken.address,e.destinationToken.chainId,e.destinationToken.decimals,e.executorAddress,e.direction,e.maxSlippage]),l=u.useRef({key:i,plans:new Map,pending:new Map,latestOutput:void 0});l.current.key!==i&&(l.current={key:i,plans:new Map,pending:new Map,latestOutput:void 0});const d=l.current,[c,m]=u.useState(0),[p,f]=u.useState(null),h=u.useCallback(async(w,S=!1)=>{if(!e.enabled||!o.plan||!e.executorAddress)throw new Error("Source funding route is not ready");const v=e.direction==="output"?String(w??0n):"input";e.direction==="output"&&w&&w>0n&&(d.latestOutput=w);const k=d.plans.get(v);if(!S&&k&&k.expiresAt>Date.now()){if(w&&k.bridgeDestinationNet<w)throw new Error("The source budget cannot cover destination funding; refresh the quote");return k}const C=d.pending.get(v);if(C)return C;const E=(async()=>{try{const F=e.direction==="output"?await Vu({plan:o.plan,executorAddress:e.executorAddress,bridgeDestinationAmount:w??0n,registry:r.output,maxSlippage:e.maxSlippage}):await Li(await qu({plan:o.plan,executorAddress:e.executorAddress,sourceAmountIn:I.parseUnits(e.selectedAsset.amount,n.decimals),registry:r.input,maxSlippage:e.maxSlippage}));if(l.current!==d)throw new Error("Source quote changed before funding completed");return d.plans.set(v,F),f(null),m(B=>B+1),F}catch(F){throw l.current===d&&f({key:i,message:F instanceof Error?F.message:"Unable to quote source funding"}),F}finally{d.pending.delete(v)}})();return d.pending.set(v,E),E},[e.enabled,o.plan,e.executorAddress,e.direction,e.selectedAsset?.amount,e.maxSlippage,r,d]);u.useEffect(()=>{if(!s||!e.enabled||!o.plan)return;const w=()=>{const v=e.direction==="output"?e.outputAmount??d.latestOutput:void 0;if(e.direction==="output"&&v===void 0)return;const k=e.direction==="output"?String(v):"input",C=d.plans.get(k);h(v,!!C&&C.expiresAt-Date.now()<=(e.direction==="input-inclusive"?2e4:1e4)).catch(()=>{})};w();const S=setInterval(w,5e3);return()=>clearInterval(S)},[s,e.enabled,e.direction,e.outputAmount,o.plan,h]),u.useEffect(()=>{if(!e.enabled)return;const w=e.direction==="output"?String(e.outputAmount??d.latestOutput??0n):"input",S=d.plans.get(w)?.expiresAt;if(!S||S<=Date.now())return;const v=setTimeout(()=>m(k=>k+1),S-Date.now());return()=>clearTimeout(v)},[e.enabled,e.direction,e.outputAmount,d,c]);const x=w=>{const S=d.plans.get(e.direction==="output"?String(w??0n):"input");return S&&S.expiresAt>Date.now()?S:null},b=d.plans.get("input")??null,y=u.useMemo(()=>{if(!o.plan||e.direction!=="output"&&!b)return null;const w=o.plan.bridgeDestination;return{amount:b?I.formatUnits(b.bridgeDestinationNet,w.decimals):"1",asset:{address:w.address,chainId:w.chainId,decimals:w.decimals,symbol:w.symbol,name:w.symbol,isNative:A.isNativeToken(w.address),_source:"spice",balance:b?.bridgeDestinationNet??0n,balanceFormatted:0,balanceUsd:0}}},[o.plan,e.direction,b?.quoteKey]);return{required:s,plan:o.plan,key:i,virtualSelectedAsset:y,prepare:h,getPrepared:x,error:o.error??(p?.key===i?p.message:null),isCurrent:()=>l.current===d}}function ur(e){const{enabled:t,actionExecution:n,destinationToken:s,selectedAsset:o,paymentAmount:r="0",amountDirection:i="input",sourceChains:l,supportedSourceAssets:d,includeExternalWalletAssets:c=!1,includeCrossChainEmbeddedAssets:m=!1,sourceFundingRecoveryKey:p="generic",sourceFundingRecovery:f="resume",feeOnlyAction:h=!1,actionProceeds:x,buildActionCalls:b,feeExecutionMode:y=e.feeOnlyAction?"backend-transfer":"user-transfer",buildSpicenetBatch:w,onPayExecute:S,recipient:v,maxSlippage:k,resolveInputSwap:C,resolveExactOutputSwap:E,prependSourceEscrow:F=!1,isZeroAmountPay:B=!1,onSuccess:j,onError:T}=e,R=i==="output",D=x&&(!h||A.isNativeToken(s.address))?"Action proceeds require a fee-only ERC20 action":h&&(!R||Number(r)!==0||n||S||F)?"Fee-only actions require zero-output mode and SDK-managed embedded execution":null,M=u.useRef(D);M.current=D;const P=i==="input-inclusive",q=R?"output":"input",z=s.chainId,X=u.useRef(t);X.current=t;const N=u.useContext(g.SpiceFlowProviderContext),H=(N?.mode||"7702")!=="7702",V=!!N?.isWhitelistGateActive,G=!!N?.isWhitelistConfigured&&N?.isUserWhitelisted!==!0,{address:J,isConnected:U,isReady:L,isAuthenticated:O,provider:ee}=g.useWallet(),{execute:ue,estimate:re}=ds(),{externalWallet:se,embeddedAddress:ie,activeWallet:ce,activeAddress:_}=g.useProviderWallets(),Ce=N?.externalWalletAddress,W=N?.embeddedWalletAddress||ie,ae=u.useRef({resolve:x?.resolve,token:x?.token,owner:W,buildActionCalls:b,resolver:E,revision:0});(ae.current.owner!==W||ae.current.resolve!==x?.resolve||ae.current.token!==x?.token||ae.current.buildActionCalls!==b||ae.current.resolver!==E)&&(ae.current={resolve:x?.resolve,token:x?.token,owner:W,buildActionCalls:b,resolver:E,revision:ae.current.revision+1});const he=ae.current.revision,ne=JSON.stringify([he,s.address,s.chainId,s.decimals,r,i,v,h,y,o?.asset.decimals,o?.asset.address,o?.asset.chainId,o?.asset.receiptTokenId,o?.asset._source,o?.asset._fundingWallet,o?.asset.chainTokens,k,N?.liquidityVenues]),Q=u.useRef(ne);Q.current=ne;const te=u.useMemo(()=>l??N?.supportedChainIds??[],[l,N?.supportedChainIds]),be=u.useMemo(()=>{if(V)return[];if(d)return d;const K=N?.allowedTokens;if(!K||K.length===0)return;const we=new Set(K.map(It=>It.toLowerCase())),Ye=[],Ne=new Set;for(const It of te){const _t=g.getChainConfig(It);for(const Tn of _t?.supportedTokens??[]){if(!we.has(Tn.symbol.toLowerCase()))continue;const jr=Tn.address.toLowerCase();Ne.has(jr)||(Ne.add(jr),Ye.push(Tn.address))}}return Ye},[d,N?.allowedTokens,te,V]),$=Ni({destinationToken:s,supportedSourceAssets:be,sourceChains:te,includeExternalWalletAssets:c,includeCrossChainEmbeddedAssets:m,enabled:t&&(H?!!Ce:!!W)}),{displayAssets:Se,filteredSpiceAssets:ct,embeddedWalletAddress:xe}=$,pt=u.useMemo(()=>V||R||H?Se:Se.filter(K=>c&&K._fundingWallet==="external"||m&&K._fundingWallet==="embedded"&&Xn(K,be)||Ou(K,z,be)),[Se,V,R,H,c,m,z,be]),[Me,Ue]=u.useState(!1),[Xe,Ae]=u.useState(null),[nt,st]=u.useState("idle"),[ft,ot]=u.useState(""),[_e,Be]=u.useState(null),[Ct,mt]=u.useState(!1),[Te,Ke]=u.useState(null),[Oe,Y]=u.useState(null),Ee=Oe,[ye,Re]=u.useState(!1),[dt,Qe]=u.useState(!1),[yt,lt]=u.useState(null),[qt,Lt]=u.useState(null),Nt=u.useRef(T);Nt.current=T;const Je=u.useCallback(K=>{Ae(K),typeof K=="string"&&K&&Nt.current?.(new Error(K),g.getRelayerErrorDetail(K))},[]),pe=u.useRef(o);pe.current=o;const Pe=u.useRef(!1),at=u.useRef(null),ut=u.useRef(null),ve=u.useRef(null),fe=u.useRef(null),He=u.useRef(null),it=u.useRef(null),Ge=u.useRef(null),[,Ie]=u.useState(0),Et=u.useMemo(()=>{if(!n)return{scope:null,error:null};if(R||F||A.isNativeToken(s.address))return{scope:null,error:"External action execution requires an ERC20 input supply with SDK-managed funding"};const K=xe??ie;if(!Ce||!K)return{scope:null,error:null};try{return{scope:Bu(N?.network??"testnet",z,Ce,K,n.recoveryKey),error:null}}catch(we){return{scope:null,error:g.sanitizeError(we,"External action recovery is unavailable")}}},[n?.recoveryKey,!!n,R,F,s.address,xe,ie,Ce,N?.network,z]),De=Et.scope,[bt,jt]=u.useState({scope:null,record:null,error:null});u.useEffect(()=>{const K=()=>{try{jt({scope:De,record:De?Xs(De):null,error:null})}catch(Ne){jt({scope:De,record:null,error:g.sanitizeError(Ne,"Saved action needs recovery")})}},we=()=>{K(),f==="balance"&&De&&ju(De).then(Ne=>{Ne&&(K(),$.refreshWalletAssets(),$.refreshSpiceAssets())}).catch(Ne=>console.warn("[useSpiceSupply] external funding reconciliation pending",Ne))};we(),st("idle"),ot(""),Be(null),Ae(null),window.addEventListener("storage",we),window.addEventListener(Ti,we);const Ye=f==="balance"?setInterval(we,15e3):void 0;return()=>{clearInterval(Ye),window.removeEventListener("storage",we),window.removeEventListener(Ti,we)}},[De,f]);const Ht=bt.scope===De,zt=Ht?bt.record:null,Pt=zt?ir(zt):null,$e=Et.error??(Ht?bt.error:null),et=u.useRef({actionExecution:n,scope:De,error:$e,buildActionCalls:b});et.current={actionExecution:n,scope:De,error:$e,buildActionCalls:b};const Rt=u.useCallback((K,we)=>{if(!n)return b(K,we);if(!Ce)throw new Error("Connect the external wallet before supplying");return Du(K,we,Ce)},[!!n,b,Ce]),Yt=u.useCallback(()=>{fe.current=null,Je(null),lt(null),Qe(!1)},[Je]),tn=o?`${o.asset.address}:${o.asset.chainId}:${o.asset._source}:${o.asset._fundingWallet}:${o.amount}`:"";u.useEffect(()=>{Yt()},[tn,r,Yt]);const Ft=(n?void 0:v)??xe??ie??J,ge=Qu({enabled:t&&!Me,selectedAsset:o,destinationToken:s,executorAddress:xe??ie,direction:i,outputAmount:R?Oe?.grossAmount:void 0,maxSlippage:k}),qe=u.useMemo(()=>({}),[ne,tn,ge.key,Ft,C,E,w,_,Ce]),xt=u.useRef(qe);xt.current=qe;const Wt=ge.getPrepared(R?Oe?.grossAmount:void 0),Fe=u.useRef(null),Ut=P&&ge.required;(!Ut||Fe.current?.scope!==qe)&&(Fe.current=null),Ut&&(!Fe.current||Fe.current.plan.expiresAt<=Date.now()||it.current?.sourcePlan===Fe.current.plan)&&(Fe.current=Wt&&ge.virtualSelectedAsset?{scope:qe,plan:Wt,selection:ge.virtualSelectedAsset}:null);const Ze=Ut?Fe.current?.plan??null:Wt,Xt=Ut&&Ze&&Ze.expiresAt>Date.now()?null:ge.error,tt=Ut?Fe.current?.selection??null:ge.required?ge.virtualSelectedAsset:o,Mt=u.useRef(new Map),vt=Js({direction:q,selectedAsset:h?null:tt,destinationToken:s,chainId:z,recipient:Ft,executorAddress:xe??ie,fixedInputToken:ge.plan?.bridgeDestination.address,paymentAmount:r,maxSlippage:k,resolveInputSwap:C,resolveExactOutputSwap:E}),Jt=u.useMemo(()=>{if(P&&ge.required&&tt&&(!Oe||Oe.grossAmount!==Bt(I.parseUnits(tt.amount,tt.asset.decimals),tt.asset.decimals,Oe.decimals,"floor")))return null;if(!P||!tt||!Oe)return tt;if(Oe.netAmount<=0n)return null;const K=Bt(Oe.netAmount,Oe.decimals,tt.asset.decimals,"floor");return{...tt,amount:I.formatUnits(K,tt.asset.decimals)}},[P,ge.required,tt,Oe]),oe=Js({direction:q,selectedAsset:h?null:Jt,destinationToken:s,chainId:z,recipient:Ft,executorAddress:xe??ie,fixedInputToken:ge.plan?.bridgeDestination.address,paymentAmount:r,maxSlippage:k,resolveInputSwap:C,resolveExactOutputSwap:E}),Le=P?oe:vt,Ot=ge.plan?.bridgeDestination.address??(tt?tt.asset._source==="spice"?fi(tt.asset,z,s.address):Qt(tt.asset,z):null),Ve=h?{...Le,needsSwap:!1,isDirect:!0,selectedIsEquivalent:!0,isQuoting:!1,resolvedTokenIn:Ot,exactOutputSwap:null,resolvedSwap:null}:Le,{isQuoting:kt,resolvedSwap:nn,exactOutputSwap:de,resolvedTokenIn:me,isDirect:ze,needsSwap:je,selectedIsEquivalent:St}=Ve,Dt=kt||P&&vt.isQuoting||ge.required&&!tt;u.useEffect(()=>{ge.required&&R&&Oe?.grossAmount&&t&&!Me&&ge.prepare(Oe.grossAmount).catch(()=>{})},[ge.key,ge.prepare,R,Oe?.grossAmount,t,Me]);const Gt=ge.required?Ze?.quote.sourceAmountInMax??null:o&&Oe?Kt(Oe.grossAmount,Oe.decimals,o.asset.decimals):null,rt=P?vt:Ve,ht=R?parseFloat(r||"0"):parseFloat(o?.amount||"")||0,Vt=o?.asset?._source==="wallet",sn=!!o?.asset&&Vt&&o.asset.chainId!==z,Z=u.useMemo(()=>o?.asset?ct.find(K=>g.addressesEqual(K.address,o.asset.address))?.balanceFormatted??0:0,[o,ct]),le=Vt?o?.asset.balanceFormatted??0:Z,We=u.useMemo(()=>{if(!o?.asset)return!1;if(ge.required)return Gt!==null&&Gt>o.asset.balance;if(R)return Ee?Kt(Ee.grossAmount,Ee.decimals,o.asset.decimals)>o.asset.balance:St||ze?ht>o.asset.balanceFormatted:de?parseFloat(I.formatUnits(de.amountInMax,o.asset.decimals))>o.asset.balanceFormatted:!1;if(Ee){const K=Kt(Ee.grossAmount,Ee.decimals,o.asset.decimals);return Vt?K>o.asset.balance:parseFloat(I.formatUnits(K,o.asset.decimals))>le}return ht>le},[o,ge.required,Gt,R,Ee,St,ht,de,le,Vt,ze]),ke=P&&!!Ee&&Ee.netAmount===0n,gt=u.useMemo(()=>o?.asset?g.addressesEqual(o.asset.address,s.address)&&o.asset.chainId===s.chainId:!1,[o,s.address,s.chainId]),wt=!h&&gt&&o?.asset._source==="wallet"&&en(o.asset,H)&&(R||H||!!n),Tt=wt&&ht>0&&!!o?.asset,dn=G&&!wt,ln=u.useMemo(()=>ge.plan?ge.plan.bridgeDestination.address:o?.asset?je&&me?me:o.asset.chainId===z?o.asset.address:me??Qt(o.asset,z)??s.address:s.address,[o,ge.plan,s.address,je,z,me]),un=u.useCallback((K,we)=>({currentPaymentAmount:r,destinationToken:s,embeddedWalletAddress:xe,providerEmbeddedAddress:ie,externalWalletAddress:Ce,address:J,recipient:v,swapOutputRecipient:Ft,isNon7702:H,isPayMode:R,isFeeInclusiveInput:P,swapInputAmount:we.inputAmount,feeOnlyAction:h,resolvedChainId:z,buildActionCalls:Rt,feeExecutionMode:y,buildSpicenetBatch:w,selectedAsset:K&&F?{...K,asset:{...K.asset,_source:"spice",_fundingWallet:void 0}}:K,needsSwap:we.needsSwap,resolvedSwap:we.resolvedSwap,exactOutputSwap:we.exactOutputSwap,quoteAmountOut:we.quoteAmountOut,resolvedTokenIn:we.resolvedTokenIn}),[r,s,xe,ie,Ce,J,v,Ft,H,R,P,h,z,Rt,y,w,F]),At=u.useMemo(()=>un(tt,Ve),[un,tt,Ve.needsSwap,Ve.resolvedSwap,Ve.exactOutputSwap,Ve.quoteAmountOut,Ve.resolvedTokenIn,Ve.inputAmount]),Wn=u.useMemo(()=>P?un(tt,vt):At,[P,At,un,tt,vt.needsSwap,vt.resolvedSwap,vt.exactOutputSwap,vt.quoteAmountOut,vt.resolvedTokenIn,vt.inputAmount]),xs=u.useCallback(async(K,we)=>{if(!ge.required||!K.length)return K;const Ye=P&&Ze?Ze:await ge.prepare(we);if(!ge.isCurrent())throw new Error("Source funding quote expired or changed; refresh before retrying");if(Ye.bridgeDestinationNet<we)throw new Error("Source funding no longer covers the quoted destination amount");for(const[Ne,It]of Mt.current)It.expiresAt<=Date.now()&&Mt.current.delete(Ne);return Mt.current.set(Zn(Ye.chainBatches[0]),Ye),[...Ye.chainBatches,...K]},[ge.required,ge.prepare,P,Ze]),no=u.useCallback(async K=>{const we=await ii({...At,requestTimestampMs:ut.current??Date.now()},K),Ye=K?.fundingAmountOverride??At.exactOutputSwap?.amountInMax??I.parseUnits(r||"0",s.decimals);return xs(we,Ye)},[At,xs,r,s.decimals]),ys=u.useCallback(async(K,we)=>{const Ye={...K,requestTimestampMs:ut.current??Date.now()},Ne=await li(Ye,we);if(ge.required){const Tn=we?.fundingAmountOverride??I.parseUnits(K.selectedAsset?.amount||"0",K.selectedAsset?.asset.decimals??18);return xs(Ne,Tn)}if(!F||!o||Ne.length===0)return Ne;const It=R?Ye.currentPaymentAmount:o.amount;let _t=we?.fundingAmountOverride;if(_t===void 0)try{_t=I.parseUnits(It||"0",o.asset.decimals)}catch{return Ne}return _t<=0n?Ne:[Qs(o.asset.address,_t,o.asset.chainId),...Ne]},[F,o,R,ge.required,xs]),so=u.useCallback(K=>ys(At,K),[ys,At]),vr=u.useCallback(K=>ys(Wn,K),[ys,Wn]),kr=u.useCallback(K=>_o({signal:K,liquidityVenues:N?.liquidityVenues,maxSlippage:k,resolveExactOutputSwap:E,selectedAsset:Wn.selectedAsset,isPayMode:R,isFeeInclusiveInput:P,feeOnlyAction:h,actionProceeds:x,parsedAmount:ht,needsSwap:rt.needsSwap,exactOutputSwap:rt.exactOutputSwap,isNon7702:H,isSourceDestToken:gt,currentPaymentAmount:r,destinationToken:s,feeExecutionMode:y,resolvedTokenIn:rt.resolvedTokenIn,embeddedWalletAddress:xe,providerEmbeddedAddress:ie,resolvedChainId:z,isConnected:U,address:J,ready:L,authenticated:O,isDirect:rt.isDirect,resolvedSwap:rt.resolvedSwap,isQuoting:rt.isQuoting,executionTokenAddress:ln,buildPayChainBatches:no,buildSupplyChainBatches:vr,estimate:re}),[Wn,N?.liquidityVenues,k,E,R,P,h,x,ht,rt,H,gt,r,s,y,xe,ie,no,re,z,U,J,L,O,vr,ln]);u.useEffect(()=>{ve.current=kr},[kr]);const Sr=u.useMemo(()=>{if(!Tt)return null;let K;try{K=I.parseUnits(r||"0",s.decimals)}catch{return null}return{symbol:s.symbol,decimals:s.decimals,grossAmount:K,netAmount:K,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[Tt,r,s.symbol,s.decimals]),vn=(!!o?.asset||!!x)&&(ht>0||h),$t=u.useMemo(()=>!t||Me||nt!=="idle"&&nt!=="error"||!vn||Tt||!o?.asset&&!x?null:[R?"pay":"supply",i,h?"fee-only":"supply",o?.asset.address.toLowerCase()??"proceeds",o?.asset.chainId,o?.asset._source,o?.asset.receiptTokenId,o?.asset.decimals,o?.asset._fundingWallet,o?.amount,h?he:"",h?o?.asset.balance.toString():"",h?JSON.stringify(o?.asset.chainTokens??{}):"",h?JSON.stringify(N?.liquidityVenues??{}):"",h?k:"",ge.key,tt?.amount??"",r,s.address.toLowerCase(),s.chainId,s.decimals,z,rt.resolvedTokenIn?.toLowerCase()??"",rt.needsSwap?"swap":"direct",rt.isDirect?"direct-token":"routed-token",H?"non7702":"7702",gt?"source-dest":"cross-chain",rt.isQuoting?"quoting":"quoted",rt.exactOutputSwap?.amountIn?.toString()??"",rt.exactOutputSwap?.amountInMax?.toString()??"",rt.exactOutputSwap?.venue??"",rt.resolvedSwap?.amountOut?.toString()??"",rt.quoteAmountOut?.toString()??"",xe??"",ie??"",J??"",Ft??""].join("|"),[t,Me,nt,vn,x,he,N?.liquidityVenues,k,Tt,o,o?.asset.balance,ge.key,tt?.amount,R,i,h,r,s,z,rt,H,gt,xe,ie,J,Ft]),Un=!!$t&&fe.current?.key===$t,bs=qt?.key===$t?qt:null,fl=bs?bs.requiredAmount:h&&!Un?null:fe.current?.quote.fundingConversion?.sourceAmountMax??Gt,ws=!!bs||(!h||Un)&&(fe.current?.quote.fundingConversion&&o?fe.current.quote.fundingConversion.sourceAmountMax>o.asset.balance:We);as({shouldRun:t&&!Me&&(nt==="idle"||nt==="error")&&vn&&!Tt&&!rt.isQuoting&&!!$t,deps:[t,Me,nt,vn,Tt,Sr,rt.isQuoting,$t],onSkip:()=>{if(Lt(null),!t){fe.current=null,Re(!1),Qe(!1),lt(null),Y(null);return}if(Me||nt!=="idle"&&nt!=="error"){Re(!1);return}if(!vn){fe.current=null,Y(null),Re(!1),Qe(!1),lt(null);return}if(Tt){Y(Sr),Re(!1),Qe(!0),lt(null);return}rt.isQuoting&&(Re(!1),Qe(!1))},onCleanup:()=>{Re(!1),Lt(null)},delayMs:500,backgroundIntervalMs:P&&ge.required?void 0:5e3,run:async({isBackground:K,isCurrent:we,signal:Ye})=>{const Ne=$t;Lt(null),K||(lt(null),Re(!0));try{const It=await ve.current?.(Ye);if(!we())return;It&&Ne?(fe.current={key:Ne,quote:It},Y(It.preview),Qe(!0)):(fe.current=null,Y(null),Qe(!1)),lt(null)}catch(It){if(!we())return;if(It instanceof mi&&Ne){fe.current=null,Y(null),Qe(!1),Lt({key:Ne,requiredAmount:It.requiredAmount}),lt(null);return}if(K&&fe.current?.key===Ne){console.warn("[useSpiceSupply] fee refresh failed:",It),Qe(!1),lt("Fees could not be refreshed. Waiting for a new estimate.");return}const _t=g.sanitizeError(It,"Unable to calculate fees for this action.");fe.current=null,Y(null),Qe(!1),lt(_t)}finally{we()&&Re(!1)}}});const ml=u.useCallback(K=>{st({building:"building","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[K.step]||"executing"),ot(K.message),K.txHash&&Be(K.txHash)},[]);u.useEffect(()=>{t||(Je(null),Ue(!1),st("idle"),ot(""),Be(null),mt(!1),Ke(null),Y(null),Re(!1),Qe(!1),lt(null),Pe.current=!1,at.current&&(at.current.abort(),at.current=null))},[t,Je]),u.useEffect(()=>()=>{at.current?.abort(),ae.current.revision++},[]),u.useEffect(()=>{if(!R||Te?.status!=="success"||Pe.current||!J)return;Pe.current=!0;const K=pe.current;!K?.asset||K.asset._source==="wallet"||$.refreshSpiceAssets()},[R,Te?.status,J,$]),He.current={selectedAsset:ge.required?o:At.selectedAsset,sourceConversionRequired:ge.required,sourceConversion:ge.required&&tt?{virtualSelectedAsset:tt,acceptedSourceAmountInMax:Ze?.quote.sourceAmountInMax??0n,getPlan:K=>K[0]?Mt.current.get(Zn(K[0])):void 0,refreshPlan:K=>ge.prepare(K.bridgeDestinationNet,!0),isCurrent:ge.isCurrent}:void 0,parsedAmount:ht,currentPaymentAmount:r,isInsufficientBalance:ws,isPayMode:R,isFeeInclusiveInput:P,feeOnlyAction:h,validateFeeQuote:()=>{if(!X.current||Q.current!==ne)throw new Error("The fee action or route changed; refresh before retrying")},actionProceeds:x?{token:x.token,resolve:async K=>{if(!X.current||ae.current.revision!==he)throw new Error("Action proceeds quote is stale");const we=await x.resolve(K);if(!X.current||ae.current.revision!==he)throw new Error("Action proceeds quote is stale");return we}}:void 0,isNon7702:H,isSourceDestToken:gt,needsSwap:je,swapInputAmount:Ve.inputAmount,exactOutputSwap:de,selectedIsEquivalent:St,resolvedTokenIn:me,embeddedWalletAddress:xe,providerEmbeddedAddress:ie,externalWallet:se,externalWalletAddress:Ce,activeSignerWallet:ce,activeSignerAddress:_,address:J,isConnected:U,ready:L,authenticated:O,provider:ee,resolvedChainId:z,executionTokenAddress:ln,destinationToken:s,sourceFundingRecoveryKey:p,recipient:v,buildActionCalls:Rt,feeExecutionMode:y,buildSpicenetBatch:w,onPayExecute:S,onSuccess:j,feeQuote:$t&&fe.current?.key===$t?fe.current.quote:null,execution:{estimate:re,execute:ue,buildPayChainBatches:no,buildSupplyChainBatches:so,onProgress:ml},ui:{setError:Je,setStep:st,setStatusMsg:ot,setTxHash:Be,setIsExecuting:Ue,setShowStatusPanel:mt,setPaymentResult:Ke},refs:{spiceDepositSubmittedRef:Pe,abortControllerRef:at}};const Ln=u.useRef(!1),Jn=u.useRef({scope:"",identity:""});Jn.current={scope:xe??ie?`spiceflow:sourceSupply:${JSON.stringify([N?.network??"testnet",z,(Ce??xe??ie).toLowerCase(),(xe??ie).toLowerCase()])}`:"",identity:tr(He.current)};const zn=u.useCallback(async K=>{if(Ln.current)return;Ln.current=!0;const we=He.current,Ye=Jn.current;try{if(M.current)throw new Error(M.current);if(Ge.current?.(),!Ye.scope)return await K(we);await Tu({scope:Ye.scope,ctx:we,run:K,isCurrent:()=>X.current&&Jn.current.scope===Ye.scope&&Jn.current.identity===Ye.identity})}catch(Ne){if(Jn.current.scope===Ye.scope){const It=g.sanitizeError(Ne,"Supply funding failed");Je(It),st("error"),we.isPayMode&&Ke({status:"failed",error:It})}}finally{Ln.current=!1,$.refreshWalletAssets(),$.refreshSpiceAssets()}},[Je]),oo=u.useCallback(async()=>{if(!X.current||Ln.current)return;ut.current=Date.now();const K=et.current;if(!K.actionExecution)return zn(Zs);Ln.current=!0,Ue(!0),Je(null),st("executing");try{if(K.error)throw new Error(K.error);if(!K.scope)throw new Error("Connect the external wallet and its Spicenet account");const we=()=>X.current&&et.current.scope===K.scope,Ye=He.current;await Nu({scope:K.scope,recovery:f,ctx:{...Ye,execution:{...Ye.execution,onProgress:Ne=>{we()&&Ye.execution.onProgress(Ne)}},ui:{setError:Ne=>{we()&&Ye.ui.setError(Ne)},setStep:Ne=>{we()&&Ye.ui.setStep(Ne)},setStatusMsg:Ne=>{we()&&Ye.ui.setStatusMsg(Ne)},setTxHash:Ne=>{we()&&Ye.ui.setTxHash(Ne)},setIsExecuting:Ne=>{we()&&Ye.ui.setIsExecuting(Ne)},setShowStatusPanel:Ne=>{we()&&Ye.ui.setShowStatusPanel(Ne)},setPaymentResult:Ne=>{we()&&Ye.ui.setPaymentResult(Ne)}}},buildActionCalls:K.buildActionCalls,isCurrent:we,onRecord:Ne=>{we()&&jt({scope:K.scope,record:Ne,error:null})}})}catch(we){et.current.scope===K.scope&&(Je(g.sanitizeError(we,"External wallet action failed")),st("error"))}finally{Ln.current=!1,Ue(!1)}},[Je,zn,f]),hl=u.useCallback(()=>X.current?(ut.current=Date.now(),et.current.actionExecution?(Je("External action execution currently supports exact-input supplies"),Promise.resolve()):zn(ar)):Promise.resolve(),[zn]),gl=u.useCallback(async K=>{if(!X.current)throw new Error("Supply is disabled");if(et.current.actionExecution)throw new Error("submitSupply manages external action funding");const we=pe.current?.asset;if(!we)throw new Error("No source asset selected");if(!xe)throw new Error("Your Spicenet account is not ready yet");const Ye=A.normalizeNativeTokenAddress(we.address),Ne=we.isNative||A.isNativeToken(Ye),It=g.getClientForChain(we.chainId);await zn(async _t=>{await er({identity:tr(_t),state:_t.sourceFunding,onState:Tn=>_t.onSourceFundingChange?.(Tn),sourceClient:It,recipient:xe,tokenAddr:Ye,isNative:Ne,requiredAmount:K,createWallet:()=>On({wallet:se,account:Ce,chainId:we.chainId,onSwitch:()=>ot("Switching source network...")})})})},[xe,Ce,se,zn]),xl=u.useCallback(K=>P?Promise.resolve(en(K,H)&&(K.isNative||A.isNativeToken(K.address))?null:I.formatUnits(K.balance,K.decimals)):wi({asset:K,isPayMode:R,isNon7702:H,needsSwap:je,isQuoting:Dt,embeddedWalletAddress:xe,buildSupplyChainBatches:so,estimate:re,executionTokenAddress:ln,feeExecutionMode:y}),[P,R,H,je,Dt,xe,so,re,ln,y]),yl=u.useCallback(()=>{const K=et.current.scope;K&&(Ru(K),jt({scope:K,record:null,error:null})),st("idle"),Be(null),Ke(null),mt(!1),$.refreshSpiceAssets()},[$]),bl=u.useCallback(()=>{mt(!1),Ke(null)},[]),wl=u.useCallback(()=>{X.current&&(st("idle"),Je(null),setTimeout(()=>{X.current&&(ut.current=Date.now(),oo())},50))},[Je,oo]),Cl=u.useCallback(()=>{mt(!1),Ke(null),Pe.current=!1,$.refreshSpiceAssets(),$.refreshWalletAssets()},[$]),Ar=!!$t&&fe.current?.key===$t,Ir=!!x&&Ar&&Ee?.grossAmount===0n&&dt,Er=(!vn||Tt||Un)&&(!(x||h)||Ar)&&t&&(!h||R&&ht===0&&(!!o||Ir)&&!n&&!S&&!F)&&(!ge.required||!!Ze&&!Xt)&&(R?(B||!!o?.asset||Ir)&&ht>=0&&!ws&&!Me&&(B&&!h||Tt||dt)&&!yt&&(B||!je||!!de)&&!dn:!!o?.asset&&ht>0&&!ws&&!Me&&(wt||dt)&&!yt&&!ke&&(sn||ze||!!nn&&!Dt)&&!dn),Fr=n?t&&!!De&&Ht&&!$e&&!Me&&!dn&&(Pt?Pt.phase!=="complete"&&!Pt.requiresRecovery:Er):Er,kn={assets:{...$,selectable:pt},quote:{...Ve,isQuoting:Dt||ge.required&&!Ze&&!Xt,quoteError:Xt??Ve.quoteError,hasSourceConversion:ge.required,executionInput:ge.plan?{address:ge.plan.bridgeDestination.address,chainId:z,decimals:ge.plan.bridgeDestination.decimals,amount:Ee?.netAmount??0n}:null},fees:{preview:Ee,fundingConversion:Un?fe.current?.quote.fundingConversion:void 0,proceedsUsed:fe.current?.key===$t?fe.current?.quote.proceedsUsed:void 0,fundingShortfall:(x||fe.current?.quote.fundingConversion)&&fe.current?.key===$t?fe.current?.quote.fundingConversion?.amountOut??fe.current?.quote.grossFundingAmount:void 0,source:Ze?{address:Ze.quote.plan.bridgeSource.address,chainId:Ze.quote.plan.bridgeSource.chainId,symbol:Ze.quote.plan.bridgeSource.symbol,decimals:Ze.quote.plan.bridgeSource.decimals,gasFee:Ze.sourceGasFee,spicenetFee:Ze.sourceSpicenetFee}:null,isLoading:ye||t&&!Me&&(nt==="idle"||nt==="error")&&vn&&!Tt&&!rt.isQuoting&&!Un&&!bs&&!yt,ready:dt&&(!vn||Tt||Un),error:yt},amount:{parsed:ht,isInsufficientBalance:ws,sourceBalance:le,feesExceedAmount:ke,sourceRequiredAmount:fl},status:{step:nt,statusMsg:ft,txHash:_e,isExecuting:Me,error:D??$e??Xe,showStatusPanel:Ct,paymentResult:Te,externalAction:Pt,sourceFunding:null},flags:{directExecutionFeeNote:Tt},canExecute:Fr,submitSupply:oo,submitPay:hl,fundEmbeddedSource:gl,retrySupply:wl,dismissPaymentStatus:bl,resolveMaxAmount:xl,resetAfterSuccess:yl,resetPaymentState:Cl},$n=P&&(ge.required||je)&&!h&&!n,_n=o&&$.displayAssets.find(K=>K.chainId===o.asset.chainId&&g.addressesEqual(A.normalizeNativeTokenAddress(K.address),A.normalizeNativeTokenAddress(o.asset.address))&&K._source===o.asset._source&&K._fundingWallet===o.asset._fundingWallet),ro=(()=>{try{return o?I.parseUnits(o.amount||"0",o.asset.decimals):null}catch{return null}})(),Tr=$n&&t&&!Me&&(nt==="idle"||nt==="error")&&U&&L&&O&&!dn&&!!_n&&ro!==null&&ro>0n&&ro<=_n.balance;(!Tr||it.current?.scope!==qe)&&(it.current=null);const Br=Math.min((ge.required?Ze?.expiresAt:1/0)??0,je?Ve.quoteExpiresAt??0:1/0);if(Tr&&Fr&&!kn.quote.isQuoting&&!kn.fees.isLoading&&(!je||Ve.resolvedSwap&&Ve.inputAmount!=null)&&Br>Date.now()){const K=He.current;it.current={scope:qe,expiresAt:Br,context:K,sourcePlan:Ze,quote:kn.quote,fees:kn.fees,amount:kn.amount}}const Zt=it.current;u.useEffect(()=>{const K=Fe.current;Ut&&Wt&&K&&K.plan===Zt?.sourcePlan&&K.plan!==Wt&&Ie(we=>we+1)},[Ut,Wt,Zt?.sourcePlan]);const ao=!!Zt&&Zt.scope===qe&&Zt.expiresAt>Date.now();if(Ge.current=$n?()=>{if(!X.current||!ao||xt.current!==Zt.scope||Zt.expiresAt<=Date.now())throw new Error("Swap quote expired or changed; wait for a complete quote before retrying")}:null,ao){const K=Ge.current,we=Zt.context;He.current={...we,selectedAsset:o&&_n?{...o,asset:_n}:o,validateFeeQuote:()=>{K(),we.validateFeeQuote?.()},sourceConversion:we.sourceConversion?{...we.sourceConversion,isCurrent:()=>X.current&&xt.current===Zt.scope&&(!we.needsSwap||(Zt.quote.quoteExpiresAt??0)>Date.now())&&we.sourceConversion.isCurrent()}:void 0}}const io=Math.min(...[Zt?.expiresAt,Ze?.expiresAt].filter(K=>K!==void 0&&K>Date.now()));u.useEffect(()=>{if(!Number.isFinite(io))return;const K=setTimeout(()=>Ie(we=>we+1),io-Date.now());return()=>clearTimeout(K)},[io]);const Cs=Math.min(vt.quoteExpiresAt??1/0,Ve.quoteExpiresAt??1/0);return u.useEffect(()=>{if(!$n||!t||Me||!Number.isFinite(Cs)||ge.required&&!Ze||Ze&&Ze.expiresAt<Cs)return;const K=setTimeout(()=>{vt.refreshQuote(),oe.refreshQuote()},Math.max(0,Cs-Date.now()-1e4));return()=>clearTimeout(K)},[$n,t,Me,ge.required,Ze?.expiresAt,Cs,vt.refreshQuote,oe.refreshQuote]),$n?ao?{...kn,quote:Zt.quote,fees:Zt.fees,amount:{...Zt.amount,sourceBalance:_n?.balanceFormatted??le,isInsufficientBalance:!1},canExecute:!0}:{...kn,canExecute:!1}:kn}function Ku(e){return!!e.embeddedAddress&&!!e.externalAddress}function Yu(e,t,n){const s=n.filter(o=>o.amount>0n);return{chainId:e,domain:"evm",tokenTransfers:[],calls:A.isNativeToken(t)?s.map(o=>({to:o.recipient,value:o.amount,data:"0x"})):s.map(o=>({to:t,value:0n,data:I.encodeFunctionData({abi:I.erc20Abi,functionName:"transfer",args:[o.recipient,o.amount]})}))}}new Set([A.SPICE_GAS_FEE_RECIPIENT,A.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function Gu(e){return`0x77${e.slice(4)}`}function zi({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:s,withdrawalAmount:o,deliveryRecipient:r,deliveryTransfers:i,requestTimestampMs:l}){const d=i?.length?i:[{token:n,recipient:r,amount:o??s}],c=d.reduce((h,x)=>h+x.amount,0n);if(c<=0n)return null;const m=l??Date.now(),p=BigInt(Math.floor(m/1e3)),f=Gu(I.keccak256(I.encodeAbiParameters([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[e??r,n,r,c,BigInt(t),BigInt(m)])));return{chainId:A.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:[{to:A.ZERO_ADDRESS,value:0n,data:I.encodeFunctionData({abi:A.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:f,nbf:0n,exp:p+3600n,metadata:"{}",transfers:d.map(h=>({token:I.getAddress(h.token).toLowerCase(),to:I.getAddress(h.recipient).toLowerCase(),amount:h.amount}))}]})}]}}const hs=e=>`${e._source}:${e.chainId}:${e.receiptTokenId??e.address.toLowerCase()}`;function Zu(e){const{asset:t,amount:n,recipient:s,owner:o,onSuccess:r}=e,i=t?.chainId??e.sourceChains?.[0]??0,l=u.useMemo(()=>A.getTokensForChain(i).find(y=>y.equivalenceGroup==="USDC"),[i]),[d,c]=u.useState(null),m=u.useCallback((y,w)=>{if(!t||n<=0n||n>t.balance||!s||!o||g.addressesEqual(o,s))throw new Error("Enter a valid withdrawal amount and recipient.");if(w.chainId!==t.chainId||!g.addressesEqual(w.executorAddress??w.userAddress,o))throw new Error("The withdrawal wallet or network changed. Review the withdrawal again.");return Yu(t.chainId,t.address,[{recipient:s,amount:n}]).calls},[t?.address,t?.chainId,t?.balance,n,s,o]),p=u.useMemo(()=>d?{asset:d,amount:"0"}:null,[d]),f=ur({enabled:e.enabled&&!!l&&!!t&&n>0n&&!!s&&!!o&&!g.addressesEqual(o,s),feeOnlyAction:!0,isZeroAmountPay:!0,amountDirection:"output",paymentAmount:"0",destinationToken:{address:l?.address??A.ZERO_ADDRESS,symbol:l?.symbol??"USDC",decimals:l?.decimals??6,chainId:i},recipient:o,selectedAsset:p,sourceChains:e.sourceChains,includeCrossChainEmbeddedAssets:!0,includeExternalWalletAssets:!1,feeExecutionMode:"backend-transfer",buildActionCalls:m,buildSpicenetBatch:zi,onError:(y,w)=>e.onError?.(y.message,w),onSuccess:()=>{t&&(window.dispatchEvent(new CustomEvent("withdraw-completed")),r?.({token:t.symbol,amount:I.formatUnits(n,t.decimals),chainId:i}))}}),h=`${e.enabled}:${t?.chainId}:${t?.address}:${n}:${s}`,x=u.useRef(h);u.useEffect(()=>{x.current===h||f.status.isExecuting||(x.current=h,(f.status.step==="success"||f.status.paymentResult?.status==="success")&&f.resetAfterSuccess())},[h,f.status.isExecuting,f.status.step,f.status.paymentResult?.status,f.resetAfterSuccess]);const b=u.useMemo(()=>l?f.assets.displayAssets.flatMap(y=>{if(y._fundingWallet==="external"||y.isNative)return[];if(!(y._source==="spice"?Dn(y,i).some(v=>g.addressesEqual(v,l.address)):y._fundingWallet==="embedded"&&A.getTokensForChain(y.chainId).some(v=>v.equivalenceGroup==="USDC"&&g.addressesEqual(v.address,y.address))))return[];const w=t&&y._source==="wallet"&&y.chainId===t.chainId&&g.addressesEqual(y.address,t.address)?n:0n,S=y.balance-w;return S>0n?[{...y,balance:S,balanceFormatted:Number(I.formatUnits(S,y.decimals))}]:[]}).sort((y,w)=>{const S=v=>v._source==="wallet"&&v.chainId===i?0:v._source==="spice"?1:2;return S(y)-S(w)||w.balanceFormatted-y.balanceFormatted}):[],[f.assets.displayAssets,l,i,t?.address,t?.chainId,n]);return u.useEffect(()=>{if(!e.enabled||f.status.isExecuting)return;const y=(d&&b.find(w=>hs(w)===hs(d)))??b[0]??null;(!d||!y||hs(d)!==hs(y)||d.balance!==y.balance)&&c(y)},[e.enabled,f.status.isExecuting,b,d]),{supply:f,candidates:b,source:d,setSource:c,feeToken:l,sourceKey:hs}}const qi=({isSuccess:e,type:t,chainName:n,explorerUrl:s,txHash:o,dark:r=!1,successBg:i="#d1fae5",successBorder:l="#6ee7b7",successText:d="#065f46",errorBg:c="#fee2e2",errorBorder:m="#fca5a5",errorText:p="#dc2626",textSecondary:f="#6b7280"})=>a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?i:c,border:e?`1px solid ${l}`:`1px solid ${m}`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[a.jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:a.jsx("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:a.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),a.jsxs("div",{children:[a.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:g.font.mono,letterSpacing:"0.5px",color:e?d:p},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),a.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:f},children:["on ",n]})]})]}),s&&o&&a.jsxs("a",{href:`${s}/tx/${o}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:f,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[a.jsx("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),a.jsx("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),a.jsx("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),Hi=`
31
31
  @keyframes slideUp {
32
32
  from { transform: translateY(100%); }
33
33
  to { transform: translateY(0); }