@spicenet-io/spiceflow-ui 4.0.9 → 4.0.10

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(Lo,{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:B.encodeFunctionData({abi:B.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 fs(e){return e.filter(t=>t.domain!=="spicenet")}function ms(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 mr(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:h,exactOutputSwap:y,resolvedTokenIn:C,requestTimestampMs:k}=e,S=B.parseUnits(n,s.decimals),M=t?.actionAmountOverride??S,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??S,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",T=pr(g??null,d,c),v=N||d||T,A=(E,W)=>({token:E,from:"escrow",to:b,amount:W}),I=(E,W,U)=>T?[ur(E,W,c),...U]:U;if(S===0n)return[j];if(h&&y){const E=C??an(g.asset,c)??g.asset.address,W=t?.fundingAmountOverride??y.amountInMax,U=v?[A(E,W)]:[],z={to:E,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},P={chainId:c,calls:[z,...y.calls,...R],tokenTransfers:[...U,...j.tokenTransfers??[]]};if(!v)return[P];const D=await ps(P,x,{userAddress:b,destinationChainId:c,deliveryToken:E,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:ms(P),sourceAsset:g.asset},k);return I(E,W,D)}if(v){const E=C??an(g.asset,c)??s.address;if(T&&E.toLowerCase()===s.address.toLowerCase())return[j];const W=t?.fundingAmountOverride??S,U={...j,tokenTransfers:[A(E,W),...j.tokenTransfers??[]]},z=await ps(U,x,{userAddress:b,destinationChainId:c,deliveryToken:E,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:ms(U),sourceAsset:g.asset},k);return I(E,W,z)}return[j]}async function hr(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:h,quoteAmountOut:y,resolvedTokenIn:C,requestTimestampMs:k}=e,S=h?.amountOutMinimum??y;if(!n?.asset||!s)return[];const M=a??(x?r:s);if(!M)return[];const b=t?.fundingAmountOverride??t?.actionAmountOverride??B.parseUnits(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??b,R=t?.sourceFundingAmountOverride??b,j=t?.deliveryAmountOverride??w,N=t?.withdrawalAmountOverride??j,T=t?.actionAmountOverride??b,v={userAddress:M,chainId:l,destinationToken:d.address,feeToken:c==="user-transfer"&&g&&C?C:d.address,grossAmount:w,netAmount:T,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},A=u(T,v),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(!h||S===null)throw new Error("Swap quote not available yet")}if(g&&h&&S){const O=u(t?.actionAmountOverride??S,{...v,netAmount:t?.actionAmountOverride??S}),{feeCall:X,remainingCalls:pe}=fr(O,c,g,v.feeToken);return[{chainId:l,calls:[...X?[X]:[],...h.calls,...pe]}]}return[{chainId:l,calls:A}]}if(!p&&!x&&I&&n.asset.chainId!==l)throw new Error("Cross-chain wallet supplies require external wallet mode");const E=!p&&!x?n.asset?._source!=="wallet":n.asset?._source==="spice",W=x&&I,U=pr(n,x,l);if(!(E||W||U))return[{chainId:l,calls:A}];const z=U?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=(O,X)=>({token:O,from:W?"solver":"escrow",to:s,amount:X}),D=(O,X)=>W?[{token:O,from:"escrow",to:F.SPICE_SOLVER_ADDRESS,amount:X}]:[];if(g){if(!C)throw new Error("Swap input token could not be resolved");if(!h||S===null)throw new Error("Swap quote not available yet")}if(g&&h&&S&&C){const O=u(t?.actionAmountOverride??S,{...v,netAmount:t?.actionAmountOverride??S}),{feeCall:X,remainingCalls:pe}=fr(O,c,g,v.feeToken),q={chainId:l,calls:[...X?[X]:[],...h.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:ms(q),sourceAsset:n.asset},k);return z?[z,...J]:J}const Q=C??an(n.asset,l)??d.address,H={chainId:l,calls:A,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:ms(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),h=await u(x,c,t.balance,g?{userOverride:p,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:p,feeExecutionMode:f}:{userOverride:p}),y=fn(h,{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,S=zl(t.balance,C,k,t.balance);return S>0n?jo(S,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:h,isConnected:y,address:C,ready:k,authenticated:S,isDirect:M,resolvedSwap:b,isQuoting:w,executionTokenAddress:R,buildPayChainBatches:j,buildSupplyChainBatches:N,estimate:T,estimateRequiredGrossFunding:v}=e;if(!t?.asset)return null;if(n){if(s<=0||r&&!a||d)return null;const D=B.parseUnits(u,c.decimals),Q=p||an(t.asset,h)||t.asset.address||c.address,H={chainId:h,tokenAddress:Q,symbol:F.getTokenByAddress(Q,h)?.symbol??t.asset.symbol,decimals:F.getTokenByAddress(Q,h)?.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 v(le,ke=>j({fundingAmountOverride:ke}),Q,be),fe=await j({fundingAmountOverride:ie}),ce=await T(fe,Q,ie,{...be,feeExecutionMode:f});return fn(ce,H)}if(!y||!C||!k||!S)return null;const ee=x||g||C,O=r?a?.amountInMax??0n:D;if(O===0n)return null;const X=await v(O,J=>j({fundingAmountOverride:J}).then(le=>on(fs(le),ee)),Q,{useCustomTransfers:!0});let pe=on(fs(await j({fundingAmountOverride:X})),ee);const q=await T(pe,Q,X,{useCustomTransfers:!0,feeExecutionMode:f});return fn(q,H)}if(s<=0||!x)return null;const A=x||g;if(!(!n&&!l&&t.asset?._source==="wallet"&&t.asset.chainId!==h)&&!M&&!b&&!w||w)return null;const I=B.parseUnits(t.amount,t.asset.decimals),E=await N();if(E.length===0)return null;const W=l&&t.asset?._source==="wallet"&&t.asset.chainId===h,U={chainId:h,tokenAddress:R,symbol:F.getTokenByAddress(R,h)?.symbol??c.symbol,decimals:F.getTokenByAddress(R,h)?.decimals??c.decimals};if(W){const D=await m.relayerService.estimateBatchGas({user:A,outputToken:R,stepIndex:0,chainBatches:E}),Q=es(I,10n),H=Q+D.gasFee;return{...U,grossAmount:I+H,netAmount:I,totalFee:H,gasFee:D.gasFee,spicenetFee:Q,bridgeFee:0n,gasQuoteSource:D.gasQuoteSource}}const z=E.some(D=>D.tokenTransfers?.length),P=await T(E,R,I,z?{userOverride:A,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:A,feeExecutionMode:f}:{userOverride:A});return fn(P,U)}const Ll=10n;function Cr(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=an(n,e.resolvedChainId);if(!s||!m.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=B.formatUnits(a,n.decimals),d=B.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${l} ${n.symbol}; available ${d} ${n.symbol}.`)}function Js(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=fn(e,Js(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=B.decodeFunctionData({abi:B.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 $s(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:Cn(r.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Cn(r.gasFee,n.feeBreakdown.gasFee,100n)}function wr(e,t){return e?Cn(e.grossAmount,t.grossAmount,100n)&&Cn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Cn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Cn(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=B.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 h=await e.execution.estimate(r,e.executionTokenAddress,u,d),y=fn(h,Js(e));p=e.feeExecutionMode==="user-transfer"&&y?Vn(h,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:h})=>{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(h,e.resolvedChainId,C);const k=wr(x,y),S=$s(h,e,y);return k||S?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=B.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 v=await m.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),A=es(r,10n),I=A+v.gasFee;c=r+I,e.feeExecutionMode==="user-transfer"&&(x={grossAmount:c,netAmount:a,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:A,gasFee:v.gasFee,bridgeFee:0n}})}else for(let v=0;v<4;v+=1){const A=await e.execution.estimate(d,e.executionTokenAddress,0n,u),I=e.feeExecutionMode==="user-transfer"?Vn(A,e,a):void 0,E=fn(A,Js(e)),W=I?.grossAmount??(E?E.grossAmount>r?E.grossAmount:r:c);if(x=I,W===c){c=W;break}c=W;const U=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),z=ln(c,U?.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 h=l?c:ln(c,g?.decimals??e.destinationToken.decimals,s.decimals);Cr(e,c),d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:h,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 S=m.getChainConfig(y),M=B.createWalletClient({account:e.externalWalletAddress,chain:S?.viemChain,transport:B.custom(k)}),b=F.normalizeNativeTokenAddress(s.address),w=s.isNative||F.isNativeToken(b),R=m.getClientForChain(y),j=v=>Ys({extWc:M,sourceClient:R,recipient:C,tokenAddr:b,isNative:w,amount:v,viemChain:S?.viemChain});e.ui.setStatusMsg("Funding embedded wallet..."),await j(h);let N=h;if(e.feeExecutionMode==="user-transfer")for(let v=0;v<4;v+=1){const A=await e.execution.estimate(d,e.executionTokenAddress,0n,u),I=Vn(A,e,a);if(!I)break;const E=l?I.grossAmount:ln(I.grossAmount,g?.decimals??e.destinationToken.decimals,s.decimals);if(E>N&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await j(E-N),N=E),x=I,c=I.grossAmount,h=E,d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:h,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I}),$s(d,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let T=x;await e.execution.execute(d,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:v,chainBatches:A})=>{const I=Vn(v,e,a);if(!I)return null;const E=wr(T,I),W=$s(A,e,I);if(E||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.");T=I;const U=l?I.grossAmount:ln(I.grossAmount,g?.decimals??e.destinationToken.decimals,s.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:U,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=B.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=m.getChainConfig(e.resolvedChainId),c=B.createWalletClient({account:s,chain:u?.viemChain,transport:B.custom(d)}),f=m.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=B.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=F.getEscrowContractAddress(s),c=F.normalizeNativeTokenAddress(n.address),f=n.isNative||F.isNativeToken(c),p=t,x=v=>({chainId:s,calls:f?[{to:u,value:v,data:"0x"}]:[{to:c,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"transfer",args:[u,v]})}]}),g=(v,A,I)=>{const E=fs(v),W=P=>(P.tokenTransfers??[]).some(D=>D.from==="escrow"),U=E.filter(P=>!W(P)),z=E.filter(W);return[...U,...on(z,p,A,I)]},h=async(v,A,I)=>[x(v),...g(await e.execution.buildPayChainBatches({fundingAmountOverride:v}),A,I)],y=await e.execution.estimateRequiredGrossFunding(a,v=>h(v),l,d);let C=y,k=await h(y);const S=await e.execution.estimate(k,l,y,{...d,feeExecutionMode:e.feeExecutionMode}),M=fn(S,{chainId:e.resolvedChainId,tokenAddress:l,symbol:F.getTokenByAddress(l,e.resolvedChainId)?.symbol??n.symbol,decimals:F.getTokenByAddress(l,e.resolvedChainId)?.decimals??n.decimals})?.grossAmount??y;M!==y&&(C=M),k=await h(C,S,{payoutAlreadyGross:!0});const b=await e.externalWallet.getEthereumProvider();await Wn(b,s);const w=m.getChainConfig(s),R=B.createWalletClient({account:e.externalWalletAddress,chain:w?.viemChain,transport:B.custom(b)}),j=m.getClientForChain(s);await Ys({extWc:R,sourceClient:j,recipient:t,tokenAddr:c,isNative:f,amount:C,viemChain:w?.viemChain});const N=k.some(v=>v.tokenTransfers?.length),T={...d,skipUserFundingPreflight:!0};return await e.execution.execute(k,l,N?C:0n,v=>{v.txHash&&(e.ui.setPaymentResult(A=>({...A??{status:"processing"},txHash:v.txHash})),e.ui.setTxHash(v.txHash))},void 0,N?T:{userOverride:t,skipUserFundingPreflight:!0})}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=B.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=m.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=B.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,S=>{S.txHash&&(e.ui.setPaymentResult(M=>({...M,txHash:S.txHash})),e.ui.setTxHash(S.txHash))},void 0,s);e.ui.setPaymentResult(S=>({status:"success",txHash:S?.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,S)=>{const M=fs(C),b=j=>(j.tokenTransfers??[]).some(N=>N.from==="escrow"),w=M.filter(j=>!b(j)),R=M.filter(b);return[...w,...on(R,d,k,S)]},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=fn(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 h=p.some(C=>C.tokenTransfers?.length),y=await e.execution.execute(p,a,h?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=m.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:h,paymentAmount:y,needsSwap:C,exactOutputSwap:k,adjustable:S=!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"}):h?o.jsx(In,{value:h,title:h,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:S,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:h,adjustable:y,maxAmount:C,onAmountChange:k})=>{const S='"IBM Plex Mono", monospace',M=parseFloat(p||"0"),b=C?parseFloat(C):0,[w,R]=i.useState(p||""),j=i.useRef(null),[N,T]=i.useState(null),[v,A]=i.useState(null);i.useEffect(()=>{y||R(p||"")},[p,y]);const I=U=>{let z=U;z.startsWith(".")&&(z="0"+z);const P=m.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)},E=U=>{if(!b)return;if(U===100){R(C||b.toString()),j.current&&clearTimeout(j.current),k?.(C||b.toString());return}const z=10**n,P=Math.floor(b*U/100*z)/z,D=m.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:U=>I(U.target.value),placeholder:"0.0",fontFamily:S,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:S,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),o.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:S,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((U,z)=>{const P=Math.abs(W-U)<1,D=z===4,Q=U/100,H=N===U,ee=v===U;return o.jsx("button",{onClick:()=>E(U),onMouseEnter:()=>T(U),onMouseLeave:()=>{T(null),A(null)},onMouseDown:()=>A(U),onMouseUp:()=>A(null),title:`${U}%`,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"})]})},U)})})]})]}),x&&g&&!h&&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=m.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=>m.addressesEqual(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const s=Bn(n);return s?t.some(r=>m.addressesEqual(r,s.address)):!1})}function Tr(e,t,n){let{symbol:s,name:r,logoURI:a}=t;const l=m.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(m.SpiceFlowProviderContext),l=(a?.mode||"7702")!=="7702",d=a?.embeddedWalletAddress,{externalAddress:u,embeddedAddress:c,activeAddress:f}=m.useProviderWallets(),p=d||c,{assets:x,refetch:g}=Qn({address:p,supportedChains:s,enabled:r&&!l&&!!p,refetchInterval:3e4}),h=i.useMemo(()=>l?[]:x.filter(T=>Fr(T,n)),[x,n,l]),y=l?f??u:d,C=i.useMemo(()=>{const T=new Set,v=[],A=I=>{if(!I)return;const E=I.toLowerCase();T.has(E)||(T.add(E),v.push(B.getAddress(I)))};if(A(t.address),n)for(const I of n)A(I);return v},[l,t.address,n]),k=i.useMemo(()=>C.map(T=>T.toLowerCase()).sort().join(","),[C]),S=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 T=++w.current,v=B.getAddress(y),A=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=m.getChainConfig(t.chainId)?.supportedTokens?.find(H=>m.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 A){const H=m.getChainConfig(Q)?.supportedTokens?.find(ee=>m.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 E=new Map;for(const z of I){const P=E.get(z.chainId)||[];P.push(z),E.set(z.chainId,P)}const W=async(z,P)=>{try{const D=await sn.readContract(z,{address:P.address,abi:B.erc20Abi,functionName:"balanceOf",args:[v]}),{decimals:Q,symbol:H,name:ee,logoURI:O}=await nr(z,P.address,P.configToken);return Tr(P,{decimals:Q,symbol:H,name:ee,logoURI:O,balance:D},t)}catch{return null}},U=await Promise.all(Array.from(E.entries()).map(async([z,P])=>{let D;try{D=m.getClientForChain(z)}catch{return[]}const Q=[],H=[];for(const O of P){const X=Q.length;Q.push({address:O.address,abi:B.erc20Abi,functionName:"balanceOf",args:[v]}),O.configToken||Q.push({address:O.address,abi:B.erc20Abi,functionName:"decimals"},{address:O.address,abi:B.erc20Abi,functionName:"symbol"},{address:O.address,abi:B.erc20Abi,functionName:"name"}),H.push({start:X,item:O})}let ee=null;try{ee=await D.multicall({contracts:Q})}catch{ee=null}return ee?H.map(({start:O,item:X})=>{const pe=ee[O],q=pe?.status==="success"?pe.result:0n;let J,le,be,ie;if(X.configToken)J=X.configToken.decimals,le=X.configToken.symbol,be=X.configToken.name,ie=X.configToken.logo;else{const fe=ee[O+1],ce=ee[O+2],ke=ee[O+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(X,{decimals:J,symbol:le,name:be,logoURI:ie,balance:q},t)}):(await Promise.all(P.map(O=>W(D,O)))).filter(O=>O!==null)}));T===w.current&&b(U.flat())},[r,l,y,k,S,t.address,t.chainId,t.symbol,t.logoURI]);i.useEffect(()=>{R.current=j},[j]),i.useEffect(()=>{if(!r){b([]);return}R.current();const T=setInterval(()=>{R.current()},15e3);return()=>clearInterval(T)},[r,l,y,k,S,t.address,t.chainId]);const N=i.useCallback(()=>{j()},[j]);return{displayAssets:i.useMemo(()=>{const T=[],v=M.filter(I=>I.balance>0n);for(const I of v)T.push({...I,_source:"wallet"});for(const I of h)T.push({...I,_source:"spice"});const A=t.address.toLowerCase();return T.sort((I,E)=>jr(I,A,t.chainId)-jr(E,A,t.chainId)),T},[M,h,t.address,t.chainId]),filteredSpiceAssets:h,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 m.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 m.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 eo=.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??eo,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 m.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 h=BigInt(g.dstAmount);if(h<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const y=Dr(h,a),C=[];return g.tx.to&&!c&&C.push({to:n.tokenIn,value:0n,data:B.encodeFunctionData({abi:B.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:h,amountOutMinimum:y,calls:C}}catch(f){if(f instanceof m.SpiceflowError)throw f;const p=f instanceof Error?f.message:String(f);throw new m.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],to={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??eo,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:B.encodeFunctionData({abi:B.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:B.encodeFunctionData({abi: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??eo,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:B.encodeFunctionData({abi:Gl,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 Gl=[{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 m.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 m.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 m.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 m.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:to});async function Xl(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),[h,y]=i.useState(null),[C,k]=i.useState(null),[S,M]=i.useState(null),[b,w]=i.useState(null),[R,j]=i.useState(null),[N,T]=i.useState(null),v=i.useRef(null),A=i.useRef(null),I=i.useRef(0),E=i.useRef(new Map),W=i.useMemo(()=>Qr,[]),U=i.useMemo(()=>Hr({customVenues:[...d?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:d}]:[],zr(to),zr(Ur)]}),[d,r]),z=i.useMemo(()=>{if(!n?.asset)return null;const J=an(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?Gn(n.asset,r):[],[n?.asset,r]),D=i.useMemo(()=>P.map(J=>J.toLowerCase()).join(","),[P]);i.useEffect(()=>{let J=!1;if(A.current&&(clearTimeout(A.current),A.current=null),!n?.asset||P.length<=1){T(null);return}return A.current=setTimeout(async()=>{const le=t==="input"?n.amount:l||"0";let be=0n;try{be=t==="input"?B.parseUnits(le,n.asset.decimals):0n}catch{be=0n}try{const ie=await ko(n.asset,r,{requiredAmount:be});J||T(ie)}catch{J||T(null)}},400),()=>{J=!0,A.current&&(clearTimeout(A.current),A.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:m.addressesEqual(Q,s.address),[n,s.address,s.chainId,Q]),O=Q?m.addressesEqual(Q,s.address):!1,X=t==="output"&&parseFloat(l||"0")===0,pe=!!n?.asset&&!ee&&!O&&!X,q=pe?R??Q:Q;return i.useEffect(()=>{v.current&&clearTimeout(v.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"?B.parseUnits(n.amount,be):B.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 v.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=E.current.get(K);if(ne&&ne.expiresAt>Date.now()&&ne.resolvedSwap){Y=ne.resolvedSwap,_=ge;break}const me=await te.resolve({type:"swap",tokenIn:ge,tokenOut:s.address,amountIn:ie},r,a);if(ce())return;if(me){E.current.set(K,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:me}),Y=me,_=ge;break}}if(!Y||!_)throw new Error("No liquidity for this pair");j(_),w(Y.amountOut),k(Y),M(null);const re=parseFloat(B.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=E.current.get(re);if(ge&&ge.expiresAt>Date.now()&&ge.exactOutputSwap){te=ge.exactOutputSwap,Y=_;break}try{const K=await U.getQuote({tokenIn:_,tokenOut:s.address,amountOut:ie},r,a);if(ce())return;E.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(B.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),()=>{v.current&&clearTimeout(v.current)}},[t,pe,n?.amount,n?.asset?.address,n?.asset?.decimals,l,H,r,s.address,s.decimals,a,W,U]),{isQuoting:u,quoteError:f,estimatedOutput:x,estimatedInput:h,resolvedSwap:C,exactOutputSwap:S,quoteAmountOut:b,resolvedTokenIn:q,isDirect:O,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:h,paymentAmount:y,amountInputMode:C="fixed",minPaymentAmount:k,maxPaymentAmount:S,onAmountChange:M,styles:b,dark:w,title:R,subtitle:j,onAddFunds:N,onSuccess:T,onError:v})=>{const A=x==="output",{theme:I,dark:E,primaryColor:W,dk:U,palette:z,fontFamily:P,monoFont:D,inputDark:Q,cardBg:H,cardBorder:ee,textPrimary:O,textSecondary:X,subtitleText:pe}=m.useSpiceBrand(b,w),q=i.useMemo(()=>Q?{...I,colors:{...I.colors,secondary:U.cardBg,surfaceHover:U.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:I,[Q,I,U.cardBg,U.hoverBg]),J=s.chainId,le=i.useContext(m.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 he=le?.allowedTokens;if(!he||he.length===0)return;const $e=new Set(he.map(xn=>xn.toLowerCase())),dn=[],gn=new Set;for(const xn of ke){const hs=m.getChainConfig(xn);for(const gs of hs?.supportedTokens??[]){if(!$e.has(gs.symbol.toLowerCase()))continue;const no=gs.address.toLowerCase();gn.has(no)||(gn.add(no),dn.push(gs.address))}}return dn},[a,le?.allowedTokens,ke,fe]),Y=m.useWallet(),{address:_,isConnected:re,isReady:ge,isAuthenticated:K,provider:ne}=Y,{execute:me,estimate:oe}=Mn(),{externalWallet:Be,embeddedAddress:it,activeWallet:St,activeAddress:It}=m.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||A||ie?At:Te;i.useEffect(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:be,walletAddressUsed:We,count:Ze.length,assets:Ze.map(he=>({symbol:he.symbol,address:he.address,chainId:he.chainId,balanceFormatted:he.balanceFormatted,source:he?._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"),[Ge,tn]=i.useState(""),[Zt,Ve]=i.useState(null),[Lt,Et]=i.useState(!1),[Ue,ye]=i.useState(null),[Oe,Ke]=i.useState(null),[Gt,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),Xt=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:mt,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=A?parseFloat(Me||"0"):parseFloat(L?.amount||"")||0,Pt=nt>0&&nt<mn,$=L?.asset?._source==="wallet",se=!!L?.asset&&$&&L.asset.chainId!==J,Ce=i.useMemo(()=>L?.asset?Te.find(he=>m.addressesEqual(he.address,L.asset.address))?.balanceFormatted??0:0,[L,Te]),Ne=$?L?.asset.balanceFormatted??0:Ce,Ye=i.useMemo(()=>{if(!L?.asset)return!1;if(A)return Oe?ln(Oe.grossAmount,Oe.decimals,L.asset.decimals)>L.asset.balance:Ae||bt?nt>L.asset.balanceFormatted:Se?parseFloat(B.formatUnits(Se.amountInMax,L.asset.decimals))>L.asset.balanceFormatted:!1;if(Oe){const he=ln(Oe.grossAmount,Oe.decimals,L.asset.decimals);return $?he>L.asset.balance:parseFloat(B.formatUnits(he,L.asset.decimals))>Ne}return nt>Ne},[L,A,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(he=>{Re($e=>({asset:he,amount:$e?.asset?.address===he.address&&$e?.asset?.chainId===he.chainId&&$e.amount||""})),zt(null),qe(null),yt(!1)},[]),dt=i.useCallback(he=>{Re($e=>$e&&{...$e,amount:he}),zt(null),qe(null),yt(!1)},[]),at=i.useCallback(he=>{let $e=he;S&&parseFloat($e)>parseFloat(S)&&($e=S),Qe($e),M?.($e),zt(null),qe(null),yt(!1)},[S,M]);i.useCallback(he=>{if(jt.current||!_)return;const $e=nn.current;!$e?.asset||!$e.amount||$e.asset?._source==="wallet"||B.parseUnits(A?Me:$e.amount,$e.asset.decimals)===0n||(jt.current=!0,_e())},[_,J,_e,A,Me]);const Ee=i.useCallback(he=>{Dt({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[he.step]||"executing"),tn(he.message),he.txHash&&Ve(he.txHash)},[]),xt=i.useMemo(()=>({currentPaymentAmount:Me,destinationToken:s,embeddedWalletAddress:We,providerEmbeddedAddress:it,externalWalletAddress:lt,address:_,isNon7702:ie,isPayMode:A,resolvedChainId:J,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:L,needsSwap:tt,resolvedSwap:mt,exactOutputSwap:Se,quoteAmountOut:Ct,resolvedTokenIn:ot}),[Me,s,We,it,lt,_,ie,A,J,l,d,u,L,tt,mt,Se,Ct,ot]),De=i.useCallback(he=>mr({...xt,requestTimestampMs:Xt.current??Date.now()},he),[xt]),Z=i.useCallback(he=>hr({...xt,requestTimestampMs:Xt.current??Date.now()},he),[xt]),xe=i.useCallback((he,$e,dn,gn)=>gr(he,$e,dn,oe,gn),[oe]),ut=i.useMemo(()=>L?.asset?tt&&ot?ot:L.asset.chainId===J?L.asset.address:ot??an(L.asset,J)??s.address:s.address,[L,s.address,tt,J,ot]),ht=i.useCallback(()=>(Xt.current=Date.now(),kr(ct.current)),[]),Le=i.useMemo(()=>L?.asset?m.addressesEqual(L.asset.address,s.address)&&L.asset.chainId===s.chainId:!1,[L,s.address,s.chainId]),kt=Le&&(ie||A),Xe=kt&&nt>0&&!!L?.asset,Vt=ce&&!kt,V=i.useMemo(()=>{if(!Xe)return null;let he;try{he=B.parseUnits(Me||"0",s.decimals)}catch{return null}return{symbol:s.symbol,decimals:s.decimals,grossAmount:he,netAmount:he,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[Xe,Me,s.symbol,s.decimals]),G=Nt,de=i.useMemo(()=>!(!L?.asset||nt<=0),[L,nt,Xe]),ae=i.useMemo(()=>!e||ze||ve!=="idle"||!de||Xe||!L?.asset?null:[A?"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??"",mt?.amountOut?.toString()??"",Ct?.toString()??"",We??"",it??"",_??""].join("|"),[e,ze,ve,de,Xe,L,A,x,Me,s,J,ot,tt,bt,ie,Le,ft,Se,mt,Ct,We,it,_]),Pe=i.useCallback(()=>yr({selectedAsset:L,isPayMode:A,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:mt,isQuoting:ft,executionTokenAddress:ut,buildPayChainBatches:De,buildSupplyChainBatches:Z,estimate:oe,estimateRequiredGrossFunding:xe}),[L,A,nt,tt,Se,ie,Le,Me,s,d,ot,We,it,xe,De,oe,J,re,_,ge,K,bt,mt,ft,Z,ut]);i.useEffect(()=>{gt.current=Pe},[Pe]);const je=i.useCallback(he=>xr({asset:he,isPayMode:A,isNon7702:ie,needsSwap:tt,isQuoting:ft,embeddedWalletAddress:We,buildSupplyChainBatches:Z,estimate:oe,executionTokenAddress:ut,feeExecutionMode:d}),[A,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(Xe){Ke(V),we(!1),yt(!0),qe(null);return}if(ft){Ft.current+=1,we(!1),yt(!1);return}if(!ae)return;let he=!1;const $e=async()=>{const gn=++Ft.current;qe(null),we(!0);try{const xn=await gt.current?.();if(he||Ft.current!==gn)return;xn?(Ke(xn),yt(!0)):(Ke(null),yt(!1)),qe(null)}catch(xn){if(he||Ft.current!==gn)return;const hs=m.sanitizeError(xn,"Unable to calculate fees for this action.");Ke(null),yt(!1),qe(hs)}finally{!he&&Ft.current===gn&&we(!1)}},dn=window.setTimeout(()=>{$e()},250);return()=>{he=!0,clearTimeout(dn),we(!1)}},[e,ze,ve,de,Xe,V,ft,ae]);const He=i.useCallback(()=>(Xt.current=Date.now(),Ir(ct.current)),[]);i.useEffect(()=>{!A&&ve==="success"&&Zt&&(_e(),T?.(Zt))},[A,ve,Zt,_e,T]),i.useEffect(()=>{if(!A||Ue?.status!=="success"||jt.current||!_)return;jt.current=!0;const he=nn.current;!he?.asset||he.asset?._source==="wallet"||_e()},[A,Ue?.status,_,_e]);const st=i.useRef(T),vt=i.useRef(v);i.useEffect(()=>{st.current=T},[T]),i.useEffect(()=>{vt.current=v},[v]),i.useEffect(()=>{e&&(_e(),wt())},[e,_e,wt]),i.useEffect(()=>{A&&(Ue?.status==="success"&&st.current?.(Ue.txHash||""),Ue?.status==="failed"&&vt.current?.(new Error("Payment execution failed")))},[A,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:A,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:T,onError:v,execution:{estimate:oe,execute:me,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=A&&C==="fixed"&&Jt!==void 0&&Jt!==""&&nt===0,$t=A?(Tt||!!L?.asset)&&nt>=0&&!Pt&&!Ye&&!ze&&(Tt||Xe||Mt)&&!pt&&(Tt||!tt||!!Se)&&!Vt:!!L?.asset&&nt>0&&!Pt&&!Ye&&!ze&&(kt||Mt)&&!pt&&(se||bt||!!mt&&!ft)&&!Vt;i.useEffect(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:$t,isPayMode:A,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:Xe,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,A,L,nt,Tt,Pt,Ye,ze,kt,Xe,Mt,pt,tt,bt,Le,Se,ft,ce,Vt,fe,s]);const kn=bt?h||`Your ${s.symbol} will be used directly.`:g||"Your assets will be swapped and used in a single atomic transaction.",jn=(J?m.getChainConfig(J):void 0)?.viemChain?.blockExplorers?.default?.url??"",vn=Yr.indexOf(ve),Fe=ze?(qr[ve]||"EXECUTING...").toUpperCase():ve==="success"?"DONE":Pt?`MINIMUM ${mn}`:Ye?"INSUFFICIENT BALANCE":p.toUpperCase(),Je=i.useMemo(()=>{if(ze)return"PAYING...";if(Pt)return`MINIMUM ${mn}`;if(Ye&&L?.asset)return`INSUFFICIENT ${L.asset.symbol}`;if(p)return p.toUpperCase();const he=nt>0?` ${Me} ${s.symbol}`:"";return tt?`SWAP & PAY${he}`:`PAY${he}`},[ze,Pt,Ye,L,p,nt,Me,s.symbol,tt]),Ot=ve==="success"?()=>{Dt("idle"),Re(null),Ve(null),_e()}:ht,cn=ve==="success"?!1:!$t;if(!e)return null;const Yn=A?R||`Pay ${s.symbol}`:p,Pn=A?j:o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[o.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:o.jsx(Ds,{color:pe})}),o.jsx("p",{style:{fontSize:"12px",color:pe,margin:0,lineHeight:"1.4",fontFamily:P},children:kn})]});if(A){const he=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:E,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(Ws,{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(B.formatUnits(Se.amountIn,L.asset.decimals)).toFixed(6)}`:void 0:Me??void 0:void 0,dark:E,theme:q,styles:b})}),o.jsx(Ar,{variant:"pay",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:W,fontFamily:P,textPrimary:O,textSecondary:X,cardBg:H,cardBorder:ee,dk:U,dark:E,isQuoting:ft,quoteError:Qt,estimatedOutput:Wt,paymentAmount:Me,needsSwap:tt,exactOutputSwap:Se,adjustable:C==="adjustable",maxAmount:S,onAmountChange:at}),de&&o.jsx(as,{fontFamily:P,textPrimary:O,textSecondary:X,cardBg:H,cardBorder:ee,resolvedDark:E,darkCardBorder:U.cardBorder,primaryColor:W,feePreview:Oe,isLoading:Gt,errorText:pt,directExecutionFeeNote:Xe}),G&&o.jsx(Nn,{variant:"error",palette:z,fontFamily:P,style:{marginBottom:"12px"},children:G}),o.jsx(m.Button,{variant:"outline",fullWidth:!0,onClick:He,disabled:!$t,loading:ze,dark:E,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:E?U.shell:"white",borderRadius:E?"12px":"6px",padding:"16px 0"},children:o.jsx(Ls,{type:"payment",isOpen:Ue.status!=="processing",isProcessing:ze||Ue.status==="processing",closeOnComplete:!1,chainName:m.getChainName(J),explorerUrl:m.getExplorerUrl(J,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Et(!1),ye(null),He()},onNewTx:Ut,onClose:()=>{Et(!1),ye(null)},onComplete:Ut,results:he,styles:b,dark:E})})]})})}return o.jsx(un,{isOpen:e,onClose:t,title:Yn,subtitle:Pn,dark:E,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?m.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:O,textSecondary:X,cardBg:H,cardBorder:ee,dark:E,isQuoting:ft,quoteError:Qt,estimatedOutput:Wt}),de&&o.jsx(as,{fontFamily:P,textPrimary:O,textSecondary:X,cardBg:H,cardBorder:ee,resolvedDark:E,darkCardBorder:U.cardBorder,primaryColor:W,feePreview:Oe,isLoading:Gt,errorText:pt,directExecutionFeeNote:Xe}),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(m.Spinner,{size:14,color:W}),o.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:ve==="success"?O:ve==="error"?z.errorText:O,fontFamily:P,flex:1},children:ve==="success"?"Deposit confirmed":ve==="error"?Ge||"Transaction failed":qr[ve]||Ge}),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(ht,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:`${X}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(m.Button,{variant:"outline",fullWidth:!0,disabled:cn,onClick:Ot,theme:I,dark:E,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}=m.useWallet(),s=i.useContext(m.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 m.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 m.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 m.SpiceflowError("INVALID_PARAMS","buildIntent: action.calls must not be empty.",{action:t});if(s<=0n)throw new m.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,S])=>`${k} (chain ${S})`).join(", ");throw new m.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:h,resolvedSwaps:y}=await er({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:h}}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],h=Kr(r,g),y=a(h),C=[{chainId:n,calls:[...s,...y]}];try{return await e(C,l,d,u,c,f)}catch(k){const S=typeof k?.message=="string"?k.message:String(k?.message??"");if(m.isSpiceflowError(k)&&ac.has(k.code)||k.name==="AbortError"||c?.aborted||S.includes("User rejected")||S.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 m.SpiceflowError("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:p.length,chainId:n})}ra(),exports.SpiceFlowProvider=m.SpiceFlowProvider,exports.SpiceFlowProviderContext=m.SpiceFlowProviderContext,exports.SpiceflowError=m.SpiceflowError,exports.Spinner=m.Spinner,exports.buildDarkPalette=m.buildDarkPalette,exports.buildLightPalette=m.buildLightPalette,exports.getChainConfig=m.getChainConfig,exports.getChainName=m.getChainName,exports.isSpiceflowError=m.isSpiceflowError,exports.relayerService=m.relayerService,exports.resolveTheme=m.resolveTheme,exports.useIsUserWhitelisted=m.useIsUserWhitelisted,exports.useSpiceBrand=m.useSpiceBrand,exports.useWallet=m.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=Ws,exports.CheckIcon=Wo,exports.ChevronIcon=bn,exports.CloseIcon=Tn,exports.DetailRow=Dn,exports.ProviderLogin=zs,exports.SATSUMA_CITREA_CONFIG=to,exports.SearchInput=bs,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=mr,exports.buildRoutedBatches=er,exports.buildSupplyChainBatches=hr,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=Vs,exports.font=ro,exports.getAssetChainTokenCandidates=Gn,exports.getBestUniV3Quote=Mr,exports.getUniV3Quote=Rr,exports.isSupportedSupplyAsset=Fr,exports.isSwapIntent=Nr,exports.radius=Cs,exports.resolveAssetTokenAddressOnChain=an,exports.resolveFundedToken=ko,exports.resolveInputSupplySwapQuote=Xl,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(Lo,{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:B.encodeFunctionData({abi:B.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 fs(e){return e.filter(t=>t.domain!=="spicenet")}function ms(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 mr(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:h,exactOutputSwap:y,resolvedTokenIn:C,requestTimestampMs:k}=e,S=B.parseUnits(n,s.decimals),M=t?.actionAmountOverride??S,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??S,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",T=pr(g??null,d,c),v=N||d||T,A=(E,W)=>({token:E,from:"escrow",to:b,amount:W}),I=(E,W,U)=>T?[ur(E,W,c),...U]:U;if(S===0n)return[j];if(h&&y){const E=C??an(g.asset,c)??g.asset.address,W=t?.fundingAmountOverride??y.amountInMax,U=v?[A(E,W)]:[],z={to:E,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},P={chainId:c,calls:[z,...y.calls,...R],tokenTransfers:[...U,...j.tokenTransfers??[]]};if(!v)return[P];const D=await ps(P,x,{userAddress:b,destinationChainId:c,deliveryToken:E,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:ms(P),sourceAsset:g.asset},k);return I(E,W,D)}if(v){const E=C??an(g.asset,c)??s.address;if(T&&E.toLowerCase()===s.address.toLowerCase())return[j];const W=t?.fundingAmountOverride??S,U={...j,tokenTransfers:[A(E,W),...j.tokenTransfers??[]]},z=await ps(U,x,{userAddress:b,destinationChainId:c,deliveryToken:E,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:ms(U),sourceAsset:g.asset},k);return I(E,W,z)}return[j]}async function hr(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:h,quoteAmountOut:y,resolvedTokenIn:C,requestTimestampMs:k}=e,S=h?.amountOutMinimum??y;if(!n?.asset||!s)return[];const M=a??(x?r:s);if(!M)return[];const b=t?.fundingAmountOverride??t?.actionAmountOverride??B.parseUnits(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??b,R=t?.sourceFundingAmountOverride??b,j=t?.deliveryAmountOverride??w,N=t?.withdrawalAmountOverride??j,T=t?.actionAmountOverride??b,v={userAddress:M,chainId:l,destinationToken:d.address,feeToken:c==="user-transfer"&&g&&C?C:d.address,grossAmount:w,netAmount:T,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},A=u(T,v),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(!h||S===null)throw new Error("Swap quote not available yet")}if(g&&h&&S){const O=u(t?.actionAmountOverride??S,{...v,netAmount:t?.actionAmountOverride??S}),{feeCall:X,remainingCalls:pe}=fr(O,c,g,v.feeToken);return[{chainId:l,calls:[...X?[X]:[],...h.calls,...pe]}]}return[{chainId:l,calls:A}]}if(!p&&!x&&I&&n.asset.chainId!==l)throw new Error("Cross-chain wallet supplies require external wallet mode");const E=!p&&!x?n.asset?._source!=="wallet":n.asset?._source==="spice",W=x&&I,U=pr(n,x,l);if(!(E||W||U))return[{chainId:l,calls:A}];const z=U?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=(O,X)=>({token:O,from:W?"solver":"escrow",to:s,amount:X}),D=(O,X)=>W?[{token:O,from:"escrow",to:F.SPICE_SOLVER_ADDRESS,amount:X}]:[];if(g){if(!C)throw new Error("Swap input token could not be resolved");if(!h||S===null)throw new Error("Swap quote not available yet")}if(g&&h&&S&&C){const O=u(t?.actionAmountOverride??S,{...v,netAmount:t?.actionAmountOverride??S}),{feeCall:X,remainingCalls:pe}=fr(O,c,g,v.feeToken),q={chainId:l,calls:[...X?[X]:[],...h.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:ms(q),sourceAsset:n.asset},k);return z?[z,...J]:J}const Q=C??an(n.asset,l)??d.address,H={chainId:l,calls:A,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:ms(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),h=await u(x,c,t.balance,g?{userOverride:p,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:p,feeExecutionMode:f}:{userOverride:p}),y=fn(h,{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,S=zl(t.balance,C,k,t.balance);return S>0n?jo(S,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:h,isConnected:y,address:C,ready:k,authenticated:S,isDirect:M,resolvedSwap:b,isQuoting:w,executionTokenAddress:R,buildPayChainBatches:j,buildSupplyChainBatches:N,estimate:T,estimateRequiredGrossFunding:v}=e;if(!t?.asset)return null;if(n){if(s<=0||r&&!a||d)return null;const D=B.parseUnits(u,c.decimals),Q=p||an(t.asset,h)||t.asset.address||c.address,H={chainId:h,tokenAddress:Q,symbol:F.getTokenByAddress(Q,h)?.symbol??t.asset.symbol,decimals:F.getTokenByAddress(Q,h)?.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 v(le,ke=>j({fundingAmountOverride:ke}),Q,be),fe=await j({fundingAmountOverride:ie}),ce=await T(fe,Q,ie,{...be,feeExecutionMode:f});return fn(ce,H)}if(!y||!C||!k||!S)return null;const ee=x||g||C,O=r?a?.amountInMax??0n:D;if(O===0n)return null;const X=await v(O,J=>j({fundingAmountOverride:J}).then(le=>on(fs(le),ee)),Q,{useCustomTransfers:!0});let pe=on(fs(await j({fundingAmountOverride:X})),ee);const q=await T(pe,Q,X,{useCustomTransfers:!0,feeExecutionMode:f});return fn(q,H)}if(s<=0||!x)return null;const A=x||g;if(!(!n&&!l&&t.asset?._source==="wallet"&&t.asset.chainId!==h)&&!M&&!b&&!w||w)return null;const I=B.parseUnits(t.amount,t.asset.decimals),E=await N();if(E.length===0)return null;const W=l&&t.asset?._source==="wallet"&&t.asset.chainId===h,U={chainId:h,tokenAddress:R,symbol:F.getTokenByAddress(R,h)?.symbol??c.symbol,decimals:F.getTokenByAddress(R,h)?.decimals??c.decimals};if(W){const D=await m.relayerService.estimateBatchGas({user:A,outputToken:R,stepIndex:0,chainBatches:E}),Q=es(I,10n),H=Q+D.gasFee;return{...U,grossAmount:I+H,netAmount:I,totalFee:H,gasFee:D.gasFee,spicenetFee:Q,bridgeFee:0n,gasQuoteSource:D.gasQuoteSource}}const z=E.some(D=>D.tokenTransfers?.length),P=await T(E,R,I,z?{userOverride:A,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:A,feeExecutionMode:f}:{userOverride:A});return fn(P,U)}const Ll=10n;function Cr(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=an(n,e.resolvedChainId);if(!s||!m.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=B.formatUnits(a,n.decimals),d=B.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${l} ${n.symbol}; available ${d} ${n.symbol}.`)}function Js(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=fn(e,Js(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=B.decodeFunctionData({abi:B.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 $s(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:Cn(r.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Cn(r.gasFee,n.feeBreakdown.gasFee,100n)}function wr(e,t){return e?Cn(e.grossAmount,t.grossAmount,100n)&&Cn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Cn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Cn(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=B.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 h=await e.execution.estimate(r,e.executionTokenAddress,u,d),y=fn(h,Js(e));p=e.feeExecutionMode==="user-transfer"&&y?Vn(h,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:h})=>{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(h,e.resolvedChainId,C);const k=wr(x,y),S=$s(h,e,y);return k||S?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=B.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 v=await m.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),A=es(r,10n),I=A+v.gasFee;c=r+I,e.feeExecutionMode==="user-transfer"&&(x={grossAmount:c,netAmount:a,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:A,gasFee:v.gasFee,bridgeFee:0n}})}else for(let v=0;v<4;v+=1){const A=await e.execution.estimate(d,e.executionTokenAddress,0n,u),I=e.feeExecutionMode==="user-transfer"?Vn(A,e,a):void 0,E=fn(A,Js(e)),W=I?.grossAmount??(E?E.grossAmount>r?E.grossAmount:r:c);if(x=I,W===c){c=W;break}c=W;const U=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),z=ln(c,U?.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 h=l?c:ln(c,g?.decimals??e.destinationToken.decimals,s.decimals);Cr(e,c),d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:h,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 S=m.getChainConfig(y),M=B.createWalletClient({account:e.externalWalletAddress,chain:S?.viemChain,transport:B.custom(k)}),b=F.normalizeNativeTokenAddress(s.address),w=s.isNative||F.isNativeToken(b),R=m.getClientForChain(y),j=v=>Ys({extWc:M,sourceClient:R,recipient:C,tokenAddr:b,isNative:w,amount:v,viemChain:S?.viemChain});e.ui.setStatusMsg("Funding embedded wallet..."),await j(h);let N=h;if(e.feeExecutionMode==="user-transfer")for(let v=0;v<4;v+=1){const A=await e.execution.estimate(d,e.executionTokenAddress,0n,u),I=Vn(A,e,a);if(!I)break;const E=l?I.grossAmount:ln(I.grossAmount,g?.decimals??e.destinationToken.decimals,s.decimals);if(E>N&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await j(E-N),N=E),x=I,c=I.grossAmount,h=E,d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:h,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I}),$s(d,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let T=x;await e.execution.execute(d,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:v,chainBatches:A})=>{const I=Vn(v,e,a);if(!I)return null;const E=wr(T,I),W=$s(A,e,I);if(E||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.");T=I;const U=l?I.grossAmount:ln(I.grossAmount,g?.decimals??e.destinationToken.decimals,s.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:U,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=B.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=m.getChainConfig(e.resolvedChainId),c=B.createWalletClient({account:s,chain:u?.viemChain,transport:B.custom(d)}),f=m.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=B.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=F.getEscrowContractAddress(s),c=F.normalizeNativeTokenAddress(n.address),f=n.isNative||F.isNativeToken(c),p=t,x=v=>({chainId:s,calls:f?[{to:u,value:v,data:"0x"}]:[{to:c,value:0n,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"transfer",args:[u,v]})}]}),g=(v,A,I)=>{const E=fs(v),W=P=>(P.tokenTransfers??[]).some(D=>D.from==="escrow"),U=E.filter(P=>!W(P)),z=E.filter(W);return[...U,...on(z,p,A,I)]},h=async(v,A,I)=>[x(v),...g(await e.execution.buildPayChainBatches({fundingAmountOverride:v}),A,I)],y=await e.execution.estimateRequiredGrossFunding(a,v=>h(v),l,d);let C=y,k=await h(y);const S=await e.execution.estimate(k,l,y,{...d,feeExecutionMode:e.feeExecutionMode}),M=fn(S,{chainId:e.resolvedChainId,tokenAddress:l,symbol:F.getTokenByAddress(l,e.resolvedChainId)?.symbol??n.symbol,decimals:F.getTokenByAddress(l,e.resolvedChainId)?.decimals??n.decimals})?.grossAmount??y;M!==y&&(C=M),k=await h(C,S,{payoutAlreadyGross:!0});const b=await e.externalWallet.getEthereumProvider();await Wn(b,s);const w=m.getChainConfig(s),R=B.createWalletClient({account:e.externalWalletAddress,chain:w?.viemChain,transport:B.custom(b)}),j=m.getClientForChain(s);await Ys({extWc:R,sourceClient:j,recipient:t,tokenAddr:c,isNative:f,amount:C,viemChain:w?.viemChain});const N=k.some(v=>v.tokenTransfers?.length),T={...d,skipUserFundingPreflight:!0};return await e.execution.execute(k,l,N?C:0n,v=>{v.txHash&&(e.ui.setPaymentResult(A=>({...A??{status:"processing"},txHash:v.txHash})),e.ui.setTxHash(v.txHash))},void 0,N?T:{userOverride:t,skipUserFundingPreflight:!0})}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=B.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=m.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=B.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,B.zeroAddress,0n,S=>{S.txHash&&(e.ui.setPaymentResult(M=>({...M,txHash:S.txHash})),e.ui.setTxHash(S.txHash))},void 0,s);e.ui.setPaymentResult(S=>({status:"success",txHash:S?.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,S)=>{const M=fs(C),b=j=>(j.tokenTransfers??[]).some(N=>N.from==="escrow"),w=M.filter(j=>!b(j)),R=M.filter(b);return[...w,...on(R,d,k,S)]},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=fn(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 h=p.some(C=>C.tokenTransfers?.length),y=await e.execution.execute(p,a,h?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=m.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:h,paymentAmount:y,needsSwap:C,exactOutputSwap:k,adjustable:S=!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"}):h?o.jsx(In,{value:h,title:h,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:S,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:h,adjustable:y,maxAmount:C,onAmountChange:k})=>{const S='"IBM Plex Mono", monospace',M=parseFloat(p||"0"),b=C?parseFloat(C):0,[w,R]=i.useState(p||""),j=i.useRef(null),[N,T]=i.useState(null),[v,A]=i.useState(null);i.useEffect(()=>{y||R(p||"")},[p,y]);const I=U=>{let z=U;z.startsWith(".")&&(z="0"+z);const P=m.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)},E=U=>{if(!b)return;if(U===100){R(C||b.toString()),j.current&&clearTimeout(j.current),k?.(C||b.toString());return}const z=10**n,P=Math.floor(b*U/100*z)/z,D=m.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:U=>I(U.target.value),placeholder:"0.0",fontFamily:S,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:S,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),o.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:S,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((U,z)=>{const P=Math.abs(W-U)<1,D=z===4,Q=U/100,H=N===U,ee=v===U;return o.jsx("button",{onClick:()=>E(U),onMouseEnter:()=>T(U),onMouseLeave:()=>{T(null),A(null)},onMouseDown:()=>A(U),onMouseUp:()=>A(null),title:`${U}%`,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"})]})},U)})})]})]}),x&&g&&!h&&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=m.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=>m.addressesEqual(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const s=Bn(n);return s?t.some(r=>m.addressesEqual(r,s.address)):!1})}function Tr(e,t,n){let{symbol:s,name:r,logoURI:a}=t;const l=m.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(m.SpiceFlowProviderContext),l=(a?.mode||"7702")!=="7702",d=a?.embeddedWalletAddress,{externalAddress:u,embeddedAddress:c,activeAddress:f}=m.useProviderWallets(),p=d||c,{assets:x,refetch:g}=Qn({address:p,supportedChains:s,enabled:r&&!l&&!!p,refetchInterval:3e4}),h=i.useMemo(()=>l?[]:x.filter(T=>Fr(T,n)),[x,n,l]),y=l?f??u:d,C=i.useMemo(()=>{const T=new Set,v=[],A=I=>{if(!I)return;const E=I.toLowerCase();T.has(E)||(T.add(E),v.push(B.getAddress(I)))};if(A(t.address),n)for(const I of n)A(I);return v},[l,t.address,n]),k=i.useMemo(()=>C.map(T=>T.toLowerCase()).sort().join(","),[C]),S=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 T=++w.current,v=B.getAddress(y),A=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=m.getChainConfig(t.chainId)?.supportedTokens?.find(H=>m.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 A){const H=m.getChainConfig(Q)?.supportedTokens?.find(ee=>m.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 E=new Map;for(const z of I){const P=E.get(z.chainId)||[];P.push(z),E.set(z.chainId,P)}const W=async(z,P)=>{try{const D=await sn.readContract(z,{address:P.address,abi:B.erc20Abi,functionName:"balanceOf",args:[v]}),{decimals:Q,symbol:H,name:ee,logoURI:O}=await nr(z,P.address,P.configToken);return Tr(P,{decimals:Q,symbol:H,name:ee,logoURI:O,balance:D},t)}catch{return null}},U=await Promise.all(Array.from(E.entries()).map(async([z,P])=>{let D;try{D=m.getClientForChain(z)}catch{return[]}const Q=[],H=[];for(const O of P){const X=Q.length;Q.push({address:O.address,abi:B.erc20Abi,functionName:"balanceOf",args:[v]}),O.configToken||Q.push({address:O.address,abi:B.erc20Abi,functionName:"decimals"},{address:O.address,abi:B.erc20Abi,functionName:"symbol"},{address:O.address,abi:B.erc20Abi,functionName:"name"}),H.push({start:X,item:O})}let ee=null;try{ee=await D.multicall({contracts:Q})}catch{ee=null}return ee?H.map(({start:O,item:X})=>{const pe=ee[O],q=pe?.status==="success"?pe.result:0n;let J,le,be,ie;if(X.configToken)J=X.configToken.decimals,le=X.configToken.symbol,be=X.configToken.name,ie=X.configToken.logo;else{const fe=ee[O+1],ce=ee[O+2],ke=ee[O+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(X,{decimals:J,symbol:le,name:be,logoURI:ie,balance:q},t)}):(await Promise.all(P.map(O=>W(D,O)))).filter(O=>O!==null)}));T===w.current&&b(U.flat())},[r,l,y,k,S,t.address,t.chainId,t.symbol,t.logoURI]);i.useEffect(()=>{R.current=j},[j]),i.useEffect(()=>{if(!r){b([]);return}R.current();const T=setInterval(()=>{R.current()},15e3);return()=>clearInterval(T)},[r,l,y,k,S,t.address,t.chainId]);const N=i.useCallback(()=>{j()},[j]);return{displayAssets:i.useMemo(()=>{const T=[],v=M.filter(I=>I.balance>0n);for(const I of v)T.push({...I,_source:"wallet"});for(const I of h)T.push({...I,_source:"spice"});const A=t.address.toLowerCase();return T.sort((I,E)=>jr(I,A,t.chainId)-jr(E,A,t.chainId)),T},[M,h,t.address,t.chainId]),filteredSpiceAssets:h,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 m.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 m.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 eo=.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??eo,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 m.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 h=BigInt(g.dstAmount);if(h<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const y=Dr(h,a),C=[];return g.tx.to&&!c&&C.push({to:n.tokenIn,value:0n,data:B.encodeFunctionData({abi:B.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:h,amountOutMinimum:y,calls:C}}catch(f){if(f instanceof m.SpiceflowError)throw f;const p=f instanceof Error?f.message:String(f);throw new m.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],to={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??eo,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:B.encodeFunctionData({abi:B.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:B.encodeFunctionData({abi: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??eo,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:B.encodeFunctionData({abi:Gl,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 Gl=[{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 m.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 m.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 m.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 m.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:to});async function Xl(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),[h,y]=i.useState(null),[C,k]=i.useState(null),[S,M]=i.useState(null),[b,w]=i.useState(null),[R,j]=i.useState(null),[N,T]=i.useState(null),v=i.useRef(null),A=i.useRef(null),I=i.useRef(0),E=i.useRef(new Map),W=i.useMemo(()=>Qr,[]),U=i.useMemo(()=>Hr({customVenues:[...d?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:d}]:[],zr(to),zr(Ur)]}),[d,r]),z=i.useMemo(()=>{if(!n?.asset)return null;const J=an(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?Gn(n.asset,r):[],[n?.asset,r]),D=i.useMemo(()=>P.map(J=>J.toLowerCase()).join(","),[P]);i.useEffect(()=>{let J=!1;if(A.current&&(clearTimeout(A.current),A.current=null),!n?.asset||P.length<=1){T(null);return}return A.current=setTimeout(async()=>{const le=t==="input"?n.amount:l||"0";let be=0n;try{be=t==="input"?B.parseUnits(le,n.asset.decimals):0n}catch{be=0n}try{const ie=await ko(n.asset,r,{requiredAmount:be});J||T(ie)}catch{J||T(null)}},400),()=>{J=!0,A.current&&(clearTimeout(A.current),A.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:m.addressesEqual(Q,s.address),[n,s.address,s.chainId,Q]),O=Q?m.addressesEqual(Q,s.address):!1,X=t==="output"&&parseFloat(l||"0")===0,pe=!!n?.asset&&!ee&&!O&&!X,q=pe?R??Q:Q;return i.useEffect(()=>{v.current&&clearTimeout(v.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"?B.parseUnits(n.amount,be):B.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 v.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=E.current.get(K);if(ne&&ne.expiresAt>Date.now()&&ne.resolvedSwap){Y=ne.resolvedSwap,_=ge;break}const me=await te.resolve({type:"swap",tokenIn:ge,tokenOut:s.address,amountIn:ie},r,a);if(ce())return;if(me){E.current.set(K,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:me}),Y=me,_=ge;break}}if(!Y||!_)throw new Error("No liquidity for this pair");j(_),w(Y.amountOut),k(Y),M(null);const re=parseFloat(B.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=E.current.get(re);if(ge&&ge.expiresAt>Date.now()&&ge.exactOutputSwap){te=ge.exactOutputSwap,Y=_;break}try{const K=await U.getQuote({tokenIn:_,tokenOut:s.address,amountOut:ie},r,a);if(ce())return;E.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(B.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),()=>{v.current&&clearTimeout(v.current)}},[t,pe,n?.amount,n?.asset?.address,n?.asset?.decimals,l,H,r,s.address,s.decimals,a,W,U]),{isQuoting:u,quoteError:f,estimatedOutput:x,estimatedInput:h,resolvedSwap:C,exactOutputSwap:S,quoteAmountOut:b,resolvedTokenIn:q,isDirect:O,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:h,paymentAmount:y,amountInputMode:C="fixed",minPaymentAmount:k,maxPaymentAmount:S,onAmountChange:M,styles:b,dark:w,title:R,subtitle:j,onAddFunds:N,onSuccess:T,onError:v})=>{const A=x==="output",{theme:I,dark:E,primaryColor:W,dk:U,palette:z,fontFamily:P,monoFont:D,inputDark:Q,cardBg:H,cardBorder:ee,textPrimary:O,textSecondary:X,subtitleText:pe}=m.useSpiceBrand(b,w),q=i.useMemo(()=>Q?{...I,colors:{...I.colors,secondary:U.cardBg,surfaceHover:U.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:I,[Q,I,U.cardBg,U.hoverBg]),J=s.chainId,le=i.useContext(m.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 he=le?.allowedTokens;if(!he||he.length===0)return;const $e=new Set(he.map(xn=>xn.toLowerCase())),dn=[],gn=new Set;for(const xn of ke){const hs=m.getChainConfig(xn);for(const gs of hs?.supportedTokens??[]){if(!$e.has(gs.symbol.toLowerCase()))continue;const no=gs.address.toLowerCase();gn.has(no)||(gn.add(no),dn.push(gs.address))}}return dn},[a,le?.allowedTokens,ke,fe]),Y=m.useWallet(),{address:_,isConnected:re,isReady:ge,isAuthenticated:K,provider:ne}=Y,{execute:me,estimate:oe}=Mn(),{externalWallet:Be,embeddedAddress:it,activeWallet:St,activeAddress:It}=m.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||A||ie?At:Te;i.useEffect(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:be,walletAddressUsed:We,count:Ze.length,assets:Ze.map(he=>({symbol:he.symbol,address:he.address,chainId:he.chainId,balanceFormatted:he.balanceFormatted,source:he?._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"),[Ge,tn]=i.useState(""),[Zt,Ve]=i.useState(null),[Lt,Et]=i.useState(!1),[Ue,ye]=i.useState(null),[Oe,Ke]=i.useState(null),[Gt,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),Xt=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:mt,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=A?parseFloat(Me||"0"):parseFloat(L?.amount||"")||0,Pt=nt>0&&nt<mn,$=L?.asset?._source==="wallet",se=!!L?.asset&&$&&L.asset.chainId!==J,Ce=i.useMemo(()=>L?.asset?Te.find(he=>m.addressesEqual(he.address,L.asset.address))?.balanceFormatted??0:0,[L,Te]),Ne=$?L?.asset.balanceFormatted??0:Ce,Ye=i.useMemo(()=>{if(!L?.asset)return!1;if(A)return Oe?ln(Oe.grossAmount,Oe.decimals,L.asset.decimals)>L.asset.balance:Ae||bt?nt>L.asset.balanceFormatted:Se?parseFloat(B.formatUnits(Se.amountInMax,L.asset.decimals))>L.asset.balanceFormatted:!1;if(Oe){const he=ln(Oe.grossAmount,Oe.decimals,L.asset.decimals);return $?he>L.asset.balance:parseFloat(B.formatUnits(he,L.asset.decimals))>Ne}return nt>Ne},[L,A,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(he=>{Re($e=>({asset:he,amount:$e?.asset?.address===he.address&&$e?.asset?.chainId===he.chainId&&$e.amount||""})),zt(null),qe(null),yt(!1)},[]),dt=i.useCallback(he=>{Re($e=>$e&&{...$e,amount:he}),zt(null),qe(null),yt(!1)},[]),at=i.useCallback(he=>{let $e=he;S&&parseFloat($e)>parseFloat(S)&&($e=S),Qe($e),M?.($e),zt(null),qe(null),yt(!1)},[S,M]);i.useCallback(he=>{if(jt.current||!_)return;const $e=nn.current;!$e?.asset||!$e.amount||$e.asset?._source==="wallet"||B.parseUnits(A?Me:$e.amount,$e.asset.decimals)===0n||(jt.current=!0,_e())},[_,J,_e,A,Me]);const Ee=i.useCallback(he=>{Dt({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[he.step]||"executing"),tn(he.message),he.txHash&&Ve(he.txHash)},[]),xt=i.useMemo(()=>({currentPaymentAmount:Me,destinationToken:s,embeddedWalletAddress:We,providerEmbeddedAddress:it,externalWalletAddress:lt,address:_,isNon7702:ie,isPayMode:A,resolvedChainId:J,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:L,needsSwap:tt,resolvedSwap:mt,exactOutputSwap:Se,quoteAmountOut:Ct,resolvedTokenIn:ot}),[Me,s,We,it,lt,_,ie,A,J,l,d,u,L,tt,mt,Se,Ct,ot]),De=i.useCallback(he=>mr({...xt,requestTimestampMs:Xt.current??Date.now()},he),[xt]),Z=i.useCallback(he=>hr({...xt,requestTimestampMs:Xt.current??Date.now()},he),[xt]),xe=i.useCallback((he,$e,dn,gn)=>gr(he,$e,dn,oe,gn),[oe]),ut=i.useMemo(()=>L?.asset?tt&&ot?ot:L.asset.chainId===J?L.asset.address:ot??an(L.asset,J)??s.address:s.address,[L,s.address,tt,J,ot]),ht=i.useCallback(()=>(Xt.current=Date.now(),kr(ct.current)),[]),Le=i.useMemo(()=>L?.asset?m.addressesEqual(L.asset.address,s.address)&&L.asset.chainId===s.chainId:!1,[L,s.address,s.chainId]),kt=Le&&(ie||A),Xe=kt&&nt>0&&!!L?.asset,Vt=ce&&!kt,V=i.useMemo(()=>{if(!Xe)return null;let he;try{he=B.parseUnits(Me||"0",s.decimals)}catch{return null}return{symbol:s.symbol,decimals:s.decimals,grossAmount:he,netAmount:he,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[Xe,Me,s.symbol,s.decimals]),G=Nt,de=i.useMemo(()=>!(!L?.asset||nt<=0),[L,nt,Xe]),ae=i.useMemo(()=>!e||ze||ve!=="idle"||!de||Xe||!L?.asset?null:[A?"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??"",mt?.amountOut?.toString()??"",Ct?.toString()??"",We??"",it??"",_??""].join("|"),[e,ze,ve,de,Xe,L,A,x,Me,s,J,ot,tt,bt,ie,Le,ft,Se,mt,Ct,We,it,_]),Pe=i.useCallback(()=>yr({selectedAsset:L,isPayMode:A,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:mt,isQuoting:ft,executionTokenAddress:ut,buildPayChainBatches:De,buildSupplyChainBatches:Z,estimate:oe,estimateRequiredGrossFunding:xe}),[L,A,nt,tt,Se,ie,Le,Me,s,d,ot,We,it,xe,De,oe,J,re,_,ge,K,bt,mt,ft,Z,ut]);i.useEffect(()=>{gt.current=Pe},[Pe]);const je=i.useCallback(he=>xr({asset:he,isPayMode:A,isNon7702:ie,needsSwap:tt,isQuoting:ft,embeddedWalletAddress:We,buildSupplyChainBatches:Z,estimate:oe,executionTokenAddress:ut,feeExecutionMode:d}),[A,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(Xe){Ke(V),we(!1),yt(!0),qe(null);return}if(ft){Ft.current+=1,we(!1),yt(!1);return}if(!ae)return;let he=!1;const $e=async()=>{const gn=++Ft.current;qe(null),we(!0);try{const xn=await gt.current?.();if(he||Ft.current!==gn)return;xn?(Ke(xn),yt(!0)):(Ke(null),yt(!1)),qe(null)}catch(xn){if(he||Ft.current!==gn)return;const hs=m.sanitizeError(xn,"Unable to calculate fees for this action.");Ke(null),yt(!1),qe(hs)}finally{!he&&Ft.current===gn&&we(!1)}},dn=window.setTimeout(()=>{$e()},250);return()=>{he=!0,clearTimeout(dn),we(!1)}},[e,ze,ve,de,Xe,V,ft,ae]);const He=i.useCallback(()=>(Xt.current=Date.now(),Ir(ct.current)),[]);i.useEffect(()=>{!A&&ve==="success"&&Zt&&(_e(),T?.(Zt))},[A,ve,Zt,_e,T]),i.useEffect(()=>{if(!A||Ue?.status!=="success"||jt.current||!_)return;jt.current=!0;const he=nn.current;!he?.asset||he.asset?._source==="wallet"||_e()},[A,Ue?.status,_,_e]);const st=i.useRef(T),vt=i.useRef(v);i.useEffect(()=>{st.current=T},[T]),i.useEffect(()=>{vt.current=v},[v]),i.useEffect(()=>{e&&(_e(),wt())},[e,_e,wt]),i.useEffect(()=>{A&&(Ue?.status==="success"&&st.current?.(Ue.txHash||""),Ue?.status==="failed"&&vt.current?.(new Error("Payment execution failed")))},[A,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:A,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:T,onError:v,execution:{estimate:oe,execute:me,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=A&&C==="fixed"&&Jt!==void 0&&Jt!==""&&nt===0,$t=A?(Tt||!!L?.asset)&&nt>=0&&!Pt&&!Ye&&!ze&&(Tt||Xe||Mt)&&!pt&&(Tt||!tt||!!Se)&&!Vt:!!L?.asset&&nt>0&&!Pt&&!Ye&&!ze&&(kt||Mt)&&!pt&&(se||bt||!!mt&&!ft)&&!Vt;i.useEffect(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:$t,isPayMode:A,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:Xe,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,A,L,nt,Tt,Pt,Ye,ze,kt,Xe,Mt,pt,tt,bt,Le,Se,ft,ce,Vt,fe,s]);const kn=bt?h||`Your ${s.symbol} will be used directly.`:g||"Your assets will be swapped and used in a single atomic transaction.",jn=(J?m.getChainConfig(J):void 0)?.viemChain?.blockExplorers?.default?.url??"",vn=Yr.indexOf(ve),Fe=ze?(qr[ve]||"EXECUTING...").toUpperCase():ve==="success"?"DONE":Pt?`MINIMUM ${mn}`:Ye?"INSUFFICIENT BALANCE":p.toUpperCase(),Je=i.useMemo(()=>{if(ze)return"PAYING...";if(Pt)return`MINIMUM ${mn}`;if(Ye&&L?.asset)return`INSUFFICIENT ${L.asset.symbol}`;if(p)return p.toUpperCase();const he=nt>0?` ${Me} ${s.symbol}`:"";return tt?`SWAP & PAY${he}`:`PAY${he}`},[ze,Pt,Ye,L,p,nt,Me,s.symbol,tt]),Ot=ve==="success"?()=>{Dt("idle"),Re(null),Ve(null),_e()}:ht,cn=ve==="success"?!1:!$t;if(!e)return null;const Yn=A?R||`Pay ${s.symbol}`:p,Pn=A?j:o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[o.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:o.jsx(Ds,{color:pe})}),o.jsx("p",{style:{fontSize:"12px",color:pe,margin:0,lineHeight:"1.4",fontFamily:P},children:kn})]});if(A){const he=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:E,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(Ws,{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(B.formatUnits(Se.amountIn,L.asset.decimals)).toFixed(6)}`:void 0:Me??void 0:void 0,dark:E,theme:q,styles:b})}),o.jsx(Ar,{variant:"pay",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:W,fontFamily:P,textPrimary:O,textSecondary:X,cardBg:H,cardBorder:ee,dk:U,dark:E,isQuoting:ft,quoteError:Qt,estimatedOutput:Wt,paymentAmount:Me,needsSwap:tt,exactOutputSwap:Se,adjustable:C==="adjustable",maxAmount:S,onAmountChange:at}),de&&o.jsx(as,{fontFamily:P,textPrimary:O,textSecondary:X,cardBg:H,cardBorder:ee,resolvedDark:E,darkCardBorder:U.cardBorder,primaryColor:W,feePreview:Oe,isLoading:Gt,errorText:pt,directExecutionFeeNote:Xe}),G&&o.jsx(Nn,{variant:"error",palette:z,fontFamily:P,style:{marginBottom:"12px"},children:G}),o.jsx(m.Button,{variant:"outline",fullWidth:!0,onClick:He,disabled:!$t,loading:ze,dark:E,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:E?U.shell:"white",borderRadius:E?"12px":"6px",padding:"16px 0"},children:o.jsx(Ls,{type:"payment",isOpen:Ue.status!=="processing",isProcessing:ze||Ue.status==="processing",closeOnComplete:!1,chainName:m.getChainName(J),explorerUrl:m.getExplorerUrl(J,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Et(!1),ye(null),He()},onNewTx:Ut,onClose:()=>{Et(!1),ye(null)},onComplete:Ut,results:he,styles:b,dark:E})})]})})}return o.jsx(un,{isOpen:e,onClose:t,title:Yn,subtitle:Pn,dark:E,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?m.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:O,textSecondary:X,cardBg:H,cardBorder:ee,dark:E,isQuoting:ft,quoteError:Qt,estimatedOutput:Wt}),de&&o.jsx(as,{fontFamily:P,textPrimary:O,textSecondary:X,cardBg:H,cardBorder:ee,resolvedDark:E,darkCardBorder:U.cardBorder,primaryColor:W,feePreview:Oe,isLoading:Gt,errorText:pt,directExecutionFeeNote:Xe}),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(m.Spinner,{size:14,color:W}),o.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:ve==="success"?O:ve==="error"?z.errorText:O,fontFamily:P,flex:1},children:ve==="success"?"Deposit confirmed":ve==="error"?Ge||"Transaction failed":qr[ve]||Ge}),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(ht,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:`${X}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(m.Button,{variant:"outline",fullWidth:!0,disabled:cn,onClick:Ot,theme:I,dark:E,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}=m.useWallet(),s=i.useContext(m.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 m.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 m.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 m.SpiceflowError("INVALID_PARAMS","buildIntent: action.calls must not be empty.",{action:t});if(s<=0n)throw new m.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,S])=>`${k} (chain ${S})`).join(", ");throw new m.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:h,resolvedSwaps:y}=await er({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:h}}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],h=Kr(r,g),y=a(h),C=[{chainId:n,calls:[...s,...y]}];try{return await e(C,l,d,u,c,f)}catch(k){const S=typeof k?.message=="string"?k.message:String(k?.message??"");if(m.isSpiceflowError(k)&&ac.has(k.code)||k.name==="AbortError"||c?.aborted||S.includes("User rejected")||S.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 m.SpiceflowError("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:p.length,chainId:n})}ra(),exports.SpiceFlowProvider=m.SpiceFlowProvider,exports.SpiceFlowProviderContext=m.SpiceFlowProviderContext,exports.SpiceflowError=m.SpiceflowError,exports.Spinner=m.Spinner,exports.buildDarkPalette=m.buildDarkPalette,exports.buildLightPalette=m.buildLightPalette,exports.getChainConfig=m.getChainConfig,exports.getChainName=m.getChainName,exports.isSpiceflowError=m.isSpiceflowError,exports.relayerService=m.relayerService,exports.resolveTheme=m.resolveTheme,exports.useIsUserWhitelisted=m.useIsUserWhitelisted,exports.useSpiceBrand=m.useSpiceBrand,exports.useWallet=m.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=Ws,exports.CheckIcon=Wo,exports.ChevronIcon=bn,exports.CloseIcon=Tn,exports.DetailRow=Dn,exports.ProviderLogin=zs,exports.SATSUMA_CITREA_CONFIG=to,exports.SearchInput=bs,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=mr,exports.buildRoutedBatches=er,exports.buildSupplyChainBatches=hr,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=Vs,exports.font=ro,exports.getAssetChainTokenCandidates=Gn,exports.getBestUniV3Quote=Mr,exports.getUniV3Quote=Rr,exports.isSupportedSupplyAsset=Fr,exports.isSwapIntent=Nr,exports.radius=Cs,exports.resolveAssetTokenAddressOnChain=an,exports.resolveFundedToken=ko,exports.resolveInputSupplySwapQuote=Xl,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;