@spicenet-io/spiceflow-ui 4.0.1 → 4.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -105,4 +105,4 @@
|
|
|
105
105
|
from { opacity: 0; transform: translateY(-4px); }
|
|
106
106
|
to { opacity: 1; transform: translateY(0); }
|
|
107
107
|
}
|
|
108
|
-
`})]}),document.body):null;return o.jsxs(o.Fragment,{children:[wt,Ze,j&&Un.createPortal(o.jsx(zo,{isOpen:!0,onClose:Y,supportedChains:[j.chainId],escrowOnly:!0,escrowTokenAddress:j.tokenAddress,escrowAmount:j.amount,escrowTokenDecimals:j.tokenDecimals,escrowTokenSymbol:j.tokenSymbol,styles:u,onDepositSuccess:ee}),document.body)]})},Ul="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(Ul)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function fs(e,t,n,s){if(!t)return[e];const r=await t({...n,requestTimestampMs:s});return r?[r,e]:[e]}function Vn(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,v=B.parseUnits(n,s.decimals),M=t?.actionAmountOverride??v,b=r||a||(d?void 0:l);if(!b)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:b,chainId:c,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??v,netAmount:M,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},R=f(M,w),j={chainId:c,calls:R},N=!u&&!d?!0:g?.asset?._source==="spice",T=pr(g??null,d,c),S=N||d||T,A=(E,W)=>({token:E,from:d?"solver":"escrow",to:b,amount:W}),I=(E,W,O)=>T?[ur(E,W,c),...O]:O;if(v===0n)return[j];if(h&&y){const E=C??an(g.asset,c)??g.asset.address,W=t?.fundingAmountOverride??y.amountInMax,O=S?[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:[...O,...j.tokenTransfers??[]]};if(!S)return[P];const D=await fs(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(S){const E=C??an(g.asset,c)??s.address,W=t?.fundingAmountOverride??v,O={...j,tokenTransfers:[A(E,W),...j.tokenTransfers??[]]},z=await fs(O,x,{userAddress:b,destinationChainId:c,deliveryToken:E,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:ms(O),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,v=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,S={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,S),I=n.asset?._source==="wallet";if(!p&&x&&I&&n.asset.chainId===l){if(g){if(!C)throw new Error("Swap input token could not be resolved");if(!h||v===null)throw new Error("Swap quote not available yet")}if(g&&h&&v){const U=u(t?.actionAmountOverride??v,{...S,netAmount:t?.actionAmountOverride??v}),{feeCall:G,remainingCalls:ue}=fr(U,c,g,S.feeToken);return[{chainId:l,calls:[...G?[G]:[],...h.calls,...ue]}]}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,O=pr(n,x,l);if(!(E||W||O))return[{chainId:l,calls:A}];const z=O?ur(C??F.normalizeNativeTokenAddress(n.asset.address),R,l):W&&n.asset.chainId!==l?{chainId:n.asset.chainId,calls:[dr(F.normalizeNativeTokenAddress(n.asset.address),R,F.getEscrowContractAddress(n.asset.chainId))]}:null,P=(U,G)=>({token:U,from:W?"solver":"escrow",to:s,amount:G}),D=(U,G)=>W?[{token:U,from:"escrow",to:F.SPICE_SOLVER_ADDRESS,amount:G}]:[];if(g){if(!C)throw new Error("Swap input token could not be resolved");if(!h||v===null)throw new Error("Swap quote not available yet")}if(g&&h&&v&&C){const U=u(t?.actionAmountOverride??v,{...S,netAmount:t?.actionAmountOverride??v}),{feeCall:G,remainingCalls:ue}=fr(U,c,g,S.feeToken),q={chainId:l,calls:[...G?[G]:[],...h.calls,...ue],tokenTransfers:[...D(C,N),P(C,j)]},J=await fs(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,L={chainId:l,calls:A,tokenTransfers:[...D(Q,N),P(Q,j)]},te=await fs(L,f,{userAddress:s,destinationChainId:l,deliveryToken:Q,deliveryAmount:j,withdrawalAmount:N,deliveryRecipient:s,deliveryTransfers:ms(L),sourceAsset:n.asset},k);return z?[z,...te]:te}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 Ol(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=Cn(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,v=Ol(t.balance,C,k,t.balance);return v>0n?Eo(v,t.decimals):null}async function yr(e){const{selectedAsset:t,isPayMode:n,parsedAmount:s,needsSwap:r,exactOutputSwap:a,isNon7702:l,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:c,feeExecutionMode:f,resolvedTokenIn:p,embeddedWalletAddress:x,providerEmbeddedAddress:g,resolvedChainId:h,isConnected:y,address:C,ready:k,authenticated:v,isDirect:M,resolvedSwap:b,isQuoting:w,executionTokenAddress:R,buildPayChainBatches:j,buildSupplyChainBatches:N,estimate:T,estimateRequiredGrossFunding:S}=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,L={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=J,be=r?a?.amountInMax??0n:D;if(be===0n)return null;const ie=await S(be,ke=>j({fundingAmountOverride:ke}).then(_=>tn(Vn(_),le)),Q,{userOverride:J,useCustomTransfers:!0}),pe=tn(Vn(await j({fundingAmountOverride:ie})),le),ce=await T(pe,Q,ie,{userOverride:J,useCustomTransfers:!0,feeExecutionMode:f});return Cn(ce,L)}if(!y||!C||!k||!v)return null;const te=x||g||C,U=r?a?.amountInMax??0n:D;if(U===0n)return null;const G=await S(U,J=>j({fundingAmountOverride:J}).then(le=>tn(Vn(le),te)),Q,{useCustomTransfers:!0});let ue=tn(Vn(await j({fundingAmountOverride:G})),te);const q=await T(ue,Q,G,{useCustomTransfers:!0,feeExecutionMode:f});return Cn(q,L)}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,O={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=ts(I,10n),L=Q+D.gasFee;return{...O,grossAmount:I+L,netAmount:I,totalFee:L,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 Cn(P,O)}const zl=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 Gs(e){const t=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function qn(e,t,n){const s=Cn(e,Gs(t));if(!s)return;const r=ts(n,zl),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 Js(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=br(e,t.resolvedChainId,s);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:yn(r.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&yn(r.gasFee,n.feeBreakdown.gasFee,100n)}function wr(e,t){return e?yn(e.grossAmount,t.grossAmount,100n)&&yn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&yn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&yn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function kr(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const s=await $s(e);e.ui.setTxHash(s??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const s=new AbortController;e.refs.abortControllerRef.current=s,await vr(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){const r=s instanceof Error?s:new Error(String(s));if(r.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const a=r.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(a),e.ui.setError(a),e.onError?.(r)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=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=Cn(h,Gs(e));p=e.feeExecutionMode==="user-transfer"&&y?qn(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=qn(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),v=Js(h,e,y);return k||v?null:(x=y,e.execution.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:f,actionContextOverride:y}))}}:d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const s=n instanceof Error?n:new Error(String(n));if(s.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(s)}finally{e.ui.setIsExecuting(!1)}}async function vr(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const s=e.selectedAsset.asset,r=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 S=await m.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),A=ts(r,10n),I=A+S.gasFee;c=r+I,e.feeExecutionMode==="user-transfer"&&(x={grossAmount:c,netAmount:a,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:A,gasFee:S.gasFee,bridgeFee:0n}})}else for(let S=0;S<4;S+=1){const A=await e.execution.estimate(d,e.executionTokenAddress,0n,u),I=e.feeExecutionMode==="user-transfer"?qn(A,e,a):void 0,E=Cn(A,Gs(e)),W=I?.grossAmount??(E?E.grossAmount>r?E.grossAmount:r:c);if(x=I,W===c){c=W;break}c=W;const O=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),z=ln(c,O?.decimals??e.destinationToken.decimals,s.decimals);d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:z,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I})}const g=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let 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 v=m.getChainConfig(y),M=B.createWalletClient({account:e.externalWalletAddress,chain:v?.viemChain,transport:B.custom(k)}),b=F.normalizeNativeTokenAddress(s.address),w=s.isNative||F.isNativeToken(b),R=m.getClientForChain(y),j=S=>sr({extWc:M,sourceClient:R,recipient:C,tokenAddr:b,isNative:w,amount:S,viemChain:v?.viemChain});e.ui.setStatusMsg("Funding embedded wallet..."),await j(h);let N=h;if(e.feeExecutionMode==="user-transfer")for(let S=0;S<4;S+=1){const A=await e.execution.estimate(d,e.executionTokenAddress,0n,u),I=qn(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}),Js(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:S,chainBatches:A})=>{const I=qn(S,e,a);if(!I)return null;const E=wr(T,I),W=Js(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 O=l?I.grossAmount:ln(I.grossAmount,g?.decimals??e.destinationToken.decimals,s.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:O,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:p,actionContextOverride:I})}}:u)}async function $s(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,s=e.activeSignerAddress??e.externalWalletAddress;if(!s||!n)throw new Error("Please connect your wallet to continue");const r=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=await e.execution.estimateRequiredGrossFunding(a,k=>e.execution.buildPayChainBatches({fundingAmountOverride:k}),l,d),c=F.getEscrowContractAddress(s),f=await e.externalWallet.getEthereumProvider();await Wn(f,s);const p=m.getChainConfig(s),x=B.createWalletClient({account:e.externalWalletAddress,chain:p?.viemChain,transport:B.custom(f)}),g=F.normalizeNativeTokenAddress(n.address),h=n.isNative||F.isNativeToken(g)?await x.sendTransaction({to:c,value:u,chain:p?.viemChain}):await x.sendTransaction({to:g,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"transfer",args:[c,u]}),chain:p?.viemChain});if((await m.getClientForChain(s).waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const y=await e.execution.buildPayChainBatches({fundingAmountOverride:u}),C=y.some(k=>k.tokenTransfers?.length);return await e.execution.execute(y,l,u,k=>{k.txHash&&(e.ui.setPaymentResult(v=>({...v??{status:"processing"},txHash:k.txHash})),e.ui.setTxHash(k.txHash))},void 0,C?d:{userOverride:t})}async function Ir(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let s;if(e.isSourceDestToken||e.parsedAmount===0)s=await $s(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,a=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,v=>{v.txHash&&(e.ui.setPaymentResult(M=>({...M,txHash:v.txHash})),e.ui.setTxHash(v.txHash))},void 0,s);e.ui.setPaymentResult(v=>({status:"success",txHash:v?.txHash||k}));return}const r=e.selectedAsset?.asset;if(!r)throw new Error("Select a payment source");const a=e.resolvedTokenIn||r.address||e.destinationToken.address,l=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,d=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,u=(C,k,v)=>{const M=Vn(C),b=j=>(j.tokenTransfers??[]).some(N=>N.from==="escrow"),w=M.filter(j=>!b(j)),R=M.filter(b);return[...w,...tn(R,d,k,v)]},c=await e.execution.estimateRequiredGrossFunding(l,C=>e.execution.buildPayChainBatches({fundingAmountOverride:C}).then(k=>u(k)),a,s);let f=c,p=u(await e.execution.buildPayChainBatches({fundingAmountOverride:c}));const x=await e.execution.estimate(p,a,c,s),g=Cn(x,{chainId:e.resolvedChainId,tokenAddress:a,symbol:F.getTokenByAddress(a,e.resolvedChainId)?.symbol??r.symbol,decimals:F.getTokenByAddress(a,e.resolvedChainId)?.decimals??r.decimals})?.grossAmount??c;g!==c&&(f=g),p=u(await e.execution.buildPayChainBatches({fundingAmountOverride:f}),x,{payoutAlreadyGross:!0});const 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 Ll=({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:v=!1,maxAmount:M,onAmountChange:b})=>e==="supply"?o.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${c}`,borderRadius:p?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[o.jsxs("div",{style:{minWidth:0},children:[o.jsx("span",{style:{fontFamily:a,fontSize:"17px",fontWeight:500,color:p?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),o.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,fontFamily:a,marginTop:"10px"},children:"Net amount after swap and fees"})]}),o.jsxs("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${c}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[o.jsx(Er,{symbol:t,logoURI:n,primaryColor:r,size:24}),o.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:p?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),o.jsx("div",{style:{textAlign:"right",minWidth:0},children:x?o.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:a},children:"Quoting..."}):g?o.jsx("span",{style:{fontSize:"13px",color:p?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):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(Hl,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:k,isQuoting:x,adjustable:v,maxAmount:M,onAmountChange:b}),Ar=i.memo(Ll),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)}),Hl=({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 v='"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),[S,A]=i.useState(null);i.useEffect(()=>{y||R(p||"")},[p,y]);const I=O=>{let z=O;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=O=>{if(!b)return;if(O===100){R(C||b.toString()),j.current&&clearTimeout(j.current),k?.(C||b.toString());return}const z=10**n,P=Math.floor(b*O/100*z)/z,D=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:O=>I(O.target.value),placeholder:"0.0",fontFamily:v,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):o.jsx(In,{element:"div",value:M>0?p:"0.00",title:M>0?p:"0.00",fontFamily:v,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),o.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:v,marginTop:"2px"},children:e}),y&&b>0&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((O,z)=>{const P=Math.abs(W-O)<1,D=z===4,Q=O/100,L=N===O,te=S===O;return o.jsx("button",{onClick:()=>E(O),onMouseEnter:()=>T(O),onMouseLeave:()=>{T(null),A(null)},onMouseDown:()=>A(O),onMouseUp:()=>A(null),title:`${O}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:P?1:L?.8:.5,transform:te?"scale(0.85)":L?"scale(1.15)":"scale(1)",transition:_t.interactive},children:o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[o.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:D?s:"none",stroke:D?s:f?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!D&&Q>0&&o.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${Q>.5?1:0} 1 ${7+6.84375*Math.sin(Q*2*Math.PI)} ${7-6.84375*Math.cos(Q*2*Math.PI)} Z`,fill:f?c?.textSecondary||"#9ca3af":"#3C3E42"})]})},O)})})]})]}),x&&g&&!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,S=[],A=I=>{if(!I)return;const E=I.toLowerCase();T.has(E)||(T.add(E),S.push(B.getAddress(I)))};if(A(t.address),n)for(const I of n)A(I);return S},[l,t.address,n]),k=i.useMemo(()=>C.map(T=>T.toLowerCase()).sort().join(","),[C]),v=i.useMemo(()=>JSON.stringify([...s||[]].sort()),[s]),[M,b]=i.useState([]),w=i.useRef(0),R=i.useRef(async()=>{}),j=i.useCallback(async()=>{if(!r||!y||C.length===0){w.current++,b([]);return}const T=++w.current,S=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(L=>m.addressesEqual(L.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 L=m.getChainConfig(Q)?.supportedTokens?.find(te=>m.addressesEqual(te.address,P));if(L){I.push({address:z,chainId:Q,configToken:{decimals:L.decimals,symbol:L.symbol,name:L.name,logo:L.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 on.readContract(z,{address:P.address,abi:B.erc20Abi,functionName:"balanceOf",args:[S]}),{decimals:Q,symbol:L,name:te,logoURI:U}=await tr(z,P.address,P.configToken);return Tr(P,{decimals:Q,symbol:L,name:te,logoURI:U,balance:D},t)}catch{return null}},O=await Promise.all(Array.from(E.entries()).map(async([z,P])=>{let D;try{D=m.getClientForChain(z)}catch{return[]}const Q=[],L=[];for(const U of P){const G=Q.length;Q.push({address:U.address,abi:B.erc20Abi,functionName:"balanceOf",args:[S]}),U.configToken||Q.push({address:U.address,abi:B.erc20Abi,functionName:"decimals"},{address:U.address,abi:B.erc20Abi,functionName:"symbol"},{address:U.address,abi:B.erc20Abi,functionName:"name"}),L.push({start:G,item:U})}let te=null;try{te=await D.multicall({contracts:Q})}catch{te=null}return te?L.map(({start:U,item:G})=>{const ue=te[U],q=ue?.status==="success"?ue.result:0n;let J,le,be,ie;if(G.configToken)J=G.configToken.decimals,le=G.configToken.symbol,be=G.configToken.name,ie=G.configToken.logo;else{const pe=te[U+1],ce=te[U+2],ke=te[U+3];J=pe?.status==="success"?Number(pe.result):18,le=ce?.status==="success"?ce.result:"TOKEN",be=ke?.status==="success"?ke.result:le}return Tr(G,{decimals:J,symbol:le,name:be,logoURI:ie,balance:q},t)}):(await Promise.all(P.map(U=>W(D,U)))).filter(U=>U!==null)}));T===w.current&&b(O.flat())},[r,l,y,k,v,t.address,t.chainId,t.symbol,t.logoURI]);i.useEffect(()=>{R.current=j},[j]),i.useEffect(()=>{if(!r){b([]);return}R.current();const T=setInterval(()=>{R.current()},15e3);return()=>clearInterval(T)},[r,l,y,k,v,t.address,t.chainId]);const N=i.useCallback(()=>{j()},[j]);return{displayAssets:i.useMemo(()=>{const T=[],S=M.filter(I=>I.balance>0n);for(const I of S)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 Ql=[{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 Vl(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:Ql,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 ql(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>Vl({...e,fee:r})));let s=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!s||a.value.amountIn<s.amountIn)&&(s={...a.value,fee:t[r]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}function Nr(e){return e.type==="swap"}const _s=.02,Yl=[1,8453,42161,10,137,43114,56],Kl="https://api.1inch.dev/swap/v6.0";function Dr(e,t){return F.applySlippage(e,t)}function Wr(e){const t=e?.baseUrl??Kl;return{name:"1inch",chainIds:e?.chainIds??Yl,resolve:async(n,s,r)=>{const a=n.maxSlippage??_s,l=a*100,d=F.isNativeToken(n.tokenIn)?F.NATIVE_TOKEN_ADDRESS:n.tokenIn,u=F.isNativeToken(n.tokenOut)?F.NATIVE_TOKEN_ADDRESS:n.tokenOut,c=F.isNativeToken(n.tokenIn);try{const f=new URL(`${t}/${s}/swap`);f.searchParams.set("src",d),f.searchParams.set("dst",u),f.searchParams.set("amount",n.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",l.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const x=await fetch(f.toString(),{headers:p});if(!x.ok)throw new 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],eo={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Ur={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Or(e){return{name:"satsuma",chainIds:e.chainIds??Pr,resolve:async(t,n,s)=>{const r=t.maxSlippage??_s,a=F.isNativeToken(t.tokenIn);let l;try{l=await Mr({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const d=Dr(l.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data: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??_s,a=F.isNativeToken(t.tokenIn);let l;try{l=await ql({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:Zl,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 Zl=[{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(u=>u.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(u=>u.resolve(s,r,a)))).filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u!==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()});return d.sort((u,c)=>u.amountIn<c.amountIn?-1:u.amountIn>c.amountIn?1:0),d[0]}return{getQuote:n,venues:t}}const Qr=Lr({satsuma:eo});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),[v,M]=i.useState(null),[b,w]=i.useState(null),[R,j]=i.useState(null),[N,T]=i.useState(null),S=i.useRef(null),A=i.useRef(null),I=i.useRef(0),E=i.useRef(new Map),W=i.useMemo(()=>Qr,[]),O=i.useMemo(()=>Hr({customVenues:[...d?[{name:"consumer-exact-output",chainIds:[r],resolve:d}]:[],zr(eo),zr(Ur)]}),[d,r]),z=i.useMemo(()=>{if(!n?.asset)return null;const J=an(n.asset,r);if(J)return J;const le=mn(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 wo(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]),L=i.useMemo(()=>!n?.asset||!Q?[]:[Q,...P.filter(J=>J.toLowerCase()!==Q.toLowerCase())],[n?.asset,Q,P]),te=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]),U=Q?m.addressesEqual(Q,s.address):!1,G=t==="output"&&parseFloat(l||"0")===0,ue=!!n?.asset&&!te&&!U&&!G,q=ue?R??Q:Q;return i.useEffect(()=>{S.current&&clearTimeout(S.current);const J=t==="input"?n?.amount:l,le=parseFloat(J||"0");if(!ue||!Number.isFinite(le)||le<=0||!n?.asset||!a||L.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 pe=++I.current,ce=()=>pe!==I.current;c(!0);const ke=t==="output"?150:400;return S.current=setTimeout(async()=>{try{if(t==="input"){const _=W.getVenueForChain(r);if(!_)throw new Error("No swap venue for this chain");let Y=null,ee=null;for(const ge of L){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,ee=ge;break}const me=await _.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,ee=ge;break}}if(!Y||!ee)throw new Error("No liquidity for this pair");j(ee),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 _=null,Y=null;for(const ee of L){const re=`${t}:${r}:${ee.toLowerCase()}:${s.address.toLowerCase()}:${ie.toString()}`,ge=E.current.get(re);if(ge&&ge.expiresAt>Date.now()&&ge.exactOutputSwap){_=ge.exactOutputSwap,Y=ee;break}try{const K=await O.getQuote({tokenIn:ee,tokenOut:s.address,amountOut:ie},r,a);if(ce())return;E.current.set(re,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:K}),_=K,Y=ee;break}catch{if(ce())return}}if(!_||!Y)throw new Error("No liquidity for this pair");j(Y),M(_),k(null),w(null),y(parseFloat(B.formatUnits(_.amountIn,be)).toFixed(6)),g(null),p(null)}}catch(_){if(ce())return;const Y=_ instanceof Error?_.message:"Failed to get quote";p(Y),g(null),y(null),k(null),M(null),w(null),j(null)}finally{ce()||c(!1)}},ke),()=>{S.current&&clearTimeout(S.current)}},[t,ue,n?.amount,n?.asset?.address,n?.asset?.decimals,l,L,r,s.address,s.decimals,a,W,O]),{isQuoting:u,quoteError:f,estimatedOutput:x,estimatedInput:h,resolvedSwap:C,exactOutputSwap:v,quoteAmountOut:b,resolvedTokenIn:q,isDirect:U,needsSwap:ue,selectedIsEquivalent:te}}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"],Gl=()=>{},Jl=({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:v,onAmountChange:M,styles:b,dark:w,title:R,subtitle:j,onAddFunds:N,onSuccess:T,onError:S})=>{const A=x==="output",{theme:I,dark:E,primaryColor:W,dk:O,palette:z,fontFamily:P,monoFont:D,inputDark:Q,cardBg:L,cardBorder:te,textPrimary:U,textSecondary:G,subtitleText:ue}=m.useSpiceBrand(b,w),q=i.useMemo(()=>Q?{...I,colors:{...I.colors,secondary:O.cardBg,surfaceHover:O.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:I,[Q,I,O.cardBg,O.hoverBg]),J=s.chainId,le=i.useContext(m.SpiceFlowProviderContext),be=le?.mode||"7702",ie=be!=="7702",pe=!!le?.isWhitelistGateActive,ce=!!le?.isWhitelistConfigured&&le?.isUserWhitelisted!==!0,ke=i.useMemo(()=>r??le?.supportedChainIds??[],[r,le?.supportedChainIds]),_=i.useMemo(()=>{if(pe)return[];if(a)return a;const he=le?.allowedTokens;if(!he||he.length===0)return;const $e=new Set(he.map(gn=>gn.toLowerCase())),dn=[],hn=new Set;for(const gn of ke){const hs=m.getChainConfig(gn);for(const gs of hs?.supportedTokens??[]){if(!$e.has(gs.symbol.toLowerCase()))continue;const to=gs.address.toLowerCase();hn.has(to)||(hn.add(to),dn.push(gs.address))}}return dn},[a,le?.allowedTokens,ke,pe]),Y=m.useWallet(),{address:ee,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,fe=le?.embeddedWalletAddress||it,{displayAssets:At,filteredSpiceAssets:Te,embeddedWalletAddress:De,refreshSpiceAssets:_e,refreshWalletAssets:wt}=Br({destinationToken:s,supportedSourceAssets:_,sourceChains:ke,enabled:e&&(ie?!!lt:!!fe)}),Ze=pe||A||ie?At:Te;i.useEffect(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:be,walletAddressUsed:De,count:Ze.length,assets:Ze.map(he=>({symbol:he.symbol,address:he.address,chainId:he.chainId,balanceFormatted:he.balanceFormatted,source:he?._source}))})},[e,be,De,Ze]);const[H,He]=i.useState(null),[Ie,Qe]=i.useState(y||""),[Oe,Rt]=i.useState(!1),[Nt,zt]=i.useState(null),[ve,Dt]=i.useState("idle"),[Xe,nn]=i.useState(""),[Zt,Ve]=i.useState(null),[Lt,Et]=i.useState(!1),[Pe,ye]=i.useState(null),[Ue,Ke]=i.useState(null),[Xt,we]=i.useState(!1),[Mt,yt]=i.useState(!1),[pt,qe]=i.useState(null),sn=i.useRef(H),jt=i.useRef(!1),Ht=i.useRef(null),Gt=i.useRef(null),Ft=i.useRef(0),gt=i.useRef(null),ct=i.useRef(null);i.useEffect(()=>{sn.current=H},[H]);const Re=C==="adjustable"?Ie:y||"0",et=De||it||ee,{isQuoting:ft,quoteError:Qt,estimatedOutput:Wt,resolvedSwap:mt,exactOutputSwap:Se,quoteAmountOut:Ct,resolvedTokenIn:ot,isDirect:bt,needsSwap:tt,selectedIsEquivalent:Ae}=Vr({direction:x,selectedAsset:H,destinationToken:s,chainId:J,recipient:et,paymentAmount:Re,resolveExactOutputSwap:f}),nt=A?parseFloat(Re||"0"):parseFloat(H?.amount||"")||0,Pt=nt>0&&nt<fn,$=H?.asset?._source==="wallet",se=!!H?.asset&&$&&H.asset.chainId!==J,Ce=i.useMemo(()=>H?.asset?Te.find(he=>m.addressesEqual(he.address,H.asset.address))?.balanceFormatted??0:0,[H,Te]),Me=$?H?.asset.balanceFormatted??0:Ce,Ye=i.useMemo(()=>{if(!H?.asset)return!1;if(A)return Ue?ln(Ue.grossAmount,Ue.decimals,H.asset.decimals)>H.asset.balance:Ae||bt?nt>H.asset.balanceFormatted:Se?parseFloat(B.formatUnits(Se.amountInMax,H.asset.decimals))>H.asset.balanceFormatted:!1;if(Ue){const he=ln(Ue.grossAmount,Ue.decimals,H.asset.decimals);return $?he>H.asset.balance:parseFloat(B.formatUnits(he,H.asset.decimals))>Me}return nt>Me},[H,A,Ue,Ae,nt,Se,Me,$,bt]);i.useEffect(()=>{e||(He(null),zt(null),Rt(!1),Dt("idle"),nn(""),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=>{He($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=>{He($e=>$e&&{...$e,amount:he}),zt(null),qe(null),yt(!1)},[]),at=i.useCallback(he=>{let $e=he;v&&parseFloat($e)>parseFloat(v)&&($e=v),Qe($e),M?.($e),zt(null),qe(null),yt(!1)},[v,M]);i.useCallback(he=>{if(jt.current||!ee)return;const $e=sn.current;!$e?.asset||!$e.amount||$e.asset?._source==="wallet"||B.parseUnits(A?Re:$e.amount,$e.asset.decimals)===0n||(jt.current=!0,_e())},[ee,J,_e,A,Re]);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"),nn(he.message),he.txHash&&Ve(he.txHash)},[]),xt=i.useMemo(()=>({currentPaymentAmount:Re,destinationToken:s,embeddedWalletAddress:De,providerEmbeddedAddress:it,externalWalletAddress:lt,address:ee,isNon7702:ie,isPayMode:A,resolvedChainId:J,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:H,needsSwap:tt,resolvedSwap:mt,exactOutputSwap:Se,quoteAmountOut:Ct,resolvedTokenIn:ot}),[Re,s,De,it,lt,ee,ie,A,J,l,d,u,H,tt,mt,Se,Ct,ot]),Ne=i.useCallback(he=>mr({...xt,requestTimestampMs:Gt.current??Date.now()},he),[xt]),Z=i.useCallback(he=>hr({...xt,requestTimestampMs:Gt.current??Date.now()},he),[xt]),xe=i.useCallback((he,$e,dn,hn)=>gr(he,$e,dn,oe,hn),[oe]),ut=i.useMemo(()=>H?.asset?tt&&ot?ot:H.asset.chainId===J?H.asset.address:ot??an(H.asset,J)??s.address:s.address,[H,s.address,tt,J,ot]),ht=i.useCallback(()=>(Gt.current=Date.now(),kr(ct.current)),[]),ze=i.useMemo(()=>H?.asset?m.addressesEqual(H.asset.address,s.address)&&H.asset.chainId===s.chainId:!1,[H,s.address,s.chainId]),kt=ze&&(ie||A),Ge=kt&&nt>0&&!!H?.asset,Vt=ce&&!kt,V=i.useMemo(()=>{if(!Ge)return null;let he;try{he=B.parseUnits(Re||"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"}},[Ge,Re,s.symbol,s.decimals]),X=Nt,de=i.useMemo(()=>!(!H?.asset||nt<=0),[H,nt,Ge]),ae=i.useMemo(()=>!e||Oe||ve!=="idle"||!de||Ge||!H?.asset?null:[A?"pay":"supply",x,H.asset.address.toLowerCase(),H.asset.chainId,H.amount,Re,s.address.toLowerCase(),s.chainId,J,ot?.toLowerCase()??"",tt?"swap":"direct",bt?"direct-token":"routed-token",ie?"non7702":"7702",ze?"source-dest":"cross-chain",ft?"quoting":"quoted",Se?.amountIn?.toString()??"",Se?.amountInMax?.toString()??"",Se?.venue??"",mt?.amountOut?.toString()??"",Ct?.toString()??"",De??"",it??"",ee??""].join("|"),[e,Oe,ve,de,Ge,H,A,x,Re,s,J,ot,tt,bt,ie,ze,ft,Se,mt,Ct,De,it,ee]),We=i.useCallback(()=>yr({selectedAsset:H,isPayMode:A,parsedAmount:nt,needsSwap:tt,exactOutputSwap:Se,isNon7702:ie,isSourceDestToken:ze,currentPaymentAmount:Re,destinationToken:s,feeExecutionMode:d,resolvedTokenIn:ot,embeddedWalletAddress:De,providerEmbeddedAddress:it,resolvedChainId:J,isConnected:re,address:ee,ready:ge,authenticated:K,isDirect:bt,resolvedSwap:mt,isQuoting:ft,executionTokenAddress:ut,buildPayChainBatches:Ne,buildSupplyChainBatches:Z,estimate:oe,estimateRequiredGrossFunding:xe}),[H,A,nt,tt,Se,ie,ze,Re,s,d,ot,De,it,xe,Ne,oe,J,re,ee,ge,K,bt,mt,ft,Z,ut]);i.useEffect(()=>{gt.current=We},[We]);const je=i.useCallback(he=>xr({asset:he,isPayMode:A,isNon7702:ie,needsSwap:tt,isQuoting:ft,embeddedWalletAddress:De,buildSupplyChainBatches:Z,estimate:oe,executionTokenAddress:ut,feeExecutionMode:d}),[A,ie,tt,ft,De,Z,oe,ut,d]);i.useEffect(()=>{if(!e){we(!1),yt(!1),qe(null),Ke(null);return}if(Oe||ve!=="idle"){Ft.current+=1,we(!1);return}if(!de){Ke(null),we(!1),yt(!1),qe(null);return}if(Ge){Ke(V),we(!1),yt(!0),qe(null);return}if(ft){Ft.current+=1,we(!1),yt(!1);return}if(!ae)return;let he=!1;const $e=async()=>{const hn=++Ft.current;qe(null),we(!0);try{const gn=await gt.current?.();if(he||Ft.current!==hn)return;gn?(Ke(gn),yt(!0)):(Ke(null),yt(!1)),qe(null)}catch(gn){if(he||Ft.current!==hn)return;const hs=m.sanitizeError(gn,"Unable to calculate fees for this action.");Ke(null),yt(!1),qe(hs)}finally{!he&&Ft.current===hn&&we(!1)}},dn=window.setTimeout(()=>{$e()},250);return()=>{he=!0,clearTimeout(dn),we(!1)}},[e,Oe,ve,de,Ge,V,ft,ae]);const Le=i.useCallback(()=>(Gt.current=Date.now(),Ir(ct.current)),[]);i.useEffect(()=>{!A&&ve==="success"&&Zt&&(_e(),T?.(Zt))},[A,ve,Zt,_e,T]),i.useEffect(()=>{if(!A||Pe?.status!=="success"||jt.current||!ee)return;jt.current=!0;const he=sn.current;!he?.asset||he.asset?._source==="wallet"||_e()},[A,Pe?.status,ee,_e]);const st=i.useRef(T),vt=i.useRef(S);i.useEffect(()=>{st.current=T},[T]),i.useEffect(()=>{vt.current=S},[S]),i.useEffect(()=>{e&&(_e(),wt())},[e,_e,wt]),i.useEffect(()=>{A&&(Pe?.status==="success"&&st.current?.(Pe.txHash||""),Pe?.status==="failed"&&vt.current?.(new Error("Payment execution failed")))},[A,Pe?.status]);const Ut=i.useCallback(()=>{Et(!1),ye(null),He(null),jt.current=!1,_e(),wt()},[_e,wt]);ct.current={selectedAsset:H,parsedAmount:nt,currentPaymentAmount:Re,isInsufficientBalance:Ye,isPayMode:A,isNon7702:ie,isSourceDestToken:ze,needsSwap:tt,exactOutputSwap:Se,selectedIsEquivalent:Ae,resolvedTokenIn:ot,embeddedWalletAddress:De,providerEmbeddedAddress:it,externalWallet:Be,externalWalletAddress:lt,activeSignerWallet:St,activeSignerAddress:It,address:ee,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:S,execution:{estimate:oe,execute:me,buildPayChainBatches:Ne,buildSupplyChainBatches:Z,estimateRequiredGrossFunding:xe,onProgress:Ee},ui:{setError:zt,setStep:Dt,setStatusMsg:nn,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||!!H?.asset)&&nt>=0&&!Pt&&!Ye&&!Oe&&(Tt||Ge||Mt)&&!pt&&(Tt||!tt||!!Se)&&!Vt:!!H?.asset&&nt>0&&!Pt&&!Ye&&!Oe&&(kt||Mt)&&!pt&&(se||bt||!!mt&&!ft)&&!Vt;i.useEffect(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:$t,isPayMode:A,hasSelectedAsset:!!H?.asset,selectedAsset:H?.asset?{symbol:H.asset.symbol,address:H.asset.address,chainId:H.asset.chainId,balanceFormatted:H.asset.balanceFormatted,source:H.asset?._source}:null,parsedAmount:nt,isZeroAmountPay:Tt,isBelowMinimum:Pt,isInsufficientBalance:Ye,isExecuting:Oe,directExternalAction:kt,directExecutionFeeNote:Ge,feeEstimateReady:Mt,feeEstimateError:pt,needsSwap:tt,isDirect:bt,isSourceDestToken:ze,hasExactOutputSwap:!!Se,isQuoting:ft,whitelistHoldPending:ce,supplyHeldForWhitelist:Vt,isWhitelistGateActive:pe,destinationToken:{symbol:s.symbol,address:s.address,chainId:s.chainId}})},[e,$t,A,H,nt,Tt,Pt,Ye,Oe,kt,Ge,Mt,pt,tt,bt,ze,Se,ft,ce,Vt,pe,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=Oe?(qr[ve]||"EXECUTING...").toUpperCase():ve==="success"?"DONE":Pt?`MINIMUM ${fn}`:Ye?"INSUFFICIENT BALANCE":p.toUpperCase(),Je=i.useMemo(()=>{if(Oe)return"PAYING...";if(Pt)return`MINIMUM ${fn}`;if(Ye&&H?.asset)return`INSUFFICIENT ${H.asset.symbol}`;if(p)return p.toUpperCase();const he=nt>0?` ${Re} ${s.symbol}`:"";return tt?`SWAP & PAY${he}`:`PAY${he}`},[Oe,Pt,Ye,H,p,nt,Re,s.symbol,tt]),Ot=ve==="success"?()=>{Dt("idle"),He(null),Ve(null),_e()}:ht,cn=ve==="success"?!1:!$t;if(!e)return null;const Kn=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:ue})}),o.jsx("p",{style:{fontSize:"12px",color:ue,margin:0,lineHeight:"1.4",fontFamily:P},children:kn})]});if(A){const he=Pe&&(Pe.status==="success"||Pe.status==="failed")?[{asset:{symbol:H?.asset?.symbol||s.symbol,address:H?.asset?.address||""},amount:Re,txHash:Pe.txHash||"",success:Pe.status==="success",error:Pe.status==="failed"?Pe.error:void 0}]:void 0;return o.jsx(un,{isOpen:e,onClose:t,title:Kn,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:H??void 0,onAssetSelect:rt,onAmountChange:Gl,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:H?.asset?tt?ft?"...":Se?`~${parseFloat(B.formatUnits(Se.amountIn,H.asset.decimals)).toFixed(6)}`:void 0:Re??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:U,textSecondary:G,cardBg:L,cardBorder:te,dk:O,dark:E,isQuoting:ft,quoteError:Qt,estimatedOutput:Wt,paymentAmount:Re,needsSwap:tt,exactOutputSwap:Se,adjustable:C==="adjustable",maxAmount:v,onAmountChange:at}),de&&o.jsx(is,{fontFamily:P,textPrimary:U,textSecondary:G,cardBg:L,cardBorder:te,resolvedDark:E,darkCardBorder:O.cardBorder,primaryColor:W,feePreview:Ue,isLoading:Xt,errorText:pt,directExecutionFeeNote:Ge}),X&&o.jsx(Nn,{variant:"error",palette:z,fontFamily:P,style:{marginBottom:"12px"},children:X}),o.jsx(m.Button,{variant:"outline",fullWidth:!0,onClick:Le,disabled:!$t,loading:Oe,dark:E,styles:{...b,button:{...b?.button,backgroundColor:W}},children:Je}),Pe&&Lt&&o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:E?O.shell:"white",borderRadius:E?"12px":"6px",padding:"16px 0"},children:o.jsx(Ls,{type:"payment",isOpen:Pe.status!=="processing",isProcessing:Oe||Pe.status==="processing",closeOnComplete:!1,chainName:m.getChainName(J),explorerUrl:m.getExplorerUrl(J,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Et(!1),ye(null),Le()},onNewTx:Ut,onClose:()=>{Et(!1),ye(null)},onComplete:Ut,results:he,styles:b,dark:E})})]})})}return o.jsx(un,{isOpen:e,onClose:t,title:Kn,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:H||void 0,onAssetSelect:rt,onAmountChange:dt,disabled:Oe||ve==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:q,styles:b,dark:Q,resolveMaxAmount:je,maxAmount:Me>0?m.formatDecimalInput(Me,H?.asset.decimals??s.decimals):void 0})}),H?.asset&&!bt&&o.jsx(Ar,{variant:"supply",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:W,fontFamily:P,textPrimary:U,textSecondary:G,cardBg:L,cardBorder:te,dark:E,isQuoting:ft,quoteError:Qt,estimatedOutput:Wt}),de&&o.jsx(is,{fontFamily:P,textPrimary:U,textSecondary:G,cardBg:L,cardBorder:te,resolvedDark:E,darkCardBorder:O.cardBorder,primaryColor:W,feePreview:Ue,isLoading:Xt,errorText:pt,directExecutionFeeNote:Ge}),ve!=="idle"&&o.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:ve==="success"?L:ve==="error"?z.errorBg:L,border:`1px solid ${ve==="success"?te:ve==="error"?z.errorBorder:te}`},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"?U:ve==="error"?z.errorText:U,fontFamily:P,flex:1},children:ve==="success"?"Deposit confirmed":ve==="error"?Xe||"Transaction failed":qr[ve]||Xe}),ve==="success"&&Zt&&o.jsx("a",{href:`${jn}/tx/${Zt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:W,fontFamily:P,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),ve==="error"&&o.jsx("button",{onClick:()=>{Dt("idle"),zt(null),setTimeout(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:`${G}22`,overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:W,transformOrigin:"left center",transform:`scaleX(${(vn+1)/Yr.length})`,transition:"transform 400ms ease"}})})]}),Nt&&ve==="idle"&&o.jsx(Nn,{variant:"error",palette:z,fontFamily:P,style:{marginBottom:"16px"},children:Nt}),o.jsx(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 _l(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 ec(){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 Yn(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 tc(e,t){if(e[0].toUpperCase()===t[0].toUpperCase()&&e[1]===t[1])return!0;let n,s;try{n=Yn(e),s=Yn(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 nc(){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 sc(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??nc();if(!u.some(C=>tc(n,C))){const C=u.map(([k,v])=>`${k} (chain ${v})`).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=Yn(n),f=Yn(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 _o({route:p,sourceAmount:s,userAddress:a,registry:r,actionCalls:t.calls,slippage:l});return{chainBatches:x,route:p,resolvedSwaps:y,resolvedInputToken:c,resolvedOutputToken:f,solverFrontToken:g,solverFrontAmount:h}}const oc=[0n,1n,30n],rc=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 ac(e,t){const{chainId:n,swapCalls:s,quoteAmountOut:r,buildActionCalls:a,tokenAddress:l,tokenTransferAmount:d,onProgress:u,signal:c,options:f,buffers:p=oc}=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 v=typeof k?.message=="string"?k.message:String(k?.message??"");if(m.isSpiceflowError(k)&&rc.has(k.code)||k.name==="AbortError"||c?.aborted||v.includes("User rejected")||v.includes("User denied")||k.code===4001||x>=p.length-1)throw k;const M=Number(p[x+1])/10;console.warn(`[SwapThenAction] Action attempt ${x+1} failed (buffer ${Number(g)/10}%), retrying with ${M}% buffer...`,k.message),u?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${M}% buffer)...`})}}throw new 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=Pl,exports.AddFundsLink=Ws,exports.CheckIcon=Do,exports.ChevronIcon=bn,exports.CloseIcon=Tn,exports.DetailRow=Dn,exports.ProviderLogin=zs,exports.SATSUMA_CITREA_CONFIG=eo,exports.SearchInput=bs,exports.SelectChainModal=Ui,exports.SpiceDeposit=Pi,exports.SpiceLock=ar,exports.SpiceLockModal=ar,exports.SpiceSupply=Jl,exports.SpiceWithdraw=el,exports.StatusBanner=Nn,exports.UNIV3_BASE_CONFIG=Ur,exports.applyBuffer=Kr,exports.areEquivalentOnChains=Hn,exports.buildIntent=sc,exports.buildPayChainBatches=mr,exports.buildRoutedBatches=_o,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=ac,exports.findEquivalentOnChain=mn,exports.findTokenOnChain=Vs,exports.font=oo,exports.getAssetChainTokenCandidates=Gn,exports.getBestUniV3Quote=Mr,exports.getUniV3Quote=Rr,exports.isSupportedSupplyAsset=Fr,exports.isSwapIntent=Nr,exports.radius=Cs,exports.resolveAssetTokenAddressOnChain=an,exports.resolveFundedToken=wo,exports.resolveInputSupplySwapQuote=Xl,exports.resolveRoute=$o,exports.resolveTokenRef=Yn,exports.scaleTokenAmount=ln,exports.transition=_t,exports.useAssetInput=$l,exports.useLockDuration=_l,exports.useSmartWallet=ec,exports.useSpiceAssets=Qn,exports.useSpiceExecution=Mn,exports.useSpicePendingDeposits=ir,exports.useSupplyAssets=Br,exports.useSupplyQuote=Vr,exports.z=Sn;
|
|
108
|
+
`})]}),document.body):null;return o.jsxs(o.Fragment,{children:[wt,Ze,j&&Un.createPortal(o.jsx(zo,{isOpen:!0,onClose:Y,supportedChains:[j.chainId],escrowOnly:!0,escrowTokenAddress:j.tokenAddress,escrowAmount:j.amount,escrowTokenDecimals:j.tokenDecimals,escrowTokenSymbol:j.tokenSymbol,styles:u,onDepositSuccess:ee}),document.body)]})},Ul="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(Ul)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function fs(e,t,n,s){if(!t)return[e];const r=await t({...n,requestTimestampMs:s});return r?[r,e]:[e]}function Vn(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,v=B.parseUnits(n,s.decimals),M=t?.actionAmountOverride??v,b=r||a||(d?void 0:l);if(!b)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:b,chainId:c,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??v,netAmount:M,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},R=f(M,w),j={chainId:c,calls:R},N=!u&&!d?!0:g?.asset?._source==="spice",T=pr(g??null,d,c),S=N||d||T,A=(E,W)=>({token:E,from:d?"solver":"escrow",to:b,amount:W}),I=(E,W,O)=>T?[ur(E,W,c),...O]:O;if(v===0n)return[j];if(h&&y){const E=C??an(g.asset,c)??g.asset.address,W=t?.fundingAmountOverride??y.amountInMax,O=S?[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:[...O,...j.tokenTransfers??[]]};if(!S)return[P];const D=await fs(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(S){const E=C??an(g.asset,c)??s.address;if(T&&E.toLowerCase()===s.address.toLowerCase())return[j];const W=t?.fundingAmountOverride??v,O={...j,tokenTransfers:[A(E,W),...j.tokenTransfers??[]]},z=await fs(O,x,{userAddress:b,destinationChainId:c,deliveryToken:E,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:ms(O),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,v=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,S={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,S),I=n.asset?._source==="wallet";if(!p&&x&&I&&n.asset.chainId===l){if(g){if(!C)throw new Error("Swap input token could not be resolved");if(!h||v===null)throw new Error("Swap quote not available yet")}if(g&&h&&v){const U=u(t?.actionAmountOverride??v,{...S,netAmount:t?.actionAmountOverride??v}),{feeCall:G,remainingCalls:ue}=fr(U,c,g,S.feeToken);return[{chainId:l,calls:[...G?[G]:[],...h.calls,...ue]}]}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,O=pr(n,x,l);if(!(E||W||O))return[{chainId:l,calls:A}];const z=O?ur(C??F.normalizeNativeTokenAddress(n.asset.address),R,l):W&&n.asset.chainId!==l?{chainId:n.asset.chainId,calls:[dr(F.normalizeNativeTokenAddress(n.asset.address),R,F.getEscrowContractAddress(n.asset.chainId))]}:null,P=(U,G)=>({token:U,from:W?"solver":"escrow",to:s,amount:G}),D=(U,G)=>W?[{token:U,from:"escrow",to:F.SPICE_SOLVER_ADDRESS,amount:G}]:[];if(g){if(!C)throw new Error("Swap input token could not be resolved");if(!h||v===null)throw new Error("Swap quote not available yet")}if(g&&h&&v&&C){const U=u(t?.actionAmountOverride??v,{...S,netAmount:t?.actionAmountOverride??v}),{feeCall:G,remainingCalls:ue}=fr(U,c,g,S.feeToken),q={chainId:l,calls:[...G?[G]:[],...h.calls,...ue],tokenTransfers:[...D(C,N),P(C,j)]},J=await fs(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,L={chainId:l,calls:A,tokenTransfers:[...D(Q,N),P(Q,j)]},te=await fs(L,f,{userAddress:s,destinationChainId:l,deliveryToken:Q,deliveryAmount:j,withdrawalAmount:N,deliveryRecipient:s,deliveryTransfers:ms(L),sourceAsset:n.asset},k);return z?[z,...te]:te}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 Ol(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=Cn(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,v=Ol(t.balance,C,k,t.balance);return v>0n?Eo(v,t.decimals):null}async function yr(e){const{selectedAsset:t,isPayMode:n,parsedAmount:s,needsSwap:r,exactOutputSwap:a,isNon7702:l,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:c,feeExecutionMode:f,resolvedTokenIn:p,embeddedWalletAddress:x,providerEmbeddedAddress:g,resolvedChainId:h,isConnected:y,address:C,ready:k,authenticated:v,isDirect:M,resolvedSwap:b,isQuoting:w,executionTokenAddress:R,buildPayChainBatches:j,buildSupplyChainBatches:N,estimate:T,estimateRequiredGrossFunding:S}=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,L={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=J,be=r?a?.amountInMax??0n:D;if(be===0n)return null;const ie=await S(be,ke=>j({fundingAmountOverride:ke}).then(_=>tn(Vn(_),le)),Q,{userOverride:J,useCustomTransfers:!0}),pe=tn(Vn(await j({fundingAmountOverride:ie})),le),ce=await T(pe,Q,ie,{userOverride:J,useCustomTransfers:!0,feeExecutionMode:f});return Cn(ce,L)}if(!y||!C||!k||!v)return null;const te=x||g||C,U=r?a?.amountInMax??0n:D;if(U===0n)return null;const G=await S(U,J=>j({fundingAmountOverride:J}).then(le=>tn(Vn(le),te)),Q,{useCustomTransfers:!0});let ue=tn(Vn(await j({fundingAmountOverride:G})),te);const q=await T(ue,Q,G,{useCustomTransfers:!0,feeExecutionMode:f});return Cn(q,L)}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,O={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=ts(I,10n),L=Q+D.gasFee;return{...O,grossAmount:I+L,netAmount:I,totalFee:L,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 Cn(P,O)}const zl=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 Gs(e){const t=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function qn(e,t,n){const s=Cn(e,Gs(t));if(!s)return;const r=ts(n,zl),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 Js(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=br(e,t.resolvedChainId,s);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:yn(r.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&yn(r.gasFee,n.feeBreakdown.gasFee,100n)}function wr(e,t){return e?yn(e.grossAmount,t.grossAmount,100n)&&yn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&yn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&yn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function kr(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const s=await $s(e);e.ui.setTxHash(s??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const s=new AbortController;e.refs.abortControllerRef.current=s,await vr(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){const r=s instanceof Error?s:new Error(String(s));if(r.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const a=r.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(a),e.ui.setError(a),e.onError?.(r)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=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=Cn(h,Gs(e));p=e.feeExecutionMode==="user-transfer"&&y?qn(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=qn(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),v=Js(h,e,y);return k||v?null:(x=y,e.execution.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:f,actionContextOverride:y}))}}:d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const s=n instanceof Error?n:new Error(String(n));if(s.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(s)}finally{e.ui.setIsExecuting(!1)}}async function vr(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const s=e.selectedAsset.asset,r=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 S=await m.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),A=ts(r,10n),I=A+S.gasFee;c=r+I,e.feeExecutionMode==="user-transfer"&&(x={grossAmount:c,netAmount:a,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:A,gasFee:S.gasFee,bridgeFee:0n}})}else for(let S=0;S<4;S+=1){const A=await e.execution.estimate(d,e.executionTokenAddress,0n,u),I=e.feeExecutionMode==="user-transfer"?qn(A,e,a):void 0,E=Cn(A,Gs(e)),W=I?.grossAmount??(E?E.grossAmount>r?E.grossAmount:r:c);if(x=I,W===c){c=W;break}c=W;const O=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),z=ln(c,O?.decimals??e.destinationToken.decimals,s.decimals);d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:z,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I})}const g=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let 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 v=m.getChainConfig(y),M=B.createWalletClient({account:e.externalWalletAddress,chain:v?.viemChain,transport:B.custom(k)}),b=F.normalizeNativeTokenAddress(s.address),w=s.isNative||F.isNativeToken(b),R=m.getClientForChain(y),j=S=>sr({extWc:M,sourceClient:R,recipient:C,tokenAddr:b,isNative:w,amount:S,viemChain:v?.viemChain});e.ui.setStatusMsg("Funding embedded wallet..."),await j(h);let N=h;if(e.feeExecutionMode==="user-transfer")for(let S=0;S<4;S+=1){const A=await e.execution.estimate(d,e.executionTokenAddress,0n,u),I=qn(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}),Js(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:S,chainBatches:A})=>{const I=qn(S,e,a);if(!I)return null;const E=wr(T,I),W=Js(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 O=l?I.grossAmount:ln(I.grossAmount,g?.decimals??e.destinationToken.decimals,s.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:O,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:p,actionContextOverride:I})}}:u)}async function $s(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,s=e.activeSignerAddress??e.externalWalletAddress;if(!s||!n)throw new Error("Please connect your wallet to continue");const r=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=await e.execution.estimateRequiredGrossFunding(a,k=>e.execution.buildPayChainBatches({fundingAmountOverride:k}),l,d),c=F.getEscrowContractAddress(s),f=await e.externalWallet.getEthereumProvider();await Wn(f,s);const p=m.getChainConfig(s),x=B.createWalletClient({account:e.externalWalletAddress,chain:p?.viemChain,transport:B.custom(f)}),g=F.normalizeNativeTokenAddress(n.address),h=n.isNative||F.isNativeToken(g)?await x.sendTransaction({to:c,value:u,chain:p?.viemChain}):await x.sendTransaction({to:g,data:B.encodeFunctionData({abi:B.erc20Abi,functionName:"transfer",args:[c,u]}),chain:p?.viemChain});if((await m.getClientForChain(s).waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const y=await e.execution.buildPayChainBatches({fundingAmountOverride:u}),C=y.some(k=>k.tokenTransfers?.length);return await e.execution.execute(y,l,u,k=>{k.txHash&&(e.ui.setPaymentResult(v=>({...v??{status:"processing"},txHash:k.txHash})),e.ui.setTxHash(k.txHash))},void 0,C?d:{userOverride:t})}async function Ir(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let s;if(e.isSourceDestToken||e.parsedAmount===0)s=await $s(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,a=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,v=>{v.txHash&&(e.ui.setPaymentResult(M=>({...M,txHash:v.txHash})),e.ui.setTxHash(v.txHash))},void 0,s);e.ui.setPaymentResult(v=>({status:"success",txHash:v?.txHash||k}));return}const r=e.selectedAsset?.asset;if(!r)throw new Error("Select a payment source");const a=e.resolvedTokenIn||r.address||e.destinationToken.address,l=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,d=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,u=(C,k,v)=>{const M=Vn(C),b=j=>(j.tokenTransfers??[]).some(N=>N.from==="escrow"),w=M.filter(j=>!b(j)),R=M.filter(b);return[...w,...tn(R,d,k,v)]},c=await e.execution.estimateRequiredGrossFunding(l,C=>e.execution.buildPayChainBatches({fundingAmountOverride:C}).then(k=>u(k)),a,s);let f=c,p=u(await e.execution.buildPayChainBatches({fundingAmountOverride:c}));const x=await e.execution.estimate(p,a,c,s),g=Cn(x,{chainId:e.resolvedChainId,tokenAddress:a,symbol:F.getTokenByAddress(a,e.resolvedChainId)?.symbol??r.symbol,decimals:F.getTokenByAddress(a,e.resolvedChainId)?.decimals??r.decimals})?.grossAmount??c;g!==c&&(f=g),p=u(await e.execution.buildPayChainBatches({fundingAmountOverride:f}),x,{payoutAlreadyGross:!0});const 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 Ll=({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:v=!1,maxAmount:M,onAmountChange:b})=>e==="supply"?o.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${c}`,borderRadius:p?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[o.jsxs("div",{style:{minWidth:0},children:[o.jsx("span",{style:{fontFamily:a,fontSize:"17px",fontWeight:500,color:p?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),o.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,fontFamily:a,marginTop:"10px"},children:"Net amount after swap and fees"})]}),o.jsxs("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${c}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[o.jsx(Er,{symbol:t,logoURI:n,primaryColor:r,size:24}),o.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:p?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),o.jsx("div",{style:{textAlign:"right",minWidth:0},children:x?o.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:a},children:"Quoting..."}):g?o.jsx("span",{style:{fontSize:"13px",color:p?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):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(Hl,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:k,isQuoting:x,adjustable:v,maxAmount:M,onAmountChange:b}),Ar=i.memo(Ll),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)}),Hl=({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 v='"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),[S,A]=i.useState(null);i.useEffect(()=>{y||R(p||"")},[p,y]);const I=O=>{let z=O;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=O=>{if(!b)return;if(O===100){R(C||b.toString()),j.current&&clearTimeout(j.current),k?.(C||b.toString());return}const z=10**n,P=Math.floor(b*O/100*z)/z,D=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:O=>I(O.target.value),placeholder:"0.0",fontFamily:v,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):o.jsx(In,{element:"div",value:M>0?p:"0.00",title:M>0?p:"0.00",fontFamily:v,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),o.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:v,marginTop:"2px"},children:e}),y&&b>0&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((O,z)=>{const P=Math.abs(W-O)<1,D=z===4,Q=O/100,L=N===O,te=S===O;return o.jsx("button",{onClick:()=>E(O),onMouseEnter:()=>T(O),onMouseLeave:()=>{T(null),A(null)},onMouseDown:()=>A(O),onMouseUp:()=>A(null),title:`${O}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:P?1:L?.8:.5,transform:te?"scale(0.85)":L?"scale(1.15)":"scale(1)",transition:_t.interactive},children:o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[o.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:D?s:"none",stroke:D?s:f?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!D&&Q>0&&o.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${Q>.5?1:0} 1 ${7+6.84375*Math.sin(Q*2*Math.PI)} ${7-6.84375*Math.cos(Q*2*Math.PI)} Z`,fill:f?c?.textSecondary||"#9ca3af":"#3C3E42"})]})},O)})})]})]}),x&&g&&!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,S=[],A=I=>{if(!I)return;const E=I.toLowerCase();T.has(E)||(T.add(E),S.push(B.getAddress(I)))};if(A(t.address),n)for(const I of n)A(I);return S},[l,t.address,n]),k=i.useMemo(()=>C.map(T=>T.toLowerCase()).sort().join(","),[C]),v=i.useMemo(()=>JSON.stringify([...s||[]].sort()),[s]),[M,b]=i.useState([]),w=i.useRef(0),R=i.useRef(async()=>{}),j=i.useCallback(async()=>{if(!r||!y||C.length===0){w.current++,b([]);return}const T=++w.current,S=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(L=>m.addressesEqual(L.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 L=m.getChainConfig(Q)?.supportedTokens?.find(te=>m.addressesEqual(te.address,P));if(L){I.push({address:z,chainId:Q,configToken:{decimals:L.decimals,symbol:L.symbol,name:L.name,logo:L.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 on.readContract(z,{address:P.address,abi:B.erc20Abi,functionName:"balanceOf",args:[S]}),{decimals:Q,symbol:L,name:te,logoURI:U}=await tr(z,P.address,P.configToken);return Tr(P,{decimals:Q,symbol:L,name:te,logoURI:U,balance:D},t)}catch{return null}},O=await Promise.all(Array.from(E.entries()).map(async([z,P])=>{let D;try{D=m.getClientForChain(z)}catch{return[]}const Q=[],L=[];for(const U of P){const G=Q.length;Q.push({address:U.address,abi:B.erc20Abi,functionName:"balanceOf",args:[S]}),U.configToken||Q.push({address:U.address,abi:B.erc20Abi,functionName:"decimals"},{address:U.address,abi:B.erc20Abi,functionName:"symbol"},{address:U.address,abi:B.erc20Abi,functionName:"name"}),L.push({start:G,item:U})}let te=null;try{te=await D.multicall({contracts:Q})}catch{te=null}return te?L.map(({start:U,item:G})=>{const ue=te[U],q=ue?.status==="success"?ue.result:0n;let J,le,be,ie;if(G.configToken)J=G.configToken.decimals,le=G.configToken.symbol,be=G.configToken.name,ie=G.configToken.logo;else{const pe=te[U+1],ce=te[U+2],ke=te[U+3];J=pe?.status==="success"?Number(pe.result):18,le=ce?.status==="success"?ce.result:"TOKEN",be=ke?.status==="success"?ke.result:le}return Tr(G,{decimals:J,symbol:le,name:be,logoURI:ie,balance:q},t)}):(await Promise.all(P.map(U=>W(D,U)))).filter(U=>U!==null)}));T===w.current&&b(O.flat())},[r,l,y,k,v,t.address,t.chainId,t.symbol,t.logoURI]);i.useEffect(()=>{R.current=j},[j]),i.useEffect(()=>{if(!r){b([]);return}R.current();const T=setInterval(()=>{R.current()},15e3);return()=>clearInterval(T)},[r,l,y,k,v,t.address,t.chainId]);const N=i.useCallback(()=>{j()},[j]);return{displayAssets:i.useMemo(()=>{const T=[],S=M.filter(I=>I.balance>0n);for(const I of S)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 Ql=[{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 Vl(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:Ql,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 ql(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>Vl({...e,fee:r})));let s=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!s||a.value.amountIn<s.amountIn)&&(s={...a.value,fee:t[r]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}function Nr(e){return e.type==="swap"}const _s=.02,Yl=[1,8453,42161,10,137,43114,56],Kl="https://api.1inch.dev/swap/v6.0";function Dr(e,t){return F.applySlippage(e,t)}function Wr(e){const t=e?.baseUrl??Kl;return{name:"1inch",chainIds:e?.chainIds??Yl,resolve:async(n,s,r)=>{const a=n.maxSlippage??_s,l=a*100,d=F.isNativeToken(n.tokenIn)?F.NATIVE_TOKEN_ADDRESS:n.tokenIn,u=F.isNativeToken(n.tokenOut)?F.NATIVE_TOKEN_ADDRESS:n.tokenOut,c=F.isNativeToken(n.tokenIn);try{const f=new URL(`${t}/${s}/swap`);f.searchParams.set("src",d),f.searchParams.set("dst",u),f.searchParams.set("amount",n.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",l.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const x=await fetch(f.toString(),{headers:p});if(!x.ok)throw new 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],eo={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Ur={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Or(e){return{name:"satsuma",chainIds:e.chainIds??Pr,resolve:async(t,n,s)=>{const r=t.maxSlippage??_s,a=F.isNativeToken(t.tokenIn);let l;try{l=await Mr({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const d=Dr(l.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data: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??_s,a=F.isNativeToken(t.tokenIn);let l;try{l=await ql({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:Zl,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 Zl=[{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(u=>u.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(u=>u.resolve(s,r,a)))).filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u!==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()});return d.sort((u,c)=>u.amountIn<c.amountIn?-1:u.amountIn>c.amountIn?1:0),d[0]}return{getQuote:n,venues:t}}const Qr=Lr({satsuma:eo});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),[v,M]=i.useState(null),[b,w]=i.useState(null),[R,j]=i.useState(null),[N,T]=i.useState(null),S=i.useRef(null),A=i.useRef(null),I=i.useRef(0),E=i.useRef(new Map),W=i.useMemo(()=>Qr,[]),O=i.useMemo(()=>Hr({customVenues:[...d?[{name:"consumer-exact-output",chainIds:[r],resolve:d}]:[],zr(eo),zr(Ur)]}),[d,r]),z=i.useMemo(()=>{if(!n?.asset)return null;const J=an(n.asset,r);if(J)return J;const le=mn(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 wo(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]),L=i.useMemo(()=>!n?.asset||!Q?[]:[Q,...P.filter(J=>J.toLowerCase()!==Q.toLowerCase())],[n?.asset,Q,P]),te=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]),U=Q?m.addressesEqual(Q,s.address):!1,G=t==="output"&&parseFloat(l||"0")===0,ue=!!n?.asset&&!te&&!U&&!G,q=ue?R??Q:Q;return i.useEffect(()=>{S.current&&clearTimeout(S.current);const J=t==="input"?n?.amount:l,le=parseFloat(J||"0");if(!ue||!Number.isFinite(le)||le<=0||!n?.asset||!a||L.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 pe=++I.current,ce=()=>pe!==I.current;c(!0);const ke=t==="output"?150:400;return S.current=setTimeout(async()=>{try{if(t==="input"){const _=W.getVenueForChain(r);if(!_)throw new Error("No swap venue for this chain");let Y=null,ee=null;for(const ge of L){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,ee=ge;break}const me=await _.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,ee=ge;break}}if(!Y||!ee)throw new Error("No liquidity for this pair");j(ee),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 _=null,Y=null;for(const ee of L){const re=`${t}:${r}:${ee.toLowerCase()}:${s.address.toLowerCase()}:${ie.toString()}`,ge=E.current.get(re);if(ge&&ge.expiresAt>Date.now()&&ge.exactOutputSwap){_=ge.exactOutputSwap,Y=ee;break}try{const K=await O.getQuote({tokenIn:ee,tokenOut:s.address,amountOut:ie},r,a);if(ce())return;E.current.set(re,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:K}),_=K,Y=ee;break}catch{if(ce())return}}if(!_||!Y)throw new Error("No liquidity for this pair");j(Y),M(_),k(null),w(null),y(parseFloat(B.formatUnits(_.amountIn,be)).toFixed(6)),g(null),p(null)}}catch(_){if(ce())return;const Y=_ instanceof Error?_.message:"Failed to get quote";p(Y),g(null),y(null),k(null),M(null),w(null),j(null)}finally{ce()||c(!1)}},ke),()=>{S.current&&clearTimeout(S.current)}},[t,ue,n?.amount,n?.asset?.address,n?.asset?.decimals,l,L,r,s.address,s.decimals,a,W,O]),{isQuoting:u,quoteError:f,estimatedOutput:x,estimatedInput:h,resolvedSwap:C,exactOutputSwap:v,quoteAmountOut:b,resolvedTokenIn:q,isDirect:U,needsSwap:ue,selectedIsEquivalent:te}}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"],Gl=()=>{},Jl=({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:v,onAmountChange:M,styles:b,dark:w,title:R,subtitle:j,onAddFunds:N,onSuccess:T,onError:S})=>{const A=x==="output",{theme:I,dark:E,primaryColor:W,dk:O,palette:z,fontFamily:P,monoFont:D,inputDark:Q,cardBg:L,cardBorder:te,textPrimary:U,textSecondary:G,subtitleText:ue}=m.useSpiceBrand(b,w),q=i.useMemo(()=>Q?{...I,colors:{...I.colors,secondary:O.cardBg,surfaceHover:O.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:I,[Q,I,O.cardBg,O.hoverBg]),J=s.chainId,le=i.useContext(m.SpiceFlowProviderContext),be=le?.mode||"7702",ie=be!=="7702",pe=!!le?.isWhitelistGateActive,ce=!!le?.isWhitelistConfigured&&le?.isUserWhitelisted!==!0,ke=i.useMemo(()=>r??le?.supportedChainIds??[],[r,le?.supportedChainIds]),_=i.useMemo(()=>{if(pe)return[];if(a)return a;const he=le?.allowedTokens;if(!he||he.length===0)return;const $e=new Set(he.map(gn=>gn.toLowerCase())),dn=[],hn=new Set;for(const gn of ke){const hs=m.getChainConfig(gn);for(const gs of hs?.supportedTokens??[]){if(!$e.has(gs.symbol.toLowerCase()))continue;const to=gs.address.toLowerCase();hn.has(to)||(hn.add(to),dn.push(gs.address))}}return dn},[a,le?.allowedTokens,ke,pe]),Y=m.useWallet(),{address:ee,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,fe=le?.embeddedWalletAddress||it,{displayAssets:At,filteredSpiceAssets:Te,embeddedWalletAddress:De,refreshSpiceAssets:_e,refreshWalletAssets:wt}=Br({destinationToken:s,supportedSourceAssets:_,sourceChains:ke,enabled:e&&(ie?!!lt:!!fe)}),Ze=pe||A||ie?At:Te;i.useEffect(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:be,walletAddressUsed:De,count:Ze.length,assets:Ze.map(he=>({symbol:he.symbol,address:he.address,chainId:he.chainId,balanceFormatted:he.balanceFormatted,source:he?._source}))})},[e,be,De,Ze]);const[H,He]=i.useState(null),[Ie,Qe]=i.useState(y||""),[Oe,Rt]=i.useState(!1),[Nt,zt]=i.useState(null),[ve,Dt]=i.useState("idle"),[Xe,nn]=i.useState(""),[Zt,Ve]=i.useState(null),[Lt,Et]=i.useState(!1),[Pe,ye]=i.useState(null),[Ue,Ke]=i.useState(null),[Xt,we]=i.useState(!1),[Mt,yt]=i.useState(!1),[pt,qe]=i.useState(null),sn=i.useRef(H),jt=i.useRef(!1),Ht=i.useRef(null),Gt=i.useRef(null),Ft=i.useRef(0),gt=i.useRef(null),ct=i.useRef(null);i.useEffect(()=>{sn.current=H},[H]);const Re=C==="adjustable"?Ie:y||"0",et=De||it||ee,{isQuoting:ft,quoteError:Qt,estimatedOutput:Wt,resolvedSwap:mt,exactOutputSwap:Se,quoteAmountOut:Ct,resolvedTokenIn:ot,isDirect:bt,needsSwap:tt,selectedIsEquivalent:Ae}=Vr({direction:x,selectedAsset:H,destinationToken:s,chainId:J,recipient:et,paymentAmount:Re,resolveExactOutputSwap:f}),nt=A?parseFloat(Re||"0"):parseFloat(H?.amount||"")||0,Pt=nt>0&&nt<fn,$=H?.asset?._source==="wallet",se=!!H?.asset&&$&&H.asset.chainId!==J,Ce=i.useMemo(()=>H?.asset?Te.find(he=>m.addressesEqual(he.address,H.asset.address))?.balanceFormatted??0:0,[H,Te]),Me=$?H?.asset.balanceFormatted??0:Ce,Ye=i.useMemo(()=>{if(!H?.asset)return!1;if(A)return Ue?ln(Ue.grossAmount,Ue.decimals,H.asset.decimals)>H.asset.balance:Ae||bt?nt>H.asset.balanceFormatted:Se?parseFloat(B.formatUnits(Se.amountInMax,H.asset.decimals))>H.asset.balanceFormatted:!1;if(Ue){const he=ln(Ue.grossAmount,Ue.decimals,H.asset.decimals);return $?he>H.asset.balance:parseFloat(B.formatUnits(he,H.asset.decimals))>Me}return nt>Me},[H,A,Ue,Ae,nt,Se,Me,$,bt]);i.useEffect(()=>{e||(He(null),zt(null),Rt(!1),Dt("idle"),nn(""),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=>{He($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=>{He($e=>$e&&{...$e,amount:he}),zt(null),qe(null),yt(!1)},[]),at=i.useCallback(he=>{let $e=he;v&&parseFloat($e)>parseFloat(v)&&($e=v),Qe($e),M?.($e),zt(null),qe(null),yt(!1)},[v,M]);i.useCallback(he=>{if(jt.current||!ee)return;const $e=sn.current;!$e?.asset||!$e.amount||$e.asset?._source==="wallet"||B.parseUnits(A?Re:$e.amount,$e.asset.decimals)===0n||(jt.current=!0,_e())},[ee,J,_e,A,Re]);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"),nn(he.message),he.txHash&&Ve(he.txHash)},[]),xt=i.useMemo(()=>({currentPaymentAmount:Re,destinationToken:s,embeddedWalletAddress:De,providerEmbeddedAddress:it,externalWalletAddress:lt,address:ee,isNon7702:ie,isPayMode:A,resolvedChainId:J,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:H,needsSwap:tt,resolvedSwap:mt,exactOutputSwap:Se,quoteAmountOut:Ct,resolvedTokenIn:ot}),[Re,s,De,it,lt,ee,ie,A,J,l,d,u,H,tt,mt,Se,Ct,ot]),Ne=i.useCallback(he=>mr({...xt,requestTimestampMs:Gt.current??Date.now()},he),[xt]),Z=i.useCallback(he=>hr({...xt,requestTimestampMs:Gt.current??Date.now()},he),[xt]),xe=i.useCallback((he,$e,dn,hn)=>gr(he,$e,dn,oe,hn),[oe]),ut=i.useMemo(()=>H?.asset?tt&&ot?ot:H.asset.chainId===J?H.asset.address:ot??an(H.asset,J)??s.address:s.address,[H,s.address,tt,J,ot]),ht=i.useCallback(()=>(Gt.current=Date.now(),kr(ct.current)),[]),ze=i.useMemo(()=>H?.asset?m.addressesEqual(H.asset.address,s.address)&&H.asset.chainId===s.chainId:!1,[H,s.address,s.chainId]),kt=ze&&(ie||A),Ge=kt&&nt>0&&!!H?.asset,Vt=ce&&!kt,V=i.useMemo(()=>{if(!Ge)return null;let he;try{he=B.parseUnits(Re||"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"}},[Ge,Re,s.symbol,s.decimals]),X=Nt,de=i.useMemo(()=>!(!H?.asset||nt<=0),[H,nt,Ge]),ae=i.useMemo(()=>!e||Oe||ve!=="idle"||!de||Ge||!H?.asset?null:[A?"pay":"supply",x,H.asset.address.toLowerCase(),H.asset.chainId,H.amount,Re,s.address.toLowerCase(),s.chainId,J,ot?.toLowerCase()??"",tt?"swap":"direct",bt?"direct-token":"routed-token",ie?"non7702":"7702",ze?"source-dest":"cross-chain",ft?"quoting":"quoted",Se?.amountIn?.toString()??"",Se?.amountInMax?.toString()??"",Se?.venue??"",mt?.amountOut?.toString()??"",Ct?.toString()??"",De??"",it??"",ee??""].join("|"),[e,Oe,ve,de,Ge,H,A,x,Re,s,J,ot,tt,bt,ie,ze,ft,Se,mt,Ct,De,it,ee]),We=i.useCallback(()=>yr({selectedAsset:H,isPayMode:A,parsedAmount:nt,needsSwap:tt,exactOutputSwap:Se,isNon7702:ie,isSourceDestToken:ze,currentPaymentAmount:Re,destinationToken:s,feeExecutionMode:d,resolvedTokenIn:ot,embeddedWalletAddress:De,providerEmbeddedAddress:it,resolvedChainId:J,isConnected:re,address:ee,ready:ge,authenticated:K,isDirect:bt,resolvedSwap:mt,isQuoting:ft,executionTokenAddress:ut,buildPayChainBatches:Ne,buildSupplyChainBatches:Z,estimate:oe,estimateRequiredGrossFunding:xe}),[H,A,nt,tt,Se,ie,ze,Re,s,d,ot,De,it,xe,Ne,oe,J,re,ee,ge,K,bt,mt,ft,Z,ut]);i.useEffect(()=>{gt.current=We},[We]);const je=i.useCallback(he=>xr({asset:he,isPayMode:A,isNon7702:ie,needsSwap:tt,isQuoting:ft,embeddedWalletAddress:De,buildSupplyChainBatches:Z,estimate:oe,executionTokenAddress:ut,feeExecutionMode:d}),[A,ie,tt,ft,De,Z,oe,ut,d]);i.useEffect(()=>{if(!e){we(!1),yt(!1),qe(null),Ke(null);return}if(Oe||ve!=="idle"){Ft.current+=1,we(!1);return}if(!de){Ke(null),we(!1),yt(!1),qe(null);return}if(Ge){Ke(V),we(!1),yt(!0),qe(null);return}if(ft){Ft.current+=1,we(!1),yt(!1);return}if(!ae)return;let he=!1;const $e=async()=>{const hn=++Ft.current;qe(null),we(!0);try{const gn=await gt.current?.();if(he||Ft.current!==hn)return;gn?(Ke(gn),yt(!0)):(Ke(null),yt(!1)),qe(null)}catch(gn){if(he||Ft.current!==hn)return;const hs=m.sanitizeError(gn,"Unable to calculate fees for this action.");Ke(null),yt(!1),qe(hs)}finally{!he&&Ft.current===hn&&we(!1)}},dn=window.setTimeout(()=>{$e()},250);return()=>{he=!0,clearTimeout(dn),we(!1)}},[e,Oe,ve,de,Ge,V,ft,ae]);const Le=i.useCallback(()=>(Gt.current=Date.now(),Ir(ct.current)),[]);i.useEffect(()=>{!A&&ve==="success"&&Zt&&(_e(),T?.(Zt))},[A,ve,Zt,_e,T]),i.useEffect(()=>{if(!A||Pe?.status!=="success"||jt.current||!ee)return;jt.current=!0;const he=sn.current;!he?.asset||he.asset?._source==="wallet"||_e()},[A,Pe?.status,ee,_e]);const st=i.useRef(T),vt=i.useRef(S);i.useEffect(()=>{st.current=T},[T]),i.useEffect(()=>{vt.current=S},[S]),i.useEffect(()=>{e&&(_e(),wt())},[e,_e,wt]),i.useEffect(()=>{A&&(Pe?.status==="success"&&st.current?.(Pe.txHash||""),Pe?.status==="failed"&&vt.current?.(new Error("Payment execution failed")))},[A,Pe?.status]);const Ut=i.useCallback(()=>{Et(!1),ye(null),He(null),jt.current=!1,_e(),wt()},[_e,wt]);ct.current={selectedAsset:H,parsedAmount:nt,currentPaymentAmount:Re,isInsufficientBalance:Ye,isPayMode:A,isNon7702:ie,isSourceDestToken:ze,needsSwap:tt,exactOutputSwap:Se,selectedIsEquivalent:Ae,resolvedTokenIn:ot,embeddedWalletAddress:De,providerEmbeddedAddress:it,externalWallet:Be,externalWalletAddress:lt,activeSignerWallet:St,activeSignerAddress:It,address:ee,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:S,execution:{estimate:oe,execute:me,buildPayChainBatches:Ne,buildSupplyChainBatches:Z,estimateRequiredGrossFunding:xe,onProgress:Ee},ui:{setError:zt,setStep:Dt,setStatusMsg:nn,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||!!H?.asset)&&nt>=0&&!Pt&&!Ye&&!Oe&&(Tt||Ge||Mt)&&!pt&&(Tt||!tt||!!Se)&&!Vt:!!H?.asset&&nt>0&&!Pt&&!Ye&&!Oe&&(kt||Mt)&&!pt&&(se||bt||!!mt&&!ft)&&!Vt;i.useEffect(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:$t,isPayMode:A,hasSelectedAsset:!!H?.asset,selectedAsset:H?.asset?{symbol:H.asset.symbol,address:H.asset.address,chainId:H.asset.chainId,balanceFormatted:H.asset.balanceFormatted,source:H.asset?._source}:null,parsedAmount:nt,isZeroAmountPay:Tt,isBelowMinimum:Pt,isInsufficientBalance:Ye,isExecuting:Oe,directExternalAction:kt,directExecutionFeeNote:Ge,feeEstimateReady:Mt,feeEstimateError:pt,needsSwap:tt,isDirect:bt,isSourceDestToken:ze,hasExactOutputSwap:!!Se,isQuoting:ft,whitelistHoldPending:ce,supplyHeldForWhitelist:Vt,isWhitelistGateActive:pe,destinationToken:{symbol:s.symbol,address:s.address,chainId:s.chainId}})},[e,$t,A,H,nt,Tt,Pt,Ye,Oe,kt,Ge,Mt,pt,tt,bt,ze,Se,ft,ce,Vt,pe,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=Oe?(qr[ve]||"EXECUTING...").toUpperCase():ve==="success"?"DONE":Pt?`MINIMUM ${fn}`:Ye?"INSUFFICIENT BALANCE":p.toUpperCase(),Je=i.useMemo(()=>{if(Oe)return"PAYING...";if(Pt)return`MINIMUM ${fn}`;if(Ye&&H?.asset)return`INSUFFICIENT ${H.asset.symbol}`;if(p)return p.toUpperCase();const he=nt>0?` ${Re} ${s.symbol}`:"";return tt?`SWAP & PAY${he}`:`PAY${he}`},[Oe,Pt,Ye,H,p,nt,Re,s.symbol,tt]),Ot=ve==="success"?()=>{Dt("idle"),He(null),Ve(null),_e()}:ht,cn=ve==="success"?!1:!$t;if(!e)return null;const Kn=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:ue})}),o.jsx("p",{style:{fontSize:"12px",color:ue,margin:0,lineHeight:"1.4",fontFamily:P},children:kn})]});if(A){const he=Pe&&(Pe.status==="success"||Pe.status==="failed")?[{asset:{symbol:H?.asset?.symbol||s.symbol,address:H?.asset?.address||""},amount:Re,txHash:Pe.txHash||"",success:Pe.status==="success",error:Pe.status==="failed"?Pe.error:void 0}]:void 0;return o.jsx(un,{isOpen:e,onClose:t,title:Kn,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:H??void 0,onAssetSelect:rt,onAmountChange:Gl,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:H?.asset?tt?ft?"...":Se?`~${parseFloat(B.formatUnits(Se.amountIn,H.asset.decimals)).toFixed(6)}`:void 0:Re??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:U,textSecondary:G,cardBg:L,cardBorder:te,dk:O,dark:E,isQuoting:ft,quoteError:Qt,estimatedOutput:Wt,paymentAmount:Re,needsSwap:tt,exactOutputSwap:Se,adjustable:C==="adjustable",maxAmount:v,onAmountChange:at}),de&&o.jsx(is,{fontFamily:P,textPrimary:U,textSecondary:G,cardBg:L,cardBorder:te,resolvedDark:E,darkCardBorder:O.cardBorder,primaryColor:W,feePreview:Ue,isLoading:Xt,errorText:pt,directExecutionFeeNote:Ge}),X&&o.jsx(Nn,{variant:"error",palette:z,fontFamily:P,style:{marginBottom:"12px"},children:X}),o.jsx(m.Button,{variant:"outline",fullWidth:!0,onClick:Le,disabled:!$t,loading:Oe,dark:E,styles:{...b,button:{...b?.button,backgroundColor:W}},children:Je}),Pe&&Lt&&o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:E?O.shell:"white",borderRadius:E?"12px":"6px",padding:"16px 0"},children:o.jsx(Ls,{type:"payment",isOpen:Pe.status!=="processing",isProcessing:Oe||Pe.status==="processing",closeOnComplete:!1,chainName:m.getChainName(J),explorerUrl:m.getExplorerUrl(J,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Et(!1),ye(null),Le()},onNewTx:Ut,onClose:()=>{Et(!1),ye(null)},onComplete:Ut,results:he,styles:b,dark:E})})]})})}return o.jsx(un,{isOpen:e,onClose:t,title:Kn,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:H||void 0,onAssetSelect:rt,onAmountChange:dt,disabled:Oe||ve==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:q,styles:b,dark:Q,resolveMaxAmount:je,maxAmount:Me>0?m.formatDecimalInput(Me,H?.asset.decimals??s.decimals):void 0})}),H?.asset&&!bt&&o.jsx(Ar,{variant:"supply",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:W,fontFamily:P,textPrimary:U,textSecondary:G,cardBg:L,cardBorder:te,dark:E,isQuoting:ft,quoteError:Qt,estimatedOutput:Wt}),de&&o.jsx(is,{fontFamily:P,textPrimary:U,textSecondary:G,cardBg:L,cardBorder:te,resolvedDark:E,darkCardBorder:O.cardBorder,primaryColor:W,feePreview:Ue,isLoading:Xt,errorText:pt,directExecutionFeeNote:Ge}),ve!=="idle"&&o.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:ve==="success"?L:ve==="error"?z.errorBg:L,border:`1px solid ${ve==="success"?te:ve==="error"?z.errorBorder:te}`},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"?U:ve==="error"?z.errorText:U,fontFamily:P,flex:1},children:ve==="success"?"Deposit confirmed":ve==="error"?Xe||"Transaction failed":qr[ve]||Xe}),ve==="success"&&Zt&&o.jsx("a",{href:`${jn}/tx/${Zt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:W,fontFamily:P,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),ve==="error"&&o.jsx("button",{onClick:()=>{Dt("idle"),zt(null),setTimeout(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:`${G}22`,overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:W,transformOrigin:"left center",transform:`scaleX(${(vn+1)/Yr.length})`,transition:"transform 400ms ease"}})})]}),Nt&&ve==="idle"&&o.jsx(Nn,{variant:"error",palette:z,fontFamily:P,style:{marginBottom:"16px"},children:Nt}),o.jsx(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 _l(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 ec(){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 Yn(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 tc(e,t){if(e[0].toUpperCase()===t[0].toUpperCase()&&e[1]===t[1])return!0;let n,s;try{n=Yn(e),s=Yn(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 nc(){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 sc(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??nc();if(!u.some(C=>tc(n,C))){const C=u.map(([k,v])=>`${k} (chain ${v})`).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=Yn(n),f=Yn(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 _o({route:p,sourceAmount:s,userAddress:a,registry:r,actionCalls:t.calls,slippage:l});return{chainBatches:x,route:p,resolvedSwaps:y,resolvedInputToken:c,resolvedOutputToken:f,solverFrontToken:g,solverFrontAmount:h}}const oc=[0n,1n,30n],rc=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 ac(e,t){const{chainId:n,swapCalls:s,quoteAmountOut:r,buildActionCalls:a,tokenAddress:l,tokenTransferAmount:d,onProgress:u,signal:c,options:f,buffers:p=oc}=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 v=typeof k?.message=="string"?k.message:String(k?.message??"");if(m.isSpiceflowError(k)&&rc.has(k.code)||k.name==="AbortError"||c?.aborted||v.includes("User rejected")||v.includes("User denied")||k.code===4001||x>=p.length-1)throw k;const M=Number(p[x+1])/10;console.warn(`[SwapThenAction] Action attempt ${x+1} failed (buffer ${Number(g)/10}%), retrying with ${M}% buffer...`,k.message),u?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${M}% buffer)...`})}}throw new 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=Pl,exports.AddFundsLink=Ws,exports.CheckIcon=Do,exports.ChevronIcon=bn,exports.CloseIcon=Tn,exports.DetailRow=Dn,exports.ProviderLogin=zs,exports.SATSUMA_CITREA_CONFIG=eo,exports.SearchInput=bs,exports.SelectChainModal=Ui,exports.SpiceDeposit=Pi,exports.SpiceLock=ar,exports.SpiceLockModal=ar,exports.SpiceSupply=Jl,exports.SpiceWithdraw=el,exports.StatusBanner=Nn,exports.UNIV3_BASE_CONFIG=Ur,exports.applyBuffer=Kr,exports.areEquivalentOnChains=Hn,exports.buildIntent=sc,exports.buildPayChainBatches=mr,exports.buildRoutedBatches=_o,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=ac,exports.findEquivalentOnChain=mn,exports.findTokenOnChain=Vs,exports.font=oo,exports.getAssetChainTokenCandidates=Gn,exports.getBestUniV3Quote=Mr,exports.getUniV3Quote=Rr,exports.isSupportedSupplyAsset=Fr,exports.isSwapIntent=Nr,exports.radius=Cs,exports.resolveAssetTokenAddressOnChain=an,exports.resolveFundedToken=wo,exports.resolveInputSupplySwapQuote=Xl,exports.resolveRoute=$o,exports.resolveTokenRef=Yn,exports.scaleTokenAmount=ln,exports.transition=_t,exports.useAssetInput=$l,exports.useLockDuration=_l,exports.useSmartWallet=ec,exports.useSpiceAssets=Qn,exports.useSpiceExecution=Mn,exports.useSpicePendingDeposits=ir,exports.useSupplyAssets=Br,exports.useSupplyQuote=Vr,exports.z=Sn;
|
package/dist/index.js
CHANGED
|
@@ -105,4 +105,4 @@ import{jsxs as x,jsx as l,Fragment as vn}from"react/jsx-runtime";import Rn,{useS
|
|
|
105
105
|
from { opacity: 0; transform: translateY(-4px); }
|
|
106
106
|
to { opacity: 1; transform: translateY(0); }
|
|
107
107
|
}
|
|
108
|
-
`})]}),document.body):null;return x(vn,{children:[Ut,nt,E&&mr.createPortal(l(Jr,{isOpen:!0,onClose:V,supportedChains:[E.chainId],escrowOnly:!0,escrowTokenAddress:E.tokenAddress,escrowAmount:E.amount,escrowTokenDecimals:E.tokenDecimals,escrowTokenSymbol:E.tokenSymbol,styles:d,onDepositSuccess:_}),document.body)]})},fd="0xa9059cbb";function Ca(e,t,n){return Ue(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:Tt({abi:Fe,functionName:"transfer",args:[n,t]})}}function va(e,t,n){return{chainId:n,calls:[Ca(e,t,hn(n))]}}function ka(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function Ia(e,t,n,o){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(fd)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function ls(e,t,n,o){if(!t)return[e];const s=await t({...n,requestTimestampMs:o});return s?[s,e]:[e]}function Mo(e){return e.filter(t=>t.domain!=="spicenet")}function cs(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:It(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function Wn(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return(e+o-1n)/o}async function Aa(e,t){const{currentPaymentAmount:n,destinationToken:o,embeddedWalletAddress:s,providerEmbeddedAddress:r,address:a,isNon7702:c,isPayMode:d,resolvedChainId:i,buildActionCalls:p,feeExecutionMode:u,buildSpicenetBatch:m,selectedAsset:h,needsSwap:f,exactOutputSwap:g,resolvedTokenIn:y,requestTimestampMs:C}=e,v=ze(n,o.decimals),T=t?.actionAmountOverride??v,b=s||r||(c?void 0:a);if(!b)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:b,chainId:i,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??v,netAmount:T,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},B=p(T,w),E={chainId:i,calls:B},M=!d&&!c?!0:h?.asset?._source==="spice",F=ka(h??null,c,i),k=M||c||F,A=(S,W)=>({token:S,from:c?"solver":"escrow",to:b,amount:W}),I=(S,W,P)=>F?[va(S,W,i),...P]:P;if(v===0n)return[E];if(f&&g){const S=y??Dn(h.asset,i)??h.asset.address,W=t?.fundingAmountOverride??g.amountInMax,P=k?[A(S,W)]:[],z={to:S,value:0n,data:Tt({abi:Fe,functionName:"approve",args:[g.calls[0]?.to,g.amountInMax]})},N={chainId:i,calls:[z,...g.calls,...B],tokenTransfers:[...P,...E.tokenTransfers??[]]};if(!k)return[N];const D=await ls(N,m,{userAddress:b,destinationChainId:i,deliveryToken:S,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:cs(N),sourceAsset:h.asset},C);return I(S,W,D)}if(k){const S=y??Dn(h.asset,i)??o.address,W=t?.fundingAmountOverride??v,P={...E,tokenTransfers:[A(S,W),...E.tokenTransfers??[]]},z=await ls(P,m,{userAddress:b,destinationChainId:i,deliveryToken:S,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:cs(P),sourceAsset:h.asset},C);return I(S,W,z)}return[E]}async function Sa(e,t){const{selectedAsset:n,embeddedWalletAddress:o,externalWalletAddress:s,recipient:r,resolvedChainId:a,destinationToken:c,buildActionCalls:d,feeExecutionMode:i,buildSpicenetBatch:p,isPayMode:u,isNon7702:m,needsSwap:h,resolvedSwap:f,quoteAmountOut:g,resolvedTokenIn:y,requestTimestampMs:C}=e,v=f?.amountOutMinimum??g;if(!n?.asset||!o)return[];const T=r??(m?s:o);if(!T)return[];const b=t?.fundingAmountOverride??t?.actionAmountOverride??ze(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??b,B=t?.sourceFundingAmountOverride??b,E=t?.deliveryAmountOverride??w,M=t?.withdrawalAmountOverride??E,F=t?.actionAmountOverride??b,k={userAddress:T,chainId:a,destinationToken:c.address,feeToken:i==="user-transfer"&&h&&y?y:c.address,grossAmount:w,netAmount:F,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:i,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},A=d(F,k),I=n.asset?._source==="wallet";if(!u&&m&&I&&n.asset.chainId===a){if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!f||v===null)throw new Error("Swap quote not available yet")}if(h&&f&&v){const U=d(t?.actionAmountOverride??v,{...k,netAmount:t?.actionAmountOverride??v}),{feeCall:Z,remainingCalls:fe}=Ia(U,i,h,k.feeToken);return[{chainId:a,calls:[...Z?[Z]:[],...f.calls,...fe]}]}return[{chainId:a,calls:A}]}if(!u&&!m&&I&&n.asset.chainId!==a)throw new Error("Cross-chain wallet supplies require external wallet mode");const S=!u&&!m?n.asset?._source!=="wallet":n.asset?._source==="spice",W=m&&I,P=ka(n,m,a);if(!(S||W||P))return[{chainId:a,calls:A}];const z=P?va(y??It(n.asset.address),B,a):W&&n.asset.chainId!==a?{chainId:n.asset.chainId,calls:[Ca(It(n.asset.address),B,hn(n.asset.chainId))]}:null,N=(U,Z)=>({token:U,from:W?"solver":"escrow",to:o,amount:Z}),D=(U,Z)=>W?[{token:U,from:"escrow",to:Ii,amount:Z}]:[];if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!f||v===null)throw new Error("Swap quote not available yet")}if(h&&f&&v&&y){const U=d(t?.actionAmountOverride??v,{...k,netAmount:t?.actionAmountOverride??v}),{feeCall:Z,remainingCalls:fe}=Ia(U,i,h,k.feeToken),Q={chainId:a,calls:[...Z?[Z]:[],...f.calls,...fe],tokenTransfers:[...D(y,M),N(y,E)]},G=await ls(Q,p,{userAddress:o,destinationChainId:a,deliveryToken:y,deliveryAmount:E,withdrawalAmount:M,deliveryRecipient:o,deliveryTransfers:cs(Q),sourceAsset:n.asset},C);return z?[z,...G]:G}const H=y??Dn(n.asset,a)??c.address,L={chainId:a,calls:A,tokenTransfers:[...D(H,M),N(H,E)]},ee=await ls(L,p,{userAddress:o,destinationChainId:a,deliveryToken:H,deliveryAmount:E,withdrawalAmount:M,deliveryRecipient:o,deliveryTransfers:cs(L),sourceAsset:n.asset},C);return z?[z,...ee]:ee}async function Ea(e,t,n,o,s){let r=e;for(let a=0;a<4;a++){const c=await t(r),d=await o(c,n,r,s),i=Dl(d);if(i===null||i>=e)return r;const p=r-i,u=e+p;if(u<=r)return r;r=u}return r}function hd(e,t,n,o){if(e<=0n)return 0n;const s=e-t;if(s<=0n)return 0n;const r=o+n;return r<=0n?s:s*o/r}async function Fa(e){const{asset:t,isPayMode:n,isNon7702:o,needsSwap:s,isQuoting:r,embeddedWalletAddress:a,buildSupplyChainBatches:c,estimate:d,executionTokenAddress:i,feeExecutionMode:p}=e;if(n||o||s||r||!a||t.balance<=0n)return null;const u=a,m=await c({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(m.length===0)return null;const h=m.some(T=>T.tokenTransfers?.length),f=await d(m,i,t.balance,h?{userOverride:u,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:u,feeExecutionMode:p}:{userOverride:u}),g=Jn(f,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),y=g?Wn(g.gasFee,g.decimals,t.decimals):0n,C=g?Wn(g.spicenetFee,g.decimals,t.decimals):0n,v=hd(t.balance,y,C,t.balance);return v>0n?zr(v,t.decimals):null}async function Ba(e){const{selectedAsset:t,isPayMode:n,parsedAmount:o,needsSwap:s,exactOutputSwap:r,isNon7702:a,isSourceDestToken:c,currentPaymentAmount:d,destinationToken:i,feeExecutionMode:p,resolvedTokenIn:u,embeddedWalletAddress:m,providerEmbeddedAddress:h,resolvedChainId:f,isConnected:g,address:y,ready:C,authenticated:v,isDirect:T,resolvedSwap:b,isQuoting:w,executionTokenAddress:B,buildPayChainBatches:E,buildSupplyChainBatches:M,estimate:F,estimateRequiredGrossFunding:k}=e;if(!t?.asset)return null;if(n){if(o<=0||s&&!r||c)return null;const D=ze(d,i.decimals),H=u||Dn(t.asset,f)||t.asset.address||i.address,L={chainId:f,tokenAddress:H,symbol:Qt(H,f)?.symbol??t.asset.symbol,decimals:Qt(H,f)?.decimals??t.asset.decimals};if(a){const G=m||h;if(!G)return null;const de=G,ve=s?r?.amountInMax??0n:D;if(ve===0n)return null;const ce=await k(ve,Se=>E({fundingAmountOverride:Se}).then($=>En(Mo($),de)),H,{userOverride:G,useCustomTransfers:!0}),he=En(Mo(await E({fundingAmountOverride:ce})),de),ue=await F(he,H,ce,{userOverride:G,useCustomTransfers:!0,feeExecutionMode:p});return Jn(ue,L)}if(!g||!y||!C||!v)return null;const ee=m||h||y,U=s?r?.amountInMax??0n:D;if(U===0n)return null;const Z=await k(U,G=>E({fundingAmountOverride:G}).then(de=>En(Mo(de),ee)),H,{useCustomTransfers:!0});let fe=En(Mo(await E({fundingAmountOverride:Z})),ee);const Q=await F(fe,H,Z,{useCustomTransfers:!0,feeExecutionMode:p});return Jn(Q,L)}if(o<=0||!m)return null;const A=m||h;if(!(!n&&!a&&t.asset?._source==="wallet"&&t.asset.chainId!==f)&&!T&&!b&&!w||w)return null;const I=ze(t.amount,t.asset.decimals),S=await M();if(S.length===0)return null;const W=a&&t.asset?._source==="wallet"&&t.asset.chainId===f,P={chainId:f,tokenAddress:B,symbol:Qt(B,f)?.symbol??i.symbol,decimals:Qt(B,f)?.decimals??i.decimals};if(W){const D=await vt.estimateBatchGas({user:A,outputToken:B,stepIndex:0,chainBatches:S}),H=Go(I,10n),L=H+D.gasFee;return{...P,grossAmount:I+L,netAmount:I,totalFee:L,gasFee:D.gasFee,spicenetFee:H,bridgeFee:0n,gasQuoteSource:D.gasQuoteSource}}const z=S.some(D=>D.tokenTransfers?.length),N=await F(S,B,I,z?{userOverride:A,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:A,feeExecutionMode:p}:{userOverride:A});return Jn(N,P)}const md=10n;function Ta(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const o=Dn(n,e.resolvedChainId);if(!o||!Ie(o,e.executionTokenAddress))return;const s=Qt(e.executionTokenAddress,e.resolvedChainId),r=Wn(t,s?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const a=pt(r,n.decimals),c=pt(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${a} ${n.symbol}; available ${c} ${n.symbol}.`)}function Js(e){const t=Qt(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Ro(e,t,n){const o=Jn(e,Js(t));if(!o)return;const s=Go(n,md),r=o.bridgeFee??0n,a=s+o.gasFee+r;return{grossAmount:n+a,netAmount:n,combinedFeeAmount:a,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:s,gasFee:o.gasFee,bridgeFee:r}}}function Ma(e,t,n){let o=0n,s=0n;const r=n.toLowerCase();for(const a of e)if(a.chainId===t){for(const c of a.calls??[])if(c.to.toLowerCase()===r)try{const d=Oo({abi:Fe,data:c.data});if(d.functionName!=="transfer")continue;const i=d.args[0].toLowerCase(),p=d.args[1];i===so.toLowerCase()?o+=p:i===In.toLowerCase()&&(s+=p)}catch{continue}}return{spicenetFee:o,gasFee:s}}function $s(e,t,n){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,s=Ma(e,t.resolvedChainId,o);return s.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||s.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Gn(s.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Gn(s.gasFee,n.feeBreakdown.gasFee,100n)}function Ra(e,t){return e?Gn(e.grossAmount,t.grossAmount,100n)&&Gn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Gn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Gn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function Da(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const o=await _s(e);e.ui.setTxHash(o??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const o=new AbortController;e.refs.abortControllerRef.current=o,await Wa(e,o.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(o){const s=o instanceof Error?o:new Error(String(o));if(s.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(s)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=ze(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=n;let s=await e.execution.buildSupplyChainBatches();const r=e.selectedAsset.asset?._source==="wallet",a=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!r&&!s.some(h=>Ao(h.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const c=s.some(h=>h.tokenTransfers?.length)?{userOverride:a,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:a,feeExecutionMode:e.feeExecutionMode}:{userOverride:a};let d=n;const i=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!i?o:void 0;let u;for(let h=0;h<4;h+=1){const f=await e.execution.estimate(s,e.executionTokenAddress,d,c),g=Jn(f,Js(e));u=e.feeExecutionMode==="user-transfer"&&g?Ro(f,e,o):void 0;const y=u?.grossAmount??g?.grossAmount??d;if(y===d){d=y;break}d=y,s=await e.execution.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u})}e.feeExecutionMode==="user-transfer"&&(Ta(e,d),s=await e.execution.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u}));let m=u;await e.execution.execute(s,e.executionTokenAddress,d,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:h,chainBatches:f})=>{const g=Ro(h,e,o);if(!g)return null;const y=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;Ma(f,e.resolvedChainId,y);const C=Ra(m,g),v=$s(f,e,g);return C||v?null:(m=g,e.execution.buildSupplyChainBatches({fundingAmountOverride:g.grossAmount,actionAmountOverride:p,actionContextOverride:g}))}}:c),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const o=n instanceof Error?n:new Error(String(n));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const s=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(s),e.ui.setError(s),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function Wa(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const o=e.selectedAsset.asset,s=ze(e.selectedAsset.amount,o.decimals),r=s,a=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let c=await e.execution.buildSupplyChainBatches();const d={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let i=s;const p=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,u=e.feeExecutionMode==="user-transfer"&&!p?r:void 0;let m;if(a){const k=await vt.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:c}),A=Go(s,10n),I=A+k.gasFee;i=s+I,e.feeExecutionMode==="user-transfer"&&(m={grossAmount:i,netAmount:r,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:A,gasFee:k.gasFee,bridgeFee:0n}})}else for(let k=0;k<4;k+=1){const A=await e.execution.estimate(c,e.executionTokenAddress,0n,d),I=e.feeExecutionMode==="user-transfer"?Ro(A,e,r):void 0,S=Jn(A,Js(e)),W=I?.grossAmount??(S?S.grossAmount>s?S.grossAmount:s:i);if(m=I,W===i){i=W;break}i=W;const P=Qt(e.executionTokenAddress,e.resolvedChainId),z=Wn(i,P?.decimals??e.destinationToken.decimals,o.decimals);c=await e.execution.buildSupplyChainBatches({fundingAmountOverride:i,sourceFundingAmountOverride:z,withdrawalAmountOverride:i,actionAmountOverride:u,actionContextOverride:I})}const h=Qt(e.executionTokenAddress,e.resolvedChainId);let f=a?i:Wn(i,h?.decimals??e.destinationToken.decimals,o.decimals);Ta(e,i),c=await e.execution.buildSupplyChainBatches({fundingAmountOverride:i,sourceFundingAmountOverride:f,withdrawalAmountOverride:i,actionAmountOverride:u,actionContextOverride:m});const g=o.chainId,y=n,C=await e.externalWallet.getEthereumProvider();await vo(C,g,()=>e.ui.setStatusMsg("Switching source network..."));const v=Ee(g),T=Yn({account:e.externalWalletAddress,chain:v?.viemChain,transport:Kn(C)}),b=It(o.address),w=o.isNative||Ue(b),B=gt(g),E=k=>ha({extWc:T,sourceClient:B,recipient:y,tokenAddr:b,isNative:w,amount:k,viemChain:v?.viemChain});e.ui.setStatusMsg("Funding embedded wallet..."),await E(f);let M=f;if(e.feeExecutionMode==="user-transfer")for(let k=0;k<4;k+=1){const A=await e.execution.estimate(c,e.executionTokenAddress,0n,d),I=Ro(A,e,r);if(!I)break;const S=a?I.grossAmount:Wn(I.grossAmount,h?.decimals??e.destinationToken.decimals,o.decimals);if(S>M&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await E(S-M),M=S),m=I,i=I.grossAmount,f=S,c=await e.execution.buildSupplyChainBatches({fundingAmountOverride:i,sourceFundingAmountOverride:f,withdrawalAmountOverride:i,actionAmountOverride:u,actionContextOverride:I}),$s(c,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let F=m;await e.execution.execute(c,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:k,chainBatches:A})=>{const I=Ro(k,e,r);if(!I)return null;const S=Ra(F,I),W=$s(A,e,I);if(S||W)return null;if(I.grossAmount>i)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");F=I;const P=a?I.grossAmount:Wn(I.grossAmount,h?.decimals??e.destinationToken.decimals,o.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:P,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:u,actionContextOverride:I})}}:d)}async function _s(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,o=e.activeSignerAddress??e.externalWalletAddress;if(!o||!n)throw new Error("Please connect your wallet to continue");const s=ze(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),r={userAddress:o,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},a=e.buildActionCalls(s,r);if(a.length===0)throw new Error("No action calls configured");const c=await n.getEthereumProvider();await vo(c,e.resolvedChainId);const d=Ee(e.resolvedChainId),i=Yn({account:o,chain:d?.viemChain,transport:Kn(c)}),p=gt(e.resolvedChainId);let u;for(const m of a){const h=await i.sendTransaction({to:m.to,data:m.data,value:m.value,chain:d?.viemChain});if((await p.waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");u=h}return u}async function Na(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,o=n.chainId,s=ze(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?s:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const a=e.resolvedTokenIn||e.selectedAsset.asset.address,c={userOverride:t,useCustomTransfers:!0},d=await e.execution.estimateRequiredGrossFunding(r,C=>e.execution.buildPayChainBatches({fundingAmountOverride:C}),a,c),i=hn(o),p=await e.externalWallet.getEthereumProvider();await vo(p,o);const u=Ee(o),m=Yn({account:e.externalWalletAddress,chain:u?.viemChain,transport:Kn(p)}),h=It(n.address),f=n.isNative||Ue(h)?await m.sendTransaction({to:i,value:d,chain:u?.viemChain}):await m.sendTransaction({to:h,data:Tt({abi:Fe,functionName:"transfer",args:[i,d]}),chain:u?.viemChain});if((await gt(o).waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const g=await e.execution.buildPayChainBatches({fundingAmountOverride:d}),y=g.some(C=>C.tokenTransfers?.length);return await e.execution.execute(g,a,d,C=>{C.txHash&&(e.ui.setPaymentResult(v=>({...v??{status:"processing"},txHash:C.txHash})),e.ui.setTxHash(C.txHash))},void 0,y?c:{userOverride:t})}async function Ua(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let o;if(e.isSourceDestToken||e.parsedAmount===0)o=await _s(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,r=ze(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const c=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!c)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const d=e.resolvedTokenIn||s.address,i=await e.execution.estimateRequiredGrossFunding(a,m=>e.execution.buildPayChainBatches({fundingAmountOverride:m}),d,{userOverride:c,useCustomTransfers:!0}),p=await e.execution.buildPayChainBatches({fundingAmountOverride:i}),u=await e.onPayExecute({asset:s,amount:e.currentPaymentAmount,amountWei:r,destinationToken:e.destinationToken,chainBatches:p,requiredNetFunding:a,grossFundingAmount:i,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:d,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});u&&(e.ui.setTxHash(u),e.ui.setPaymentResult(m=>({...m??{status:"processing"},txHash:u}))),o=u||void 0}else o=await Na(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||o||""}))}catch(o){const s=kn(o,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(o instanceof Error?o:new Error(s))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=ze(e.currentPaymentAmount,e.destinationToken.decimals),o={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const y=await e.execution.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),C=await e.execution.execute(y,e.destinationToken.address,0n,v=>{v.txHash&&(e.ui.setPaymentResult(T=>({...T,txHash:v.txHash})),e.ui.setTxHash(v.txHash))},void 0,o);e.ui.setPaymentResult(v=>({status:"success",txHash:v?.txHash||C}));return}const s=e.selectedAsset?.asset;if(!s)throw new Error("Select a payment source");const r=e.resolvedTokenIn||s.address||e.destinationToken.address,a=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,c=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,d=(y,C,v)=>{const T=Mo(y),b=E=>(E.tokenTransfers??[]).some(M=>M.from==="escrow"),w=T.filter(E=>!b(E)),B=T.filter(b);return[...w,...En(B,c,C,v)]},i=await e.execution.estimateRequiredGrossFunding(a,y=>e.execution.buildPayChainBatches({fundingAmountOverride:y}).then(C=>d(C)),r,o);let p=i,u=d(await e.execution.buildPayChainBatches({fundingAmountOverride:i}));const m=await e.execution.estimate(u,r,i,o),h=Jn(m,{chainId:e.resolvedChainId,tokenAddress:r,symbol:Qt(r,e.resolvedChainId)?.symbol??s.symbol,decimals:Qt(r,e.resolvedChainId)?.decimals??s.decimals})?.grossAmount??i;h!==i&&(p=h),u=d(await e.execution.buildPayChainBatches({fundingAmountOverride:p}),m,{payoutAlreadyGross:!0});const f=u.some(y=>y.tokenTransfers?.length),g=await e.execution.execute(u,r,f?p:0n,y=>{y.txHash&&(e.ui.setPaymentResult(C=>({...C,txHash:y.txHash})),e.ui.setTxHash(y.txHash))},void 0,o);e.ui.setPaymentResult(y=>({status:"success",txHash:y?.txHash||g}))}catch(n){const o=kn(n,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(n instanceof Error?n:new Error(o))}finally{e.ui.setIsExecuting(!1)}}const gd=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:c,cardBg:d,cardBorder:i,dk:p,dark:u,isQuoting:m,quoteError:h,estimatedOutput:f,paymentAmount:g,needsSwap:y,exactOutputSwap:C,adjustable:v=!1,maxAmount:T,onAmountChange:b})=>e==="supply"?x("div",{style:{backgroundColor:d,border:`1px solid ${i}`,borderRadius:u?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[x("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[x("div",{style:{minWidth:0},children:[l("span",{style:{fontFamily:r,fontSize:"17px",fontWeight:500,color:u?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),l("div",{style:{fontSize:"12px",fontWeight:500,color:c,fontFamily:r,marginTop:"10px"},children:"Net amount after swap and fees"})]}),x("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${i}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[l(za,{symbol:t,logoURI:n,primaryColor:s,size:24}),l("span",{style:{fontSize:"16px",fontWeight:500,color:u?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:r,letterSpacing:0},children:t})]})]}),l("div",{style:{textAlign:"right",minWidth:0},children:m?l("span",{style:{fontSize:"18px",color:c,fontFamily:r},children:"Quoting..."}):h?l("span",{style:{fontSize:"13px",color:u?"#f87171":"#dc2626",fontFamily:r},children:"Quote failed"}):f?l(ao,{value:f,title:f,fontFamily:r,color:a,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):l("span",{style:{fontSize:"20px",color:c,fontFamily:r},children:"\u2014"})})]}):l(yd,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:c,cardBg:d,cardBorder:i,dk:p,dark:u,paymentAmount:g||"0",needsSwap:y,exactOutputSwap:C,isQuoting:m,adjustable:v,maxAmount:T,onAmountChange:b}),Pa=pn(gd),za=({symbol:e,logoURI:t,primaryColor:n,size:o})=>t?l("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):l("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),yd=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:o,fontFamily:s,textPrimary:r,textSecondary:a,cardBg:c,cardBorder:d,dk:i,dark:p,paymentAmount:u,needsSwap:m,exactOutputSwap:h,isQuoting:f,adjustable:g,maxAmount:y,onAmountChange:C})=>{const v='"IBM Plex Mono", monospace',T=parseFloat(u||"0"),b=y?parseFloat(y):0,[w,B]=R(u||""),E=le(null),[M,F]=R(null),[k,A]=R(null);X(()=>{g||B(u||"")},[u,g]);const I=P=>{let z=P;z.startsWith(".")&&(z="0"+z);const N=uo(z);let D=N;y&&parseFloat(N)>parseFloat(y)&&(D=y),B(D),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>C?.(D),300)},S=P=>{if(!b)return;if(P===100){B(y||b.toString()),E.current&&clearTimeout(E.current),C?.(y||b.toString());return}const z=10**n,N=Math.floor(b*P/100*z)/z,D=po(N,n);B(D),E.current&&clearTimeout(E.current),C?.(D)},W=b>0?parseFloat(w||"0")/b*100:0;return X(()=>()=>{E.current&&clearTimeout(E.current)},[]),x("div",{style:{backgroundColor:c,border:`1px solid ${d}`,borderRadius:p?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[x("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[x("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[l(za,{symbol:e,logoURI:t,primaryColor:o,size:32}),x("div",{children:[l("span",{style:{fontSize:"14px",fontWeight:600,color:r,fontFamily:s},children:"Payment"}),l("div",{style:{fontSize:"12px",color:a,fontFamily:s,marginTop:"2px"},children:e})]})]}),x("div",{style:{textAlign:"right"},children:[g?l(ao,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:P=>I(P.target.value),placeholder:"0.0",fontFamily:v,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):l(ao,{element:"div",value:T>0?u:"0.00",title:T>0?u:"0.00",fontFamily:v,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),l("div",{style:{fontSize:"12px",color:a,fontFamily:v,marginTop:"2px"},children:e}),g&&b>0&&l("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((P,z)=>{const N=Math.abs(W-P)<1,D=z===4,H=P/100,L=M===P,ee=k===P;return l("button",{onClick:()=>S(P),onMouseEnter:()=>F(P),onMouseLeave:()=>{F(null),A(null)},onMouseDown:()=>A(P),onMouseUp:()=>A(null),title:`${P}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:N?1:L?.8:.5,transform:ee?"scale(0.85)":L?"scale(1.15)":"scale(1)",transition:An.interactive},children:x("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[l("circle",{cx:"7",cy:"7",r:"6.84375",fill:D?o:"none",stroke:D?o:p?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!D&&H>0&&l("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${H>.5?1:0} 1 ${7+6.84375*Math.sin(H*2*Math.PI)} ${7-6.84375*Math.cos(H*2*Math.PI)} Z`,fill:p?i?.textSecondary||"#9ca3af":"#3C3E42"})]})},P)})})]})]}),m&&h&&!f&&l("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:p?`1px solid ${i?.cardBorder||d}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:x("span",{style:{fontSize:"11px",color:a,fontFamily:s,opacity:.7},children:["via ",h.venue]})})]})};function La(e,t,n){const o=Ie(e.address,t),s=e.chainId===n,r=e._source==="wallet";return r&&o&&s?0:r&&s?1:!r&&o?2:!r&&s?3:4}function Oa(e,t){return!t||t.length===0||t.some(n=>Ie(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const o=yo(n);return o?t.some(s=>Ie(s,o.address)):!1})}function Ha(e,t,n){let{symbol:o,name:s,logoURI:r}=t;const a=Ie(e.address,n.address)&&e.chainId===n.chainId;a&&n.logoURI&&(r=n.logoURI),a&&!e.configToken&&o==="TOKEN"&&(o=n.symbol,s=n.symbol);const c=parseFloat((Number(t.balance)/Math.pow(10,t.decimals)).toFixed(6));return{address:e.address,name:s,symbol:o,decimals:t.decimals,balance:t.balance,balanceFormatted:c,balanceUsd:0,logoURI:r,isNative:!1,chainId:e.chainId}}function ja(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:o,enabled:s}=e,r=rn(Zt),a=(r?.mode||"7702")!=="7702",c=r?.embeddedWalletAddress,{externalAddress:d,embeddedAddress:i,activeAddress:p}=mo(),u=c||i,{assets:m,refetch:h}=To({address:u,supportedChains:o,enabled:s&&!a&&!!u,refetchInterval:3e4}),f=oe(()=>a?[]:m.filter(F=>Oa(F,n)),[m,n,a]),g=a?p??d:c,y=oe(()=>{const F=new Set,k=[],A=I=>{if(!I)return;const S=I.toLowerCase();F.has(S)||(F.add(S),k.push(kt(I)))};if(A(t.address),n)for(const I of n)A(I);return k},[a,t.address,n]),C=oe(()=>y.map(F=>F.toLowerCase()).sort().join(","),[y]),v=oe(()=>JSON.stringify([...o||[]].sort()),[o]),[T,b]=R([]),w=le(0),B=le(async()=>{}),E=re(async()=>{if(!s||!g||y.length===0){w.current++,b([]);return}const F=++w.current,k=kt(g),A=a?o&&o.length>0?o:[t.chainId]:[t.chainId],I=[];for(const z of y){const N=z.toLowerCase();if(N===Xt)continue;if(N===t.address.toLowerCase()){const H=Ee(t.chainId)?.supportedTokens?.find(L=>Ie(L.address,N));I.push({address:z,chainId:t.chainId,configToken:H?{decimals:H.decimals,symbol:H.symbol,name:H.name,logo:H.logo}:void 0});continue}let D=!1;for(const H of A){const L=Ee(H)?.supportedTokens?.find(ee=>Ie(ee.address,N));if(L){I.push({address:z,chainId:H,configToken:{decimals:L.decimals,symbol:L.symbol,name:L.name,logo:L.logo}}),D=!0;break}}D||I.push({address:z,chainId:t.chainId})}const S=new Map;for(const z of I){const N=S.get(z.chainId)||[];N.push(z),S.set(z.chainId,N)}const W=async(z,N)=>{try{const D=await Zn(z,{address:N.address,abi:Fe,functionName:"balanceOf",args:[k]}),{decimals:H,symbol:L,name:ee,logoURI:U}=await pa(z,N.address,N.configToken);return Ha(N,{decimals:H,symbol:L,name:ee,logoURI:U,balance:D},t)}catch{return null}},P=await Promise.all(Array.from(S.entries()).map(async([z,N])=>{let D;try{D=gt(z)}catch{return[]}const H=[],L=[];for(const U of N){const Z=H.length;H.push({address:U.address,abi:Fe,functionName:"balanceOf",args:[k]}),U.configToken||H.push({address:U.address,abi:Fe,functionName:"decimals"},{address:U.address,abi:Fe,functionName:"symbol"},{address:U.address,abi:Fe,functionName:"name"}),L.push({start:Z,item:U})}let ee=null;try{ee=await D.multicall({contracts:H})}catch{ee=null}return ee?L.map(({start:U,item:Z})=>{const fe=ee[U],Q=fe?.status==="success"?fe.result:0n;let G,de,ve,ce;if(Z.configToken)G=Z.configToken.decimals,de=Z.configToken.symbol,ve=Z.configToken.name,ce=Z.configToken.logo;else{const he=ee[U+1],ue=ee[U+2],Se=ee[U+3];G=he?.status==="success"?Number(he.result):18,de=ue?.status==="success"?ue.result:"TOKEN",ve=Se?.status==="success"?Se.result:de}return Ha(Z,{decimals:G,symbol:de,name:ve,logoURI:ce,balance:Q},t)}):(await Promise.all(N.map(U=>W(D,U)))).filter(U=>U!==null)}));F===w.current&&b(P.flat())},[s,a,g,C,v,t.address,t.chainId,t.symbol,t.logoURI]);X(()=>{B.current=E},[E]),X(()=>{if(!s){b([]);return}B.current();const F=setInterval(()=>{B.current()},15e3);return()=>clearInterval(F)},[s,a,g,C,v,t.address,t.chainId]);const M=re(()=>{E()},[E]);return{displayAssets:oe(()=>{const F=[],k=T.filter(I=>I.balance>0n);for(const I of k)F.push({...I,_source:"wallet"});for(const I of f)F.push({...I,_source:"spice"});const A=t.address.toLowerCase();return F.sort((I,S)=>La(I,A,t.chainId)-La(S,A,t.chainId)),F},[T,f,t.address,t.chainId]),filteredSpiceAssets:f,walletAssets:T,embeddedWalletAddress:u,externalAddress:d,isNon7702:a,refreshSpiceAssets:h,refreshWalletAssets:M}}async function Qa(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:s,chainId:r,config:a}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const c=(await gt(r).simulateContract({address:a.quoterV2,abi:Ai,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,fee:s,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function Va(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>Qa({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const xd=[{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 bd(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:s,chainId:r,config:a}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const c=(await gt(r).simulateContract({address:a.quoterV2,abi:xd,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,fee:s,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function wd(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>bd({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function qa(e){return e.type==="swap"}const er=.02,Cd=[1,8453,42161,10,137,43114,56],vd="https://api.1inch.dev/swap/v6.0";function Ya(e,t){return Ei(e,t)}function Ka(e){const t=e?.baseUrl??vd;return{name:"1inch",chainIds:e?.chainIds??Cd,resolve:async(n,o,s)=>{const r=n.maxSlippage??er,a=r*100,c=Ue(n.tokenIn)?fr:n.tokenIn,d=Ue(n.tokenOut)?fr:n.tokenOut,i=Ue(n.tokenIn);try{const p=new URL(`${t}/${o}/swap`);p.searchParams.set("src",c),p.searchParams.set("dst",d),p.searchParams.set("amount",n.amountIn.toString()),p.searchParams.set("from",s),p.searchParams.set("slippage",a.toString()),p.searchParams.set("disableEstimate","true"),p.searchParams.set("allowPartialFill","false");const u={Accept:"application/json"};e?.apiKey&&(u.Authorization=`Bearer ${e.apiKey}`);const m=await fetch(p.toString(),{headers:u});if(!m.ok)throw new Ae("VENUE_API_ERROR",`[1inchVenue] API returned ${m.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${m.status}`});const h=await m.json();if(!h.dstAmount||!h.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const f=BigInt(h.dstAmount);if(f<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const g=Ya(f,r),y=[];return h.tx.to&&!i&&y.push({to:n.tokenIn,value:0n,data:Tt({abi:Fe,functionName:"approve",args:[h.tx.to,n.amountIn]})}),y.push({to:h.tx.to,value:BigInt(h.tx.value||"0"),data:h.tx.data}),{venue:"1inch",amountOut:f,amountOutMinimum:g,calls:y}}catch(p){if(p instanceof Ae)throw p;const u=p instanceof Error?p.message:String(p);throw new Ae("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${u}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:u})}}}}const Za=[4114,5115],tr={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Xa={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Ga(e){return{name:"satsuma",chainIds:e.chainIds??Za,resolve:async(t,n,o)=>{const s=t.maxSlippage??er,r=Ue(t.tokenIn);let a;try{a=await Va({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const c=Ya(a.amountOut,s),d=[];return r||d.push({to:t.tokenIn,value:0n,data:Tt({abi:Fe,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),d.push({to:e.swapRouter,value:r?t.amountIn:0n,data:Tt({abi:Si,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:a.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:a.amountOut,amountOutMinimum:c,calls:d}}}}function Ja(e){return{name:"satsuma",chainIds:e.chainIds??Za,resolve:async(t,n,o)=>{const s=t.maxSlippage??er,r=Ue(t.tokenIn);let a;try{a=await wd({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const c=BigInt(Math.round(s*1e4)),d=a.amountIn+a.amountIn*c/10000n,i=[];return i.push({to:e.swapRouter,value:r?d:0n,data:Tt({abi:kd,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:a.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:a.amountIn,amountInMax:d,amountOut:t.amountOut,calls:i}}}}const kd=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"exactOutputSingle",outputs:[{name:"amountIn",type:"uint256"}],stateMutability:"payable",type:"function"}];function $a(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Ga(e.satsuma)),t.push(Ka(e?.oneInch));function n(s){return t.find(r=>r.chainIds.includes(s))}async function o(s,r,a){const c=[],d=[];for(const i of s){if(!qa(i)){c.push(i);continue}const p=n(r);if(!p)throw new Ae("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${r}. Cannot resolve swap ${i.tokenIn} \u2192 ${i.tokenOut}.`,{chainId:r,tokenIn:i.tokenIn,tokenOut:i.tokenOut,amountIn:i.amountIn.toString()});const u=await p.resolve(i,r,a);if(!u)throw new Ae("NO_LIQUIDITY",`${p.name} returned no quote for ${i.tokenIn} \u2192 ${i.tokenOut} on chain ${r}.`,{venue:p.name,chainId:r,tokenIn:i.tokenIn,tokenOut:i.tokenOut,amountIn:i.amountIn.toString()});c.push(...u.calls),d.push(u)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:o,getVenueForChain:n,venues:t}}function _a(e){const t=e?.customVenues??[];async function n(o,s,r){const a=t.filter(d=>d.chainIds.includes(s));if(a.length===0)throw new Ae("NO_SWAP_ROUTE",`No exact-output venue supports chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const c=(await Promise.allSettled(a.map(d=>d.resolve(o,s,r)))).filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d!==null);if(c.length===0)throw new Ae("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return c.sort((d,i)=>d.amountIn<i.amountIn?-1:d.amountIn>i.amountIn?1:0),c[0]}return{getQuote:n,venues:t}}const ei=$a({satsuma:tr});async function Id(e){const t=ei.getVenueForChain(e.chainId);if(!t)throw new Error(`No swap venue configured for chain ${e.chainId}.`);const n=await t.resolve({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn},e.chainId,e.recipient);if(!n)throw new Error("No liquidity for this pair.");return n}function ti(e){const{direction:t,selectedAsset:n,destinationToken:o,chainId:s,recipient:r,paymentAmount:a,resolveExactOutputSwap:c}=e,[d,i]=R(!1),[p,u]=R(null),[m,h]=R(null),[f,g]=R(null),[y,C]=R(null),[v,T]=R(null),[b,w]=R(null),[B,E]=R(null),[M,F]=R(null),k=le(null),A=le(null),I=le(0),S=le(new Map),W=oe(()=>ei,[]),P=oe(()=>_a({customVenues:[...c?[{name:"consumer-exact-output",chainIds:[s],resolve:c}]:[],Ja(tr),Ja(Xa)]}),[c,s]),z=oe(()=>{if(!n?.asset)return null;const G=Dn(n.asset,s);if(G)return G;const de=jn(n.asset.address,s,n.asset.chainId);return de?de.address:null},[n?.asset,s]),N=oe(()=>n?.asset?qo(n.asset,s):[],[n?.asset,s]),D=oe(()=>N.map(G=>G.toLowerCase()).join(","),[N]);X(()=>{let G=!1;if(A.current&&(clearTimeout(A.current),A.current=null),!n?.asset||N.length<=1){F(null);return}return A.current=setTimeout(async()=>{const de=t==="input"?n.amount:a||"0";let ve=0n;try{ve=t==="input"?ze(de,n.asset.decimals):0n}catch{ve=0n}try{const ce=await Rr(n.asset,s,{requiredAmount:ve});G||F(ce)}catch{G||F(null)}},400),()=>{G=!0,A.current&&(clearTimeout(A.current),A.current=null)}},[n?.asset,n?.amount,s,N.length,D,t,a]);const H=oe(()=>M??z,[M,z]),L=oe(()=>!n?.asset||!H?[]:[H,...N.filter(G=>G.toLowerCase()!==H.toLowerCase())],[n?.asset,H,N]),ee=oe(()=>!n?.asset||!Bo(n.asset.address,n.asset.chainId,o.address,o.chainId)||!H?!1:Ie(H,o.address),[n,o.address,o.chainId,H]),U=H?Ie(H,o.address):!1,Z=t==="output"&&parseFloat(a||"0")===0,fe=!!n?.asset&&!ee&&!U&&!Z,Q=fe?B??H:H;return X(()=>{k.current&&clearTimeout(k.current);const G=t==="input"?n?.amount:a,de=parseFloat(G||"0");if(!fe||!Number.isFinite(de)||de<=0||!n?.asset||!r||L.length===0){I.current++,h(null),g(null),C(null),T(null),w(null),E(null),u(null),i(!1);return}const ve=n.asset.decimals;let ce;try{ce=t==="input"?ze(n.amount,ve):ze(a||"0",o.decimals)}catch{I.current++,u("Invalid amount"),i(!1);return}const he=++I.current,ue=()=>he!==I.current;i(!0);const Se=t==="output"?150:400;return k.current=setTimeout(async()=>{try{if(t==="input"){const $=W.getVenueForChain(s);if(!$)throw new Error("No swap venue for this chain");let V=null,_=null;for(const xe of L){const q=`${t}:${s}:${xe.toLowerCase()}:${o.address.toLowerCase()}:${ce.toString()}`,te=S.current.get(q);if(te&&te.expiresAt>Date.now()&&te.resolvedSwap){V=te.resolvedSwap,_=xe;break}const ge=await $.resolve({type:"swap",tokenIn:xe,tokenOut:o.address,amountIn:ce},s,r);if(ue())return;if(ge){S.current.set(q,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:ge}),V=ge,_=xe;break}}if(!V||!_)throw new Error("No liquidity for this pair");E(_),w(V.amountOut),C(V),T(null);const ae=parseFloat(pt(V.amountOut,o.decimals));h(ae<.01?ae.toPrecision(4):ae.toLocaleString(void 0,{maximumFractionDigits:6})),g(null),u(null)}else{let $=null,V=null;for(const _ of L){const ae=`${t}:${s}:${_.toLowerCase()}:${o.address.toLowerCase()}:${ce.toString()}`,xe=S.current.get(ae);if(xe&&xe.expiresAt>Date.now()&&xe.exactOutputSwap){$=xe.exactOutputSwap,V=_;break}try{const q=await P.getQuote({tokenIn:_,tokenOut:o.address,amountOut:ce},s,r);if(ue())return;S.current.set(ae,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:q}),$=q,V=_;break}catch{if(ue())return}}if(!$||!V)throw new Error("No liquidity for this pair");E(V),T($),C(null),w(null),g(parseFloat(pt($.amountIn,ve)).toFixed(6)),h(null),u(null)}}catch($){if(ue())return;const V=$ instanceof Error?$.message:"Failed to get quote";u(V),h(null),g(null),C(null),T(null),w(null),E(null)}finally{ue()||i(!1)}},Se),()=>{k.current&&clearTimeout(k.current)}},[t,fe,n?.amount,n?.asset?.address,n?.asset?.decimals,a,L,s,o.address,o.decimals,r,W,P]),{isQuoting:d,quoteError:p,estimatedOutput:m,estimatedInput:f,resolvedSwap:y,exactOutputSwap:v,quoteAmountOut:b,resolvedTokenIn:Q,isDirect:U,needsSwap:fe,selectedIsEquivalent:ee}}const ni={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},oi=["signing-delegation","signing-intent","submitting","executing"],Ad=()=>{},Sd=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:o,sourceChains:s,supportedSourceAssets:r,buildActionCalls:a,feeExecutionMode:c="user-transfer",buildSpicenetBatch:d,onPayExecute:i,resolveExactOutputSwap:p,actionLabel:u,amountDirection:m="input",swapDescription:h,directDescription:f,paymentAmount:g,amountInputMode:y="fixed",minPaymentAmount:C,maxPaymentAmount:v,onAmountChange:T,styles:b,dark:w,title:B,subtitle:E,onAddFunds:M,onSuccess:F,onError:k})=>{const A=m==="output",{theme:I,dark:S,primaryColor:W,dk:P,palette:z,fontFamily:N,monoFont:D,inputDark:H,cardBg:L,cardBorder:ee,textPrimary:U,textSecondary:Z,subtitleText:fe}=Bt(b,w),Q=oe(()=>H?{...I,colors:{...I.colors,secondary:P.cardBg,surfaceHover:P.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:I,[H,I,P.cardBg,P.hoverBg]),G=o.chainId,de=rn(Zt),ve=de?.mode||"7702",ce=ve!=="7702",he=!!de?.isWhitelistGateActive,ue=!!de?.isWhitelistConfigured&&de?.isUserWhitelisted!==!0,Se=oe(()=>s??de?.supportedChainIds??[],[s,de?.supportedChainIds]),$=oe(()=>{if(he)return[];if(r)return r;const ye=de?.allowedTokens;if(!ye||ye.length===0)return;const at=new Set(ye.map(Vn=>Vn.toLowerCase())),Un=[],Qn=new Set;for(const Vn of Se){const ds=Ee(Vn);for(const us of ds?.supportedTokens??[]){if(!at.has(us.symbol.toLowerCase()))continue;const nr=us.address.toLowerCase();Qn.has(nr)||(Qn.add(nr),Un.push(us.address))}}return Un},[r,de?.allowedTokens,Se,he]),V=Pn(),{address:_,isConnected:ae,isReady:xe,isAuthenticated:q,provider:te}=V,{execute:ge,estimate:se}=bo(),{externalWallet:Le,embeddedAddress:yt,activeWallet:Ot,activeAddress:Ht}=mo(),xt=de?.externalWalletAddress,me=de?.embeddedWalletAddress||yt,{displayAssets:jt,filteredSpiceAssets:Pe,embeddedWalletAddress:Qe,refreshSpiceAssets:it,refreshWalletAssets:Ut}=ja({destinationToken:o,supportedSourceAssets:$,sourceChains:Se,enabled:e&&(ce?!!xt:!!me)}),nt=he||A||ce?jt:Pe;X(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:ve,walletAddressUsed:Qe,count:nt.length,assets:nt.map(ye=>({symbol:ye.symbol,address:ye.address,chainId:ye.chainId,balanceFormatted:ye.balanceFormatted,source:ye?._source}))})},[e,ve,Qe,nt]);const[O,Ge]=R(null),[Me,Je]=R(g||""),[Ke,Jt]=R(!1),[_t,an]=R(null),[Be,en]=R("idle"),[ot,Fn]=R(""),[yn,$e]=R(null),[ln,Vt]=R(!1),[qe,we]=R(null),[Ye,tt]=R(null),[xn,ke]=R(!1),[$t,Dt]=R(!1),[At,_e]=R(null),Bn=le(O),qt=le(!1),cn=le(null),bn=le(null),Yt=le(0),Mt=le(null),bt=le(null);X(()=>{Bn.current=O},[O]);const Oe=y==="adjustable"?Me:g||"0",lt=Qe||yt||_,{isQuoting:St,quoteError:dn,estimatedOutput:tn,resolvedSwap:Et,exactOutputSwap:Te,quoteAmountOut:Wt,resolvedTokenIn:ft,isDirect:Nt,needsSwap:ct,selectedIsEquivalent:Re}=ti({direction:m,selectedAsset:O,destinationToken:o,chainId:G,recipient:lt,paymentAmount:Oe,resolveExactOutputSwap:p}),dt=A?parseFloat(Oe||"0"):parseFloat(O?.amount||"")||0,nn=dt>0&&dt<Hn,J=O?.asset?._source==="wallet",ne=!!O?.asset&&J&&O.asset.chainId!==G,Ce=oe(()=>O?.asset?Pe.find(ye=>Ie(ye.address,O.asset.address))?.balanceFormatted??0:0,[O,Pe]),He=J?O?.asset.balanceFormatted??0:Ce,et=oe(()=>{if(!O?.asset)return!1;if(A)return Ye?Wn(Ye.grossAmount,Ye.decimals,O.asset.decimals)>O.asset.balance:Re||Nt?dt>O.asset.balanceFormatted:Te?parseFloat(pt(Te.amountInMax,O.asset.decimals))>O.asset.balanceFormatted:!1;if(Ye){const ye=Wn(Ye.grossAmount,Ye.decimals,O.asset.decimals);return J?ye>O.asset.balance:parseFloat(pt(ye,O.asset.decimals))>He}return dt>He},[O,A,Ye,Re,dt,Te,He,J,Nt]);X(()=>{e||(Ge(null),an(null),Jt(!1),en("idle"),Fn(""),$e(null),Vt(!1),we(null),tt(null),ke(!1),Dt(!1),_e(null),qt.current=!1,y==="adjustable"&&Je(g||""),cn.current&&(cn.current.abort(),cn.current=null))},[e]);const ht=re(ye=>{Ge(at=>({asset:ye,amount:at?.asset?.address===ye.address&&at?.asset?.chainId===ye.chainId&&at.amount||""})),an(null),_e(null),Dt(!1)},[]),wt=re(ye=>{Ge(at=>at&&{...at,amount:ye}),an(null),_e(null),Dt(!1)},[]),mt=re(ye=>{let at=ye;v&&parseFloat(at)>parseFloat(v)&&(at=v),Je(at),T?.(at),an(null),_e(null),Dt(!1)},[v,T]);re(ye=>{if(qt.current||!_)return;const at=Bn.current;!at?.asset||!at.amount||at.asset?._source==="wallet"||ze(A?Oe:at.amount,at.asset.decimals)===0n||(qt.current=!0,it())},[_,G,it,A,Oe]);const De=re(ye=>{en({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[ye.step]||"executing"),Fn(ye.message),ye.txHash&&$e(ye.txHash)},[]),Rt=oe(()=>({currentPaymentAmount:Oe,destinationToken:o,embeddedWalletAddress:Qe,providerEmbeddedAddress:yt,externalWalletAddress:xt,address:_,isNon7702:ce,isPayMode:A,resolvedChainId:G,buildActionCalls:a,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:O,needsSwap:ct,resolvedSwap:Et,exactOutputSwap:Te,quoteAmountOut:Wt,resolvedTokenIn:ft}),[Oe,o,Qe,yt,xt,_,ce,A,G,a,c,d,O,ct,Et,Te,Wt,ft]),je=re(ye=>Aa({...Rt,requestTimestampMs:bn.current??Date.now()},ye),[Rt]),Y=re(ye=>Sa({...Rt,requestTimestampMs:bn.current??Date.now()},ye),[Rt]),be=re((ye,at,Un,Qn)=>Ea(ye,at,Un,se,Qn),[se]),Ct=oe(()=>O?.asset?ct&&ft?ft:O.asset.chainId===G?O.asset.address:ft??Dn(O.asset,G)??o.address:o.address,[O,o.address,ct,G,ft]),Ft=re(()=>(bn.current=Date.now(),Da(bt.current)),[]),Ze=oe(()=>O?.asset?Ie(O.asset.address,o.address)&&O.asset.chainId===o.chainId:!1,[O,o.address,o.chainId]),Pt=Ze&&(ce||A),st=Pt&&dt>0&&!!O?.asset,un=ue&&!Pt,j=oe(()=>{if(!st)return null;let ye;try{ye=ze(Oe||"0",o.decimals)}catch{return null}return{symbol:o.symbol,decimals:o.decimals,grossAmount:ye,netAmount:ye,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[st,Oe,o.symbol,o.decimals]),K=_t,pe=oe(()=>!(!O?.asset||dt<=0),[O,dt,st]),ie=oe(()=>!e||Ke||Be!=="idle"||!pe||st||!O?.asset?null:[A?"pay":"supply",m,O.asset.address.toLowerCase(),O.asset.chainId,O.amount,Oe,o.address.toLowerCase(),o.chainId,G,ft?.toLowerCase()??"",ct?"swap":"direct",Nt?"direct-token":"routed-token",ce?"non7702":"7702",Ze?"source-dest":"cross-chain",St?"quoting":"quoted",Te?.amountIn?.toString()??"",Te?.amountInMax?.toString()??"",Te?.venue??"",Et?.amountOut?.toString()??"",Wt?.toString()??"",Qe??"",yt??"",_??""].join("|"),[e,Ke,Be,pe,st,O,A,m,Oe,o,G,ft,ct,Nt,ce,Ze,St,Te,Et,Wt,Qe,yt,_]),Ve=re(()=>Ba({selectedAsset:O,isPayMode:A,parsedAmount:dt,needsSwap:ct,exactOutputSwap:Te,isNon7702:ce,isSourceDestToken:Ze,currentPaymentAmount:Oe,destinationToken:o,feeExecutionMode:c,resolvedTokenIn:ft,embeddedWalletAddress:Qe,providerEmbeddedAddress:yt,resolvedChainId:G,isConnected:ae,address:_,ready:xe,authenticated:q,isDirect:Nt,resolvedSwap:Et,isQuoting:St,executionTokenAddress:Ct,buildPayChainBatches:je,buildSupplyChainBatches:Y,estimate:se,estimateRequiredGrossFunding:be}),[O,A,dt,ct,Te,ce,Ze,Oe,o,c,ft,Qe,yt,be,je,se,G,ae,_,xe,q,Nt,Et,St,Y,Ct]);X(()=>{Mt.current=Ve},[Ve]);const We=re(ye=>Fa({asset:ye,isPayMode:A,isNon7702:ce,needsSwap:ct,isQuoting:St,embeddedWalletAddress:Qe,buildSupplyChainBatches:Y,estimate:se,executionTokenAddress:Ct,feeExecutionMode:c}),[A,ce,ct,St,Qe,Y,se,Ct,c]);X(()=>{if(!e){ke(!1),Dt(!1),_e(null),tt(null);return}if(Ke||Be!=="idle"){Yt.current+=1,ke(!1);return}if(!pe){tt(null),ke(!1),Dt(!1),_e(null);return}if(st){tt(j),ke(!1),Dt(!0),_e(null);return}if(St){Yt.current+=1,ke(!1),Dt(!1);return}if(!ie)return;let ye=!1;const at=async()=>{const Qn=++Yt.current;_e(null),ke(!0);try{const Vn=await Mt.current?.();if(ye||Yt.current!==Qn)return;Vn?(tt(Vn),Dt(!0)):(tt(null),Dt(!1)),_e(null)}catch(Vn){if(ye||Yt.current!==Qn)return;const ds=kn(Vn,"Unable to calculate fees for this action.");tt(null),Dt(!1),_e(ds)}finally{!ye&&Yt.current===Qn&&ke(!1)}},Un=window.setTimeout(()=>{at()},250);return()=>{ye=!0,clearTimeout(Un),ke(!1)}},[e,Ke,Be,pe,st,j,St,ie]);const Xe=re(()=>(bn.current=Date.now(),Ua(bt.current)),[]);X(()=>{!A&&Be==="success"&&yn&&(it(),F?.(yn))},[A,Be,yn,it,F]),X(()=>{if(!A||qe?.status!=="success"||qt.current||!_)return;qt.current=!0;const ye=Bn.current;!ye?.asset||ye.asset?._source==="wallet"||it()},[A,qe?.status,_,it]);const ut=le(F),zt=le(k);X(()=>{ut.current=F},[F]),X(()=>{zt.current=k},[k]),X(()=>{e&&(it(),Ut())},[e,it,Ut]),X(()=>{A&&(qe?.status==="success"&&ut.current?.(qe.txHash||""),qe?.status==="failed"&&zt.current?.(new Error("Payment execution failed")))},[A,qe?.status]);const on=re(()=>{Vt(!1),we(null),Ge(null),qt.current=!1,it(),Ut()},[it,Ut]);bt.current={selectedAsset:O,parsedAmount:dt,currentPaymentAmount:Oe,isInsufficientBalance:et,isPayMode:A,isNon7702:ce,isSourceDestToken:Ze,needsSwap:ct,exactOutputSwap:Te,selectedIsEquivalent:Re,resolvedTokenIn:ft,embeddedWalletAddress:Qe,providerEmbeddedAddress:yt,externalWallet:Le,externalWalletAddress:xt,activeSignerWallet:Ot,activeSignerAddress:Ht,address:_,isConnected:ae,ready:xe,authenticated:q,provider:te,resolvedChainId:G,executionTokenAddress:Ct,destinationToken:o,buildActionCalls:a,feeExecutionMode:c,buildSpicenetBatch:d,onPayExecute:i,onSuccess:F,onError:k,execution:{estimate:se,execute:ge,buildPayChainBatches:je,buildSupplyChainBatches:Y,estimateRequiredGrossFunding:be,onProgress:De},ui:{setError:an,setStep:en,setStatusMsg:Fn,setTxHash:$e,setIsExecuting:Jt,setShowStatusPanel:Vt,setPaymentResult:we},refs:{spiceDepositSubmittedRef:qt,abortControllerRef:cn}};const wn=g?.trim(),Kt=A&&y==="fixed"&&wn!==void 0&&wn!==""&&dt===0,Cn=A?(Kt||!!O?.asset)&&dt>=0&&!nn&&!et&&!Ke&&(Kt||st||$t)&&!At&&(Kt||!ct||!!Te)&&!un:!!O?.asset&&dt>0&&!nn&&!et&&!Ke&&(Pt||$t)&&!At&&(ne||Nt||!!Et&&!St)&&!un;X(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:Cn,isPayMode:A,hasSelectedAsset:!!O?.asset,selectedAsset:O?.asset?{symbol:O.asset.symbol,address:O.asset.address,chainId:O.asset.chainId,balanceFormatted:O.asset.balanceFormatted,source:O.asset?._source}:null,parsedAmount:dt,isZeroAmountPay:Kt,isBelowMinimum:nn,isInsufficientBalance:et,isExecuting:Ke,directExternalAction:Pt,directExecutionFeeNote:st,feeEstimateReady:$t,feeEstimateError:At,needsSwap:ct,isDirect:Nt,isSourceDestToken:Ze,hasExactOutputSwap:!!Te,isQuoting:St,whitelistHoldPending:ue,supplyHeldForWhitelist:un,isWhitelistGateActive:he,destinationToken:{symbol:o.symbol,address:o.address,chainId:o.chainId}})},[e,Cn,A,O,dt,Kt,nn,et,Ke,Pt,st,$t,At,ct,Nt,Ze,Te,St,ue,un,he,o]);const eo=Nt?f||`Your ${o.symbol} will be used directly.`:h||"Your assets will be swapped and used in a single atomic transaction.",co=(G?Ee(G):void 0)?.viemChain?.blockExplorers?.default?.url??"",to=oi.indexOf(Be),Ne=Ke?(ni[Be]||"EXECUTING...").toUpperCase():Be==="success"?"DONE":nn?`MINIMUM ${Hn}`:et?"INSUFFICIENT BALANCE":u.toUpperCase(),rt=oe(()=>{if(Ke)return"PAYING...";if(nn)return`MINIMUM ${Hn}`;if(et&&O?.asset)return`INSUFFICIENT ${O.asset.symbol}`;if(u)return u.toUpperCase();const ye=dt>0?` ${Oe} ${o.symbol}`:"";return ct?`SWAP & PAY${ye}`:`PAY${ye}`},[Ke,nn,et,O,u,dt,Oe,o.symbol,ct]),sn=Be==="success"?()=>{en("idle"),Ge(null),$e(null),it()}:Ft,Nn=Be==="success"?!1:!Cn;if(!e)return null;const Wo=A?B||`Pay ${o.symbol}`:u,ko=A?E:x("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[l("span",{style:{marginTop:"3px",flexShrink:0},children:l(Us,{color:fe})}),l("p",{style:{fontSize:"12px",color:fe,margin:0,lineHeight:"1.4",fontFamily:N},children:eo})]});if(A){const ye=qe&&(qe.status==="success"||qe.status==="failed")?[{asset:{symbol:O?.asset?.symbol||o.symbol,address:O?.asset?.address||""},amount:Oe,txHash:qe.txHash||"",success:qe.status==="success",error:qe.status==="failed"?qe.error:void 0}]:void 0;return l(Ln,{isOpen:e,onClose:t,title:Wo,subtitle:ko,styles:b,dark:S,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:x("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[M&&l("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:l(Ps,{onClick:M,color:W,fontFamily:N})}),!Kt&&l("div",{style:{marginBottom:"12px"},children:l(Fo,{assets:nt,selectedAsset:O??void 0,onAssetSelect:ht,onAmountChange:Ad,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:O?.asset?ct?St?"...":Te?`~${parseFloat(pt(Te.amountIn,O.asset.decimals)).toFixed(6)}`:void 0:Oe??void 0:void 0,dark:S,theme:Q,styles:b})}),l(Pa,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:W,fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:L,cardBorder:ee,dk:P,dark:S,isQuoting:St,quoteError:dn,estimatedOutput:tn,paymentAmount:Oe,needsSwap:ct,exactOutputSwap:Te,adjustable:y==="adjustable",maxAmount:v,onAmountChange:mt}),pe&&l(ns,{fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:L,cardBorder:ee,resolvedDark:S,darkCardBorder:P.cardBorder,primaryColor:W,feePreview:Ye,isLoading:xn,errorText:At,directExecutionFeeNote:st}),K&&l(wo,{variant:"error",palette:z,fontFamily:N,style:{marginBottom:"12px"},children:K}),l(Lt,{variant:"outline",fullWidth:!0,onClick:Xe,disabled:!Cn,loading:Ke,dark:S,styles:{...b,button:{...b?.button,backgroundColor:W}},children:rt}),qe&&ln&&l("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:S?P.shell:"white",borderRadius:S?"12px":"6px",padding:"16px 0"},children:l(js,{type:"payment",isOpen:qe.status!=="processing",isProcessing:Ke||qe.status==="processing",closeOnComplete:!1,chainName:fn(G),explorerUrl:ho(G,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Vt(!1),we(null),Xe()},onNewTx:on,onClose:()=>{Vt(!1),we(null)},onComplete:on,results:ye,styles:b,dark:S})})]})})}return l(Ln,{isOpen:e,onClose:t,title:Wo,subtitle:ko,dark:S,styles:b,theme:I,closeOnBackdropClick:n,children:x("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[l("div",{style:{marginBottom:"16px"},children:l(Fo,{assets:nt,selectedAsset:O||void 0,onAssetSelect:ht,onAmountChange:wt,disabled:Ke||Be==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:Q,styles:b,dark:H,resolveMaxAmount:We,maxAmount:He>0?po(He,O?.asset.decimals??o.decimals):void 0})}),O?.asset&&!Nt&&l(Pa,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:W,fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:L,cardBorder:ee,dark:S,isQuoting:St,quoteError:dn,estimatedOutput:tn}),pe&&l(ns,{fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:L,cardBorder:ee,resolvedDark:S,darkCardBorder:P.cardBorder,primaryColor:W,feePreview:Ye,isLoading:xn,errorText:At,directExecutionFeeNote:st}),Be!=="idle"&&x("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Be==="success"?L:Be==="error"?z.errorBg:L,border:`1px solid ${Be==="success"?ee:Be==="error"?z.errorBorder:ee}`},children:[x("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Be==="success"?l("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:l("path",{d:"M5 13l4 4L19 7",stroke:z.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Be==="error"?l("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:l("path",{d:"M18 6L6 18M6 6l12 12",stroke:z.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):l(qn,{size:14,color:W}),l("span",{style:{fontSize:"13px",fontWeight:500,color:Be==="success"?U:Be==="error"?z.errorText:U,fontFamily:N,flex:1},children:Be==="success"?"Deposit confirmed":Be==="error"?ot||"Transaction failed":ni[Be]||ot}),Be==="success"&&yn&&l("a",{href:`${co}/tx/${yn}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:W,fontFamily:N,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Be==="error"&&l("button",{onClick:()=>{en("idle"),an(null),setTimeout(Ft,50)},style:{background:"none",border:"none",fontSize:"12px",color:W,fontFamily:N,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),to>=0&&Be!=="success"&&Be!=="error"&&l("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${Z}22`,overflow:"hidden"},children:l("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:W,transformOrigin:"left center",transform:`scaleX(${(to+1)/oi.length})`,transition:"transform 400ms ease"}})})]}),_t&&Be==="idle"&&l(wo,{variant:"error",palette:z,fontFamily:N,style:{marginBottom:"16px"},children:_t}),l(Lt,{variant:"outline",fullWidth:!0,disabled:Nn,onClick:sn,theme:I,dark:S,styles:{...b,button:{...b?.button,backgroundColor:W}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:D},children:Ne})]})})},Ed=()=>{const[e,t]=R("0"),[n,o]=R(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:n,setSelectedAsset:o}};function Fd(e,t=0){const[n,o]=R(t),s=e[n]??e[0],r=oe(()=>s?BigInt(Math.round(s.months*30*24*3600)):0n,[s?.months]);return{selectedDurationIdx:n,setSelectedDurationIdx:o,selectedDuration:s,durationSeconds:r}}function Bd(){const{actions:e,isReady:t,isAuthenticated:n}=Pn(),o=rn(Zt)?.embeddedWalletAddress,s=le(!1),r=le(0),a=le(null),c=le(e),[d,i]=R(0);c.current=e,X(()=>{s.current=!1,r.current=0,a.current&&(clearTimeout(a.current),a.current=null)},[o]),X(()=>{if(!o||!t||!n||s.current)return;s.current=!0;let p=!1;return(async()=>{await Sn(2e3);try{await hi(o,c.current.signMessage),r.current=0}catch(u){console.warn("[SmartWallet] Registration failed:",u),s.current=!1,!p&&r.current<3&&(r.current+=1,a.current=setTimeout(()=>{i(m=>m+1)},5e3))}})(),()=>{p=!0,a.current&&(clearTimeout(a.current),a.current=null)}},[o,t,n,d])}function Do(e){try{return Fi(e)}catch{throw new Ae("ROUTE_TOKEN_NOT_FOUND",`Token "${e[0]}" not found on chain ${e[1]} in the token registry.`,{symbol:e[0],chainId:e[1]})}}function Td(e,t){if(e[0].toUpperCase()===t[0].toUpperCase()&&e[1]===t[1])return!0;let n,o;try{n=Do(e),o=Do(t)}catch{return!1}const s=new Set(pr(o.address).map(r=>r.toLowerCase()));return s.add(o.address.toLowerCase()),s.has(n.address.toLowerCase())}function Md(){const e=[];for(const t of Object.keys(Bi).map(Number))for(const n of dr(t))e.push([n.symbol,t]);return e}async function Rd(e){const{action:t,inputToken:n,inputAmount:o,registry:s,userAddress:r,slippage:a,intermediaryCandidates:c}=e;if(t.calls.length===0)throw new Ae("INVALID_PARAMS","buildIntent: action.calls must not be empty.",{action:t});if(o<=0n)throw new Ae("INVALID_PARAMS","buildIntent: inputAmount must be greater than zero.",{inputAmount:o.toString()});const d=t.supportedInputTokens??Md();if(!d.some(y=>Td(n,y))){const y=d.map(([C,v])=>`${C} (chain ${v})`).join(", ");throw new Ae("ROUTE_UNSUPPORTED_INPUT",`Input token "${n[0]}" on chain ${n[1]} is not in the action's supported input tokens. Supported: ${y}.`,{inputToken:{symbol:n[0],chainId:n[1]},supportedInputTokens:d})}const i=Do(n),p=Do(t.outputToken),u=ca({sourceAsset:i,outputAsset:p,sourceChainId:i.chainId,destinationChainId:t.chainId,intermediaryCandidates:c}),{chainBatches:m,solverFrontToken:h,solverFrontAmount:f,resolvedSwaps:g}=await da({route:u,sourceAmount:o,userAddress:r,registry:s,actionCalls:t.calls,slippage:a});return{chainBatches:m,route:u,resolvedSwaps:g,resolvedInputToken:i,resolvedOutputToken:p,solverFrontToken:h,solverFrontAmount:f}}const Dd=[0n,1n,30n],Wd=new Set(["ABORT","CONCURRENT_EXECUTION","WALLET_DISCONNECTED","WALLET_REJECTED","NO_VENUE_FOR_CHAIN"]);function si(e,t){return t===0n?e:e*(1000n-t)/1000n}async function Nd(e,t){const{chainId:n,swapCalls:o,quoteAmountOut:s,buildActionCalls:r,tokenAddress:a,tokenTransferAmount:c,onProgress:d,signal:i,options:p,buffers:u=Dd}=t;for(let m=0;m<u.length;m++){const h=u[m],f=si(s,h),g=r(f),y=[{chainId:n,calls:[...o,...g]}];try{return await e(y,a,c,d,i,p)}catch(C){const v=typeof C?.message=="string"?C.message:String(C?.message??"");if(lr(C)&&Wd.has(C.code)||C.name==="AbortError"||i?.aborted||v.includes("User rejected")||v.includes("User denied")||C.code===4001||m>=u.length-1)throw C;const T=Number(u[m+1])/10;console.warn(`[SwapThenAction] Action attempt ${m+1} failed (buffer ${Number(h)/10}%), retrying with ${T}% buffer...`,C.message),d?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${T}% buffer)...`})}}throw new Ae("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:u.length,chainId:n})}Wi();export{pd as AccountDisplay,Ps as AddFundsLink,Yr as CheckIcon,$n as ChevronIcon,go as CloseIcon,Co as DetailRow,tu as NATIVE_TOKEN_ADDRESS,Hs as ProviderLogin,tr as SATSUMA_CITREA_CONFIG,nu as SPICENET_NATIVE_CHAIN_ID,ou as SPICE_COMBINED_FEE_RECIPIENT,su as SPICE_GAS_FEE_RECIPIENT,ru as SPICE_PLATFORM_FEE_RECIPIENT,au as SPICE_SOLVER_ADDRESS,Cs as SearchInput,fc as SelectChainModal,pc as SpiceDeposit,Xd as SpiceFlowProvider,Zt as SpiceFlowProviderContext,ya as SpiceLock,ya as SpiceLockModal,Sd as SpiceSupply,Bc as SpiceWithdraw,Ae as SpiceflowError,qn as Spinner,wo as StatusBanner,Xa as UNIV3_BASE_CONFIG,si as applyBuffer,iu as applySlippage,Bo as areEquivalentOnChains,Gd as buildDarkPalette,Rd as buildIntent,Jd as buildLightPalette,Aa as buildPayChainBatches,da as buildRoutedBatches,Sa as buildSupplyChainBatches,lu as buildUniV3SwapCalls,Ka as create1inchVenue,_a as createExactOutputRegistry,$a as createLiquidityRegistry,Ga as createSatsumaVenue,mn as duration,Gt as easing,Ba as estimateFeePreview,Ea as estimateRequiredGrossFunding,Fa as estimateSupplyMaxAmount,_s as executeDirectExternalAction,Na as executeNon7702Pay,Wa as executeNon7702Supply,Ua as executePay,Da as executeSupply,Nd as executeSwapThenAction,jn as findEquivalentOnChain,qs as findTokenOnChain,gr as font,qo as getAssetChainTokenCandidates,Va as getBestUniV3Quote,Ee as getChainConfig,cu as getChainIdsByNetwork,fn as getChainName,du as getEscrowContractAddress,Qa as getUniV3Quote,uu as isNativeToken,lr as isSpiceflowError,pu as isSpicenetChainId,Oa as isSupportedSupplyAsset,qa as isSwapIntent,fu as normalizeNativeTokenAddress,ws as radius,vt as relayerService,Dn as resolveAssetTokenAddressOnChain,Rr as resolveFundedToken,Id as resolveInputSupplySwapQuote,ca as resolveRoute,$d as resolveTheme,Do as resolveTokenRef,Wn as scaleTokenAmount,hu as spicenetAbi,mu as spicenetWithdrawalAbi,An as transition,Ed as useAssetInput,_d as useIsUserWhitelisted,Fd as useLockDuration,Bd as useSmartWallet,To as useSpiceAssets,Bt as useSpiceBrand,bo as useSpiceExecution,xa as useSpicePendingDeposits,ja as useSupplyAssets,ti as useSupplyQuote,Pn as useWallet,ro as z};
|
|
108
|
+
`})]}),document.body):null;return x(vn,{children:[Ut,nt,E&&mr.createPortal(l(Jr,{isOpen:!0,onClose:V,supportedChains:[E.chainId],escrowOnly:!0,escrowTokenAddress:E.tokenAddress,escrowAmount:E.amount,escrowTokenDecimals:E.tokenDecimals,escrowTokenSymbol:E.tokenSymbol,styles:d,onDepositSuccess:_}),document.body)]})},fd="0xa9059cbb";function Ca(e,t,n){return Ue(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:Tt({abi:Fe,functionName:"transfer",args:[n,t]})}}function va(e,t,n){return{chainId:n,calls:[Ca(e,t,hn(n))]}}function ka(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function Ia(e,t,n,o){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(fd)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function ls(e,t,n,o){if(!t)return[e];const s=await t({...n,requestTimestampMs:o});return s?[s,e]:[e]}function Mo(e){return e.filter(t=>t.domain!=="spicenet")}function cs(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:It(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function Wn(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return(e+o-1n)/o}async function Aa(e,t){const{currentPaymentAmount:n,destinationToken:o,embeddedWalletAddress:s,providerEmbeddedAddress:r,address:a,isNon7702:c,isPayMode:d,resolvedChainId:i,buildActionCalls:p,feeExecutionMode:u,buildSpicenetBatch:m,selectedAsset:h,needsSwap:f,exactOutputSwap:g,resolvedTokenIn:y,requestTimestampMs:C}=e,v=ze(n,o.decimals),T=t?.actionAmountOverride??v,b=s||r||(c?void 0:a);if(!b)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:b,chainId:i,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??v,netAmount:T,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},B=p(T,w),E={chainId:i,calls:B},M=!d&&!c?!0:h?.asset?._source==="spice",F=ka(h??null,c,i),k=M||c||F,A=(S,W)=>({token:S,from:c?"solver":"escrow",to:b,amount:W}),I=(S,W,P)=>F?[va(S,W,i),...P]:P;if(v===0n)return[E];if(f&&g){const S=y??Dn(h.asset,i)??h.asset.address,W=t?.fundingAmountOverride??g.amountInMax,P=k?[A(S,W)]:[],z={to:S,value:0n,data:Tt({abi:Fe,functionName:"approve",args:[g.calls[0]?.to,g.amountInMax]})},N={chainId:i,calls:[z,...g.calls,...B],tokenTransfers:[...P,...E.tokenTransfers??[]]};if(!k)return[N];const D=await ls(N,m,{userAddress:b,destinationChainId:i,deliveryToken:S,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:cs(N),sourceAsset:h.asset},C);return I(S,W,D)}if(k){const S=y??Dn(h.asset,i)??o.address;if(F&&S.toLowerCase()===o.address.toLowerCase())return[E];const W=t?.fundingAmountOverride??v,P={...E,tokenTransfers:[A(S,W),...E.tokenTransfers??[]]},z=await ls(P,m,{userAddress:b,destinationChainId:i,deliveryToken:S,deliveryAmount:W,deliveryRecipient:b,deliveryTransfers:cs(P),sourceAsset:h.asset},C);return I(S,W,z)}return[E]}async function Sa(e,t){const{selectedAsset:n,embeddedWalletAddress:o,externalWalletAddress:s,recipient:r,resolvedChainId:a,destinationToken:c,buildActionCalls:d,feeExecutionMode:i,buildSpicenetBatch:p,isPayMode:u,isNon7702:m,needsSwap:h,resolvedSwap:f,quoteAmountOut:g,resolvedTokenIn:y,requestTimestampMs:C}=e,v=f?.amountOutMinimum??g;if(!n?.asset||!o)return[];const T=r??(m?s:o);if(!T)return[];const b=t?.fundingAmountOverride??t?.actionAmountOverride??ze(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??b,B=t?.sourceFundingAmountOverride??b,E=t?.deliveryAmountOverride??w,M=t?.withdrawalAmountOverride??E,F=t?.actionAmountOverride??b,k={userAddress:T,chainId:a,destinationToken:c.address,feeToken:i==="user-transfer"&&h&&y?y:c.address,grossAmount:w,netAmount:F,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:i,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},A=d(F,k),I=n.asset?._source==="wallet";if(!u&&m&&I&&n.asset.chainId===a){if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!f||v===null)throw new Error("Swap quote not available yet")}if(h&&f&&v){const U=d(t?.actionAmountOverride??v,{...k,netAmount:t?.actionAmountOverride??v}),{feeCall:Z,remainingCalls:fe}=Ia(U,i,h,k.feeToken);return[{chainId:a,calls:[...Z?[Z]:[],...f.calls,...fe]}]}return[{chainId:a,calls:A}]}if(!u&&!m&&I&&n.asset.chainId!==a)throw new Error("Cross-chain wallet supplies require external wallet mode");const S=!u&&!m?n.asset?._source!=="wallet":n.asset?._source==="spice",W=m&&I,P=ka(n,m,a);if(!(S||W||P))return[{chainId:a,calls:A}];const z=P?va(y??It(n.asset.address),B,a):W&&n.asset.chainId!==a?{chainId:n.asset.chainId,calls:[Ca(It(n.asset.address),B,hn(n.asset.chainId))]}:null,N=(U,Z)=>({token:U,from:W?"solver":"escrow",to:o,amount:Z}),D=(U,Z)=>W?[{token:U,from:"escrow",to:Ii,amount:Z}]:[];if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!f||v===null)throw new Error("Swap quote not available yet")}if(h&&f&&v&&y){const U=d(t?.actionAmountOverride??v,{...k,netAmount:t?.actionAmountOverride??v}),{feeCall:Z,remainingCalls:fe}=Ia(U,i,h,k.feeToken),Q={chainId:a,calls:[...Z?[Z]:[],...f.calls,...fe],tokenTransfers:[...D(y,M),N(y,E)]},G=await ls(Q,p,{userAddress:o,destinationChainId:a,deliveryToken:y,deliveryAmount:E,withdrawalAmount:M,deliveryRecipient:o,deliveryTransfers:cs(Q),sourceAsset:n.asset},C);return z?[z,...G]:G}const H=y??Dn(n.asset,a)??c.address,L={chainId:a,calls:A,tokenTransfers:[...D(H,M),N(H,E)]},ee=await ls(L,p,{userAddress:o,destinationChainId:a,deliveryToken:H,deliveryAmount:E,withdrawalAmount:M,deliveryRecipient:o,deliveryTransfers:cs(L),sourceAsset:n.asset},C);return z?[z,...ee]:ee}async function Ea(e,t,n,o,s){let r=e;for(let a=0;a<4;a++){const c=await t(r),d=await o(c,n,r,s),i=Dl(d);if(i===null||i>=e)return r;const p=r-i,u=e+p;if(u<=r)return r;r=u}return r}function hd(e,t,n,o){if(e<=0n)return 0n;const s=e-t;if(s<=0n)return 0n;const r=o+n;return r<=0n?s:s*o/r}async function Fa(e){const{asset:t,isPayMode:n,isNon7702:o,needsSwap:s,isQuoting:r,embeddedWalletAddress:a,buildSupplyChainBatches:c,estimate:d,executionTokenAddress:i,feeExecutionMode:p}=e;if(n||o||s||r||!a||t.balance<=0n)return null;const u=a,m=await c({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(m.length===0)return null;const h=m.some(T=>T.tokenTransfers?.length),f=await d(m,i,t.balance,h?{userOverride:u,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:u,feeExecutionMode:p}:{userOverride:u}),g=Jn(f,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),y=g?Wn(g.gasFee,g.decimals,t.decimals):0n,C=g?Wn(g.spicenetFee,g.decimals,t.decimals):0n,v=hd(t.balance,y,C,t.balance);return v>0n?zr(v,t.decimals):null}async function Ba(e){const{selectedAsset:t,isPayMode:n,parsedAmount:o,needsSwap:s,exactOutputSwap:r,isNon7702:a,isSourceDestToken:c,currentPaymentAmount:d,destinationToken:i,feeExecutionMode:p,resolvedTokenIn:u,embeddedWalletAddress:m,providerEmbeddedAddress:h,resolvedChainId:f,isConnected:g,address:y,ready:C,authenticated:v,isDirect:T,resolvedSwap:b,isQuoting:w,executionTokenAddress:B,buildPayChainBatches:E,buildSupplyChainBatches:M,estimate:F,estimateRequiredGrossFunding:k}=e;if(!t?.asset)return null;if(n){if(o<=0||s&&!r||c)return null;const D=ze(d,i.decimals),H=u||Dn(t.asset,f)||t.asset.address||i.address,L={chainId:f,tokenAddress:H,symbol:Qt(H,f)?.symbol??t.asset.symbol,decimals:Qt(H,f)?.decimals??t.asset.decimals};if(a){const G=m||h;if(!G)return null;const de=G,ve=s?r?.amountInMax??0n:D;if(ve===0n)return null;const ce=await k(ve,Se=>E({fundingAmountOverride:Se}).then($=>En(Mo($),de)),H,{userOverride:G,useCustomTransfers:!0}),he=En(Mo(await E({fundingAmountOverride:ce})),de),ue=await F(he,H,ce,{userOverride:G,useCustomTransfers:!0,feeExecutionMode:p});return Jn(ue,L)}if(!g||!y||!C||!v)return null;const ee=m||h||y,U=s?r?.amountInMax??0n:D;if(U===0n)return null;const Z=await k(U,G=>E({fundingAmountOverride:G}).then(de=>En(Mo(de),ee)),H,{useCustomTransfers:!0});let fe=En(Mo(await E({fundingAmountOverride:Z})),ee);const Q=await F(fe,H,Z,{useCustomTransfers:!0,feeExecutionMode:p});return Jn(Q,L)}if(o<=0||!m)return null;const A=m||h;if(!(!n&&!a&&t.asset?._source==="wallet"&&t.asset.chainId!==f)&&!T&&!b&&!w||w)return null;const I=ze(t.amount,t.asset.decimals),S=await M();if(S.length===0)return null;const W=a&&t.asset?._source==="wallet"&&t.asset.chainId===f,P={chainId:f,tokenAddress:B,symbol:Qt(B,f)?.symbol??i.symbol,decimals:Qt(B,f)?.decimals??i.decimals};if(W){const D=await vt.estimateBatchGas({user:A,outputToken:B,stepIndex:0,chainBatches:S}),H=Go(I,10n),L=H+D.gasFee;return{...P,grossAmount:I+L,netAmount:I,totalFee:L,gasFee:D.gasFee,spicenetFee:H,bridgeFee:0n,gasQuoteSource:D.gasQuoteSource}}const z=S.some(D=>D.tokenTransfers?.length),N=await F(S,B,I,z?{userOverride:A,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:A,feeExecutionMode:p}:{userOverride:A});return Jn(N,P)}const md=10n;function Ta(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const o=Dn(n,e.resolvedChainId);if(!o||!Ie(o,e.executionTokenAddress))return;const s=Qt(e.executionTokenAddress,e.resolvedChainId),r=Wn(t,s?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const a=pt(r,n.decimals),c=pt(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${a} ${n.symbol}; available ${c} ${n.symbol}.`)}function Js(e){const t=Qt(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Ro(e,t,n){const o=Jn(e,Js(t));if(!o)return;const s=Go(n,md),r=o.bridgeFee??0n,a=s+o.gasFee+r;return{grossAmount:n+a,netAmount:n,combinedFeeAmount:a,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:s,gasFee:o.gasFee,bridgeFee:r}}}function Ma(e,t,n){let o=0n,s=0n;const r=n.toLowerCase();for(const a of e)if(a.chainId===t){for(const c of a.calls??[])if(c.to.toLowerCase()===r)try{const d=Oo({abi:Fe,data:c.data});if(d.functionName!=="transfer")continue;const i=d.args[0].toLowerCase(),p=d.args[1];i===so.toLowerCase()?o+=p:i===In.toLowerCase()&&(s+=p)}catch{continue}}return{spicenetFee:o,gasFee:s}}function $s(e,t,n){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,s=Ma(e,t.resolvedChainId,o);return s.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||s.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Gn(s.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Gn(s.gasFee,n.feeBreakdown.gasFee,100n)}function Ra(e,t){return e?Gn(e.grossAmount,t.grossAmount,100n)&&Gn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Gn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Gn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function Da(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const o=await _s(e);e.ui.setTxHash(o??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const o=new AbortController;e.refs.abortControllerRef.current=o,await Wa(e,o.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(o){const s=o instanceof Error?o:new Error(String(o));if(s.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(s)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=ze(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=n;let s=await e.execution.buildSupplyChainBatches();const r=e.selectedAsset.asset?._source==="wallet",a=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!r&&!s.some(h=>Ao(h.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const c=s.some(h=>h.tokenTransfers?.length)?{userOverride:a,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:a,feeExecutionMode:e.feeExecutionMode}:{userOverride:a};let d=n;const i=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!i?o:void 0;let u;for(let h=0;h<4;h+=1){const f=await e.execution.estimate(s,e.executionTokenAddress,d,c),g=Jn(f,Js(e));u=e.feeExecutionMode==="user-transfer"&&g?Ro(f,e,o):void 0;const y=u?.grossAmount??g?.grossAmount??d;if(y===d){d=y;break}d=y,s=await e.execution.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u})}e.feeExecutionMode==="user-transfer"&&(Ta(e,d),s=await e.execution.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u}));let m=u;await e.execution.execute(s,e.executionTokenAddress,d,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:h,chainBatches:f})=>{const g=Ro(h,e,o);if(!g)return null;const y=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;Ma(f,e.resolvedChainId,y);const C=Ra(m,g),v=$s(f,e,g);return C||v?null:(m=g,e.execution.buildSupplyChainBatches({fundingAmountOverride:g.grossAmount,actionAmountOverride:p,actionContextOverride:g}))}}:c),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const o=n instanceof Error?n:new Error(String(n));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const s=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(s),e.ui.setError(s),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function Wa(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const o=e.selectedAsset.asset,s=ze(e.selectedAsset.amount,o.decimals),r=s,a=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let c=await e.execution.buildSupplyChainBatches();const d={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let i=s;const p=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,u=e.feeExecutionMode==="user-transfer"&&!p?r:void 0;let m;if(a){const k=await vt.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:c}),A=Go(s,10n),I=A+k.gasFee;i=s+I,e.feeExecutionMode==="user-transfer"&&(m={grossAmount:i,netAmount:r,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:A,gasFee:k.gasFee,bridgeFee:0n}})}else for(let k=0;k<4;k+=1){const A=await e.execution.estimate(c,e.executionTokenAddress,0n,d),I=e.feeExecutionMode==="user-transfer"?Ro(A,e,r):void 0,S=Jn(A,Js(e)),W=I?.grossAmount??(S?S.grossAmount>s?S.grossAmount:s:i);if(m=I,W===i){i=W;break}i=W;const P=Qt(e.executionTokenAddress,e.resolvedChainId),z=Wn(i,P?.decimals??e.destinationToken.decimals,o.decimals);c=await e.execution.buildSupplyChainBatches({fundingAmountOverride:i,sourceFundingAmountOverride:z,withdrawalAmountOverride:i,actionAmountOverride:u,actionContextOverride:I})}const h=Qt(e.executionTokenAddress,e.resolvedChainId);let f=a?i:Wn(i,h?.decimals??e.destinationToken.decimals,o.decimals);Ta(e,i),c=await e.execution.buildSupplyChainBatches({fundingAmountOverride:i,sourceFundingAmountOverride:f,withdrawalAmountOverride:i,actionAmountOverride:u,actionContextOverride:m});const g=o.chainId,y=n,C=await e.externalWallet.getEthereumProvider();await vo(C,g,()=>e.ui.setStatusMsg("Switching source network..."));const v=Ee(g),T=Yn({account:e.externalWalletAddress,chain:v?.viemChain,transport:Kn(C)}),b=It(o.address),w=o.isNative||Ue(b),B=gt(g),E=k=>ha({extWc:T,sourceClient:B,recipient:y,tokenAddr:b,isNative:w,amount:k,viemChain:v?.viemChain});e.ui.setStatusMsg("Funding embedded wallet..."),await E(f);let M=f;if(e.feeExecutionMode==="user-transfer")for(let k=0;k<4;k+=1){const A=await e.execution.estimate(c,e.executionTokenAddress,0n,d),I=Ro(A,e,r);if(!I)break;const S=a?I.grossAmount:Wn(I.grossAmount,h?.decimals??e.destinationToken.decimals,o.decimals);if(S>M&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await E(S-M),M=S),m=I,i=I.grossAmount,f=S,c=await e.execution.buildSupplyChainBatches({fundingAmountOverride:i,sourceFundingAmountOverride:f,withdrawalAmountOverride:i,actionAmountOverride:u,actionContextOverride:I}),$s(c,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let F=m;await e.execution.execute(c,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:k,chainBatches:A})=>{const I=Ro(k,e,r);if(!I)return null;const S=Ra(F,I),W=$s(A,e,I);if(S||W)return null;if(I.grossAmount>i)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");F=I;const P=a?I.grossAmount:Wn(I.grossAmount,h?.decimals??e.destinationToken.decimals,o.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:P,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:u,actionContextOverride:I})}}:d)}async function _s(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,o=e.activeSignerAddress??e.externalWalletAddress;if(!o||!n)throw new Error("Please connect your wallet to continue");const s=ze(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),r={userAddress:o,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},a=e.buildActionCalls(s,r);if(a.length===0)throw new Error("No action calls configured");const c=await n.getEthereumProvider();await vo(c,e.resolvedChainId);const d=Ee(e.resolvedChainId),i=Yn({account:o,chain:d?.viemChain,transport:Kn(c)}),p=gt(e.resolvedChainId);let u;for(const m of a){const h=await i.sendTransaction({to:m.to,data:m.data,value:m.value,chain:d?.viemChain});if((await p.waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");u=h}return u}async function Na(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,o=n.chainId,s=ze(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?s:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const a=e.resolvedTokenIn||e.selectedAsset.asset.address,c={userOverride:t,useCustomTransfers:!0},d=await e.execution.estimateRequiredGrossFunding(r,C=>e.execution.buildPayChainBatches({fundingAmountOverride:C}),a,c),i=hn(o),p=await e.externalWallet.getEthereumProvider();await vo(p,o);const u=Ee(o),m=Yn({account:e.externalWalletAddress,chain:u?.viemChain,transport:Kn(p)}),h=It(n.address),f=n.isNative||Ue(h)?await m.sendTransaction({to:i,value:d,chain:u?.viemChain}):await m.sendTransaction({to:h,data:Tt({abi:Fe,functionName:"transfer",args:[i,d]}),chain:u?.viemChain});if((await gt(o).waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const g=await e.execution.buildPayChainBatches({fundingAmountOverride:d}),y=g.some(C=>C.tokenTransfers?.length);return await e.execution.execute(g,a,d,C=>{C.txHash&&(e.ui.setPaymentResult(v=>({...v??{status:"processing"},txHash:C.txHash})),e.ui.setTxHash(C.txHash))},void 0,y?c:{userOverride:t})}async function Ua(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let o;if(e.isSourceDestToken||e.parsedAmount===0)o=await _s(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,r=ze(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const c=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!c)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const d=e.resolvedTokenIn||s.address,i=await e.execution.estimateRequiredGrossFunding(a,m=>e.execution.buildPayChainBatches({fundingAmountOverride:m}),d,{userOverride:c,useCustomTransfers:!0}),p=await e.execution.buildPayChainBatches({fundingAmountOverride:i}),u=await e.onPayExecute({asset:s,amount:e.currentPaymentAmount,amountWei:r,destinationToken:e.destinationToken,chainBatches:p,requiredNetFunding:a,grossFundingAmount:i,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:d,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});u&&(e.ui.setTxHash(u),e.ui.setPaymentResult(m=>({...m??{status:"processing"},txHash:u}))),o=u||void 0}else o=await Na(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||o||""}))}catch(o){const s=kn(o,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(o instanceof Error?o:new Error(s))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=ze(e.currentPaymentAmount,e.destinationToken.decimals),o={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const y=await e.execution.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),C=await e.execution.execute(y,e.destinationToken.address,0n,v=>{v.txHash&&(e.ui.setPaymentResult(T=>({...T,txHash:v.txHash})),e.ui.setTxHash(v.txHash))},void 0,o);e.ui.setPaymentResult(v=>({status:"success",txHash:v?.txHash||C}));return}const s=e.selectedAsset?.asset;if(!s)throw new Error("Select a payment source");const r=e.resolvedTokenIn||s.address||e.destinationToken.address,a=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,c=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,d=(y,C,v)=>{const T=Mo(y),b=E=>(E.tokenTransfers??[]).some(M=>M.from==="escrow"),w=T.filter(E=>!b(E)),B=T.filter(b);return[...w,...En(B,c,C,v)]},i=await e.execution.estimateRequiredGrossFunding(a,y=>e.execution.buildPayChainBatches({fundingAmountOverride:y}).then(C=>d(C)),r,o);let p=i,u=d(await e.execution.buildPayChainBatches({fundingAmountOverride:i}));const m=await e.execution.estimate(u,r,i,o),h=Jn(m,{chainId:e.resolvedChainId,tokenAddress:r,symbol:Qt(r,e.resolvedChainId)?.symbol??s.symbol,decimals:Qt(r,e.resolvedChainId)?.decimals??s.decimals})?.grossAmount??i;h!==i&&(p=h),u=d(await e.execution.buildPayChainBatches({fundingAmountOverride:p}),m,{payoutAlreadyGross:!0});const f=u.some(y=>y.tokenTransfers?.length),g=await e.execution.execute(u,r,f?p:0n,y=>{y.txHash&&(e.ui.setPaymentResult(C=>({...C,txHash:y.txHash})),e.ui.setTxHash(y.txHash))},void 0,o);e.ui.setPaymentResult(y=>({status:"success",txHash:y?.txHash||g}))}catch(n){const o=kn(n,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(n instanceof Error?n:new Error(o))}finally{e.ui.setIsExecuting(!1)}}const gd=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:c,cardBg:d,cardBorder:i,dk:p,dark:u,isQuoting:m,quoteError:h,estimatedOutput:f,paymentAmount:g,needsSwap:y,exactOutputSwap:C,adjustable:v=!1,maxAmount:T,onAmountChange:b})=>e==="supply"?x("div",{style:{backgroundColor:d,border:`1px solid ${i}`,borderRadius:u?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[x("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[x("div",{style:{minWidth:0},children:[l("span",{style:{fontFamily:r,fontSize:"17px",fontWeight:500,color:u?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),l("div",{style:{fontSize:"12px",fontWeight:500,color:c,fontFamily:r,marginTop:"10px"},children:"Net amount after swap and fees"})]}),x("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${i}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[l(za,{symbol:t,logoURI:n,primaryColor:s,size:24}),l("span",{style:{fontSize:"16px",fontWeight:500,color:u?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:r,letterSpacing:0},children:t})]})]}),l("div",{style:{textAlign:"right",minWidth:0},children:m?l("span",{style:{fontSize:"18px",color:c,fontFamily:r},children:"Quoting..."}):h?l("span",{style:{fontSize:"13px",color:u?"#f87171":"#dc2626",fontFamily:r},children:"Quote failed"}):f?l(ao,{value:f,title:f,fontFamily:r,color:a,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):l("span",{style:{fontSize:"20px",color:c,fontFamily:r},children:"\u2014"})})]}):l(yd,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:c,cardBg:d,cardBorder:i,dk:p,dark:u,paymentAmount:g||"0",needsSwap:y,exactOutputSwap:C,isQuoting:m,adjustable:v,maxAmount:T,onAmountChange:b}),Pa=pn(gd),za=({symbol:e,logoURI:t,primaryColor:n,size:o})=>t?l("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):l("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),yd=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:o,fontFamily:s,textPrimary:r,textSecondary:a,cardBg:c,cardBorder:d,dk:i,dark:p,paymentAmount:u,needsSwap:m,exactOutputSwap:h,isQuoting:f,adjustable:g,maxAmount:y,onAmountChange:C})=>{const v='"IBM Plex Mono", monospace',T=parseFloat(u||"0"),b=y?parseFloat(y):0,[w,B]=R(u||""),E=le(null),[M,F]=R(null),[k,A]=R(null);X(()=>{g||B(u||"")},[u,g]);const I=P=>{let z=P;z.startsWith(".")&&(z="0"+z);const N=uo(z);let D=N;y&&parseFloat(N)>parseFloat(y)&&(D=y),B(D),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>C?.(D),300)},S=P=>{if(!b)return;if(P===100){B(y||b.toString()),E.current&&clearTimeout(E.current),C?.(y||b.toString());return}const z=10**n,N=Math.floor(b*P/100*z)/z,D=po(N,n);B(D),E.current&&clearTimeout(E.current),C?.(D)},W=b>0?parseFloat(w||"0")/b*100:0;return X(()=>()=>{E.current&&clearTimeout(E.current)},[]),x("div",{style:{backgroundColor:c,border:`1px solid ${d}`,borderRadius:p?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[x("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[x("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[l(za,{symbol:e,logoURI:t,primaryColor:o,size:32}),x("div",{children:[l("span",{style:{fontSize:"14px",fontWeight:600,color:r,fontFamily:s},children:"Payment"}),l("div",{style:{fontSize:"12px",color:a,fontFamily:s,marginTop:"2px"},children:e})]})]}),x("div",{style:{textAlign:"right"},children:[g?l(ao,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:P=>I(P.target.value),placeholder:"0.0",fontFamily:v,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):l(ao,{element:"div",value:T>0?u:"0.00",title:T>0?u:"0.00",fontFamily:v,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),l("div",{style:{fontSize:"12px",color:a,fontFamily:v,marginTop:"2px"},children:e}),g&&b>0&&l("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((P,z)=>{const N=Math.abs(W-P)<1,D=z===4,H=P/100,L=M===P,ee=k===P;return l("button",{onClick:()=>S(P),onMouseEnter:()=>F(P),onMouseLeave:()=>{F(null),A(null)},onMouseDown:()=>A(P),onMouseUp:()=>A(null),title:`${P}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:N?1:L?.8:.5,transform:ee?"scale(0.85)":L?"scale(1.15)":"scale(1)",transition:An.interactive},children:x("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[l("circle",{cx:"7",cy:"7",r:"6.84375",fill:D?o:"none",stroke:D?o:p?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!D&&H>0&&l("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${H>.5?1:0} 1 ${7+6.84375*Math.sin(H*2*Math.PI)} ${7-6.84375*Math.cos(H*2*Math.PI)} Z`,fill:p?i?.textSecondary||"#9ca3af":"#3C3E42"})]})},P)})})]})]}),m&&h&&!f&&l("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:p?`1px solid ${i?.cardBorder||d}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:x("span",{style:{fontSize:"11px",color:a,fontFamily:s,opacity:.7},children:["via ",h.venue]})})]})};function La(e,t,n){const o=Ie(e.address,t),s=e.chainId===n,r=e._source==="wallet";return r&&o&&s?0:r&&s?1:!r&&o?2:!r&&s?3:4}function Oa(e,t){return!t||t.length===0||t.some(n=>Ie(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const o=yo(n);return o?t.some(s=>Ie(s,o.address)):!1})}function Ha(e,t,n){let{symbol:o,name:s,logoURI:r}=t;const a=Ie(e.address,n.address)&&e.chainId===n.chainId;a&&n.logoURI&&(r=n.logoURI),a&&!e.configToken&&o==="TOKEN"&&(o=n.symbol,s=n.symbol);const c=parseFloat((Number(t.balance)/Math.pow(10,t.decimals)).toFixed(6));return{address:e.address,name:s,symbol:o,decimals:t.decimals,balance:t.balance,balanceFormatted:c,balanceUsd:0,logoURI:r,isNative:!1,chainId:e.chainId}}function ja(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:o,enabled:s}=e,r=rn(Zt),a=(r?.mode||"7702")!=="7702",c=r?.embeddedWalletAddress,{externalAddress:d,embeddedAddress:i,activeAddress:p}=mo(),u=c||i,{assets:m,refetch:h}=To({address:u,supportedChains:o,enabled:s&&!a&&!!u,refetchInterval:3e4}),f=oe(()=>a?[]:m.filter(F=>Oa(F,n)),[m,n,a]),g=a?p??d:c,y=oe(()=>{const F=new Set,k=[],A=I=>{if(!I)return;const S=I.toLowerCase();F.has(S)||(F.add(S),k.push(kt(I)))};if(A(t.address),n)for(const I of n)A(I);return k},[a,t.address,n]),C=oe(()=>y.map(F=>F.toLowerCase()).sort().join(","),[y]),v=oe(()=>JSON.stringify([...o||[]].sort()),[o]),[T,b]=R([]),w=le(0),B=le(async()=>{}),E=re(async()=>{if(!s||!g||y.length===0){w.current++,b([]);return}const F=++w.current,k=kt(g),A=a?o&&o.length>0?o:[t.chainId]:[t.chainId],I=[];for(const z of y){const N=z.toLowerCase();if(N===Xt)continue;if(N===t.address.toLowerCase()){const H=Ee(t.chainId)?.supportedTokens?.find(L=>Ie(L.address,N));I.push({address:z,chainId:t.chainId,configToken:H?{decimals:H.decimals,symbol:H.symbol,name:H.name,logo:H.logo}:void 0});continue}let D=!1;for(const H of A){const L=Ee(H)?.supportedTokens?.find(ee=>Ie(ee.address,N));if(L){I.push({address:z,chainId:H,configToken:{decimals:L.decimals,symbol:L.symbol,name:L.name,logo:L.logo}}),D=!0;break}}D||I.push({address:z,chainId:t.chainId})}const S=new Map;for(const z of I){const N=S.get(z.chainId)||[];N.push(z),S.set(z.chainId,N)}const W=async(z,N)=>{try{const D=await Zn(z,{address:N.address,abi:Fe,functionName:"balanceOf",args:[k]}),{decimals:H,symbol:L,name:ee,logoURI:U}=await pa(z,N.address,N.configToken);return Ha(N,{decimals:H,symbol:L,name:ee,logoURI:U,balance:D},t)}catch{return null}},P=await Promise.all(Array.from(S.entries()).map(async([z,N])=>{let D;try{D=gt(z)}catch{return[]}const H=[],L=[];for(const U of N){const Z=H.length;H.push({address:U.address,abi:Fe,functionName:"balanceOf",args:[k]}),U.configToken||H.push({address:U.address,abi:Fe,functionName:"decimals"},{address:U.address,abi:Fe,functionName:"symbol"},{address:U.address,abi:Fe,functionName:"name"}),L.push({start:Z,item:U})}let ee=null;try{ee=await D.multicall({contracts:H})}catch{ee=null}return ee?L.map(({start:U,item:Z})=>{const fe=ee[U],Q=fe?.status==="success"?fe.result:0n;let G,de,ve,ce;if(Z.configToken)G=Z.configToken.decimals,de=Z.configToken.symbol,ve=Z.configToken.name,ce=Z.configToken.logo;else{const he=ee[U+1],ue=ee[U+2],Se=ee[U+3];G=he?.status==="success"?Number(he.result):18,de=ue?.status==="success"?ue.result:"TOKEN",ve=Se?.status==="success"?Se.result:de}return Ha(Z,{decimals:G,symbol:de,name:ve,logoURI:ce,balance:Q},t)}):(await Promise.all(N.map(U=>W(D,U)))).filter(U=>U!==null)}));F===w.current&&b(P.flat())},[s,a,g,C,v,t.address,t.chainId,t.symbol,t.logoURI]);X(()=>{B.current=E},[E]),X(()=>{if(!s){b([]);return}B.current();const F=setInterval(()=>{B.current()},15e3);return()=>clearInterval(F)},[s,a,g,C,v,t.address,t.chainId]);const M=re(()=>{E()},[E]);return{displayAssets:oe(()=>{const F=[],k=T.filter(I=>I.balance>0n);for(const I of k)F.push({...I,_source:"wallet"});for(const I of f)F.push({...I,_source:"spice"});const A=t.address.toLowerCase();return F.sort((I,S)=>La(I,A,t.chainId)-La(S,A,t.chainId)),F},[T,f,t.address,t.chainId]),filteredSpiceAssets:f,walletAssets:T,embeddedWalletAddress:u,externalAddress:d,isNon7702:a,refreshSpiceAssets:h,refreshWalletAssets:M}}async function Qa(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:s,chainId:r,config:a}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const c=(await gt(r).simulateContract({address:a.quoterV2,abi:Ai,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,fee:s,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function Va(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>Qa({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const xd=[{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 bd(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:s,chainId:r,config:a}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const c=(await gt(r).simulateContract({address:a.quoterV2,abi:xd,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,fee:s,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function wd(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>bd({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function qa(e){return e.type==="swap"}const er=.02,Cd=[1,8453,42161,10,137,43114,56],vd="https://api.1inch.dev/swap/v6.0";function Ya(e,t){return Ei(e,t)}function Ka(e){const t=e?.baseUrl??vd;return{name:"1inch",chainIds:e?.chainIds??Cd,resolve:async(n,o,s)=>{const r=n.maxSlippage??er,a=r*100,c=Ue(n.tokenIn)?fr:n.tokenIn,d=Ue(n.tokenOut)?fr:n.tokenOut,i=Ue(n.tokenIn);try{const p=new URL(`${t}/${o}/swap`);p.searchParams.set("src",c),p.searchParams.set("dst",d),p.searchParams.set("amount",n.amountIn.toString()),p.searchParams.set("from",s),p.searchParams.set("slippage",a.toString()),p.searchParams.set("disableEstimate","true"),p.searchParams.set("allowPartialFill","false");const u={Accept:"application/json"};e?.apiKey&&(u.Authorization=`Bearer ${e.apiKey}`);const m=await fetch(p.toString(),{headers:u});if(!m.ok)throw new Ae("VENUE_API_ERROR",`[1inchVenue] API returned ${m.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${m.status}`});const h=await m.json();if(!h.dstAmount||!h.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const f=BigInt(h.dstAmount);if(f<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const g=Ya(f,r),y=[];return h.tx.to&&!i&&y.push({to:n.tokenIn,value:0n,data:Tt({abi:Fe,functionName:"approve",args:[h.tx.to,n.amountIn]})}),y.push({to:h.tx.to,value:BigInt(h.tx.value||"0"),data:h.tx.data}),{venue:"1inch",amountOut:f,amountOutMinimum:g,calls:y}}catch(p){if(p instanceof Ae)throw p;const u=p instanceof Error?p.message:String(p);throw new Ae("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${u}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:u})}}}}const Za=[4114,5115],tr={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Xa={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Ga(e){return{name:"satsuma",chainIds:e.chainIds??Za,resolve:async(t,n,o)=>{const s=t.maxSlippage??er,r=Ue(t.tokenIn);let a;try{a=await Va({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const c=Ya(a.amountOut,s),d=[];return r||d.push({to:t.tokenIn,value:0n,data:Tt({abi:Fe,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),d.push({to:e.swapRouter,value:r?t.amountIn:0n,data:Tt({abi:Si,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:a.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:a.amountOut,amountOutMinimum:c,calls:d}}}}function Ja(e){return{name:"satsuma",chainIds:e.chainIds??Za,resolve:async(t,n,o)=>{const s=t.maxSlippage??er,r=Ue(t.tokenIn);let a;try{a=await wd({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const c=BigInt(Math.round(s*1e4)),d=a.amountIn+a.amountIn*c/10000n,i=[];return i.push({to:e.swapRouter,value:r?d:0n,data:Tt({abi:kd,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:a.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:a.amountIn,amountInMax:d,amountOut:t.amountOut,calls:i}}}}const kd=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"exactOutputSingle",outputs:[{name:"amountIn",type:"uint256"}],stateMutability:"payable",type:"function"}];function $a(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Ga(e.satsuma)),t.push(Ka(e?.oneInch));function n(s){return t.find(r=>r.chainIds.includes(s))}async function o(s,r,a){const c=[],d=[];for(const i of s){if(!qa(i)){c.push(i);continue}const p=n(r);if(!p)throw new Ae("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${r}. Cannot resolve swap ${i.tokenIn} \u2192 ${i.tokenOut}.`,{chainId:r,tokenIn:i.tokenIn,tokenOut:i.tokenOut,amountIn:i.amountIn.toString()});const u=await p.resolve(i,r,a);if(!u)throw new Ae("NO_LIQUIDITY",`${p.name} returned no quote for ${i.tokenIn} \u2192 ${i.tokenOut} on chain ${r}.`,{venue:p.name,chainId:r,tokenIn:i.tokenIn,tokenOut:i.tokenOut,amountIn:i.amountIn.toString()});c.push(...u.calls),d.push(u)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:o,getVenueForChain:n,venues:t}}function _a(e){const t=e?.customVenues??[];async function n(o,s,r){const a=t.filter(d=>d.chainIds.includes(s));if(a.length===0)throw new Ae("NO_SWAP_ROUTE",`No exact-output venue supports chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const c=(await Promise.allSettled(a.map(d=>d.resolve(o,s,r)))).filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d!==null);if(c.length===0)throw new Ae("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return c.sort((d,i)=>d.amountIn<i.amountIn?-1:d.amountIn>i.amountIn?1:0),c[0]}return{getQuote:n,venues:t}}const ei=$a({satsuma:tr});async function Id(e){const t=ei.getVenueForChain(e.chainId);if(!t)throw new Error(`No swap venue configured for chain ${e.chainId}.`);const n=await t.resolve({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn},e.chainId,e.recipient);if(!n)throw new Error("No liquidity for this pair.");return n}function ti(e){const{direction:t,selectedAsset:n,destinationToken:o,chainId:s,recipient:r,paymentAmount:a,resolveExactOutputSwap:c}=e,[d,i]=R(!1),[p,u]=R(null),[m,h]=R(null),[f,g]=R(null),[y,C]=R(null),[v,T]=R(null),[b,w]=R(null),[B,E]=R(null),[M,F]=R(null),k=le(null),A=le(null),I=le(0),S=le(new Map),W=oe(()=>ei,[]),P=oe(()=>_a({customVenues:[...c?[{name:"consumer-exact-output",chainIds:[s],resolve:c}]:[],Ja(tr),Ja(Xa)]}),[c,s]),z=oe(()=>{if(!n?.asset)return null;const G=Dn(n.asset,s);if(G)return G;const de=jn(n.asset.address,s,n.asset.chainId);return de?de.address:null},[n?.asset,s]),N=oe(()=>n?.asset?qo(n.asset,s):[],[n?.asset,s]),D=oe(()=>N.map(G=>G.toLowerCase()).join(","),[N]);X(()=>{let G=!1;if(A.current&&(clearTimeout(A.current),A.current=null),!n?.asset||N.length<=1){F(null);return}return A.current=setTimeout(async()=>{const de=t==="input"?n.amount:a||"0";let ve=0n;try{ve=t==="input"?ze(de,n.asset.decimals):0n}catch{ve=0n}try{const ce=await Rr(n.asset,s,{requiredAmount:ve});G||F(ce)}catch{G||F(null)}},400),()=>{G=!0,A.current&&(clearTimeout(A.current),A.current=null)}},[n?.asset,n?.amount,s,N.length,D,t,a]);const H=oe(()=>M??z,[M,z]),L=oe(()=>!n?.asset||!H?[]:[H,...N.filter(G=>G.toLowerCase()!==H.toLowerCase())],[n?.asset,H,N]),ee=oe(()=>!n?.asset||!Bo(n.asset.address,n.asset.chainId,o.address,o.chainId)||!H?!1:Ie(H,o.address),[n,o.address,o.chainId,H]),U=H?Ie(H,o.address):!1,Z=t==="output"&&parseFloat(a||"0")===0,fe=!!n?.asset&&!ee&&!U&&!Z,Q=fe?B??H:H;return X(()=>{k.current&&clearTimeout(k.current);const G=t==="input"?n?.amount:a,de=parseFloat(G||"0");if(!fe||!Number.isFinite(de)||de<=0||!n?.asset||!r||L.length===0){I.current++,h(null),g(null),C(null),T(null),w(null),E(null),u(null),i(!1);return}const ve=n.asset.decimals;let ce;try{ce=t==="input"?ze(n.amount,ve):ze(a||"0",o.decimals)}catch{I.current++,u("Invalid amount"),i(!1);return}const he=++I.current,ue=()=>he!==I.current;i(!0);const Se=t==="output"?150:400;return k.current=setTimeout(async()=>{try{if(t==="input"){const $=W.getVenueForChain(s);if(!$)throw new Error("No swap venue for this chain");let V=null,_=null;for(const xe of L){const q=`${t}:${s}:${xe.toLowerCase()}:${o.address.toLowerCase()}:${ce.toString()}`,te=S.current.get(q);if(te&&te.expiresAt>Date.now()&&te.resolvedSwap){V=te.resolvedSwap,_=xe;break}const ge=await $.resolve({type:"swap",tokenIn:xe,tokenOut:o.address,amountIn:ce},s,r);if(ue())return;if(ge){S.current.set(q,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:ge}),V=ge,_=xe;break}}if(!V||!_)throw new Error("No liquidity for this pair");E(_),w(V.amountOut),C(V),T(null);const ae=parseFloat(pt(V.amountOut,o.decimals));h(ae<.01?ae.toPrecision(4):ae.toLocaleString(void 0,{maximumFractionDigits:6})),g(null),u(null)}else{let $=null,V=null;for(const _ of L){const ae=`${t}:${s}:${_.toLowerCase()}:${o.address.toLowerCase()}:${ce.toString()}`,xe=S.current.get(ae);if(xe&&xe.expiresAt>Date.now()&&xe.exactOutputSwap){$=xe.exactOutputSwap,V=_;break}try{const q=await P.getQuote({tokenIn:_,tokenOut:o.address,amountOut:ce},s,r);if(ue())return;S.current.set(ae,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:q}),$=q,V=_;break}catch{if(ue())return}}if(!$||!V)throw new Error("No liquidity for this pair");E(V),T($),C(null),w(null),g(parseFloat(pt($.amountIn,ve)).toFixed(6)),h(null),u(null)}}catch($){if(ue())return;const V=$ instanceof Error?$.message:"Failed to get quote";u(V),h(null),g(null),C(null),T(null),w(null),E(null)}finally{ue()||i(!1)}},Se),()=>{k.current&&clearTimeout(k.current)}},[t,fe,n?.amount,n?.asset?.address,n?.asset?.decimals,a,L,s,o.address,o.decimals,r,W,P]),{isQuoting:d,quoteError:p,estimatedOutput:m,estimatedInput:f,resolvedSwap:y,exactOutputSwap:v,quoteAmountOut:b,resolvedTokenIn:Q,isDirect:U,needsSwap:fe,selectedIsEquivalent:ee}}const ni={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},oi=["signing-delegation","signing-intent","submitting","executing"],Ad=()=>{},Sd=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:o,sourceChains:s,supportedSourceAssets:r,buildActionCalls:a,feeExecutionMode:c="user-transfer",buildSpicenetBatch:d,onPayExecute:i,resolveExactOutputSwap:p,actionLabel:u,amountDirection:m="input",swapDescription:h,directDescription:f,paymentAmount:g,amountInputMode:y="fixed",minPaymentAmount:C,maxPaymentAmount:v,onAmountChange:T,styles:b,dark:w,title:B,subtitle:E,onAddFunds:M,onSuccess:F,onError:k})=>{const A=m==="output",{theme:I,dark:S,primaryColor:W,dk:P,palette:z,fontFamily:N,monoFont:D,inputDark:H,cardBg:L,cardBorder:ee,textPrimary:U,textSecondary:Z,subtitleText:fe}=Bt(b,w),Q=oe(()=>H?{...I,colors:{...I.colors,secondary:P.cardBg,surfaceHover:P.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:I,[H,I,P.cardBg,P.hoverBg]),G=o.chainId,de=rn(Zt),ve=de?.mode||"7702",ce=ve!=="7702",he=!!de?.isWhitelistGateActive,ue=!!de?.isWhitelistConfigured&&de?.isUserWhitelisted!==!0,Se=oe(()=>s??de?.supportedChainIds??[],[s,de?.supportedChainIds]),$=oe(()=>{if(he)return[];if(r)return r;const ye=de?.allowedTokens;if(!ye||ye.length===0)return;const at=new Set(ye.map(Vn=>Vn.toLowerCase())),Un=[],Qn=new Set;for(const Vn of Se){const ds=Ee(Vn);for(const us of ds?.supportedTokens??[]){if(!at.has(us.symbol.toLowerCase()))continue;const nr=us.address.toLowerCase();Qn.has(nr)||(Qn.add(nr),Un.push(us.address))}}return Un},[r,de?.allowedTokens,Se,he]),V=Pn(),{address:_,isConnected:ae,isReady:xe,isAuthenticated:q,provider:te}=V,{execute:ge,estimate:se}=bo(),{externalWallet:Le,embeddedAddress:yt,activeWallet:Ot,activeAddress:Ht}=mo(),xt=de?.externalWalletAddress,me=de?.embeddedWalletAddress||yt,{displayAssets:jt,filteredSpiceAssets:Pe,embeddedWalletAddress:Qe,refreshSpiceAssets:it,refreshWalletAssets:Ut}=ja({destinationToken:o,supportedSourceAssets:$,sourceChains:Se,enabled:e&&(ce?!!xt:!!me)}),nt=he||A||ce?jt:Pe;X(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:ve,walletAddressUsed:Qe,count:nt.length,assets:nt.map(ye=>({symbol:ye.symbol,address:ye.address,chainId:ye.chainId,balanceFormatted:ye.balanceFormatted,source:ye?._source}))})},[e,ve,Qe,nt]);const[O,Ge]=R(null),[Me,Je]=R(g||""),[Ke,Jt]=R(!1),[_t,an]=R(null),[Be,en]=R("idle"),[ot,Fn]=R(""),[yn,$e]=R(null),[ln,Vt]=R(!1),[qe,we]=R(null),[Ye,tt]=R(null),[xn,ke]=R(!1),[$t,Dt]=R(!1),[At,_e]=R(null),Bn=le(O),qt=le(!1),cn=le(null),bn=le(null),Yt=le(0),Mt=le(null),bt=le(null);X(()=>{Bn.current=O},[O]);const Oe=y==="adjustable"?Me:g||"0",lt=Qe||yt||_,{isQuoting:St,quoteError:dn,estimatedOutput:tn,resolvedSwap:Et,exactOutputSwap:Te,quoteAmountOut:Wt,resolvedTokenIn:ft,isDirect:Nt,needsSwap:ct,selectedIsEquivalent:Re}=ti({direction:m,selectedAsset:O,destinationToken:o,chainId:G,recipient:lt,paymentAmount:Oe,resolveExactOutputSwap:p}),dt=A?parseFloat(Oe||"0"):parseFloat(O?.amount||"")||0,nn=dt>0&&dt<Hn,J=O?.asset?._source==="wallet",ne=!!O?.asset&&J&&O.asset.chainId!==G,Ce=oe(()=>O?.asset?Pe.find(ye=>Ie(ye.address,O.asset.address))?.balanceFormatted??0:0,[O,Pe]),He=J?O?.asset.balanceFormatted??0:Ce,et=oe(()=>{if(!O?.asset)return!1;if(A)return Ye?Wn(Ye.grossAmount,Ye.decimals,O.asset.decimals)>O.asset.balance:Re||Nt?dt>O.asset.balanceFormatted:Te?parseFloat(pt(Te.amountInMax,O.asset.decimals))>O.asset.balanceFormatted:!1;if(Ye){const ye=Wn(Ye.grossAmount,Ye.decimals,O.asset.decimals);return J?ye>O.asset.balance:parseFloat(pt(ye,O.asset.decimals))>He}return dt>He},[O,A,Ye,Re,dt,Te,He,J,Nt]);X(()=>{e||(Ge(null),an(null),Jt(!1),en("idle"),Fn(""),$e(null),Vt(!1),we(null),tt(null),ke(!1),Dt(!1),_e(null),qt.current=!1,y==="adjustable"&&Je(g||""),cn.current&&(cn.current.abort(),cn.current=null))},[e]);const ht=re(ye=>{Ge(at=>({asset:ye,amount:at?.asset?.address===ye.address&&at?.asset?.chainId===ye.chainId&&at.amount||""})),an(null),_e(null),Dt(!1)},[]),wt=re(ye=>{Ge(at=>at&&{...at,amount:ye}),an(null),_e(null),Dt(!1)},[]),mt=re(ye=>{let at=ye;v&&parseFloat(at)>parseFloat(v)&&(at=v),Je(at),T?.(at),an(null),_e(null),Dt(!1)},[v,T]);re(ye=>{if(qt.current||!_)return;const at=Bn.current;!at?.asset||!at.amount||at.asset?._source==="wallet"||ze(A?Oe:at.amount,at.asset.decimals)===0n||(qt.current=!0,it())},[_,G,it,A,Oe]);const De=re(ye=>{en({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[ye.step]||"executing"),Fn(ye.message),ye.txHash&&$e(ye.txHash)},[]),Rt=oe(()=>({currentPaymentAmount:Oe,destinationToken:o,embeddedWalletAddress:Qe,providerEmbeddedAddress:yt,externalWalletAddress:xt,address:_,isNon7702:ce,isPayMode:A,resolvedChainId:G,buildActionCalls:a,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:O,needsSwap:ct,resolvedSwap:Et,exactOutputSwap:Te,quoteAmountOut:Wt,resolvedTokenIn:ft}),[Oe,o,Qe,yt,xt,_,ce,A,G,a,c,d,O,ct,Et,Te,Wt,ft]),je=re(ye=>Aa({...Rt,requestTimestampMs:bn.current??Date.now()},ye),[Rt]),Y=re(ye=>Sa({...Rt,requestTimestampMs:bn.current??Date.now()},ye),[Rt]),be=re((ye,at,Un,Qn)=>Ea(ye,at,Un,se,Qn),[se]),Ct=oe(()=>O?.asset?ct&&ft?ft:O.asset.chainId===G?O.asset.address:ft??Dn(O.asset,G)??o.address:o.address,[O,o.address,ct,G,ft]),Ft=re(()=>(bn.current=Date.now(),Da(bt.current)),[]),Ze=oe(()=>O?.asset?Ie(O.asset.address,o.address)&&O.asset.chainId===o.chainId:!1,[O,o.address,o.chainId]),Pt=Ze&&(ce||A),st=Pt&&dt>0&&!!O?.asset,un=ue&&!Pt,j=oe(()=>{if(!st)return null;let ye;try{ye=ze(Oe||"0",o.decimals)}catch{return null}return{symbol:o.symbol,decimals:o.decimals,grossAmount:ye,netAmount:ye,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[st,Oe,o.symbol,o.decimals]),K=_t,pe=oe(()=>!(!O?.asset||dt<=0),[O,dt,st]),ie=oe(()=>!e||Ke||Be!=="idle"||!pe||st||!O?.asset?null:[A?"pay":"supply",m,O.asset.address.toLowerCase(),O.asset.chainId,O.amount,Oe,o.address.toLowerCase(),o.chainId,G,ft?.toLowerCase()??"",ct?"swap":"direct",Nt?"direct-token":"routed-token",ce?"non7702":"7702",Ze?"source-dest":"cross-chain",St?"quoting":"quoted",Te?.amountIn?.toString()??"",Te?.amountInMax?.toString()??"",Te?.venue??"",Et?.amountOut?.toString()??"",Wt?.toString()??"",Qe??"",yt??"",_??""].join("|"),[e,Ke,Be,pe,st,O,A,m,Oe,o,G,ft,ct,Nt,ce,Ze,St,Te,Et,Wt,Qe,yt,_]),Ve=re(()=>Ba({selectedAsset:O,isPayMode:A,parsedAmount:dt,needsSwap:ct,exactOutputSwap:Te,isNon7702:ce,isSourceDestToken:Ze,currentPaymentAmount:Oe,destinationToken:o,feeExecutionMode:c,resolvedTokenIn:ft,embeddedWalletAddress:Qe,providerEmbeddedAddress:yt,resolvedChainId:G,isConnected:ae,address:_,ready:xe,authenticated:q,isDirect:Nt,resolvedSwap:Et,isQuoting:St,executionTokenAddress:Ct,buildPayChainBatches:je,buildSupplyChainBatches:Y,estimate:se,estimateRequiredGrossFunding:be}),[O,A,dt,ct,Te,ce,Ze,Oe,o,c,ft,Qe,yt,be,je,se,G,ae,_,xe,q,Nt,Et,St,Y,Ct]);X(()=>{Mt.current=Ve},[Ve]);const We=re(ye=>Fa({asset:ye,isPayMode:A,isNon7702:ce,needsSwap:ct,isQuoting:St,embeddedWalletAddress:Qe,buildSupplyChainBatches:Y,estimate:se,executionTokenAddress:Ct,feeExecutionMode:c}),[A,ce,ct,St,Qe,Y,se,Ct,c]);X(()=>{if(!e){ke(!1),Dt(!1),_e(null),tt(null);return}if(Ke||Be!=="idle"){Yt.current+=1,ke(!1);return}if(!pe){tt(null),ke(!1),Dt(!1),_e(null);return}if(st){tt(j),ke(!1),Dt(!0),_e(null);return}if(St){Yt.current+=1,ke(!1),Dt(!1);return}if(!ie)return;let ye=!1;const at=async()=>{const Qn=++Yt.current;_e(null),ke(!0);try{const Vn=await Mt.current?.();if(ye||Yt.current!==Qn)return;Vn?(tt(Vn),Dt(!0)):(tt(null),Dt(!1)),_e(null)}catch(Vn){if(ye||Yt.current!==Qn)return;const ds=kn(Vn,"Unable to calculate fees for this action.");tt(null),Dt(!1),_e(ds)}finally{!ye&&Yt.current===Qn&&ke(!1)}},Un=window.setTimeout(()=>{at()},250);return()=>{ye=!0,clearTimeout(Un),ke(!1)}},[e,Ke,Be,pe,st,j,St,ie]);const Xe=re(()=>(bn.current=Date.now(),Ua(bt.current)),[]);X(()=>{!A&&Be==="success"&&yn&&(it(),F?.(yn))},[A,Be,yn,it,F]),X(()=>{if(!A||qe?.status!=="success"||qt.current||!_)return;qt.current=!0;const ye=Bn.current;!ye?.asset||ye.asset?._source==="wallet"||it()},[A,qe?.status,_,it]);const ut=le(F),zt=le(k);X(()=>{ut.current=F},[F]),X(()=>{zt.current=k},[k]),X(()=>{e&&(it(),Ut())},[e,it,Ut]),X(()=>{A&&(qe?.status==="success"&&ut.current?.(qe.txHash||""),qe?.status==="failed"&&zt.current?.(new Error("Payment execution failed")))},[A,qe?.status]);const on=re(()=>{Vt(!1),we(null),Ge(null),qt.current=!1,it(),Ut()},[it,Ut]);bt.current={selectedAsset:O,parsedAmount:dt,currentPaymentAmount:Oe,isInsufficientBalance:et,isPayMode:A,isNon7702:ce,isSourceDestToken:Ze,needsSwap:ct,exactOutputSwap:Te,selectedIsEquivalent:Re,resolvedTokenIn:ft,embeddedWalletAddress:Qe,providerEmbeddedAddress:yt,externalWallet:Le,externalWalletAddress:xt,activeSignerWallet:Ot,activeSignerAddress:Ht,address:_,isConnected:ae,ready:xe,authenticated:q,provider:te,resolvedChainId:G,executionTokenAddress:Ct,destinationToken:o,buildActionCalls:a,feeExecutionMode:c,buildSpicenetBatch:d,onPayExecute:i,onSuccess:F,onError:k,execution:{estimate:se,execute:ge,buildPayChainBatches:je,buildSupplyChainBatches:Y,estimateRequiredGrossFunding:be,onProgress:De},ui:{setError:an,setStep:en,setStatusMsg:Fn,setTxHash:$e,setIsExecuting:Jt,setShowStatusPanel:Vt,setPaymentResult:we},refs:{spiceDepositSubmittedRef:qt,abortControllerRef:cn}};const wn=g?.trim(),Kt=A&&y==="fixed"&&wn!==void 0&&wn!==""&&dt===0,Cn=A?(Kt||!!O?.asset)&&dt>=0&&!nn&&!et&&!Ke&&(Kt||st||$t)&&!At&&(Kt||!ct||!!Te)&&!un:!!O?.asset&&dt>0&&!nn&&!et&&!Ke&&(Pt||$t)&&!At&&(ne||Nt||!!Et&&!St)&&!un;X(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:Cn,isPayMode:A,hasSelectedAsset:!!O?.asset,selectedAsset:O?.asset?{symbol:O.asset.symbol,address:O.asset.address,chainId:O.asset.chainId,balanceFormatted:O.asset.balanceFormatted,source:O.asset?._source}:null,parsedAmount:dt,isZeroAmountPay:Kt,isBelowMinimum:nn,isInsufficientBalance:et,isExecuting:Ke,directExternalAction:Pt,directExecutionFeeNote:st,feeEstimateReady:$t,feeEstimateError:At,needsSwap:ct,isDirect:Nt,isSourceDestToken:Ze,hasExactOutputSwap:!!Te,isQuoting:St,whitelistHoldPending:ue,supplyHeldForWhitelist:un,isWhitelistGateActive:he,destinationToken:{symbol:o.symbol,address:o.address,chainId:o.chainId}})},[e,Cn,A,O,dt,Kt,nn,et,Ke,Pt,st,$t,At,ct,Nt,Ze,Te,St,ue,un,he,o]);const eo=Nt?f||`Your ${o.symbol} will be used directly.`:h||"Your assets will be swapped and used in a single atomic transaction.",co=(G?Ee(G):void 0)?.viemChain?.blockExplorers?.default?.url??"",to=oi.indexOf(Be),Ne=Ke?(ni[Be]||"EXECUTING...").toUpperCase():Be==="success"?"DONE":nn?`MINIMUM ${Hn}`:et?"INSUFFICIENT BALANCE":u.toUpperCase(),rt=oe(()=>{if(Ke)return"PAYING...";if(nn)return`MINIMUM ${Hn}`;if(et&&O?.asset)return`INSUFFICIENT ${O.asset.symbol}`;if(u)return u.toUpperCase();const ye=dt>0?` ${Oe} ${o.symbol}`:"";return ct?`SWAP & PAY${ye}`:`PAY${ye}`},[Ke,nn,et,O,u,dt,Oe,o.symbol,ct]),sn=Be==="success"?()=>{en("idle"),Ge(null),$e(null),it()}:Ft,Nn=Be==="success"?!1:!Cn;if(!e)return null;const Wo=A?B||`Pay ${o.symbol}`:u,ko=A?E:x("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[l("span",{style:{marginTop:"3px",flexShrink:0},children:l(Us,{color:fe})}),l("p",{style:{fontSize:"12px",color:fe,margin:0,lineHeight:"1.4",fontFamily:N},children:eo})]});if(A){const ye=qe&&(qe.status==="success"||qe.status==="failed")?[{asset:{symbol:O?.asset?.symbol||o.symbol,address:O?.asset?.address||""},amount:Oe,txHash:qe.txHash||"",success:qe.status==="success",error:qe.status==="failed"?qe.error:void 0}]:void 0;return l(Ln,{isOpen:e,onClose:t,title:Wo,subtitle:ko,styles:b,dark:S,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:x("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[M&&l("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:l(Ps,{onClick:M,color:W,fontFamily:N})}),!Kt&&l("div",{style:{marginBottom:"12px"},children:l(Fo,{assets:nt,selectedAsset:O??void 0,onAssetSelect:ht,onAmountChange:Ad,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:O?.asset?ct?St?"...":Te?`~${parseFloat(pt(Te.amountIn,O.asset.decimals)).toFixed(6)}`:void 0:Oe??void 0:void 0,dark:S,theme:Q,styles:b})}),l(Pa,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:W,fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:L,cardBorder:ee,dk:P,dark:S,isQuoting:St,quoteError:dn,estimatedOutput:tn,paymentAmount:Oe,needsSwap:ct,exactOutputSwap:Te,adjustable:y==="adjustable",maxAmount:v,onAmountChange:mt}),pe&&l(ns,{fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:L,cardBorder:ee,resolvedDark:S,darkCardBorder:P.cardBorder,primaryColor:W,feePreview:Ye,isLoading:xn,errorText:At,directExecutionFeeNote:st}),K&&l(wo,{variant:"error",palette:z,fontFamily:N,style:{marginBottom:"12px"},children:K}),l(Lt,{variant:"outline",fullWidth:!0,onClick:Xe,disabled:!Cn,loading:Ke,dark:S,styles:{...b,button:{...b?.button,backgroundColor:W}},children:rt}),qe&&ln&&l("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:S?P.shell:"white",borderRadius:S?"12px":"6px",padding:"16px 0"},children:l(js,{type:"payment",isOpen:qe.status!=="processing",isProcessing:Ke||qe.status==="processing",closeOnComplete:!1,chainName:fn(G),explorerUrl:ho(G,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Vt(!1),we(null),Xe()},onNewTx:on,onClose:()=>{Vt(!1),we(null)},onComplete:on,results:ye,styles:b,dark:S})})]})})}return l(Ln,{isOpen:e,onClose:t,title:Wo,subtitle:ko,dark:S,styles:b,theme:I,closeOnBackdropClick:n,children:x("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[l("div",{style:{marginBottom:"16px"},children:l(Fo,{assets:nt,selectedAsset:O||void 0,onAssetSelect:ht,onAmountChange:wt,disabled:Ke||Be==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:Q,styles:b,dark:H,resolveMaxAmount:We,maxAmount:He>0?po(He,O?.asset.decimals??o.decimals):void 0})}),O?.asset&&!Nt&&l(Pa,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:W,fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:L,cardBorder:ee,dark:S,isQuoting:St,quoteError:dn,estimatedOutput:tn}),pe&&l(ns,{fontFamily:N,textPrimary:U,textSecondary:Z,cardBg:L,cardBorder:ee,resolvedDark:S,darkCardBorder:P.cardBorder,primaryColor:W,feePreview:Ye,isLoading:xn,errorText:At,directExecutionFeeNote:st}),Be!=="idle"&&x("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Be==="success"?L:Be==="error"?z.errorBg:L,border:`1px solid ${Be==="success"?ee:Be==="error"?z.errorBorder:ee}`},children:[x("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Be==="success"?l("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:l("path",{d:"M5 13l4 4L19 7",stroke:z.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Be==="error"?l("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:l("path",{d:"M18 6L6 18M6 6l12 12",stroke:z.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):l(qn,{size:14,color:W}),l("span",{style:{fontSize:"13px",fontWeight:500,color:Be==="success"?U:Be==="error"?z.errorText:U,fontFamily:N,flex:1},children:Be==="success"?"Deposit confirmed":Be==="error"?ot||"Transaction failed":ni[Be]||ot}),Be==="success"&&yn&&l("a",{href:`${co}/tx/${yn}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:W,fontFamily:N,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Be==="error"&&l("button",{onClick:()=>{en("idle"),an(null),setTimeout(Ft,50)},style:{background:"none",border:"none",fontSize:"12px",color:W,fontFamily:N,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),to>=0&&Be!=="success"&&Be!=="error"&&l("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${Z}22`,overflow:"hidden"},children:l("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:W,transformOrigin:"left center",transform:`scaleX(${(to+1)/oi.length})`,transition:"transform 400ms ease"}})})]}),_t&&Be==="idle"&&l(wo,{variant:"error",palette:z,fontFamily:N,style:{marginBottom:"16px"},children:_t}),l(Lt,{variant:"outline",fullWidth:!0,disabled:Nn,onClick:sn,theme:I,dark:S,styles:{...b,button:{...b?.button,backgroundColor:W}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:D},children:Ne})]})})},Ed=()=>{const[e,t]=R("0"),[n,o]=R(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:n,setSelectedAsset:o}};function Fd(e,t=0){const[n,o]=R(t),s=e[n]??e[0],r=oe(()=>s?BigInt(Math.round(s.months*30*24*3600)):0n,[s?.months]);return{selectedDurationIdx:n,setSelectedDurationIdx:o,selectedDuration:s,durationSeconds:r}}function Bd(){const{actions:e,isReady:t,isAuthenticated:n}=Pn(),o=rn(Zt)?.embeddedWalletAddress,s=le(!1),r=le(0),a=le(null),c=le(e),[d,i]=R(0);c.current=e,X(()=>{s.current=!1,r.current=0,a.current&&(clearTimeout(a.current),a.current=null)},[o]),X(()=>{if(!o||!t||!n||s.current)return;s.current=!0;let p=!1;return(async()=>{await Sn(2e3);try{await hi(o,c.current.signMessage),r.current=0}catch(u){console.warn("[SmartWallet] Registration failed:",u),s.current=!1,!p&&r.current<3&&(r.current+=1,a.current=setTimeout(()=>{i(m=>m+1)},5e3))}})(),()=>{p=!0,a.current&&(clearTimeout(a.current),a.current=null)}},[o,t,n,d])}function Do(e){try{return Fi(e)}catch{throw new Ae("ROUTE_TOKEN_NOT_FOUND",`Token "${e[0]}" not found on chain ${e[1]} in the token registry.`,{symbol:e[0],chainId:e[1]})}}function Td(e,t){if(e[0].toUpperCase()===t[0].toUpperCase()&&e[1]===t[1])return!0;let n,o;try{n=Do(e),o=Do(t)}catch{return!1}const s=new Set(pr(o.address).map(r=>r.toLowerCase()));return s.add(o.address.toLowerCase()),s.has(n.address.toLowerCase())}function Md(){const e=[];for(const t of Object.keys(Bi).map(Number))for(const n of dr(t))e.push([n.symbol,t]);return e}async function Rd(e){const{action:t,inputToken:n,inputAmount:o,registry:s,userAddress:r,slippage:a,intermediaryCandidates:c}=e;if(t.calls.length===0)throw new Ae("INVALID_PARAMS","buildIntent: action.calls must not be empty.",{action:t});if(o<=0n)throw new Ae("INVALID_PARAMS","buildIntent: inputAmount must be greater than zero.",{inputAmount:o.toString()});const d=t.supportedInputTokens??Md();if(!d.some(y=>Td(n,y))){const y=d.map(([C,v])=>`${C} (chain ${v})`).join(", ");throw new Ae("ROUTE_UNSUPPORTED_INPUT",`Input token "${n[0]}" on chain ${n[1]} is not in the action's supported input tokens. Supported: ${y}.`,{inputToken:{symbol:n[0],chainId:n[1]},supportedInputTokens:d})}const i=Do(n),p=Do(t.outputToken),u=ca({sourceAsset:i,outputAsset:p,sourceChainId:i.chainId,destinationChainId:t.chainId,intermediaryCandidates:c}),{chainBatches:m,solverFrontToken:h,solverFrontAmount:f,resolvedSwaps:g}=await da({route:u,sourceAmount:o,userAddress:r,registry:s,actionCalls:t.calls,slippage:a});return{chainBatches:m,route:u,resolvedSwaps:g,resolvedInputToken:i,resolvedOutputToken:p,solverFrontToken:h,solverFrontAmount:f}}const Dd=[0n,1n,30n],Wd=new Set(["ABORT","CONCURRENT_EXECUTION","WALLET_DISCONNECTED","WALLET_REJECTED","NO_VENUE_FOR_CHAIN"]);function si(e,t){return t===0n?e:e*(1000n-t)/1000n}async function Nd(e,t){const{chainId:n,swapCalls:o,quoteAmountOut:s,buildActionCalls:r,tokenAddress:a,tokenTransferAmount:c,onProgress:d,signal:i,options:p,buffers:u=Dd}=t;for(let m=0;m<u.length;m++){const h=u[m],f=si(s,h),g=r(f),y=[{chainId:n,calls:[...o,...g]}];try{return await e(y,a,c,d,i,p)}catch(C){const v=typeof C?.message=="string"?C.message:String(C?.message??"");if(lr(C)&&Wd.has(C.code)||C.name==="AbortError"||i?.aborted||v.includes("User rejected")||v.includes("User denied")||C.code===4001||m>=u.length-1)throw C;const T=Number(u[m+1])/10;console.warn(`[SwapThenAction] Action attempt ${m+1} failed (buffer ${Number(h)/10}%), retrying with ${T}% buffer...`,C.message),d?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${T}% buffer)...`})}}throw new Ae("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:u.length,chainId:n})}Wi();export{pd as AccountDisplay,Ps as AddFundsLink,Yr as CheckIcon,$n as ChevronIcon,go as CloseIcon,Co as DetailRow,tu as NATIVE_TOKEN_ADDRESS,Hs as ProviderLogin,tr as SATSUMA_CITREA_CONFIG,nu as SPICENET_NATIVE_CHAIN_ID,ou as SPICE_COMBINED_FEE_RECIPIENT,su as SPICE_GAS_FEE_RECIPIENT,ru as SPICE_PLATFORM_FEE_RECIPIENT,au as SPICE_SOLVER_ADDRESS,Cs as SearchInput,fc as SelectChainModal,pc as SpiceDeposit,Xd as SpiceFlowProvider,Zt as SpiceFlowProviderContext,ya as SpiceLock,ya as SpiceLockModal,Sd as SpiceSupply,Bc as SpiceWithdraw,Ae as SpiceflowError,qn as Spinner,wo as StatusBanner,Xa as UNIV3_BASE_CONFIG,si as applyBuffer,iu as applySlippage,Bo as areEquivalentOnChains,Gd as buildDarkPalette,Rd as buildIntent,Jd as buildLightPalette,Aa as buildPayChainBatches,da as buildRoutedBatches,Sa as buildSupplyChainBatches,lu as buildUniV3SwapCalls,Ka as create1inchVenue,_a as createExactOutputRegistry,$a as createLiquidityRegistry,Ga as createSatsumaVenue,mn as duration,Gt as easing,Ba as estimateFeePreview,Ea as estimateRequiredGrossFunding,Fa as estimateSupplyMaxAmount,_s as executeDirectExternalAction,Na as executeNon7702Pay,Wa as executeNon7702Supply,Ua as executePay,Da as executeSupply,Nd as executeSwapThenAction,jn as findEquivalentOnChain,qs as findTokenOnChain,gr as font,qo as getAssetChainTokenCandidates,Va as getBestUniV3Quote,Ee as getChainConfig,cu as getChainIdsByNetwork,fn as getChainName,du as getEscrowContractAddress,Qa as getUniV3Quote,uu as isNativeToken,lr as isSpiceflowError,pu as isSpicenetChainId,Oa as isSupportedSupplyAsset,qa as isSwapIntent,fu as normalizeNativeTokenAddress,ws as radius,vt as relayerService,Dn as resolveAssetTokenAddressOnChain,Rr as resolveFundedToken,Id as resolveInputSupplySwapQuote,ca as resolveRoute,$d as resolveTheme,Do as resolveTokenRef,Wn as scaleTokenAmount,hu as spicenetAbi,mu as spicenetWithdrawalAbi,An as transition,Ed as useAssetInput,_d as useIsUserWhitelisted,Fd as useLockDuration,Bd as useSmartWallet,To as useSpiceAssets,Bt as useSpiceBrand,bo as useSpiceExecution,xa as useSpicePendingDeposits,ja as useSupplyAssets,ti as useSupplyQuote,Pn as useWallet,ro as z};
|