@spicenet-io/spiceflow-ui 4.0.6 → 4.0.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 CHANGED
@@ -105,4 +105,4 @@
105
105
  from { opacity: 0; transform: translateY(-4px); }
106
106
  to { opacity: 1; transform: translateY(0); }
107
107
  }
108
- `})]}),document.body):null;return o.jsxs(o.Fragment,{children:[wt,Ze,j&&Un.createPortal(o.jsx(zo,{isOpen:!0,onClose:Y,supportedChains:[j.chainId],escrowOnly:!0,escrowTokenAddress:j.tokenAddress,escrowAmount:j.amount,escrowTokenDecimals:j.tokenDecimals,escrowTokenSymbol:j.tokenSymbol,styles:u,onDepositSuccess:_}),document.body)]})},Ol="0xa9059cbb";function dr(e,t,n){return F.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[n,t]})}}function ur(e,t,n){return{chainId:n,calls:[dr(e,t,F.getEscrowContractAddress(n))]}}function pr(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function fr(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith(Ol)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function ps(e,t,n,s){if(!t)return[e];const r=await t({...n,requestTimestampMs:s});return r?[r,e]:[e]}function Xs(e){return e.filter(t=>t.domain!=="spicenet")}function fs(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:F.normalizeNativeTokenAddress(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function ln(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const s=10n**BigInt(t-n);return(e+s-1n)/s}async function hr(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:l,isNon7702:d,isPayMode:u,resolvedChainId:c,buildActionCalls:f,feeExecutionMode:p,buildSpicenetBatch:x,selectedAsset:g,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:C,requestTimestampMs:k}=e,v=T.parseUnits(n,s.decimals),M=t?.actionAmountOverride??v,b=r||a||(d?void 0:l);if(!b)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:b,chainId:c,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??v,netAmount:M,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},R=f(M,w),j={chainId:c,calls:R},N=!u&&!d?!0:g?.asset?._source==="spice",B=pr(g??null,d,c),S=N||d||B,E=(A,W)=>({token:A,from:d?"solver":"escrow",to:b,amount:W}),I=(A,W,O)=>B?[ur(A,W,c),...O]:O;if(v===0n)return[j];if(m&&y){const A=C??rn(g.asset,c)??g.asset.address,W=t?.fundingAmountOverride??y.amountInMax,O=S?[E(A,W)]:[],z={to:A,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},P={chainId:c,calls:[z,...y.calls,...R],tokenTransfers:[...O,...j.tokenTransfers??[]]};if(!S)return[P];const D=await ps(P,x,{userAddress:b,destinationChainId:c,deliveryToken:A,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:fs(P),sourceAsset:g.asset},k);return I(A,W,D)}if(S){const A=C??rn(g.asset,c)??s.address;if(B&&A.toLowerCase()===s.address.toLowerCase())return[j];const W=t?.fundingAmountOverride??v,O={...j,tokenTransfers:[E(A,W),...j.tokenTransfers??[]]},z=await ps(O,x,{userAddress:b,destinationChainId:c,deliveryToken:A,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:fs(O),sourceAsset:g.asset},k);return I(A,W,z)}return[j]}async function mr(e,t){const{selectedAsset:n,embeddedWalletAddress:s,externalWalletAddress:r,recipient:a,resolvedChainId:l,destinationToken:d,buildActionCalls:u,feeExecutionMode:c,buildSpicenetBatch:f,isPayMode:p,isNon7702:x,needsSwap:g,resolvedSwap:m,quoteAmountOut:y,resolvedTokenIn:C,requestTimestampMs:k}=e,v=m?.amountOutMinimum??y;if(!n?.asset||!s)return[];const M=a??(x?r:s);if(!M)return[];const b=t?.fundingAmountOverride??t?.actionAmountOverride??T.parseUnits(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??b,R=t?.sourceFundingAmountOverride??b,j=t?.deliveryAmountOverride??w,N=t?.withdrawalAmountOverride??j,B=t?.actionAmountOverride??b,S={userAddress:M,chainId:l,destinationToken:d.address,feeToken:c==="user-transfer"&&g&&C?C:d.address,grossAmount:w,netAmount:B,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},E=u(B,S),I=n.asset?._source==="wallet";if(!p&&x&&I&&n.asset.chainId===l){if(g){if(!C)throw new Error("Swap input token could not be resolved");if(!m||v===null)throw new Error("Swap quote not available yet")}if(g&&m&&v){const U=u(t?.actionAmountOverride??v,{...S,netAmount:t?.actionAmountOverride??v}),{feeCall:G,remainingCalls:pe}=fr(U,c,g,S.feeToken);return[{chainId:l,calls:[...G?[G]:[],...m.calls,...pe]}]}return[{chainId:l,calls:E}]}if(!p&&!x&&I&&n.asset.chainId!==l)throw new Error("Cross-chain wallet supplies require external wallet mode");const A=!p&&!x?n.asset?._source!=="wallet":n.asset?._source==="spice",W=x&&I,O=pr(n,x,l);if(!(A||W||O))return[{chainId:l,calls:E}];const z=O?ur(C??F.normalizeNativeTokenAddress(n.asset.address),R,l):W&&n.asset.chainId!==l?{chainId:n.asset.chainId,calls:[dr(F.normalizeNativeTokenAddress(n.asset.address),R,F.getEscrowContractAddress(n.asset.chainId))]}:null,P=(U,G)=>({token:U,from:W?"solver":"escrow",to:s,amount:G}),D=(U,G)=>W?[{token:U,from:"escrow",to:F.SPICE_SOLVER_ADDRESS,amount:G}]:[];if(g){if(!C)throw new Error("Swap input token could not be resolved");if(!m||v===null)throw new Error("Swap quote not available yet")}if(g&&m&&v&&C){const U=u(t?.actionAmountOverride??v,{...S,netAmount:t?.actionAmountOverride??v}),{feeCall:G,remainingCalls:pe}=fr(U,c,g,S.feeToken),q={chainId:l,calls:[...G?[G]:[],...m.calls,...pe],tokenTransfers:[...D(C,N),P(C,j)]},J=await ps(q,f,{userAddress:s,destinationChainId:l,deliveryToken:C,deliveryAmount:j,withdrawalAmount:N,deliveryRecipient:s,deliveryTransfers:fs(q),sourceAsset:n.asset},k);return z?[z,...J]:J}const Q=C??rn(n.asset,l)??d.address,H={chainId:l,calls:E,tokenTransfers:[...D(Q,N),P(Q,j)]},ee=await ps(H,f,{userAddress:s,destinationChainId:l,deliveryToken:Q,deliveryAmount:j,withdrawalAmount:N,deliveryRecipient:s,deliveryTransfers:fs(H),sourceAsset:n.asset},k);return z?[z,...ee]:ee}async function gr(e,t,n,s,r){let a=e;for(let l=0;l<4;l++){const d=await t(a),u=await s(d,n,a,r),c=oi(u);if(c===null||c>=e)return a;const f=a-c,p=e+f;if(p<=a)return a;a=p}return a}function zl(e,t,n,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 xr(e){const{asset:t,isPayMode:n,isNon7702:s,needsSwap:r,isQuoting:a,embeddedWalletAddress:l,buildSupplyChainBatches:d,estimate:u,executionTokenAddress:c,feeExecutionMode:f}=e;if(n||s||r||a||!l||t.balance<=0n)return null;const p=l,x=await d({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(x.length===0)return null;const g=x.some(M=>M.tokenTransfers?.length),m=await u(x,c,t.balance,g?{userOverride:p,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:p,feeExecutionMode:f}:{userOverride:p}),y=Cn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),C=y?ln(y.gasFee,y.decimals,t.decimals):0n,k=y?ln(y.spicenetFee,y.decimals,t.decimals):0n,v=zl(t.balance,C,k,t.balance);return v>0n?Eo(v,t.decimals):null}async function yr(e){const{selectedAsset:t,isPayMode:n,parsedAmount:s,needsSwap:r,exactOutputSwap:a,isNon7702:l,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:c,feeExecutionMode:f,resolvedTokenIn:p,embeddedWalletAddress:x,providerEmbeddedAddress:g,resolvedChainId:m,isConnected:y,address:C,ready:k,authenticated:v,isDirect:M,resolvedSwap:b,isQuoting:w,executionTokenAddress:R,buildPayChainBatches:j,buildSupplyChainBatches:N,estimate:B,estimateRequiredGrossFunding:S}=e;if(!t?.asset)return null;if(n){if(s<=0||r&&!a||d)return null;const D=T.parseUnits(u,c.decimals),Q=p||rn(t.asset,m)||t.asset.address||c.address,H={chainId:m,tokenAddress:Q,symbol:F.getTokenByAddress(Q,m)?.symbol??t.asset.symbol,decimals:F.getTokenByAddress(Q,m)?.decimals??t.asset.decimals};if(l){const J=x||g;if(!J)return null;const le=r?a?.amountInMax??0n:D;if(le===0n)return null;const be={userOverride:J,useCustomTransfers:!0},ie=await S(le,ke=>j({fundingAmountOverride:ke}),Q,be),fe=await j({fundingAmountOverride:ie}),ce=await B(fe,Q,ie,{...be,feeExecutionMode:f});return Cn(ce,H)}if(!y||!C||!k||!v)return null;const ee=x||g||C,U=r?a?.amountInMax??0n:D;if(U===0n)return null;const G=await S(U,J=>j({fundingAmountOverride:J}).then(le=>an(Xs(le),ee)),Q,{useCustomTransfers:!0});let pe=an(Xs(await j({fundingAmountOverride:G})),ee);const q=await B(pe,Q,G,{useCustomTransfers:!0,feeExecutionMode:f});return Cn(q,H)}if(s<=0||!x)return null;const E=x||g;if(!(!n&&!l&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!M&&!b&&!w||w)return null;const I=T.parseUnits(t.amount,t.asset.decimals),A=await N();if(A.length===0)return null;const W=l&&t.asset?._source==="wallet"&&t.asset.chainId===m,O={chainId:m,tokenAddress:R,symbol:F.getTokenByAddress(R,m)?.symbol??c.symbol,decimals:F.getTokenByAddress(R,m)?.decimals??c.decimals};if(W){const D=await h.relayerService.estimateBatchGas({user:E,outputToken:R,stepIndex:0,chainBatches:A}),Q=es(I,10n),H=Q+D.gasFee;return{...O,grossAmount:I+H,netAmount:I,totalFee:H,gasFee:D.gasFee,spicenetFee:Q,bridgeFee:0n,gasQuoteSource:D.gasQuoteSource}}const z=A.some(D=>D.tokenTransfers?.length),P=await B(A,R,I,z?{userOverride:E,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:E,feeExecutionMode:f}:{userOverride:E});return Cn(P,O)}const Ll=10n;function Cr(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=rn(n,e.resolvedChainId);if(!s||!h.addressesEqual(s,e.executionTokenAddress))return;const r=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=ln(t,r?.decimals??e.destinationToken.decimals,n.decimals);if(a<=n.balance)return;const l=T.formatUnits(a,n.decimals),d=T.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${l} ${n.symbol}; available ${d} ${n.symbol}.`)}function Gs(e){const t=F.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 Vn(e,t,n){const s=Cn(e,Gs(t));if(!s)return;const r=es(n,Ll),a=s.bridgeFee??0n,l=r+s.gasFee+a;return{grossAmount:n+l,netAmount:n,combinedFeeAmount:l,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:r,gasFee:s.gasFee,bridgeFee:a}}}function br(e,t,n){let s=0n,r=0n;const a=n.toLowerCase();for(const l of e)if(l.chainId===t){for(const d of l.calls??[])if(d.to.toLowerCase()===a)try{const u=T.decodeFunctionData({abi:T.erc20Abi,data:d.data});if(u.functionName!=="transfer")continue;const c=u.args[0].toLowerCase(),f=u.args[1];c===F.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=f:c===F.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(r+=f)}catch{continue}}return{spicenetFee:s,gasFee:r}}function Js(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=br(e,t.resolvedChainId,s);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:yn(r.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&yn(r.gasFee,n.feeBreakdown.gasFee,100n)}function wr(e,t){return e?yn(e.grossAmount,t.grossAmount,100n)&&yn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&yn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&yn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function kr(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 $s(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 vr(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){const r=s instanceof Error?s:new Error(String(s));if(r.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const a=r.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(a),e.ui.setError(a),e.onError?.(r)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=T.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),s=n;let r=await e.execution.buildSupplyChainBatches();const a=e.selectedAsset.asset?._source==="wallet",l=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!a&&!r.some(g=>F.isSpicenetChainId(g.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const d=r.some(g=>g.tokenTransfers?.length)?{userOverride:l,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:l,feeExecutionMode:e.feeExecutionMode}:{userOverride:l};let u=n;const c=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,f=e.feeExecutionMode==="user-transfer"&&!c?s:void 0;let p;for(let g=0;g<4;g+=1){const m=await e.execution.estimate(r,e.executionTokenAddress,u,d),y=Cn(m,Gs(e));p=e.feeExecutionMode==="user-transfer"&&y?Vn(m,e,s):void 0;const C=p?.grossAmount??y?.grossAmount??u;if(C===u){u=C;break}u=C,r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:p})}e.feeExecutionMode==="user-transfer"&&(Cr(e,u),r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:p}));let x=p;await e.execution.execute(r,e.executionTokenAddress,u,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:g,chainBatches:m})=>{const y=Vn(g,e,s);if(!y)return null;const C=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;br(m,e.resolvedChainId,C);const k=wr(x,y),v=Js(m,e,y);return k||v?null:(x=y,e.execution.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:f,actionContextOverride:y}))}}:d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const s=n instanceof Error?n:new Error(String(n));if(s.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(s)}finally{e.ui.setIsExecuting(!1)}}async function vr(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=T.parseUnits(e.selectedAsset.amount,s.decimals),a=r,l=s?._source==="wallet"&&s.chainId===e.resolvedChainId;let d=await e.execution.buildSupplyChainBatches();const u={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let c=r;const f=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!f?a:void 0;let x;if(l){const S=await h.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),E=es(r,10n),I=E+S.gasFee;c=r+I,e.feeExecutionMode==="user-transfer"&&(x={grossAmount:c,netAmount:a,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:E,gasFee:S.gasFee,bridgeFee:0n}})}else for(let S=0;S<4;S+=1){const E=await e.execution.estimate(d,e.executionTokenAddress,0n,u),I=e.feeExecutionMode==="user-transfer"?Vn(E,e,a):void 0,A=Cn(E,Gs(e)),W=I?.grossAmount??(A?A.grossAmount>r?A.grossAmount:r:c);if(x=I,W===c){c=W;break}c=W;const O=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),z=ln(c,O?.decimals??e.destinationToken.decimals,s.decimals);d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:z,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I})}const g=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let m=l?c:ln(c,g?.decimals??e.destinationToken.decimals,s.decimals);Cr(e,c),d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:x});const y=s.chainId,C=n,k=await e.externalWallet.getEthereumProvider();await Wn(k,y,()=>e.ui.setStatusMsg("Switching source network..."));const v=h.getChainConfig(y),M=T.createWalletClient({account:e.externalWalletAddress,chain:v?.viemChain,transport:T.custom(k)}),b=F.normalizeNativeTokenAddress(s.address),w=s.isNative||F.isNativeToken(b),R=h.getClientForChain(y),j=S=>sr({extWc:M,sourceClient:R,recipient:C,tokenAddr:b,isNative:w,amount:S,viemChain:v?.viemChain});e.ui.setStatusMsg("Funding embedded wallet..."),await j(m);let N=m;if(e.feeExecutionMode==="user-transfer")for(let S=0;S<4;S+=1){const E=await e.execution.estimate(d,e.executionTokenAddress,0n,u),I=Vn(E,e,a);if(!I)break;const A=l?I.grossAmount:ln(I.grossAmount,g?.decimals??e.destinationToken.decimals,s.decimals);if(A>N&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await j(A-N),N=A),x=I,c=I.grossAmount,m=A,d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I}),Js(d,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let B=x;await e.execution.execute(d,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:S,chainBatches:E})=>{const I=Vn(S,e,a);if(!I)return null;const A=wr(B,I),W=Js(E,e,I);if(A||W)return null;if(I.grossAmount>c)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");B=I;const O=l?I.grossAmount:ln(I.grossAmount,g?.decimals??e.destinationToken.decimals,s.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:O,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:p,actionContextOverride:I})}}:u)}async function $s(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=T.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),a={userAddress:s,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},l=e.buildActionCalls(r,a);if(l.length===0)throw new Error("No action calls configured");const d=await n.getEthereumProvider();await Wn(d,e.resolvedChainId);const u=h.getChainConfig(e.resolvedChainId),c=T.createWalletClient({account:s,chain:u?.viemChain,transport:T.custom(d)}),f=h.getClientForChain(e.resolvedChainId);let p;for(const x of l){const g=await c.sendTransaction({to:x.to,data:x.data,value:x.value,chain:u?.viemChain});if((await f.waitForTransactionReceipt({hash:g,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");p=g}return p}async function Sr(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=T.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const l=e.resolvedTokenIn||e.selectedAsset.asset.address,d={userOverride:t,useCustomTransfers:!0},u=await e.execution.estimateRequiredGrossFunding(a,k=>e.execution.buildPayChainBatches({fundingAmountOverride:k}),l,d),c=F.getEscrowContractAddress(s),f=await e.externalWallet.getEthereumProvider();await Wn(f,s);const p=h.getChainConfig(s),x=T.createWalletClient({account:e.externalWalletAddress,chain:p?.viemChain,transport:T.custom(f)}),g=F.normalizeNativeTokenAddress(n.address),m=n.isNative||F.isNativeToken(g)?await x.sendTransaction({to:c,value:u,chain:p?.viemChain}):await x.sendTransaction({to:g,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[c,u]}),chain:p?.viemChain});if((await h.getClientForChain(s).waitForTransactionReceipt({hash:m,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const y=await e.execution.buildPayChainBatches({fundingAmountOverride:u}),C=y.some(k=>k.tokenTransfers?.length);return await e.execution.execute(y,l,u,k=>{k.txHash&&(e.ui.setPaymentResult(v=>({...v??{status:"processing"},txHash:k.txHash})),e.ui.setTxHash(k.txHash))},void 0,C?d:{userOverride:t})}async function Ir(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 $s(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,a=T.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),l=e.selectedIsEquivalent?a:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(l===0n)throw new Error("Quote not available yet");const d=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!d)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const u=e.resolvedTokenIn||r.address,c=await e.execution.estimateRequiredGrossFunding(l,x=>e.execution.buildPayChainBatches({fundingAmountOverride:x}),u,{userOverride:d,useCustomTransfers:!0}),f=await e.execution.buildPayChainBatches({fundingAmountOverride:c}),p=await e.onPayExecute({asset:r,amount:e.currentPaymentAmount,amountWei:a,destinationToken:e.destinationToken,chainBatches:f,requiredNetFunding:l,grossFundingAmount:c,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:u,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});p&&(e.ui.setTxHash(p),e.ui.setPaymentResult(x=>({...x??{status:"processing"},txHash:p}))),s=p||void 0}else s=await Sr(e);e.ui.setPaymentResult(r=>({status:"success",txHash:r?.txHash||s||""}))}catch(s){const r=h.sanitizeError(s,"Payment failed. Please try again.");e.ui.setError(r),e.ui.setPaymentResult({status:"failed",error:r}),e.onError?.(s instanceof Error?s:new Error(r))}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=T.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),s={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const C=await e.execution.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),k=await e.execution.execute(C,e.destinationToken.address,0n,v=>{v.txHash&&(e.ui.setPaymentResult(M=>({...M,txHash:v.txHash})),e.ui.setTxHash(v.txHash))},void 0,s);e.ui.setPaymentResult(v=>({status:"success",txHash:v?.txHash||k}));return}const r=e.selectedAsset?.asset;if(!r)throw new Error("Select a payment source");const a=e.resolvedTokenIn||r.address||e.destinationToken.address,l=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,d=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,u=(C,k,v)=>{const M=Xs(C),b=j=>(j.tokenTransfers??[]).some(N=>N.from==="escrow"),w=M.filter(j=>!b(j)),R=M.filter(b);return[...w,...an(R,d,k,v)]},c=await e.execution.estimateRequiredGrossFunding(l,C=>e.execution.buildPayChainBatches({fundingAmountOverride:C}).then(k=>u(k)),a,s);let f=c,p=u(await e.execution.buildPayChainBatches({fundingAmountOverride:c}));const x=await e.execution.estimate(p,a,c,s),g=Cn(x,{chainId:e.resolvedChainId,tokenAddress:a,symbol:F.getTokenByAddress(a,e.resolvedChainId)?.symbol??r.symbol,decimals:F.getTokenByAddress(a,e.resolvedChainId)?.decimals??r.decimals})?.grossAmount??c;g!==c&&(f=g),p=u(await e.execution.buildPayChainBatches({fundingAmountOverride:f}),x,{payoutAlreadyGross:!0});const m=p.some(C=>C.tokenTransfers?.length),y=await e.execution.execute(p,a,m?f:0n,C=>{C.txHash&&(e.ui.setPaymentResult(k=>({...k,txHash:C.txHash})),e.ui.setTxHash(C.txHash))},void 0,s);e.ui.setPaymentResult(C=>({status:"success",txHash:C?.txHash||y}))}catch(n){const s=h.sanitizeError(n,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(n instanceof Error?n:new Error(s))}finally{e.ui.setIsExecuting(!1)}}const Hl=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,isQuoting:x,quoteError:g,estimatedOutput:m,paymentAmount:y,needsSwap:C,exactOutputSwap:k,adjustable:v=!1,maxAmount:M,onAmountChange:b})=>e==="supply"?o.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${c}`,borderRadius:p?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[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:p?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),o.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,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 ${c}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[o.jsx(Er,{symbol:t,logoURI:n,primaryColor:r,size:24}),o.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:p?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),o.jsx("div",{style:{textAlign:"right",minWidth:0},children:x?o.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:a},children:"Quoting..."}):g?o.jsx("span",{style:{fontSize:"13px",color:p?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):m?o.jsx(In,{value:m,title:m,fontFamily:a,color:l,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):o.jsx("span",{style:{fontSize:"20px",color:d,fontFamily:a},children:"\u2014"})})]}):o.jsx(Ql,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:k,isQuoting:x,adjustable:v,maxAmount:M,onAmountChange:b}),Ar=i.memo(Hl),Er=({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)}),Ql=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:l,cardBg:d,cardBorder:u,dk:c,dark:f,paymentAmount:p,needsSwap:x,exactOutputSwap:g,isQuoting:m,adjustable:y,maxAmount:C,onAmountChange:k})=>{const v='"IBM Plex Mono", monospace',M=parseFloat(p||"0"),b=C?parseFloat(C):0,[w,R]=i.useState(p||""),j=i.useRef(null),[N,B]=i.useState(null),[S,E]=i.useState(null);i.useEffect(()=>{y||R(p||"")},[p,y]);const I=O=>{let z=O;z.startsWith(".")&&(z="0"+z);const P=h.parseNumericInput(z);let D=P;C&&parseFloat(P)>parseFloat(C)&&(D=C),R(D),j.current&&clearTimeout(j.current),j.current=setTimeout(()=>k?.(D),300)},A=O=>{if(!b)return;if(O===100){R(C||b.toString()),j.current&&clearTimeout(j.current),k?.(C||b.toString());return}const z=10**n,P=Math.floor(b*O/100*z)/z,D=h.formatDecimalInput(P,n);R(D),j.current&&clearTimeout(j.current),k?.(D)},W=b>0?parseFloat(w||"0")/b*100:0;return i.useEffect(()=>()=>{j.current&&clearTimeout(j.current)},[]),o.jsxs("div",{style:{backgroundColor:d,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(Er,{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:l,fontFamily:r,marginTop:"2px"},children:e})]})]}),o.jsxs("div",{style:{textAlign:"right"},children:[y?o.jsx(In,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:O=>I(O.target.value),placeholder:"0.0",fontFamily:v,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):o.jsx(In,{element:"div",value:M>0?p:"0.00",title:M>0?p:"0.00",fontFamily:v,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),o.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:v,marginTop:"2px"},children:e}),y&&b>0&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((O,z)=>{const P=Math.abs(W-O)<1,D=z===4,Q=O/100,H=N===O,ee=S===O;return o.jsx("button",{onClick:()=>A(O),onMouseEnter:()=>B(O),onMouseLeave:()=>{B(null),E(null)},onMouseDown:()=>E(O),onMouseUp:()=>E(null),title:`${O}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:P?1:H?.8:.5,transform:ee?"scale(0.85)":H?"scale(1.15)":"scale(1)",transition:_t.interactive},children:o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[o.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:D?s:"none",stroke:D?s:f?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!D&&Q>0&&o.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${Q>.5?1:0} 1 ${7+6.84375*Math.sin(Q*2*Math.PI)} ${7-6.84375*Math.cos(Q*2*Math.PI)} Z`,fill:f?c?.textSecondary||"#9ca3af":"#3C3E42"})]})},O)})})]})]}),x&&g&&!m&&o.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:f?`1px solid ${c?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:o.jsxs("span",{style:{fontSize:"11px",color:l,fontFamily:r,opacity:.7},children:["via ",g.venue]})})]})};function jr(e,t,n){const s=h.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 Fr(e,t){return!t||t.length===0||t.some(n=>h.addressesEqual(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const s=Bn(n);return s?t.some(r=>h.addressesEqual(r,s.address)):!1})}function Tr(e,t,n){let{symbol:s,name:r,logoURI:a}=t;const l=h.addressesEqual(e.address,n.address)&&e.chainId===n.chainId;l&&n.logoURI&&(a=n.logoURI),l&&!e.configToken&&s==="TOKEN"&&(s=n.symbol,r=n.symbol);const d=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:d,balanceUsd:0,logoURI:a,isNative:!1,chainId:e.chainId}}function Br(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:s,enabled:r}=e,a=i.useContext(h.SpiceFlowProviderContext),l=(a?.mode||"7702")!=="7702",d=a?.embeddedWalletAddress,{externalAddress:u,embeddedAddress:c,activeAddress:f}=h.useProviderWallets(),p=d||c,{assets:x,refetch:g}=Qn({address:p,supportedChains:s,enabled:r&&!l&&!!p,refetchInterval:3e4}),m=i.useMemo(()=>l?[]:x.filter(B=>Fr(B,n)),[x,n,l]),y=l?f??u:d,C=i.useMemo(()=>{const B=new Set,S=[],E=I=>{if(!I)return;const A=I.toLowerCase();B.has(A)||(B.add(A),S.push(T.getAddress(I)))};if(E(t.address),n)for(const I of n)E(I);return S},[l,t.address,n]),k=i.useMemo(()=>C.map(B=>B.toLowerCase()).sort().join(","),[C]),v=i.useMemo(()=>JSON.stringify([...s||[]].sort()),[s]),[M,b]=i.useState([]),w=i.useRef(0),R=i.useRef(async()=>{}),j=i.useCallback(async()=>{if(!r||!y||C.length===0){w.current++,b([]);return}const B=++w.current,S=T.getAddress(y),E=l?s&&s.length>0?s:[t.chainId]:[t.chainId],I=[];for(const z of C){const P=z.toLowerCase();if(P===F.ZERO_ADDRESS)continue;if(P===t.address.toLowerCase()){const Q=h.getChainConfig(t.chainId)?.supportedTokens?.find(H=>h.addressesEqual(H.address,P));I.push({address:z,chainId:t.chainId,configToken:Q?{decimals:Q.decimals,symbol:Q.symbol,name:Q.name,logo:Q.logo}:void 0});continue}let D=!1;for(const Q of E){const H=h.getChainConfig(Q)?.supportedTokens?.find(ee=>h.addressesEqual(ee.address,P));if(H){I.push({address:z,chainId:Q,configToken:{decimals:H.decimals,symbol:H.symbol,name:H.name,logo:H.logo}}),D=!0;break}}D||I.push({address:z,chainId:t.chainId})}const A=new Map;for(const z of I){const P=A.get(z.chainId)||[];P.push(z),A.set(z.chainId,P)}const W=async(z,P)=>{try{const D=await sn.readContract(z,{address:P.address,abi:T.erc20Abi,functionName:"balanceOf",args:[S]}),{decimals:Q,symbol:H,name:ee,logoURI:U}=await tr(z,P.address,P.configToken);return Tr(P,{decimals:Q,symbol:H,name:ee,logoURI:U,balance:D},t)}catch{return null}},O=await Promise.all(Array.from(A.entries()).map(async([z,P])=>{let D;try{D=h.getClientForChain(z)}catch{return[]}const Q=[],H=[];for(const U of P){const G=Q.length;Q.push({address:U.address,abi:T.erc20Abi,functionName:"balanceOf",args:[S]}),U.configToken||Q.push({address:U.address,abi:T.erc20Abi,functionName:"decimals"},{address:U.address,abi:T.erc20Abi,functionName:"symbol"},{address:U.address,abi:T.erc20Abi,functionName:"name"}),H.push({start:G,item:U})}let ee=null;try{ee=await D.multicall({contracts:Q})}catch{ee=null}return ee?H.map(({start:U,item:G})=>{const pe=ee[U],q=pe?.status==="success"?pe.result:0n;let J,le,be,ie;if(G.configToken)J=G.configToken.decimals,le=G.configToken.symbol,be=G.configToken.name,ie=G.configToken.logo;else{const fe=ee[U+1],ce=ee[U+2],ke=ee[U+3];J=fe?.status==="success"?Number(fe.result):18,le=ce?.status==="success"?ce.result:"TOKEN",be=ke?.status==="success"?ke.result:le}return Tr(G,{decimals:J,symbol:le,name:be,logoURI:ie,balance:q},t)}):(await Promise.all(P.map(U=>W(D,U)))).filter(U=>U!==null)}));B===w.current&&b(O.flat())},[r,l,y,k,v,t.address,t.chainId,t.symbol,t.logoURI]);i.useEffect(()=>{R.current=j},[j]),i.useEffect(()=>{if(!r){b([]);return}R.current();const B=setInterval(()=>{R.current()},15e3);return()=>clearInterval(B)},[r,l,y,k,v,t.address,t.chainId]);const N=i.useCallback(()=>{j()},[j]);return{displayAssets:i.useMemo(()=>{const B=[],S=M.filter(I=>I.balance>0n);for(const I of S)B.push({...I,_source:"wallet"});for(const I of m)B.push({...I,_source:"spice"});const E=t.address.toLowerCase();return B.sort((I,A)=>jr(I,E,t.chainId)-jr(A,E,t.chainId)),B},[M,m,t.address,t.chainId]),filteredSpiceAssets:m,walletAssets:M,embeddedWalletAddress:p,externalAddress:u,isNon7702:l,refreshSpiceAssets:g,refreshWalletAssets:N}}async function Rr(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:r,chainId:a,config:l}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const d=(await h.getClientForChain(a).simulateContract({address:l.quoterV2,abi:F.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function Mr(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>Rr({...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 Vl=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"quoteExactOutputSingle",outputs:[{name:"amountIn",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];async function ql(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:r,chainId:a,config:l}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const d=(await h.getClientForChain(a).simulateContract({address:l.quoterV2,abi:Vl,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function Yl(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>ql({...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 Nr(e){return e.type==="swap"}const _s=.02,Kl=[1,8453,42161,10,137,43114,56],Zl="https://api.1inch.dev/swap/v6.0";function Dr(e,t){return F.applySlippage(e,t)}function Wr(e){const t=e?.baseUrl??Zl;return{name:"1inch",chainIds:e?.chainIds??Kl,resolve:async(n,s,r)=>{const a=n.maxSlippage??_s,l=a*100,d=F.isNativeToken(n.tokenIn)?F.NATIVE_TOKEN_ADDRESS:n.tokenIn,u=F.isNativeToken(n.tokenOut)?F.NATIVE_TOKEN_ADDRESS:n.tokenOut,c=F.isNativeToken(n.tokenIn);try{const f=new URL(`${t}/${s}/swap`);f.searchParams.set("src",d),f.searchParams.set("dst",u),f.searchParams.set("amount",n.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",l.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const x=await fetch(f.toString(),{headers:p});if(!x.ok)throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${x.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 ${x.status}`});const g=await x.json();if(!g.dstAmount||!g.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const m=BigInt(g.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const y=Dr(m,a),C=[];return g.tx.to&&!c&&C.push({to:n.tokenIn,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[g.tx.to,n.amountIn]})}),C.push({to:g.tx.to,value:BigInt(g.tx.value||"0"),data:g.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:C}}catch(f){if(f instanceof h.SpiceflowError)throw f;const p=f instanceof Error?f.message:String(f);throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${p}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:p})}}}}const Pr=[4114,5115],eo={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Ur={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Or(e){return{name:"satsuma",chainIds:e.chainIds??Pr,resolve:async(t,n,s)=>{const r=t.maxSlippage??_s,a=F.isNativeToken(t.tokenIn);let l;try{l=await Mr({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const d=Dr(l.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:T.encodeFunctionData({abi:F.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:l.fee,recipient:s,amountIn:t.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:l.amountOut,amountOutMinimum:d,calls:u}}}}function zr(e){return{name:"satsuma",chainIds:e.chainIds??Pr,resolve:async(t,n,s)=>{const r=t.maxSlippage??_s,a=F.isNativeToken(t.tokenIn);let l;try{l=await Yl({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const d=BigInt(Math.round(r*1e4)),u=l.amountIn+l.amountIn*d/10000n,c=[];return c.push({to:e.swapRouter,value:a?u:0n,data:T.encodeFunctionData({abi:Xl,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:l.fee,recipient:s,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:l.amountIn,amountInMax:u,amountOut:t.amountOut,calls:c}}}}const Xl=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"exactOutputSingle",outputs:[{name:"amountIn",type:"uint256"}],stateMutability:"payable",type:"function"}];function Lr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Or(e.satsuma)),t.push(Wr(e?.oneInch));function n(r){return t.find(a=>a.chainIds.includes(r))}async function s(r,a,l){const d=[],u=[];for(const c of r){if(!Nr(c)){d.push(c);continue}const f=n(a);if(!f)throw new h.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${c.tokenIn} \u2192 ${c.tokenOut}.`,{chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});const p=await f.resolve(c,a,l);if(!p)throw new h.SpiceflowError("NO_LIQUIDITY",`${f.name} returned no quote for ${c.tokenIn} \u2192 ${c.tokenOut} on chain ${a}.`,{venue:f.name,chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});d.push(...p.calls),u.push(p)}return{calls:d,resolvedSwaps:u}}return{resolveSwapIntents:s,getVenueForChain:n,venues:t}}function Hr(e){const t=e?.customVenues??[];async function n(s,r,a){const l=t.filter(c=>c.chainIds.includes(r));if(l.length===0)throw new h.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const d=(await Promise.allSettled(l.map(async c=>({venue:c,quote:await c.resolve(s,r,a)})))).filter(c=>c.status==="fulfilled").map(c=>c.value).filter(c=>c.quote!==null);if(d.length===0)throw new h.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=d.find(c=>c.venue.preferred);return u?u.quote:(d.sort((c,f)=>c.quote.amountIn<f.quote.amountIn?-1:c.quote.amountIn>f.quote.amountIn?1:0),d[0].quote)}return{getQuote:n,venues:t}}const Qr=Lr({satsuma:eo});async function Gl(e){const t=Qr.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 Vr(e){const{direction:t,selectedAsset:n,destinationToken:s,chainId:r,recipient:a,paymentAmount:l,resolveExactOutputSwap:d}=e,[u,c]=i.useState(!1),[f,p]=i.useState(null),[x,g]=i.useState(null),[m,y]=i.useState(null),[C,k]=i.useState(null),[v,M]=i.useState(null),[b,w]=i.useState(null),[R,j]=i.useState(null),[N,B]=i.useState(null),S=i.useRef(null),E=i.useRef(null),I=i.useRef(0),A=i.useRef(new Map),W=i.useMemo(()=>Qr,[]),O=i.useMemo(()=>Hr({customVenues:[...d?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:d}]:[],zr(eo),zr(Ur)]}),[d,r]),z=i.useMemo(()=>{if(!n?.asset)return null;const J=rn(n.asset,r);if(J)return J;const le=hn(n.asset.address,r,n.asset.chainId);return le?le.address:null},[n?.asset,r]),P=i.useMemo(()=>n?.asset?Xn(n.asset,r):[],[n?.asset,r]),D=i.useMemo(()=>P.map(J=>J.toLowerCase()).join(","),[P]);i.useEffect(()=>{let J=!1;if(E.current&&(clearTimeout(E.current),E.current=null),!n?.asset||P.length<=1){B(null);return}return E.current=setTimeout(async()=>{const le=t==="input"?n.amount:l||"0";let be=0n;try{be=t==="input"?T.parseUnits(le,n.asset.decimals):0n}catch{be=0n}try{const ie=await wo(n.asset,r,{requiredAmount:be});J||B(ie)}catch{J||B(null)}},400),()=>{J=!0,E.current&&(clearTimeout(E.current),E.current=null)}},[n?.asset,n?.amount,r,P.length,D,t,l]);const Q=i.useMemo(()=>N??z,[N,z]),H=i.useMemo(()=>!n?.asset||!Q?[]:[Q,...P.filter(J=>J.toLowerCase()!==Q.toLowerCase())],[n?.asset,Q,P]),ee=i.useMemo(()=>!n?.asset||!Hn(n.asset.address,n.asset.chainId,s.address,s.chainId)||!Q?!1:h.addressesEqual(Q,s.address),[n,s.address,s.chainId,Q]),U=Q?h.addressesEqual(Q,s.address):!1,G=t==="output"&&parseFloat(l||"0")===0,pe=!!n?.asset&&!ee&&!U&&!G,q=pe?R??Q:Q;return i.useEffect(()=>{S.current&&clearTimeout(S.current);const J=t==="input"?n?.amount:l,le=parseFloat(J||"0");if(!pe||!Number.isFinite(le)||le<=0||!n?.asset||!a||H.length===0){I.current++,g(null),y(null),k(null),M(null),w(null),j(null),p(null),c(!1);return}const be=n.asset.decimals;let ie;try{ie=t==="input"?T.parseUnits(n.amount,be):T.parseUnits(l||"0",s.decimals)}catch{I.current++,p("Invalid amount"),c(!1);return}const fe=++I.current,ce=()=>fe!==I.current;c(!0);const ke=t==="output"?150:400;return S.current=setTimeout(async()=>{try{if(t==="input"){const te=W.getVenueForChain(r);if(!te)throw new Error("No swap venue for this chain");let Y=null,_=null;for(const ge of H){const K=`${t}:${r}:${ge.toLowerCase()}:${s.address.toLowerCase()}:${ie.toString()}`,ne=A.current.get(K);if(ne&&ne.expiresAt>Date.now()&&ne.resolvedSwap){Y=ne.resolvedSwap,_=ge;break}const he=await te.resolve({type:"swap",tokenIn:ge,tokenOut:s.address,amountIn:ie},r,a);if(ce())return;if(he){A.current.set(K,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:he}),Y=he,_=ge;break}}if(!Y||!_)throw new Error("No liquidity for this pair");j(_),w(Y.amountOut),k(Y),M(null);const re=parseFloat(T.formatUnits(Y.amountOut,s.decimals));g(re<.01?re.toPrecision(4):re.toLocaleString(void 0,{maximumFractionDigits:6})),y(null),p(null)}else{let te=null,Y=null;for(const _ of H){const re=`${t}:${r}:${_.toLowerCase()}:${s.address.toLowerCase()}:${ie.toString()}`,ge=A.current.get(re);if(ge&&ge.expiresAt>Date.now()&&ge.exactOutputSwap){te=ge.exactOutputSwap,Y=_;break}try{const K=await O.getQuote({tokenIn:_,tokenOut:s.address,amountOut:ie},r,a);if(ce())return;A.current.set(re,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:K}),te=K,Y=_;break}catch{if(ce())return}}if(!te||!Y)throw new Error("No liquidity for this pair");j(Y),M(te),k(null),w(null),y(parseFloat(T.formatUnits(te.amountIn,be)).toFixed(6)),g(null),p(null)}}catch(te){if(ce())return;const Y=te instanceof Error?te.message:"Failed to get quote";p(Y),g(null),y(null),k(null),M(null),w(null),j(null)}finally{ce()||c(!1)}},ke),()=>{S.current&&clearTimeout(S.current)}},[t,pe,n?.amount,n?.asset?.address,n?.asset?.decimals,l,H,r,s.address,s.decimals,a,W,O]),{isQuoting:u,quoteError:f,estimatedOutput:x,estimatedInput:m,resolvedSwap:C,exactOutputSwap:v,quoteAmountOut:b,resolvedTokenIn:q,isDirect:U,needsSwap:pe,selectedIsEquivalent:ee}}const qr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Yr=["signing-delegation","signing-intent","submitting","executing"],Jl=()=>{},$l=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:s,sourceChains:r,supportedSourceAssets:a,buildActionCalls:l,feeExecutionMode:d="user-transfer",buildSpicenetBatch:u,onPayExecute:c,resolveExactOutputSwap:f,actionLabel:p,amountDirection:x="input",swapDescription:g,directDescription:m,paymentAmount:y,amountInputMode:C="fixed",minPaymentAmount:k,maxPaymentAmount:v,onAmountChange:M,styles:b,dark:w,title:R,subtitle:j,onAddFunds:N,onSuccess:B,onError:S})=>{const E=x==="output",{theme:I,dark:A,primaryColor:W,dk:O,palette:z,fontFamily:P,monoFont:D,inputDark:Q,cardBg:H,cardBorder:ee,textPrimary:U,textSecondary:G,subtitleText:pe}=h.useSpiceBrand(b,w),q=i.useMemo(()=>Q?{...I,colors:{...I.colors,secondary:O.cardBg,surfaceHover:O.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:I,[Q,I,O.cardBg,O.hoverBg]),J=s.chainId,le=i.useContext(h.SpiceFlowProviderContext),be=le?.mode||"7702",ie=be!=="7702",fe=!!le?.isWhitelistGateActive,ce=!!le?.isWhitelistConfigured&&le?.isUserWhitelisted!==!0,ke=i.useMemo(()=>r??le?.supportedChainIds??[],[r,le?.supportedChainIds]),te=i.useMemo(()=>{if(fe)return[];if(a)return a;const me=le?.allowedTokens;if(!me||me.length===0)return;const $e=new Set(me.map(gn=>gn.toLowerCase())),dn=[],mn=new Set;for(const gn of ke){const hs=h.getChainConfig(gn);for(const ms of hs?.supportedTokens??[]){if(!$e.has(ms.symbol.toLowerCase()))continue;const to=ms.address.toLowerCase();mn.has(to)||(mn.add(to),dn.push(ms.address))}}return dn},[a,le?.allowedTokens,ke,fe]),Y=h.useWallet(),{address:_,isConnected:re,isReady:ge,isAuthenticated:K,provider:ne}=Y,{execute:he,estimate:oe}=Mn(),{externalWallet:Be,embeddedAddress:it,activeWallet:St,activeAddress:It}=h.useProviderWallets(),lt=le?.externalWalletAddress,ue=le?.embeddedWalletAddress||it,{displayAssets:At,filteredSpiceAssets:Te,embeddedWalletAddress:We,refreshSpiceAssets:_e,refreshWalletAssets:wt}=Br({destinationToken:s,supportedSourceAssets:te,sourceChains:ke,enabled:e&&(ie?!!lt:!!ue)}),Ze=fe||E||ie?At:Te;i.useEffect(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:be,walletAddressUsed:We,count:Ze.length,assets:Ze.map(me=>({symbol:me.symbol,address:me.address,chainId:me.chainId,balanceFormatted:me.balanceFormatted,source:me?._source}))})},[e,be,We,Ze]);const[L,Re]=i.useState(null),[Ie,Qe]=i.useState(y||""),[ze,Rt]=i.useState(!1),[Nt,zt]=i.useState(null),[ve,Dt]=i.useState("idle"),[Xe,tn]=i.useState(""),[Zt,Ve]=i.useState(null),[Lt,Et]=i.useState(!1),[Ue,ye]=i.useState(null),[Oe,Ke]=i.useState(null),[Xt,we]=i.useState(!1),[Mt,yt]=i.useState(!1),[pt,qe]=i.useState(null),nn=i.useRef(L),jt=i.useRef(!1),Ht=i.useRef(null),Gt=i.useRef(null),Ft=i.useRef(0),gt=i.useRef(null),ct=i.useRef(null);i.useEffect(()=>{nn.current=L},[L]);const Me=C==="adjustable"?Ie:y||"0",et=We||it||_,{isQuoting:ft,quoteError:Qt,estimatedOutput:Wt,resolvedSwap:ht,exactOutputSwap:Se,quoteAmountOut:Ct,resolvedTokenIn:ot,isDirect:bt,needsSwap:tt,selectedIsEquivalent:Ae}=Vr({direction:x,selectedAsset:L,destinationToken:s,chainId:J,recipient:et,paymentAmount:Me,resolveExactOutputSwap:f}),nt=E?parseFloat(Me||"0"):parseFloat(L?.amount||"")||0,Pt=nt>0&&nt<fn,$=L?.asset?._source==="wallet",se=!!L?.asset&&$&&L.asset.chainId!==J,Ce=i.useMemo(()=>L?.asset?Te.find(me=>h.addressesEqual(me.address,L.asset.address))?.balanceFormatted??0:0,[L,Te]),Ne=$?L?.asset.balanceFormatted??0:Ce,Ye=i.useMemo(()=>{if(!L?.asset)return!1;if(E)return Oe?ln(Oe.grossAmount,Oe.decimals,L.asset.decimals)>L.asset.balance:Ae||bt?nt>L.asset.balanceFormatted:Se?parseFloat(T.formatUnits(Se.amountInMax,L.asset.decimals))>L.asset.balanceFormatted:!1;if(Oe){const me=ln(Oe.grossAmount,Oe.decimals,L.asset.decimals);return $?me>L.asset.balance:parseFloat(T.formatUnits(me,L.asset.decimals))>Ne}return nt>Ne},[L,E,Oe,Ae,nt,Se,Ne,$,bt]);i.useEffect(()=>{e||(Re(null),zt(null),Rt(!1),Dt("idle"),tn(""),Ve(null),Et(!1),ye(null),Ke(null),we(!1),yt(!1),qe(null),jt.current=!1,C==="adjustable"&&Qe(y||""),Ht.current&&(Ht.current.abort(),Ht.current=null))},[e]);const rt=i.useCallback(me=>{Re($e=>({asset:me,amount:$e?.asset?.address===me.address&&$e?.asset?.chainId===me.chainId&&$e.amount||""})),zt(null),qe(null),yt(!1)},[]),dt=i.useCallback(me=>{Re($e=>$e&&{...$e,amount:me}),zt(null),qe(null),yt(!1)},[]),at=i.useCallback(me=>{let $e=me;v&&parseFloat($e)>parseFloat(v)&&($e=v),Qe($e),M?.($e),zt(null),qe(null),yt(!1)},[v,M]);i.useCallback(me=>{if(jt.current||!_)return;const $e=nn.current;!$e?.asset||!$e.amount||$e.asset?._source==="wallet"||T.parseUnits(E?Me:$e.amount,$e.asset.decimals)===0n||(jt.current=!0,_e())},[_,J,_e,E,Me]);const Ee=i.useCallback(me=>{Dt({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[me.step]||"executing"),tn(me.message),me.txHash&&Ve(me.txHash)},[]),xt=i.useMemo(()=>({currentPaymentAmount:Me,destinationToken:s,embeddedWalletAddress:We,providerEmbeddedAddress:it,externalWalletAddress:lt,address:_,isNon7702:ie,isPayMode:E,resolvedChainId:J,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:L,needsSwap:tt,resolvedSwap:ht,exactOutputSwap:Se,quoteAmountOut:Ct,resolvedTokenIn:ot}),[Me,s,We,it,lt,_,ie,E,J,l,d,u,L,tt,ht,Se,Ct,ot]),De=i.useCallback(me=>hr({...xt,requestTimestampMs:Gt.current??Date.now()},me),[xt]),Z=i.useCallback(me=>mr({...xt,requestTimestampMs:Gt.current??Date.now()},me),[xt]),xe=i.useCallback((me,$e,dn,mn)=>gr(me,$e,dn,oe,mn),[oe]),ut=i.useMemo(()=>L?.asset?tt&&ot?ot:L.asset.chainId===J?L.asset.address:ot??rn(L.asset,J)??s.address:s.address,[L,s.address,tt,J,ot]),mt=i.useCallback(()=>(Gt.current=Date.now(),kr(ct.current)),[]),Le=i.useMemo(()=>L?.asset?h.addressesEqual(L.asset.address,s.address)&&L.asset.chainId===s.chainId:!1,[L,s.address,s.chainId]),kt=Le&&(ie||E),Ge=kt&&nt>0&&!!L?.asset,Vt=ce&&!kt,V=i.useMemo(()=>{if(!Ge)return null;let me;try{me=T.parseUnits(Me||"0",s.decimals)}catch{return null}return{symbol:s.symbol,decimals:s.decimals,grossAmount:me,netAmount:me,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[Ge,Me,s.symbol,s.decimals]),X=Nt,de=i.useMemo(()=>!(!L?.asset||nt<=0),[L,nt,Ge]),ae=i.useMemo(()=>!e||ze||ve!=="idle"||!de||Ge||!L?.asset?null:[E?"pay":"supply",x,L.asset.address.toLowerCase(),L.asset.chainId,L.amount,Me,s.address.toLowerCase(),s.chainId,J,ot?.toLowerCase()??"",tt?"swap":"direct",bt?"direct-token":"routed-token",ie?"non7702":"7702",Le?"source-dest":"cross-chain",ft?"quoting":"quoted",Se?.amountIn?.toString()??"",Se?.amountInMax?.toString()??"",Se?.venue??"",ht?.amountOut?.toString()??"",Ct?.toString()??"",We??"",it??"",_??""].join("|"),[e,ze,ve,de,Ge,L,E,x,Me,s,J,ot,tt,bt,ie,Le,ft,Se,ht,Ct,We,it,_]),Pe=i.useCallback(()=>yr({selectedAsset:L,isPayMode:E,parsedAmount:nt,needsSwap:tt,exactOutputSwap:Se,isNon7702:ie,isSourceDestToken:Le,currentPaymentAmount:Me,destinationToken:s,feeExecutionMode:d,resolvedTokenIn:ot,embeddedWalletAddress:We,providerEmbeddedAddress:it,resolvedChainId:J,isConnected:re,address:_,ready:ge,authenticated:K,isDirect:bt,resolvedSwap:ht,isQuoting:ft,executionTokenAddress:ut,buildPayChainBatches:De,buildSupplyChainBatches:Z,estimate:oe,estimateRequiredGrossFunding:xe}),[L,E,nt,tt,Se,ie,Le,Me,s,d,ot,We,it,xe,De,oe,J,re,_,ge,K,bt,ht,ft,Z,ut]);i.useEffect(()=>{gt.current=Pe},[Pe]);const je=i.useCallback(me=>xr({asset:me,isPayMode:E,isNon7702:ie,needsSwap:tt,isQuoting:ft,embeddedWalletAddress:We,buildSupplyChainBatches:Z,estimate:oe,executionTokenAddress:ut,feeExecutionMode:d}),[E,ie,tt,ft,We,Z,oe,ut,d]);i.useEffect(()=>{if(!e){we(!1),yt(!1),qe(null),Ke(null);return}if(ze||ve!=="idle"){Ft.current+=1,we(!1);return}if(!de){Ke(null),we(!1),yt(!1),qe(null);return}if(Ge){Ke(V),we(!1),yt(!0),qe(null);return}if(ft){Ft.current+=1,we(!1),yt(!1);return}if(!ae)return;let me=!1;const $e=async()=>{const mn=++Ft.current;qe(null),we(!0);try{const gn=await gt.current?.();if(me||Ft.current!==mn)return;gn?(Ke(gn),yt(!0)):(Ke(null),yt(!1)),qe(null)}catch(gn){if(me||Ft.current!==mn)return;const hs=h.sanitizeError(gn,"Unable to calculate fees for this action.");Ke(null),yt(!1),qe(hs)}finally{!me&&Ft.current===mn&&we(!1)}},dn=window.setTimeout(()=>{$e()},250);return()=>{me=!0,clearTimeout(dn),we(!1)}},[e,ze,ve,de,Ge,V,ft,ae]);const He=i.useCallback(()=>(Gt.current=Date.now(),Ir(ct.current)),[]);i.useEffect(()=>{!E&&ve==="success"&&Zt&&(_e(),B?.(Zt))},[E,ve,Zt,_e,B]),i.useEffect(()=>{if(!E||Ue?.status!=="success"||jt.current||!_)return;jt.current=!0;const me=nn.current;!me?.asset||me.asset?._source==="wallet"||_e()},[E,Ue?.status,_,_e]);const st=i.useRef(B),vt=i.useRef(S);i.useEffect(()=>{st.current=B},[B]),i.useEffect(()=>{vt.current=S},[S]),i.useEffect(()=>{e&&(_e(),wt())},[e,_e,wt]),i.useEffect(()=>{E&&(Ue?.status==="success"&&st.current?.(Ue.txHash||""),Ue?.status==="failed"&&vt.current?.(new Error("Payment execution failed")))},[E,Ue?.status]);const Ut=i.useCallback(()=>{Et(!1),ye(null),Re(null),jt.current=!1,_e(),wt()},[_e,wt]);ct.current={selectedAsset:L,parsedAmount:nt,currentPaymentAmount:Me,isInsufficientBalance:Ye,isPayMode:E,isNon7702:ie,isSourceDestToken:Le,needsSwap:tt,exactOutputSwap:Se,selectedIsEquivalent:Ae,resolvedTokenIn:ot,embeddedWalletAddress:We,providerEmbeddedAddress:it,externalWallet:Be,externalWalletAddress:lt,activeSignerWallet:St,activeSignerAddress:It,address:_,isConnected:re,ready:ge,authenticated:K,provider:ne,resolvedChainId:J,executionTokenAddress:ut,destinationToken:s,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:c,onSuccess:B,onError:S,execution:{estimate:oe,execute:he,buildPayChainBatches:De,buildSupplyChainBatches:Z,estimateRequiredGrossFunding:xe,onProgress:Ee},ui:{setError:zt,setStep:Dt,setStatusMsg:tn,setTxHash:Ve,setIsExecuting:Rt,setShowStatusPanel:Et,setPaymentResult:ye},refs:{spiceDepositSubmittedRef:jt,abortControllerRef:Ht}};const Jt=y?.trim(),Tt=E&&C==="fixed"&&Jt!==void 0&&Jt!==""&&nt===0,$t=E?(Tt||!!L?.asset)&&nt>=0&&!Pt&&!Ye&&!ze&&(Tt||Ge||Mt)&&!pt&&(Tt||!tt||!!Se)&&!Vt:!!L?.asset&&nt>0&&!Pt&&!Ye&&!ze&&(kt||Mt)&&!pt&&(se||bt||!!ht&&!ft)&&!Vt;i.useEffect(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:$t,isPayMode:E,hasSelectedAsset:!!L?.asset,selectedAsset:L?.asset?{symbol:L.asset.symbol,address:L.asset.address,chainId:L.asset.chainId,balanceFormatted:L.asset.balanceFormatted,source:L.asset?._source}:null,parsedAmount:nt,isZeroAmountPay:Tt,isBelowMinimum:Pt,isInsufficientBalance:Ye,isExecuting:ze,directExternalAction:kt,directExecutionFeeNote:Ge,feeEstimateReady:Mt,feeEstimateError:pt,needsSwap:tt,isDirect:bt,isSourceDestToken:Le,hasExactOutputSwap:!!Se,isQuoting:ft,whitelistHoldPending:ce,supplyHeldForWhitelist:Vt,isWhitelistGateActive:fe,destinationToken:{symbol:s.symbol,address:s.address,chainId:s.chainId}})},[e,$t,E,L,nt,Tt,Pt,Ye,ze,kt,Ge,Mt,pt,tt,bt,Le,Se,ft,ce,Vt,fe,s]);const kn=bt?m||`Your ${s.symbol} will be used directly.`:g||"Your assets will be swapped and used in a single atomic transaction.",jn=(J?h.getChainConfig(J):void 0)?.viemChain?.blockExplorers?.default?.url??"",vn=Yr.indexOf(ve),Fe=ze?(qr[ve]||"EXECUTING...").toUpperCase():ve==="success"?"DONE":Pt?`MINIMUM ${fn}`:Ye?"INSUFFICIENT BALANCE":p.toUpperCase(),Je=i.useMemo(()=>{if(ze)return"PAYING...";if(Pt)return`MINIMUM ${fn}`;if(Ye&&L?.asset)return`INSUFFICIENT ${L.asset.symbol}`;if(p)return p.toUpperCase();const me=nt>0?` ${Me} ${s.symbol}`:"";return tt?`SWAP & PAY${me}`:`PAY${me}`},[ze,Pt,Ye,L,p,nt,Me,s.symbol,tt]),Ot=ve==="success"?()=>{Dt("idle"),Re(null),Ve(null),_e()}:mt,cn=ve==="success"?!1:!$t;if(!e)return null;const Yn=E?R||`Pay ${s.symbol}`:p,Pn=E?j:o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[o.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:o.jsx(Ns,{color:pe})}),o.jsx("p",{style:{fontSize:"12px",color:pe,margin:0,lineHeight:"1.4",fontFamily:P},children:kn})]});if(E){const me=Ue&&(Ue.status==="success"||Ue.status==="failed")?[{asset:{symbol:L?.asset?.symbol||s.symbol,address:L?.asset?.address||""},amount:Me,txHash:Ue.txHash||"",success:Ue.status==="success",error:Ue.status==="failed"?Ue.error:void 0}]:void 0;return o.jsx(un,{isOpen:e,onClose:t,title:Yn,subtitle:Pn,styles:b,dark:A,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[N&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:o.jsx(Ds,{onClick:N,color:W,fontFamily:P})}),!Tt&&o.jsx("div",{style:{marginBottom:"12px"},children:o.jsx(Ln,{assets:Ze,selectedAsset:L??void 0,onAssetSelect:rt,onAmountChange:Jl,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:L?.asset?tt?ft?"...":Se?`~${parseFloat(T.formatUnits(Se.amountIn,L.asset.decimals)).toFixed(6)}`:void 0:Me??void 0:void 0,dark:A,theme:q,styles:b})}),o.jsx(Ar,{variant:"pay",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:W,fontFamily:P,textPrimary:U,textSecondary:G,cardBg:H,cardBorder:ee,dk:O,dark:A,isQuoting:ft,quoteError:Qt,estimatedOutput:Wt,paymentAmount:Me,needsSwap:tt,exactOutputSwap:Se,adjustable:C==="adjustable",maxAmount:v,onAmountChange:at}),de&&o.jsx(as,{fontFamily:P,textPrimary:U,textSecondary:G,cardBg:H,cardBorder:ee,resolvedDark:A,darkCardBorder:O.cardBorder,primaryColor:W,feePreview:Oe,isLoading:Xt,errorText:pt,directExecutionFeeNote:Ge}),X&&o.jsx(Nn,{variant:"error",palette:z,fontFamily:P,style:{marginBottom:"12px"},children:X}),o.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:He,disabled:!$t,loading:ze,dark:A,styles:{...b,button:{...b?.button,backgroundColor:W}},children:Je}),Ue&&Lt&&o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:A?O.shell:"white",borderRadius:A?"12px":"6px",padding:"16px 0"},children:o.jsx(zs,{type:"payment",isOpen:Ue.status!=="processing",isProcessing:ze||Ue.status==="processing",closeOnComplete:!1,chainName:h.getChainName(J),explorerUrl:h.getExplorerUrl(J,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Et(!1),ye(null),He()},onNewTx:Ut,onClose:()=>{Et(!1),ye(null)},onComplete:Ut,results:me,styles:b,dark:A})})]})})}return o.jsx(un,{isOpen:e,onClose:t,title:Yn,subtitle:Pn,dark:A,styles:b,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(Ln,{assets:Ze,selectedAsset:L||void 0,onAssetSelect:rt,onAmountChange:dt,disabled:ze||ve==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:q,styles:b,dark:Q,resolveMaxAmount:je,maxAmount:Ne>0?h.formatDecimalInput(Ne,L?.asset.decimals??s.decimals):void 0})}),L?.asset&&!bt&&o.jsx(Ar,{variant:"supply",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:W,fontFamily:P,textPrimary:U,textSecondary:G,cardBg:H,cardBorder:ee,dark:A,isQuoting:ft,quoteError:Qt,estimatedOutput:Wt}),de&&o.jsx(as,{fontFamily:P,textPrimary:U,textSecondary:G,cardBg:H,cardBorder:ee,resolvedDark:A,darkCardBorder:O.cardBorder,primaryColor:W,feePreview:Oe,isLoading:Xt,errorText:pt,directExecutionFeeNote:Ge}),ve!=="idle"&&o.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:ve==="success"?H:ve==="error"?z.errorBg:H,border:`1px solid ${ve==="success"?ee:ve==="error"?z.errorBorder:ee}`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ve==="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:z.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):ve==="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:z.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):o.jsx(h.Spinner,{size:14,color:W}),o.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:ve==="success"?U:ve==="error"?z.errorText:U,fontFamily:P,flex:1},children:ve==="success"?"Deposit confirmed":ve==="error"?Xe||"Transaction failed":qr[ve]||Xe}),ve==="success"&&Zt&&o.jsx("a",{href:`${jn}/tx/${Zt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:W,fontFamily:P,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),ve==="error"&&o.jsx("button",{onClick:()=>{Dt("idle"),zt(null),setTimeout(mt,50)},style:{background:"none",border:"none",fontSize:"12px",color:W,fontFamily:P,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),vn>=0&&ve!=="success"&&ve!=="error"&&o.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${G}22`,overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:W,transformOrigin:"left center",transform:`scaleX(${(vn+1)/Yr.length})`,transition:"transform 400ms ease"}})})]}),Nt&&ve==="idle"&&o.jsx(Nn,{variant:"error",palette:z,fontFamily:P,style:{marginBottom:"16px"},children:Nt}),o.jsx(h.Button,{variant:"outline",fullWidth:!0,disabled:cn,onClick:Ot,theme:I,dark:A,styles:{...b,button:{...b?.button,backgroundColor:W}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:D},children:Fe})]})})},_l=()=>{const[e,t]=i.useState("0"),[n,s]=i.useState(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:n,setSelectedAsset:s}};function ec(e,t=0){const[n,s]=i.useState(t),r=e[n]??e[0],a=i.useMemo(()=>r?BigInt(Math.round(r.months*30*24*3600)):0n,[r?.months]);return{selectedDurationIdx:n,setSelectedDurationIdx:s,selectedDuration:r,durationSeconds:a}}function tc(){const{actions:e,isReady:t,isAuthenticated:n}=h.useWallet(),s=i.useContext(h.SpiceFlowProviderContext)?.embeddedWalletAddress,r=i.useRef(!1),a=i.useRef(0),l=i.useRef(null),d=i.useRef(e),[u,c]=i.useState(0);d.current=e,i.useEffect(()=>{r.current=!1,a.current=0,l.current&&(clearTimeout(l.current),l.current=null)},[s]),i.useEffect(()=>{if(!s||!t||!n||r.current)return;r.current=!0;let f=!1;return(async()=>{await en(2e3);try{await h.ensureSmartWallet(s,d.current.signMessage),a.current=0}catch(p){console.warn("[SmartWallet] Registration failed:",p),r.current=!1,!f&&a.current<3&&(a.current+=1,l.current=setTimeout(()=>{c(x=>x+1)},5e3))}})(),()=>{f=!0,l.current&&(clearTimeout(l.current),l.current=null)}},[s,t,n,u])}function qn(e){try{return F.resolveTokenRef(e)}catch{throw new h.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Token "${e[0]}" not found on chain ${e[1]} in the token registry.`,{symbol:e[0],chainId:e[1]})}}function nc(e,t){if(e[0].toUpperCase()===t[0].toUpperCase()&&e[1]===t[1])return!0;let n,s;try{n=qn(e),s=qn(t)}catch{return!1}const r=new Set(F.getEquivalentAddresses(s.address).map(a=>a.toLowerCase()));return r.add(s.address.toLowerCase()),r.has(n.address.toLowerCase())}function sc(){const e=[];for(const t of Object.keys(F.CHAINS).map(Number))for(const n of F.getTokensForChain(t))e.push([n.symbol,t]);return e}async function oc(e){const{action:t,inputToken:n,inputAmount:s,registry:r,userAddress:a,slippage:l,intermediaryCandidates:d}=e;if(t.calls.length===0)throw new h.SpiceflowError("INVALID_PARAMS","buildIntent: action.calls must not be empty.",{action:t});if(s<=0n)throw new h.SpiceflowError("INVALID_PARAMS","buildIntent: inputAmount must be greater than zero.",{inputAmount:s.toString()});const u=t.supportedInputTokens??sc();if(!u.some(C=>nc(n,C))){const C=u.map(([k,v])=>`${k} (chain ${v})`).join(", ");throw new h.SpiceflowError("ROUTE_UNSUPPORTED_INPUT",`Input token "${n[0]}" on chain ${n[1]} is not in the action's supported input tokens. Supported: ${C}.`,{inputToken:{symbol:n[0],chainId:n[1]},supportedInputTokens:u})}const c=qn(n),f=qn(t.outputToken),p=$o({sourceAsset:c,outputAsset:f,sourceChainId:c.chainId,destinationChainId:t.chainId,intermediaryCandidates:d}),{chainBatches:x,solverFrontToken:g,solverFrontAmount:m,resolvedSwaps:y}=await _o({route:p,sourceAmount:s,userAddress:a,registry:r,actionCalls:t.calls,slippage:l});return{chainBatches:x,route:p,resolvedSwaps:y,resolvedInputToken:c,resolvedOutputToken:f,solverFrontToken:g,solverFrontAmount:m}}const rc=[0n,1n,30n],ac=new Set(["ABORT","CONCURRENT_EXECUTION","WALLET_DISCONNECTED","WALLET_REJECTED","NO_VENUE_FOR_CHAIN"]);function Kr(e,t){return t===0n?e:e*(1000n-t)/1000n}async function ic(e,t){const{chainId:n,swapCalls:s,quoteAmountOut:r,buildActionCalls:a,tokenAddress:l,tokenTransferAmount:d,onProgress:u,signal:c,options:f,buffers:p=rc}=t;for(let x=0;x<p.length;x++){const g=p[x],m=Kr(r,g),y=a(m),C=[{chainId:n,calls:[...s,...y]}];try{return await e(C,l,d,u,c,f)}catch(k){const v=typeof k?.message=="string"?k.message:String(k?.message??"");if(h.isSpiceflowError(k)&&ac.has(k.code)||k.name==="AbortError"||c?.aborted||v.includes("User rejected")||v.includes("User denied")||k.code===4001||x>=p.length-1)throw k;const M=Number(p[x+1])/10;console.warn(`[SwapThenAction] Action attempt ${x+1} failed (buffer ${Number(g)/10}%), retrying with ${M}% buffer...`,k.message),u?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${M}% buffer)...`})}}throw new h.SpiceflowError("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:p.length,chainId:n})}ra(),exports.SpiceFlowProvider=h.SpiceFlowProvider,exports.SpiceFlowProviderContext=h.SpiceFlowProviderContext,exports.SpiceflowError=h.SpiceflowError,exports.Spinner=h.Spinner,exports.buildDarkPalette=h.buildDarkPalette,exports.buildLightPalette=h.buildLightPalette,exports.getChainConfig=h.getChainConfig,exports.getChainName=h.getChainName,exports.isSpiceflowError=h.isSpiceflowError,exports.relayerService=h.relayerService,exports.resolveTheme=h.resolveTheme,exports.useIsUserWhitelisted=h.useIsUserWhitelisted,exports.useSpiceBrand=h.useSpiceBrand,exports.useWallet=h.useWallet,Object.defineProperty(exports,"NATIVE_TOKEN_ADDRESS",{enumerable:!0,get:function(){return F.ZERO_ADDRESS}}),Object.defineProperty(exports,"SPICENET_NATIVE_CHAIN_ID",{enumerable:!0,get:function(){return F.SPICENET_NATIVE_CHAIN_ID}}),Object.defineProperty(exports,"SPICE_COMBINED_FEE_RECIPIENT",{enumerable:!0,get:function(){return F.SPICE_COMBINED_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_GAS_FEE_RECIPIENT",{enumerable:!0,get:function(){return F.SPICE_GAS_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_PLATFORM_FEE_RECIPIENT",{enumerable:!0,get:function(){return F.SPICE_PLATFORM_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_SOLVER_ADDRESS",{enumerable:!0,get:function(){return F.SPICE_SOLVER_ADDRESS}}),Object.defineProperty(exports,"applySlippage",{enumerable:!0,get:function(){return F.applySlippage}}),Object.defineProperty(exports,"buildUniV3SwapCalls",{enumerable:!0,get:function(){return F.buildUniV3SwapCalls}}),Object.defineProperty(exports,"getChainIdsByNetwork",{enumerable:!0,get:function(){return F.getChainIdsByNetwork}}),Object.defineProperty(exports,"getEscrowContractAddress",{enumerable:!0,get:function(){return F.getEscrowContractAddress}}),Object.defineProperty(exports,"isNativeToken",{enumerable:!0,get:function(){return F.isNativeToken}}),Object.defineProperty(exports,"isSpicenetChainId",{enumerable:!0,get:function(){return F.isSpicenetChainId}}),Object.defineProperty(exports,"normalizeNativeTokenAddress",{enumerable:!0,get:function(){return F.normalizeNativeTokenAddress}}),Object.defineProperty(exports,"spicenetAbi",{enumerable:!0,get:function(){return F.spicenetAbi}}),Object.defineProperty(exports,"spicenetWithdrawalAbi",{enumerable:!0,get:function(){return F.spicenetAbi}}),exports.AccountDisplay=Ul,exports.AddFundsLink=Ds,exports.CheckIcon=Do,exports.ChevronIcon=bn,exports.CloseIcon=Tn,exports.DetailRow=Dn,exports.ProviderLogin=Os,exports.SATSUMA_CITREA_CONFIG=eo,exports.SearchInput=Cs,exports.SelectChainModal=Ui,exports.SpiceDeposit=Pi,exports.SpiceLock=ar,exports.SpiceLockModal=ar,exports.SpiceSupply=$l,exports.SpiceWithdraw=el,exports.StatusBanner=Nn,exports.UNIV3_BASE_CONFIG=Ur,exports.applyBuffer=Kr,exports.areEquivalentOnChains=Hn,exports.buildIntent=oc,exports.buildPayChainBatches=hr,exports.buildRoutedBatches=_o,exports.buildSupplyChainBatches=mr,exports.create1inchVenue=Wr,exports.createExactOutputRegistry=Hr,exports.createLiquidityRegistry=Lr,exports.createSatsumaVenue=Or,exports.duration=Yt,exports.easing=Bt,exports.estimateFeePreview=yr,exports.estimateRequiredGrossFunding=gr,exports.estimateSupplyMaxAmount=xr,exports.executeDirectExternalAction=$s,exports.executeNon7702Pay=Sr,exports.executeNon7702Supply=vr,exports.executePay=Ir,exports.executeSupply=kr,exports.executeSwapThenAction=ic,exports.findEquivalentOnChain=hn,exports.findTokenOnChain=Qs,exports.font=oo,exports.getAssetChainTokenCandidates=Xn,exports.getBestUniV3Quote=Mr,exports.getUniV3Quote=Rr,exports.isSupportedSupplyAsset=Fr,exports.isSwapIntent=Nr,exports.radius=ys,exports.resolveAssetTokenAddressOnChain=rn,exports.resolveFundedToken=wo,exports.resolveInputSupplySwapQuote=Gl,exports.resolveRoute=$o,exports.resolveTokenRef=qn,exports.scaleTokenAmount=ln,exports.transition=_t,exports.useAssetInput=_l,exports.useLockDuration=ec,exports.useSmartWallet=tc,exports.useSpiceAssets=Qn,exports.useSpiceExecution=Mn,exports.useSpicePendingDeposits=ir,exports.useSupplyAssets=Br,exports.useSupplyQuote=Vr,exports.z=Sn;
108
+ `})]}),document.body):null;return o.jsxs(o.Fragment,{children:[wt,Ze,j&&Un.createPortal(o.jsx(zo,{isOpen:!0,onClose:Y,supportedChains:[j.chainId],escrowOnly:!0,escrowTokenAddress:j.tokenAddress,escrowAmount:j.amount,escrowTokenDecimals:j.tokenDecimals,escrowTokenSymbol:j.tokenSymbol,styles:u,onDepositSuccess:_}),document.body)]})},Ol="0xa9059cbb";function dr(e,t,n){return F.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[n,t]})}}function ur(e,t,n){return{chainId:n,calls:[dr(e,t,F.getEscrowContractAddress(n))]}}function pr(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function fr(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith(Ol)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function ps(e,t,n,s){if(!t)return[e];const r=await t({...n,requestTimestampMs:s});return r?[r,e]:[e]}function Xs(e){return e.filter(t=>t.domain!=="spicenet")}function fs(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:F.normalizeNativeTokenAddress(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function ln(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const s=10n**BigInt(t-n);return(e+s-1n)/s}async function hr(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:l,isNon7702:d,isPayMode:u,resolvedChainId:c,buildActionCalls:f,feeExecutionMode:p,buildSpicenetBatch:x,selectedAsset:g,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:C,requestTimestampMs:k}=e,v=T.parseUnits(n,s.decimals),M=t?.actionAmountOverride??v,b=r||a||(d?void 0:l);if(!b)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:b,chainId:c,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??v,netAmount:M,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},R=f(M,w),j={chainId:c,calls:R},N=!u&&!d?!0:g?.asset?._source==="spice",B=pr(g??null,d,c),S=N||d||B,E=(A,W)=>({token:A,from:"escrow",to:b,amount:W}),I=(A,W,O)=>B?[ur(A,W,c),...O]:O;if(v===0n)return[j];if(m&&y){const A=C??rn(g.asset,c)??g.asset.address,W=t?.fundingAmountOverride??y.amountInMax,O=S?[E(A,W)]:[],z={to:A,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},P={chainId:c,calls:[z,...y.calls,...R],tokenTransfers:[...O,...j.tokenTransfers??[]]};if(!S)return[P];const D=await ps(P,x,{userAddress:b,destinationChainId:c,deliveryToken:A,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:fs(P),sourceAsset:g.asset},k);return I(A,W,D)}if(S){const A=C??rn(g.asset,c)??s.address;if(B&&A.toLowerCase()===s.address.toLowerCase())return[j];const W=t?.fundingAmountOverride??v,O={...j,tokenTransfers:[E(A,W),...j.tokenTransfers??[]]},z=await ps(O,x,{userAddress:b,destinationChainId:c,deliveryToken:A,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:fs(O),sourceAsset:g.asset},k);return I(A,W,z)}return[j]}async function mr(e,t){const{selectedAsset:n,embeddedWalletAddress:s,externalWalletAddress:r,recipient:a,resolvedChainId:l,destinationToken:d,buildActionCalls:u,feeExecutionMode:c,buildSpicenetBatch:f,isPayMode:p,isNon7702:x,needsSwap:g,resolvedSwap:m,quoteAmountOut:y,resolvedTokenIn:C,requestTimestampMs:k}=e,v=m?.amountOutMinimum??y;if(!n?.asset||!s)return[];const M=a??(x?r:s);if(!M)return[];const b=t?.fundingAmountOverride??t?.actionAmountOverride??T.parseUnits(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??b,R=t?.sourceFundingAmountOverride??b,j=t?.deliveryAmountOverride??w,N=t?.withdrawalAmountOverride??j,B=t?.actionAmountOverride??b,S={userAddress:M,chainId:l,destinationToken:d.address,feeToken:c==="user-transfer"&&g&&C?C:d.address,grossAmount:w,netAmount:B,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},E=u(B,S),I=n.asset?._source==="wallet";if(!p&&x&&I&&n.asset.chainId===l){if(g){if(!C)throw new Error("Swap input token could not be resolved");if(!m||v===null)throw new Error("Swap quote not available yet")}if(g&&m&&v){const U=u(t?.actionAmountOverride??v,{...S,netAmount:t?.actionAmountOverride??v}),{feeCall:G,remainingCalls:pe}=fr(U,c,g,S.feeToken);return[{chainId:l,calls:[...G?[G]:[],...m.calls,...pe]}]}return[{chainId:l,calls:E}]}if(!p&&!x&&I&&n.asset.chainId!==l)throw new Error("Cross-chain wallet supplies require external wallet mode");const A=!p&&!x?n.asset?._source!=="wallet":n.asset?._source==="spice",W=x&&I,O=pr(n,x,l);if(!(A||W||O))return[{chainId:l,calls:E}];const z=O?ur(C??F.normalizeNativeTokenAddress(n.asset.address),R,l):W&&n.asset.chainId!==l?{chainId:n.asset.chainId,calls:[dr(F.normalizeNativeTokenAddress(n.asset.address),R,F.getEscrowContractAddress(n.asset.chainId))]}:null,P=(U,G)=>({token:U,from:W?"solver":"escrow",to:s,amount:G}),D=(U,G)=>W?[{token:U,from:"escrow",to:F.SPICE_SOLVER_ADDRESS,amount:G}]:[];if(g){if(!C)throw new Error("Swap input token could not be resolved");if(!m||v===null)throw new Error("Swap quote not available yet")}if(g&&m&&v&&C){const U=u(t?.actionAmountOverride??v,{...S,netAmount:t?.actionAmountOverride??v}),{feeCall:G,remainingCalls:pe}=fr(U,c,g,S.feeToken),q={chainId:l,calls:[...G?[G]:[],...m.calls,...pe],tokenTransfers:[...D(C,N),P(C,j)]},J=await ps(q,f,{userAddress:s,destinationChainId:l,deliveryToken:C,deliveryAmount:j,withdrawalAmount:N,deliveryRecipient:s,deliveryTransfers:fs(q),sourceAsset:n.asset},k);return z?[z,...J]:J}const Q=C??rn(n.asset,l)??d.address,H={chainId:l,calls:E,tokenTransfers:[...D(Q,N),P(Q,j)]},ee=await ps(H,f,{userAddress:s,destinationChainId:l,deliveryToken:Q,deliveryAmount:j,withdrawalAmount:N,deliveryRecipient:s,deliveryTransfers:fs(H),sourceAsset:n.asset},k);return z?[z,...ee]:ee}async function gr(e,t,n,s,r){let a=e;for(let l=0;l<4;l++){const d=await t(a),u=await s(d,n,a,r),c=oi(u);if(c===null||c>=e)return a;const f=a-c,p=e+f;if(p<=a)return a;a=p}return a}function zl(e,t,n,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 xr(e){const{asset:t,isPayMode:n,isNon7702:s,needsSwap:r,isQuoting:a,embeddedWalletAddress:l,buildSupplyChainBatches:d,estimate:u,executionTokenAddress:c,feeExecutionMode:f}=e;if(n||s||r||a||!l||t.balance<=0n)return null;const p=l,x=await d({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(x.length===0)return null;const g=x.some(M=>M.tokenTransfers?.length),m=await u(x,c,t.balance,g?{userOverride:p,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:p,feeExecutionMode:f}:{userOverride:p}),y=Cn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),C=y?ln(y.gasFee,y.decimals,t.decimals):0n,k=y?ln(y.spicenetFee,y.decimals,t.decimals):0n,v=zl(t.balance,C,k,t.balance);return v>0n?Eo(v,t.decimals):null}async function yr(e){const{selectedAsset:t,isPayMode:n,parsedAmount:s,needsSwap:r,exactOutputSwap:a,isNon7702:l,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:c,feeExecutionMode:f,resolvedTokenIn:p,embeddedWalletAddress:x,providerEmbeddedAddress:g,resolvedChainId:m,isConnected:y,address:C,ready:k,authenticated:v,isDirect:M,resolvedSwap:b,isQuoting:w,executionTokenAddress:R,buildPayChainBatches:j,buildSupplyChainBatches:N,estimate:B,estimateRequiredGrossFunding:S}=e;if(!t?.asset)return null;if(n){if(s<=0||r&&!a||d)return null;const D=T.parseUnits(u,c.decimals),Q=p||rn(t.asset,m)||t.asset.address||c.address,H={chainId:m,tokenAddress:Q,symbol:F.getTokenByAddress(Q,m)?.symbol??t.asset.symbol,decimals:F.getTokenByAddress(Q,m)?.decimals??t.asset.decimals};if(l){const J=x||g;if(!J)return null;const le=r?a?.amountInMax??0n:D;if(le===0n)return null;const be={userOverride:J,useCustomTransfers:!0},ie=await S(le,ke=>j({fundingAmountOverride:ke}),Q,be),fe=await j({fundingAmountOverride:ie}),ce=await B(fe,Q,ie,{...be,feeExecutionMode:f});return Cn(ce,H)}if(!y||!C||!k||!v)return null;const ee=x||g||C,U=r?a?.amountInMax??0n:D;if(U===0n)return null;const G=await S(U,J=>j({fundingAmountOverride:J}).then(le=>an(Xs(le),ee)),Q,{useCustomTransfers:!0});let pe=an(Xs(await j({fundingAmountOverride:G})),ee);const q=await B(pe,Q,G,{useCustomTransfers:!0,feeExecutionMode:f});return Cn(q,H)}if(s<=0||!x)return null;const E=x||g;if(!(!n&&!l&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!M&&!b&&!w||w)return null;const I=T.parseUnits(t.amount,t.asset.decimals),A=await N();if(A.length===0)return null;const W=l&&t.asset?._source==="wallet"&&t.asset.chainId===m,O={chainId:m,tokenAddress:R,symbol:F.getTokenByAddress(R,m)?.symbol??c.symbol,decimals:F.getTokenByAddress(R,m)?.decimals??c.decimals};if(W){const D=await h.relayerService.estimateBatchGas({user:E,outputToken:R,stepIndex:0,chainBatches:A}),Q=es(I,10n),H=Q+D.gasFee;return{...O,grossAmount:I+H,netAmount:I,totalFee:H,gasFee:D.gasFee,spicenetFee:Q,bridgeFee:0n,gasQuoteSource:D.gasQuoteSource}}const z=A.some(D=>D.tokenTransfers?.length),P=await B(A,R,I,z?{userOverride:E,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:E,feeExecutionMode:f}:{userOverride:E});return Cn(P,O)}const Ll=10n;function Cr(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=rn(n,e.resolvedChainId);if(!s||!h.addressesEqual(s,e.executionTokenAddress))return;const r=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=ln(t,r?.decimals??e.destinationToken.decimals,n.decimals);if(a<=n.balance)return;const l=T.formatUnits(a,n.decimals),d=T.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${l} ${n.symbol}; available ${d} ${n.symbol}.`)}function Gs(e){const t=F.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 Vn(e,t,n){const s=Cn(e,Gs(t));if(!s)return;const r=es(n,Ll),a=s.bridgeFee??0n,l=r+s.gasFee+a;return{grossAmount:n+l,netAmount:n,combinedFeeAmount:l,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:r,gasFee:s.gasFee,bridgeFee:a}}}function br(e,t,n){let s=0n,r=0n;const a=n.toLowerCase();for(const l of e)if(l.chainId===t){for(const d of l.calls??[])if(d.to.toLowerCase()===a)try{const u=T.decodeFunctionData({abi:T.erc20Abi,data:d.data});if(u.functionName!=="transfer")continue;const c=u.args[0].toLowerCase(),f=u.args[1];c===F.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=f:c===F.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(r+=f)}catch{continue}}return{spicenetFee:s,gasFee:r}}function Js(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=br(e,t.resolvedChainId,s);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:yn(r.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&yn(r.gasFee,n.feeBreakdown.gasFee,100n)}function wr(e,t){return e?yn(e.grossAmount,t.grossAmount,100n)&&yn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&yn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&yn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function kr(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 $s(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 vr(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){const r=s instanceof Error?s:new Error(String(s));if(r.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const a=r.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(a),e.ui.setError(a),e.onError?.(r)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=T.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),s=n;let r=await e.execution.buildSupplyChainBatches();const a=e.selectedAsset.asset?._source==="wallet",l=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!a&&!r.some(g=>F.isSpicenetChainId(g.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const d=r.some(g=>g.tokenTransfers?.length)?{userOverride:l,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:l,feeExecutionMode:e.feeExecutionMode}:{userOverride:l};let u=n;const c=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,f=e.feeExecutionMode==="user-transfer"&&!c?s:void 0;let p;for(let g=0;g<4;g+=1){const m=await e.execution.estimate(r,e.executionTokenAddress,u,d),y=Cn(m,Gs(e));p=e.feeExecutionMode==="user-transfer"&&y?Vn(m,e,s):void 0;const C=p?.grossAmount??y?.grossAmount??u;if(C===u){u=C;break}u=C,r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:p})}e.feeExecutionMode==="user-transfer"&&(Cr(e,u),r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:p}));let x=p;await e.execution.execute(r,e.executionTokenAddress,u,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:g,chainBatches:m})=>{const y=Vn(g,e,s);if(!y)return null;const C=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;br(m,e.resolvedChainId,C);const k=wr(x,y),v=Js(m,e,y);return k||v?null:(x=y,e.execution.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:f,actionContextOverride:y}))}}:d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const s=n instanceof Error?n:new Error(String(n));if(s.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(s)}finally{e.ui.setIsExecuting(!1)}}async function vr(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=T.parseUnits(e.selectedAsset.amount,s.decimals),a=r,l=s?._source==="wallet"&&s.chainId===e.resolvedChainId;let d=await e.execution.buildSupplyChainBatches();const u={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let c=r;const f=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!f?a:void 0;let x;if(l){const S=await h.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),E=es(r,10n),I=E+S.gasFee;c=r+I,e.feeExecutionMode==="user-transfer"&&(x={grossAmount:c,netAmount:a,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:E,gasFee:S.gasFee,bridgeFee:0n}})}else for(let S=0;S<4;S+=1){const E=await e.execution.estimate(d,e.executionTokenAddress,0n,u),I=e.feeExecutionMode==="user-transfer"?Vn(E,e,a):void 0,A=Cn(E,Gs(e)),W=I?.grossAmount??(A?A.grossAmount>r?A.grossAmount:r:c);if(x=I,W===c){c=W;break}c=W;const O=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),z=ln(c,O?.decimals??e.destinationToken.decimals,s.decimals);d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:z,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I})}const g=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let m=l?c:ln(c,g?.decimals??e.destinationToken.decimals,s.decimals);Cr(e,c),d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:x});const y=s.chainId,C=n,k=await e.externalWallet.getEthereumProvider();await Wn(k,y,()=>e.ui.setStatusMsg("Switching source network..."));const v=h.getChainConfig(y),M=T.createWalletClient({account:e.externalWalletAddress,chain:v?.viemChain,transport:T.custom(k)}),b=F.normalizeNativeTokenAddress(s.address),w=s.isNative||F.isNativeToken(b),R=h.getClientForChain(y),j=S=>sr({extWc:M,sourceClient:R,recipient:C,tokenAddr:b,isNative:w,amount:S,viemChain:v?.viemChain});e.ui.setStatusMsg("Funding embedded wallet..."),await j(m);let N=m;if(e.feeExecutionMode==="user-transfer")for(let S=0;S<4;S+=1){const E=await e.execution.estimate(d,e.executionTokenAddress,0n,u),I=Vn(E,e,a);if(!I)break;const A=l?I.grossAmount:ln(I.grossAmount,g?.decimals??e.destinationToken.decimals,s.decimals);if(A>N&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await j(A-N),N=A),x=I,c=I.grossAmount,m=A,d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I}),Js(d,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let B=x;await e.execution.execute(d,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:S,chainBatches:E})=>{const I=Vn(S,e,a);if(!I)return null;const A=wr(B,I),W=Js(E,e,I);if(A||W)return null;if(I.grossAmount>c)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");B=I;const O=l?I.grossAmount:ln(I.grossAmount,g?.decimals??e.destinationToken.decimals,s.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:O,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:p,actionContextOverride:I})}}:u)}async function $s(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=T.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),a={userAddress:s,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},l=e.buildActionCalls(r,a);if(l.length===0)throw new Error("No action calls configured");const d=await n.getEthereumProvider();await Wn(d,e.resolvedChainId);const u=h.getChainConfig(e.resolvedChainId),c=T.createWalletClient({account:s,chain:u?.viemChain,transport:T.custom(d)}),f=h.getClientForChain(e.resolvedChainId);let p;for(const x of l){const g=await c.sendTransaction({to:x.to,data:x.data,value:x.value,chain:u?.viemChain});if((await f.waitForTransactionReceipt({hash:g,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");p=g}return p}async function Sr(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=T.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const l=e.resolvedTokenIn||e.selectedAsset.asset.address,d={userOverride:t,useCustomTransfers:!0},u=await e.execution.estimateRequiredGrossFunding(a,k=>e.execution.buildPayChainBatches({fundingAmountOverride:k}),l,d),c=F.getEscrowContractAddress(s),f=await e.externalWallet.getEthereumProvider();await Wn(f,s);const p=h.getChainConfig(s),x=T.createWalletClient({account:e.externalWalletAddress,chain:p?.viemChain,transport:T.custom(f)}),g=F.normalizeNativeTokenAddress(n.address),m=n.isNative||F.isNativeToken(g)?await x.sendTransaction({to:c,value:u,chain:p?.viemChain}):await x.sendTransaction({to:g,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[c,u]}),chain:p?.viemChain});if((await h.getClientForChain(s).waitForTransactionReceipt({hash:m,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const y=await e.execution.buildPayChainBatches({fundingAmountOverride:u}),C=y.some(k=>k.tokenTransfers?.length);return await e.execution.execute(y,l,u,k=>{k.txHash&&(e.ui.setPaymentResult(v=>({...v??{status:"processing"},txHash:k.txHash})),e.ui.setTxHash(k.txHash))},void 0,C?d:{userOverride:t})}async function Ir(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 $s(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,a=T.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),l=e.selectedIsEquivalent?a:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(l===0n)throw new Error("Quote not available yet");const d=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!d)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const u=e.resolvedTokenIn||r.address,c=await e.execution.estimateRequiredGrossFunding(l,x=>e.execution.buildPayChainBatches({fundingAmountOverride:x}),u,{userOverride:d,useCustomTransfers:!0}),f=await e.execution.buildPayChainBatches({fundingAmountOverride:c}),p=await e.onPayExecute({asset:r,amount:e.currentPaymentAmount,amountWei:a,destinationToken:e.destinationToken,chainBatches:f,requiredNetFunding:l,grossFundingAmount:c,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:u,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});p&&(e.ui.setTxHash(p),e.ui.setPaymentResult(x=>({...x??{status:"processing"},txHash:p}))),s=p||void 0}else s=await Sr(e);e.ui.setPaymentResult(r=>({status:"success",txHash:r?.txHash||s||""}))}catch(s){const r=h.sanitizeError(s,"Payment failed. Please try again.");e.ui.setError(r),e.ui.setPaymentResult({status:"failed",error:r}),e.onError?.(s instanceof Error?s:new Error(r))}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=T.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),s={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const C=await e.execution.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),k=await e.execution.execute(C,e.destinationToken.address,0n,v=>{v.txHash&&(e.ui.setPaymentResult(M=>({...M,txHash:v.txHash})),e.ui.setTxHash(v.txHash))},void 0,s);e.ui.setPaymentResult(v=>({status:"success",txHash:v?.txHash||k}));return}const r=e.selectedAsset?.asset;if(!r)throw new Error("Select a payment source");const a=e.resolvedTokenIn||r.address||e.destinationToken.address,l=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,d=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,u=(C,k,v)=>{const M=Xs(C),b=j=>(j.tokenTransfers??[]).some(N=>N.from==="escrow"),w=M.filter(j=>!b(j)),R=M.filter(b);return[...w,...an(R,d,k,v)]},c=await e.execution.estimateRequiredGrossFunding(l,C=>e.execution.buildPayChainBatches({fundingAmountOverride:C}).then(k=>u(k)),a,s);let f=c,p=u(await e.execution.buildPayChainBatches({fundingAmountOverride:c}));const x=await e.execution.estimate(p,a,c,s),g=Cn(x,{chainId:e.resolvedChainId,tokenAddress:a,symbol:F.getTokenByAddress(a,e.resolvedChainId)?.symbol??r.symbol,decimals:F.getTokenByAddress(a,e.resolvedChainId)?.decimals??r.decimals})?.grossAmount??c;g!==c&&(f=g),p=u(await e.execution.buildPayChainBatches({fundingAmountOverride:f}),x,{payoutAlreadyGross:!0});const m=p.some(C=>C.tokenTransfers?.length),y=await e.execution.execute(p,a,m?f:0n,C=>{C.txHash&&(e.ui.setPaymentResult(k=>({...k,txHash:C.txHash})),e.ui.setTxHash(C.txHash))},void 0,s);e.ui.setPaymentResult(C=>({status:"success",txHash:C?.txHash||y}))}catch(n){const s=h.sanitizeError(n,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(n instanceof Error?n:new Error(s))}finally{e.ui.setIsExecuting(!1)}}const Hl=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,isQuoting:x,quoteError:g,estimatedOutput:m,paymentAmount:y,needsSwap:C,exactOutputSwap:k,adjustable:v=!1,maxAmount:M,onAmountChange:b})=>e==="supply"?o.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${c}`,borderRadius:p?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[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:p?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),o.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,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 ${c}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[o.jsx(Er,{symbol:t,logoURI:n,primaryColor:r,size:24}),o.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:p?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),o.jsx("div",{style:{textAlign:"right",minWidth:0},children:x?o.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:a},children:"Quoting..."}):g?o.jsx("span",{style:{fontSize:"13px",color:p?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):m?o.jsx(In,{value:m,title:m,fontFamily:a,color:l,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):o.jsx("span",{style:{fontSize:"20px",color:d,fontFamily:a},children:"\u2014"})})]}):o.jsx(Ql,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:k,isQuoting:x,adjustable:v,maxAmount:M,onAmountChange:b}),Ar=i.memo(Hl),Er=({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)}),Ql=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:l,cardBg:d,cardBorder:u,dk:c,dark:f,paymentAmount:p,needsSwap:x,exactOutputSwap:g,isQuoting:m,adjustable:y,maxAmount:C,onAmountChange:k})=>{const v='"IBM Plex Mono", monospace',M=parseFloat(p||"0"),b=C?parseFloat(C):0,[w,R]=i.useState(p||""),j=i.useRef(null),[N,B]=i.useState(null),[S,E]=i.useState(null);i.useEffect(()=>{y||R(p||"")},[p,y]);const I=O=>{let z=O;z.startsWith(".")&&(z="0"+z);const P=h.parseNumericInput(z);let D=P;C&&parseFloat(P)>parseFloat(C)&&(D=C),R(D),j.current&&clearTimeout(j.current),j.current=setTimeout(()=>k?.(D),300)},A=O=>{if(!b)return;if(O===100){R(C||b.toString()),j.current&&clearTimeout(j.current),k?.(C||b.toString());return}const z=10**n,P=Math.floor(b*O/100*z)/z,D=h.formatDecimalInput(P,n);R(D),j.current&&clearTimeout(j.current),k?.(D)},W=b>0?parseFloat(w||"0")/b*100:0;return i.useEffect(()=>()=>{j.current&&clearTimeout(j.current)},[]),o.jsxs("div",{style:{backgroundColor:d,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(Er,{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:l,fontFamily:r,marginTop:"2px"},children:e})]})]}),o.jsxs("div",{style:{textAlign:"right"},children:[y?o.jsx(In,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:O=>I(O.target.value),placeholder:"0.0",fontFamily:v,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):o.jsx(In,{element:"div",value:M>0?p:"0.00",title:M>0?p:"0.00",fontFamily:v,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),o.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:v,marginTop:"2px"},children:e}),y&&b>0&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((O,z)=>{const P=Math.abs(W-O)<1,D=z===4,Q=O/100,H=N===O,ee=S===O;return o.jsx("button",{onClick:()=>A(O),onMouseEnter:()=>B(O),onMouseLeave:()=>{B(null),E(null)},onMouseDown:()=>E(O),onMouseUp:()=>E(null),title:`${O}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:P?1:H?.8:.5,transform:ee?"scale(0.85)":H?"scale(1.15)":"scale(1)",transition:_t.interactive},children:o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[o.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:D?s:"none",stroke:D?s:f?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!D&&Q>0&&o.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${Q>.5?1:0} 1 ${7+6.84375*Math.sin(Q*2*Math.PI)} ${7-6.84375*Math.cos(Q*2*Math.PI)} Z`,fill:f?c?.textSecondary||"#9ca3af":"#3C3E42"})]})},O)})})]})]}),x&&g&&!m&&o.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:f?`1px solid ${c?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:o.jsxs("span",{style:{fontSize:"11px",color:l,fontFamily:r,opacity:.7},children:["via ",g.venue]})})]})};function jr(e,t,n){const s=h.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 Fr(e,t){return!t||t.length===0||t.some(n=>h.addressesEqual(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const s=Bn(n);return s?t.some(r=>h.addressesEqual(r,s.address)):!1})}function Tr(e,t,n){let{symbol:s,name:r,logoURI:a}=t;const l=h.addressesEqual(e.address,n.address)&&e.chainId===n.chainId;l&&n.logoURI&&(a=n.logoURI),l&&!e.configToken&&s==="TOKEN"&&(s=n.symbol,r=n.symbol);const d=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:d,balanceUsd:0,logoURI:a,isNative:!1,chainId:e.chainId}}function Br(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:s,enabled:r}=e,a=i.useContext(h.SpiceFlowProviderContext),l=(a?.mode||"7702")!=="7702",d=a?.embeddedWalletAddress,{externalAddress:u,embeddedAddress:c,activeAddress:f}=h.useProviderWallets(),p=d||c,{assets:x,refetch:g}=Qn({address:p,supportedChains:s,enabled:r&&!l&&!!p,refetchInterval:3e4}),m=i.useMemo(()=>l?[]:x.filter(B=>Fr(B,n)),[x,n,l]),y=l?f??u:d,C=i.useMemo(()=>{const B=new Set,S=[],E=I=>{if(!I)return;const A=I.toLowerCase();B.has(A)||(B.add(A),S.push(T.getAddress(I)))};if(E(t.address),n)for(const I of n)E(I);return S},[l,t.address,n]),k=i.useMemo(()=>C.map(B=>B.toLowerCase()).sort().join(","),[C]),v=i.useMemo(()=>JSON.stringify([...s||[]].sort()),[s]),[M,b]=i.useState([]),w=i.useRef(0),R=i.useRef(async()=>{}),j=i.useCallback(async()=>{if(!r||!y||C.length===0){w.current++,b([]);return}const B=++w.current,S=T.getAddress(y),E=l?s&&s.length>0?s:[t.chainId]:[t.chainId],I=[];for(const z of C){const P=z.toLowerCase();if(P===F.ZERO_ADDRESS)continue;if(P===t.address.toLowerCase()){const Q=h.getChainConfig(t.chainId)?.supportedTokens?.find(H=>h.addressesEqual(H.address,P));I.push({address:z,chainId:t.chainId,configToken:Q?{decimals:Q.decimals,symbol:Q.symbol,name:Q.name,logo:Q.logo}:void 0});continue}let D=!1;for(const Q of E){const H=h.getChainConfig(Q)?.supportedTokens?.find(ee=>h.addressesEqual(ee.address,P));if(H){I.push({address:z,chainId:Q,configToken:{decimals:H.decimals,symbol:H.symbol,name:H.name,logo:H.logo}}),D=!0;break}}D||I.push({address:z,chainId:t.chainId})}const A=new Map;for(const z of I){const P=A.get(z.chainId)||[];P.push(z),A.set(z.chainId,P)}const W=async(z,P)=>{try{const D=await sn.readContract(z,{address:P.address,abi:T.erc20Abi,functionName:"balanceOf",args:[S]}),{decimals:Q,symbol:H,name:ee,logoURI:U}=await tr(z,P.address,P.configToken);return Tr(P,{decimals:Q,symbol:H,name:ee,logoURI:U,balance:D},t)}catch{return null}},O=await Promise.all(Array.from(A.entries()).map(async([z,P])=>{let D;try{D=h.getClientForChain(z)}catch{return[]}const Q=[],H=[];for(const U of P){const G=Q.length;Q.push({address:U.address,abi:T.erc20Abi,functionName:"balanceOf",args:[S]}),U.configToken||Q.push({address:U.address,abi:T.erc20Abi,functionName:"decimals"},{address:U.address,abi:T.erc20Abi,functionName:"symbol"},{address:U.address,abi:T.erc20Abi,functionName:"name"}),H.push({start:G,item:U})}let ee=null;try{ee=await D.multicall({contracts:Q})}catch{ee=null}return ee?H.map(({start:U,item:G})=>{const pe=ee[U],q=pe?.status==="success"?pe.result:0n;let J,le,be,ie;if(G.configToken)J=G.configToken.decimals,le=G.configToken.symbol,be=G.configToken.name,ie=G.configToken.logo;else{const fe=ee[U+1],ce=ee[U+2],ke=ee[U+3];J=fe?.status==="success"?Number(fe.result):18,le=ce?.status==="success"?ce.result:"TOKEN",be=ke?.status==="success"?ke.result:le}return Tr(G,{decimals:J,symbol:le,name:be,logoURI:ie,balance:q},t)}):(await Promise.all(P.map(U=>W(D,U)))).filter(U=>U!==null)}));B===w.current&&b(O.flat())},[r,l,y,k,v,t.address,t.chainId,t.symbol,t.logoURI]);i.useEffect(()=>{R.current=j},[j]),i.useEffect(()=>{if(!r){b([]);return}R.current();const B=setInterval(()=>{R.current()},15e3);return()=>clearInterval(B)},[r,l,y,k,v,t.address,t.chainId]);const N=i.useCallback(()=>{j()},[j]);return{displayAssets:i.useMemo(()=>{const B=[],S=M.filter(I=>I.balance>0n);for(const I of S)B.push({...I,_source:"wallet"});for(const I of m)B.push({...I,_source:"spice"});const E=t.address.toLowerCase();return B.sort((I,A)=>jr(I,E,t.chainId)-jr(A,E,t.chainId)),B},[M,m,t.address,t.chainId]),filteredSpiceAssets:m,walletAssets:M,embeddedWalletAddress:p,externalAddress:u,isNon7702:l,refreshSpiceAssets:g,refreshWalletAssets:N}}async function Rr(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:r,chainId:a,config:l}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const d=(await h.getClientForChain(a).simulateContract({address:l.quoterV2,abi:F.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function Mr(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>Rr({...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 Vl=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"quoteExactOutputSingle",outputs:[{name:"amountIn",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];async function ql(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:r,chainId:a,config:l}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const d=(await h.getClientForChain(a).simulateContract({address:l.quoterV2,abi:Vl,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function Yl(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>ql({...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 Nr(e){return e.type==="swap"}const _s=.02,Kl=[1,8453,42161,10,137,43114,56],Zl="https://api.1inch.dev/swap/v6.0";function Dr(e,t){return F.applySlippage(e,t)}function Wr(e){const t=e?.baseUrl??Zl;return{name:"1inch",chainIds:e?.chainIds??Kl,resolve:async(n,s,r)=>{const a=n.maxSlippage??_s,l=a*100,d=F.isNativeToken(n.tokenIn)?F.NATIVE_TOKEN_ADDRESS:n.tokenIn,u=F.isNativeToken(n.tokenOut)?F.NATIVE_TOKEN_ADDRESS:n.tokenOut,c=F.isNativeToken(n.tokenIn);try{const f=new URL(`${t}/${s}/swap`);f.searchParams.set("src",d),f.searchParams.set("dst",u),f.searchParams.set("amount",n.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",l.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const x=await fetch(f.toString(),{headers:p});if(!x.ok)throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${x.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 ${x.status}`});const g=await x.json();if(!g.dstAmount||!g.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const m=BigInt(g.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const y=Dr(m,a),C=[];return g.tx.to&&!c&&C.push({to:n.tokenIn,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[g.tx.to,n.amountIn]})}),C.push({to:g.tx.to,value:BigInt(g.tx.value||"0"),data:g.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:C}}catch(f){if(f instanceof h.SpiceflowError)throw f;const p=f instanceof Error?f.message:String(f);throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${p}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:p})}}}}const Pr=[4114,5115],eo={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Ur={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Or(e){return{name:"satsuma",chainIds:e.chainIds??Pr,resolve:async(t,n,s)=>{const r=t.maxSlippage??_s,a=F.isNativeToken(t.tokenIn);let l;try{l=await Mr({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const d=Dr(l.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:T.encodeFunctionData({abi:F.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:l.fee,recipient:s,amountIn:t.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:l.amountOut,amountOutMinimum:d,calls:u}}}}function zr(e){return{name:"satsuma",chainIds:e.chainIds??Pr,resolve:async(t,n,s)=>{const r=t.maxSlippage??_s,a=F.isNativeToken(t.tokenIn);let l;try{l=await Yl({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const d=BigInt(Math.round(r*1e4)),u=l.amountIn+l.amountIn*d/10000n,c=[];return c.push({to:e.swapRouter,value:a?u:0n,data:T.encodeFunctionData({abi:Xl,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:l.fee,recipient:s,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:l.amountIn,amountInMax:u,amountOut:t.amountOut,calls:c}}}}const Xl=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"exactOutputSingle",outputs:[{name:"amountIn",type:"uint256"}],stateMutability:"payable",type:"function"}];function Lr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Or(e.satsuma)),t.push(Wr(e?.oneInch));function n(r){return t.find(a=>a.chainIds.includes(r))}async function s(r,a,l){const d=[],u=[];for(const c of r){if(!Nr(c)){d.push(c);continue}const f=n(a);if(!f)throw new h.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${c.tokenIn} \u2192 ${c.tokenOut}.`,{chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});const p=await f.resolve(c,a,l);if(!p)throw new h.SpiceflowError("NO_LIQUIDITY",`${f.name} returned no quote for ${c.tokenIn} \u2192 ${c.tokenOut} on chain ${a}.`,{venue:f.name,chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});d.push(...p.calls),u.push(p)}return{calls:d,resolvedSwaps:u}}return{resolveSwapIntents:s,getVenueForChain:n,venues:t}}function Hr(e){const t=e?.customVenues??[];async function n(s,r,a){const l=t.filter(c=>c.chainIds.includes(r));if(l.length===0)throw new h.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const d=(await Promise.allSettled(l.map(async c=>({venue:c,quote:await c.resolve(s,r,a)})))).filter(c=>c.status==="fulfilled").map(c=>c.value).filter(c=>c.quote!==null);if(d.length===0)throw new h.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=d.find(c=>c.venue.preferred);return u?u.quote:(d.sort((c,f)=>c.quote.amountIn<f.quote.amountIn?-1:c.quote.amountIn>f.quote.amountIn?1:0),d[0].quote)}return{getQuote:n,venues:t}}const Qr=Lr({satsuma:eo});async function Gl(e){const t=Qr.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 Vr(e){const{direction:t,selectedAsset:n,destinationToken:s,chainId:r,recipient:a,paymentAmount:l,resolveExactOutputSwap:d}=e,[u,c]=i.useState(!1),[f,p]=i.useState(null),[x,g]=i.useState(null),[m,y]=i.useState(null),[C,k]=i.useState(null),[v,M]=i.useState(null),[b,w]=i.useState(null),[R,j]=i.useState(null),[N,B]=i.useState(null),S=i.useRef(null),E=i.useRef(null),I=i.useRef(0),A=i.useRef(new Map),W=i.useMemo(()=>Qr,[]),O=i.useMemo(()=>Hr({customVenues:[...d?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:d}]:[],zr(eo),zr(Ur)]}),[d,r]),z=i.useMemo(()=>{if(!n?.asset)return null;const J=rn(n.asset,r);if(J)return J;const le=hn(n.asset.address,r,n.asset.chainId);return le?le.address:null},[n?.asset,r]),P=i.useMemo(()=>n?.asset?Xn(n.asset,r):[],[n?.asset,r]),D=i.useMemo(()=>P.map(J=>J.toLowerCase()).join(","),[P]);i.useEffect(()=>{let J=!1;if(E.current&&(clearTimeout(E.current),E.current=null),!n?.asset||P.length<=1){B(null);return}return E.current=setTimeout(async()=>{const le=t==="input"?n.amount:l||"0";let be=0n;try{be=t==="input"?T.parseUnits(le,n.asset.decimals):0n}catch{be=0n}try{const ie=await wo(n.asset,r,{requiredAmount:be});J||B(ie)}catch{J||B(null)}},400),()=>{J=!0,E.current&&(clearTimeout(E.current),E.current=null)}},[n?.asset,n?.amount,r,P.length,D,t,l]);const Q=i.useMemo(()=>N??z,[N,z]),H=i.useMemo(()=>!n?.asset||!Q?[]:[Q,...P.filter(J=>J.toLowerCase()!==Q.toLowerCase())],[n?.asset,Q,P]),ee=i.useMemo(()=>!n?.asset||!Hn(n.asset.address,n.asset.chainId,s.address,s.chainId)||!Q?!1:h.addressesEqual(Q,s.address),[n,s.address,s.chainId,Q]),U=Q?h.addressesEqual(Q,s.address):!1,G=t==="output"&&parseFloat(l||"0")===0,pe=!!n?.asset&&!ee&&!U&&!G,q=pe?R??Q:Q;return i.useEffect(()=>{S.current&&clearTimeout(S.current);const J=t==="input"?n?.amount:l,le=parseFloat(J||"0");if(!pe||!Number.isFinite(le)||le<=0||!n?.asset||!a||H.length===0){I.current++,g(null),y(null),k(null),M(null),w(null),j(null),p(null),c(!1);return}const be=n.asset.decimals;let ie;try{ie=t==="input"?T.parseUnits(n.amount,be):T.parseUnits(l||"0",s.decimals)}catch{I.current++,p("Invalid amount"),c(!1);return}const fe=++I.current,ce=()=>fe!==I.current;c(!0);const ke=t==="output"?150:400;return S.current=setTimeout(async()=>{try{if(t==="input"){const te=W.getVenueForChain(r);if(!te)throw new Error("No swap venue for this chain");let Y=null,_=null;for(const ge of H){const K=`${t}:${r}:${ge.toLowerCase()}:${s.address.toLowerCase()}:${ie.toString()}`,ne=A.current.get(K);if(ne&&ne.expiresAt>Date.now()&&ne.resolvedSwap){Y=ne.resolvedSwap,_=ge;break}const he=await te.resolve({type:"swap",tokenIn:ge,tokenOut:s.address,amountIn:ie},r,a);if(ce())return;if(he){A.current.set(K,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:he}),Y=he,_=ge;break}}if(!Y||!_)throw new Error("No liquidity for this pair");j(_),w(Y.amountOut),k(Y),M(null);const re=parseFloat(T.formatUnits(Y.amountOut,s.decimals));g(re<.01?re.toPrecision(4):re.toLocaleString(void 0,{maximumFractionDigits:6})),y(null),p(null)}else{let te=null,Y=null;for(const _ of H){const re=`${t}:${r}:${_.toLowerCase()}:${s.address.toLowerCase()}:${ie.toString()}`,ge=A.current.get(re);if(ge&&ge.expiresAt>Date.now()&&ge.exactOutputSwap){te=ge.exactOutputSwap,Y=_;break}try{const K=await O.getQuote({tokenIn:_,tokenOut:s.address,amountOut:ie},r,a);if(ce())return;A.current.set(re,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:K}),te=K,Y=_;break}catch{if(ce())return}}if(!te||!Y)throw new Error("No liquidity for this pair");j(Y),M(te),k(null),w(null),y(parseFloat(T.formatUnits(te.amountIn,be)).toFixed(6)),g(null),p(null)}}catch(te){if(ce())return;const Y=te instanceof Error?te.message:"Failed to get quote";p(Y),g(null),y(null),k(null),M(null),w(null),j(null)}finally{ce()||c(!1)}},ke),()=>{S.current&&clearTimeout(S.current)}},[t,pe,n?.amount,n?.asset?.address,n?.asset?.decimals,l,H,r,s.address,s.decimals,a,W,O]),{isQuoting:u,quoteError:f,estimatedOutput:x,estimatedInput:m,resolvedSwap:C,exactOutputSwap:v,quoteAmountOut:b,resolvedTokenIn:q,isDirect:U,needsSwap:pe,selectedIsEquivalent:ee}}const qr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Yr=["signing-delegation","signing-intent","submitting","executing"],Jl=()=>{},$l=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:s,sourceChains:r,supportedSourceAssets:a,buildActionCalls:l,feeExecutionMode:d="user-transfer",buildSpicenetBatch:u,onPayExecute:c,resolveExactOutputSwap:f,actionLabel:p,amountDirection:x="input",swapDescription:g,directDescription:m,paymentAmount:y,amountInputMode:C="fixed",minPaymentAmount:k,maxPaymentAmount:v,onAmountChange:M,styles:b,dark:w,title:R,subtitle:j,onAddFunds:N,onSuccess:B,onError:S})=>{const E=x==="output",{theme:I,dark:A,primaryColor:W,dk:O,palette:z,fontFamily:P,monoFont:D,inputDark:Q,cardBg:H,cardBorder:ee,textPrimary:U,textSecondary:G,subtitleText:pe}=h.useSpiceBrand(b,w),q=i.useMemo(()=>Q?{...I,colors:{...I.colors,secondary:O.cardBg,surfaceHover:O.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:I,[Q,I,O.cardBg,O.hoverBg]),J=s.chainId,le=i.useContext(h.SpiceFlowProviderContext),be=le?.mode||"7702",ie=be!=="7702",fe=!!le?.isWhitelistGateActive,ce=!!le?.isWhitelistConfigured&&le?.isUserWhitelisted!==!0,ke=i.useMemo(()=>r??le?.supportedChainIds??[],[r,le?.supportedChainIds]),te=i.useMemo(()=>{if(fe)return[];if(a)return a;const me=le?.allowedTokens;if(!me||me.length===0)return;const $e=new Set(me.map(gn=>gn.toLowerCase())),dn=[],mn=new Set;for(const gn of ke){const hs=h.getChainConfig(gn);for(const ms of hs?.supportedTokens??[]){if(!$e.has(ms.symbol.toLowerCase()))continue;const to=ms.address.toLowerCase();mn.has(to)||(mn.add(to),dn.push(ms.address))}}return dn},[a,le?.allowedTokens,ke,fe]),Y=h.useWallet(),{address:_,isConnected:re,isReady:ge,isAuthenticated:K,provider:ne}=Y,{execute:he,estimate:oe}=Mn(),{externalWallet:Be,embeddedAddress:it,activeWallet:St,activeAddress:It}=h.useProviderWallets(),lt=le?.externalWalletAddress,ue=le?.embeddedWalletAddress||it,{displayAssets:At,filteredSpiceAssets:Te,embeddedWalletAddress:We,refreshSpiceAssets:_e,refreshWalletAssets:wt}=Br({destinationToken:s,supportedSourceAssets:te,sourceChains:ke,enabled:e&&(ie?!!lt:!!ue)}),Ze=fe||E||ie?At:Te;i.useEffect(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:be,walletAddressUsed:We,count:Ze.length,assets:Ze.map(me=>({symbol:me.symbol,address:me.address,chainId:me.chainId,balanceFormatted:me.balanceFormatted,source:me?._source}))})},[e,be,We,Ze]);const[L,Re]=i.useState(null),[Ie,Qe]=i.useState(y||""),[ze,Rt]=i.useState(!1),[Nt,zt]=i.useState(null),[ve,Dt]=i.useState("idle"),[Xe,tn]=i.useState(""),[Zt,Ve]=i.useState(null),[Lt,Et]=i.useState(!1),[Ue,ye]=i.useState(null),[Oe,Ke]=i.useState(null),[Xt,we]=i.useState(!1),[Mt,yt]=i.useState(!1),[pt,qe]=i.useState(null),nn=i.useRef(L),jt=i.useRef(!1),Ht=i.useRef(null),Gt=i.useRef(null),Ft=i.useRef(0),gt=i.useRef(null),ct=i.useRef(null);i.useEffect(()=>{nn.current=L},[L]);const Me=C==="adjustable"?Ie:y||"0",et=We||it||_,{isQuoting:ft,quoteError:Qt,estimatedOutput:Wt,resolvedSwap:ht,exactOutputSwap:Se,quoteAmountOut:Ct,resolvedTokenIn:ot,isDirect:bt,needsSwap:tt,selectedIsEquivalent:Ae}=Vr({direction:x,selectedAsset:L,destinationToken:s,chainId:J,recipient:et,paymentAmount:Me,resolveExactOutputSwap:f}),nt=E?parseFloat(Me||"0"):parseFloat(L?.amount||"")||0,Pt=nt>0&&nt<fn,$=L?.asset?._source==="wallet",se=!!L?.asset&&$&&L.asset.chainId!==J,Ce=i.useMemo(()=>L?.asset?Te.find(me=>h.addressesEqual(me.address,L.asset.address))?.balanceFormatted??0:0,[L,Te]),Ne=$?L?.asset.balanceFormatted??0:Ce,Ye=i.useMemo(()=>{if(!L?.asset)return!1;if(E)return Oe?ln(Oe.grossAmount,Oe.decimals,L.asset.decimals)>L.asset.balance:Ae||bt?nt>L.asset.balanceFormatted:Se?parseFloat(T.formatUnits(Se.amountInMax,L.asset.decimals))>L.asset.balanceFormatted:!1;if(Oe){const me=ln(Oe.grossAmount,Oe.decimals,L.asset.decimals);return $?me>L.asset.balance:parseFloat(T.formatUnits(me,L.asset.decimals))>Ne}return nt>Ne},[L,E,Oe,Ae,nt,Se,Ne,$,bt]);i.useEffect(()=>{e||(Re(null),zt(null),Rt(!1),Dt("idle"),tn(""),Ve(null),Et(!1),ye(null),Ke(null),we(!1),yt(!1),qe(null),jt.current=!1,C==="adjustable"&&Qe(y||""),Ht.current&&(Ht.current.abort(),Ht.current=null))},[e]);const rt=i.useCallback(me=>{Re($e=>({asset:me,amount:$e?.asset?.address===me.address&&$e?.asset?.chainId===me.chainId&&$e.amount||""})),zt(null),qe(null),yt(!1)},[]),dt=i.useCallback(me=>{Re($e=>$e&&{...$e,amount:me}),zt(null),qe(null),yt(!1)},[]),at=i.useCallback(me=>{let $e=me;v&&parseFloat($e)>parseFloat(v)&&($e=v),Qe($e),M?.($e),zt(null),qe(null),yt(!1)},[v,M]);i.useCallback(me=>{if(jt.current||!_)return;const $e=nn.current;!$e?.asset||!$e.amount||$e.asset?._source==="wallet"||T.parseUnits(E?Me:$e.amount,$e.asset.decimals)===0n||(jt.current=!0,_e())},[_,J,_e,E,Me]);const Ee=i.useCallback(me=>{Dt({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[me.step]||"executing"),tn(me.message),me.txHash&&Ve(me.txHash)},[]),xt=i.useMemo(()=>({currentPaymentAmount:Me,destinationToken:s,embeddedWalletAddress:We,providerEmbeddedAddress:it,externalWalletAddress:lt,address:_,isNon7702:ie,isPayMode:E,resolvedChainId:J,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:L,needsSwap:tt,resolvedSwap:ht,exactOutputSwap:Se,quoteAmountOut:Ct,resolvedTokenIn:ot}),[Me,s,We,it,lt,_,ie,E,J,l,d,u,L,tt,ht,Se,Ct,ot]),De=i.useCallback(me=>hr({...xt,requestTimestampMs:Gt.current??Date.now()},me),[xt]),Z=i.useCallback(me=>mr({...xt,requestTimestampMs:Gt.current??Date.now()},me),[xt]),xe=i.useCallback((me,$e,dn,mn)=>gr(me,$e,dn,oe,mn),[oe]),ut=i.useMemo(()=>L?.asset?tt&&ot?ot:L.asset.chainId===J?L.asset.address:ot??rn(L.asset,J)??s.address:s.address,[L,s.address,tt,J,ot]),mt=i.useCallback(()=>(Gt.current=Date.now(),kr(ct.current)),[]),Le=i.useMemo(()=>L?.asset?h.addressesEqual(L.asset.address,s.address)&&L.asset.chainId===s.chainId:!1,[L,s.address,s.chainId]),kt=Le&&(ie||E),Ge=kt&&nt>0&&!!L?.asset,Vt=ce&&!kt,V=i.useMemo(()=>{if(!Ge)return null;let me;try{me=T.parseUnits(Me||"0",s.decimals)}catch{return null}return{symbol:s.symbol,decimals:s.decimals,grossAmount:me,netAmount:me,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[Ge,Me,s.symbol,s.decimals]),X=Nt,de=i.useMemo(()=>!(!L?.asset||nt<=0),[L,nt,Ge]),ae=i.useMemo(()=>!e||ze||ve!=="idle"||!de||Ge||!L?.asset?null:[E?"pay":"supply",x,L.asset.address.toLowerCase(),L.asset.chainId,L.amount,Me,s.address.toLowerCase(),s.chainId,J,ot?.toLowerCase()??"",tt?"swap":"direct",bt?"direct-token":"routed-token",ie?"non7702":"7702",Le?"source-dest":"cross-chain",ft?"quoting":"quoted",Se?.amountIn?.toString()??"",Se?.amountInMax?.toString()??"",Se?.venue??"",ht?.amountOut?.toString()??"",Ct?.toString()??"",We??"",it??"",_??""].join("|"),[e,ze,ve,de,Ge,L,E,x,Me,s,J,ot,tt,bt,ie,Le,ft,Se,ht,Ct,We,it,_]),Pe=i.useCallback(()=>yr({selectedAsset:L,isPayMode:E,parsedAmount:nt,needsSwap:tt,exactOutputSwap:Se,isNon7702:ie,isSourceDestToken:Le,currentPaymentAmount:Me,destinationToken:s,feeExecutionMode:d,resolvedTokenIn:ot,embeddedWalletAddress:We,providerEmbeddedAddress:it,resolvedChainId:J,isConnected:re,address:_,ready:ge,authenticated:K,isDirect:bt,resolvedSwap:ht,isQuoting:ft,executionTokenAddress:ut,buildPayChainBatches:De,buildSupplyChainBatches:Z,estimate:oe,estimateRequiredGrossFunding:xe}),[L,E,nt,tt,Se,ie,Le,Me,s,d,ot,We,it,xe,De,oe,J,re,_,ge,K,bt,ht,ft,Z,ut]);i.useEffect(()=>{gt.current=Pe},[Pe]);const je=i.useCallback(me=>xr({asset:me,isPayMode:E,isNon7702:ie,needsSwap:tt,isQuoting:ft,embeddedWalletAddress:We,buildSupplyChainBatches:Z,estimate:oe,executionTokenAddress:ut,feeExecutionMode:d}),[E,ie,tt,ft,We,Z,oe,ut,d]);i.useEffect(()=>{if(!e){we(!1),yt(!1),qe(null),Ke(null);return}if(ze||ve!=="idle"){Ft.current+=1,we(!1);return}if(!de){Ke(null),we(!1),yt(!1),qe(null);return}if(Ge){Ke(V),we(!1),yt(!0),qe(null);return}if(ft){Ft.current+=1,we(!1),yt(!1);return}if(!ae)return;let me=!1;const $e=async()=>{const mn=++Ft.current;qe(null),we(!0);try{const gn=await gt.current?.();if(me||Ft.current!==mn)return;gn?(Ke(gn),yt(!0)):(Ke(null),yt(!1)),qe(null)}catch(gn){if(me||Ft.current!==mn)return;const hs=h.sanitizeError(gn,"Unable to calculate fees for this action.");Ke(null),yt(!1),qe(hs)}finally{!me&&Ft.current===mn&&we(!1)}},dn=window.setTimeout(()=>{$e()},250);return()=>{me=!0,clearTimeout(dn),we(!1)}},[e,ze,ve,de,Ge,V,ft,ae]);const He=i.useCallback(()=>(Gt.current=Date.now(),Ir(ct.current)),[]);i.useEffect(()=>{!E&&ve==="success"&&Zt&&(_e(),B?.(Zt))},[E,ve,Zt,_e,B]),i.useEffect(()=>{if(!E||Ue?.status!=="success"||jt.current||!_)return;jt.current=!0;const me=nn.current;!me?.asset||me.asset?._source==="wallet"||_e()},[E,Ue?.status,_,_e]);const st=i.useRef(B),vt=i.useRef(S);i.useEffect(()=>{st.current=B},[B]),i.useEffect(()=>{vt.current=S},[S]),i.useEffect(()=>{e&&(_e(),wt())},[e,_e,wt]),i.useEffect(()=>{E&&(Ue?.status==="success"&&st.current?.(Ue.txHash||""),Ue?.status==="failed"&&vt.current?.(new Error("Payment execution failed")))},[E,Ue?.status]);const Ut=i.useCallback(()=>{Et(!1),ye(null),Re(null),jt.current=!1,_e(),wt()},[_e,wt]);ct.current={selectedAsset:L,parsedAmount:nt,currentPaymentAmount:Me,isInsufficientBalance:Ye,isPayMode:E,isNon7702:ie,isSourceDestToken:Le,needsSwap:tt,exactOutputSwap:Se,selectedIsEquivalent:Ae,resolvedTokenIn:ot,embeddedWalletAddress:We,providerEmbeddedAddress:it,externalWallet:Be,externalWalletAddress:lt,activeSignerWallet:St,activeSignerAddress:It,address:_,isConnected:re,ready:ge,authenticated:K,provider:ne,resolvedChainId:J,executionTokenAddress:ut,destinationToken:s,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:c,onSuccess:B,onError:S,execution:{estimate:oe,execute:he,buildPayChainBatches:De,buildSupplyChainBatches:Z,estimateRequiredGrossFunding:xe,onProgress:Ee},ui:{setError:zt,setStep:Dt,setStatusMsg:tn,setTxHash:Ve,setIsExecuting:Rt,setShowStatusPanel:Et,setPaymentResult:ye},refs:{spiceDepositSubmittedRef:jt,abortControllerRef:Ht}};const Jt=y?.trim(),Tt=E&&C==="fixed"&&Jt!==void 0&&Jt!==""&&nt===0,$t=E?(Tt||!!L?.asset)&&nt>=0&&!Pt&&!Ye&&!ze&&(Tt||Ge||Mt)&&!pt&&(Tt||!tt||!!Se)&&!Vt:!!L?.asset&&nt>0&&!Pt&&!Ye&&!ze&&(kt||Mt)&&!pt&&(se||bt||!!ht&&!ft)&&!Vt;i.useEffect(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:$t,isPayMode:E,hasSelectedAsset:!!L?.asset,selectedAsset:L?.asset?{symbol:L.asset.symbol,address:L.asset.address,chainId:L.asset.chainId,balanceFormatted:L.asset.balanceFormatted,source:L.asset?._source}:null,parsedAmount:nt,isZeroAmountPay:Tt,isBelowMinimum:Pt,isInsufficientBalance:Ye,isExecuting:ze,directExternalAction:kt,directExecutionFeeNote:Ge,feeEstimateReady:Mt,feeEstimateError:pt,needsSwap:tt,isDirect:bt,isSourceDestToken:Le,hasExactOutputSwap:!!Se,isQuoting:ft,whitelistHoldPending:ce,supplyHeldForWhitelist:Vt,isWhitelistGateActive:fe,destinationToken:{symbol:s.symbol,address:s.address,chainId:s.chainId}})},[e,$t,E,L,nt,Tt,Pt,Ye,ze,kt,Ge,Mt,pt,tt,bt,Le,Se,ft,ce,Vt,fe,s]);const kn=bt?m||`Your ${s.symbol} will be used directly.`:g||"Your assets will be swapped and used in a single atomic transaction.",jn=(J?h.getChainConfig(J):void 0)?.viemChain?.blockExplorers?.default?.url??"",vn=Yr.indexOf(ve),Fe=ze?(qr[ve]||"EXECUTING...").toUpperCase():ve==="success"?"DONE":Pt?`MINIMUM ${fn}`:Ye?"INSUFFICIENT BALANCE":p.toUpperCase(),Je=i.useMemo(()=>{if(ze)return"PAYING...";if(Pt)return`MINIMUM ${fn}`;if(Ye&&L?.asset)return`INSUFFICIENT ${L.asset.symbol}`;if(p)return p.toUpperCase();const me=nt>0?` ${Me} ${s.symbol}`:"";return tt?`SWAP & PAY${me}`:`PAY${me}`},[ze,Pt,Ye,L,p,nt,Me,s.symbol,tt]),Ot=ve==="success"?()=>{Dt("idle"),Re(null),Ve(null),_e()}:mt,cn=ve==="success"?!1:!$t;if(!e)return null;const Yn=E?R||`Pay ${s.symbol}`:p,Pn=E?j:o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[o.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:o.jsx(Ns,{color:pe})}),o.jsx("p",{style:{fontSize:"12px",color:pe,margin:0,lineHeight:"1.4",fontFamily:P},children:kn})]});if(E){const me=Ue&&(Ue.status==="success"||Ue.status==="failed")?[{asset:{symbol:L?.asset?.symbol||s.symbol,address:L?.asset?.address||""},amount:Me,txHash:Ue.txHash||"",success:Ue.status==="success",error:Ue.status==="failed"?Ue.error:void 0}]:void 0;return o.jsx(un,{isOpen:e,onClose:t,title:Yn,subtitle:Pn,styles:b,dark:A,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[N&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:o.jsx(Ds,{onClick:N,color:W,fontFamily:P})}),!Tt&&o.jsx("div",{style:{marginBottom:"12px"},children:o.jsx(Ln,{assets:Ze,selectedAsset:L??void 0,onAssetSelect:rt,onAmountChange:Jl,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:L?.asset?tt?ft?"...":Se?`~${parseFloat(T.formatUnits(Se.amountIn,L.asset.decimals)).toFixed(6)}`:void 0:Me??void 0:void 0,dark:A,theme:q,styles:b})}),o.jsx(Ar,{variant:"pay",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:W,fontFamily:P,textPrimary:U,textSecondary:G,cardBg:H,cardBorder:ee,dk:O,dark:A,isQuoting:ft,quoteError:Qt,estimatedOutput:Wt,paymentAmount:Me,needsSwap:tt,exactOutputSwap:Se,adjustable:C==="adjustable",maxAmount:v,onAmountChange:at}),de&&o.jsx(as,{fontFamily:P,textPrimary:U,textSecondary:G,cardBg:H,cardBorder:ee,resolvedDark:A,darkCardBorder:O.cardBorder,primaryColor:W,feePreview:Oe,isLoading:Xt,errorText:pt,directExecutionFeeNote:Ge}),X&&o.jsx(Nn,{variant:"error",palette:z,fontFamily:P,style:{marginBottom:"12px"},children:X}),o.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:He,disabled:!$t,loading:ze,dark:A,styles:{...b,button:{...b?.button,backgroundColor:W}},children:Je}),Ue&&Lt&&o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:A?O.shell:"white",borderRadius:A?"12px":"6px",padding:"16px 0"},children:o.jsx(zs,{type:"payment",isOpen:Ue.status!=="processing",isProcessing:ze||Ue.status==="processing",closeOnComplete:!1,chainName:h.getChainName(J),explorerUrl:h.getExplorerUrl(J,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Et(!1),ye(null),He()},onNewTx:Ut,onClose:()=>{Et(!1),ye(null)},onComplete:Ut,results:me,styles:b,dark:A})})]})})}return o.jsx(un,{isOpen:e,onClose:t,title:Yn,subtitle:Pn,dark:A,styles:b,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(Ln,{assets:Ze,selectedAsset:L||void 0,onAssetSelect:rt,onAmountChange:dt,disabled:ze||ve==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:q,styles:b,dark:Q,resolveMaxAmount:je,maxAmount:Ne>0?h.formatDecimalInput(Ne,L?.asset.decimals??s.decimals):void 0})}),L?.asset&&!bt&&o.jsx(Ar,{variant:"supply",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:W,fontFamily:P,textPrimary:U,textSecondary:G,cardBg:H,cardBorder:ee,dark:A,isQuoting:ft,quoteError:Qt,estimatedOutput:Wt}),de&&o.jsx(as,{fontFamily:P,textPrimary:U,textSecondary:G,cardBg:H,cardBorder:ee,resolvedDark:A,darkCardBorder:O.cardBorder,primaryColor:W,feePreview:Oe,isLoading:Xt,errorText:pt,directExecutionFeeNote:Ge}),ve!=="idle"&&o.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:ve==="success"?H:ve==="error"?z.errorBg:H,border:`1px solid ${ve==="success"?ee:ve==="error"?z.errorBorder:ee}`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ve==="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:z.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):ve==="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:z.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):o.jsx(h.Spinner,{size:14,color:W}),o.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:ve==="success"?U:ve==="error"?z.errorText:U,fontFamily:P,flex:1},children:ve==="success"?"Deposit confirmed":ve==="error"?Xe||"Transaction failed":qr[ve]||Xe}),ve==="success"&&Zt&&o.jsx("a",{href:`${jn}/tx/${Zt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:W,fontFamily:P,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),ve==="error"&&o.jsx("button",{onClick:()=>{Dt("idle"),zt(null),setTimeout(mt,50)},style:{background:"none",border:"none",fontSize:"12px",color:W,fontFamily:P,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),vn>=0&&ve!=="success"&&ve!=="error"&&o.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${G}22`,overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:W,transformOrigin:"left center",transform:`scaleX(${(vn+1)/Yr.length})`,transition:"transform 400ms ease"}})})]}),Nt&&ve==="idle"&&o.jsx(Nn,{variant:"error",palette:z,fontFamily:P,style:{marginBottom:"16px"},children:Nt}),o.jsx(h.Button,{variant:"outline",fullWidth:!0,disabled:cn,onClick:Ot,theme:I,dark:A,styles:{...b,button:{...b?.button,backgroundColor:W}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:D},children:Fe})]})})},_l=()=>{const[e,t]=i.useState("0"),[n,s]=i.useState(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:n,setSelectedAsset:s}};function ec(e,t=0){const[n,s]=i.useState(t),r=e[n]??e[0],a=i.useMemo(()=>r?BigInt(Math.round(r.months*30*24*3600)):0n,[r?.months]);return{selectedDurationIdx:n,setSelectedDurationIdx:s,selectedDuration:r,durationSeconds:a}}function tc(){const{actions:e,isReady:t,isAuthenticated:n}=h.useWallet(),s=i.useContext(h.SpiceFlowProviderContext)?.embeddedWalletAddress,r=i.useRef(!1),a=i.useRef(0),l=i.useRef(null),d=i.useRef(e),[u,c]=i.useState(0);d.current=e,i.useEffect(()=>{r.current=!1,a.current=0,l.current&&(clearTimeout(l.current),l.current=null)},[s]),i.useEffect(()=>{if(!s||!t||!n||r.current)return;r.current=!0;let f=!1;return(async()=>{await en(2e3);try{await h.ensureSmartWallet(s,d.current.signMessage),a.current=0}catch(p){console.warn("[SmartWallet] Registration failed:",p),r.current=!1,!f&&a.current<3&&(a.current+=1,l.current=setTimeout(()=>{c(x=>x+1)},5e3))}})(),()=>{f=!0,l.current&&(clearTimeout(l.current),l.current=null)}},[s,t,n,u])}function qn(e){try{return F.resolveTokenRef(e)}catch{throw new h.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Token "${e[0]}" not found on chain ${e[1]} in the token registry.`,{symbol:e[0],chainId:e[1]})}}function nc(e,t){if(e[0].toUpperCase()===t[0].toUpperCase()&&e[1]===t[1])return!0;let n,s;try{n=qn(e),s=qn(t)}catch{return!1}const r=new Set(F.getEquivalentAddresses(s.address).map(a=>a.toLowerCase()));return r.add(s.address.toLowerCase()),r.has(n.address.toLowerCase())}function sc(){const e=[];for(const t of Object.keys(F.CHAINS).map(Number))for(const n of F.getTokensForChain(t))e.push([n.symbol,t]);return e}async function oc(e){const{action:t,inputToken:n,inputAmount:s,registry:r,userAddress:a,slippage:l,intermediaryCandidates:d}=e;if(t.calls.length===0)throw new h.SpiceflowError("INVALID_PARAMS","buildIntent: action.calls must not be empty.",{action:t});if(s<=0n)throw new h.SpiceflowError("INVALID_PARAMS","buildIntent: inputAmount must be greater than zero.",{inputAmount:s.toString()});const u=t.supportedInputTokens??sc();if(!u.some(C=>nc(n,C))){const C=u.map(([k,v])=>`${k} (chain ${v})`).join(", ");throw new h.SpiceflowError("ROUTE_UNSUPPORTED_INPUT",`Input token "${n[0]}" on chain ${n[1]} is not in the action's supported input tokens. Supported: ${C}.`,{inputToken:{symbol:n[0],chainId:n[1]},supportedInputTokens:u})}const c=qn(n),f=qn(t.outputToken),p=$o({sourceAsset:c,outputAsset:f,sourceChainId:c.chainId,destinationChainId:t.chainId,intermediaryCandidates:d}),{chainBatches:x,solverFrontToken:g,solverFrontAmount:m,resolvedSwaps:y}=await _o({route:p,sourceAmount:s,userAddress:a,registry:r,actionCalls:t.calls,slippage:l});return{chainBatches:x,route:p,resolvedSwaps:y,resolvedInputToken:c,resolvedOutputToken:f,solverFrontToken:g,solverFrontAmount:m}}const rc=[0n,1n,30n],ac=new Set(["ABORT","CONCURRENT_EXECUTION","WALLET_DISCONNECTED","WALLET_REJECTED","NO_VENUE_FOR_CHAIN"]);function Kr(e,t){return t===0n?e:e*(1000n-t)/1000n}async function ic(e,t){const{chainId:n,swapCalls:s,quoteAmountOut:r,buildActionCalls:a,tokenAddress:l,tokenTransferAmount:d,onProgress:u,signal:c,options:f,buffers:p=rc}=t;for(let x=0;x<p.length;x++){const g=p[x],m=Kr(r,g),y=a(m),C=[{chainId:n,calls:[...s,...y]}];try{return await e(C,l,d,u,c,f)}catch(k){const v=typeof k?.message=="string"?k.message:String(k?.message??"");if(h.isSpiceflowError(k)&&ac.has(k.code)||k.name==="AbortError"||c?.aborted||v.includes("User rejected")||v.includes("User denied")||k.code===4001||x>=p.length-1)throw k;const M=Number(p[x+1])/10;console.warn(`[SwapThenAction] Action attempt ${x+1} failed (buffer ${Number(g)/10}%), retrying with ${M}% buffer...`,k.message),u?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${M}% buffer)...`})}}throw new h.SpiceflowError("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:p.length,chainId:n})}ra(),exports.SpiceFlowProvider=h.SpiceFlowProvider,exports.SpiceFlowProviderContext=h.SpiceFlowProviderContext,exports.SpiceflowError=h.SpiceflowError,exports.Spinner=h.Spinner,exports.buildDarkPalette=h.buildDarkPalette,exports.buildLightPalette=h.buildLightPalette,exports.getChainConfig=h.getChainConfig,exports.getChainName=h.getChainName,exports.isSpiceflowError=h.isSpiceflowError,exports.relayerService=h.relayerService,exports.resolveTheme=h.resolveTheme,exports.useIsUserWhitelisted=h.useIsUserWhitelisted,exports.useSpiceBrand=h.useSpiceBrand,exports.useWallet=h.useWallet,Object.defineProperty(exports,"NATIVE_TOKEN_ADDRESS",{enumerable:!0,get:function(){return F.ZERO_ADDRESS}}),Object.defineProperty(exports,"SPICENET_NATIVE_CHAIN_ID",{enumerable:!0,get:function(){return F.SPICENET_NATIVE_CHAIN_ID}}),Object.defineProperty(exports,"SPICE_COMBINED_FEE_RECIPIENT",{enumerable:!0,get:function(){return F.SPICE_COMBINED_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_GAS_FEE_RECIPIENT",{enumerable:!0,get:function(){return F.SPICE_GAS_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_PLATFORM_FEE_RECIPIENT",{enumerable:!0,get:function(){return F.SPICE_PLATFORM_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_SOLVER_ADDRESS",{enumerable:!0,get:function(){return F.SPICE_SOLVER_ADDRESS}}),Object.defineProperty(exports,"applySlippage",{enumerable:!0,get:function(){return F.applySlippage}}),Object.defineProperty(exports,"buildUniV3SwapCalls",{enumerable:!0,get:function(){return F.buildUniV3SwapCalls}}),Object.defineProperty(exports,"getChainIdsByNetwork",{enumerable:!0,get:function(){return F.getChainIdsByNetwork}}),Object.defineProperty(exports,"getEscrowContractAddress",{enumerable:!0,get:function(){return F.getEscrowContractAddress}}),Object.defineProperty(exports,"isNativeToken",{enumerable:!0,get:function(){return F.isNativeToken}}),Object.defineProperty(exports,"isSpicenetChainId",{enumerable:!0,get:function(){return F.isSpicenetChainId}}),Object.defineProperty(exports,"normalizeNativeTokenAddress",{enumerable:!0,get:function(){return F.normalizeNativeTokenAddress}}),Object.defineProperty(exports,"spicenetAbi",{enumerable:!0,get:function(){return F.spicenetAbi}}),Object.defineProperty(exports,"spicenetWithdrawalAbi",{enumerable:!0,get:function(){return F.spicenetAbi}}),exports.AccountDisplay=Ul,exports.AddFundsLink=Ds,exports.CheckIcon=Do,exports.ChevronIcon=bn,exports.CloseIcon=Tn,exports.DetailRow=Dn,exports.ProviderLogin=Os,exports.SATSUMA_CITREA_CONFIG=eo,exports.SearchInput=Cs,exports.SelectChainModal=Ui,exports.SpiceDeposit=Pi,exports.SpiceLock=ar,exports.SpiceLockModal=ar,exports.SpiceSupply=$l,exports.SpiceWithdraw=el,exports.StatusBanner=Nn,exports.UNIV3_BASE_CONFIG=Ur,exports.applyBuffer=Kr,exports.areEquivalentOnChains=Hn,exports.buildIntent=oc,exports.buildPayChainBatches=hr,exports.buildRoutedBatches=_o,exports.buildSupplyChainBatches=mr,exports.create1inchVenue=Wr,exports.createExactOutputRegistry=Hr,exports.createLiquidityRegistry=Lr,exports.createSatsumaVenue=Or,exports.duration=Yt,exports.easing=Bt,exports.estimateFeePreview=yr,exports.estimateRequiredGrossFunding=gr,exports.estimateSupplyMaxAmount=xr,exports.executeDirectExternalAction=$s,exports.executeNon7702Pay=Sr,exports.executeNon7702Supply=vr,exports.executePay=Ir,exports.executeSupply=kr,exports.executeSwapThenAction=ic,exports.findEquivalentOnChain=hn,exports.findTokenOnChain=Qs,exports.font=oo,exports.getAssetChainTokenCandidates=Xn,exports.getBestUniV3Quote=Mr,exports.getUniV3Quote=Rr,exports.isSupportedSupplyAsset=Fr,exports.isSwapIntent=Nr,exports.radius=ys,exports.resolveAssetTokenAddressOnChain=rn,exports.resolveFundedToken=wo,exports.resolveInputSupplySwapQuote=Gl,exports.resolveRoute=$o,exports.resolveTokenRef=qn,exports.scaleTokenAmount=ln,exports.transition=_t,exports.useAssetInput=_l,exports.useLockDuration=ec,exports.useSmartWallet=tc,exports.useSpiceAssets=Qn,exports.useSpiceExecution=Mn,exports.useSpicePendingDeposits=ir,exports.useSupplyAssets=Br,exports.useSupplyQuote=Vr,exports.z=Sn;
package/dist/index.js CHANGED
@@ -105,4 +105,4 @@ import{jsxs as x,jsx as l,Fragment as kn}from"react/jsx-runtime";import Mn,{useS
105
105
  from { opacity: 0; transform: translateY(-4px); }
106
106
  to { opacity: 1; transform: translateY(0); }
107
107
  }
108
- `})]}),document.body):null;return x(kn,{children:[Ut,nt,E&&mr.createPortal(l(Jr,{isOpen:!0,onClose:V,supportedChains:[E.chainId],escrowOnly:!0,escrowTokenAddress:E.tokenAddress,escrowAmount:E.amount,escrowTokenDecimals:E.tokenDecimals,escrowTokenSymbol:E.tokenSymbol,styles:d,onDepositSuccess:$}),document.body)]})},hd="0xa9059cbb";function Ca(e,t,n){return Ue(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:Tt({abi:Fe,functionName:"transfer",args:[n,t]})}}function va(e,t,n){return{chainId:n,calls:[Ca(e,t,hn(n))]}}function ka(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function Ia(e,t,n,o){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(hd)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function is(e,t,n,o){if(!t)return[e];const s=await t({...n,requestTimestampMs:o});return s?[s,e]:[e]}function Gs(e){return e.filter(t=>t.domain!=="spicenet")}function ls(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:It(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function Wn(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return(e+o-1n)/o}async function Aa(e,t){const{currentPaymentAmount:n,destinationToken:o,embeddedWalletAddress:s,providerEmbeddedAddress:r,address:a,isNon7702:c,isPayMode:d,resolvedChainId:i,buildActionCalls:p,feeExecutionMode:u,buildSpicenetBatch:m,selectedAsset:h,needsSwap:f,exactOutputSwap:g,resolvedTokenIn:y,requestTimestampMs:C}=e,v=ze(n,o.decimals),T=t?.actionAmountOverride??v,b=s||r||(c?void 0:a);if(!b)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:b,chainId:i,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??v,netAmount:T,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},B=p(T,w),E={chainId:i,calls:B},M=!d&&!c?!0:h?.asset?._source==="spice",F=ka(h??null,c,i),k=M||c||F,S=(A,W)=>({token:A,from:c?"solver":"escrow",to:b,amount:W}),I=(A,W,P)=>F?[va(A,W,i),...P]:P;if(v===0n)return[E];if(f&&g){const A=y??Rn(h.asset,i)??h.asset.address,W=t?.fundingAmountOverride??g.amountInMax,P=k?[S(A,W)]:[],z={to:A,value:0n,data:Tt({abi:Fe,functionName:"approve",args:[g.calls[0]?.to,g.amountInMax]})},N={chainId:i,calls:[z,...g.calls,...B],tokenTransfers:[...P,...E.tokenTransfers??[]]};if(!k)return[N];const D=await is(N,m,{userAddress:b,destinationChainId:i,deliveryToken:A,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:ls(N),sourceAsset:h.asset},C);return I(A,W,D)}if(k){const A=y??Rn(h.asset,i)??o.address;if(F&&A.toLowerCase()===o.address.toLowerCase())return[E];const W=t?.fundingAmountOverride??v,P={...E,tokenTransfers:[S(A,W),...E.tokenTransfers??[]]},z=await is(P,m,{userAddress:b,destinationChainId:i,deliveryToken:A,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:ls(P),sourceAsset:h.asset},C);return I(A,W,z)}return[E]}async function Sa(e,t){const{selectedAsset:n,embeddedWalletAddress:o,externalWalletAddress:s,recipient:r,resolvedChainId:a,destinationToken:c,buildActionCalls:d,feeExecutionMode:i,buildSpicenetBatch:p,isPayMode:u,isNon7702:m,needsSwap:h,resolvedSwap:f,quoteAmountOut:g,resolvedTokenIn:y,requestTimestampMs:C}=e,v=f?.amountOutMinimum??g;if(!n?.asset||!o)return[];const T=r??(m?s:o);if(!T)return[];const b=t?.fundingAmountOverride??t?.actionAmountOverride??ze(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??b,B=t?.sourceFundingAmountOverride??b,E=t?.deliveryAmountOverride??w,M=t?.withdrawalAmountOverride??E,F=t?.actionAmountOverride??b,k={userAddress:T,chainId:a,destinationToken:c.address,feeToken:i==="user-transfer"&&h&&y?y:c.address,grossAmount:w,netAmount:F,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:i,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},S=d(F,k),I=n.asset?._source==="wallet";if(!u&&m&&I&&n.asset.chainId===a){if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!f||v===null)throw new Error("Swap quote not available yet")}if(h&&f&&v){const U=d(t?.actionAmountOverride??v,{...k,netAmount:t?.actionAmountOverride??v}),{feeCall:Z,remainingCalls:he}=Ia(U,i,h,k.feeToken);return[{chainId:a,calls:[...Z?[Z]:[],...f.calls,...he]}]}return[{chainId:a,calls:S}]}if(!u&&!m&&I&&n.asset.chainId!==a)throw new Error("Cross-chain wallet supplies require external wallet mode");const A=!u&&!m?n.asset?._source!=="wallet":n.asset?._source==="spice",W=m&&I,P=ka(n,m,a);if(!(A||W||P))return[{chainId:a,calls:S}];const z=P?va(y??It(n.asset.address),B,a):W&&n.asset.chainId!==a?{chainId:n.asset.chainId,calls:[Ca(It(n.asset.address),B,hn(n.asset.chainId))]}:null,N=(U,Z)=>({token:U,from:W?"solver":"escrow",to:o,amount:Z}),D=(U,Z)=>W?[{token:U,from:"escrow",to:Ii,amount:Z}]:[];if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!f||v===null)throw new Error("Swap quote not available yet")}if(h&&f&&v&&y){const U=d(t?.actionAmountOverride??v,{...k,netAmount:t?.actionAmountOverride??v}),{feeCall:Z,remainingCalls:he}=Ia(U,i,h,k.feeToken),Q={chainId:a,calls:[...Z?[Z]:[],...f.calls,...he],tokenTransfers:[...D(y,M),N(y,E)]},G=await is(Q,p,{userAddress:o,destinationChainId:a,deliveryToken:y,deliveryAmount:E,withdrawalAmount:M,deliveryRecipient:o,deliveryTransfers:ls(Q),sourceAsset:n.asset},C);return z?[z,...G]:G}const H=y??Rn(n.asset,a)??c.address,O={chainId:a,calls:S,tokenTransfers:[...D(H,M),N(H,E)]},_=await is(O,p,{userAddress:o,destinationChainId:a,deliveryToken:H,deliveryAmount:E,withdrawalAmount:M,deliveryRecipient:o,deliveryTransfers:ls(O),sourceAsset:n.asset},C);return z?[z,..._]:_}async function Ea(e,t,n,o,s){let r=e;for(let a=0;a<4;a++){const c=await t(r),d=await o(c,n,r,s),i=Dl(d);if(i===null||i>=e)return r;const p=r-i,u=e+p;if(u<=r)return r;r=u}return r}function md(e,t,n,o){if(e<=0n)return 0n;const s=e-t;if(s<=0n)return 0n;const r=o+n;return r<=0n?s:s*o/r}async function Fa(e){const{asset:t,isPayMode:n,isNon7702:o,needsSwap:s,isQuoting:r,embeddedWalletAddress:a,buildSupplyChainBatches:c,estimate:d,executionTokenAddress:i,feeExecutionMode:p}=e;if(n||o||s||r||!a||t.balance<=0n)return null;const u=a,m=await c({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(m.length===0)return null;const h=m.some(T=>T.tokenTransfers?.length),f=await d(m,i,t.balance,h?{userOverride:u,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:u,feeExecutionMode:p}:{userOverride:u}),g=Jn(f,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),y=g?Wn(g.gasFee,g.decimals,t.decimals):0n,C=g?Wn(g.spicenetFee,g.decimals,t.decimals):0n,v=md(t.balance,y,C,t.balance);return v>0n?zr(v,t.decimals):null}async function Ba(e){const{selectedAsset:t,isPayMode:n,parsedAmount:o,needsSwap:s,exactOutputSwap:r,isNon7702:a,isSourceDestToken:c,currentPaymentAmount:d,destinationToken:i,feeExecutionMode:p,resolvedTokenIn:u,embeddedWalletAddress:m,providerEmbeddedAddress:h,resolvedChainId:f,isConnected:g,address:y,ready:C,authenticated:v,isDirect:T,resolvedSwap:b,isQuoting:w,executionTokenAddress:B,buildPayChainBatches:E,buildSupplyChainBatches:M,estimate:F,estimateRequiredGrossFunding:k}=e;if(!t?.asset)return null;if(n){if(o<=0||s&&!r||c)return null;const D=ze(d,i.decimals),H=u||Rn(t.asset,f)||t.asset.address||i.address,O={chainId:f,tokenAddress:H,symbol:Qt(H,f)?.symbol??t.asset.symbol,decimals:Qt(H,f)?.decimals??t.asset.decimals};if(a){const G=m||h;if(!G)return null;const de=s?r?.amountInMax??0n:D;if(de===0n)return null;const ve={userOverride:G,useCustomTransfers:!0},ce=await k(de,Se=>E({fundingAmountOverride:Se}),H,ve),me=await E({fundingAmountOverride:ce}),ue=await F(me,H,ce,{...ve,feeExecutionMode:p});return Jn(ue,O)}if(!g||!y||!C||!v)return null;const _=m||h||y,U=s?r?.amountInMax??0n:D;if(U===0n)return null;const Z=await k(U,G=>E({fundingAmountOverride:G}).then(de=>Dn(Gs(de),_)),H,{useCustomTransfers:!0});let he=Dn(Gs(await E({fundingAmountOverride:Z})),_);const Q=await F(he,H,Z,{useCustomTransfers:!0,feeExecutionMode:p});return Jn(Q,O)}if(o<=0||!m)return null;const S=m||h;if(!(!n&&!a&&t.asset?._source==="wallet"&&t.asset.chainId!==f)&&!T&&!b&&!w||w)return null;const I=ze(t.amount,t.asset.decimals),A=await M();if(A.length===0)return null;const W=a&&t.asset?._source==="wallet"&&t.asset.chainId===f,P={chainId:f,tokenAddress:B,symbol:Qt(B,f)?.symbol??i.symbol,decimals:Qt(B,f)?.decimals??i.decimals};if(W){const D=await vt.estimateBatchGas({user:S,outputToken:B,stepIndex:0,chainBatches:A}),H=Xo(I,10n),O=H+D.gasFee;return{...P,grossAmount:I+O,netAmount:I,totalFee:O,gasFee:D.gasFee,spicenetFee:H,bridgeFee:0n,gasQuoteSource:D.gasQuoteSource}}const z=A.some(D=>D.tokenTransfers?.length),N=await F(A,B,I,z?{userOverride:S,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:S,feeExecutionMode:p}:{userOverride:S});return Jn(N,P)}const gd=10n;function Ta(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const o=Rn(n,e.resolvedChainId);if(!o||!Ie(o,e.executionTokenAddress))return;const s=Qt(e.executionTokenAddress,e.resolvedChainId),r=Wn(t,s?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const a=pt(r,n.decimals),c=pt(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${a} ${n.symbol}; available ${c} ${n.symbol}.`)}function Js(e){const t=Qt(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Mo(e,t,n){const o=Jn(e,Js(t));if(!o)return;const s=Xo(n,gd),r=o.bridgeFee??0n,a=s+o.gasFee+r;return{grossAmount:n+a,netAmount:n,combinedFeeAmount:a,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:s,gasFee:o.gasFee,bridgeFee:r}}}function Ma(e,t,n){let o=0n,s=0n;const r=n.toLowerCase();for(const a of e)if(a.chainId===t){for(const c of a.calls??[])if(c.to.toLowerCase()===r)try{const d=Lo({abi:Fe,data:c.data});if(d.functionName!=="transfer")continue;const i=d.args[0].toLowerCase(),p=d.args[1];i===so.toLowerCase()?o+=p:i===An.toLowerCase()&&(s+=p)}catch{continue}}return{spicenetFee:o,gasFee:s}}function $s(e,t,n){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,s=Ma(e,t.resolvedChainId,o);return s.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||s.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Gn(s.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Gn(s.gasFee,n.feeBreakdown.gasFee,100n)}function Ra(e,t){return e?Gn(e.grossAmount,t.grossAmount,100n)&&Gn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Gn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Gn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function Da(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const o=await _s(e);e.ui.setTxHash(o??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const o=new AbortController;e.refs.abortControllerRef.current=o,await Wa(e,o.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(o){const s=o instanceof Error?o:new Error(String(o));if(s.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(s)}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=ze(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=n;let s=await e.execution.buildSupplyChainBatches();const r=e.selectedAsset.asset?._source==="wallet",a=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!r&&!s.some(h=>Ao(h.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const c=s.some(h=>h.tokenTransfers?.length)?{userOverride:a,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:a,feeExecutionMode:e.feeExecutionMode}:{userOverride:a};let d=n;const i=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!i?o:void 0;let u;for(let h=0;h<4;h+=1){const f=await e.execution.estimate(s,e.executionTokenAddress,d,c),g=Jn(f,Js(e));u=e.feeExecutionMode==="user-transfer"&&g?Mo(f,e,o):void 0;const y=u?.grossAmount??g?.grossAmount??d;if(y===d){d=y;break}d=y,s=await e.execution.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u})}e.feeExecutionMode==="user-transfer"&&(Ta(e,d),s=await e.execution.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u}));let m=u;await e.execution.execute(s,e.executionTokenAddress,d,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:h,chainBatches:f})=>{const g=Mo(h,e,o);if(!g)return null;const y=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;Ma(f,e.resolvedChainId,y);const C=Ra(m,g),v=$s(f,e,g);return C||v?null:(m=g,e.execution.buildSupplyChainBatches({fundingAmountOverride:g.grossAmount,actionAmountOverride:p,actionContextOverride:g}))}}:c),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const o=n instanceof Error?n:new Error(String(n));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const s=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(s),e.ui.setError(s),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function Wa(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const o=e.selectedAsset.asset,s=ze(e.selectedAsset.amount,o.decimals),r=s,a=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let c=await e.execution.buildSupplyChainBatches();const d={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let i=s;const p=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,u=e.feeExecutionMode==="user-transfer"&&!p?r:void 0;let m;if(a){const k=await vt.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:c}),S=Xo(s,10n),I=S+k.gasFee;i=s+I,e.feeExecutionMode==="user-transfer"&&(m={grossAmount:i,netAmount:r,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:S,gasFee:k.gasFee,bridgeFee:0n}})}else for(let k=0;k<4;k+=1){const S=await e.execution.estimate(c,e.executionTokenAddress,0n,d),I=e.feeExecutionMode==="user-transfer"?Mo(S,e,r):void 0,A=Jn(S,Js(e)),W=I?.grossAmount??(A?A.grossAmount>s?A.grossAmount:s:i);if(m=I,W===i){i=W;break}i=W;const P=Qt(e.executionTokenAddress,e.resolvedChainId),z=Wn(i,P?.decimals??e.destinationToken.decimals,o.decimals);c=await e.execution.buildSupplyChainBatches({fundingAmountOverride:i,sourceFundingAmountOverride:z,withdrawalAmountOverride:i,actionAmountOverride:u,actionContextOverride:I})}const h=Qt(e.executionTokenAddress,e.resolvedChainId);let f=a?i:Wn(i,h?.decimals??e.destinationToken.decimals,o.decimals);Ta(e,i),c=await e.execution.buildSupplyChainBatches({fundingAmountOverride:i,sourceFundingAmountOverride:f,withdrawalAmountOverride:i,actionAmountOverride:u,actionContextOverride:m});const g=o.chainId,y=n,C=await e.externalWallet.getEthereumProvider();await vo(C,g,()=>e.ui.setStatusMsg("Switching source network..."));const v=Ee(g),T=Yn({account:e.externalWalletAddress,chain:v?.viemChain,transport:Kn(C)}),b=It(o.address),w=o.isNative||Ue(b),B=gt(g),E=k=>ha({extWc:T,sourceClient:B,recipient:y,tokenAddr:b,isNative:w,amount:k,viemChain:v?.viemChain});e.ui.setStatusMsg("Funding embedded wallet..."),await E(f);let M=f;if(e.feeExecutionMode==="user-transfer")for(let k=0;k<4;k+=1){const S=await e.execution.estimate(c,e.executionTokenAddress,0n,d),I=Mo(S,e,r);if(!I)break;const A=a?I.grossAmount:Wn(I.grossAmount,h?.decimals??e.destinationToken.decimals,o.decimals);if(A>M&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await E(A-M),M=A),m=I,i=I.grossAmount,f=A,c=await e.execution.buildSupplyChainBatches({fundingAmountOverride:i,sourceFundingAmountOverride:f,withdrawalAmountOverride:i,actionAmountOverride:u,actionContextOverride:I}),$s(c,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let F=m;await e.execution.execute(c,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:k,chainBatches:S})=>{const I=Mo(k,e,r);if(!I)return null;const A=Ra(F,I),W=$s(S,e,I);if(A||W)return null;if(I.grossAmount>i)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");F=I;const P=a?I.grossAmount:Wn(I.grossAmount,h?.decimals??e.destinationToken.decimals,o.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:P,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:u,actionContextOverride:I})}}:d)}async function _s(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,o=e.activeSignerAddress??e.externalWalletAddress;if(!o||!n)throw new Error("Please connect your wallet to continue");const s=ze(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),r={userAddress:o,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},a=e.buildActionCalls(s,r);if(a.length===0)throw new Error("No action calls configured");const c=await n.getEthereumProvider();await vo(c,e.resolvedChainId);const d=Ee(e.resolvedChainId),i=Yn({account:o,chain:d?.viemChain,transport:Kn(c)}),p=gt(e.resolvedChainId);let u;for(const m of a){const h=await i.sendTransaction({to:m.to,data:m.data,value:m.value,chain:d?.viemChain});if((await p.waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");u=h}return u}async function Na(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,o=n.chainId,s=ze(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?s:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const a=e.resolvedTokenIn||e.selectedAsset.asset.address,c={userOverride:t,useCustomTransfers:!0},d=await e.execution.estimateRequiredGrossFunding(r,C=>e.execution.buildPayChainBatches({fundingAmountOverride:C}),a,c),i=hn(o),p=await e.externalWallet.getEthereumProvider();await vo(p,o);const u=Ee(o),m=Yn({account:e.externalWalletAddress,chain:u?.viemChain,transport:Kn(p)}),h=It(n.address),f=n.isNative||Ue(h)?await m.sendTransaction({to:i,value:d,chain:u?.viemChain}):await m.sendTransaction({to:h,data:Tt({abi:Fe,functionName:"transfer",args:[i,d]}),chain:u?.viemChain});if((await gt(o).waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const g=await e.execution.buildPayChainBatches({fundingAmountOverride:d}),y=g.some(C=>C.tokenTransfers?.length);return await e.execution.execute(g,a,d,C=>{C.txHash&&(e.ui.setPaymentResult(v=>({...v??{status:"processing"},txHash:C.txHash})),e.ui.setTxHash(C.txHash))},void 0,y?c:{userOverride:t})}async function Ua(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let o;if(e.isSourceDestToken||e.parsedAmount===0)o=await _s(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,r=ze(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const c=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!c)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const d=e.resolvedTokenIn||s.address,i=await e.execution.estimateRequiredGrossFunding(a,m=>e.execution.buildPayChainBatches({fundingAmountOverride:m}),d,{userOverride:c,useCustomTransfers:!0}),p=await e.execution.buildPayChainBatches({fundingAmountOverride:i}),u=await e.onPayExecute({asset:s,amount:e.currentPaymentAmount,amountWei:r,destinationToken:e.destinationToken,chainBatches:p,requiredNetFunding:a,grossFundingAmount:i,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:d,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});u&&(e.ui.setTxHash(u),e.ui.setPaymentResult(m=>({...m??{status:"processing"},txHash:u}))),o=u||void 0}else o=await Na(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||o||""}))}catch(o){const s=In(o,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(o instanceof Error?o:new Error(s))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=ze(e.currentPaymentAmount,e.destinationToken.decimals),o={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const y=await e.execution.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),C=await e.execution.execute(y,e.destinationToken.address,0n,v=>{v.txHash&&(e.ui.setPaymentResult(T=>({...T,txHash:v.txHash})),e.ui.setTxHash(v.txHash))},void 0,o);e.ui.setPaymentResult(v=>({status:"success",txHash:v?.txHash||C}));return}const s=e.selectedAsset?.asset;if(!s)throw new Error("Select a payment source");const r=e.resolvedTokenIn||s.address||e.destinationToken.address,a=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,c=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,d=(y,C,v)=>{const T=Gs(y),b=E=>(E.tokenTransfers??[]).some(M=>M.from==="escrow"),w=T.filter(E=>!b(E)),B=T.filter(b);return[...w,...Dn(B,c,C,v)]},i=await e.execution.estimateRequiredGrossFunding(a,y=>e.execution.buildPayChainBatches({fundingAmountOverride:y}).then(C=>d(C)),r,o);let p=i,u=d(await e.execution.buildPayChainBatches({fundingAmountOverride:i}));const m=await e.execution.estimate(u,r,i,o),h=Jn(m,{chainId:e.resolvedChainId,tokenAddress:r,symbol:Qt(r,e.resolvedChainId)?.symbol??s.symbol,decimals:Qt(r,e.resolvedChainId)?.decimals??s.decimals})?.grossAmount??i;h!==i&&(p=h),u=d(await e.execution.buildPayChainBatches({fundingAmountOverride:p}),m,{payoutAlreadyGross:!0});const f=u.some(y=>y.tokenTransfers?.length),g=await e.execution.execute(u,r,f?p:0n,y=>{y.txHash&&(e.ui.setPaymentResult(C=>({...C,txHash:y.txHash})),e.ui.setTxHash(y.txHash))},void 0,o);e.ui.setPaymentResult(y=>({status:"success",txHash:y?.txHash||g}))}catch(n){const o=In(n,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(n instanceof Error?n:new Error(o))}finally{e.ui.setIsExecuting(!1)}}const yd=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:c,cardBg:d,cardBorder:i,dk:p,dark:u,isQuoting:m,quoteError:h,estimatedOutput:f,paymentAmount:g,needsSwap:y,exactOutputSwap:C,adjustable:v=!1,maxAmount:T,onAmountChange:b})=>e==="supply"?x("div",{style:{backgroundColor:d,border:`1px solid ${i}`,borderRadius:u?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[x("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[x("div",{style:{minWidth:0},children:[l("span",{style:{fontFamily:r,fontSize:"17px",fontWeight:500,color:u?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),l("div",{style:{fontSize:"12px",fontWeight:500,color:c,fontFamily:r,marginTop:"10px"},children:"Net amount after swap and fees"})]}),x("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${i}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[l(za,{symbol:t,logoURI:n,primaryColor:s,size:24}),l("span",{style:{fontSize:"16px",fontWeight:500,color:u?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:r,letterSpacing:0},children:t})]})]}),l("div",{style:{textAlign:"right",minWidth:0},children:m?l("span",{style:{fontSize:"18px",color:c,fontFamily:r},children:"Quoting..."}):h?l("span",{style:{fontSize:"13px",color:u?"#f87171":"#dc2626",fontFamily:r},children:"Quote failed"}):f?l(ao,{value:f,title:f,fontFamily:r,color:a,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):l("span",{style:{fontSize:"20px",color:c,fontFamily:r},children:"\u2014"})})]}):l(xd,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:c,cardBg:d,cardBorder:i,dk:p,dark:u,paymentAmount:g||"0",needsSwap:y,exactOutputSwap:C,isQuoting:m,adjustable:v,maxAmount:T,onAmountChange:b}),Pa=pn(yd),za=({symbol:e,logoURI:t,primaryColor:n,size:o})=>t?l("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):l("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),xd=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:o,fontFamily:s,textPrimary:r,textSecondary:a,cardBg:c,cardBorder:d,dk:i,dark:p,paymentAmount:u,needsSwap:m,exactOutputSwap:h,isQuoting:f,adjustable:g,maxAmount:y,onAmountChange:C})=>{const v='"IBM Plex Mono", monospace',T=parseFloat(u||"0"),b=y?parseFloat(y):0,[w,B]=R(u||""),E=le(null),[M,F]=R(null),[k,S]=R(null);X(()=>{g||B(u||"")},[u,g]);const I=P=>{let z=P;z.startsWith(".")&&(z="0"+z);const N=uo(z);let D=N;y&&parseFloat(N)>parseFloat(y)&&(D=y),B(D),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>C?.(D),300)},A=P=>{if(!b)return;if(P===100){B(y||b.toString()),E.current&&clearTimeout(E.current),C?.(y||b.toString());return}const z=10**n,N=Math.floor(b*P/100*z)/z,D=po(N,n);B(D),E.current&&clearTimeout(E.current),C?.(D)},W=b>0?parseFloat(w||"0")/b*100:0;return X(()=>()=>{E.current&&clearTimeout(E.current)},[]),x("div",{style:{backgroundColor:c,border:`1px solid ${d}`,borderRadius:p?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[x("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[x("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[l(za,{symbol:e,logoURI:t,primaryColor:o,size:32}),x("div",{children:[l("span",{style:{fontSize:"14px",fontWeight:600,color:r,fontFamily:s},children:"Payment"}),l("div",{style:{fontSize:"12px",color:a,fontFamily:s,marginTop:"2px"},children:e})]})]}),x("div",{style:{textAlign:"right"},children:[g?l(ao,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:P=>I(P.target.value),placeholder:"0.0",fontFamily:v,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):l(ao,{element:"div",value:T>0?u:"0.00",title:T>0?u:"0.00",fontFamily:v,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),l("div",{style:{fontSize:"12px",color:a,fontFamily:v,marginTop:"2px"},children:e}),g&&b>0&&l("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((P,z)=>{const N=Math.abs(W-P)<1,D=z===4,H=P/100,O=M===P,_=k===P;return l("button",{onClick:()=>A(P),onMouseEnter:()=>F(P),onMouseLeave:()=>{F(null),S(null)},onMouseDown:()=>S(P),onMouseUp:()=>S(null),title:`${P}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:N?1:O?.8:.5,transform:_?"scale(0.85)":O?"scale(1.15)":"scale(1)",transition:Sn.interactive},children:x("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[l("circle",{cx:"7",cy:"7",r:"6.84375",fill:D?o:"none",stroke:D?o:p?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!D&&H>0&&l("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${H>.5?1:0} 1 ${7+6.84375*Math.sin(H*2*Math.PI)} ${7-6.84375*Math.cos(H*2*Math.PI)} Z`,fill:p?i?.textSecondary||"#9ca3af":"#3C3E42"})]})},P)})})]})]}),m&&h&&!f&&l("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:p?`1px solid ${i?.cardBorder||d}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:x("span",{style:{fontSize:"11px",color:a,fontFamily:s,opacity:.7},children:["via ",h.venue]})})]})};function La(e,t,n){const o=Ie(e.address,t),s=e.chainId===n,r=e._source==="wallet";return r&&o&&s?0:r&&s?1:!r&&o?2:!r&&s?3:4}function Oa(e,t){return!t||t.length===0||t.some(n=>Ie(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const o=yo(n);return o?t.some(s=>Ie(s,o.address)):!1})}function Ha(e,t,n){let{symbol:o,name:s,logoURI:r}=t;const a=Ie(e.address,n.address)&&e.chainId===n.chainId;a&&n.logoURI&&(r=n.logoURI),a&&!e.configToken&&o==="TOKEN"&&(o=n.symbol,s=n.symbol);const c=parseFloat((Number(t.balance)/Math.pow(10,t.decimals)).toFixed(6));return{address:e.address,name:s,symbol:o,decimals:t.decimals,balance:t.balance,balanceFormatted:c,balanceUsd:0,logoURI:r,isNative:!1,chainId:e.chainId}}function ja(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:o,enabled:s}=e,r=rn(Zt),a=(r?.mode||"7702")!=="7702",c=r?.embeddedWalletAddress,{externalAddress:d,embeddedAddress:i,activeAddress:p}=mo(),u=c||i,{assets:m,refetch:h}=To({address:u,supportedChains:o,enabled:s&&!a&&!!u,refetchInterval:3e4}),f=oe(()=>a?[]:m.filter(F=>Oa(F,n)),[m,n,a]),g=a?p??d:c,y=oe(()=>{const F=new Set,k=[],S=I=>{if(!I)return;const A=I.toLowerCase();F.has(A)||(F.add(A),k.push(kt(I)))};if(S(t.address),n)for(const I of n)S(I);return k},[a,t.address,n]),C=oe(()=>y.map(F=>F.toLowerCase()).sort().join(","),[y]),v=oe(()=>JSON.stringify([...o||[]].sort()),[o]),[T,b]=R([]),w=le(0),B=le(async()=>{}),E=re(async()=>{if(!s||!g||y.length===0){w.current++,b([]);return}const F=++w.current,k=kt(g),S=a?o&&o.length>0?o:[t.chainId]:[t.chainId],I=[];for(const z of y){const N=z.toLowerCase();if(N===Xt)continue;if(N===t.address.toLowerCase()){const H=Ee(t.chainId)?.supportedTokens?.find(O=>Ie(O.address,N));I.push({address:z,chainId:t.chainId,configToken:H?{decimals:H.decimals,symbol:H.symbol,name:H.name,logo:H.logo}:void 0});continue}let D=!1;for(const H of S){const O=Ee(H)?.supportedTokens?.find(_=>Ie(_.address,N));if(O){I.push({address:z,chainId:H,configToken:{decimals:O.decimals,symbol:O.symbol,name:O.name,logo:O.logo}}),D=!0;break}}D||I.push({address:z,chainId:t.chainId})}const A=new Map;for(const z of I){const N=A.get(z.chainId)||[];N.push(z),A.set(z.chainId,N)}const W=async(z,N)=>{try{const D=await Zn(z,{address:N.address,abi:Fe,functionName:"balanceOf",args:[k]}),{decimals:H,symbol:O,name:_,logoURI:U}=await pa(z,N.address,N.configToken);return Ha(N,{decimals:H,symbol:O,name:_,logoURI:U,balance:D},t)}catch{return null}},P=await Promise.all(Array.from(A.entries()).map(async([z,N])=>{let D;try{D=gt(z)}catch{return[]}const H=[],O=[];for(const U of N){const Z=H.length;H.push({address:U.address,abi:Fe,functionName:"balanceOf",args:[k]}),U.configToken||H.push({address:U.address,abi:Fe,functionName:"decimals"},{address:U.address,abi:Fe,functionName:"symbol"},{address:U.address,abi:Fe,functionName:"name"}),O.push({start:Z,item:U})}let _=null;try{_=await D.multicall({contracts:H})}catch{_=null}return _?O.map(({start:U,item:Z})=>{const he=_[U],Q=he?.status==="success"?he.result:0n;let G,de,ve,ce;if(Z.configToken)G=Z.configToken.decimals,de=Z.configToken.symbol,ve=Z.configToken.name,ce=Z.configToken.logo;else{const me=_[U+1],ue=_[U+2],Se=_[U+3];G=me?.status==="success"?Number(me.result):18,de=ue?.status==="success"?ue.result:"TOKEN",ve=Se?.status==="success"?Se.result:de}return Ha(Z,{decimals:G,symbol:de,name:ve,logoURI:ce,balance:Q},t)}):(await Promise.all(N.map(U=>W(D,U)))).filter(U=>U!==null)}));F===w.current&&b(P.flat())},[s,a,g,C,v,t.address,t.chainId,t.symbol,t.logoURI]);X(()=>{B.current=E},[E]),X(()=>{if(!s){b([]);return}B.current();const F=setInterval(()=>{B.current()},15e3);return()=>clearInterval(F)},[s,a,g,C,v,t.address,t.chainId]);const M=re(()=>{E()},[E]);return{displayAssets:oe(()=>{const F=[],k=T.filter(I=>I.balance>0n);for(const I of k)F.push({...I,_source:"wallet"});for(const I of f)F.push({...I,_source:"spice"});const S=t.address.toLowerCase();return F.sort((I,A)=>La(I,S,t.chainId)-La(A,S,t.chainId)),F},[T,f,t.address,t.chainId]),filteredSpiceAssets:f,walletAssets:T,embeddedWalletAddress:u,externalAddress:d,isNon7702:a,refreshSpiceAssets:h,refreshWalletAssets:M}}async function Qa(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:s,chainId:r,config:a}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const c=(await gt(r).simulateContract({address:a.quoterV2,abi:Ai,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,fee:s,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function Va(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>Qa({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const bd=[{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 wd(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:s,chainId:r,config:a}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const c=(await gt(r).simulateContract({address:a.quoterV2,abi:bd,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,fee:s,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function Cd(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>wd({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function qa(e){return e.type==="swap"}const er=.02,vd=[1,8453,42161,10,137,43114,56],kd="https://api.1inch.dev/swap/v6.0";function Ya(e,t){return Ei(e,t)}function Ka(e){const t=e?.baseUrl??kd;return{name:"1inch",chainIds:e?.chainIds??vd,resolve:async(n,o,s)=>{const r=n.maxSlippage??er,a=r*100,c=Ue(n.tokenIn)?fr:n.tokenIn,d=Ue(n.tokenOut)?fr:n.tokenOut,i=Ue(n.tokenIn);try{const p=new URL(`${t}/${o}/swap`);p.searchParams.set("src",c),p.searchParams.set("dst",d),p.searchParams.set("amount",n.amountIn.toString()),p.searchParams.set("from",s),p.searchParams.set("slippage",a.toString()),p.searchParams.set("disableEstimate","true"),p.searchParams.set("allowPartialFill","false");const u={Accept:"application/json"};e?.apiKey&&(u.Authorization=`Bearer ${e.apiKey}`);const m=await fetch(p.toString(),{headers:u});if(!m.ok)throw new Ae("VENUE_API_ERROR",`[1inchVenue] API returned ${m.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${m.status}`});const h=await m.json();if(!h.dstAmount||!h.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const f=BigInt(h.dstAmount);if(f<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const g=Ya(f,r),y=[];return h.tx.to&&!i&&y.push({to:n.tokenIn,value:0n,data:Tt({abi:Fe,functionName:"approve",args:[h.tx.to,n.amountIn]})}),y.push({to:h.tx.to,value:BigInt(h.tx.value||"0"),data:h.tx.data}),{venue:"1inch",amountOut:f,amountOutMinimum:g,calls:y}}catch(p){if(p instanceof Ae)throw p;const u=p instanceof Error?p.message:String(p);throw new Ae("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${u}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:u})}}}}const Za=[4114,5115],tr={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Xa={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Ga(e){return{name:"satsuma",chainIds:e.chainIds??Za,resolve:async(t,n,o)=>{const s=t.maxSlippage??er,r=Ue(t.tokenIn);let a;try{a=await Va({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 c=Ya(a.amountOut,s),d=[];return r||d.push({to:t.tokenIn,value:0n,data:Tt({abi:Fe,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),d.push({to:e.swapRouter,value:r?t.amountIn:0n,data:Tt({abi:Si,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:a.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:a.amountOut,amountOutMinimum:c,calls:d}}}}function Ja(e){return{name:"satsuma",chainIds:e.chainIds??Za,resolve:async(t,n,o)=>{const s=t.maxSlippage??er,r=Ue(t.tokenIn);let a;try{a=await Cd({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 c=BigInt(Math.round(s*1e4)),d=a.amountIn+a.amountIn*c/10000n,i=[];return i.push({to:e.swapRouter,value:r?d:0n,data:Tt({abi:Id,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:a.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:a.amountIn,amountInMax:d,amountOut:t.amountOut,calls:i}}}}const Id=[{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 $a(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Ga(e.satsuma)),t.push(Ka(e?.oneInch));function n(s){return t.find(r=>r.chainIds.includes(s))}async function o(s,r,a){const c=[],d=[];for(const i of s){if(!qa(i)){c.push(i);continue}const p=n(r);if(!p)throw new Ae("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${r}. Cannot resolve swap ${i.tokenIn} \u2192 ${i.tokenOut}.`,{chainId:r,tokenIn:i.tokenIn,tokenOut:i.tokenOut,amountIn:i.amountIn.toString()});const u=await p.resolve(i,r,a);if(!u)throw new Ae("NO_LIQUIDITY",`${p.name} returned no quote for ${i.tokenIn} \u2192 ${i.tokenOut} on chain ${r}.`,{venue:p.name,chainId:r,tokenIn:i.tokenIn,tokenOut:i.tokenOut,amountIn:i.amountIn.toString()});c.push(...u.calls),d.push(u)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:o,getVenueForChain:n,venues:t}}function _a(e){const t=e?.customVenues??[];async function n(o,s,r){const a=t.filter(i=>i.chainIds.includes(s));if(a.length===0)throw new Ae("NO_SWAP_ROUTE",`No exact-output venue supports chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const c=(await Promise.allSettled(a.map(async i=>({venue:i,quote:await i.resolve(o,s,r)})))).filter(i=>i.status==="fulfilled").map(i=>i.value).filter(i=>i.quote!==null);if(c.length===0)throw new Ae("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});const d=c.find(i=>i.venue.preferred);return d?d.quote:(c.sort((i,p)=>i.quote.amountIn<p.quote.amountIn?-1:i.quote.amountIn>p.quote.amountIn?1:0),c[0].quote)}return{getQuote:n,venues:t}}const ei=$a({satsuma:tr});async function Ad(e){const t=ei.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 ti(e){const{direction:t,selectedAsset:n,destinationToken:o,chainId:s,recipient:r,paymentAmount:a,resolveExactOutputSwap:c}=e,[d,i]=R(!1),[p,u]=R(null),[m,h]=R(null),[f,g]=R(null),[y,C]=R(null),[v,T]=R(null),[b,w]=R(null),[B,E]=R(null),[M,F]=R(null),k=le(null),S=le(null),I=le(0),A=le(new Map),W=oe(()=>ei,[]),P=oe(()=>_a({customVenues:[...c?[{name:"consumer-exact-output",chainIds:[s],preferred:!0,resolve:c}]:[],Ja(tr),Ja(Xa)]}),[c,s]),z=oe(()=>{if(!n?.asset)return null;const G=Rn(n.asset,s);if(G)return G;const de=jn(n.asset.address,s,n.asset.chainId);return de?de.address:null},[n?.asset,s]),N=oe(()=>n?.asset?Vo(n.asset,s):[],[n?.asset,s]),D=oe(()=>N.map(G=>G.toLowerCase()).join(","),[N]);X(()=>{let G=!1;if(S.current&&(clearTimeout(S.current),S.current=null),!n?.asset||N.length<=1){F(null);return}return S.current=setTimeout(async()=>{const de=t==="input"?n.amount:a||"0";let ve=0n;try{ve=t==="input"?ze(de,n.asset.decimals):0n}catch{ve=0n}try{const ce=await Rr(n.asset,s,{requiredAmount:ve});G||F(ce)}catch{G||F(null)}},400),()=>{G=!0,S.current&&(clearTimeout(S.current),S.current=null)}},[n?.asset,n?.amount,s,N.length,D,t,a]);const H=oe(()=>M??z,[M,z]),O=oe(()=>!n?.asset||!H?[]:[H,...N.filter(G=>G.toLowerCase()!==H.toLowerCase())],[n?.asset,H,N]),_=oe(()=>!n?.asset||!Bo(n.asset.address,n.asset.chainId,o.address,o.chainId)||!H?!1:Ie(H,o.address),[n,o.address,o.chainId,H]),U=H?Ie(H,o.address):!1,Z=t==="output"&&parseFloat(a||"0")===0,he=!!n?.asset&&!_&&!U&&!Z,Q=he?B??H:H;return X(()=>{k.current&&clearTimeout(k.current);const G=t==="input"?n?.amount:a,de=parseFloat(G||"0");if(!he||!Number.isFinite(de)||de<=0||!n?.asset||!r||O.length===0){I.current++,h(null),g(null),C(null),T(null),w(null),E(null),u(null),i(!1);return}const ve=n.asset.decimals;let ce;try{ce=t==="input"?ze(n.amount,ve):ze(a||"0",o.decimals)}catch{I.current++,u("Invalid amount"),i(!1);return}const me=++I.current,ue=()=>me!==I.current;i(!0);const Se=t==="output"?150:400;return k.current=setTimeout(async()=>{try{if(t==="input"){const ee=W.getVenueForChain(s);if(!ee)throw new Error("No swap venue for this chain");let V=null,$=null;for(const xe of O){const q=`${t}:${s}:${xe.toLowerCase()}:${o.address.toLowerCase()}:${ce.toString()}`,te=A.current.get(q);if(te&&te.expiresAt>Date.now()&&te.resolvedSwap){V=te.resolvedSwap,$=xe;break}const ge=await ee.resolve({type:"swap",tokenIn:xe,tokenOut:o.address,amountIn:ce},s,r);if(ue())return;if(ge){A.current.set(q,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:ge}),V=ge,$=xe;break}}if(!V||!$)throw new Error("No liquidity for this pair");E($),w(V.amountOut),C(V),T(null);const ae=parseFloat(pt(V.amountOut,o.decimals));h(ae<.01?ae.toPrecision(4):ae.toLocaleString(void 0,{maximumFractionDigits:6})),g(null),u(null)}else{let ee=null,V=null;for(const $ of O){const ae=`${t}:${s}:${$.toLowerCase()}:${o.address.toLowerCase()}:${ce.toString()}`,xe=A.current.get(ae);if(xe&&xe.expiresAt>Date.now()&&xe.exactOutputSwap){ee=xe.exactOutputSwap,V=$;break}try{const q=await P.getQuote({tokenIn:$,tokenOut:o.address,amountOut:ce},s,r);if(ue())return;A.current.set(ae,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:q}),ee=q,V=$;break}catch{if(ue())return}}if(!ee||!V)throw new Error("No liquidity for this pair");E(V),T(ee),C(null),w(null),g(parseFloat(pt(ee.amountIn,ve)).toFixed(6)),h(null),u(null)}}catch(ee){if(ue())return;const V=ee instanceof Error?ee.message:"Failed to get quote";u(V),h(null),g(null),C(null),T(null),w(null),E(null)}finally{ue()||i(!1)}},Se),()=>{k.current&&clearTimeout(k.current)}},[t,he,n?.amount,n?.asset?.address,n?.asset?.decimals,a,O,s,o.address,o.decimals,r,W,P]),{isQuoting:d,quoteError:p,estimatedOutput:m,estimatedInput:f,resolvedSwap:y,exactOutputSwap:v,quoteAmountOut:b,resolvedTokenIn:Q,isDirect:U,needsSwap:he,selectedIsEquivalent:_}}const ni={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},oi=["signing-delegation","signing-intent","submitting","executing"],Sd=()=>{},Ed=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:o,sourceChains:s,supportedSourceAssets:r,buildActionCalls:a,feeExecutionMode:c="user-transfer",buildSpicenetBatch:d,onPayExecute:i,resolveExactOutputSwap:p,actionLabel:u,amountDirection:m="input",swapDescription:h,directDescription:f,paymentAmount:g,amountInputMode:y="fixed",minPaymentAmount:C,maxPaymentAmount:v,onAmountChange:T,styles:b,dark:w,title:B,subtitle:E,onAddFunds:M,onSuccess:F,onError:k})=>{const S=m==="output",{theme:I,dark:A,primaryColor:W,dk:P,palette:z,fontFamily:N,monoFont:D,inputDark:H,cardBg:O,cardBorder:_,textPrimary:U,textSecondary:Z,subtitleText:he}=Bt(b,w),Q=oe(()=>H?{...I,colors:{...I.colors,secondary:P.cardBg,surfaceHover:P.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:I,[H,I,P.cardBg,P.hoverBg]),G=o.chainId,de=rn(Zt),ve=de?.mode||"7702",ce=ve!=="7702",me=!!de?.isWhitelistGateActive,ue=!!de?.isWhitelistConfigured&&de?.isUserWhitelisted!==!0,Se=oe(()=>s??de?.supportedChainIds??[],[s,de?.supportedChainIds]),ee=oe(()=>{if(me)return[];if(r)return r;const ye=de?.allowedTokens;if(!ye||ye.length===0)return;const at=new Set(ye.map(Vn=>Vn.toLowerCase())),Un=[],Qn=new Set;for(const Vn of Se){const cs=Ee(Vn);for(const ds of cs?.supportedTokens??[]){if(!at.has(ds.symbol.toLowerCase()))continue;const nr=ds.address.toLowerCase();Qn.has(nr)||(Qn.add(nr),Un.push(ds.address))}}return Un},[r,de?.allowedTokens,Se,me]),V=Pn(),{address:$,isConnected:ae,isReady:xe,isAuthenticated:q,provider:te}=V,{execute:ge,estimate:se}=bo(),{externalWallet:Le,embeddedAddress:yt,activeWallet:Ot,activeAddress:Ht}=mo(),xt=de?.externalWalletAddress,fe=de?.embeddedWalletAddress||yt,{displayAssets:jt,filteredSpiceAssets:Pe,embeddedWalletAddress:Ve,refreshSpiceAssets:it,refreshWalletAssets:Ut}=ja({destinationToken:o,supportedSourceAssets:ee,sourceChains:Se,enabled:e&&(ce?!!xt:!!fe)}),nt=me||S||ce?jt:Pe;X(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:ve,walletAddressUsed:Ve,count:nt.length,assets:nt.map(ye=>({symbol:ye.symbol,address:ye.address,chainId:ye.chainId,balanceFormatted:ye.balanceFormatted,source:ye?._source}))})},[e,ve,Ve,nt]);const[L,Oe]=R(null),[Me,Je]=R(g||""),[Ze,Jt]=R(!1),[_t,an]=R(null),[Be,en]=R("idle"),[ot,Fn]=R(""),[xn,$e]=R(null),[ln,Vt]=R(!1),[Ye,we]=R(null),[Ke,tt]=R(null),[bn,ke]=R(!1),[$t,Dt]=R(!1),[At,_e]=R(null),Bn=le(L),qt=le(!1),cn=le(null),wn=le(null),Yt=le(0),Mt=le(null),bt=le(null);X(()=>{Bn.current=L},[L]);const He=y==="adjustable"?Me:g||"0",lt=Ve||yt||$,{isQuoting:St,quoteError:dn,estimatedOutput:tn,resolvedSwap:Et,exactOutputSwap:Te,quoteAmountOut:Wt,resolvedTokenIn:ft,isDirect:Nt,needsSwap:ct,selectedIsEquivalent:Re}=ti({direction:m,selectedAsset:L,destinationToken:o,chainId:G,recipient:lt,paymentAmount:He,resolveExactOutputSwap:p}),dt=S?parseFloat(He||"0"):parseFloat(L?.amount||"")||0,nn=dt>0&&dt<Hn,J=L?.asset?._source==="wallet",ne=!!L?.asset&&J&&L.asset.chainId!==G,Ce=oe(()=>L?.asset?Pe.find(ye=>Ie(ye.address,L.asset.address))?.balanceFormatted??0:0,[L,Pe]),je=J?L?.asset.balanceFormatted??0:Ce,et=oe(()=>{if(!L?.asset)return!1;if(S)return Ke?Wn(Ke.grossAmount,Ke.decimals,L.asset.decimals)>L.asset.balance:Re||Nt?dt>L.asset.balanceFormatted:Te?parseFloat(pt(Te.amountInMax,L.asset.decimals))>L.asset.balanceFormatted:!1;if(Ke){const ye=Wn(Ke.grossAmount,Ke.decimals,L.asset.decimals);return J?ye>L.asset.balance:parseFloat(pt(ye,L.asset.decimals))>je}return dt>je},[L,S,Ke,Re,dt,Te,je,J,Nt]);X(()=>{e||(Oe(null),an(null),Jt(!1),en("idle"),Fn(""),$e(null),Vt(!1),we(null),tt(null),ke(!1),Dt(!1),_e(null),qt.current=!1,y==="adjustable"&&Je(g||""),cn.current&&(cn.current.abort(),cn.current=null))},[e]);const ht=re(ye=>{Oe(at=>({asset:ye,amount:at?.asset?.address===ye.address&&at?.asset?.chainId===ye.chainId&&at.amount||""})),an(null),_e(null),Dt(!1)},[]),wt=re(ye=>{Oe(at=>at&&{...at,amount:ye}),an(null),_e(null),Dt(!1)},[]),mt=re(ye=>{let at=ye;v&&parseFloat(at)>parseFloat(v)&&(at=v),Je(at),T?.(at),an(null),_e(null),Dt(!1)},[v,T]);re(ye=>{if(qt.current||!$)return;const at=Bn.current;!at?.asset||!at.amount||at.asset?._source==="wallet"||ze(S?He:at.amount,at.asset.decimals)===0n||(qt.current=!0,it())},[$,G,it,S,He]);const De=re(ye=>{en({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[ye.step]||"executing"),Fn(ye.message),ye.txHash&&$e(ye.txHash)},[]),Rt=oe(()=>({currentPaymentAmount:He,destinationToken:o,embeddedWalletAddress:Ve,providerEmbeddedAddress:yt,externalWalletAddress:xt,address:$,isNon7702:ce,isPayMode:S,resolvedChainId:G,buildActionCalls:a,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:L,needsSwap:ct,resolvedSwap:Et,exactOutputSwap:Te,quoteAmountOut:Wt,resolvedTokenIn:ft}),[He,o,Ve,yt,xt,$,ce,S,G,a,c,d,L,ct,Et,Te,Wt,ft]),Qe=re(ye=>Aa({...Rt,requestTimestampMs:wn.current??Date.now()},ye),[Rt]),Y=re(ye=>Sa({...Rt,requestTimestampMs:wn.current??Date.now()},ye),[Rt]),be=re((ye,at,Un,Qn)=>Ea(ye,at,Un,se,Qn),[se]),Ct=oe(()=>L?.asset?ct&&ft?ft:L.asset.chainId===G?L.asset.address:ft??Rn(L.asset,G)??o.address:o.address,[L,o.address,ct,G,ft]),Ft=re(()=>(wn.current=Date.now(),Da(bt.current)),[]),Xe=oe(()=>L?.asset?Ie(L.asset.address,o.address)&&L.asset.chainId===o.chainId:!1,[L,o.address,o.chainId]),Pt=Xe&&(ce||S),st=Pt&&dt>0&&!!L?.asset,un=ue&&!Pt,j=oe(()=>{if(!st)return null;let ye;try{ye=ze(He||"0",o.decimals)}catch{return null}return{symbol:o.symbol,decimals:o.decimals,grossAmount:ye,netAmount:ye,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[st,He,o.symbol,o.decimals]),K=_t,pe=oe(()=>!(!L?.asset||dt<=0),[L,dt,st]),ie=oe(()=>!e||Ze||Be!=="idle"||!pe||st||!L?.asset?null:[S?"pay":"supply",m,L.asset.address.toLowerCase(),L.asset.chainId,L.amount,He,o.address.toLowerCase(),o.chainId,G,ft?.toLowerCase()??"",ct?"swap":"direct",Nt?"direct-token":"routed-token",ce?"non7702":"7702",Xe?"source-dest":"cross-chain",St?"quoting":"quoted",Te?.amountIn?.toString()??"",Te?.amountInMax?.toString()??"",Te?.venue??"",Et?.amountOut?.toString()??"",Wt?.toString()??"",Ve??"",yt??"",$??""].join("|"),[e,Ze,Be,pe,st,L,S,m,He,o,G,ft,ct,Nt,ce,Xe,St,Te,Et,Wt,Ve,yt,$]),qe=re(()=>Ba({selectedAsset:L,isPayMode:S,parsedAmount:dt,needsSwap:ct,exactOutputSwap:Te,isNon7702:ce,isSourceDestToken:Xe,currentPaymentAmount:He,destinationToken:o,feeExecutionMode:c,resolvedTokenIn:ft,embeddedWalletAddress:Ve,providerEmbeddedAddress:yt,resolvedChainId:G,isConnected:ae,address:$,ready:xe,authenticated:q,isDirect:Nt,resolvedSwap:Et,isQuoting:St,executionTokenAddress:Ct,buildPayChainBatches:Qe,buildSupplyChainBatches:Y,estimate:se,estimateRequiredGrossFunding:be}),[L,S,dt,ct,Te,ce,Xe,He,o,c,ft,Ve,yt,be,Qe,se,G,ae,$,xe,q,Nt,Et,St,Y,Ct]);X(()=>{Mt.current=qe},[qe]);const We=re(ye=>Fa({asset:ye,isPayMode:S,isNon7702:ce,needsSwap:ct,isQuoting:St,embeddedWalletAddress:Ve,buildSupplyChainBatches:Y,estimate:se,executionTokenAddress:Ct,feeExecutionMode:c}),[S,ce,ct,St,Ve,Y,se,Ct,c]);X(()=>{if(!e){ke(!1),Dt(!1),_e(null),tt(null);return}if(Ze||Be!=="idle"){Yt.current+=1,ke(!1);return}if(!pe){tt(null),ke(!1),Dt(!1),_e(null);return}if(st){tt(j),ke(!1),Dt(!0),_e(null);return}if(St){Yt.current+=1,ke(!1),Dt(!1);return}if(!ie)return;let ye=!1;const at=async()=>{const Qn=++Yt.current;_e(null),ke(!0);try{const Vn=await Mt.current?.();if(ye||Yt.current!==Qn)return;Vn?(tt(Vn),Dt(!0)):(tt(null),Dt(!1)),_e(null)}catch(Vn){if(ye||Yt.current!==Qn)return;const cs=In(Vn,"Unable to calculate fees for this action.");tt(null),Dt(!1),_e(cs)}finally{!ye&&Yt.current===Qn&&ke(!1)}},Un=window.setTimeout(()=>{at()},250);return()=>{ye=!0,clearTimeout(Un),ke(!1)}},[e,Ze,Be,pe,st,j,St,ie]);const Ge=re(()=>(wn.current=Date.now(),Ua(bt.current)),[]);X(()=>{!S&&Be==="success"&&xn&&(it(),F?.(xn))},[S,Be,xn,it,F]),X(()=>{if(!S||Ye?.status!=="success"||qt.current||!$)return;qt.current=!0;const ye=Bn.current;!ye?.asset||ye.asset?._source==="wallet"||it()},[S,Ye?.status,$,it]);const ut=le(F),zt=le(k);X(()=>{ut.current=F},[F]),X(()=>{zt.current=k},[k]),X(()=>{e&&(it(),Ut())},[e,it,Ut]),X(()=>{S&&(Ye?.status==="success"&&ut.current?.(Ye.txHash||""),Ye?.status==="failed"&&zt.current?.(new Error("Payment execution failed")))},[S,Ye?.status]);const on=re(()=>{Vt(!1),we(null),Oe(null),qt.current=!1,it(),Ut()},[it,Ut]);bt.current={selectedAsset:L,parsedAmount:dt,currentPaymentAmount:He,isInsufficientBalance:et,isPayMode:S,isNon7702:ce,isSourceDestToken:Xe,needsSwap:ct,exactOutputSwap:Te,selectedIsEquivalent:Re,resolvedTokenIn:ft,embeddedWalletAddress:Ve,providerEmbeddedAddress:yt,externalWallet:Le,externalWalletAddress:xt,activeSignerWallet:Ot,activeSignerAddress:Ht,address:$,isConnected:ae,ready:xe,authenticated:q,provider:te,resolvedChainId:G,executionTokenAddress:Ct,destinationToken:o,buildActionCalls:a,feeExecutionMode:c,buildSpicenetBatch:d,onPayExecute:i,onSuccess:F,onError:k,execution:{estimate:se,execute:ge,buildPayChainBatches:Qe,buildSupplyChainBatches:Y,estimateRequiredGrossFunding:be,onProgress:De},ui:{setError:an,setStep:en,setStatusMsg:Fn,setTxHash:$e,setIsExecuting:Jt,setShowStatusPanel:Vt,setPaymentResult:we},refs:{spiceDepositSubmittedRef:qt,abortControllerRef:cn}};const Cn=g?.trim(),Kt=S&&y==="fixed"&&Cn!==void 0&&Cn!==""&&dt===0,vn=S?(Kt||!!L?.asset)&&dt>=0&&!nn&&!et&&!Ze&&(Kt||st||$t)&&!At&&(Kt||!ct||!!Te)&&!un:!!L?.asset&&dt>0&&!nn&&!et&&!Ze&&(Pt||$t)&&!At&&(ne||Nt||!!Et&&!St)&&!un;X(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:vn,isPayMode:S,hasSelectedAsset:!!L?.asset,selectedAsset:L?.asset?{symbol:L.asset.symbol,address:L.asset.address,chainId:L.asset.chainId,balanceFormatted:L.asset.balanceFormatted,source:L.asset?._source}:null,parsedAmount:dt,isZeroAmountPay:Kt,isBelowMinimum:nn,isInsufficientBalance:et,isExecuting:Ze,directExternalAction:Pt,directExecutionFeeNote:st,feeEstimateReady:$t,feeEstimateError:At,needsSwap:ct,isDirect:Nt,isSourceDestToken:Xe,hasExactOutputSwap:!!Te,isQuoting:St,whitelistHoldPending:ue,supplyHeldForWhitelist:un,isWhitelistGateActive:me,destinationToken:{symbol:o.symbol,address:o.address,chainId:o.chainId}})},[e,vn,S,L,dt,Kt,nn,et,Ze,Pt,st,$t,At,ct,Nt,Xe,Te,St,ue,un,me,o]);const eo=Nt?f||`Your ${o.symbol} will be used directly.`:h||"Your assets will be swapped and used in a single atomic transaction.",co=(G?Ee(G):void 0)?.viemChain?.blockExplorers?.default?.url??"",to=oi.indexOf(Be),Ne=Ze?(ni[Be]||"EXECUTING...").toUpperCase():Be==="success"?"DONE":nn?`MINIMUM ${Hn}`:et?"INSUFFICIENT BALANCE":u.toUpperCase(),rt=oe(()=>{if(Ze)return"PAYING...";if(nn)return`MINIMUM ${Hn}`;if(et&&L?.asset)return`INSUFFICIENT ${L.asset.symbol}`;if(u)return u.toUpperCase();const ye=dt>0?` ${He} ${o.symbol}`:"";return ct?`SWAP & PAY${ye}`:`PAY${ye}`},[Ze,nn,et,L,u,dt,He,o.symbol,ct]),sn=Be==="success"?()=>{en("idle"),Oe(null),$e(null),it()}:Ft,Nn=Be==="success"?!1:!vn;if(!e)return null;const Do=S?B||`Pay ${o.symbol}`:u,ko=S?E:x("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[l("span",{style:{marginTop:"3px",flexShrink:0},children:l(Ns,{color:he})}),l("p",{style:{fontSize:"12px",color:he,margin:0,lineHeight:"1.4",fontFamily:N},children:eo})]});if(S){const ye=Ye&&(Ye.status==="success"||Ye.status==="failed")?[{asset:{symbol:L?.asset?.symbol||o.symbol,address:L?.asset?.address||""},amount:He,txHash:Ye.txHash||"",success:Ye.status==="success",error:Ye.status==="failed"?Ye.error:void 0}]:void 0;return l(Ln,{isOpen:e,onClose:t,title:Do,subtitle:ko,styles:b,dark:A,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:x("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[M&&l("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:l(Us,{onClick:M,color:W,fontFamily:N})}),!Kt&&l("div",{style:{marginBottom:"12px"},children:l(Fo,{assets:nt,selectedAsset:L??void 0,onAssetSelect:ht,onAmountChange:Sd,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:L?.asset?ct?St?"...":Te?`~${parseFloat(pt(Te.amountIn,L.asset.decimals)).toFixed(6)}`:void 0:He??void 0:void 0,dark:A,theme:Q,styles:b})}),l(Pa,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:W,fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:O,cardBorder:_,dk:P,dark:A,isQuoting:St,quoteError:dn,estimatedOutput:tn,paymentAmount:He,needsSwap:ct,exactOutputSwap:Te,adjustable:y==="adjustable",maxAmount:v,onAmountChange:mt}),pe&&l(ts,{fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:O,cardBorder:_,resolvedDark:A,darkCardBorder:P.cardBorder,primaryColor:W,feePreview:Ke,isLoading:bn,errorText:At,directExecutionFeeNote:st}),K&&l(wo,{variant:"error",palette:z,fontFamily:N,style:{marginBottom:"12px"},children:K}),l(Lt,{variant:"outline",fullWidth:!0,onClick:Ge,disabled:!vn,loading:Ze,dark:A,styles:{...b,button:{...b?.button,backgroundColor:W}},children:rt}),Ye&&ln&&l("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:A?P.shell:"white",borderRadius:A?"12px":"6px",padding:"16px 0"},children:l(Hs,{type:"payment",isOpen:Ye.status!=="processing",isProcessing:Ze||Ye.status==="processing",closeOnComplete:!1,chainName:fn(G),explorerUrl:ho(G,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Vt(!1),we(null),Ge()},onNewTx:on,onClose:()=>{Vt(!1),we(null)},onComplete:on,results:ye,styles:b,dark:A})})]})})}return l(Ln,{isOpen:e,onClose:t,title:Do,subtitle:ko,dark:A,styles:b,theme:I,closeOnBackdropClick:n,children:x("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[l("div",{style:{marginBottom:"16px"},children:l(Fo,{assets:nt,selectedAsset:L||void 0,onAssetSelect:ht,onAmountChange:wt,disabled:Ze||Be==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:Q,styles:b,dark:H,resolveMaxAmount:We,maxAmount:je>0?po(je,L?.asset.decimals??o.decimals):void 0})}),L?.asset&&!Nt&&l(Pa,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:W,fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:O,cardBorder:_,dark:A,isQuoting:St,quoteError:dn,estimatedOutput:tn}),pe&&l(ts,{fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:O,cardBorder:_,resolvedDark:A,darkCardBorder:P.cardBorder,primaryColor:W,feePreview:Ke,isLoading:bn,errorText:At,directExecutionFeeNote:st}),Be!=="idle"&&x("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Be==="success"?O:Be==="error"?z.errorBg:O,border:`1px solid ${Be==="success"?_:Be==="error"?z.errorBorder:_}`},children:[x("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Be==="success"?l("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:l("path",{d:"M5 13l4 4L19 7",stroke:z.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Be==="error"?l("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:l("path",{d:"M18 6L6 18M6 6l12 12",stroke:z.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):l(qn,{size:14,color:W}),l("span",{style:{fontSize:"13px",fontWeight:500,color:Be==="success"?U:Be==="error"?z.errorText:U,fontFamily:N,flex:1},children:Be==="success"?"Deposit confirmed":Be==="error"?ot||"Transaction failed":ni[Be]||ot}),Be==="success"&&xn&&l("a",{href:`${co}/tx/${xn}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:W,fontFamily:N,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Be==="error"&&l("button",{onClick:()=>{en("idle"),an(null),setTimeout(Ft,50)},style:{background:"none",border:"none",fontSize:"12px",color:W,fontFamily:N,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),to>=0&&Be!=="success"&&Be!=="error"&&l("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${Z}22`,overflow:"hidden"},children:l("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:W,transformOrigin:"left center",transform:`scaleX(${(to+1)/oi.length})`,transition:"transform 400ms ease"}})})]}),_t&&Be==="idle"&&l(wo,{variant:"error",palette:z,fontFamily:N,style:{marginBottom:"16px"},children:_t}),l(Lt,{variant:"outline",fullWidth:!0,disabled:Nn,onClick:sn,theme:I,dark:A,styles:{...b,button:{...b?.button,backgroundColor:W}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:D},children:Ne})]})})},Fd=()=>{const[e,t]=R("0"),[n,o]=R(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:n,setSelectedAsset:o}};function Bd(e,t=0){const[n,o]=R(t),s=e[n]??e[0],r=oe(()=>s?BigInt(Math.round(s.months*30*24*3600)):0n,[s?.months]);return{selectedDurationIdx:n,setSelectedDurationIdx:o,selectedDuration:s,durationSeconds:r}}function Td(){const{actions:e,isReady:t,isAuthenticated:n}=Pn(),o=rn(Zt)?.embeddedWalletAddress,s=le(!1),r=le(0),a=le(null),c=le(e),[d,i]=R(0);c.current=e,X(()=>{s.current=!1,r.current=0,a.current&&(clearTimeout(a.current),a.current=null)},[o]),X(()=>{if(!o||!t||!n||s.current)return;s.current=!0;let p=!1;return(async()=>{await En(2e3);try{await hi(o,c.current.signMessage),r.current=0}catch(u){console.warn("[SmartWallet] Registration failed:",u),s.current=!1,!p&&r.current<3&&(r.current+=1,a.current=setTimeout(()=>{i(m=>m+1)},5e3))}})(),()=>{p=!0,a.current&&(clearTimeout(a.current),a.current=null)}},[o,t,n,d])}function Ro(e){try{return Fi(e)}catch{throw new Ae("ROUTE_TOKEN_NOT_FOUND",`Token "${e[0]}" not found on chain ${e[1]} in the token registry.`,{symbol:e[0],chainId:e[1]})}}function Md(e,t){if(e[0].toUpperCase()===t[0].toUpperCase()&&e[1]===t[1])return!0;let n,o;try{n=Ro(e),o=Ro(t)}catch{return!1}const s=new Set(pr(o.address).map(r=>r.toLowerCase()));return s.add(o.address.toLowerCase()),s.has(n.address.toLowerCase())}function Rd(){const e=[];for(const t of Object.keys(Bi).map(Number))for(const n of dr(t))e.push([n.symbol,t]);return e}async function Dd(e){const{action:t,inputToken:n,inputAmount:o,registry:s,userAddress:r,slippage:a,intermediaryCandidates:c}=e;if(t.calls.length===0)throw new Ae("INVALID_PARAMS","buildIntent: action.calls must not be empty.",{action:t});if(o<=0n)throw new Ae("INVALID_PARAMS","buildIntent: inputAmount must be greater than zero.",{inputAmount:o.toString()});const d=t.supportedInputTokens??Rd();if(!d.some(y=>Md(n,y))){const y=d.map(([C,v])=>`${C} (chain ${v})`).join(", ");throw new Ae("ROUTE_UNSUPPORTED_INPUT",`Input token "${n[0]}" on chain ${n[1]} is not in the action's supported input tokens. Supported: ${y}.`,{inputToken:{symbol:n[0],chainId:n[1]},supportedInputTokens:d})}const i=Ro(n),p=Ro(t.outputToken),u=ca({sourceAsset:i,outputAsset:p,sourceChainId:i.chainId,destinationChainId:t.chainId,intermediaryCandidates:c}),{chainBatches:m,solverFrontToken:h,solverFrontAmount:f,resolvedSwaps:g}=await da({route:u,sourceAmount:o,userAddress:r,registry:s,actionCalls:t.calls,slippage:a});return{chainBatches:m,route:u,resolvedSwaps:g,resolvedInputToken:i,resolvedOutputToken:p,solverFrontToken:h,solverFrontAmount:f}}const Wd=[0n,1n,30n],Nd=new Set(["ABORT","CONCURRENT_EXECUTION","WALLET_DISCONNECTED","WALLET_REJECTED","NO_VENUE_FOR_CHAIN"]);function si(e,t){return t===0n?e:e*(1000n-t)/1000n}async function Ud(e,t){const{chainId:n,swapCalls:o,quoteAmountOut:s,buildActionCalls:r,tokenAddress:a,tokenTransferAmount:c,onProgress:d,signal:i,options:p,buffers:u=Wd}=t;for(let m=0;m<u.length;m++){const h=u[m],f=si(s,h),g=r(f),y=[{chainId:n,calls:[...o,...g]}];try{return await e(y,a,c,d,i,p)}catch(C){const v=typeof C?.message=="string"?C.message:String(C?.message??"");if(lr(C)&&Nd.has(C.code)||C.name==="AbortError"||i?.aborted||v.includes("User rejected")||v.includes("User denied")||C.code===4001||m>=u.length-1)throw C;const T=Number(u[m+1])/10;console.warn(`[SwapThenAction] Action attempt ${m+1} failed (buffer ${Number(h)/10}%), retrying with ${T}% buffer...`,C.message),d?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${T}% buffer)...`})}}throw new Ae("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:u.length,chainId:n})}Wi();export{fd as AccountDisplay,Us as AddFundsLink,Yr as CheckIcon,$n as ChevronIcon,go as CloseIcon,Co as DetailRow,nu as NATIVE_TOKEN_ADDRESS,Os as ProviderLogin,tr as SATSUMA_CITREA_CONFIG,ou as SPICENET_NATIVE_CHAIN_ID,su as SPICE_COMBINED_FEE_RECIPIENT,ru as SPICE_GAS_FEE_RECIPIENT,au as SPICE_PLATFORM_FEE_RECIPIENT,iu as SPICE_SOLVER_ADDRESS,ws as SearchInput,fc as SelectChainModal,pc as SpiceDeposit,Gd as SpiceFlowProvider,Zt as SpiceFlowProviderContext,ya as SpiceLock,ya as SpiceLockModal,Ed as SpiceSupply,Bc as SpiceWithdraw,Ae as SpiceflowError,qn as Spinner,wo as StatusBanner,Xa as UNIV3_BASE_CONFIG,si as applyBuffer,lu as applySlippage,Bo as areEquivalentOnChains,Jd as buildDarkPalette,Dd as buildIntent,$d as buildLightPalette,Aa as buildPayChainBatches,da as buildRoutedBatches,Sa as buildSupplyChainBatches,cu as buildUniV3SwapCalls,Ka as create1inchVenue,_a as createExactOutputRegistry,$a as createLiquidityRegistry,Ga as createSatsumaVenue,gn as duration,Gt as easing,Ba as estimateFeePreview,Ea as estimateRequiredGrossFunding,Fa as estimateSupplyMaxAmount,_s as executeDirectExternalAction,Na as executeNon7702Pay,Wa as executeNon7702Supply,Ua as executePay,Da as executeSupply,Ud as executeSwapThenAction,jn as findEquivalentOnChain,Vs as findTokenOnChain,gr as font,Vo as getAssetChainTokenCandidates,Va as getBestUniV3Quote,Ee as getChainConfig,du as getChainIdsByNetwork,fn as getChainName,uu as getEscrowContractAddress,Qa as getUniV3Quote,pu as isNativeToken,lr as isSpiceflowError,fu as isSpicenetChainId,Oa as isSupportedSupplyAsset,qa as isSwapIntent,hu as normalizeNativeTokenAddress,bs as radius,vt as relayerService,Rn as resolveAssetTokenAddressOnChain,Rr as resolveFundedToken,Ad as resolveInputSupplySwapQuote,ca as resolveRoute,_d as resolveTheme,Ro as resolveTokenRef,Wn as scaleTokenAmount,mu as spicenetAbi,gu as spicenetWithdrawalAbi,Sn as transition,Fd as useAssetInput,eu as useIsUserWhitelisted,Bd as useLockDuration,Td as useSmartWallet,To as useSpiceAssets,Bt as useSpiceBrand,bo as useSpiceExecution,xa as useSpicePendingDeposits,ja as useSupplyAssets,ti as useSupplyQuote,Pn as useWallet,ro as z};
108
+ `})]}),document.body):null;return x(kn,{children:[Ut,nt,E&&mr.createPortal(l(Jr,{isOpen:!0,onClose:V,supportedChains:[E.chainId],escrowOnly:!0,escrowTokenAddress:E.tokenAddress,escrowAmount:E.amount,escrowTokenDecimals:E.tokenDecimals,escrowTokenSymbol:E.tokenSymbol,styles:d,onDepositSuccess:$}),document.body)]})},hd="0xa9059cbb";function Ca(e,t,n){return Ue(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:Tt({abi:Fe,functionName:"transfer",args:[n,t]})}}function va(e,t,n){return{chainId:n,calls:[Ca(e,t,hn(n))]}}function ka(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function Ia(e,t,n,o){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(hd)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function is(e,t,n,o){if(!t)return[e];const s=await t({...n,requestTimestampMs:o});return s?[s,e]:[e]}function Gs(e){return e.filter(t=>t.domain!=="spicenet")}function ls(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:It(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function Wn(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return(e+o-1n)/o}async function Aa(e,t){const{currentPaymentAmount:n,destinationToken:o,embeddedWalletAddress:s,providerEmbeddedAddress:r,address:a,isNon7702:c,isPayMode:d,resolvedChainId:i,buildActionCalls:p,feeExecutionMode:u,buildSpicenetBatch:m,selectedAsset:h,needsSwap:f,exactOutputSwap:g,resolvedTokenIn:y,requestTimestampMs:C}=e,v=ze(n,o.decimals),T=t?.actionAmountOverride??v,b=s||r||(c?void 0:a);if(!b)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:b,chainId:i,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??v,netAmount:T,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},B=p(T,w),E={chainId:i,calls:B},M=!d&&!c?!0:h?.asset?._source==="spice",F=ka(h??null,c,i),k=M||c||F,S=(A,W)=>({token:A,from:"escrow",to:b,amount:W}),I=(A,W,P)=>F?[va(A,W,i),...P]:P;if(v===0n)return[E];if(f&&g){const A=y??Rn(h.asset,i)??h.asset.address,W=t?.fundingAmountOverride??g.amountInMax,P=k?[S(A,W)]:[],z={to:A,value:0n,data:Tt({abi:Fe,functionName:"approve",args:[g.calls[0]?.to,g.amountInMax]})},N={chainId:i,calls:[z,...g.calls,...B],tokenTransfers:[...P,...E.tokenTransfers??[]]};if(!k)return[N];const D=await is(N,m,{userAddress:b,destinationChainId:i,deliveryToken:A,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:ls(N),sourceAsset:h.asset},C);return I(A,W,D)}if(k){const A=y??Rn(h.asset,i)??o.address;if(F&&A.toLowerCase()===o.address.toLowerCase())return[E];const W=t?.fundingAmountOverride??v,P={...E,tokenTransfers:[S(A,W),...E.tokenTransfers??[]]},z=await is(P,m,{userAddress:b,destinationChainId:i,deliveryToken:A,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:ls(P),sourceAsset:h.asset},C);return I(A,W,z)}return[E]}async function Sa(e,t){const{selectedAsset:n,embeddedWalletAddress:o,externalWalletAddress:s,recipient:r,resolvedChainId:a,destinationToken:c,buildActionCalls:d,feeExecutionMode:i,buildSpicenetBatch:p,isPayMode:u,isNon7702:m,needsSwap:h,resolvedSwap:f,quoteAmountOut:g,resolvedTokenIn:y,requestTimestampMs:C}=e,v=f?.amountOutMinimum??g;if(!n?.asset||!o)return[];const T=r??(m?s:o);if(!T)return[];const b=t?.fundingAmountOverride??t?.actionAmountOverride??ze(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??b,B=t?.sourceFundingAmountOverride??b,E=t?.deliveryAmountOverride??w,M=t?.withdrawalAmountOverride??E,F=t?.actionAmountOverride??b,k={userAddress:T,chainId:a,destinationToken:c.address,feeToken:i==="user-transfer"&&h&&y?y:c.address,grossAmount:w,netAmount:F,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:i,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},S=d(F,k),I=n.asset?._source==="wallet";if(!u&&m&&I&&n.asset.chainId===a){if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!f||v===null)throw new Error("Swap quote not available yet")}if(h&&f&&v){const U=d(t?.actionAmountOverride??v,{...k,netAmount:t?.actionAmountOverride??v}),{feeCall:Z,remainingCalls:he}=Ia(U,i,h,k.feeToken);return[{chainId:a,calls:[...Z?[Z]:[],...f.calls,...he]}]}return[{chainId:a,calls:S}]}if(!u&&!m&&I&&n.asset.chainId!==a)throw new Error("Cross-chain wallet supplies require external wallet mode");const A=!u&&!m?n.asset?._source!=="wallet":n.asset?._source==="spice",W=m&&I,P=ka(n,m,a);if(!(A||W||P))return[{chainId:a,calls:S}];const z=P?va(y??It(n.asset.address),B,a):W&&n.asset.chainId!==a?{chainId:n.asset.chainId,calls:[Ca(It(n.asset.address),B,hn(n.asset.chainId))]}:null,N=(U,Z)=>({token:U,from:W?"solver":"escrow",to:o,amount:Z}),D=(U,Z)=>W?[{token:U,from:"escrow",to:Ii,amount:Z}]:[];if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!f||v===null)throw new Error("Swap quote not available yet")}if(h&&f&&v&&y){const U=d(t?.actionAmountOverride??v,{...k,netAmount:t?.actionAmountOverride??v}),{feeCall:Z,remainingCalls:he}=Ia(U,i,h,k.feeToken),Q={chainId:a,calls:[...Z?[Z]:[],...f.calls,...he],tokenTransfers:[...D(y,M),N(y,E)]},G=await is(Q,p,{userAddress:o,destinationChainId:a,deliveryToken:y,deliveryAmount:E,withdrawalAmount:M,deliveryRecipient:o,deliveryTransfers:ls(Q),sourceAsset:n.asset},C);return z?[z,...G]:G}const H=y??Rn(n.asset,a)??c.address,O={chainId:a,calls:S,tokenTransfers:[...D(H,M),N(H,E)]},_=await is(O,p,{userAddress:o,destinationChainId:a,deliveryToken:H,deliveryAmount:E,withdrawalAmount:M,deliveryRecipient:o,deliveryTransfers:ls(O),sourceAsset:n.asset},C);return z?[z,..._]:_}async function Ea(e,t,n,o,s){let r=e;for(let a=0;a<4;a++){const c=await t(r),d=await o(c,n,r,s),i=Dl(d);if(i===null||i>=e)return r;const p=r-i,u=e+p;if(u<=r)return r;r=u}return r}function md(e,t,n,o){if(e<=0n)return 0n;const s=e-t;if(s<=0n)return 0n;const r=o+n;return r<=0n?s:s*o/r}async function Fa(e){const{asset:t,isPayMode:n,isNon7702:o,needsSwap:s,isQuoting:r,embeddedWalletAddress:a,buildSupplyChainBatches:c,estimate:d,executionTokenAddress:i,feeExecutionMode:p}=e;if(n||o||s||r||!a||t.balance<=0n)return null;const u=a,m=await c({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(m.length===0)return null;const h=m.some(T=>T.tokenTransfers?.length),f=await d(m,i,t.balance,h?{userOverride:u,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:u,feeExecutionMode:p}:{userOverride:u}),g=Jn(f,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),y=g?Wn(g.gasFee,g.decimals,t.decimals):0n,C=g?Wn(g.spicenetFee,g.decimals,t.decimals):0n,v=md(t.balance,y,C,t.balance);return v>0n?zr(v,t.decimals):null}async function Ba(e){const{selectedAsset:t,isPayMode:n,parsedAmount:o,needsSwap:s,exactOutputSwap:r,isNon7702:a,isSourceDestToken:c,currentPaymentAmount:d,destinationToken:i,feeExecutionMode:p,resolvedTokenIn:u,embeddedWalletAddress:m,providerEmbeddedAddress:h,resolvedChainId:f,isConnected:g,address:y,ready:C,authenticated:v,isDirect:T,resolvedSwap:b,isQuoting:w,executionTokenAddress:B,buildPayChainBatches:E,buildSupplyChainBatches:M,estimate:F,estimateRequiredGrossFunding:k}=e;if(!t?.asset)return null;if(n){if(o<=0||s&&!r||c)return null;const D=ze(d,i.decimals),H=u||Rn(t.asset,f)||t.asset.address||i.address,O={chainId:f,tokenAddress:H,symbol:Qt(H,f)?.symbol??t.asset.symbol,decimals:Qt(H,f)?.decimals??t.asset.decimals};if(a){const G=m||h;if(!G)return null;const de=s?r?.amountInMax??0n:D;if(de===0n)return null;const ve={userOverride:G,useCustomTransfers:!0},ce=await k(de,Se=>E({fundingAmountOverride:Se}),H,ve),me=await E({fundingAmountOverride:ce}),ue=await F(me,H,ce,{...ve,feeExecutionMode:p});return Jn(ue,O)}if(!g||!y||!C||!v)return null;const _=m||h||y,U=s?r?.amountInMax??0n:D;if(U===0n)return null;const Z=await k(U,G=>E({fundingAmountOverride:G}).then(de=>Dn(Gs(de),_)),H,{useCustomTransfers:!0});let he=Dn(Gs(await E({fundingAmountOverride:Z})),_);const Q=await F(he,H,Z,{useCustomTransfers:!0,feeExecutionMode:p});return Jn(Q,O)}if(o<=0||!m)return null;const S=m||h;if(!(!n&&!a&&t.asset?._source==="wallet"&&t.asset.chainId!==f)&&!T&&!b&&!w||w)return null;const I=ze(t.amount,t.asset.decimals),A=await M();if(A.length===0)return null;const W=a&&t.asset?._source==="wallet"&&t.asset.chainId===f,P={chainId:f,tokenAddress:B,symbol:Qt(B,f)?.symbol??i.symbol,decimals:Qt(B,f)?.decimals??i.decimals};if(W){const D=await vt.estimateBatchGas({user:S,outputToken:B,stepIndex:0,chainBatches:A}),H=Xo(I,10n),O=H+D.gasFee;return{...P,grossAmount:I+O,netAmount:I,totalFee:O,gasFee:D.gasFee,spicenetFee:H,bridgeFee:0n,gasQuoteSource:D.gasQuoteSource}}const z=A.some(D=>D.tokenTransfers?.length),N=await F(A,B,I,z?{userOverride:S,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:S,feeExecutionMode:p}:{userOverride:S});return Jn(N,P)}const gd=10n;function Ta(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const o=Rn(n,e.resolvedChainId);if(!o||!Ie(o,e.executionTokenAddress))return;const s=Qt(e.executionTokenAddress,e.resolvedChainId),r=Wn(t,s?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const a=pt(r,n.decimals),c=pt(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${a} ${n.symbol}; available ${c} ${n.symbol}.`)}function Js(e){const t=Qt(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Mo(e,t,n){const o=Jn(e,Js(t));if(!o)return;const s=Xo(n,gd),r=o.bridgeFee??0n,a=s+o.gasFee+r;return{grossAmount:n+a,netAmount:n,combinedFeeAmount:a,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:s,gasFee:o.gasFee,bridgeFee:r}}}function Ma(e,t,n){let o=0n,s=0n;const r=n.toLowerCase();for(const a of e)if(a.chainId===t){for(const c of a.calls??[])if(c.to.toLowerCase()===r)try{const d=Lo({abi:Fe,data:c.data});if(d.functionName!=="transfer")continue;const i=d.args[0].toLowerCase(),p=d.args[1];i===so.toLowerCase()?o+=p:i===An.toLowerCase()&&(s+=p)}catch{continue}}return{spicenetFee:o,gasFee:s}}function $s(e,t,n){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,s=Ma(e,t.resolvedChainId,o);return s.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||s.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Gn(s.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Gn(s.gasFee,n.feeBreakdown.gasFee,100n)}function Ra(e,t){return e?Gn(e.grossAmount,t.grossAmount,100n)&&Gn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Gn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Gn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function Da(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const o=await _s(e);e.ui.setTxHash(o??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const o=new AbortController;e.refs.abortControllerRef.current=o,await Wa(e,o.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(o){const s=o instanceof Error?o:new Error(String(o));if(s.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(s)}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=ze(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=n;let s=await e.execution.buildSupplyChainBatches();const r=e.selectedAsset.asset?._source==="wallet",a=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!r&&!s.some(h=>Ao(h.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const c=s.some(h=>h.tokenTransfers?.length)?{userOverride:a,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:a,feeExecutionMode:e.feeExecutionMode}:{userOverride:a};let d=n;const i=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!i?o:void 0;let u;for(let h=0;h<4;h+=1){const f=await e.execution.estimate(s,e.executionTokenAddress,d,c),g=Jn(f,Js(e));u=e.feeExecutionMode==="user-transfer"&&g?Mo(f,e,o):void 0;const y=u?.grossAmount??g?.grossAmount??d;if(y===d){d=y;break}d=y,s=await e.execution.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u})}e.feeExecutionMode==="user-transfer"&&(Ta(e,d),s=await e.execution.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u}));let m=u;await e.execution.execute(s,e.executionTokenAddress,d,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:h,chainBatches:f})=>{const g=Mo(h,e,o);if(!g)return null;const y=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;Ma(f,e.resolvedChainId,y);const C=Ra(m,g),v=$s(f,e,g);return C||v?null:(m=g,e.execution.buildSupplyChainBatches({fundingAmountOverride:g.grossAmount,actionAmountOverride:p,actionContextOverride:g}))}}:c),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const o=n instanceof Error?n:new Error(String(n));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const s=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(s),e.ui.setError(s),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function Wa(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const o=e.selectedAsset.asset,s=ze(e.selectedAsset.amount,o.decimals),r=s,a=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let c=await e.execution.buildSupplyChainBatches();const d={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let i=s;const p=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,u=e.feeExecutionMode==="user-transfer"&&!p?r:void 0;let m;if(a){const k=await vt.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:c}),S=Xo(s,10n),I=S+k.gasFee;i=s+I,e.feeExecutionMode==="user-transfer"&&(m={grossAmount:i,netAmount:r,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:S,gasFee:k.gasFee,bridgeFee:0n}})}else for(let k=0;k<4;k+=1){const S=await e.execution.estimate(c,e.executionTokenAddress,0n,d),I=e.feeExecutionMode==="user-transfer"?Mo(S,e,r):void 0,A=Jn(S,Js(e)),W=I?.grossAmount??(A?A.grossAmount>s?A.grossAmount:s:i);if(m=I,W===i){i=W;break}i=W;const P=Qt(e.executionTokenAddress,e.resolvedChainId),z=Wn(i,P?.decimals??e.destinationToken.decimals,o.decimals);c=await e.execution.buildSupplyChainBatches({fundingAmountOverride:i,sourceFundingAmountOverride:z,withdrawalAmountOverride:i,actionAmountOverride:u,actionContextOverride:I})}const h=Qt(e.executionTokenAddress,e.resolvedChainId);let f=a?i:Wn(i,h?.decimals??e.destinationToken.decimals,o.decimals);Ta(e,i),c=await e.execution.buildSupplyChainBatches({fundingAmountOverride:i,sourceFundingAmountOverride:f,withdrawalAmountOverride:i,actionAmountOverride:u,actionContextOverride:m});const g=o.chainId,y=n,C=await e.externalWallet.getEthereumProvider();await vo(C,g,()=>e.ui.setStatusMsg("Switching source network..."));const v=Ee(g),T=Yn({account:e.externalWalletAddress,chain:v?.viemChain,transport:Kn(C)}),b=It(o.address),w=o.isNative||Ue(b),B=gt(g),E=k=>ha({extWc:T,sourceClient:B,recipient:y,tokenAddr:b,isNative:w,amount:k,viemChain:v?.viemChain});e.ui.setStatusMsg("Funding embedded wallet..."),await E(f);let M=f;if(e.feeExecutionMode==="user-transfer")for(let k=0;k<4;k+=1){const S=await e.execution.estimate(c,e.executionTokenAddress,0n,d),I=Mo(S,e,r);if(!I)break;const A=a?I.grossAmount:Wn(I.grossAmount,h?.decimals??e.destinationToken.decimals,o.decimals);if(A>M&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await E(A-M),M=A),m=I,i=I.grossAmount,f=A,c=await e.execution.buildSupplyChainBatches({fundingAmountOverride:i,sourceFundingAmountOverride:f,withdrawalAmountOverride:i,actionAmountOverride:u,actionContextOverride:I}),$s(c,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let F=m;await e.execution.execute(c,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:k,chainBatches:S})=>{const I=Mo(k,e,r);if(!I)return null;const A=Ra(F,I),W=$s(S,e,I);if(A||W)return null;if(I.grossAmount>i)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");F=I;const P=a?I.grossAmount:Wn(I.grossAmount,h?.decimals??e.destinationToken.decimals,o.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:P,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:u,actionContextOverride:I})}}:d)}async function _s(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,o=e.activeSignerAddress??e.externalWalletAddress;if(!o||!n)throw new Error("Please connect your wallet to continue");const s=ze(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),r={userAddress:o,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},a=e.buildActionCalls(s,r);if(a.length===0)throw new Error("No action calls configured");const c=await n.getEthereumProvider();await vo(c,e.resolvedChainId);const d=Ee(e.resolvedChainId),i=Yn({account:o,chain:d?.viemChain,transport:Kn(c)}),p=gt(e.resolvedChainId);let u;for(const m of a){const h=await i.sendTransaction({to:m.to,data:m.data,value:m.value,chain:d?.viemChain});if((await p.waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");u=h}return u}async function Na(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,o=n.chainId,s=ze(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?s:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const a=e.resolvedTokenIn||e.selectedAsset.asset.address,c={userOverride:t,useCustomTransfers:!0},d=await e.execution.estimateRequiredGrossFunding(r,C=>e.execution.buildPayChainBatches({fundingAmountOverride:C}),a,c),i=hn(o),p=await e.externalWallet.getEthereumProvider();await vo(p,o);const u=Ee(o),m=Yn({account:e.externalWalletAddress,chain:u?.viemChain,transport:Kn(p)}),h=It(n.address),f=n.isNative||Ue(h)?await m.sendTransaction({to:i,value:d,chain:u?.viemChain}):await m.sendTransaction({to:h,data:Tt({abi:Fe,functionName:"transfer",args:[i,d]}),chain:u?.viemChain});if((await gt(o).waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const g=await e.execution.buildPayChainBatches({fundingAmountOverride:d}),y=g.some(C=>C.tokenTransfers?.length);return await e.execution.execute(g,a,d,C=>{C.txHash&&(e.ui.setPaymentResult(v=>({...v??{status:"processing"},txHash:C.txHash})),e.ui.setTxHash(C.txHash))},void 0,y?c:{userOverride:t})}async function Ua(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let o;if(e.isSourceDestToken||e.parsedAmount===0)o=await _s(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,r=ze(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const c=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!c)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const d=e.resolvedTokenIn||s.address,i=await e.execution.estimateRequiredGrossFunding(a,m=>e.execution.buildPayChainBatches({fundingAmountOverride:m}),d,{userOverride:c,useCustomTransfers:!0}),p=await e.execution.buildPayChainBatches({fundingAmountOverride:i}),u=await e.onPayExecute({asset:s,amount:e.currentPaymentAmount,amountWei:r,destinationToken:e.destinationToken,chainBatches:p,requiredNetFunding:a,grossFundingAmount:i,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:d,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});u&&(e.ui.setTxHash(u),e.ui.setPaymentResult(m=>({...m??{status:"processing"},txHash:u}))),o=u||void 0}else o=await Na(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||o||""}))}catch(o){const s=In(o,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(o instanceof Error?o:new Error(s))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=ze(e.currentPaymentAmount,e.destinationToken.decimals),o={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const y=await e.execution.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),C=await e.execution.execute(y,e.destinationToken.address,0n,v=>{v.txHash&&(e.ui.setPaymentResult(T=>({...T,txHash:v.txHash})),e.ui.setTxHash(v.txHash))},void 0,o);e.ui.setPaymentResult(v=>({status:"success",txHash:v?.txHash||C}));return}const s=e.selectedAsset?.asset;if(!s)throw new Error("Select a payment source");const r=e.resolvedTokenIn||s.address||e.destinationToken.address,a=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,c=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,d=(y,C,v)=>{const T=Gs(y),b=E=>(E.tokenTransfers??[]).some(M=>M.from==="escrow"),w=T.filter(E=>!b(E)),B=T.filter(b);return[...w,...Dn(B,c,C,v)]},i=await e.execution.estimateRequiredGrossFunding(a,y=>e.execution.buildPayChainBatches({fundingAmountOverride:y}).then(C=>d(C)),r,o);let p=i,u=d(await e.execution.buildPayChainBatches({fundingAmountOverride:i}));const m=await e.execution.estimate(u,r,i,o),h=Jn(m,{chainId:e.resolvedChainId,tokenAddress:r,symbol:Qt(r,e.resolvedChainId)?.symbol??s.symbol,decimals:Qt(r,e.resolvedChainId)?.decimals??s.decimals})?.grossAmount??i;h!==i&&(p=h),u=d(await e.execution.buildPayChainBatches({fundingAmountOverride:p}),m,{payoutAlreadyGross:!0});const f=u.some(y=>y.tokenTransfers?.length),g=await e.execution.execute(u,r,f?p:0n,y=>{y.txHash&&(e.ui.setPaymentResult(C=>({...C,txHash:y.txHash})),e.ui.setTxHash(y.txHash))},void 0,o);e.ui.setPaymentResult(y=>({status:"success",txHash:y?.txHash||g}))}catch(n){const o=In(n,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(n instanceof Error?n:new Error(o))}finally{e.ui.setIsExecuting(!1)}}const yd=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:c,cardBg:d,cardBorder:i,dk:p,dark:u,isQuoting:m,quoteError:h,estimatedOutput:f,paymentAmount:g,needsSwap:y,exactOutputSwap:C,adjustable:v=!1,maxAmount:T,onAmountChange:b})=>e==="supply"?x("div",{style:{backgroundColor:d,border:`1px solid ${i}`,borderRadius:u?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[x("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[x("div",{style:{minWidth:0},children:[l("span",{style:{fontFamily:r,fontSize:"17px",fontWeight:500,color:u?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),l("div",{style:{fontSize:"12px",fontWeight:500,color:c,fontFamily:r,marginTop:"10px"},children:"Net amount after swap and fees"})]}),x("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${i}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[l(za,{symbol:t,logoURI:n,primaryColor:s,size:24}),l("span",{style:{fontSize:"16px",fontWeight:500,color:u?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:r,letterSpacing:0},children:t})]})]}),l("div",{style:{textAlign:"right",minWidth:0},children:m?l("span",{style:{fontSize:"18px",color:c,fontFamily:r},children:"Quoting..."}):h?l("span",{style:{fontSize:"13px",color:u?"#f87171":"#dc2626",fontFamily:r},children:"Quote failed"}):f?l(ao,{value:f,title:f,fontFamily:r,color:a,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):l("span",{style:{fontSize:"20px",color:c,fontFamily:r},children:"\u2014"})})]}):l(xd,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:c,cardBg:d,cardBorder:i,dk:p,dark:u,paymentAmount:g||"0",needsSwap:y,exactOutputSwap:C,isQuoting:m,adjustable:v,maxAmount:T,onAmountChange:b}),Pa=pn(yd),za=({symbol:e,logoURI:t,primaryColor:n,size:o})=>t?l("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):l("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),xd=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:o,fontFamily:s,textPrimary:r,textSecondary:a,cardBg:c,cardBorder:d,dk:i,dark:p,paymentAmount:u,needsSwap:m,exactOutputSwap:h,isQuoting:f,adjustable:g,maxAmount:y,onAmountChange:C})=>{const v='"IBM Plex Mono", monospace',T=parseFloat(u||"0"),b=y?parseFloat(y):0,[w,B]=R(u||""),E=le(null),[M,F]=R(null),[k,S]=R(null);X(()=>{g||B(u||"")},[u,g]);const I=P=>{let z=P;z.startsWith(".")&&(z="0"+z);const N=uo(z);let D=N;y&&parseFloat(N)>parseFloat(y)&&(D=y),B(D),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>C?.(D),300)},A=P=>{if(!b)return;if(P===100){B(y||b.toString()),E.current&&clearTimeout(E.current),C?.(y||b.toString());return}const z=10**n,N=Math.floor(b*P/100*z)/z,D=po(N,n);B(D),E.current&&clearTimeout(E.current),C?.(D)},W=b>0?parseFloat(w||"0")/b*100:0;return X(()=>()=>{E.current&&clearTimeout(E.current)},[]),x("div",{style:{backgroundColor:c,border:`1px solid ${d}`,borderRadius:p?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[x("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[x("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[l(za,{symbol:e,logoURI:t,primaryColor:o,size:32}),x("div",{children:[l("span",{style:{fontSize:"14px",fontWeight:600,color:r,fontFamily:s},children:"Payment"}),l("div",{style:{fontSize:"12px",color:a,fontFamily:s,marginTop:"2px"},children:e})]})]}),x("div",{style:{textAlign:"right"},children:[g?l(ao,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:P=>I(P.target.value),placeholder:"0.0",fontFamily:v,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):l(ao,{element:"div",value:T>0?u:"0.00",title:T>0?u:"0.00",fontFamily:v,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),l("div",{style:{fontSize:"12px",color:a,fontFamily:v,marginTop:"2px"},children:e}),g&&b>0&&l("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((P,z)=>{const N=Math.abs(W-P)<1,D=z===4,H=P/100,O=M===P,_=k===P;return l("button",{onClick:()=>A(P),onMouseEnter:()=>F(P),onMouseLeave:()=>{F(null),S(null)},onMouseDown:()=>S(P),onMouseUp:()=>S(null),title:`${P}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:N?1:O?.8:.5,transform:_?"scale(0.85)":O?"scale(1.15)":"scale(1)",transition:Sn.interactive},children:x("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[l("circle",{cx:"7",cy:"7",r:"6.84375",fill:D?o:"none",stroke:D?o:p?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!D&&H>0&&l("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${H>.5?1:0} 1 ${7+6.84375*Math.sin(H*2*Math.PI)} ${7-6.84375*Math.cos(H*2*Math.PI)} Z`,fill:p?i?.textSecondary||"#9ca3af":"#3C3E42"})]})},P)})})]})]}),m&&h&&!f&&l("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:p?`1px solid ${i?.cardBorder||d}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:x("span",{style:{fontSize:"11px",color:a,fontFamily:s,opacity:.7},children:["via ",h.venue]})})]})};function La(e,t,n){const o=Ie(e.address,t),s=e.chainId===n,r=e._source==="wallet";return r&&o&&s?0:r&&s?1:!r&&o?2:!r&&s?3:4}function Oa(e,t){return!t||t.length===0||t.some(n=>Ie(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const o=yo(n);return o?t.some(s=>Ie(s,o.address)):!1})}function Ha(e,t,n){let{symbol:o,name:s,logoURI:r}=t;const a=Ie(e.address,n.address)&&e.chainId===n.chainId;a&&n.logoURI&&(r=n.logoURI),a&&!e.configToken&&o==="TOKEN"&&(o=n.symbol,s=n.symbol);const c=parseFloat((Number(t.balance)/Math.pow(10,t.decimals)).toFixed(6));return{address:e.address,name:s,symbol:o,decimals:t.decimals,balance:t.balance,balanceFormatted:c,balanceUsd:0,logoURI:r,isNative:!1,chainId:e.chainId}}function ja(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:o,enabled:s}=e,r=rn(Zt),a=(r?.mode||"7702")!=="7702",c=r?.embeddedWalletAddress,{externalAddress:d,embeddedAddress:i,activeAddress:p}=mo(),u=c||i,{assets:m,refetch:h}=To({address:u,supportedChains:o,enabled:s&&!a&&!!u,refetchInterval:3e4}),f=oe(()=>a?[]:m.filter(F=>Oa(F,n)),[m,n,a]),g=a?p??d:c,y=oe(()=>{const F=new Set,k=[],S=I=>{if(!I)return;const A=I.toLowerCase();F.has(A)||(F.add(A),k.push(kt(I)))};if(S(t.address),n)for(const I of n)S(I);return k},[a,t.address,n]),C=oe(()=>y.map(F=>F.toLowerCase()).sort().join(","),[y]),v=oe(()=>JSON.stringify([...o||[]].sort()),[o]),[T,b]=R([]),w=le(0),B=le(async()=>{}),E=re(async()=>{if(!s||!g||y.length===0){w.current++,b([]);return}const F=++w.current,k=kt(g),S=a?o&&o.length>0?o:[t.chainId]:[t.chainId],I=[];for(const z of y){const N=z.toLowerCase();if(N===Xt)continue;if(N===t.address.toLowerCase()){const H=Ee(t.chainId)?.supportedTokens?.find(O=>Ie(O.address,N));I.push({address:z,chainId:t.chainId,configToken:H?{decimals:H.decimals,symbol:H.symbol,name:H.name,logo:H.logo}:void 0});continue}let D=!1;for(const H of S){const O=Ee(H)?.supportedTokens?.find(_=>Ie(_.address,N));if(O){I.push({address:z,chainId:H,configToken:{decimals:O.decimals,symbol:O.symbol,name:O.name,logo:O.logo}}),D=!0;break}}D||I.push({address:z,chainId:t.chainId})}const A=new Map;for(const z of I){const N=A.get(z.chainId)||[];N.push(z),A.set(z.chainId,N)}const W=async(z,N)=>{try{const D=await Zn(z,{address:N.address,abi:Fe,functionName:"balanceOf",args:[k]}),{decimals:H,symbol:O,name:_,logoURI:U}=await pa(z,N.address,N.configToken);return Ha(N,{decimals:H,symbol:O,name:_,logoURI:U,balance:D},t)}catch{return null}},P=await Promise.all(Array.from(A.entries()).map(async([z,N])=>{let D;try{D=gt(z)}catch{return[]}const H=[],O=[];for(const U of N){const Z=H.length;H.push({address:U.address,abi:Fe,functionName:"balanceOf",args:[k]}),U.configToken||H.push({address:U.address,abi:Fe,functionName:"decimals"},{address:U.address,abi:Fe,functionName:"symbol"},{address:U.address,abi:Fe,functionName:"name"}),O.push({start:Z,item:U})}let _=null;try{_=await D.multicall({contracts:H})}catch{_=null}return _?O.map(({start:U,item:Z})=>{const he=_[U],Q=he?.status==="success"?he.result:0n;let G,de,ve,ce;if(Z.configToken)G=Z.configToken.decimals,de=Z.configToken.symbol,ve=Z.configToken.name,ce=Z.configToken.logo;else{const me=_[U+1],ue=_[U+2],Se=_[U+3];G=me?.status==="success"?Number(me.result):18,de=ue?.status==="success"?ue.result:"TOKEN",ve=Se?.status==="success"?Se.result:de}return Ha(Z,{decimals:G,symbol:de,name:ve,logoURI:ce,balance:Q},t)}):(await Promise.all(N.map(U=>W(D,U)))).filter(U=>U!==null)}));F===w.current&&b(P.flat())},[s,a,g,C,v,t.address,t.chainId,t.symbol,t.logoURI]);X(()=>{B.current=E},[E]),X(()=>{if(!s){b([]);return}B.current();const F=setInterval(()=>{B.current()},15e3);return()=>clearInterval(F)},[s,a,g,C,v,t.address,t.chainId]);const M=re(()=>{E()},[E]);return{displayAssets:oe(()=>{const F=[],k=T.filter(I=>I.balance>0n);for(const I of k)F.push({...I,_source:"wallet"});for(const I of f)F.push({...I,_source:"spice"});const S=t.address.toLowerCase();return F.sort((I,A)=>La(I,S,t.chainId)-La(A,S,t.chainId)),F},[T,f,t.address,t.chainId]),filteredSpiceAssets:f,walletAssets:T,embeddedWalletAddress:u,externalAddress:d,isNon7702:a,refreshSpiceAssets:h,refreshWalletAssets:M}}async function Qa(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:s,chainId:r,config:a}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const c=(await gt(r).simulateContract({address:a.quoterV2,abi:Ai,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,fee:s,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function Va(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>Qa({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const bd=[{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 wd(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:s,chainId:r,config:a}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const c=(await gt(r).simulateContract({address:a.quoterV2,abi:bd,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,fee:s,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function Cd(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>wd({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function qa(e){return e.type==="swap"}const er=.02,vd=[1,8453,42161,10,137,43114,56],kd="https://api.1inch.dev/swap/v6.0";function Ya(e,t){return Ei(e,t)}function Ka(e){const t=e?.baseUrl??kd;return{name:"1inch",chainIds:e?.chainIds??vd,resolve:async(n,o,s)=>{const r=n.maxSlippage??er,a=r*100,c=Ue(n.tokenIn)?fr:n.tokenIn,d=Ue(n.tokenOut)?fr:n.tokenOut,i=Ue(n.tokenIn);try{const p=new URL(`${t}/${o}/swap`);p.searchParams.set("src",c),p.searchParams.set("dst",d),p.searchParams.set("amount",n.amountIn.toString()),p.searchParams.set("from",s),p.searchParams.set("slippage",a.toString()),p.searchParams.set("disableEstimate","true"),p.searchParams.set("allowPartialFill","false");const u={Accept:"application/json"};e?.apiKey&&(u.Authorization=`Bearer ${e.apiKey}`);const m=await fetch(p.toString(),{headers:u});if(!m.ok)throw new Ae("VENUE_API_ERROR",`[1inchVenue] API returned ${m.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${m.status}`});const h=await m.json();if(!h.dstAmount||!h.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const f=BigInt(h.dstAmount);if(f<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const g=Ya(f,r),y=[];return h.tx.to&&!i&&y.push({to:n.tokenIn,value:0n,data:Tt({abi:Fe,functionName:"approve",args:[h.tx.to,n.amountIn]})}),y.push({to:h.tx.to,value:BigInt(h.tx.value||"0"),data:h.tx.data}),{venue:"1inch",amountOut:f,amountOutMinimum:g,calls:y}}catch(p){if(p instanceof Ae)throw p;const u=p instanceof Error?p.message:String(p);throw new Ae("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${u}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:u})}}}}const Za=[4114,5115],tr={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Xa={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Ga(e){return{name:"satsuma",chainIds:e.chainIds??Za,resolve:async(t,n,o)=>{const s=t.maxSlippage??er,r=Ue(t.tokenIn);let a;try{a=await Va({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 c=Ya(a.amountOut,s),d=[];return r||d.push({to:t.tokenIn,value:0n,data:Tt({abi:Fe,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),d.push({to:e.swapRouter,value:r?t.amountIn:0n,data:Tt({abi:Si,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:a.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:a.amountOut,amountOutMinimum:c,calls:d}}}}function Ja(e){return{name:"satsuma",chainIds:e.chainIds??Za,resolve:async(t,n,o)=>{const s=t.maxSlippage??er,r=Ue(t.tokenIn);let a;try{a=await Cd({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 c=BigInt(Math.round(s*1e4)),d=a.amountIn+a.amountIn*c/10000n,i=[];return i.push({to:e.swapRouter,value:r?d:0n,data:Tt({abi:Id,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:a.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:a.amountIn,amountInMax:d,amountOut:t.amountOut,calls:i}}}}const Id=[{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 $a(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Ga(e.satsuma)),t.push(Ka(e?.oneInch));function n(s){return t.find(r=>r.chainIds.includes(s))}async function o(s,r,a){const c=[],d=[];for(const i of s){if(!qa(i)){c.push(i);continue}const p=n(r);if(!p)throw new Ae("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${r}. Cannot resolve swap ${i.tokenIn} \u2192 ${i.tokenOut}.`,{chainId:r,tokenIn:i.tokenIn,tokenOut:i.tokenOut,amountIn:i.amountIn.toString()});const u=await p.resolve(i,r,a);if(!u)throw new Ae("NO_LIQUIDITY",`${p.name} returned no quote for ${i.tokenIn} \u2192 ${i.tokenOut} on chain ${r}.`,{venue:p.name,chainId:r,tokenIn:i.tokenIn,tokenOut:i.tokenOut,amountIn:i.amountIn.toString()});c.push(...u.calls),d.push(u)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:o,getVenueForChain:n,venues:t}}function _a(e){const t=e?.customVenues??[];async function n(o,s,r){const a=t.filter(i=>i.chainIds.includes(s));if(a.length===0)throw new Ae("NO_SWAP_ROUTE",`No exact-output venue supports chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const c=(await Promise.allSettled(a.map(async i=>({venue:i,quote:await i.resolve(o,s,r)})))).filter(i=>i.status==="fulfilled").map(i=>i.value).filter(i=>i.quote!==null);if(c.length===0)throw new Ae("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});const d=c.find(i=>i.venue.preferred);return d?d.quote:(c.sort((i,p)=>i.quote.amountIn<p.quote.amountIn?-1:i.quote.amountIn>p.quote.amountIn?1:0),c[0].quote)}return{getQuote:n,venues:t}}const ei=$a({satsuma:tr});async function Ad(e){const t=ei.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 ti(e){const{direction:t,selectedAsset:n,destinationToken:o,chainId:s,recipient:r,paymentAmount:a,resolveExactOutputSwap:c}=e,[d,i]=R(!1),[p,u]=R(null),[m,h]=R(null),[f,g]=R(null),[y,C]=R(null),[v,T]=R(null),[b,w]=R(null),[B,E]=R(null),[M,F]=R(null),k=le(null),S=le(null),I=le(0),A=le(new Map),W=oe(()=>ei,[]),P=oe(()=>_a({customVenues:[...c?[{name:"consumer-exact-output",chainIds:[s],preferred:!0,resolve:c}]:[],Ja(tr),Ja(Xa)]}),[c,s]),z=oe(()=>{if(!n?.asset)return null;const G=Rn(n.asset,s);if(G)return G;const de=jn(n.asset.address,s,n.asset.chainId);return de?de.address:null},[n?.asset,s]),N=oe(()=>n?.asset?Vo(n.asset,s):[],[n?.asset,s]),D=oe(()=>N.map(G=>G.toLowerCase()).join(","),[N]);X(()=>{let G=!1;if(S.current&&(clearTimeout(S.current),S.current=null),!n?.asset||N.length<=1){F(null);return}return S.current=setTimeout(async()=>{const de=t==="input"?n.amount:a||"0";let ve=0n;try{ve=t==="input"?ze(de,n.asset.decimals):0n}catch{ve=0n}try{const ce=await Rr(n.asset,s,{requiredAmount:ve});G||F(ce)}catch{G||F(null)}},400),()=>{G=!0,S.current&&(clearTimeout(S.current),S.current=null)}},[n?.asset,n?.amount,s,N.length,D,t,a]);const H=oe(()=>M??z,[M,z]),O=oe(()=>!n?.asset||!H?[]:[H,...N.filter(G=>G.toLowerCase()!==H.toLowerCase())],[n?.asset,H,N]),_=oe(()=>!n?.asset||!Bo(n.asset.address,n.asset.chainId,o.address,o.chainId)||!H?!1:Ie(H,o.address),[n,o.address,o.chainId,H]),U=H?Ie(H,o.address):!1,Z=t==="output"&&parseFloat(a||"0")===0,he=!!n?.asset&&!_&&!U&&!Z,Q=he?B??H:H;return X(()=>{k.current&&clearTimeout(k.current);const G=t==="input"?n?.amount:a,de=parseFloat(G||"0");if(!he||!Number.isFinite(de)||de<=0||!n?.asset||!r||O.length===0){I.current++,h(null),g(null),C(null),T(null),w(null),E(null),u(null),i(!1);return}const ve=n.asset.decimals;let ce;try{ce=t==="input"?ze(n.amount,ve):ze(a||"0",o.decimals)}catch{I.current++,u("Invalid amount"),i(!1);return}const me=++I.current,ue=()=>me!==I.current;i(!0);const Se=t==="output"?150:400;return k.current=setTimeout(async()=>{try{if(t==="input"){const ee=W.getVenueForChain(s);if(!ee)throw new Error("No swap venue for this chain");let V=null,$=null;for(const xe of O){const q=`${t}:${s}:${xe.toLowerCase()}:${o.address.toLowerCase()}:${ce.toString()}`,te=A.current.get(q);if(te&&te.expiresAt>Date.now()&&te.resolvedSwap){V=te.resolvedSwap,$=xe;break}const ge=await ee.resolve({type:"swap",tokenIn:xe,tokenOut:o.address,amountIn:ce},s,r);if(ue())return;if(ge){A.current.set(q,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:ge}),V=ge,$=xe;break}}if(!V||!$)throw new Error("No liquidity for this pair");E($),w(V.amountOut),C(V),T(null);const ae=parseFloat(pt(V.amountOut,o.decimals));h(ae<.01?ae.toPrecision(4):ae.toLocaleString(void 0,{maximumFractionDigits:6})),g(null),u(null)}else{let ee=null,V=null;for(const $ of O){const ae=`${t}:${s}:${$.toLowerCase()}:${o.address.toLowerCase()}:${ce.toString()}`,xe=A.current.get(ae);if(xe&&xe.expiresAt>Date.now()&&xe.exactOutputSwap){ee=xe.exactOutputSwap,V=$;break}try{const q=await P.getQuote({tokenIn:$,tokenOut:o.address,amountOut:ce},s,r);if(ue())return;A.current.set(ae,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:q}),ee=q,V=$;break}catch{if(ue())return}}if(!ee||!V)throw new Error("No liquidity for this pair");E(V),T(ee),C(null),w(null),g(parseFloat(pt(ee.amountIn,ve)).toFixed(6)),h(null),u(null)}}catch(ee){if(ue())return;const V=ee instanceof Error?ee.message:"Failed to get quote";u(V),h(null),g(null),C(null),T(null),w(null),E(null)}finally{ue()||i(!1)}},Se),()=>{k.current&&clearTimeout(k.current)}},[t,he,n?.amount,n?.asset?.address,n?.asset?.decimals,a,O,s,o.address,o.decimals,r,W,P]),{isQuoting:d,quoteError:p,estimatedOutput:m,estimatedInput:f,resolvedSwap:y,exactOutputSwap:v,quoteAmountOut:b,resolvedTokenIn:Q,isDirect:U,needsSwap:he,selectedIsEquivalent:_}}const ni={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},oi=["signing-delegation","signing-intent","submitting","executing"],Sd=()=>{},Ed=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:o,sourceChains:s,supportedSourceAssets:r,buildActionCalls:a,feeExecutionMode:c="user-transfer",buildSpicenetBatch:d,onPayExecute:i,resolveExactOutputSwap:p,actionLabel:u,amountDirection:m="input",swapDescription:h,directDescription:f,paymentAmount:g,amountInputMode:y="fixed",minPaymentAmount:C,maxPaymentAmount:v,onAmountChange:T,styles:b,dark:w,title:B,subtitle:E,onAddFunds:M,onSuccess:F,onError:k})=>{const S=m==="output",{theme:I,dark:A,primaryColor:W,dk:P,palette:z,fontFamily:N,monoFont:D,inputDark:H,cardBg:O,cardBorder:_,textPrimary:U,textSecondary:Z,subtitleText:he}=Bt(b,w),Q=oe(()=>H?{...I,colors:{...I.colors,secondary:P.cardBg,surfaceHover:P.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:I,[H,I,P.cardBg,P.hoverBg]),G=o.chainId,de=rn(Zt),ve=de?.mode||"7702",ce=ve!=="7702",me=!!de?.isWhitelistGateActive,ue=!!de?.isWhitelistConfigured&&de?.isUserWhitelisted!==!0,Se=oe(()=>s??de?.supportedChainIds??[],[s,de?.supportedChainIds]),ee=oe(()=>{if(me)return[];if(r)return r;const ye=de?.allowedTokens;if(!ye||ye.length===0)return;const at=new Set(ye.map(Vn=>Vn.toLowerCase())),Un=[],Qn=new Set;for(const Vn of Se){const cs=Ee(Vn);for(const ds of cs?.supportedTokens??[]){if(!at.has(ds.symbol.toLowerCase()))continue;const nr=ds.address.toLowerCase();Qn.has(nr)||(Qn.add(nr),Un.push(ds.address))}}return Un},[r,de?.allowedTokens,Se,me]),V=Pn(),{address:$,isConnected:ae,isReady:xe,isAuthenticated:q,provider:te}=V,{execute:ge,estimate:se}=bo(),{externalWallet:Le,embeddedAddress:yt,activeWallet:Ot,activeAddress:Ht}=mo(),xt=de?.externalWalletAddress,fe=de?.embeddedWalletAddress||yt,{displayAssets:jt,filteredSpiceAssets:Pe,embeddedWalletAddress:Ve,refreshSpiceAssets:it,refreshWalletAssets:Ut}=ja({destinationToken:o,supportedSourceAssets:ee,sourceChains:Se,enabled:e&&(ce?!!xt:!!fe)}),nt=me||S||ce?jt:Pe;X(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:ve,walletAddressUsed:Ve,count:nt.length,assets:nt.map(ye=>({symbol:ye.symbol,address:ye.address,chainId:ye.chainId,balanceFormatted:ye.balanceFormatted,source:ye?._source}))})},[e,ve,Ve,nt]);const[L,Oe]=R(null),[Me,Je]=R(g||""),[Ze,Jt]=R(!1),[_t,an]=R(null),[Be,en]=R("idle"),[ot,Fn]=R(""),[xn,$e]=R(null),[ln,Vt]=R(!1),[Ye,we]=R(null),[Ke,tt]=R(null),[bn,ke]=R(!1),[$t,Dt]=R(!1),[At,_e]=R(null),Bn=le(L),qt=le(!1),cn=le(null),wn=le(null),Yt=le(0),Mt=le(null),bt=le(null);X(()=>{Bn.current=L},[L]);const He=y==="adjustable"?Me:g||"0",lt=Ve||yt||$,{isQuoting:St,quoteError:dn,estimatedOutput:tn,resolvedSwap:Et,exactOutputSwap:Te,quoteAmountOut:Wt,resolvedTokenIn:ft,isDirect:Nt,needsSwap:ct,selectedIsEquivalent:Re}=ti({direction:m,selectedAsset:L,destinationToken:o,chainId:G,recipient:lt,paymentAmount:He,resolveExactOutputSwap:p}),dt=S?parseFloat(He||"0"):parseFloat(L?.amount||"")||0,nn=dt>0&&dt<Hn,J=L?.asset?._source==="wallet",ne=!!L?.asset&&J&&L.asset.chainId!==G,Ce=oe(()=>L?.asset?Pe.find(ye=>Ie(ye.address,L.asset.address))?.balanceFormatted??0:0,[L,Pe]),je=J?L?.asset.balanceFormatted??0:Ce,et=oe(()=>{if(!L?.asset)return!1;if(S)return Ke?Wn(Ke.grossAmount,Ke.decimals,L.asset.decimals)>L.asset.balance:Re||Nt?dt>L.asset.balanceFormatted:Te?parseFloat(pt(Te.amountInMax,L.asset.decimals))>L.asset.balanceFormatted:!1;if(Ke){const ye=Wn(Ke.grossAmount,Ke.decimals,L.asset.decimals);return J?ye>L.asset.balance:parseFloat(pt(ye,L.asset.decimals))>je}return dt>je},[L,S,Ke,Re,dt,Te,je,J,Nt]);X(()=>{e||(Oe(null),an(null),Jt(!1),en("idle"),Fn(""),$e(null),Vt(!1),we(null),tt(null),ke(!1),Dt(!1),_e(null),qt.current=!1,y==="adjustable"&&Je(g||""),cn.current&&(cn.current.abort(),cn.current=null))},[e]);const ht=re(ye=>{Oe(at=>({asset:ye,amount:at?.asset?.address===ye.address&&at?.asset?.chainId===ye.chainId&&at.amount||""})),an(null),_e(null),Dt(!1)},[]),wt=re(ye=>{Oe(at=>at&&{...at,amount:ye}),an(null),_e(null),Dt(!1)},[]),mt=re(ye=>{let at=ye;v&&parseFloat(at)>parseFloat(v)&&(at=v),Je(at),T?.(at),an(null),_e(null),Dt(!1)},[v,T]);re(ye=>{if(qt.current||!$)return;const at=Bn.current;!at?.asset||!at.amount||at.asset?._source==="wallet"||ze(S?He:at.amount,at.asset.decimals)===0n||(qt.current=!0,it())},[$,G,it,S,He]);const De=re(ye=>{en({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[ye.step]||"executing"),Fn(ye.message),ye.txHash&&$e(ye.txHash)},[]),Rt=oe(()=>({currentPaymentAmount:He,destinationToken:o,embeddedWalletAddress:Ve,providerEmbeddedAddress:yt,externalWalletAddress:xt,address:$,isNon7702:ce,isPayMode:S,resolvedChainId:G,buildActionCalls:a,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:L,needsSwap:ct,resolvedSwap:Et,exactOutputSwap:Te,quoteAmountOut:Wt,resolvedTokenIn:ft}),[He,o,Ve,yt,xt,$,ce,S,G,a,c,d,L,ct,Et,Te,Wt,ft]),Qe=re(ye=>Aa({...Rt,requestTimestampMs:wn.current??Date.now()},ye),[Rt]),Y=re(ye=>Sa({...Rt,requestTimestampMs:wn.current??Date.now()},ye),[Rt]),be=re((ye,at,Un,Qn)=>Ea(ye,at,Un,se,Qn),[se]),Ct=oe(()=>L?.asset?ct&&ft?ft:L.asset.chainId===G?L.asset.address:ft??Rn(L.asset,G)??o.address:o.address,[L,o.address,ct,G,ft]),Ft=re(()=>(wn.current=Date.now(),Da(bt.current)),[]),Xe=oe(()=>L?.asset?Ie(L.asset.address,o.address)&&L.asset.chainId===o.chainId:!1,[L,o.address,o.chainId]),Pt=Xe&&(ce||S),st=Pt&&dt>0&&!!L?.asset,un=ue&&!Pt,j=oe(()=>{if(!st)return null;let ye;try{ye=ze(He||"0",o.decimals)}catch{return null}return{symbol:o.symbol,decimals:o.decimals,grossAmount:ye,netAmount:ye,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[st,He,o.symbol,o.decimals]),K=_t,pe=oe(()=>!(!L?.asset||dt<=0),[L,dt,st]),ie=oe(()=>!e||Ze||Be!=="idle"||!pe||st||!L?.asset?null:[S?"pay":"supply",m,L.asset.address.toLowerCase(),L.asset.chainId,L.amount,He,o.address.toLowerCase(),o.chainId,G,ft?.toLowerCase()??"",ct?"swap":"direct",Nt?"direct-token":"routed-token",ce?"non7702":"7702",Xe?"source-dest":"cross-chain",St?"quoting":"quoted",Te?.amountIn?.toString()??"",Te?.amountInMax?.toString()??"",Te?.venue??"",Et?.amountOut?.toString()??"",Wt?.toString()??"",Ve??"",yt??"",$??""].join("|"),[e,Ze,Be,pe,st,L,S,m,He,o,G,ft,ct,Nt,ce,Xe,St,Te,Et,Wt,Ve,yt,$]),qe=re(()=>Ba({selectedAsset:L,isPayMode:S,parsedAmount:dt,needsSwap:ct,exactOutputSwap:Te,isNon7702:ce,isSourceDestToken:Xe,currentPaymentAmount:He,destinationToken:o,feeExecutionMode:c,resolvedTokenIn:ft,embeddedWalletAddress:Ve,providerEmbeddedAddress:yt,resolvedChainId:G,isConnected:ae,address:$,ready:xe,authenticated:q,isDirect:Nt,resolvedSwap:Et,isQuoting:St,executionTokenAddress:Ct,buildPayChainBatches:Qe,buildSupplyChainBatches:Y,estimate:se,estimateRequiredGrossFunding:be}),[L,S,dt,ct,Te,ce,Xe,He,o,c,ft,Ve,yt,be,Qe,se,G,ae,$,xe,q,Nt,Et,St,Y,Ct]);X(()=>{Mt.current=qe},[qe]);const We=re(ye=>Fa({asset:ye,isPayMode:S,isNon7702:ce,needsSwap:ct,isQuoting:St,embeddedWalletAddress:Ve,buildSupplyChainBatches:Y,estimate:se,executionTokenAddress:Ct,feeExecutionMode:c}),[S,ce,ct,St,Ve,Y,se,Ct,c]);X(()=>{if(!e){ke(!1),Dt(!1),_e(null),tt(null);return}if(Ze||Be!=="idle"){Yt.current+=1,ke(!1);return}if(!pe){tt(null),ke(!1),Dt(!1),_e(null);return}if(st){tt(j),ke(!1),Dt(!0),_e(null);return}if(St){Yt.current+=1,ke(!1),Dt(!1);return}if(!ie)return;let ye=!1;const at=async()=>{const Qn=++Yt.current;_e(null),ke(!0);try{const Vn=await Mt.current?.();if(ye||Yt.current!==Qn)return;Vn?(tt(Vn),Dt(!0)):(tt(null),Dt(!1)),_e(null)}catch(Vn){if(ye||Yt.current!==Qn)return;const cs=In(Vn,"Unable to calculate fees for this action.");tt(null),Dt(!1),_e(cs)}finally{!ye&&Yt.current===Qn&&ke(!1)}},Un=window.setTimeout(()=>{at()},250);return()=>{ye=!0,clearTimeout(Un),ke(!1)}},[e,Ze,Be,pe,st,j,St,ie]);const Ge=re(()=>(wn.current=Date.now(),Ua(bt.current)),[]);X(()=>{!S&&Be==="success"&&xn&&(it(),F?.(xn))},[S,Be,xn,it,F]),X(()=>{if(!S||Ye?.status!=="success"||qt.current||!$)return;qt.current=!0;const ye=Bn.current;!ye?.asset||ye.asset?._source==="wallet"||it()},[S,Ye?.status,$,it]);const ut=le(F),zt=le(k);X(()=>{ut.current=F},[F]),X(()=>{zt.current=k},[k]),X(()=>{e&&(it(),Ut())},[e,it,Ut]),X(()=>{S&&(Ye?.status==="success"&&ut.current?.(Ye.txHash||""),Ye?.status==="failed"&&zt.current?.(new Error("Payment execution failed")))},[S,Ye?.status]);const on=re(()=>{Vt(!1),we(null),Oe(null),qt.current=!1,it(),Ut()},[it,Ut]);bt.current={selectedAsset:L,parsedAmount:dt,currentPaymentAmount:He,isInsufficientBalance:et,isPayMode:S,isNon7702:ce,isSourceDestToken:Xe,needsSwap:ct,exactOutputSwap:Te,selectedIsEquivalent:Re,resolvedTokenIn:ft,embeddedWalletAddress:Ve,providerEmbeddedAddress:yt,externalWallet:Le,externalWalletAddress:xt,activeSignerWallet:Ot,activeSignerAddress:Ht,address:$,isConnected:ae,ready:xe,authenticated:q,provider:te,resolvedChainId:G,executionTokenAddress:Ct,destinationToken:o,buildActionCalls:a,feeExecutionMode:c,buildSpicenetBatch:d,onPayExecute:i,onSuccess:F,onError:k,execution:{estimate:se,execute:ge,buildPayChainBatches:Qe,buildSupplyChainBatches:Y,estimateRequiredGrossFunding:be,onProgress:De},ui:{setError:an,setStep:en,setStatusMsg:Fn,setTxHash:$e,setIsExecuting:Jt,setShowStatusPanel:Vt,setPaymentResult:we},refs:{spiceDepositSubmittedRef:qt,abortControllerRef:cn}};const Cn=g?.trim(),Kt=S&&y==="fixed"&&Cn!==void 0&&Cn!==""&&dt===0,vn=S?(Kt||!!L?.asset)&&dt>=0&&!nn&&!et&&!Ze&&(Kt||st||$t)&&!At&&(Kt||!ct||!!Te)&&!un:!!L?.asset&&dt>0&&!nn&&!et&&!Ze&&(Pt||$t)&&!At&&(ne||Nt||!!Et&&!St)&&!un;X(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:vn,isPayMode:S,hasSelectedAsset:!!L?.asset,selectedAsset:L?.asset?{symbol:L.asset.symbol,address:L.asset.address,chainId:L.asset.chainId,balanceFormatted:L.asset.balanceFormatted,source:L.asset?._source}:null,parsedAmount:dt,isZeroAmountPay:Kt,isBelowMinimum:nn,isInsufficientBalance:et,isExecuting:Ze,directExternalAction:Pt,directExecutionFeeNote:st,feeEstimateReady:$t,feeEstimateError:At,needsSwap:ct,isDirect:Nt,isSourceDestToken:Xe,hasExactOutputSwap:!!Te,isQuoting:St,whitelistHoldPending:ue,supplyHeldForWhitelist:un,isWhitelistGateActive:me,destinationToken:{symbol:o.symbol,address:o.address,chainId:o.chainId}})},[e,vn,S,L,dt,Kt,nn,et,Ze,Pt,st,$t,At,ct,Nt,Xe,Te,St,ue,un,me,o]);const eo=Nt?f||`Your ${o.symbol} will be used directly.`:h||"Your assets will be swapped and used in a single atomic transaction.",co=(G?Ee(G):void 0)?.viemChain?.blockExplorers?.default?.url??"",to=oi.indexOf(Be),Ne=Ze?(ni[Be]||"EXECUTING...").toUpperCase():Be==="success"?"DONE":nn?`MINIMUM ${Hn}`:et?"INSUFFICIENT BALANCE":u.toUpperCase(),rt=oe(()=>{if(Ze)return"PAYING...";if(nn)return`MINIMUM ${Hn}`;if(et&&L?.asset)return`INSUFFICIENT ${L.asset.symbol}`;if(u)return u.toUpperCase();const ye=dt>0?` ${He} ${o.symbol}`:"";return ct?`SWAP & PAY${ye}`:`PAY${ye}`},[Ze,nn,et,L,u,dt,He,o.symbol,ct]),sn=Be==="success"?()=>{en("idle"),Oe(null),$e(null),it()}:Ft,Nn=Be==="success"?!1:!vn;if(!e)return null;const Do=S?B||`Pay ${o.symbol}`:u,ko=S?E:x("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[l("span",{style:{marginTop:"3px",flexShrink:0},children:l(Ns,{color:he})}),l("p",{style:{fontSize:"12px",color:he,margin:0,lineHeight:"1.4",fontFamily:N},children:eo})]});if(S){const ye=Ye&&(Ye.status==="success"||Ye.status==="failed")?[{asset:{symbol:L?.asset?.symbol||o.symbol,address:L?.asset?.address||""},amount:He,txHash:Ye.txHash||"",success:Ye.status==="success",error:Ye.status==="failed"?Ye.error:void 0}]:void 0;return l(Ln,{isOpen:e,onClose:t,title:Do,subtitle:ko,styles:b,dark:A,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:x("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[M&&l("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:l(Us,{onClick:M,color:W,fontFamily:N})}),!Kt&&l("div",{style:{marginBottom:"12px"},children:l(Fo,{assets:nt,selectedAsset:L??void 0,onAssetSelect:ht,onAmountChange:Sd,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:L?.asset?ct?St?"...":Te?`~${parseFloat(pt(Te.amountIn,L.asset.decimals)).toFixed(6)}`:void 0:He??void 0:void 0,dark:A,theme:Q,styles:b})}),l(Pa,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:W,fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:O,cardBorder:_,dk:P,dark:A,isQuoting:St,quoteError:dn,estimatedOutput:tn,paymentAmount:He,needsSwap:ct,exactOutputSwap:Te,adjustable:y==="adjustable",maxAmount:v,onAmountChange:mt}),pe&&l(ts,{fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:O,cardBorder:_,resolvedDark:A,darkCardBorder:P.cardBorder,primaryColor:W,feePreview:Ke,isLoading:bn,errorText:At,directExecutionFeeNote:st}),K&&l(wo,{variant:"error",palette:z,fontFamily:N,style:{marginBottom:"12px"},children:K}),l(Lt,{variant:"outline",fullWidth:!0,onClick:Ge,disabled:!vn,loading:Ze,dark:A,styles:{...b,button:{...b?.button,backgroundColor:W}},children:rt}),Ye&&ln&&l("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:A?P.shell:"white",borderRadius:A?"12px":"6px",padding:"16px 0"},children:l(Hs,{type:"payment",isOpen:Ye.status!=="processing",isProcessing:Ze||Ye.status==="processing",closeOnComplete:!1,chainName:fn(G),explorerUrl:ho(G,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Vt(!1),we(null),Ge()},onNewTx:on,onClose:()=>{Vt(!1),we(null)},onComplete:on,results:ye,styles:b,dark:A})})]})})}return l(Ln,{isOpen:e,onClose:t,title:Do,subtitle:ko,dark:A,styles:b,theme:I,closeOnBackdropClick:n,children:x("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[l("div",{style:{marginBottom:"16px"},children:l(Fo,{assets:nt,selectedAsset:L||void 0,onAssetSelect:ht,onAmountChange:wt,disabled:Ze||Be==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:Q,styles:b,dark:H,resolveMaxAmount:We,maxAmount:je>0?po(je,L?.asset.decimals??o.decimals):void 0})}),L?.asset&&!Nt&&l(Pa,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:W,fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:O,cardBorder:_,dark:A,isQuoting:St,quoteError:dn,estimatedOutput:tn}),pe&&l(ts,{fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:O,cardBorder:_,resolvedDark:A,darkCardBorder:P.cardBorder,primaryColor:W,feePreview:Ke,isLoading:bn,errorText:At,directExecutionFeeNote:st}),Be!=="idle"&&x("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Be==="success"?O:Be==="error"?z.errorBg:O,border:`1px solid ${Be==="success"?_:Be==="error"?z.errorBorder:_}`},children:[x("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Be==="success"?l("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:l("path",{d:"M5 13l4 4L19 7",stroke:z.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Be==="error"?l("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:l("path",{d:"M18 6L6 18M6 6l12 12",stroke:z.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):l(qn,{size:14,color:W}),l("span",{style:{fontSize:"13px",fontWeight:500,color:Be==="success"?U:Be==="error"?z.errorText:U,fontFamily:N,flex:1},children:Be==="success"?"Deposit confirmed":Be==="error"?ot||"Transaction failed":ni[Be]||ot}),Be==="success"&&xn&&l("a",{href:`${co}/tx/${xn}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:W,fontFamily:N,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Be==="error"&&l("button",{onClick:()=>{en("idle"),an(null),setTimeout(Ft,50)},style:{background:"none",border:"none",fontSize:"12px",color:W,fontFamily:N,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),to>=0&&Be!=="success"&&Be!=="error"&&l("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${Z}22`,overflow:"hidden"},children:l("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:W,transformOrigin:"left center",transform:`scaleX(${(to+1)/oi.length})`,transition:"transform 400ms ease"}})})]}),_t&&Be==="idle"&&l(wo,{variant:"error",palette:z,fontFamily:N,style:{marginBottom:"16px"},children:_t}),l(Lt,{variant:"outline",fullWidth:!0,disabled:Nn,onClick:sn,theme:I,dark:A,styles:{...b,button:{...b?.button,backgroundColor:W}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:D},children:Ne})]})})},Fd=()=>{const[e,t]=R("0"),[n,o]=R(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:n,setSelectedAsset:o}};function Bd(e,t=0){const[n,o]=R(t),s=e[n]??e[0],r=oe(()=>s?BigInt(Math.round(s.months*30*24*3600)):0n,[s?.months]);return{selectedDurationIdx:n,setSelectedDurationIdx:o,selectedDuration:s,durationSeconds:r}}function Td(){const{actions:e,isReady:t,isAuthenticated:n}=Pn(),o=rn(Zt)?.embeddedWalletAddress,s=le(!1),r=le(0),a=le(null),c=le(e),[d,i]=R(0);c.current=e,X(()=>{s.current=!1,r.current=0,a.current&&(clearTimeout(a.current),a.current=null)},[o]),X(()=>{if(!o||!t||!n||s.current)return;s.current=!0;let p=!1;return(async()=>{await En(2e3);try{await hi(o,c.current.signMessage),r.current=0}catch(u){console.warn("[SmartWallet] Registration failed:",u),s.current=!1,!p&&r.current<3&&(r.current+=1,a.current=setTimeout(()=>{i(m=>m+1)},5e3))}})(),()=>{p=!0,a.current&&(clearTimeout(a.current),a.current=null)}},[o,t,n,d])}function Ro(e){try{return Fi(e)}catch{throw new Ae("ROUTE_TOKEN_NOT_FOUND",`Token "${e[0]}" not found on chain ${e[1]} in the token registry.`,{symbol:e[0],chainId:e[1]})}}function Md(e,t){if(e[0].toUpperCase()===t[0].toUpperCase()&&e[1]===t[1])return!0;let n,o;try{n=Ro(e),o=Ro(t)}catch{return!1}const s=new Set(pr(o.address).map(r=>r.toLowerCase()));return s.add(o.address.toLowerCase()),s.has(n.address.toLowerCase())}function Rd(){const e=[];for(const t of Object.keys(Bi).map(Number))for(const n of dr(t))e.push([n.symbol,t]);return e}async function Dd(e){const{action:t,inputToken:n,inputAmount:o,registry:s,userAddress:r,slippage:a,intermediaryCandidates:c}=e;if(t.calls.length===0)throw new Ae("INVALID_PARAMS","buildIntent: action.calls must not be empty.",{action:t});if(o<=0n)throw new Ae("INVALID_PARAMS","buildIntent: inputAmount must be greater than zero.",{inputAmount:o.toString()});const d=t.supportedInputTokens??Rd();if(!d.some(y=>Md(n,y))){const y=d.map(([C,v])=>`${C} (chain ${v})`).join(", ");throw new Ae("ROUTE_UNSUPPORTED_INPUT",`Input token "${n[0]}" on chain ${n[1]} is not in the action's supported input tokens. Supported: ${y}.`,{inputToken:{symbol:n[0],chainId:n[1]},supportedInputTokens:d})}const i=Ro(n),p=Ro(t.outputToken),u=ca({sourceAsset:i,outputAsset:p,sourceChainId:i.chainId,destinationChainId:t.chainId,intermediaryCandidates:c}),{chainBatches:m,solverFrontToken:h,solverFrontAmount:f,resolvedSwaps:g}=await da({route:u,sourceAmount:o,userAddress:r,registry:s,actionCalls:t.calls,slippage:a});return{chainBatches:m,route:u,resolvedSwaps:g,resolvedInputToken:i,resolvedOutputToken:p,solverFrontToken:h,solverFrontAmount:f}}const Wd=[0n,1n,30n],Nd=new Set(["ABORT","CONCURRENT_EXECUTION","WALLET_DISCONNECTED","WALLET_REJECTED","NO_VENUE_FOR_CHAIN"]);function si(e,t){return t===0n?e:e*(1000n-t)/1000n}async function Ud(e,t){const{chainId:n,swapCalls:o,quoteAmountOut:s,buildActionCalls:r,tokenAddress:a,tokenTransferAmount:c,onProgress:d,signal:i,options:p,buffers:u=Wd}=t;for(let m=0;m<u.length;m++){const h=u[m],f=si(s,h),g=r(f),y=[{chainId:n,calls:[...o,...g]}];try{return await e(y,a,c,d,i,p)}catch(C){const v=typeof C?.message=="string"?C.message:String(C?.message??"");if(lr(C)&&Nd.has(C.code)||C.name==="AbortError"||i?.aborted||v.includes("User rejected")||v.includes("User denied")||C.code===4001||m>=u.length-1)throw C;const T=Number(u[m+1])/10;console.warn(`[SwapThenAction] Action attempt ${m+1} failed (buffer ${Number(h)/10}%), retrying with ${T}% buffer...`,C.message),d?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${T}% buffer)...`})}}throw new Ae("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:u.length,chainId:n})}Wi();export{fd as AccountDisplay,Us as AddFundsLink,Yr as CheckIcon,$n as ChevronIcon,go as CloseIcon,Co as DetailRow,nu as NATIVE_TOKEN_ADDRESS,Os as ProviderLogin,tr as SATSUMA_CITREA_CONFIG,ou as SPICENET_NATIVE_CHAIN_ID,su as SPICE_COMBINED_FEE_RECIPIENT,ru as SPICE_GAS_FEE_RECIPIENT,au as SPICE_PLATFORM_FEE_RECIPIENT,iu as SPICE_SOLVER_ADDRESS,ws as SearchInput,fc as SelectChainModal,pc as SpiceDeposit,Gd as SpiceFlowProvider,Zt as SpiceFlowProviderContext,ya as SpiceLock,ya as SpiceLockModal,Ed as SpiceSupply,Bc as SpiceWithdraw,Ae as SpiceflowError,qn as Spinner,wo as StatusBanner,Xa as UNIV3_BASE_CONFIG,si as applyBuffer,lu as applySlippage,Bo as areEquivalentOnChains,Jd as buildDarkPalette,Dd as buildIntent,$d as buildLightPalette,Aa as buildPayChainBatches,da as buildRoutedBatches,Sa as buildSupplyChainBatches,cu as buildUniV3SwapCalls,Ka as create1inchVenue,_a as createExactOutputRegistry,$a as createLiquidityRegistry,Ga as createSatsumaVenue,gn as duration,Gt as easing,Ba as estimateFeePreview,Ea as estimateRequiredGrossFunding,Fa as estimateSupplyMaxAmount,_s as executeDirectExternalAction,Na as executeNon7702Pay,Wa as executeNon7702Supply,Ua as executePay,Da as executeSupply,Ud as executeSwapThenAction,jn as findEquivalentOnChain,Vs as findTokenOnChain,gr as font,Vo as getAssetChainTokenCandidates,Va as getBestUniV3Quote,Ee as getChainConfig,du as getChainIdsByNetwork,fn as getChainName,uu as getEscrowContractAddress,Qa as getUniV3Quote,pu as isNativeToken,lr as isSpiceflowError,fu as isSpicenetChainId,Oa as isSupportedSupplyAsset,qa as isSwapIntent,hu as normalizeNativeTokenAddress,bs as radius,vt as relayerService,Rn as resolveAssetTokenAddressOnChain,Rr as resolveFundedToken,Ad as resolveInputSupplySwapQuote,ca as resolveRoute,_d as resolveTheme,Ro as resolveTokenRef,Wn as scaleTokenAmount,mu as spicenetAbi,gu as spicenetWithdrawalAbi,Sn as transition,Fd as useAssetInput,eu as useIsUserWhitelisted,Bd as useLockDuration,Td as useSmartWallet,To as useSpiceAssets,Bt as useSpiceBrand,bo as useSpiceExecution,xa as useSpicePendingDeposits,ja as useSupplyAssets,ti as useSupplyQuote,Pn as useWallet,ro as z};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spicenet-io/spiceflow-ui",
3
- "version": "4.0.6",
3
+ "version": "4.0.7",
4
4
  "description": "Spiceflow UI SDK",
5
5
  "type": "module",
6
6
  "packageManager": "bun@1.3.13",