@spicenet-io/spiceflow-ui 4.7.6 → 4.7.7
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 +1 -1
- package/dist/index.js +6 -6
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -82,4 +82,4 @@
|
|
|
82
82
|
from { opacity: 0; transform: translateY(-4px); }
|
|
83
83
|
to { opacity: 1; transform: translateY(0); }
|
|
84
84
|
}
|
|
85
|
-
`})]}),document.body):null;return o.jsxs(o.Fragment,{children:[re,it,M&&Cn.createPortal(o.jsx($o,{isOpen:!0,onClose:ee,supportedChains:[M.chainId],escrowOnly:!0,escrowTokenAddress:M.tokenAddress,escrowAmount:M.amount,escrowTokenDecimals:M.tokenDecimals,escrowTokenSymbol:M.tokenSymbol,styles:u,onDepositSuccess:oe}),document.body)]})},wc="0xa9059cbb";function Er(e,t,n){return j.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"transfer",args:[n,t]})}}function jr(e,t,n){return{chainId:n,calls:[Er(e,t,j.getEscrowContractAddress(n))]}}function Fr(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function Br(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith(wc)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function _n(e,t,n,s){if(!t)return[e];const r=await t({...n,requestTimestampMs:s});return r?[r,e]:[e]}function Tr(e){return e.filter(t=>t.domain!=="spicenet")}function es(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:j.normalizeNativeTokenAddress(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function Lt(e,t,n){return rr(e,t,n,"ceil")}async function Rr(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:d,isNon7702:i,isPayMode:u,resolvedChainId:l,buildActionCalls:f,feeExecutionMode:m,buildSpicenetBatch:h,selectedAsset:x,needsSwap:g,exactOutputSwap:y,resolvedTokenIn:C,requestTimestampMs:S}=e,b=B.parseUnits(n,s.decimals),R=t?.actionAmountOverride??b,k=r||a||(i?void 0:d);if(!k)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:k,chainId:l,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??b,netAmount:R,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:m,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},F=f(R,w),A={chainId:l,calls:F},M=!u&&!i?!0:x?.asset?._source==="spice",E=Fr(x??null,i,l),v=M||i||E,T=(D,U)=>({token:D,from:"escrow",to:k,amount:U}),I=(D,U,N)=>E?[jr(D,U,l),...N]:N;if(b===0n)return[A];if(g&&y){const D=C??zt(x.asset,l)??x.asset.address,U=t?.fundingAmountOverride??y.amountInMax,N=v?[T(D,U)]:[],H={to:D,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},z={chainId:l,calls:[H,...y.calls,...F],tokenTransfers:[...N,...A.tokenTransfers??[]]};if(!v)return[z];const W=await _n(z,h,{userAddress:k,destinationChainId:l,deliveryToken:D,deliveryAmount:U,deliveryRecipient:k,deliveryTransfers:es(z),sourceAsset:x.asset},S);return I(D,U,W)}if(v){const D=C??zt(x.asset,l)??s.address;if(E&&D.toLowerCase()===s.address.toLowerCase())return[A];const U=t?.fundingAmountOverride??b,N={...A,tokenTransfers:[T(D,U),...A.tokenTransfers??[]]},H=await _n(N,h,{userAddress:k,destinationChainId:l,deliveryToken:D,deliveryAmount:U,deliveryRecipient:k,deliveryTransfers:es(N),sourceAsset:x.asset},S);return I(D,U,H)}return[A]}async function Dr(e,t){const{selectedAsset:n,embeddedWalletAddress:s,externalWalletAddress:r,recipient:a,resolvedChainId:d,destinationToken:i,buildActionCalls:u,feeExecutionMode:l,buildSpicenetBatch:f,isPayMode:m,isNon7702:h,needsSwap:x,resolvedSwap:g,quoteAmountOut:y,resolvedTokenIn:C,requestTimestampMs:S}=e,b=g?.amountOutMinimum??y;if(!n?.asset||!s)return[];const R=a??(h?r:s);if(!R)return[];const k=t?.fundingAmountOverride??t?.actionAmountOverride??B.parseUnits(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??k,F=t?.sourceFundingAmountOverride??k,A=t?.deliveryAmountOverride??w,M=t?.withdrawalAmountOverride??A,E=t?.actionAmountOverride??k,v={userAddress:R,chainId:d,destinationToken:i.address,feeToken:l==="user-transfer"&&x&&C?C:i.address,grossAmount:w,netAmount:E,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:l,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},T=u(E,v),I=n.asset?._source==="wallet";if(!m&&h&&I&&n.asset.chainId===d){if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!g||b===null)throw new Error("Swap quote not available yet")}if(x&&g&&b){const X=u(t?.actionAmountOverride??b,{...v,netAmount:t?.actionAmountOverride??b}),{feeCall:G,remainingCalls:ce}=Br(X,l,x,v.feeToken);return[{chainId:d,calls:[...G?[G]:[],...g.calls,...ce]}]}return[{chainId:d,calls:T}]}if(!m&&!h&&I&&n.asset.chainId!==d)throw new Error("Cross-chain wallet supplies require external wallet mode");const D=!m&&!h?n.asset?._source!=="wallet":n.asset?._source==="spice",U=h&&I,N=Fr(n,h,d);if(!(D||U||N))return[{chainId:d,calls:T}];const H=N?jr(C??j.normalizeNativeTokenAddress(n.asset.address),F,d):U&&n.asset.chainId!==d?{chainId:n.asset.chainId,calls:[Er(j.normalizeNativeTokenAddress(n.asset.address),F,j.getEscrowContractAddress(n.asset.chainId))]}:null,z=(X,G)=>({token:X,from:U?"solver":"escrow",to:s,amount:G}),W=(X,G)=>U?[{token:X,from:"escrow",to:j.SPICE_SOLVER_ADDRESS,amount:G}]:[];if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!g||b===null)throw new Error("Swap quote not available yet")}if(x&&g&&b&&C){const X=u(t?.actionAmountOverride??b,{...v,netAmount:t?.actionAmountOverride??b}),{feeCall:G,remainingCalls:ce}=Br(X,l,x,v.feeToken),V={chainId:d,calls:[...G?[G]:[],...g.calls,...ce],tokenTransfers:[...W(C,M),z(C,A)]},L=await _n(V,f,{userAddress:s,destinationChainId:d,deliveryToken:C,deliveryAmount:A,withdrawalAmount:M,deliveryRecipient:s,deliveryTransfers:es(V),sourceAsset:n.asset},S);return H?[H,...L]:L}const P=C??zt(n.asset,d)??i.address,Q={chainId:d,calls:T,tokenTransfers:[...W(P,M),z(P,A)]},q=await _n(Q,f,{userAddress:s,destinationChainId:d,deliveryToken:P,deliveryAmount:A,withdrawalAmount:M,deliveryRecipient:s,deliveryTransfers:es(Q),sourceAsset:n.asset},S);return H?[H,...q]:q}async function vc(e,t,n,s,r){let a=e;for(let d=0;d<4;d++){const i=await t(a),u=await s(i,n,a,r),l=ji(u);if(l===null||l>=e)return a;const f=a-l,m=e+f;if(m<=a)return a;a=m}return a}const Mr=(e,t)=>(e+t-1n)/t;function Sc(e,t){const n=e.spicenetFee+(e.bridgeFee??0n);return e.grossAmount<=n?t+e.gasFee+n:Mr((t+e.gasFee)*e.grossAmount,e.grossAmount-n)+2n}async function ts(e){const{requiredNetFunding:t}=e,n=await e.estimate(await e.buildBatches(t),e.fundingToken,t,e.executionOptions),s=mn(n,e.tokenDescriptor);if(!s)return{preview:null,feeEstimate:n,grossFundingAmount:t};const r=Sc(s,t),a=u=>s.grossAmount>0n?Mr(u*r,s.grossAmount):u,d=a(s.spicenetFee),i=a(s.bridgeFee??0n);return{preview:{...s,grossAmount:r,netAmount:t,spicenetFee:d,bridgeFee:i,totalFee:s.gasFee+d+i},feeEstimate:n,grossFundingAmount:r}}function Ic(e,t,n,s){if(e<=0n)return 0n;const r=e-t;if(r<=0n)return 0n;const a=s+n;return a<=0n?r:r*s/a}async function Nr(e){const{asset:t,isPayMode:n,isNon7702:s,needsSwap:r,isQuoting:a,embeddedWalletAddress:d,buildSupplyChainBatches:i,estimate:u,executionTokenAddress:l,feeExecutionMode:f}=e;if(n||s||r||a||!d||t.balance<=0n)return null;const m=d,h=await i({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(h.length===0)return null;const x=h.some(R=>R.tokenTransfers?.length),g=await u(h,l,t.balance,x?{userOverride:m,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:m,feeExecutionMode:f}:{userOverride:m}),y=mn(g,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),C=y?Lt(y.gasFee,y.decimals,t.decimals):0n,S=y?Lt(y.spicenetFee,y.decimals,t.decimals):0n,b=Ic(t.balance,C,S,t.balance);return b>0n?Uo(b,t.decimals):null}async function Wr(e){const{signal:t,selectedAsset:n,isPayMode:s,parsedAmount:r,needsSwap:a,exactOutputSwap:d,isNon7702:i,isSourceDestToken:u,currentPaymentAmount:l,destinationToken:f,feeExecutionMode:m,resolvedTokenIn:h,embeddedWalletAddress:x,providerEmbeddedAddress:g,resolvedChainId:y,isConnected:C,address:S,ready:b,authenticated:R,isDirect:k,resolvedSwap:w,isQuoting:F,executionTokenAddress:A,buildPayChainBatches:M,buildSupplyChainBatches:E,estimate:v}=e;if(!n?.asset)return null;if(s){if(r<=0||a&&!d||u)return null;const P=B.parseUnits(l,f.decimals),Q=h||zt(n.asset,y)||n.asset.address||f.address,q={chainId:y,tokenAddress:Q,symbol:j.getTokenByAddress(Q,y)?.symbol??n.asset.symbol,decimals:j.getTokenByAddress(Q,y)?.decimals??n.asset.decimals};if(i){const V=x||g;if(!V)return null;const L=a?d?.amountInMax??0n:P;if(L===0n)return null;const te=await ts({requiredNetFunding:L,buildBatches:de=>M({fundingAmountOverride:de}),fundingToken:Q,estimate:v,executionOptions:{userOverride:V,useCustomTransfers:!0,feeExecutionMode:m,signal:t},tokenDescriptor:q});return te.preview?{...te,preview:te.preview}:null}if(!C||!S||!b||!R)return null;const X=x||g||S,G=a?d?.amountInMax??0n:P;if(G===0n)return null;const ce=await ts({requiredNetFunding:G,buildBatches:V=>M({fundingAmountOverride:V}).then(L=>an(Tr(L),X)),fundingToken:Q,estimate:v,executionOptions:{useCustomTransfers:!0,feeExecutionMode:m,signal:t},tokenDescriptor:q});return ce.preview?{...ce,preview:ce.preview}:null}if(r<=0||!x)return null;const T=x||g;if(!(!s&&!i&&n.asset?._source==="wallet"&&n.asset.chainId!==y)&&!k&&!w&&!F||F)return null;const I=B.parseUnits(n.amount,n.asset.decimals),D=await E();if(D.length===0)return null;const U=i&&n.asset?._source==="wallet"&&n.asset.chainId===y,N={chainId:y,tokenAddress:A,symbol:j.getTokenByAddress(A,y)?.symbol??f.symbol,decimals:j.getTokenByAddress(A,y)?.decimals??f.decimals};if(U){const P=await p.relayerService.estimateBatchGas({user:T,outputToken:A,stepIndex:0,chainBatches:D,signal:t}),Q=Vn(I,10n),q=Q+P.gasFee;return{preview:{...N,grossAmount:I+q,netAmount:I,totalFee:q,gasFee:P.gasFee,spicenetFee:Q,bridgeFee:0n,gasQuoteSource:P.gasQuoteSource},feeEstimate:null}}const H=D.some(P=>P.tokenTransfers?.length),z=await v(D,A,I,H?{userOverride:T,useCustomTransfers:!0,feeExecutionMode:m,signal:t}:m?{userOverride:T,feeExecutionMode:m,signal:t}:{userOverride:T,signal:t}),W=mn(z,N);return W?{preview:W,feeEstimate:z}:null}const Ac=10n;function Pr(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=zt(n,e.resolvedChainId);if(!s||!p.addressesEqual(s,e.executionTokenAddress))return;const r=j.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=Lt(t,r?.decimals??e.destinationToken.decimals,n.decimals);if(a<=n.balance)return;const d=B.formatUnits(a,n.decimals),i=B.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${d} ${n.symbol}; available ${i} ${n.symbol}.`)}function Zs(e){const t=j.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Bn(e,t,n){const s=mn(e,Zs(t));if(!s)return;const r=Vn(n,Ac),a=s.bridgeFee??0n,d=r+s.gasFee+a;return{grossAmount:n+d,netAmount:n,combinedFeeAmount:d,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:r,gasFee:s.gasFee,bridgeFee:a}}}function Ec(e,t,n){let s=0n,r=0n;const a=n.toLowerCase();for(const d of e)if(d.chainId===t){for(const i of d.calls??[])if(i.to.toLowerCase()===a)try{const u=B.decodeFunctionData({abi:B.erc20Abi,data:i.data});if(u.functionName!=="transfer")continue;const l=u.args[0].toLowerCase(),f=u.args[1];l===j.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=f:l===j.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(r+=f)}catch{continue}}return{spicenetFee:s,gasFee:r}}function Gs(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=Ec(e,t.resolvedChainId,s);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:_t(r.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&_t(r.gasFee,n.feeBreakdown.gasFee,100n)}function Ur(e,t){return e?_t(e.grossAmount,t.grossAmount,100n)&&_t(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&_t(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&_t(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}function Xs(e,t,n,s){const r=Tr(e),a=u=>(u.tokenTransfers??[]).some(l=>l.from==="escrow"),d=r.filter(u=>!a(u)),i=r.filter(a);return[...d,...an(i,t,n,s)]}function Or(e,t){const n=j.getTokenByAddress(t,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:t,symbol:n?.symbol??e.selectedAsset?.asset.symbol??"",decimals:n?.decimals??e.selectedAsset?.asset.decimals??e.destinationToken.decimals}}async function zr(e,t){const n=e.feeQuote;return n?.feeEstimate&&n.grossFundingAmount!==void 0?{grossFundingAmount:n.grossFundingAmount,feeEstimate:n.feeEstimate}:ts({...t,estimate:e.execution.estimate,tokenDescriptor:Or(e,t.fundingToken)})}function Lr(e,t){const n=e.selectedIsEquivalent?t:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(n===0n)throw new Error("Quote not available yet");return n}function Hr(e,t,n){const s=t instanceof Error?t:new Error(String(t));if(s.name==="AbortError"||n){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r)}function Qr(e,t){const n=p.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}async function Vr(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const s=await qr(e);e.ui.setTxHash(s??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const s=new AbortController;e.refs.abortControllerRef.current=s,await jc(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){Hr(e,s,!!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("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=B.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),s=n;let r=await e.execution.buildSupplyChainBatches();const a=e.selectedAsset.asset?._source==="wallet",d=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!a&&!r.some(x=>j.isSpicenetChainId(x.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const i=r.some(x=>x.tokenTransfers?.length)?{userOverride:d,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:d,feeExecutionMode:e.feeExecutionMode}:{userOverride:d};let u=n;const l=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,f=e.feeExecutionMode==="user-transfer"&&!l?s:void 0;let m;for(let x=0;x<4;x+=1){const g=x===0&&e.feeQuote?.feeEstimate||await e.execution.estimate(r,e.executionTokenAddress,u,i),y=mn(g,Zs(e));m=e.feeExecutionMode==="user-transfer"&&y?Bn(g,e,s):void 0;const C=m?.grossAmount??y?.grossAmount??u;if(C===u){u=C;break}u=C,r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:m})}e.feeExecutionMode==="user-transfer"&&(Pr(e,u),r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:m}));let h=m;await e.execution.execute(r,e.executionTokenAddress,u,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...i,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:x,chainBatches:g})=>{const y=Bn(x,e,s);if(!y)return null;const C=Ur(h,y),S=Gs(g,e,y);return C||S?null:(h=y,e.execution.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:f,actionContextOverride:y}))}}:{...i,skipPreSubmitFeeEstimate:!0}),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){Hr(e,n,t.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function jc(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const s=e.selectedAsset.asset,r=B.parseUnits(e.selectedAsset.amount,s.decimals),a=r,d=s?._source==="wallet"&&s.chainId===e.resolvedChainId;let i=await e.execution.buildSupplyChainBatches();const u={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let l=r;const f=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,m=e.feeExecutionMode==="user-transfer"&&!f?a:void 0;let h;if(d){const E=e.feeQuote?.preview.gasFee??(await p.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:i})).gasFee,v=Vn(r,10n),T=v+E;l=r+T,e.feeExecutionMode==="user-transfer"&&(h={grossAmount:l,netAmount:a,combinedFeeAmount:T,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:v,gasFee:E,bridgeFee:0n}})}else for(let E=0;E<4;E+=1){const v=await e.execution.estimate(i,e.executionTokenAddress,0n,u),T=e.feeExecutionMode==="user-transfer"?Bn(v,e,a):void 0,I=mn(v,Zs(e)),D=T?.grossAmount??(I?I.grossAmount>r?I.grossAmount:r:l);if(h=T,D===l){l=D;break}l=D;const U=j.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),N=Lt(l,U?.decimals??e.destinationToken.decimals,s.decimals);i=await e.execution.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:N,withdrawalAmountOverride:l,actionAmountOverride:m,actionContextOverride:T})}const x=j.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let g=d?l:Lt(l,x?.decimals??e.destinationToken.decimals,s.decimals);Pr(e,l),i=await e.execution.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:g,withdrawalAmountOverride:l,actionAmountOverride:m,actionContextOverride:h});const y=s.chainId,C=n,{extWc:S,viemChain:b}=await xn({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:y,onSwitch:()=>e.ui.setStatusMsg("Switching source network...")}),R=j.normalizeNativeTokenAddress(s.address),k=s.isNative||j.isNativeToken(R),w=p.getClientForChain(y),F=E=>Ms({extWc:S,sourceClient:w,recipient:C,tokenAddr:R,isNative:k,amount:E,viemChain:b});e.ui.setStatusMsg("Funding embedded wallet..."),await F(g);let A=g;if(e.feeExecutionMode==="user-transfer")for(let E=0;E<4;E+=1){const v=await e.execution.estimate(i,e.executionTokenAddress,0n,u),T=Bn(v,e,a);if(!T)break;const I=d?T.grossAmount:Lt(T.grossAmount,x?.decimals??e.destinationToken.decimals,s.decimals);if(I>A&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await F(I-A),A=I),h=T,l=T.grossAmount,g=I,i=await e.execution.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:g,withdrawalAmountOverride:l,actionAmountOverride:m,actionContextOverride:T}),Gs(i,e,T))break}e.ui.setStatusMsg("Signing supply intent...");let M=h;await e.execution.execute(i,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:E,chainBatches:v})=>{const T=Bn(E,e,a);if(!T)return null;const I=Ur(M,T),D=Gs(v,e,T);if(I||D)return null;if(T.grossAmount>l)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");M=T;const U=d?T.grossAmount:Lt(T.grossAmount,x?.decimals??e.destinationToken.decimals,s.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:T.grossAmount,sourceFundingAmountOverride:U,withdrawalAmountOverride:T.grossAmount,actionAmountOverride:m,actionContextOverride:T})}}:{...u,skipPreSubmitFeeEstimate:!0})}async function qr(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 r=B.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),a={userAddress:s,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},d=e.buildActionCalls(r,a);if(d.length===0)throw new Error("No action calls configured");const{extWc:i,viemChain:u}=await xn({wallet:n,account:s,chainId:e.resolvedChainId}),l=p.getClientForChain(e.resolvedChainId);return Ko({extWc:i,client:l,calls:d,viemChain:u,errorMessage:"Transaction failed"})}async function Fc(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=n.chainId,r=B.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=Lr(e,r),d=e.resolvedTokenIn||e.selectedAsset.asset.address,i={userOverride:t,useCustomTransfers:!0},u=j.getEscrowContractAddress(s),l=j.normalizeNativeTokenAddress(n.address),f=n.isNative||j.isNativeToken(l),m=t,h=F=>({chainId:s,calls:f?[{to:u,value:F,data:"0x"}]:[{to:l,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"transfer",args:[u,F]})}]}),x=async(F,A,M)=>[h(F),...Xs(await e.execution.buildPayChainBatches({fundingAmountOverride:F}),m,A,M)],{grossFundingAmount:g,feeEstimate:y}=await ts({requiredNetFunding:a,buildBatches:F=>x(F),fundingToken:d,estimate:e.execution.estimate,executionOptions:{...i,feeExecutionMode:e.feeExecutionMode},tokenDescriptor:Or(e,d)}),C=await x(g,y,{payoutAlreadyGross:!0}),{extWc:S,viemChain:b}=await xn({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:s}),R=p.getClientForChain(s);await Ms({extWc:S,sourceClient:R,recipient:t,tokenAddr:l,isNative:f,amount:g,viemChain:b});const k=C.some(F=>F.tokenTransfers?.length),w={...i,skipUserFundingPreflight:!0,skipPreSubmitFeeEstimate:!0};return await e.execution.execute(C,d,k?g:0n,F=>{F.txHash&&(e.ui.setPaymentResult(A=>({...A??{status:"processing"},txHash:F.txHash})),e.ui.setTxHash(F.txHash))},void 0,k?w:{userOverride:t,skipUserFundingPreflight:!0,skipPreSubmitFeeEstimate:!0})}async function Kr(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let s;if(e.isSourceDestToken||e.parsedAmount===0)s=await qr(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,a=B.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),d=Lr(e,a),i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!i)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const u=e.resolvedTokenIn||r.address,{grossFundingAmount:l}=await zr(e,{requiredNetFunding:d,buildBatches:h=>e.execution.buildPayChainBatches({fundingAmountOverride:h}),fundingToken:u,executionOptions:{userOverride:i,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}}),f=await e.execution.buildPayChainBatches({fundingAmountOverride:l}),m=await e.onPayExecute({asset:r,amount:e.currentPaymentAmount,amountWei:a,destinationToken:e.destinationToken,chainBatches:f,requiredNetFunding:d,grossFundingAmount:l,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:u,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});m&&(e.ui.setTxHash(m),e.ui.setPaymentResult(h=>({...h??{status:"processing"},txHash:m}))),s=m||void 0}else s=await Fc(e);e.ui.setPaymentResult(r=>({status:"success",txHash:r?.txHash||s||""}))}catch(s){Qr(e,s)}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=B.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),s={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const x=await e.execution.buildPayChainBatches(),g=await e.execution.execute(x,e.executionTokenAddress,0n,y=>{y.txHash&&(e.ui.setPaymentResult(C=>({...C??{status:"processing"},txHash:y.txHash})),e.ui.setTxHash(y.txHash))},void 0,s);e.ui.setPaymentResult(y=>({status:"success",txHash:y?.txHash||g}));return}const r=e.selectedAsset?.asset;if(!r)throw new Error("Select a payment source");const a=e.resolvedTokenIn||r.address||e.destinationToken.address,d=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,i=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,{grossFundingAmount:u,feeEstimate:l}=await zr(e,{requiredNetFunding:d,buildBatches:x=>e.execution.buildPayChainBatches({fundingAmountOverride:x}).then(g=>Xs(g,i)),fundingToken:a,executionOptions:s}),f=Xs(await e.execution.buildPayChainBatches({fundingAmountOverride:u}),i,l,{payoutAlreadyGross:!0}),m=f.some(x=>x.tokenTransfers?.length),h=await e.execution.execute(f,a,m?u:0n,x=>{x.txHash&&(e.ui.setPaymentResult(g=>({...g,txHash:x.txHash})),e.ui.setTxHash(x.txHash))},void 0,{...s,skipPreSubmitFeeEstimate:!0});e.ui.setPaymentResult(x=>({status:"success",txHash:x?.txHash||h}))}catch(n){Qr(e,n)}finally{e.ui.setIsExecuting(!1)}}const Bc=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:d,textSecondary:i,cardBg:u,cardBorder:l,dk:f,dark:m,isQuoting:h,quoteError:x,estimatedOutput:g,paymentAmount:y,needsSwap:C,exactOutputSwap:S,adjustable:b=!1,maxAmount:R,onAmountChange:k})=>e==="supply"?o.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${l}`,borderRadius:m?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[o.jsxs("div",{style:{minWidth:0},children:[o.jsx("span",{style:{fontFamily:a,fontSize:"17px",fontWeight:500,color:m?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),o.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:i,fontFamily:a,marginTop:"10px"},children:"Net amount after swap and fees"})]}),o.jsxs("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${l}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[o.jsx(Zr,{symbol:t,logoURI:n,primaryColor:r,size:24}),o.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:m?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),o.jsx("div",{style:{textAlign:"right",minWidth:0},children:h?o.jsx("span",{style:{fontSize:"18px",color:i,fontFamily:a},children:"Quoting..."}):x?o.jsx("span",{style:{fontSize:"13px",color:m?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):g?o.jsx(sn,{value:g,title:g,fontFamily:a,color:d,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):o.jsx("span",{style:{fontSize:"20px",color:i,fontFamily:a},children:"\u2014"})})]}):o.jsx(Tc,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:d,textSecondary:i,cardBg:u,cardBorder:l,dk:f,dark:m,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:S,isQuoting:h,adjustable:b,maxAmount:R,onAmountChange:k}),Yr=c.memo(Bc),Zr=({symbol:e,logoURI:t,primaryColor:n,size:s})=>t?o.jsx("img",{src:t,alt:e,style:{width:s,height:s,borderRadius:"50%",objectFit:"cover"}}):o.jsx("div",{style:{width:s,height:s,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:s<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),Tc=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:d,cardBg:i,cardBorder:u,dk:l,dark:f,paymentAmount:m,needsSwap:h,exactOutputSwap:x,isQuoting:g,adjustable:y,maxAmount:C,onAmountChange:S})=>{const b=p.font.mono,R=parseFloat(m||"0"),k=C?parseFloat(C):0,[w,F]=c.useState(m||""),A=c.useRef(null),[M,E]=c.useState(null),[v,T]=c.useState(null);c.useEffect(()=>{y||F(m||"")},[m,y]);const I=N=>{let H=N;H.startsWith(".")&&(H="0"+H);const z=p.parseNumericInput(H);let W=z;C&&parseFloat(z)>parseFloat(C)&&(W=C),F(W),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>S?.(W),300)},D=N=>{if(!k)return;if(N===100){F(C||k.toString()),A.current&&clearTimeout(A.current),S?.(C||k.toString());return}const H=10**n,z=Math.floor(k*N/100*H)/H,W=p.formatDecimalInput(z,n);F(W),A.current&&clearTimeout(A.current),S?.(W)},U=k>0?parseFloat(w||"0")/k*100:0;return c.useEffect(()=>()=>{A.current&&clearTimeout(A.current)},[]),o.jsxs("div",{style:{backgroundColor:i,border:`1px solid ${u}`,borderRadius:f?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[o.jsx(Zr,{symbol:e,logoURI:t,primaryColor:s,size:32}),o.jsxs("div",{children:[o.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:a,fontFamily:r},children:"Payment"}),o.jsx("div",{style:{fontSize:"12px",color:d,fontFamily:r,marginTop:"2px"},children:e})]})]}),o.jsxs("div",{style:{textAlign:"right"},children:[y?o.jsx(sn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:N=>I(N.target.value),placeholder:"0.0",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):o.jsx(sn,{element:"div",value:R>0?m:"0.00",title:R>0?m:"0.00",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),o.jsx("div",{style:{fontSize:"12px",color:d,fontFamily:b,marginTop:"2px"},children:e}),y&&k>0&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((N,H)=>{const z=Math.abs(U-N)<1,W=H===4,P=M===N,Q=v===N;return o.jsx("button",{onClick:()=>D(N),onMouseEnter:()=>E(N),onMouseLeave:()=>{E(null),T(null)},onMouseDown:()=>T(N),onMouseUp:()=>T(null),title:`${N}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:z?1:P?.8:.5,transform:Q?"scale(0.85)":P?"scale(1.15)":"scale(1)",transition:p.transition.interactive},children:o.jsx(ms,{pct:N,isMax:W,primaryColor:s,dark:f,fillColor:f?l?.textSecondary||"#9ca3af":"#3C3E42"})},N)})})]})]}),h&&x&&!g&&o.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:f?`1px solid ${l?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:o.jsxs("span",{style:{fontSize:"11px",color:d,fontFamily:r,opacity:.7},children:["via ",x.venue]})})]})},Gr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Xr=["signing-delegation","signing-intent","submitting","executing"],Rc=({step:e,statusMsg:t,txHash:n,explorerUrl:s,currentStepIdx:r,palette:a,cardBg:d,cardBorder:i,textPrimary:u,textSecondary:l,fontFamily:f,primaryColor:m,onRetry:h})=>o.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:e==="success"?d:e==="error"?a.errorBg:d,border:`1px solid ${e==="success"?i:e==="error"?a.errorBorder:i}`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[e==="success"?o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:o.jsx("path",{d:"M5 13l4 4L19 7",stroke:a.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):e==="error"?o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:o.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:a.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):o.jsx(p.Spinner,{size:14,color:m}),o.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:e==="success"?u:e==="error"?a.errorText:u,fontFamily:f,flex:1},children:e==="success"?"Deposit confirmed":e==="error"?t||"Transaction failed":Gr[e]||t}),e==="success"&&n&&o.jsx("a",{href:`${s}/tx/${n}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:m,fontFamily:f,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),e==="error"&&o.jsx("button",{onClick:h,style:{background:"none",border:"none",fontSize:"12px",color:m,fontFamily:f,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),r>=0&&e!=="success"&&e!=="error"&&o.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${l}22`,overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:m,transformOrigin:"left center",transform:`scaleX(${(r+1)/Xr.length})`,transition:"transform 400ms ease"}})})]});function Jr(e,t,n){const s=p.addressesEqual(e.address,t),r=e.chainId===n,a=e._source==="wallet";return a&&s&&r?0:a&&r?1:!a&&s?2:!a&&r?3:4}function $r(e,t){return!t||t.length===0||t.some(n=>p.addressesEqual(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const s=on(n);return s?t.some(r=>p.addressesEqual(r,s.address)):!1})}function Js(e,t,n){let{symbol:s,name:r,logoURI:a}=t;const d=p.addressesEqual(e.address,n.address)&&e.chainId===n.chainId;d&&n.logoURI&&(a=n.logoURI),d&&!e.configToken&&s==="TOKEN"&&(s=n.symbol,r=n.symbol);const i=parseFloat((Number(t.balance)/Math.pow(10,t.decimals)).toFixed(6));return{address:e.address,name:r,symbol:s,decimals:t.decimals,balance:t.balance,balanceFormatted:i,balanceUsd:0,logoURI:a,isNative:j.isNativeToken(e.address),chainId:e.chainId}}function _r(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:s,enabled:r}=e,a=c.useContext(p.SpiceFlowProviderContext),d=(a?.mode||"7702")!=="7702",i=a?.embeddedWalletAddress,{externalAddress:u,embeddedAddress:l,activeAddress:f}=p.useProviderWallets(),m=i||l,{assets:h,refetch:x}=jn({address:m,supportedChains:s,enabled:r&&!d&&!!m,refetchInterval:3e4}),g=c.useMemo(()=>d?[]:h.filter(E=>$r(E,n)),[h,n,d]),y=d?f??u:i,C=c.useMemo(()=>{const E=new Set,v=[],T=I=>{if(!I)return;const D=I.toLowerCase();E.has(D)||(E.add(D),v.push(B.getAddress(I)))};if(T(t.address),n)for(const I of n)T(I);return v},[d,t.address,n]),S=c.useMemo(()=>C.map(E=>E.toLowerCase()).sort().join(","),[C]),b=c.useMemo(()=>JSON.stringify([...s||[]].sort()),[s]),[R,k]=c.useState([]),w=c.useRef(0),F=c.useRef(async()=>{}),A=c.useCallback(async()=>{if(!r||!y||C.length===0){w.current++,k([]);return}const E=++w.current,v=B.getAddress(y),T=d?s&&s.length>0?s:[t.chainId]:[t.chainId],I=[];for(const H of C){const z=H.toLowerCase();if(z===j.ZERO_ADDRESS)continue;if(j.isNativeToken(z)){const P=p.addressesEqual(z,t.address)&&!T.includes(t.chainId)?[t.chainId,...T]:T;for(const Q of P){const q=p.getChainConfig(Q)?.supportedTokens?.find(X=>j.isNativeToken(X.address));q&&I.push({address:H,chainId:Q,configToken:{decimals:q.decimals,symbol:q.symbol,name:q.name,logo:q.logo}})}continue}if(z===t.address.toLowerCase()){const P=p.getChainConfig(t.chainId)?.supportedTokens?.find(Q=>p.addressesEqual(Q.address,z));I.push({address:H,chainId:t.chainId,configToken:P?{decimals:P.decimals,symbol:P.symbol,name:P.name,logo:P.logo}:void 0});continue}let W=!1;for(const P of T){const Q=p.getChainConfig(P)?.supportedTokens?.find(q=>p.addressesEqual(q.address,z));if(Q){I.push({address:H,chainId:P,configToken:{decimals:Q.decimals,symbol:Q.symbol,name:Q.name,logo:Q.logo}}),W=!0;break}}W||I.push({address:H,chainId:t.chainId})}const D=new Map;for(const H of I){const z=D.get(H.chainId)||[];z.push(H),D.set(H.chainId,z)}const U=async(H,z)=>{try{const W=await Nt.readContract(H,{address:z.address,abi:B.erc20Abi,functionName:"balanceOf",args:[v]}),{decimals:P,symbol:Q,name:q,logoURI:X}=await xr(H,z.address,z.configToken);return Js(z,{decimals:P,symbol:Q,name:q,logoURI:X,balance:W},t)}catch{return null}},N=await Promise.all(Array.from(D.entries()).map(async([H,z])=>{let W;try{W=p.getClientForChain(H)}catch{return[]}const P=z.filter(L=>j.isNativeToken(L.address)),Q=z.filter(L=>!j.isNativeToken(L.address)),q=await Promise.all(P.map(async L=>{const te=await W.getBalance({address:v}).catch(()=>0n),de=p.getChainConfig(H)?.nativeCurrency;return Js(L,{decimals:L.configToken?.decimals??de?.decimals??18,symbol:L.configToken?.symbol??de?.symbol??"ETH",name:L.configToken?.name??de?.name??"Ether",logoURI:L.configToken?.logo,balance:te},t)}));if(Q.length===0)return q;const X=[],G=[];for(const L of Q){const te=X.length;X.push({address:L.address,abi:B.erc20Abi,functionName:"balanceOf",args:[v]}),L.configToken||X.push({address:L.address,abi:B.erc20Abi,functionName:"decimals"},{address:L.address,abi:B.erc20Abi,functionName:"symbol"},{address:L.address,abi:B.erc20Abi,functionName:"name"}),G.push({start:te,item:L})}let ce=null;try{ce=await W.multicall({contracts:X})}catch{ce=null}if(ce){const L=G.map(({start:te,item:de})=>{const ie=ce[te],Ie=ie?.status==="success"?ie.result:0n;let ye,ue,Te,O;if(de.configToken)ye=de.configToken.decimals,ue=de.configToken.symbol,Te=de.configToken.name,O=de.configToken.logo;else{const ee=ce[te+1],oe=ce[te+2],se=ce[te+3];ye=ee?.status==="success"?Number(ee.result):18,ue=oe?.status==="success"?oe.result:"TOKEN",Te=se?.status==="success"?se.result:ue}return Js(de,{decimals:ye,symbol:ue,name:Te,logoURI:O,balance:Ie},t)});return[...q,...L]}const V=await Promise.all(Q.map(L=>U(W,L)));return[...q,...V.filter(L=>L!==null)]}));E===w.current&&k(N.flat())},[r,d,y,S,b,t.address,t.chainId,t.symbol,t.logoURI]);c.useEffect(()=>{F.current=A},[A]),c.useEffect(()=>{if(!r){k([]);return}F.current();const E=setInterval(()=>{F.current()},15e3);return()=>clearInterval(E)},[r,d,y,S,b,t.address,t.chainId]);const M=c.useCallback(()=>{A()},[A]);return{displayAssets:c.useMemo(()=>{const E=[],v=R.filter(I=>I.balance>0n);for(const I of v)E.push({...I,_source:"wallet"});for(const I of g)E.push({...I,_source:"spice"});const T=t.address.toLowerCase();return E.sort((I,D)=>Jr(I,T,t.chainId)-Jr(D,T,t.chainId)),E},[R,g,t.address,t.chainId]),filteredSpiceAssets:g,walletAssets:R,embeddedWalletAddress:m,externalAddress:u,isNon7702:d,refreshSpiceAssets:x,refreshWalletAssets:M}}async function Dc(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:r,chainId:a,config:d}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const i=(await p.getClientForChain(a).simulateContract({address:d.quoterV2,abi:j.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(i[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:i[0],sqrtPriceX96After:i[1],gasEstimate:i[3]}}async function ea(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>Dc({...e,fee:r})));let s=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!s||a.value.amountOut>s.amountOut)&&(s={...a.value,fee:t[r]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}const Mc=[{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 Nc(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:r,chainId:a,config:d}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const i=(await p.getClientForChain(a).simulateContract({address:d.quoterV2,abi:Mc,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(i[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:i[0],sqrtPriceX96After:i[1],gasEstimate:i[3]}}async function Wc(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>Nc({...e,fee:r})));let s=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!s||a.value.amountIn<s.amountIn)&&(s={...a.value,fee:t[r]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}function Pc(e){return e.type==="swap"}const $s=.02,Uc=[1,8453,42161,10,137,43114,56],Oc="https://api.1inch.dev/swap/v6.0";function ta(e,t){return j.applySlippage(e,t)}function zc(e){const t=e?.baseUrl??Oc;return{name:"1inch",chainIds:e?.chainIds??Uc,resolve:async(n,s,r)=>{const a=n.maxSlippage??$s,d=a*100,i=j.isNativeToken(n.tokenIn)?j.NATIVE_TOKEN_ADDRESS:n.tokenIn,u=j.isNativeToken(n.tokenOut)?j.NATIVE_TOKEN_ADDRESS:n.tokenOut,l=j.isNativeToken(n.tokenIn);try{const f=new URL(`${t}/${s}/swap`);f.searchParams.set("src",i),f.searchParams.set("dst",u),f.searchParams.set("amount",n.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",d.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const m={Accept:"application/json"};e?.apiKey&&(m.Authorization=`Bearer ${e.apiKey}`);const h=await fetch(f.toString(),{headers:m});if(!h.ok)throw new p.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${h.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 ${h.status}`});const x=await h.json();if(!x.dstAmount||!x.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const g=BigInt(x.dstAmount);if(g<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const y=ta(g,a),C=[];return x.tx.to&&!l&&C.push({to:n.tokenIn,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"approve",args:[x.tx.to,n.amountIn]})}),C.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:g,amountOutMinimum:y,calls:C}}catch(f){if(f instanceof p.SpiceflowError)throw f;const m=f instanceof Error?f.message:String(f);throw new p.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${m}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:m})}}}}const na=[4114,5115],_s={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},sa={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]},oa={swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4]};function eo(e){return{name:"satsuma",chainIds:e.chainIds??na,resolve:async(t,n,s)=>{const r=t.maxSlippage??$s,a=j.isNativeToken(t.tokenIn);let d;try{d=await ea({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const i=ta(d.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:B.encodeFunctionData({abi:j.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:d.fee,recipient:s,amountIn:t.amountIn,amountOutMinimum:i,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:d.amountOut,amountOutMinimum:i,calls:u}}}}function to(e){return{name:"satsuma",chainIds:e.chainIds??na,resolve:async(t,n,s)=>{const r=t.maxSlippage??$s,a=j.isNativeToken(t.tokenIn);let d;try{d=await Wc({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const i=BigInt(Math.round(r*1e4)),u=d.amountIn+d.amountIn*i/10000n,l=[];return l.push({to:e.swapRouter,value:a?u:0n,data:B.encodeFunctionData({abi:Lc,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:d.fee,recipient:s,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:d.amountIn,amountInMax:u,amountOut:t.amountOut,calls:l}}}}const Lc=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"exactOutputSingle",outputs:[{name:"amountIn",type:"uint256"}],stateMutability:"payable",type:"function"}];function ra(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(eo(e.satsuma)),t.push(zc(e?.oneInch));function n(r){return t.find(a=>a.chainIds.includes(r))}async function s(r,a,d){const i=[],u=[];for(const l of r){if(!Pc(l)){i.push(l);continue}const f=n(a);if(!f)throw new p.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${l.tokenIn} \u2192 ${l.tokenOut}.`,{chainId:a,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});const m=await f.resolve(l,a,d);if(!m)throw new p.SpiceflowError("NO_LIQUIDITY",`${f.name} returned no quote for ${l.tokenIn} \u2192 ${l.tokenOut} on chain ${a}.`,{venue:f.name,chainId:a,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});i.push(...m.calls),u.push(m)}return{calls:i,resolvedSwaps:u}}return{resolveSwapIntents:s,getVenueForChain:n,venues:t}}const cn="0x0000000000000000000000000000000000000000",no=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],aa=cn,ia=.02,Hc=1800,la={quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",cn]},so={quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",cn],v3:{swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4]}},ca=B.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)"]),Qc=B.parseAbi(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),Vc=B.parseAbi(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),qc="0x10",Kc="06",Yc="07",Zc="08",Gc="09",ns="0c",ss="0e",Xc=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],Jc=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],Tn=(e,t)=>e.toLowerCase()===t.toLowerCase();function oo(e){return j.isNativeToken(e)?cn:e}function $c(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function da(e,t,n,s){const r=[],[a,d]=$c(e,t);for(const{fee:i,tickSpacing:u}of no)r.push({kind:"single",poolKey:{currency0:a,currency1:d,fee:i,tickSpacing:u,hooks:aa},zeroForOne:Tn(e,a)});for(const i of n)if(!(Tn(i,e)||Tn(i,t)))for(const u of no)for(const l of no){const f=(m,h)=>({intermediateCurrency:m,fee:h.fee,tickSpacing:h.tickSpacing,hooks:aa,hookData:"0x"});r.push({kind:"multi",path:s==="in"?[f(i,u),f(t,l)]:[f(e,u),f(i,l)]})}return r}async function ua(e,t,n,s,r,a){const d=p.getClientForChain(e),i=(await Promise.allSettled(n.map(async u=>{const{result:l}=u.kind==="single"?await d.simulateContract({address:t.quoter,abi:ca,functionName:a==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:u.poolKey,zeroForOne:u.zeroForOne,exactAmount:r,hookData:"0x"}]}):await d.simulateContract({address:t.quoter,abi:ca,functionName:a==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:s,path:u.path,exactAmount:r}]}),f=l[0];if(f<=0n)throw new Error("zero quote");return{candidate:u,amount:f}}))).filter(u=>u.status==="fulfilled").map(u=>u.value);return i.length===0?null:(i.sort((u,l)=>u.amount<l.amount?-1:u.amount>l.amount?1:0),a==="in"?i[i.length-1]:i[0])}function pa(e){const{candidate:t,direction:n,currencyIn:s,currencyOut:r,recipient:a,exactAmount:d,limitAmount:i,deadline:u}=e;let l,f;t.kind==="single"?(l=n==="in"?`0x${Kc}${ns}${ss}`:`0x${Zc}${ns}${ss}`,f=B.encodeAbiParameters([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:Xc},{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"]:d,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i,hookData:"0x"}])):(l=n==="in"?`0x${Yc}${ns}${ss}`:`0x${Gc}${ns}${ss}`,f=B.encodeAbiParameters([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:Jc},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"}]}],[{[n==="in"?"currencyIn":"currencyOut"]:n==="in"?s:r,path:t.path,[n==="in"?"amountIn":"amountOut"]:d,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i}]));const m=B.encodeAbiParameters([{type:"address"},{type:"uint256"}],[s,n==="in"?d:i]),h=B.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[r,a,0n]),x=B.encodeAbiParameters([{type:"bytes"},{type:"bytes[]"}],[l,[f,m,h]]);return B.encodeFunctionData({abi:Vc,functionName:"execute",args:[qc,[x],u]})}function fa(){return BigInt(Math.floor(Date.now()/1e3)+Hc)}function ma(e,t,n,s){return{to:e.permit2,value:0n,data:B.encodeFunctionData({abi:Qc,functionName:"approve",args:[t,e.universalRouter,n,Number(s)]})}}function ha(e){const t=e.v3?eo({...e.v3,chainIds:e.chainIds}):null;return{name:"univ4",chainIds:e.chainIds,resolve:async(n,s,r)=>{const a=n.maxSlippage??ia,d=oo(n.tokenIn),i=oo(n.tokenOut),u=j.isNativeToken(n.tokenIn),l=e.hubCurrencies??[cn];let f=null;if(!Tn(d,i)&&n.amountIn>0n){const m=await ua(s,e,da(d,i,l,"in"),d,n.amountIn,"in").catch(()=>null);if(m){const h=j.applySlippage(m.amount,a),x=fa(),g=[];u||(g.push({to:n.tokenIn,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"approve",args:[e.permit2,n.amountIn]})}),g.push(ma(e,n.tokenIn,n.amountIn,x))),g.push({to:e.universalRouter,value:u?n.amountIn:0n,data:pa({candidate:m.candidate,direction:"in",currencyIn:d,currencyOut:i,recipient:r,exactAmount:n.amountIn,limitAmount:h,deadline:x})}),f={venue:"univ4",amountOut:m.amount,amountOutMinimum:h,calls:g}}}return!f&&t?t.resolve(n,s,r):f}}}function ro(e){return{name:"univ4",chainIds:e.chainIds,resolve:async(t,n,s)=>{if(j.isNativeToken(t.tokenIn))return null;const r=oo(t.tokenOut);if(Tn(t.tokenIn,r)||t.amountOut<=0n)return null;const a=t.maxSlippage??ia,d=e.hubCurrencies??[cn],i=await ua(n,e,da(t.tokenIn,r,d,"out"),r,t.amountOut,"out").catch(()=>null);if(!i)return null;const u=BigInt(Math.round(a*1e4)),l=i.amount+i.amount*u/10000n,f=fa();return{venue:"univ4",amountIn:i.amount,amountInMax:l,amountOut:t.amountOut,calls:[ma(e,t.tokenIn,l,f),{to:e.universalRouter,value:0n,data:pa({candidate:i.candidate,direction:"out",currencyIn:t.tokenIn,currencyOut:r,recipient:s,exactAmount:t.amountOut,limitAmount:l,deadline:f})}]}}}}function ga(e){const t=e?.customVenues??[];async function n(s,r,a){const d=t.filter(l=>l.chainIds.includes(r));if(d.length===0)throw new p.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const i=(await Promise.allSettled(d.map(async l=>({venue:l,quote:await l.resolve(s,r,a)})))).filter(l=>l.status==="fulfilled").map(l=>l.value).filter(l=>l.quote!==null);if(i.length===0)throw new p.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${r}`,{chainId:r,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut.toString()});const u=i.find(l=>l.venue.preferred);return u?u.quote:(i.sort((l,f)=>l.quote.amountIn<f.quote.amountIn?-1:l.quote.amountIn>f.quote.amountIn?1:0),i[0].quote)}return{getQuote:n,venues:t}}const xa=ra({satsuma:_s,customVenues:[ha(so)]});async function _c(e){const t=xa.getVenueForChain(e.chainId);if(!t)throw new Error(`No swap venue configured for chain ${e.chainId}.`);const n=await t.resolve({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn},e.chainId,e.recipient);if(!n)throw new Error("No liquidity for this pair.");return n}function ya(e){const{direction:t,selectedAsset:n,destinationToken:s,chainId:r,recipient:a,paymentAmount:d,resolveExactOutputSwap:i}=e,[u,l]=c.useState(!1),[f,m]=c.useState(null),[h,x]=c.useState(null),[g,y]=c.useState(null),[C,S]=c.useState(null),[b,R]=c.useState(null),[k,w]=c.useState(null),[F,A]=c.useState(null),[M,E]=c.useState(null),v=c.useRef(null),T=c.useRef(null),I=c.useRef(0),D=c.useRef(new Map),U=c.useMemo(()=>xa,[]),N=c.useMemo(()=>ga({customVenues:[...i?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:i}]:[],to(_s),to(sa),to(oa),ro(la),ro(so)]}),[i,r]),H=c.useMemo(()=>{if(!n?.asset)return null;const L=zt(n.asset,r);if(L)return L;const te=Yt(n.asset.address,r,n.asset.chainId);return te?te.address:null},[n?.asset,r]),z=c.useMemo(()=>n?.asset?On(n.asset,r):[],[n?.asset,r]),W=c.useMemo(()=>z.map(L=>L.toLowerCase()).join(","),[z]);c.useEffect(()=>{let L=!1;if(T.current&&(clearTimeout(T.current),T.current=null),!n?.asset||z.length<=1){E(null);return}return T.current=setTimeout(async()=>{const te=t==="input"?n.amount:d||"0";let de=0n;try{de=t==="input"?B.parseUnits(te,n.asset.decimals):0n}catch{de=0n}try{const ie=await Fo(n.asset,r,{requiredAmount:de});L||E(ie)}catch{L||E(null)}},400),()=>{L=!0,T.current&&(clearTimeout(T.current),T.current=null)}},[n?.asset,n?.amount,r,z.length,W,t,d]);const P=c.useMemo(()=>M??H,[M,H]),Q=c.useMemo(()=>!n?.asset||!P?[]:[P,...z.filter(L=>L.toLowerCase()!==P.toLowerCase())],[n?.asset,P,z]),q=c.useMemo(()=>!n?.asset||!In(n.asset.address,n.asset.chainId,s.address,s.chainId)||!P?!1:p.addressesEqual(P,s.address),[n,s.address,s.chainId,P]),X=P?p.addressesEqual(P,s.address):!1,G=t==="output"&&parseFloat(d||"0")===0,ce=!!n?.asset&&!q&&!X&&!G,V=ce?F??P:P;return c.useEffect(()=>{v.current&&clearTimeout(v.current);const L=t==="input"?n?.amount:d,te=parseFloat(L||"0");if(!ce||!Number.isFinite(te)||te<=0||!n?.asset||!a||Q.length===0){I.current++,x(null),y(null),S(null),R(null),w(null),A(null),m(null),l(!1);return}const de=n.asset.decimals;let ie;try{ie=t==="input"?B.parseUnits(n.amount,de):B.parseUnits(d||"0",s.decimals)}catch{I.current++,m("Invalid amount"),l(!1);return}const Ie=++I.current,ye=()=>Ie!==I.current;l(!0);const ue=t==="output"?150:400,Te=async(O,ee,oe)=>{for(const se of Q){const Z=`${t}:${r}:${se.toLowerCase()}:${s.address.toLowerCase()}:${ie.toString()}`,le=D.current.get(Z),fe=le&&le.expiresAt>Date.now()?O(le):void 0;if(fe)return{quote:fe,tokenIn:se};const $=await oe(se);if(ye())return"stale";if($)return D.current.set(Z,{expiresAt:Date.now()+3e4,direction:t,...ee($)}),{quote:$,tokenIn:se}}return null};return v.current=setTimeout(async()=>{try{if(t==="input"){const O=U.getVenueForChain(r);if(!O)throw new Error("No swap venue for this chain");const ee=await Te(se=>se.resolvedSwap,se=>({resolvedSwap:se}),se=>O.resolve({type:"swap",tokenIn:se,tokenOut:s.address,amountIn:ie},r,a));if(ee==="stale")return;if(!ee)throw new Error("No liquidity for this pair");A(ee.tokenIn),w(ee.quote.amountOut),S(ee.quote),R(null);const oe=parseFloat(B.formatUnits(ee.quote.amountOut,s.decimals));x(oe<.01?oe.toPrecision(4):oe.toLocaleString(void 0,{maximumFractionDigits:6})),y(null),m(null)}else{const O=await Te(ee=>ee.exactOutputSwap,ee=>({exactOutputSwap:ee}),async ee=>{try{return await N.getQuote({tokenIn:ee,tokenOut:s.address,amountOut:ie},r,a)}catch{return null}});if(O==="stale")return;if(!O)throw new Error("No liquidity for this pair");A(O.tokenIn),R(O.quote),S(null),w(null),y(parseFloat(B.formatUnits(O.quote.amountIn,de)).toFixed(6)),x(null),m(null)}}catch(O){if(ye())return;const ee=O instanceof Error?O.message:"Failed to get quote";m(ee),x(null),y(null),S(null),R(null),w(null),A(null)}finally{ye()||l(!1)}},ue),()=>{v.current&&clearTimeout(v.current)}},[t,ce,n?.amount,n?.asset?.address,n?.asset?.decimals,d,Q,r,s.address,s.decimals,a,U,N]),{isQuoting:u,quoteError:f,estimatedOutput:h,estimatedInput:g,resolvedSwap:C,exactOutputSwap:b,quoteAmountOut:k,resolvedTokenIn:V,isDirect:X,needsSwap:ce,selectedIsEquivalent:q}}const ed=()=>{},td=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:s,sourceChains:r,supportedSourceAssets:a,buildActionCalls:d,feeExecutionMode:i="user-transfer",buildSpicenetBatch:u,onPayExecute:l,resolveExactOutputSwap:f,actionLabel:m,amountDirection:h="input",swapDescription:x,directDescription:g,paymentAmount:y,amountInputMode:C="fixed",minPaymentAmount:S,maxPaymentAmount:b,onAmountChange:R,styles:k,dark:w,title:F,subtitle:A,onAddFunds:M,onSuccess:E,onError:v})=>{const T=h==="output",{theme:I,dark:D,primaryColor:U,dk:N,palette:H,fontFamily:z,monoFont:W,inputDark:P,cardBg:Q,cardBorder:q,textPrimary:X,textSecondary:G,subtitleText:ce}=p.useSpiceBrand(k,w),V=c.useMemo(()=>P?{...I,colors:{...I.colors,secondary:N.cardBg,surfaceHover:N.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:I,[P,I,N.cardBg,N.hoverBg]),L=c.useMemo(()=>s.logoURI?s:{...s,logoURI:gs[s.symbol]},[s]),te=L.chainId,de=c.useContext(p.SpiceFlowProviderContext),ie=(de?.mode||"7702")!=="7702",Ie=!!de?.isWhitelistGateActive,ye=!!de?.isWhitelistConfigured&&de?.isUserWhitelisted!==!0,ue=c.useMemo(()=>r??de?.supportedChainIds??[],[r,de?.supportedChainIds]),Te=c.useMemo(()=>{if(Ie)return[];if(a)return a;const Ce=de?.allowedTokens;if(!Ce||Ce.length===0)return;const mt=new Set(Ce.map(Ot=>Ot.toLowerCase())),Nn=[],pn=new Set;for(const Ot of ue){const is=p.getChainConfig(Ot);for(const ls of is?.supportedTokens??[]){if(!mt.has(ls.symbol.toLowerCase()))continue;const uo=ls.address.toLowerCase();pn.has(uo)||(pn.add(uo),Nn.push(ls.address))}}return Nn},[a,de?.allowedTokens,ue,Ie]),{address:O,isConnected:ee,isReady:oe,isAuthenticated:se,provider:Z}=p.useWallet(),{execute:le,estimate:fe}=hn(),{externalWallet:$,embeddedAddress:xe,activeWallet:He,activeAddress:Xe}=p.useProviderWallets(),yt=de?.externalWalletAddress,ht=de?.embeddedWalletAddress||xe,{displayAssets:Ze,filteredSpiceAssets:me,embeddedWalletAddress:Ae,refreshSpiceAssets:De,refreshWalletAssets:Ge}=_r({destinationToken:L,supportedSourceAssets:Te,sourceChains:ue,enabled:e&&(ie?!!yt:!!ht)}),vt=Ie||T||ie?Ze:me,[re,it]=c.useState(null),[pe,je]=c.useState(y||""),[be,Qe]=c.useState(!1),[gt,St]=c.useState(null),Ne=c.useRef(v);Ne.current=v;const It=c.useCallback(Ce=>{St(Ce),typeof Ce=="string"&&Ce&&Ne.current?.(new Error(Ce),p.getRelayerErrorDetail(Ce))},[]),[Le,lt]=c.useState("idle"),[Wt,Ve]=c.useState(""),[tt,At]=c.useState(null),[Dt,we]=c.useState(!1),[Se,xt]=c.useState(null),[nt,ge]=c.useState(null),[Zt,st]=c.useState(!1),[Ct,Ee]=c.useState(!1),[Tt,ot]=c.useState(null),ct=c.useRef(re),Re=c.useRef(!1),_e=c.useRef(null),rt=c.useRef(null),Pt=c.useRef(null),Et=c.useRef(null),Mt=c.useRef(null);c.useEffect(()=>{ct.current=re},[re]);const Pe=C==="adjustable"?pe:y||"0",bt=Ae||xe||O,{isQuoting:Ue,quoteError:dt,estimatedOutput:at,resolvedSwap:pt,exactOutputSwap:qe,quoteAmountOut:ft,resolvedTokenIn:ut,isDirect:et,needsSwap:Y,selectedIsEquivalent:_}=ya({direction:h,selectedAsset:re,destinationToken:L,chainId:te,recipient:bt,paymentAmount:Pe,resolveExactOutputSwap:f}),ne=T?parseFloat(Pe||"0"):parseFloat(re?.amount||"")||0,Fe=re?.asset?._source==="wallet",J=!!re?.asset&&Fe&&re.asset.chainId!==te,ke=c.useMemo(()=>re?.asset?me.find(Ce=>p.addressesEqual(Ce.address,re.asset.address))?.balanceFormatted??0:0,[re,me]),Ke=Fe?re?.asset.balanceFormatted??0:ke,Oe=c.useMemo(()=>{if(!re?.asset)return!1;if(T)return nt?Lt(nt.grossAmount,nt.decimals,re.asset.decimals)>re.asset.balance:_||et?ne>re.asset.balanceFormatted:qe?parseFloat(B.formatUnits(qe.amountInMax,re.asset.decimals))>re.asset.balanceFormatted:!1;if(nt){const Ce=Lt(nt.grossAmount,nt.decimals,re.asset.decimals);return Fe?Ce>re.asset.balance:parseFloat(B.formatUnits(Ce,re.asset.decimals))>Ke}return ne>Ke},[re,T,nt,_,ne,qe,Ke,Fe,et]);c.useEffect(()=>{e||(it(null),It(null),Qe(!1),lt("idle"),Ve(""),At(null),we(!1),xt(null),ge(null),st(!1),Ee(!1),ot(null),Re.current=!1,C==="adjustable"&&je(y||""),_e.current&&(_e.current.abort(),_e.current=null))},[e]);const Be=c.useCallback(Ce=>{it(mt=>({asset:Ce,amount:mt?.asset?.address===Ce.address&&mt?.asset?.chainId===Ce.chainId&&mt.amount||""})),It(null),ot(null),Ee(!1)},[]),jt=c.useCallback(Ce=>{it(mt=>mt&&{...mt,amount:Ce}),It(null),ot(null),Ee(!1)},[]),We=c.useCallback(Ce=>{let mt=Ce;b&&parseFloat(mt)>parseFloat(b)&&(mt=b),je(mt),R?.(mt),It(null),ot(null),Ee(!1)},[b,R]),Me=c.useCallback(Ce=>{lt({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[Ce.step]||"executing"),Ve(Ce.message),Ce.txHash&&At(Ce.txHash)},[]),ze=c.useMemo(()=>({currentPaymentAmount:Pe,destinationToken:L,embeddedWalletAddress:Ae,providerEmbeddedAddress:xe,externalWalletAddress:yt,address:O,isNon7702:ie,isPayMode:T,resolvedChainId:te,buildActionCalls:d,feeExecutionMode:i,buildSpicenetBatch:u,selectedAsset:re,needsSwap:Y,resolvedSwap:pt,exactOutputSwap:qe,quoteAmountOut:ft,resolvedTokenIn:ut}),[Pe,L,Ae,xe,yt,O,ie,T,te,d,i,u,re,Y,pt,qe,ft,ut]),Je=c.useCallback(Ce=>Rr({...ze,requestTimestampMs:rt.current??Date.now()},Ce),[ze]),kt=c.useCallback(Ce=>Dr({...ze,requestTimestampMs:rt.current??Date.now()},Ce),[ze]),Ft=c.useMemo(()=>re?.asset?Y&&ut?ut:re.asset.chainId===te?re.asset.address:ut??zt(re.asset,te)??L.address:L.address,[re,L.address,Y,te,ut]),dn=c.useCallback(()=>(rt.current=Date.now(),Vr(Mt.current)),[]),Rt=c.useMemo(()=>re?.asset?p.addressesEqual(re.asset.address,L.address)&&re.asset.chainId===L.chainId:!1,[re,L.address,L.chainId]),Ut=Rt&&(ie||T),wt=Ut&&ne>0&&!!re?.asset,Gt=ye&&!Ut,un=c.useMemo(()=>{if(!wt)return null;let Ce;try{Ce=B.parseUnits(Pe||"0",L.decimals)}catch{return null}return{symbol:L.symbol,decimals:L.decimals,grossAmount:Ce,netAmount:Ce,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[wt,Pe,L.symbol,L.decimals]),Rn=gt,Xt=c.useMemo(()=>!(!re?.asset||ne<=0),[re,ne,wt]),Ht=c.useMemo(()=>!e||be||Le!=="idle"||!Xt||wt||!re?.asset?null:[T?"pay":"supply",h,re.asset.address.toLowerCase(),re.asset.chainId,re.amount,Pe,L.address.toLowerCase(),L.chainId,te,ut?.toLowerCase()??"",Y?"swap":"direct",et?"direct-token":"routed-token",ie?"non7702":"7702",Rt?"source-dest":"cross-chain",Ue?"quoting":"quoted",qe?.amountIn?.toString()??"",qe?.amountInMax?.toString()??"",qe?.venue??"",pt?.amountOut?.toString()??"",ft?.toString()??"",Ae??"",xe??"",O??""].join("|"),[e,be,Le,Xt,wt,re,T,h,Pe,L,te,ut,Y,et,ie,Rt,Ue,qe,pt,ft,Ae,xe,O]),yn=c.useCallback(Ce=>Wr({signal:Ce,selectedAsset:re,isPayMode:T,parsedAmount:ne,needsSwap:Y,exactOutputSwap:qe,isNon7702:ie,isSourceDestToken:Rt,currentPaymentAmount:Pe,destinationToken:L,feeExecutionMode:i,resolvedTokenIn:ut,embeddedWalletAddress:Ae,providerEmbeddedAddress:xe,resolvedChainId:te,isConnected:ee,address:O,ready:oe,authenticated:se,isDirect:et,resolvedSwap:pt,isQuoting:Ue,executionTokenAddress:Ft,buildPayChainBatches:Je,buildSupplyChainBatches:kt,estimate:fe}),[re,T,ne,Y,qe,ie,Rt,Pe,L,i,ut,Ae,xe,Je,fe,te,ee,O,oe,se,et,pt,Ue,kt,Ft]);c.useEffect(()=>{Pt.current=yn},[yn]);const os=c.useCallback(Ce=>Nr({asset:Ce,isPayMode:T,isNon7702:ie,needsSwap:Y,isQuoting:Ue,embeddedWalletAddress:Ae,buildSupplyChainBatches:kt,estimate:fe,executionTokenAddress:Ft,feeExecutionMode:i}),[T,ie,Y,Ue,Ae,kt,fe,Ft,i]);Pn({shouldRun:e&&!be&&Le==="idle"&&Xt&&!wt&&!Ue&&!!Ht,deps:[e,be,Le,Xt,wt,un,Ue,Ht],onSkip:()=>{if(!e){st(!1),Ee(!1),ot(null),ge(null);return}if(be||Le!=="idle"){st(!1);return}if(!Xt){ge(null),st(!1),Ee(!1),ot(null);return}if(wt){ge(un),st(!1),Ee(!0),ot(null);return}Ue&&(st(!1),Ee(!1))},onCleanup:()=>st(!1),delayMs:500,backgroundIntervalMs:5e3,run:async({isBackground:Ce,isCurrent:mt,signal:Nn})=>{const pn=Ht;Ce||(ot(null),st(!0));try{const Ot=await Pt.current?.(Nn);if(!mt())return;Ot&&pn?(Et.current={key:pn,quote:Ot},ge(Ot.preview),Ee(!0)):(Et.current=null,ge(null),Ee(!1)),ot(null)}catch(Ot){if(!mt())return;if(Ce&&Et.current?.key===pn){console.warn("[SpiceSupply] fee refresh failed:",Ot);return}const is=p.sanitizeError(Ot,"Unable to calculate fees for this action.");Et.current=null,ge(null),Ee(!1),ot(is)}finally{mt()&&st(!1)}}});const K=c.useCallback(()=>(rt.current=Date.now(),Kr(Mt.current)),[]);c.useEffect(()=>{!T&&Le==="success"&&tt&&(De(),E?.(tt))},[T,Le,tt,De,E]),c.useEffect(()=>{if(!T||Se?.status!=="success"||Re.current||!O)return;Re.current=!0;const Ce=ct.current;!Ce?.asset||Ce.asset?._source==="wallet"||De()},[T,Se?.status,O,De]);const ae=c.useRef(E),ve=c.useRef(v);c.useEffect(()=>{ae.current=E},[E]),c.useEffect(()=>{ve.current=v},[v]),c.useEffect(()=>{e&&(De(),Ge())},[e,De,Ge]),c.useEffect(()=>{T&&(Se?.status==="success"&&ae.current?.(Se.txHash||""),Se?.status==="failed"&&ve.current?.(new Error("Payment execution failed")))},[T,Se?.status]);const he=c.useCallback(()=>{we(!1),xt(null),it(null),Re.current=!1,De(),Ge()},[De,Ge]);Mt.current={selectedAsset:re,parsedAmount:ne,currentPaymentAmount:Pe,isInsufficientBalance:Oe,isPayMode:T,isNon7702:ie,isSourceDestToken:Rt,needsSwap:Y,exactOutputSwap:qe,selectedIsEquivalent:_,resolvedTokenIn:ut,embeddedWalletAddress:Ae,providerEmbeddedAddress:xe,externalWallet:$,externalWalletAddress:yt,activeSignerWallet:He,activeSignerAddress:Xe,address:O,isConnected:ee,ready:oe,authenticated:se,provider:Z,resolvedChainId:te,executionTokenAddress:Ft,destinationToken:L,buildActionCalls:d,feeExecutionMode:i,buildSpicenetBatch:u,onPayExecute:l,onSuccess:E,feeQuote:Ht&&Et.current?.key===Ht?Et.current.quote:null,execution:{estimate:fe,execute:le,buildPayChainBatches:Je,buildSupplyChainBatches:kt,onProgress:Me},ui:{setError:It,setStep:lt,setStatusMsg:Ve,setTxHash:At,setIsExecuting:Qe,setShowStatusPanel:we,setPaymentResult:xt},refs:{spiceDepositSubmittedRef:Re,abortControllerRef:_e}};const $e=y?.trim(),Ye=T&&C==="fixed"&&$e!==void 0&&$e!==""&&ne===0,Jt=T?(Ye||!!re?.asset)&&ne>=0&&!Oe&&!be&&(Ye||wt||Ct)&&!Tt&&(Ye||!Y||!!qe)&&!Gt:!!re?.asset&&ne>0&&!Oe&&!be&&(Ut||Ct)&&!Tt&&(J||et||!!pt&&!Ue)&&!Gt,Dn=et?g||`Your ${L.symbol} will be used directly.`:x||"Your assets will be swapped and used in a single atomic transaction.",Mn=(te?p.getChainConfig(te):void 0)?.viemChain?.blockExplorers?.default?.url??"",rs=Xr.indexOf(Le),as=be?(Gr[Le]||"EXECUTING...").toUpperCase():Le==="success"?"DONE":Oe?"INSUFFICIENT BALANCE":Y&&dt&&!Ue?"QUOTE ERROR":m.toUpperCase(),Ca=c.useMemo(()=>{if(Se?.status==="success")return"DONE";if(be)return"PAYING...";if(Oe&&re?.asset)return`INSUFFICIENT ${re.asset.symbol}`;if(Y&&dt&&!Ue)return"QUOTE ERROR";if(m)return m.toUpperCase();const Ce=ne>0?` ${Pe} ${L.symbol}`:"";return Y?`SWAP & PAY${Ce}`:`PAY${Ce}`},[be,Oe,re,m,ne,Pe,L.symbol,Y,dt,Ue,Se?.status]),ba=Le==="success"?()=>{lt("idle"),it(null),At(null),De()}:dn,ka=Le==="success"?!1:!Jt;if(!e)return null;const ao=T?F||`Pay ${L.symbol}`:m,io=T?A:o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[o.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:o.jsx(Bs,{color:ce})}),o.jsx("p",{style:{fontSize:"12px",color:ce,margin:0,lineHeight:"1.4",fontFamily:z},children:Dn})]}),lo={...k,button:{...k?.button,backgroundColor:U}},co=Xt&&o.jsx(Rs,{fontFamily:z,textPrimary:X,textSecondary:G,cardBg:Q,cardBorder:q,resolvedDark:D,darkCardBorder:N.cardBorder,primaryColor:U,feePreview:nt,isLoading:Zt,errorText:Tt,directExecutionFeeNote:wt});if(T){const Ce=Se&&(Se.status==="success"||Se.status==="failed")?[{asset:{symbol:re?.asset?.symbol||L.symbol,address:re?.asset?.address||""},amount:Pe,txHash:Se.txHash||"",success:Se.status==="success",error:Se.status==="failed"?Se.error:void 0}]:void 0;return o.jsx(Vt,{isOpen:e,onClose:t,title:ao,subtitle:io,styles:k,dark:D,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[M&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:o.jsx(Ds,{onClick:M,color:U,fontFamily:z})}),!Ye&&o.jsx("div",{style:{marginBottom:"12px"},children:o.jsx(vn,{assets:vt,selectedAsset:re??void 0,onAssetSelect:Be,onAmountChange:ed,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:re?.asset?Y?Ue?"...":qe?`~${parseFloat(B.formatUnits(qe.amountIn,re.asset.decimals)).toFixed(6)}`:void 0:Pe??void 0:void 0,dark:D,theme:V,styles:k})}),o.jsx(Yr,{variant:"pay",destinationSymbol:L.symbol,destinationLogoURI:L.logoURI,destinationDecimals:L.decimals,primaryColor:U,fontFamily:z,textPrimary:X,textSecondary:G,cardBg:Q,cardBorder:q,dk:N,dark:D,isQuoting:Ue,quoteError:dt,estimatedOutput:at,paymentAmount:Pe,needsSwap:Y,exactOutputSwap:qe,adjustable:C==="adjustable",maxAmount:b,onAmountChange:We}),co,Rn&&o.jsx(rn,{variant:"error",palette:H,fontFamily:z,style:{marginBottom:"12px"},children:Rn}),o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:Se?.status==="success"?t:K,disabled:Se?.status==="success"?!1:!Jt,loading:be,dark:D,styles:lo,children:Ca}),Se&&Dt&&o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:D?N.shell:"white",borderRadius:D?"12px":"6px",padding:"16px 0"},children:o.jsx(zs,{type:"payment",isOpen:Se.status!=="processing",isProcessing:be||Se.status==="processing",closeOnComplete:!1,chainId:te,onRetryTx:()=>{we(!1),xt(null),K()},onNewTx:he,onClose:()=>{we(!1),xt(null)},onComplete:he,results:Ce,styles:k,dark:D})})]})})}return o.jsx(Vt,{isOpen:e,onClose:t,title:ao,subtitle:io,dark:D,styles:k,theme:I,closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[o.jsx("div",{style:{marginBottom:"16px"},children:o.jsx(vn,{assets:vt,selectedAsset:re||void 0,onAssetSelect:Be,onAmountChange:jt,disabled:be||Le==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:V,styles:k,dark:P,resolveMaxAmount:os,maxAmount:Ke>0?p.formatDecimalInput(Ke,re?.asset.decimals??L.decimals):void 0})}),re?.asset&&!et&&o.jsx(Yr,{variant:"supply",destinationSymbol:L.symbol,destinationLogoURI:L.logoURI,destinationDecimals:L.decimals,primaryColor:U,fontFamily:z,textPrimary:X,textSecondary:G,cardBg:Q,cardBorder:q,dark:D,isQuoting:Ue,quoteError:dt,estimatedOutput:at}),co,Le!=="idle"&&o.jsx(Rc,{step:Le,statusMsg:Wt,txHash:tt,explorerUrl:Mn,currentStepIdx:rs,palette:H,cardBg:Q,cardBorder:q,textPrimary:X,textSecondary:G,fontFamily:z,primaryColor:U,onRetry:()=>{lt("idle"),It(null),setTimeout(dn,50)}}),gt&&Le==="idle"&&o.jsx(rn,{variant:"error",palette:H,fontFamily:z,style:{marginBottom:"16px"},children:gt}),o.jsx(p.Button,{variant:"outline",fullWidth:!0,disabled:ka,onClick:ba,theme:I,dark:D,styles:lo,style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:W},children:as})]})})},nd=()=>{const[e,t]=c.useState("0"),[n,s]=c.useState(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:n,setSelectedAsset:s}};function sd(e,t=0){const[n,s]=c.useState(t),r=e[n]??e[0],a=c.useMemo(()=>r?BigInt(Math.round(r.months*30*24*3600)):0n,[r?.months]);return{selectedDurationIdx:n,setSelectedDurationIdx:s,selectedDuration:r,durationSeconds:a}}function od(){const{actions:e,isReady:t,isAuthenticated:n}=p.useWallet(),s=c.useContext(p.SpiceFlowProviderContext)?.embeddedWalletAddress,r=c.useRef(!1),a=c.useRef(0),d=c.useRef(null),i=c.useRef(e),[u,l]=c.useState(0);i.current=e,c.useEffect(()=>{r.current=!1,a.current=0,d.current&&(clearTimeout(d.current),d.current=null)},[s]),c.useEffect(()=>{if(!s||!t||!n||r.current)return;r.current=!0;let f=!1;return(async()=>{await qt(2e3);try{await p.ensureSmartWallet(s,i.current.signMessage),a.current=0}catch(m){console.warn("[SmartWallet] Registration failed:",m),r.current=!1,!f&&a.current<3&&(a.current+=1,d.current=setTimeout(()=>{l(h=>h+1)},5e3))}})(),()=>{f=!0,d.current&&(clearTimeout(d.current),d.current=null)}},[s,t,n,u])}Aa(),exports.SpiceFlowProvider=p.SpiceFlowProvider,exports.SpiceFlowProviderContext=p.SpiceFlowProviderContext,exports.SpiceflowError=p.SpiceflowError,exports.Spinner=p.Spinner,exports.buildDarkPalette=p.buildDarkPalette,exports.buildLightPalette=p.buildLightPalette,exports.duration=p.duration,exports.easing=p.easing,exports.font=p.font,exports.getChainConfig=p.getChainConfig,exports.getChainName=p.getChainName,exports.isSpiceflowError=p.isSpiceflowError,exports.radius=p.radius,exports.relayerService=p.relayerService,exports.resolveTheme=p.resolveTheme,exports.transition=p.transition,exports.useIsUserWhitelisted=p.useIsUserWhitelisted,exports.useSpiceBrand=p.useSpiceBrand,exports.useWallet=p.useWallet,exports.z=p.z,Object.defineProperty(exports,"NATIVE_TOKEN_ADDRESS",{enumerable:!0,get:function(){return j.ZERO_ADDRESS}}),Object.defineProperty(exports,"SPICENET_NATIVE_CHAIN_ID",{enumerable:!0,get:function(){return j.SPICENET_NATIVE_CHAIN_ID}}),Object.defineProperty(exports,"SPICE_COMBINED_FEE_RECIPIENT",{enumerable:!0,get:function(){return j.SPICE_COMBINED_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_GAS_FEE_RECIPIENT",{enumerable:!0,get:function(){return j.SPICE_GAS_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_PLATFORM_FEE_RECIPIENT",{enumerable:!0,get:function(){return j.SPICE_PLATFORM_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_SOLVER_ADDRESS",{enumerable:!0,get:function(){return j.SPICE_SOLVER_ADDRESS}}),Object.defineProperty(exports,"applySlippage",{enumerable:!0,get:function(){return j.applySlippage}}),Object.defineProperty(exports,"buildUniV3SwapCalls",{enumerable:!0,get:function(){return j.buildUniV3SwapCalls}}),Object.defineProperty(exports,"getChainIdsByNetwork",{enumerable:!0,get:function(){return j.getChainIdsByNetwork}}),Object.defineProperty(exports,"getEscrowContractAddress",{enumerable:!0,get:function(){return j.getEscrowContractAddress}}),Object.defineProperty(exports,"isNativeToken",{enumerable:!0,get:function(){return j.isNativeToken}}),Object.defineProperty(exports,"isSpicenetChainId",{enumerable:!0,get:function(){return j.isSpicenetChainId}}),Object.defineProperty(exports,"normalizeNativeTokenAddress",{enumerable:!0,get:function(){return j.normalizeNativeTokenAddress}}),Object.defineProperty(exports,"spicenetAbi",{enumerable:!0,get:function(){return j.spicenetAbi}}),Object.defineProperty(exports,"spicenetWithdrawalAbi",{enumerable:!0,get:function(){return j.spicenetAbi}}),exports.AccountDisplay=kc,exports.AddFundsLink=Ds,exports.CheckIcon=fo,exports.ChevronIcon=nn,exports.CloseIcon=Sn,exports.DetailRow=gn,exports.ProviderLogin=Os,exports.SATSUMA_CITREA_CONFIG=_s,exports.SearchInput=ds,exports.SelectChainModal=ll,exports.SpiceDeposit=il,exports.SpiceLock=Jl,exports.SpiceSupply=td,exports.SpiceWithdraw=Ml,exports.StatusBanner=rn,exports.UNIV3_BASE_CONFIG=sa,exports.UNIV3_ROBINHOOD_CONFIG=oa,exports.UNIV4_BASE_CONFIG=la,exports.UNIV4_ROBINHOOD_CONFIG=so,exports.V4_NATIVE_CURRENCY=cn,exports.areEquivalentOnChains=In,exports.buildPayChainBatches=Rr,exports.buildRoutedBatches=Rl,exports.buildSupplyChainBatches=Dr,exports.createExactOutputRegistry=ga,exports.createLiquidityRegistry=ra,exports.createSatsumaVenue=eo,exports.createUniV4ExactOutputVenue=ro,exports.createUniV4Venue=ha,exports.estimateFeePreview=Wr,exports.estimateRequiredGrossFunding=vc,exports.estimateSupplyMaxAmount=Nr,exports.executePay=Kr,exports.executeSupply=Vr,exports.findEquivalentOnChain=Yt,exports.getAssetChainTokenCandidates=On,exports.getBestUniV3Quote=ea,exports.isSupportedSupplyAsset=$r,exports.resolveAssetTokenAddressOnChain=zt,exports.resolveFundedToken=Fo,exports.resolveInputSupplySwapQuote=_c,exports.resolveRoute=Tl,exports.scaleTokenAmount=Lt,exports.useAssetInput=nd,exports.useLockDuration=sd,exports.useSmartWallet=od,exports.useSpiceAssets=jn,exports.useSpiceExecution=hn,exports.useSpicePendingDeposits=Sr,exports.useSupplyAssets=_r,exports.useSupplyQuote=ya;
|
|
85
|
+
`})]}),document.body):null;return o.jsxs(o.Fragment,{children:[re,it,M&&Cn.createPortal(o.jsx($o,{isOpen:!0,onClose:ee,supportedChains:[M.chainId],escrowOnly:!0,escrowTokenAddress:M.tokenAddress,escrowAmount:M.amount,escrowTokenDecimals:M.tokenDecimals,escrowTokenSymbol:M.tokenSymbol,styles:u,onDepositSuccess:oe}),document.body)]})},wc="0xa9059cbb";function Er(e,t,n){return j.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"transfer",args:[n,t]})}}function jr(e,t,n){return{chainId:n,calls:[Er(e,t,j.getEscrowContractAddress(n))]}}function Fr(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function Br(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith(wc)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function _n(e,t,n,s){if(!t)return[e];const r=await t({...n,requestTimestampMs:s});return r?[r,e]:[e]}function Tr(e){return e.filter(t=>t.domain!=="spicenet")}function es(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:j.normalizeNativeTokenAddress(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function Lt(e,t,n){return rr(e,t,n,"ceil")}async function Rr(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:d,isNon7702:i,isPayMode:u,resolvedChainId:l,buildActionCalls:f,feeExecutionMode:m,buildSpicenetBatch:h,selectedAsset:x,needsSwap:g,exactOutputSwap:y,resolvedTokenIn:C,requestTimestampMs:S}=e,b=B.parseUnits(n,s.decimals),R=t?.actionAmountOverride??b,k=r||a||(i?void 0:d);if(!k)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:k,chainId:l,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??b,netAmount:R,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:m,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},F=f(R,w),A={chainId:l,calls:F},M=!u&&!i?!0:x?.asset?._source==="spice",E=Fr(x??null,i,l),v=M||i||E,T=(D,U)=>({token:D,from:"escrow",to:k,amount:U}),I=(D,U,N)=>E?[jr(D,U,l),...N]:N;if(b===0n)return[A];if(g&&y){const D=C??zt(x.asset,l)??x.asset.address,U=t?.fundingAmountOverride??y.amountInMax,N=v?[T(D,U)]:[],H={to:D,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},z={chainId:l,calls:[H,...y.calls,...F],tokenTransfers:[...N,...A.tokenTransfers??[]]};if(!v)return[z];const W=await _n(z,h,{userAddress:k,destinationChainId:l,deliveryToken:D,deliveryAmount:U,deliveryRecipient:k,deliveryTransfers:es(z),sourceAsset:x.asset},S);return I(D,U,W)}if(v){const D=C??zt(x.asset,l)??s.address;if(E&&D.toLowerCase()===s.address.toLowerCase())return[A];const U=t?.fundingAmountOverride??b,N={...A,tokenTransfers:[T(D,U),...A.tokenTransfers??[]]},H=await _n(N,h,{userAddress:k,destinationChainId:l,deliveryToken:D,deliveryAmount:U,deliveryRecipient:k,deliveryTransfers:es(N),sourceAsset:x.asset},S);return I(D,U,H)}return[A]}async function Dr(e,t){const{selectedAsset:n,embeddedWalletAddress:s,externalWalletAddress:r,recipient:a,resolvedChainId:d,destinationToken:i,buildActionCalls:u,feeExecutionMode:l,buildSpicenetBatch:f,isPayMode:m,isNon7702:h,needsSwap:x,resolvedSwap:g,quoteAmountOut:y,resolvedTokenIn:C,requestTimestampMs:S}=e,b=g?.amountOutMinimum??y;if(!n?.asset||!s)return[];const R=a??(h?r:s);if(!R)return[];const k=t?.fundingAmountOverride??t?.actionAmountOverride??B.parseUnits(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??k,F=t?.sourceFundingAmountOverride??k,A=t?.deliveryAmountOverride??w,M=t?.withdrawalAmountOverride??A,E=t?.actionAmountOverride??k,v={userAddress:R,chainId:d,destinationToken:i.address,feeToken:l==="user-transfer"&&x&&C?C:i.address,grossAmount:w,netAmount:E,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:l,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},T=u(E,v),I=n.asset?._source==="wallet";if(!m&&h&&I&&n.asset.chainId===d){if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!g||b===null)throw new Error("Swap quote not available yet")}if(x&&g&&b){const X=u(t?.actionAmountOverride??b,{...v,netAmount:t?.actionAmountOverride??b}),{feeCall:G,remainingCalls:ce}=Br(X,l,x,v.feeToken);return[{chainId:d,calls:[...G?[G]:[],...g.calls,...ce]}]}return[{chainId:d,calls:T}]}if(!m&&!h&&I&&n.asset.chainId!==d)throw new Error("Cross-chain wallet supplies require external wallet mode");const D=!m&&!h?n.asset?._source!=="wallet":n.asset?._source==="spice",U=h&&I,N=Fr(n,h,d);if(!(D||U||N))return[{chainId:d,calls:T}];const H=N?jr(C??j.normalizeNativeTokenAddress(n.asset.address),F,d):U&&n.asset.chainId!==d?{chainId:n.asset.chainId,calls:[Er(j.normalizeNativeTokenAddress(n.asset.address),F,j.getEscrowContractAddress(n.asset.chainId))]}:null,z=(X,G)=>({token:j.normalizeNativeTokenAddress(X),from:U?"solver":"escrow",to:s,amount:G}),W=(X,G)=>U?[{token:j.normalizeNativeTokenAddress(X),from:"escrow",to:j.SPICE_SOLVER_ADDRESS,amount:G}]:[];if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!g||b===null)throw new Error("Swap quote not available yet")}if(x&&g&&b&&C){const X=u(t?.actionAmountOverride??b,{...v,netAmount:t?.actionAmountOverride??b}),{feeCall:G,remainingCalls:ce}=Br(X,l,x,v.feeToken),V={chainId:d,calls:[...G?[G]:[],...g.calls,...ce],tokenTransfers:[...W(C,M),z(C,A)]},L=await _n(V,f,{userAddress:s,destinationChainId:d,deliveryToken:C,deliveryAmount:A,withdrawalAmount:M,deliveryRecipient:s,deliveryTransfers:es(V),sourceAsset:n.asset},S);return H?[H,...L]:L}const P=C??zt(n.asset,d)??i.address,Q={chainId:d,calls:T,tokenTransfers:[...W(P,M),z(P,A)]},q=await _n(Q,f,{userAddress:s,destinationChainId:d,deliveryToken:P,deliveryAmount:A,withdrawalAmount:M,deliveryRecipient:s,deliveryTransfers:es(Q),sourceAsset:n.asset},S);return H?[H,...q]:q}async function vc(e,t,n,s,r){let a=e;for(let d=0;d<4;d++){const i=await t(a),u=await s(i,n,a,r),l=ji(u);if(l===null||l>=e)return a;const f=a-l,m=e+f;if(m<=a)return a;a=m}return a}const Mr=(e,t)=>(e+t-1n)/t;function Sc(e,t){const n=e.spicenetFee+(e.bridgeFee??0n);return e.grossAmount<=n?t+e.gasFee+n:Mr((t+e.gasFee)*e.grossAmount,e.grossAmount-n)+2n}async function ts(e){const{requiredNetFunding:t}=e,n=await e.estimate(await e.buildBatches(t),e.fundingToken,t,e.executionOptions),s=mn(n,e.tokenDescriptor);if(!s)return{preview:null,feeEstimate:n,grossFundingAmount:t};const r=Sc(s,t),a=u=>s.grossAmount>0n?Mr(u*r,s.grossAmount):u,d=a(s.spicenetFee),i=a(s.bridgeFee??0n);return{preview:{...s,grossAmount:r,netAmount:t,spicenetFee:d,bridgeFee:i,totalFee:s.gasFee+d+i},feeEstimate:n,grossFundingAmount:r}}function Ic(e,t,n,s){if(e<=0n)return 0n;const r=e-t;if(r<=0n)return 0n;const a=s+n;return a<=0n?r:r*s/a}async function Nr(e){const{asset:t,isPayMode:n,isNon7702:s,needsSwap:r,isQuoting:a,embeddedWalletAddress:d,buildSupplyChainBatches:i,estimate:u,executionTokenAddress:l,feeExecutionMode:f}=e;if(n||s||r||a||!d||t.balance<=0n)return null;const m=d,h=await i({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(h.length===0)return null;const x=h.some(R=>R.tokenTransfers?.length),g=await u(h,l,t.balance,x?{userOverride:m,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:m,feeExecutionMode:f}:{userOverride:m}),y=mn(g,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),C=y?Lt(y.gasFee,y.decimals,t.decimals):0n,S=y?Lt(y.spicenetFee,y.decimals,t.decimals):0n,b=Ic(t.balance,C,S,t.balance);return b>0n?Uo(b,t.decimals):null}async function Wr(e){const{signal:t,selectedAsset:n,isPayMode:s,parsedAmount:r,needsSwap:a,exactOutputSwap:d,isNon7702:i,isSourceDestToken:u,currentPaymentAmount:l,destinationToken:f,feeExecutionMode:m,resolvedTokenIn:h,embeddedWalletAddress:x,providerEmbeddedAddress:g,resolvedChainId:y,isConnected:C,address:S,ready:b,authenticated:R,isDirect:k,resolvedSwap:w,isQuoting:F,executionTokenAddress:A,buildPayChainBatches:M,buildSupplyChainBatches:E,estimate:v}=e;if(!n?.asset)return null;if(s){if(r<=0||a&&!d||u)return null;const P=B.parseUnits(l,f.decimals),Q=h||zt(n.asset,y)||n.asset.address||f.address,q={chainId:y,tokenAddress:Q,symbol:j.getTokenByAddress(Q,y)?.symbol??n.asset.symbol,decimals:j.getTokenByAddress(Q,y)?.decimals??n.asset.decimals};if(i){const V=x||g;if(!V)return null;const L=a?d?.amountInMax??0n:P;if(L===0n)return null;const te=await ts({requiredNetFunding:L,buildBatches:de=>M({fundingAmountOverride:de}),fundingToken:Q,estimate:v,executionOptions:{userOverride:V,useCustomTransfers:!0,feeExecutionMode:m,signal:t},tokenDescriptor:q});return te.preview?{...te,preview:te.preview}:null}if(!C||!S||!b||!R)return null;const X=x||g||S,G=a?d?.amountInMax??0n:P;if(G===0n)return null;const ce=await ts({requiredNetFunding:G,buildBatches:V=>M({fundingAmountOverride:V}).then(L=>an(Tr(L),X)),fundingToken:Q,estimate:v,executionOptions:{useCustomTransfers:!0,feeExecutionMode:m,signal:t},tokenDescriptor:q});return ce.preview?{...ce,preview:ce.preview}:null}if(r<=0||!x)return null;const T=x||g;if(!(!s&&!i&&n.asset?._source==="wallet"&&n.asset.chainId!==y)&&!k&&!w&&!F||F)return null;const I=B.parseUnits(n.amount,n.asset.decimals),D=await E();if(D.length===0)return null;const U=i&&n.asset?._source==="wallet"&&n.asset.chainId===y,N={chainId:y,tokenAddress:A,symbol:j.getTokenByAddress(A,y)?.symbol??f.symbol,decimals:j.getTokenByAddress(A,y)?.decimals??f.decimals};if(U){const P=await p.relayerService.estimateBatchGas({user:T,outputToken:A,stepIndex:0,chainBatches:D,signal:t}),Q=Vn(I,10n),q=Q+P.gasFee;return{preview:{...N,grossAmount:I+q,netAmount:I,totalFee:q,gasFee:P.gasFee,spicenetFee:Q,bridgeFee:0n,gasQuoteSource:P.gasQuoteSource},feeEstimate:null}}const H=D.some(P=>P.tokenTransfers?.length),z=await v(D,A,I,H?{userOverride:T,useCustomTransfers:!0,feeExecutionMode:m,signal:t}:m?{userOverride:T,feeExecutionMode:m,signal:t}:{userOverride:T,signal:t}),W=mn(z,N);return W?{preview:W,feeEstimate:z}:null}const Ac=10n;function Pr(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=zt(n,e.resolvedChainId);if(!s||!p.addressesEqual(s,e.executionTokenAddress))return;const r=j.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=Lt(t,r?.decimals??e.destinationToken.decimals,n.decimals);if(a<=n.balance)return;const d=B.formatUnits(a,n.decimals),i=B.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${d} ${n.symbol}; available ${i} ${n.symbol}.`)}function Zs(e){const t=j.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Bn(e,t,n){const s=mn(e,Zs(t));if(!s)return;const r=Vn(n,Ac),a=s.bridgeFee??0n,d=r+s.gasFee+a;return{grossAmount:n+d,netAmount:n,combinedFeeAmount:d,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:r,gasFee:s.gasFee,bridgeFee:a}}}function Ec(e,t,n){let s=0n,r=0n;const a=n.toLowerCase();for(const d of e)if(d.chainId===t){for(const i of d.calls??[])if(i.to.toLowerCase()===a)try{const u=B.decodeFunctionData({abi:B.erc20Abi,data:i.data});if(u.functionName!=="transfer")continue;const l=u.args[0].toLowerCase(),f=u.args[1];l===j.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=f:l===j.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(r+=f)}catch{continue}}return{spicenetFee:s,gasFee:r}}function Gs(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=Ec(e,t.resolvedChainId,s);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:_t(r.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&_t(r.gasFee,n.feeBreakdown.gasFee,100n)}function Ur(e,t){return e?_t(e.grossAmount,t.grossAmount,100n)&&_t(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&_t(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&_t(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}function Xs(e,t,n,s){const r=Tr(e),a=u=>(u.tokenTransfers??[]).some(l=>l.from==="escrow"),d=r.filter(u=>!a(u)),i=r.filter(a);return[...d,...an(i,t,n,s)]}function Or(e,t){const n=j.getTokenByAddress(t,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:t,symbol:n?.symbol??e.selectedAsset?.asset.symbol??"",decimals:n?.decimals??e.selectedAsset?.asset.decimals??e.destinationToken.decimals}}async function zr(e,t){const n=e.feeQuote;return n?.feeEstimate&&n.grossFundingAmount!==void 0?{grossFundingAmount:n.grossFundingAmount,feeEstimate:n.feeEstimate}:ts({...t,estimate:e.execution.estimate,tokenDescriptor:Or(e,t.fundingToken)})}function Lr(e,t){const n=e.selectedIsEquivalent?t:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(n===0n)throw new Error("Quote not available yet");return n}function Hr(e,t,n){const s=t instanceof Error?t:new Error(String(t));if(s.name==="AbortError"||n){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r)}function Qr(e,t){const n=p.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}async function Vr(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const s=await qr(e);e.ui.setTxHash(s??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const s=new AbortController;e.refs.abortControllerRef.current=s,await jc(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){Hr(e,s,!!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("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=B.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),s=n;let r=await e.execution.buildSupplyChainBatches();const a=e.selectedAsset.asset?._source==="wallet",d=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!a&&!r.some(x=>j.isSpicenetChainId(x.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const i=r.some(x=>x.tokenTransfers?.length)?{userOverride:d,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:d,feeExecutionMode:e.feeExecutionMode}:{userOverride:d};let u=n;const l=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,f=e.feeExecutionMode==="user-transfer"&&!l?s:void 0;let m;for(let x=0;x<4;x+=1){const g=x===0&&e.feeQuote?.feeEstimate||await e.execution.estimate(r,e.executionTokenAddress,u,i),y=mn(g,Zs(e));m=e.feeExecutionMode==="user-transfer"&&y?Bn(g,e,s):void 0;const C=m?.grossAmount??y?.grossAmount??u;if(C===u){u=C;break}u=C,r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:m})}e.feeExecutionMode==="user-transfer"&&(Pr(e,u),r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:m}));let h=m;await e.execution.execute(r,e.executionTokenAddress,u,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...i,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:x,chainBatches:g})=>{const y=Bn(x,e,s);if(!y)return null;const C=Ur(h,y),S=Gs(g,e,y);return C||S?null:(h=y,e.execution.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:f,actionContextOverride:y}))}}:{...i,skipPreSubmitFeeEstimate:!0}),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){Hr(e,n,t.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function jc(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const s=e.selectedAsset.asset,r=B.parseUnits(e.selectedAsset.amount,s.decimals),a=r,d=s?._source==="wallet"&&s.chainId===e.resolvedChainId;let i=await e.execution.buildSupplyChainBatches();const u={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let l=r;const f=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,m=e.feeExecutionMode==="user-transfer"&&!f?a:void 0;let h;if(d){const E=e.feeQuote?.preview.gasFee??(await p.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:i})).gasFee,v=Vn(r,10n),T=v+E;l=r+T,e.feeExecutionMode==="user-transfer"&&(h={grossAmount:l,netAmount:a,combinedFeeAmount:T,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:v,gasFee:E,bridgeFee:0n}})}else for(let E=0;E<4;E+=1){const v=await e.execution.estimate(i,e.executionTokenAddress,0n,u),T=e.feeExecutionMode==="user-transfer"?Bn(v,e,a):void 0,I=mn(v,Zs(e)),D=T?.grossAmount??(I?I.grossAmount>r?I.grossAmount:r:l);if(h=T,D===l){l=D;break}l=D;const U=j.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),N=Lt(l,U?.decimals??e.destinationToken.decimals,s.decimals);i=await e.execution.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:N,withdrawalAmountOverride:l,actionAmountOverride:m,actionContextOverride:T})}const x=j.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let g=d?l:Lt(l,x?.decimals??e.destinationToken.decimals,s.decimals);Pr(e,l),i=await e.execution.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:g,withdrawalAmountOverride:l,actionAmountOverride:m,actionContextOverride:h});const y=s.chainId,C=n,{extWc:S,viemChain:b}=await xn({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:y,onSwitch:()=>e.ui.setStatusMsg("Switching source network...")}),R=j.normalizeNativeTokenAddress(s.address),k=s.isNative||j.isNativeToken(R),w=p.getClientForChain(y),F=E=>Ms({extWc:S,sourceClient:w,recipient:C,tokenAddr:R,isNative:k,amount:E,viemChain:b});e.ui.setStatusMsg("Funding embedded wallet..."),await F(g);let A=g;if(e.feeExecutionMode==="user-transfer")for(let E=0;E<4;E+=1){const v=await e.execution.estimate(i,e.executionTokenAddress,0n,u),T=Bn(v,e,a);if(!T)break;const I=d?T.grossAmount:Lt(T.grossAmount,x?.decimals??e.destinationToken.decimals,s.decimals);if(I>A&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await F(I-A),A=I),h=T,l=T.grossAmount,g=I,i=await e.execution.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:g,withdrawalAmountOverride:l,actionAmountOverride:m,actionContextOverride:T}),Gs(i,e,T))break}e.ui.setStatusMsg("Signing supply intent...");let M=h;await e.execution.execute(i,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:E,chainBatches:v})=>{const T=Bn(E,e,a);if(!T)return null;const I=Ur(M,T),D=Gs(v,e,T);if(I||D)return null;if(T.grossAmount>l)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");M=T;const U=d?T.grossAmount:Lt(T.grossAmount,x?.decimals??e.destinationToken.decimals,s.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:T.grossAmount,sourceFundingAmountOverride:U,withdrawalAmountOverride:T.grossAmount,actionAmountOverride:m,actionContextOverride:T})}}:{...u,skipPreSubmitFeeEstimate:!0})}async function qr(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 r=B.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),a={userAddress:s,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},d=e.buildActionCalls(r,a);if(d.length===0)throw new Error("No action calls configured");const{extWc:i,viemChain:u}=await xn({wallet:n,account:s,chainId:e.resolvedChainId}),l=p.getClientForChain(e.resolvedChainId);return Ko({extWc:i,client:l,calls:d,viemChain:u,errorMessage:"Transaction failed"})}async function Fc(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=n.chainId,r=B.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=Lr(e,r),d=e.resolvedTokenIn||e.selectedAsset.asset.address,i={userOverride:t,useCustomTransfers:!0},u=j.getEscrowContractAddress(s),l=j.normalizeNativeTokenAddress(n.address),f=n.isNative||j.isNativeToken(l),m=t,h=F=>({chainId:s,calls:f?[{to:u,value:F,data:"0x"}]:[{to:l,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"transfer",args:[u,F]})}]}),x=async(F,A,M)=>[h(F),...Xs(await e.execution.buildPayChainBatches({fundingAmountOverride:F}),m,A,M)],{grossFundingAmount:g,feeEstimate:y}=await ts({requiredNetFunding:a,buildBatches:F=>x(F),fundingToken:d,estimate:e.execution.estimate,executionOptions:{...i,feeExecutionMode:e.feeExecutionMode},tokenDescriptor:Or(e,d)}),C=await x(g,y,{payoutAlreadyGross:!0}),{extWc:S,viemChain:b}=await xn({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:s}),R=p.getClientForChain(s);await Ms({extWc:S,sourceClient:R,recipient:t,tokenAddr:l,isNative:f,amount:g,viemChain:b});const k=C.some(F=>F.tokenTransfers?.length),w={...i,skipUserFundingPreflight:!0,skipPreSubmitFeeEstimate:!0};return await e.execution.execute(C,d,k?g:0n,F=>{F.txHash&&(e.ui.setPaymentResult(A=>({...A??{status:"processing"},txHash:F.txHash})),e.ui.setTxHash(F.txHash))},void 0,k?w:{userOverride:t,skipUserFundingPreflight:!0,skipPreSubmitFeeEstimate:!0})}async function Kr(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let s;if(e.isSourceDestToken||e.parsedAmount===0)s=await qr(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,a=B.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),d=Lr(e,a),i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!i)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const u=e.resolvedTokenIn||r.address,{grossFundingAmount:l}=await zr(e,{requiredNetFunding:d,buildBatches:h=>e.execution.buildPayChainBatches({fundingAmountOverride:h}),fundingToken:u,executionOptions:{userOverride:i,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}}),f=await e.execution.buildPayChainBatches({fundingAmountOverride:l}),m=await e.onPayExecute({asset:r,amount:e.currentPaymentAmount,amountWei:a,destinationToken:e.destinationToken,chainBatches:f,requiredNetFunding:d,grossFundingAmount:l,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:u,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});m&&(e.ui.setTxHash(m),e.ui.setPaymentResult(h=>({...h??{status:"processing"},txHash:m}))),s=m||void 0}else s=await Fc(e);e.ui.setPaymentResult(r=>({status:"success",txHash:r?.txHash||s||""}))}catch(s){Qr(e,s)}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=B.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),s={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const x=await e.execution.buildPayChainBatches(),g=await e.execution.execute(x,e.executionTokenAddress,0n,y=>{y.txHash&&(e.ui.setPaymentResult(C=>({...C??{status:"processing"},txHash:y.txHash})),e.ui.setTxHash(y.txHash))},void 0,s);e.ui.setPaymentResult(y=>({status:"success",txHash:y?.txHash||g}));return}const r=e.selectedAsset?.asset;if(!r)throw new Error("Select a payment source");const a=e.resolvedTokenIn||r.address||e.destinationToken.address,d=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,i=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,{grossFundingAmount:u,feeEstimate:l}=await zr(e,{requiredNetFunding:d,buildBatches:x=>e.execution.buildPayChainBatches({fundingAmountOverride:x}).then(g=>Xs(g,i)),fundingToken:a,executionOptions:s}),f=Xs(await e.execution.buildPayChainBatches({fundingAmountOverride:u}),i,l,{payoutAlreadyGross:!0}),m=f.some(x=>x.tokenTransfers?.length),h=await e.execution.execute(f,a,m?u:0n,x=>{x.txHash&&(e.ui.setPaymentResult(g=>({...g,txHash:x.txHash})),e.ui.setTxHash(x.txHash))},void 0,{...s,skipPreSubmitFeeEstimate:!0});e.ui.setPaymentResult(x=>({status:"success",txHash:x?.txHash||h}))}catch(n){Qr(e,n)}finally{e.ui.setIsExecuting(!1)}}const Bc=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:d,textSecondary:i,cardBg:u,cardBorder:l,dk:f,dark:m,isQuoting:h,quoteError:x,estimatedOutput:g,paymentAmount:y,needsSwap:C,exactOutputSwap:S,adjustable:b=!1,maxAmount:R,onAmountChange:k})=>e==="supply"?o.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${l}`,borderRadius:m?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[o.jsxs("div",{style:{minWidth:0},children:[o.jsx("span",{style:{fontFamily:a,fontSize:"17px",fontWeight:500,color:m?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),o.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:i,fontFamily:a,marginTop:"10px"},children:"Net amount after swap and fees"})]}),o.jsxs("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${l}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[o.jsx(Zr,{symbol:t,logoURI:n,primaryColor:r,size:24}),o.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:m?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),o.jsx("div",{style:{textAlign:"right",minWidth:0},children:h?o.jsx("span",{style:{fontSize:"18px",color:i,fontFamily:a},children:"Quoting..."}):x?o.jsx("span",{style:{fontSize:"13px",color:m?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):g?o.jsx(sn,{value:g,title:g,fontFamily:a,color:d,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):o.jsx("span",{style:{fontSize:"20px",color:i,fontFamily:a},children:"\u2014"})})]}):o.jsx(Tc,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:d,textSecondary:i,cardBg:u,cardBorder:l,dk:f,dark:m,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:S,isQuoting:h,adjustable:b,maxAmount:R,onAmountChange:k}),Yr=c.memo(Bc),Zr=({symbol:e,logoURI:t,primaryColor:n,size:s})=>t?o.jsx("img",{src:t,alt:e,style:{width:s,height:s,borderRadius:"50%",objectFit:"cover"}}):o.jsx("div",{style:{width:s,height:s,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:s<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),Tc=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:d,cardBg:i,cardBorder:u,dk:l,dark:f,paymentAmount:m,needsSwap:h,exactOutputSwap:x,isQuoting:g,adjustable:y,maxAmount:C,onAmountChange:S})=>{const b=p.font.mono,R=parseFloat(m||"0"),k=C?parseFloat(C):0,[w,F]=c.useState(m||""),A=c.useRef(null),[M,E]=c.useState(null),[v,T]=c.useState(null);c.useEffect(()=>{y||F(m||"")},[m,y]);const I=N=>{let H=N;H.startsWith(".")&&(H="0"+H);const z=p.parseNumericInput(H);let W=z;C&&parseFloat(z)>parseFloat(C)&&(W=C),F(W),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>S?.(W),300)},D=N=>{if(!k)return;if(N===100){F(C||k.toString()),A.current&&clearTimeout(A.current),S?.(C||k.toString());return}const H=10**n,z=Math.floor(k*N/100*H)/H,W=p.formatDecimalInput(z,n);F(W),A.current&&clearTimeout(A.current),S?.(W)},U=k>0?parseFloat(w||"0")/k*100:0;return c.useEffect(()=>()=>{A.current&&clearTimeout(A.current)},[]),o.jsxs("div",{style:{backgroundColor:i,border:`1px solid ${u}`,borderRadius:f?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[o.jsx(Zr,{symbol:e,logoURI:t,primaryColor:s,size:32}),o.jsxs("div",{children:[o.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:a,fontFamily:r},children:"Payment"}),o.jsx("div",{style:{fontSize:"12px",color:d,fontFamily:r,marginTop:"2px"},children:e})]})]}),o.jsxs("div",{style:{textAlign:"right"},children:[y?o.jsx(sn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:N=>I(N.target.value),placeholder:"0.0",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):o.jsx(sn,{element:"div",value:R>0?m:"0.00",title:R>0?m:"0.00",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),o.jsx("div",{style:{fontSize:"12px",color:d,fontFamily:b,marginTop:"2px"},children:e}),y&&k>0&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((N,H)=>{const z=Math.abs(U-N)<1,W=H===4,P=M===N,Q=v===N;return o.jsx("button",{onClick:()=>D(N),onMouseEnter:()=>E(N),onMouseLeave:()=>{E(null),T(null)},onMouseDown:()=>T(N),onMouseUp:()=>T(null),title:`${N}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:z?1:P?.8:.5,transform:Q?"scale(0.85)":P?"scale(1.15)":"scale(1)",transition:p.transition.interactive},children:o.jsx(ms,{pct:N,isMax:W,primaryColor:s,dark:f,fillColor:f?l?.textSecondary||"#9ca3af":"#3C3E42"})},N)})})]})]}),h&&x&&!g&&o.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:f?`1px solid ${l?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:o.jsxs("span",{style:{fontSize:"11px",color:d,fontFamily:r,opacity:.7},children:["via ",x.venue]})})]})},Gr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Xr=["signing-delegation","signing-intent","submitting","executing"],Rc=({step:e,statusMsg:t,txHash:n,explorerUrl:s,currentStepIdx:r,palette:a,cardBg:d,cardBorder:i,textPrimary:u,textSecondary:l,fontFamily:f,primaryColor:m,onRetry:h})=>o.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:e==="success"?d:e==="error"?a.errorBg:d,border:`1px solid ${e==="success"?i:e==="error"?a.errorBorder:i}`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[e==="success"?o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:o.jsx("path",{d:"M5 13l4 4L19 7",stroke:a.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):e==="error"?o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:o.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:a.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):o.jsx(p.Spinner,{size:14,color:m}),o.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:e==="success"?u:e==="error"?a.errorText:u,fontFamily:f,flex:1},children:e==="success"?"Deposit confirmed":e==="error"?t||"Transaction failed":Gr[e]||t}),e==="success"&&n&&o.jsx("a",{href:`${s}/tx/${n}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:m,fontFamily:f,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),e==="error"&&o.jsx("button",{onClick:h,style:{background:"none",border:"none",fontSize:"12px",color:m,fontFamily:f,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),r>=0&&e!=="success"&&e!=="error"&&o.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${l}22`,overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:m,transformOrigin:"left center",transform:`scaleX(${(r+1)/Xr.length})`,transition:"transform 400ms ease"}})})]});function Jr(e,t,n){const s=p.addressesEqual(e.address,t),r=e.chainId===n,a=e._source==="wallet";return a&&s&&r?0:a&&r?1:!a&&s?2:!a&&r?3:4}function $r(e,t){return!t||t.length===0||t.some(n=>p.addressesEqual(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const s=on(n);return s?t.some(r=>p.addressesEqual(r,s.address)):!1})}function Js(e,t,n){let{symbol:s,name:r,logoURI:a}=t;const d=p.addressesEqual(e.address,n.address)&&e.chainId===n.chainId;d&&n.logoURI&&(a=n.logoURI),d&&!e.configToken&&s==="TOKEN"&&(s=n.symbol,r=n.symbol);const i=parseFloat((Number(t.balance)/Math.pow(10,t.decimals)).toFixed(6));return{address:e.address,name:r,symbol:s,decimals:t.decimals,balance:t.balance,balanceFormatted:i,balanceUsd:0,logoURI:a,isNative:j.isNativeToken(e.address),chainId:e.chainId}}function _r(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:s,enabled:r}=e,a=c.useContext(p.SpiceFlowProviderContext),d=(a?.mode||"7702")!=="7702",i=a?.embeddedWalletAddress,{externalAddress:u,embeddedAddress:l,activeAddress:f}=p.useProviderWallets(),m=i||l,{assets:h,refetch:x}=jn({address:m,supportedChains:s,enabled:r&&!d&&!!m,refetchInterval:3e4}),g=c.useMemo(()=>d?[]:h.filter(E=>$r(E,n)),[h,n,d]),y=d?f??u:i,C=c.useMemo(()=>{const E=new Set,v=[],T=I=>{if(!I)return;const D=I.toLowerCase();E.has(D)||(E.add(D),v.push(B.getAddress(I)))};if(T(t.address),n)for(const I of n)T(I);return v},[d,t.address,n]),S=c.useMemo(()=>C.map(E=>E.toLowerCase()).sort().join(","),[C]),b=c.useMemo(()=>JSON.stringify([...s||[]].sort()),[s]),[R,k]=c.useState([]),w=c.useRef(0),F=c.useRef(async()=>{}),A=c.useCallback(async()=>{if(!r||!y||C.length===0){w.current++,k([]);return}const E=++w.current,v=B.getAddress(y),T=d?s&&s.length>0?s:[t.chainId]:[t.chainId],I=[];for(const H of C){const z=H.toLowerCase();if(z===j.ZERO_ADDRESS)continue;if(j.isNativeToken(z)){const P=p.addressesEqual(z,t.address)&&!T.includes(t.chainId)?[t.chainId,...T]:T;for(const Q of P){const q=p.getChainConfig(Q)?.supportedTokens?.find(X=>j.isNativeToken(X.address));q&&I.push({address:H,chainId:Q,configToken:{decimals:q.decimals,symbol:q.symbol,name:q.name,logo:q.logo}})}continue}if(z===t.address.toLowerCase()){const P=p.getChainConfig(t.chainId)?.supportedTokens?.find(Q=>p.addressesEqual(Q.address,z));I.push({address:H,chainId:t.chainId,configToken:P?{decimals:P.decimals,symbol:P.symbol,name:P.name,logo:P.logo}:void 0});continue}let W=!1;for(const P of T){const Q=p.getChainConfig(P)?.supportedTokens?.find(q=>p.addressesEqual(q.address,z));if(Q){I.push({address:H,chainId:P,configToken:{decimals:Q.decimals,symbol:Q.symbol,name:Q.name,logo:Q.logo}}),W=!0;break}}W||I.push({address:H,chainId:t.chainId})}const D=new Map;for(const H of I){const z=D.get(H.chainId)||[];z.push(H),D.set(H.chainId,z)}const U=async(H,z)=>{try{const W=await Nt.readContract(H,{address:z.address,abi:B.erc20Abi,functionName:"balanceOf",args:[v]}),{decimals:P,symbol:Q,name:q,logoURI:X}=await xr(H,z.address,z.configToken);return Js(z,{decimals:P,symbol:Q,name:q,logoURI:X,balance:W},t)}catch{return null}},N=await Promise.all(Array.from(D.entries()).map(async([H,z])=>{let W;try{W=p.getClientForChain(H)}catch{return[]}const P=z.filter(L=>j.isNativeToken(L.address)),Q=z.filter(L=>!j.isNativeToken(L.address)),q=await Promise.all(P.map(async L=>{const te=await W.getBalance({address:v}).catch(()=>0n),de=p.getChainConfig(H)?.nativeCurrency;return Js(L,{decimals:L.configToken?.decimals??de?.decimals??18,symbol:L.configToken?.symbol??de?.symbol??"ETH",name:L.configToken?.name??de?.name??"Ether",logoURI:L.configToken?.logo,balance:te},t)}));if(Q.length===0)return q;const X=[],G=[];for(const L of Q){const te=X.length;X.push({address:L.address,abi:B.erc20Abi,functionName:"balanceOf",args:[v]}),L.configToken||X.push({address:L.address,abi:B.erc20Abi,functionName:"decimals"},{address:L.address,abi:B.erc20Abi,functionName:"symbol"},{address:L.address,abi:B.erc20Abi,functionName:"name"}),G.push({start:te,item:L})}let ce=null;try{ce=await W.multicall({contracts:X})}catch{ce=null}if(ce){const L=G.map(({start:te,item:de})=>{const ie=ce[te],Ie=ie?.status==="success"?ie.result:0n;let ye,ue,Te,O;if(de.configToken)ye=de.configToken.decimals,ue=de.configToken.symbol,Te=de.configToken.name,O=de.configToken.logo;else{const ee=ce[te+1],oe=ce[te+2],se=ce[te+3];ye=ee?.status==="success"?Number(ee.result):18,ue=oe?.status==="success"?oe.result:"TOKEN",Te=se?.status==="success"?se.result:ue}return Js(de,{decimals:ye,symbol:ue,name:Te,logoURI:O,balance:Ie},t)});return[...q,...L]}const V=await Promise.all(Q.map(L=>U(W,L)));return[...q,...V.filter(L=>L!==null)]}));E===w.current&&k(N.flat())},[r,d,y,S,b,t.address,t.chainId,t.symbol,t.logoURI]);c.useEffect(()=>{F.current=A},[A]),c.useEffect(()=>{if(!r){k([]);return}F.current();const E=setInterval(()=>{F.current()},15e3);return()=>clearInterval(E)},[r,d,y,S,b,t.address,t.chainId]);const M=c.useCallback(()=>{A()},[A]);return{displayAssets:c.useMemo(()=>{const E=[],v=R.filter(I=>I.balance>0n);for(const I of v)E.push({...I,_source:"wallet"});for(const I of g)E.push({...I,_source:"spice"});const T=t.address.toLowerCase();return E.sort((I,D)=>Jr(I,T,t.chainId)-Jr(D,T,t.chainId)),E},[R,g,t.address,t.chainId]),filteredSpiceAssets:g,walletAssets:R,embeddedWalletAddress:m,externalAddress:u,isNon7702:d,refreshSpiceAssets:x,refreshWalletAssets:M}}async function Dc(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:r,chainId:a,config:d}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const i=(await p.getClientForChain(a).simulateContract({address:d.quoterV2,abi:j.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(i[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:i[0],sqrtPriceX96After:i[1],gasEstimate:i[3]}}async function ea(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>Dc({...e,fee:r})));let s=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!s||a.value.amountOut>s.amountOut)&&(s={...a.value,fee:t[r]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}const Mc=[{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 Nc(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:r,chainId:a,config:d}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const i=(await p.getClientForChain(a).simulateContract({address:d.quoterV2,abi:Mc,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(i[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:i[0],sqrtPriceX96After:i[1],gasEstimate:i[3]}}async function Wc(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>Nc({...e,fee:r})));let s=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!s||a.value.amountIn<s.amountIn)&&(s={...a.value,fee:t[r]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}function Pc(e){return e.type==="swap"}const $s=.02,Uc=[1,8453,42161,10,137,43114,56],Oc="https://api.1inch.dev/swap/v6.0";function ta(e,t){return j.applySlippage(e,t)}function zc(e){const t=e?.baseUrl??Oc;return{name:"1inch",chainIds:e?.chainIds??Uc,resolve:async(n,s,r)=>{const a=n.maxSlippage??$s,d=a*100,i=j.isNativeToken(n.tokenIn)?j.NATIVE_TOKEN_ADDRESS:n.tokenIn,u=j.isNativeToken(n.tokenOut)?j.NATIVE_TOKEN_ADDRESS:n.tokenOut,l=j.isNativeToken(n.tokenIn);try{const f=new URL(`${t}/${s}/swap`);f.searchParams.set("src",i),f.searchParams.set("dst",u),f.searchParams.set("amount",n.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",d.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const m={Accept:"application/json"};e?.apiKey&&(m.Authorization=`Bearer ${e.apiKey}`);const h=await fetch(f.toString(),{headers:m});if(!h.ok)throw new p.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${h.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 ${h.status}`});const x=await h.json();if(!x.dstAmount||!x.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const g=BigInt(x.dstAmount);if(g<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const y=ta(g,a),C=[];return x.tx.to&&!l&&C.push({to:n.tokenIn,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"approve",args:[x.tx.to,n.amountIn]})}),C.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:g,amountOutMinimum:y,calls:C}}catch(f){if(f instanceof p.SpiceflowError)throw f;const m=f instanceof Error?f.message:String(f);throw new p.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${m}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:m})}}}}const na=[4114,5115],_s={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},sa={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]},oa={swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4]};function eo(e){return{name:"satsuma",chainIds:e.chainIds??na,resolve:async(t,n,s)=>{const r=t.maxSlippage??$s,a=j.isNativeToken(t.tokenIn);let d;try{d=await ea({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const i=ta(d.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:B.encodeFunctionData({abi:j.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:d.fee,recipient:s,amountIn:t.amountIn,amountOutMinimum:i,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:d.amountOut,amountOutMinimum:i,calls:u}}}}function to(e){return{name:"satsuma",chainIds:e.chainIds??na,resolve:async(t,n,s)=>{const r=t.maxSlippage??$s,a=j.isNativeToken(t.tokenIn);let d;try{d=await Wc({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const i=BigInt(Math.round(r*1e4)),u=d.amountIn+d.amountIn*i/10000n,l=[];return l.push({to:e.swapRouter,value:a?u:0n,data:B.encodeFunctionData({abi:Lc,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:d.fee,recipient:s,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:d.amountIn,amountInMax:u,amountOut:t.amountOut,calls:l}}}}const Lc=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"exactOutputSingle",outputs:[{name:"amountIn",type:"uint256"}],stateMutability:"payable",type:"function"}];function ra(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(eo(e.satsuma)),t.push(zc(e?.oneInch));function n(r){return t.find(a=>a.chainIds.includes(r))}async function s(r,a,d){const i=[],u=[];for(const l of r){if(!Pc(l)){i.push(l);continue}const f=n(a);if(!f)throw new p.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${l.tokenIn} \u2192 ${l.tokenOut}.`,{chainId:a,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});const m=await f.resolve(l,a,d);if(!m)throw new p.SpiceflowError("NO_LIQUIDITY",`${f.name} returned no quote for ${l.tokenIn} \u2192 ${l.tokenOut} on chain ${a}.`,{venue:f.name,chainId:a,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});i.push(...m.calls),u.push(m)}return{calls:i,resolvedSwaps:u}}return{resolveSwapIntents:s,getVenueForChain:n,venues:t}}const cn="0x0000000000000000000000000000000000000000",no=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],aa=cn,ia=.02,Hc=1800,la={quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",cn]},so={quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",cn],v3:{swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4]}},ca=B.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)"]),Qc=B.parseAbi(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),Vc=B.parseAbi(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),qc="0x10",Kc="06",Yc="07",Zc="08",Gc="09",ns="0c",ss="0e",Xc=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],Jc=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],Tn=(e,t)=>e.toLowerCase()===t.toLowerCase();function oo(e){return j.isNativeToken(e)?cn:e}function $c(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function da(e,t,n,s){const r=[],[a,d]=$c(e,t);for(const{fee:i,tickSpacing:u}of no)r.push({kind:"single",poolKey:{currency0:a,currency1:d,fee:i,tickSpacing:u,hooks:aa},zeroForOne:Tn(e,a)});for(const i of n)if(!(Tn(i,e)||Tn(i,t)))for(const u of no)for(const l of no){const f=(m,h)=>({intermediateCurrency:m,fee:h.fee,tickSpacing:h.tickSpacing,hooks:aa,hookData:"0x"});r.push({kind:"multi",path:s==="in"?[f(i,u),f(t,l)]:[f(e,u),f(i,l)]})}return r}async function ua(e,t,n,s,r,a){const d=p.getClientForChain(e),i=(await Promise.allSettled(n.map(async u=>{const{result:l}=u.kind==="single"?await d.simulateContract({address:t.quoter,abi:ca,functionName:a==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:u.poolKey,zeroForOne:u.zeroForOne,exactAmount:r,hookData:"0x"}]}):await d.simulateContract({address:t.quoter,abi:ca,functionName:a==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:s,path:u.path,exactAmount:r}]}),f=l[0];if(f<=0n)throw new Error("zero quote");return{candidate:u,amount:f}}))).filter(u=>u.status==="fulfilled").map(u=>u.value);return i.length===0?null:(i.sort((u,l)=>u.amount<l.amount?-1:u.amount>l.amount?1:0),a==="in"?i[i.length-1]:i[0])}function pa(e){const{candidate:t,direction:n,currencyIn:s,currencyOut:r,recipient:a,exactAmount:d,limitAmount:i,deadline:u}=e;let l,f;t.kind==="single"?(l=n==="in"?`0x${Kc}${ns}${ss}`:`0x${Zc}${ns}${ss}`,f=B.encodeAbiParameters([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:Xc},{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"]:d,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i,hookData:"0x"}])):(l=n==="in"?`0x${Yc}${ns}${ss}`:`0x${Gc}${ns}${ss}`,f=B.encodeAbiParameters([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:Jc},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"}]}],[{[n==="in"?"currencyIn":"currencyOut"]:n==="in"?s:r,path:t.path,[n==="in"?"amountIn":"amountOut"]:d,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i}]));const m=B.encodeAbiParameters([{type:"address"},{type:"uint256"}],[s,n==="in"?d:i]),h=B.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[r,a,0n]),x=B.encodeAbiParameters([{type:"bytes"},{type:"bytes[]"}],[l,[f,m,h]]);return B.encodeFunctionData({abi:Vc,functionName:"execute",args:[qc,[x],u]})}function fa(){return BigInt(Math.floor(Date.now()/1e3)+Hc)}function ma(e,t,n,s){return{to:e.permit2,value:0n,data:B.encodeFunctionData({abi:Qc,functionName:"approve",args:[t,e.universalRouter,n,Number(s)]})}}function ha(e){const t=e.v3?eo({...e.v3,chainIds:e.chainIds}):null;return{name:"univ4",chainIds:e.chainIds,resolve:async(n,s,r)=>{const a=n.maxSlippage??ia,d=oo(n.tokenIn),i=oo(n.tokenOut),u=j.isNativeToken(n.tokenIn),l=e.hubCurrencies??[cn];let f=null;if(!Tn(d,i)&&n.amountIn>0n){const m=await ua(s,e,da(d,i,l,"in"),d,n.amountIn,"in").catch(()=>null);if(m){const h=j.applySlippage(m.amount,a),x=fa(),g=[];u||(g.push({to:n.tokenIn,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"approve",args:[e.permit2,n.amountIn]})}),g.push(ma(e,n.tokenIn,n.amountIn,x))),g.push({to:e.universalRouter,value:u?n.amountIn:0n,data:pa({candidate:m.candidate,direction:"in",currencyIn:d,currencyOut:i,recipient:r,exactAmount:n.amountIn,limitAmount:h,deadline:x})}),f={venue:"univ4",amountOut:m.amount,amountOutMinimum:h,calls:g}}}return!f&&t?t.resolve(n,s,r):f}}}function ro(e){return{name:"univ4",chainIds:e.chainIds,resolve:async(t,n,s)=>{if(j.isNativeToken(t.tokenIn))return null;const r=oo(t.tokenOut);if(Tn(t.tokenIn,r)||t.amountOut<=0n)return null;const a=t.maxSlippage??ia,d=e.hubCurrencies??[cn],i=await ua(n,e,da(t.tokenIn,r,d,"out"),r,t.amountOut,"out").catch(()=>null);if(!i)return null;const u=BigInt(Math.round(a*1e4)),l=i.amount+i.amount*u/10000n,f=fa();return{venue:"univ4",amountIn:i.amount,amountInMax:l,amountOut:t.amountOut,calls:[ma(e,t.tokenIn,l,f),{to:e.universalRouter,value:0n,data:pa({candidate:i.candidate,direction:"out",currencyIn:t.tokenIn,currencyOut:r,recipient:s,exactAmount:t.amountOut,limitAmount:l,deadline:f})}]}}}}function ga(e){const t=e?.customVenues??[];async function n(s,r,a){const d=t.filter(l=>l.chainIds.includes(r));if(d.length===0)throw new p.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const i=(await Promise.allSettled(d.map(async l=>({venue:l,quote:await l.resolve(s,r,a)})))).filter(l=>l.status==="fulfilled").map(l=>l.value).filter(l=>l.quote!==null);if(i.length===0)throw new p.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${r}`,{chainId:r,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut.toString()});const u=i.find(l=>l.venue.preferred);return u?u.quote:(i.sort((l,f)=>l.quote.amountIn<f.quote.amountIn?-1:l.quote.amountIn>f.quote.amountIn?1:0),i[0].quote)}return{getQuote:n,venues:t}}const xa=ra({satsuma:_s,customVenues:[ha(so)]});async function _c(e){const t=xa.getVenueForChain(e.chainId);if(!t)throw new Error(`No swap venue configured for chain ${e.chainId}.`);const n=await t.resolve({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn},e.chainId,e.recipient);if(!n)throw new Error("No liquidity for this pair.");return n}function ya(e){const{direction:t,selectedAsset:n,destinationToken:s,chainId:r,recipient:a,paymentAmount:d,resolveExactOutputSwap:i}=e,[u,l]=c.useState(!1),[f,m]=c.useState(null),[h,x]=c.useState(null),[g,y]=c.useState(null),[C,S]=c.useState(null),[b,R]=c.useState(null),[k,w]=c.useState(null),[F,A]=c.useState(null),[M,E]=c.useState(null),v=c.useRef(null),T=c.useRef(null),I=c.useRef(0),D=c.useRef(new Map),U=c.useMemo(()=>xa,[]),N=c.useMemo(()=>ga({customVenues:[...i?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:i}]:[],to(_s),to(sa),to(oa),ro(la),ro(so)]}),[i,r]),H=c.useMemo(()=>{if(!n?.asset)return null;const L=zt(n.asset,r);if(L)return L;const te=Yt(n.asset.address,r,n.asset.chainId);return te?te.address:null},[n?.asset,r]),z=c.useMemo(()=>n?.asset?On(n.asset,r):[],[n?.asset,r]),W=c.useMemo(()=>z.map(L=>L.toLowerCase()).join(","),[z]);c.useEffect(()=>{let L=!1;if(T.current&&(clearTimeout(T.current),T.current=null),!n?.asset||z.length<=1){E(null);return}return T.current=setTimeout(async()=>{const te=t==="input"?n.amount:d||"0";let de=0n;try{de=t==="input"?B.parseUnits(te,n.asset.decimals):0n}catch{de=0n}try{const ie=await Fo(n.asset,r,{requiredAmount:de});L||E(ie)}catch{L||E(null)}},400),()=>{L=!0,T.current&&(clearTimeout(T.current),T.current=null)}},[n?.asset,n?.amount,r,z.length,W,t,d]);const P=c.useMemo(()=>M??H,[M,H]),Q=c.useMemo(()=>!n?.asset||!P?[]:[P,...z.filter(L=>L.toLowerCase()!==P.toLowerCase())],[n?.asset,P,z]),q=c.useMemo(()=>!n?.asset||!In(n.asset.address,n.asset.chainId,s.address,s.chainId)||!P?!1:p.addressesEqual(P,s.address),[n,s.address,s.chainId,P]),X=P?p.addressesEqual(P,s.address):!1,G=t==="output"&&parseFloat(d||"0")===0,ce=!!n?.asset&&!q&&!X&&!G,V=ce?F??P:P;return c.useEffect(()=>{v.current&&clearTimeout(v.current);const L=t==="input"?n?.amount:d,te=parseFloat(L||"0");if(!ce||!Number.isFinite(te)||te<=0||!n?.asset||!a||Q.length===0){I.current++,x(null),y(null),S(null),R(null),w(null),A(null),m(null),l(!1);return}const de=n.asset.decimals;let ie;try{ie=t==="input"?B.parseUnits(n.amount,de):B.parseUnits(d||"0",s.decimals)}catch{I.current++,m("Invalid amount"),l(!1);return}const Ie=++I.current,ye=()=>Ie!==I.current;l(!0);const ue=t==="output"?150:400,Te=async(O,ee,oe)=>{for(const se of Q){const Z=`${t}:${r}:${se.toLowerCase()}:${s.address.toLowerCase()}:${ie.toString()}`,le=D.current.get(Z),fe=le&&le.expiresAt>Date.now()?O(le):void 0;if(fe)return{quote:fe,tokenIn:se};const $=await oe(se);if(ye())return"stale";if($)return D.current.set(Z,{expiresAt:Date.now()+3e4,direction:t,...ee($)}),{quote:$,tokenIn:se}}return null};return v.current=setTimeout(async()=>{try{if(t==="input"){const O=U.getVenueForChain(r);if(!O)throw new Error("No swap venue for this chain");const ee=await Te(se=>se.resolvedSwap,se=>({resolvedSwap:se}),se=>O.resolve({type:"swap",tokenIn:se,tokenOut:s.address,amountIn:ie},r,a));if(ee==="stale")return;if(!ee)throw new Error("No liquidity for this pair");A(ee.tokenIn),w(ee.quote.amountOut),S(ee.quote),R(null);const oe=parseFloat(B.formatUnits(ee.quote.amountOut,s.decimals));x(oe<.01?oe.toPrecision(4):oe.toLocaleString(void 0,{maximumFractionDigits:6})),y(null),m(null)}else{const O=await Te(ee=>ee.exactOutputSwap,ee=>({exactOutputSwap:ee}),async ee=>{try{return await N.getQuote({tokenIn:ee,tokenOut:s.address,amountOut:ie},r,a)}catch{return null}});if(O==="stale")return;if(!O)throw new Error("No liquidity for this pair");A(O.tokenIn),R(O.quote),S(null),w(null),y(parseFloat(B.formatUnits(O.quote.amountIn,de)).toFixed(6)),x(null),m(null)}}catch(O){if(ye())return;const ee=O instanceof Error?O.message:"Failed to get quote";m(ee),x(null),y(null),S(null),R(null),w(null),A(null)}finally{ye()||l(!1)}},ue),()=>{v.current&&clearTimeout(v.current)}},[t,ce,n?.amount,n?.asset?.address,n?.asset?.decimals,d,Q,r,s.address,s.decimals,a,U,N]),{isQuoting:u,quoteError:f,estimatedOutput:h,estimatedInput:g,resolvedSwap:C,exactOutputSwap:b,quoteAmountOut:k,resolvedTokenIn:V,isDirect:X,needsSwap:ce,selectedIsEquivalent:q}}const ed=()=>{},td=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:s,sourceChains:r,supportedSourceAssets:a,buildActionCalls:d,feeExecutionMode:i="user-transfer",buildSpicenetBatch:u,onPayExecute:l,resolveExactOutputSwap:f,actionLabel:m,amountDirection:h="input",swapDescription:x,directDescription:g,paymentAmount:y,amountInputMode:C="fixed",minPaymentAmount:S,maxPaymentAmount:b,onAmountChange:R,styles:k,dark:w,title:F,subtitle:A,onAddFunds:M,onSuccess:E,onError:v})=>{const T=h==="output",{theme:I,dark:D,primaryColor:U,dk:N,palette:H,fontFamily:z,monoFont:W,inputDark:P,cardBg:Q,cardBorder:q,textPrimary:X,textSecondary:G,subtitleText:ce}=p.useSpiceBrand(k,w),V=c.useMemo(()=>P?{...I,colors:{...I.colors,secondary:N.cardBg,surfaceHover:N.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:I,[P,I,N.cardBg,N.hoverBg]),L=c.useMemo(()=>s.logoURI?s:{...s,logoURI:gs[s.symbol]},[s]),te=L.chainId,de=c.useContext(p.SpiceFlowProviderContext),ie=(de?.mode||"7702")!=="7702",Ie=!!de?.isWhitelistGateActive,ye=!!de?.isWhitelistConfigured&&de?.isUserWhitelisted!==!0,ue=c.useMemo(()=>r??de?.supportedChainIds??[],[r,de?.supportedChainIds]),Te=c.useMemo(()=>{if(Ie)return[];if(a)return a;const Ce=de?.allowedTokens;if(!Ce||Ce.length===0)return;const mt=new Set(Ce.map(Ot=>Ot.toLowerCase())),Nn=[],pn=new Set;for(const Ot of ue){const is=p.getChainConfig(Ot);for(const ls of is?.supportedTokens??[]){if(!mt.has(ls.symbol.toLowerCase()))continue;const uo=ls.address.toLowerCase();pn.has(uo)||(pn.add(uo),Nn.push(ls.address))}}return Nn},[a,de?.allowedTokens,ue,Ie]),{address:O,isConnected:ee,isReady:oe,isAuthenticated:se,provider:Z}=p.useWallet(),{execute:le,estimate:fe}=hn(),{externalWallet:$,embeddedAddress:xe,activeWallet:He,activeAddress:Xe}=p.useProviderWallets(),yt=de?.externalWalletAddress,ht=de?.embeddedWalletAddress||xe,{displayAssets:Ze,filteredSpiceAssets:me,embeddedWalletAddress:Ae,refreshSpiceAssets:De,refreshWalletAssets:Ge}=_r({destinationToken:L,supportedSourceAssets:Te,sourceChains:ue,enabled:e&&(ie?!!yt:!!ht)}),vt=Ie||T||ie?Ze:me,[re,it]=c.useState(null),[pe,je]=c.useState(y||""),[be,Qe]=c.useState(!1),[gt,St]=c.useState(null),Ne=c.useRef(v);Ne.current=v;const It=c.useCallback(Ce=>{St(Ce),typeof Ce=="string"&&Ce&&Ne.current?.(new Error(Ce),p.getRelayerErrorDetail(Ce))},[]),[Le,lt]=c.useState("idle"),[Wt,Ve]=c.useState(""),[tt,At]=c.useState(null),[Dt,we]=c.useState(!1),[Se,xt]=c.useState(null),[nt,ge]=c.useState(null),[Zt,st]=c.useState(!1),[Ct,Ee]=c.useState(!1),[Tt,ot]=c.useState(null),ct=c.useRef(re),Re=c.useRef(!1),_e=c.useRef(null),rt=c.useRef(null),Pt=c.useRef(null),Et=c.useRef(null),Mt=c.useRef(null);c.useEffect(()=>{ct.current=re},[re]);const Pe=C==="adjustable"?pe:y||"0",bt=Ae||xe||O,{isQuoting:Ue,quoteError:dt,estimatedOutput:at,resolvedSwap:pt,exactOutputSwap:qe,quoteAmountOut:ft,resolvedTokenIn:ut,isDirect:et,needsSwap:Y,selectedIsEquivalent:_}=ya({direction:h,selectedAsset:re,destinationToken:L,chainId:te,recipient:bt,paymentAmount:Pe,resolveExactOutputSwap:f}),ne=T?parseFloat(Pe||"0"):parseFloat(re?.amount||"")||0,Fe=re?.asset?._source==="wallet",J=!!re?.asset&&Fe&&re.asset.chainId!==te,ke=c.useMemo(()=>re?.asset?me.find(Ce=>p.addressesEqual(Ce.address,re.asset.address))?.balanceFormatted??0:0,[re,me]),Ke=Fe?re?.asset.balanceFormatted??0:ke,Oe=c.useMemo(()=>{if(!re?.asset)return!1;if(T)return nt?Lt(nt.grossAmount,nt.decimals,re.asset.decimals)>re.asset.balance:_||et?ne>re.asset.balanceFormatted:qe?parseFloat(B.formatUnits(qe.amountInMax,re.asset.decimals))>re.asset.balanceFormatted:!1;if(nt){const Ce=Lt(nt.grossAmount,nt.decimals,re.asset.decimals);return Fe?Ce>re.asset.balance:parseFloat(B.formatUnits(Ce,re.asset.decimals))>Ke}return ne>Ke},[re,T,nt,_,ne,qe,Ke,Fe,et]);c.useEffect(()=>{e||(it(null),It(null),Qe(!1),lt("idle"),Ve(""),At(null),we(!1),xt(null),ge(null),st(!1),Ee(!1),ot(null),Re.current=!1,C==="adjustable"&&je(y||""),_e.current&&(_e.current.abort(),_e.current=null))},[e]);const Be=c.useCallback(Ce=>{it(mt=>({asset:Ce,amount:mt?.asset?.address===Ce.address&&mt?.asset?.chainId===Ce.chainId&&mt.amount||""})),It(null),ot(null),Ee(!1)},[]),jt=c.useCallback(Ce=>{it(mt=>mt&&{...mt,amount:Ce}),It(null),ot(null),Ee(!1)},[]),We=c.useCallback(Ce=>{let mt=Ce;b&&parseFloat(mt)>parseFloat(b)&&(mt=b),je(mt),R?.(mt),It(null),ot(null),Ee(!1)},[b,R]),Me=c.useCallback(Ce=>{lt({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[Ce.step]||"executing"),Ve(Ce.message),Ce.txHash&&At(Ce.txHash)},[]),ze=c.useMemo(()=>({currentPaymentAmount:Pe,destinationToken:L,embeddedWalletAddress:Ae,providerEmbeddedAddress:xe,externalWalletAddress:yt,address:O,isNon7702:ie,isPayMode:T,resolvedChainId:te,buildActionCalls:d,feeExecutionMode:i,buildSpicenetBatch:u,selectedAsset:re,needsSwap:Y,resolvedSwap:pt,exactOutputSwap:qe,quoteAmountOut:ft,resolvedTokenIn:ut}),[Pe,L,Ae,xe,yt,O,ie,T,te,d,i,u,re,Y,pt,qe,ft,ut]),Je=c.useCallback(Ce=>Rr({...ze,requestTimestampMs:rt.current??Date.now()},Ce),[ze]),kt=c.useCallback(Ce=>Dr({...ze,requestTimestampMs:rt.current??Date.now()},Ce),[ze]),Ft=c.useMemo(()=>re?.asset?Y&&ut?ut:re.asset.chainId===te?re.asset.address:ut??zt(re.asset,te)??L.address:L.address,[re,L.address,Y,te,ut]),dn=c.useCallback(()=>(rt.current=Date.now(),Vr(Mt.current)),[]),Rt=c.useMemo(()=>re?.asset?p.addressesEqual(re.asset.address,L.address)&&re.asset.chainId===L.chainId:!1,[re,L.address,L.chainId]),Ut=Rt&&(ie||T),wt=Ut&&ne>0&&!!re?.asset,Gt=ye&&!Ut,un=c.useMemo(()=>{if(!wt)return null;let Ce;try{Ce=B.parseUnits(Pe||"0",L.decimals)}catch{return null}return{symbol:L.symbol,decimals:L.decimals,grossAmount:Ce,netAmount:Ce,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[wt,Pe,L.symbol,L.decimals]),Rn=gt,Xt=c.useMemo(()=>!(!re?.asset||ne<=0),[re,ne,wt]),Ht=c.useMemo(()=>!e||be||Le!=="idle"||!Xt||wt||!re?.asset?null:[T?"pay":"supply",h,re.asset.address.toLowerCase(),re.asset.chainId,re.amount,Pe,L.address.toLowerCase(),L.chainId,te,ut?.toLowerCase()??"",Y?"swap":"direct",et?"direct-token":"routed-token",ie?"non7702":"7702",Rt?"source-dest":"cross-chain",Ue?"quoting":"quoted",qe?.amountIn?.toString()??"",qe?.amountInMax?.toString()??"",qe?.venue??"",pt?.amountOut?.toString()??"",ft?.toString()??"",Ae??"",xe??"",O??""].join("|"),[e,be,Le,Xt,wt,re,T,h,Pe,L,te,ut,Y,et,ie,Rt,Ue,qe,pt,ft,Ae,xe,O]),yn=c.useCallback(Ce=>Wr({signal:Ce,selectedAsset:re,isPayMode:T,parsedAmount:ne,needsSwap:Y,exactOutputSwap:qe,isNon7702:ie,isSourceDestToken:Rt,currentPaymentAmount:Pe,destinationToken:L,feeExecutionMode:i,resolvedTokenIn:ut,embeddedWalletAddress:Ae,providerEmbeddedAddress:xe,resolvedChainId:te,isConnected:ee,address:O,ready:oe,authenticated:se,isDirect:et,resolvedSwap:pt,isQuoting:Ue,executionTokenAddress:Ft,buildPayChainBatches:Je,buildSupplyChainBatches:kt,estimate:fe}),[re,T,ne,Y,qe,ie,Rt,Pe,L,i,ut,Ae,xe,Je,fe,te,ee,O,oe,se,et,pt,Ue,kt,Ft]);c.useEffect(()=>{Pt.current=yn},[yn]);const os=c.useCallback(Ce=>Nr({asset:Ce,isPayMode:T,isNon7702:ie,needsSwap:Y,isQuoting:Ue,embeddedWalletAddress:Ae,buildSupplyChainBatches:kt,estimate:fe,executionTokenAddress:Ft,feeExecutionMode:i}),[T,ie,Y,Ue,Ae,kt,fe,Ft,i]);Pn({shouldRun:e&&!be&&Le==="idle"&&Xt&&!wt&&!Ue&&!!Ht,deps:[e,be,Le,Xt,wt,un,Ue,Ht],onSkip:()=>{if(!e){st(!1),Ee(!1),ot(null),ge(null);return}if(be||Le!=="idle"){st(!1);return}if(!Xt){ge(null),st(!1),Ee(!1),ot(null);return}if(wt){ge(un),st(!1),Ee(!0),ot(null);return}Ue&&(st(!1),Ee(!1))},onCleanup:()=>st(!1),delayMs:500,backgroundIntervalMs:5e3,run:async({isBackground:Ce,isCurrent:mt,signal:Nn})=>{const pn=Ht;Ce||(ot(null),st(!0));try{const Ot=await Pt.current?.(Nn);if(!mt())return;Ot&&pn?(Et.current={key:pn,quote:Ot},ge(Ot.preview),Ee(!0)):(Et.current=null,ge(null),Ee(!1)),ot(null)}catch(Ot){if(!mt())return;if(Ce&&Et.current?.key===pn){console.warn("[SpiceSupply] fee refresh failed:",Ot);return}const is=p.sanitizeError(Ot,"Unable to calculate fees for this action.");Et.current=null,ge(null),Ee(!1),ot(is)}finally{mt()&&st(!1)}}});const K=c.useCallback(()=>(rt.current=Date.now(),Kr(Mt.current)),[]);c.useEffect(()=>{!T&&Le==="success"&&tt&&(De(),E?.(tt))},[T,Le,tt,De,E]),c.useEffect(()=>{if(!T||Se?.status!=="success"||Re.current||!O)return;Re.current=!0;const Ce=ct.current;!Ce?.asset||Ce.asset?._source==="wallet"||De()},[T,Se?.status,O,De]);const ae=c.useRef(E),ve=c.useRef(v);c.useEffect(()=>{ae.current=E},[E]),c.useEffect(()=>{ve.current=v},[v]),c.useEffect(()=>{e&&(De(),Ge())},[e,De,Ge]),c.useEffect(()=>{T&&(Se?.status==="success"&&ae.current?.(Se.txHash||""),Se?.status==="failed"&&ve.current?.(new Error("Payment execution failed")))},[T,Se?.status]);const he=c.useCallback(()=>{we(!1),xt(null),it(null),Re.current=!1,De(),Ge()},[De,Ge]);Mt.current={selectedAsset:re,parsedAmount:ne,currentPaymentAmount:Pe,isInsufficientBalance:Oe,isPayMode:T,isNon7702:ie,isSourceDestToken:Rt,needsSwap:Y,exactOutputSwap:qe,selectedIsEquivalent:_,resolvedTokenIn:ut,embeddedWalletAddress:Ae,providerEmbeddedAddress:xe,externalWallet:$,externalWalletAddress:yt,activeSignerWallet:He,activeSignerAddress:Xe,address:O,isConnected:ee,ready:oe,authenticated:se,provider:Z,resolvedChainId:te,executionTokenAddress:Ft,destinationToken:L,buildActionCalls:d,feeExecutionMode:i,buildSpicenetBatch:u,onPayExecute:l,onSuccess:E,feeQuote:Ht&&Et.current?.key===Ht?Et.current.quote:null,execution:{estimate:fe,execute:le,buildPayChainBatches:Je,buildSupplyChainBatches:kt,onProgress:Me},ui:{setError:It,setStep:lt,setStatusMsg:Ve,setTxHash:At,setIsExecuting:Qe,setShowStatusPanel:we,setPaymentResult:xt},refs:{spiceDepositSubmittedRef:Re,abortControllerRef:_e}};const $e=y?.trim(),Ye=T&&C==="fixed"&&$e!==void 0&&$e!==""&&ne===0,Jt=T?(Ye||!!re?.asset)&&ne>=0&&!Oe&&!be&&(Ye||wt||Ct)&&!Tt&&(Ye||!Y||!!qe)&&!Gt:!!re?.asset&&ne>0&&!Oe&&!be&&(Ut||Ct)&&!Tt&&(J||et||!!pt&&!Ue)&&!Gt,Dn=et?g||`Your ${L.symbol} will be used directly.`:x||"Your assets will be swapped and used in a single atomic transaction.",Mn=(te?p.getChainConfig(te):void 0)?.viemChain?.blockExplorers?.default?.url??"",rs=Xr.indexOf(Le),as=be?(Gr[Le]||"EXECUTING...").toUpperCase():Le==="success"?"DONE":Oe?"INSUFFICIENT BALANCE":Y&&dt&&!Ue?"QUOTE ERROR":m.toUpperCase(),Ca=c.useMemo(()=>{if(Se?.status==="success")return"DONE";if(be)return"PAYING...";if(Oe&&re?.asset)return`INSUFFICIENT ${re.asset.symbol}`;if(Y&&dt&&!Ue)return"QUOTE ERROR";if(m)return m.toUpperCase();const Ce=ne>0?` ${Pe} ${L.symbol}`:"";return Y?`SWAP & PAY${Ce}`:`PAY${Ce}`},[be,Oe,re,m,ne,Pe,L.symbol,Y,dt,Ue,Se?.status]),ba=Le==="success"?()=>{lt("idle"),it(null),At(null),De()}:dn,ka=Le==="success"?!1:!Jt;if(!e)return null;const ao=T?F||`Pay ${L.symbol}`:m,io=T?A:o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[o.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:o.jsx(Bs,{color:ce})}),o.jsx("p",{style:{fontSize:"12px",color:ce,margin:0,lineHeight:"1.4",fontFamily:z},children:Dn})]}),lo={...k,button:{...k?.button,backgroundColor:U}},co=Xt&&o.jsx(Rs,{fontFamily:z,textPrimary:X,textSecondary:G,cardBg:Q,cardBorder:q,resolvedDark:D,darkCardBorder:N.cardBorder,primaryColor:U,feePreview:nt,isLoading:Zt,errorText:Tt,directExecutionFeeNote:wt});if(T){const Ce=Se&&(Se.status==="success"||Se.status==="failed")?[{asset:{symbol:re?.asset?.symbol||L.symbol,address:re?.asset?.address||""},amount:Pe,txHash:Se.txHash||"",success:Se.status==="success",error:Se.status==="failed"?Se.error:void 0}]:void 0;return o.jsx(Vt,{isOpen:e,onClose:t,title:ao,subtitle:io,styles:k,dark:D,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[M&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:o.jsx(Ds,{onClick:M,color:U,fontFamily:z})}),!Ye&&o.jsx("div",{style:{marginBottom:"12px"},children:o.jsx(vn,{assets:vt,selectedAsset:re??void 0,onAssetSelect:Be,onAmountChange:ed,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:re?.asset?Y?Ue?"...":qe?`~${parseFloat(B.formatUnits(qe.amountIn,re.asset.decimals)).toFixed(6)}`:void 0:Pe??void 0:void 0,dark:D,theme:V,styles:k})}),o.jsx(Yr,{variant:"pay",destinationSymbol:L.symbol,destinationLogoURI:L.logoURI,destinationDecimals:L.decimals,primaryColor:U,fontFamily:z,textPrimary:X,textSecondary:G,cardBg:Q,cardBorder:q,dk:N,dark:D,isQuoting:Ue,quoteError:dt,estimatedOutput:at,paymentAmount:Pe,needsSwap:Y,exactOutputSwap:qe,adjustable:C==="adjustable",maxAmount:b,onAmountChange:We}),co,Rn&&o.jsx(rn,{variant:"error",palette:H,fontFamily:z,style:{marginBottom:"12px"},children:Rn}),o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:Se?.status==="success"?t:K,disabled:Se?.status==="success"?!1:!Jt,loading:be,dark:D,styles:lo,children:Ca}),Se&&Dt&&o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:D?N.shell:"white",borderRadius:D?"12px":"6px",padding:"16px 0"},children:o.jsx(zs,{type:"payment",isOpen:Se.status!=="processing",isProcessing:be||Se.status==="processing",closeOnComplete:!1,chainId:te,onRetryTx:()=>{we(!1),xt(null),K()},onNewTx:he,onClose:()=>{we(!1),xt(null)},onComplete:he,results:Ce,styles:k,dark:D})})]})})}return o.jsx(Vt,{isOpen:e,onClose:t,title:ao,subtitle:io,dark:D,styles:k,theme:I,closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[o.jsx("div",{style:{marginBottom:"16px"},children:o.jsx(vn,{assets:vt,selectedAsset:re||void 0,onAssetSelect:Be,onAmountChange:jt,disabled:be||Le==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:V,styles:k,dark:P,resolveMaxAmount:os,maxAmount:Ke>0?p.formatDecimalInput(Ke,re?.asset.decimals??L.decimals):void 0})}),re?.asset&&!et&&o.jsx(Yr,{variant:"supply",destinationSymbol:L.symbol,destinationLogoURI:L.logoURI,destinationDecimals:L.decimals,primaryColor:U,fontFamily:z,textPrimary:X,textSecondary:G,cardBg:Q,cardBorder:q,dark:D,isQuoting:Ue,quoteError:dt,estimatedOutput:at}),co,Le!=="idle"&&o.jsx(Rc,{step:Le,statusMsg:Wt,txHash:tt,explorerUrl:Mn,currentStepIdx:rs,palette:H,cardBg:Q,cardBorder:q,textPrimary:X,textSecondary:G,fontFamily:z,primaryColor:U,onRetry:()=>{lt("idle"),It(null),setTimeout(dn,50)}}),gt&&Le==="idle"&&o.jsx(rn,{variant:"error",palette:H,fontFamily:z,style:{marginBottom:"16px"},children:gt}),o.jsx(p.Button,{variant:"outline",fullWidth:!0,disabled:ka,onClick:ba,theme:I,dark:D,styles:lo,style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:W},children:as})]})})},nd=()=>{const[e,t]=c.useState("0"),[n,s]=c.useState(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:n,setSelectedAsset:s}};function sd(e,t=0){const[n,s]=c.useState(t),r=e[n]??e[0],a=c.useMemo(()=>r?BigInt(Math.round(r.months*30*24*3600)):0n,[r?.months]);return{selectedDurationIdx:n,setSelectedDurationIdx:s,selectedDuration:r,durationSeconds:a}}function od(){const{actions:e,isReady:t,isAuthenticated:n}=p.useWallet(),s=c.useContext(p.SpiceFlowProviderContext)?.embeddedWalletAddress,r=c.useRef(!1),a=c.useRef(0),d=c.useRef(null),i=c.useRef(e),[u,l]=c.useState(0);i.current=e,c.useEffect(()=>{r.current=!1,a.current=0,d.current&&(clearTimeout(d.current),d.current=null)},[s]),c.useEffect(()=>{if(!s||!t||!n||r.current)return;r.current=!0;let f=!1;return(async()=>{await qt(2e3);try{await p.ensureSmartWallet(s,i.current.signMessage),a.current=0}catch(m){console.warn("[SmartWallet] Registration failed:",m),r.current=!1,!f&&a.current<3&&(a.current+=1,d.current=setTimeout(()=>{l(h=>h+1)},5e3))}})(),()=>{f=!0,d.current&&(clearTimeout(d.current),d.current=null)}},[s,t,n,u])}Aa(),exports.SpiceFlowProvider=p.SpiceFlowProvider,exports.SpiceFlowProviderContext=p.SpiceFlowProviderContext,exports.SpiceflowError=p.SpiceflowError,exports.Spinner=p.Spinner,exports.buildDarkPalette=p.buildDarkPalette,exports.buildLightPalette=p.buildLightPalette,exports.duration=p.duration,exports.easing=p.easing,exports.font=p.font,exports.getChainConfig=p.getChainConfig,exports.getChainName=p.getChainName,exports.isSpiceflowError=p.isSpiceflowError,exports.radius=p.radius,exports.relayerService=p.relayerService,exports.resolveTheme=p.resolveTheme,exports.transition=p.transition,exports.useIsUserWhitelisted=p.useIsUserWhitelisted,exports.useSpiceBrand=p.useSpiceBrand,exports.useWallet=p.useWallet,exports.z=p.z,Object.defineProperty(exports,"NATIVE_TOKEN_ADDRESS",{enumerable:!0,get:function(){return j.ZERO_ADDRESS}}),Object.defineProperty(exports,"SPICENET_NATIVE_CHAIN_ID",{enumerable:!0,get:function(){return j.SPICENET_NATIVE_CHAIN_ID}}),Object.defineProperty(exports,"SPICE_COMBINED_FEE_RECIPIENT",{enumerable:!0,get:function(){return j.SPICE_COMBINED_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_GAS_FEE_RECIPIENT",{enumerable:!0,get:function(){return j.SPICE_GAS_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_PLATFORM_FEE_RECIPIENT",{enumerable:!0,get:function(){return j.SPICE_PLATFORM_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_SOLVER_ADDRESS",{enumerable:!0,get:function(){return j.SPICE_SOLVER_ADDRESS}}),Object.defineProperty(exports,"applySlippage",{enumerable:!0,get:function(){return j.applySlippage}}),Object.defineProperty(exports,"buildUniV3SwapCalls",{enumerable:!0,get:function(){return j.buildUniV3SwapCalls}}),Object.defineProperty(exports,"getChainIdsByNetwork",{enumerable:!0,get:function(){return j.getChainIdsByNetwork}}),Object.defineProperty(exports,"getEscrowContractAddress",{enumerable:!0,get:function(){return j.getEscrowContractAddress}}),Object.defineProperty(exports,"isNativeToken",{enumerable:!0,get:function(){return j.isNativeToken}}),Object.defineProperty(exports,"isSpicenetChainId",{enumerable:!0,get:function(){return j.isSpicenetChainId}}),Object.defineProperty(exports,"normalizeNativeTokenAddress",{enumerable:!0,get:function(){return j.normalizeNativeTokenAddress}}),Object.defineProperty(exports,"spicenetAbi",{enumerable:!0,get:function(){return j.spicenetAbi}}),Object.defineProperty(exports,"spicenetWithdrawalAbi",{enumerable:!0,get:function(){return j.spicenetAbi}}),exports.AccountDisplay=kc,exports.AddFundsLink=Ds,exports.CheckIcon=fo,exports.ChevronIcon=nn,exports.CloseIcon=Sn,exports.DetailRow=gn,exports.ProviderLogin=Os,exports.SATSUMA_CITREA_CONFIG=_s,exports.SearchInput=ds,exports.SelectChainModal=ll,exports.SpiceDeposit=il,exports.SpiceLock=Jl,exports.SpiceSupply=td,exports.SpiceWithdraw=Ml,exports.StatusBanner=rn,exports.UNIV3_BASE_CONFIG=sa,exports.UNIV3_ROBINHOOD_CONFIG=oa,exports.UNIV4_BASE_CONFIG=la,exports.UNIV4_ROBINHOOD_CONFIG=so,exports.V4_NATIVE_CURRENCY=cn,exports.areEquivalentOnChains=In,exports.buildPayChainBatches=Rr,exports.buildRoutedBatches=Rl,exports.buildSupplyChainBatches=Dr,exports.createExactOutputRegistry=ga,exports.createLiquidityRegistry=ra,exports.createSatsumaVenue=eo,exports.createUniV4ExactOutputVenue=ro,exports.createUniV4Venue=ha,exports.estimateFeePreview=Wr,exports.estimateRequiredGrossFunding=vc,exports.estimateSupplyMaxAmount=Nr,exports.executePay=Kr,exports.executeSupply=Vr,exports.findEquivalentOnChain=Yt,exports.getAssetChainTokenCandidates=On,exports.getBestUniV3Quote=ea,exports.isSupportedSupplyAsset=$r,exports.resolveAssetTokenAddressOnChain=zt,exports.resolveFundedToken=Fo,exports.resolveInputSupplySwapQuote=_c,exports.resolveRoute=Tl,exports.scaleTokenAmount=Lt,exports.useAssetInput=nd,exports.useLockDuration=sd,exports.useSmartWallet=od,exports.useSpiceAssets=jn,exports.useSpiceExecution=hn,exports.useSpicePendingDeposits=Sr,exports.useSupplyAssets=_r,exports.useSupplyQuote=ya;
|