@spicenet-io/spiceflow-ui 4.22.1 → 4.22.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
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function(){if(typeof document==="undefined"||document.getElementById("spiceflow-styles"))return;var s=document.createElement("style");s.id="spiceflow-styles";s.textContent="@keyframes spiceflow-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@keyframes spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@media (prefers-reduced-motion:reduce){*,:after,:before{animation-duration:.001ms!important;animation-iteration-count:1!important;scroll-behavior:auto!important;transition-duration:.001ms!important}}.spiceflow-focus-ring:focus-visible,[data-spiceflow-focus]:focus-visible{border-radius:4px;outline:2px solid currentColor;outline-offset:2px}@media (forced-colors:active){.spiceflow-focus-ring:focus-visible,[data-spiceflow-focus]:focus-visible{outline:2px solid Highlight}}.ibm-plex-mono-thin{font-weight:100}.ibm-plex-mono-extralight,.ibm-plex-mono-thin{font-family:IBM Plex Mono,monospace!important;font-style:normal}.ibm-plex-mono-extralight{font-weight:200}.ibm-plex-mono-light{font-weight:300}.ibm-plex-mono-light,.ibm-plex-mono-regular{font-family:IBM Plex Mono,monospace!important;font-style:normal}.ibm-plex-mono-regular{font-weight:400}.ibm-plex-mono-medium{font-weight:500}.ibm-plex-mono-medium,.ibm-plex-mono-semibold{font-family:IBM Plex Mono,monospace!important;font-style:normal}.ibm-plex-mono-semibold{font-weight:600}.ibm-plex-mono-bold{font-family:IBM Plex Mono,monospace!important;font-style:normal;font-weight:700}#privy-modal-content button{border-radius:6px;font-family:IBM Plex Mono,monospace!important;font-size:small;letter-spacing:-.5px;text-transform:uppercase}#privy-modal-content input{background:#fff;border-radius:6px;padding-top:5px!important}#privy-dialog-title{display:none!important;font-size:18px;padding-bottom:10px;padding-top:10px}.AppLogoContainer-sc-a206bd44-0{display:none}#privy-modal-content{background:var(--Neutral-0,#fafafa);border:6px solid var(--Neutral-1,#e9e9e9);box-shadow:inset 0 0 0 1px rgba(0,0,0,.15),0 330px 92px transparent,0 211px 84px rgba(0,0,0,.01),0 119px 71px rgba(0,0,0,.05),0 53px 53px rgba(0,0,0,.09),0 13px 29px rgba(0,0,0,.1);height:auto!important;padding-bottom:10px}.Subtitle-sc-ddbf22b4-4{font-size:12px;margin-top:-14px;opacity:.5}.StyledLink-sc-1c6127e5-0{background:none!important}.StyledLink-sc-c8577138-0,.login-method-button{font-family:IBM Plex Mono,monospace!important}.StyledLink-sc-c8577138-0{font-style:uppercase}#protected-by-privy{color:#000!important}";document.head.appendChild(s)})();
|
|
2
|
-
"use strict";var Wd=Object.create;var Ci=Object.defineProperty;var qd=Object.getOwnPropertyDescriptor;var Ld=Object.getOwnPropertyNames;var zd=Object.getPrototypeOf,Hd=Object.prototype.hasOwnProperty;var Vd=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ld(t))!Hd.call(e,r)&&r!==n&&Ci(e,r,{get:()=>t[r],enumerable:!(s=qd(t,r))||s.enumerable});return e};var Qd=(e,t,n)=>(n=e!=null?Wd(zd(e)):{},Vd(t||!e||!e.__esModule?Ci(n,"default",{value:e,enumerable:!0}):n,e));const c=require("react/jsx-runtime"),d=require("./privy-CBW14wMQ.cjs"),p=require("react"),F=require("@spicenet-io/spiceflow-core"),ss=require("wagmi"),M=require("viem"),Kn=require("viem/actions"),pr=require("@privy-io/react-auth"),fr=require("react-dom");require("@tanstack/react-query");const Gd="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@100;200;300;400;500;600;700&display=swap",Kd="spiceflow-ibm-plex-mono",Yd="spiceflow-preconnect-googleapis",Zd="spiceflow-preconnect-gstatic";function Wo(e,t){if(document.getElementById(e))return;const n=t();n.id=e,document.head.appendChild(n)}function Xd(){typeof document>"u"||(Wo(Yd,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.googleapis.com",e}),Wo(Zd,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="",e}),Wo(Kd,()=>{const e=document.createElement("link");return e.rel="stylesheet",e.href=Gd,e}))}const Jd={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",84532:"0x4200000000000000000000000000000000000006"},ki=M.parseAbi(["function deposit() payable","function withdraw(uint256 wad)"]);function qo(e){return d.getChainConfig(e)?.wrappedNativeTokenAddress??Jd[e]}const Lo=(e,t)=>({to:e,value:t,data:M.encodeFunctionData({abi:ki,functionName:"deposit"})}),zo=(e,t)=>({to:e,value:0n,data:M.encodeFunctionData({abi:ki,functionName:"withdraw",args:[t]})});function Ho(e,t,n){const s=F.isNativeToken(t),r=F.isNativeToken(n);if(!s&&!r)return null;const o=qo(e);return o?{weth:o,wrapIn:s,unwrapOut:r}:null}function Si(e,t,n,s){const r=Ho(e,t,n);return!r||s<=0n?null:r.wrapIn&&!r.unwrapOut&&n.toLowerCase()===r.weth.toLowerCase()?[Lo(r.weth,s)]:r.unwrapOut&&!r.wrapIn&&t.toLowerCase()===r.weth.toLowerCase()?[zo(r.weth,s)]:null}function $d(e){return{...e,resolve:async(t,n,s,r)=>{const o=Si(n,t.tokenIn,t.tokenOut,t.amountIn);if(o)return{venue:"native-wrap",amountOut:t.amountIn,amountOutMinimum:t.amountIn,calls:o};const a=await e.resolve(t,n,s,r);if(a)return a;const i=Ho(n,t.tokenIn,t.tokenOut);if(!i)return null;const l=await e.resolve({...t,tokenIn:i.wrapIn?i.weth:t.tokenIn,tokenOut:i.unwrapOut?i.weth:t.tokenOut},n,s,r);return l?{...l,calls:[...i.wrapIn?[Lo(i.weth,t.amountIn)]:[],...l.calls,...i.unwrapOut?[zo(i.weth,l.amountOutMinimum)]:[]]}:null}}}function _d(e){return{...e,resolve:async(t,n,s)=>{const r=Si(n,t.tokenIn,t.tokenOut,t.amountOut);if(r)return{venue:"native-wrap",amountIn:t.amountOut,amountInMax:t.amountOut,amountOut:t.amountOut,calls:r};const o=await e.resolve(t,n,s);if(o)return o;const a=Ho(n,t.tokenIn,t.tokenOut);if(!a)return null;const i=await e.resolve({...t,tokenIn:a.wrapIn?a.weth:t.tokenIn,tokenOut:a.unwrapOut?a.weth:t.tokenOut},n,s);return i?{...i,calls:[...a.wrapIn?[Lo(a.weth,i.amountInMax)]:[],...i.calls,...a.unwrapOut?[zo(a.weth,i.amountOut)]:[]]}:null}}}const Ii=[100,500,3e3,1e4];function Jr(e,t,n,s,r){const o=[];for(const a of n){const i=typeof a=="object"&&!Array.isArray(a)?a:void 0,l=i?i.tokens:Array.isArray(a)?a:[a];if(!l.length||l.length>2)throw new Error("A v3 route must have one or two intermediate tokens");const u=[e,...l,t];if(i&&(i.feeTiers.length!==u.length-1||i.feeTiers.some(f=>!f.length)))throw new Error("A v3 route needs fee tiers for every pool");if(new Set(u.map(f=>f.toLowerCase())).size!==u.length)continue;const m=(f,h)=>{if(f===u.length){o.push(r==="in"?h:Ai(h));return}for(const y of i?.feeTiers[f-1]??s)m(f+1,M.concatHex([h,M.encodePacked(["uint24","address"],[y,u[f]])]))};m(1,u[0])}return[...new Set(o)]}function Ai(e){const t=e.slice(2),n=[];for(let s=0;s<t.length;){const r=n.length%2===0?40:6;n.push(t.slice(s,s+r)),s+=r}return`0x${n.reverse().join("")}`}const eu=M.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),tu=M.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),nu=1800;function Ei(e){const{config:t,route:n,tokenIn:s,tokenOut:r,recipient:o,amountOut:a}=e,i=e.amountInMaximum,l=e.routerHasDeadline?tu:eu,u=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+nu)}:{},m=n.path?M.encodeFunctionData({abi:l,functionName:"exactOutput",args:[{path:n.path,recipient:o,...u,amountOut:a,amountInMaximum:i}]}):M.encodeFunctionData({abi:l,functionName:"exactOutputSingle",args:[{tokenIn:s,tokenOut:r,fee:n.fee,recipient:o,...u,amountOut:a,amountInMaximum:i,sqrtPriceLimitX96:0n}]});return{to:t.swapRouter,value:0n,data:m}}const su=M.parseAbi(["function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)","function quoteExactOutput(bytes path, uint256 amountOut) returns (uint256 amountIn, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]);async function mr(e,t,n,s,r){const o=d.getClientForChain(e),{result:a}=await o.simulateContract({address:t.quoterV2,abi:su,functionName:r==="in"?"quoteExactInput":"quoteExactOutput",args:[n,s]}),[i,,,l]=a;if(i<=0n)throw new Error("No liquidity along this path.");return{amount:i,gasEstimate:l}}async function ru(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:r,chainId:o,config:a}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const i=(await d.getClientForChain(o).simulateContract({address:a.quoterV2,abi:F.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(i[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:i[0],sqrtPriceX96After:i[1],gasEstimate:i[3]}}async function Fi(e){const t=e.feeTiers??Ii,n=Jr(e.tokenIn,e.tokenOut,e.hubs??[],t,"in"),s=await Promise.allSettled([...t.map(async o=>({...await ru({...e,fee:o}),fee:o})),...n.map(async o=>{const a=await mr(e.chainId,e.config,o,e.amountIn,"in");return{amountOut:a.amount,sqrtPriceX96After:0n,gasEstimate:a.gasEstimate,fee:0,path:o}})]);let r=null;for(const o of s)o.status==="fulfilled"&&(!r||o.value.amountOut>r.amountOut)&&(r=o.value);if(!r)throw new Error("No liquidity found for this pair on any fee tier.");return r}const ou=[{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 au(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:r,chainId:o,config:a}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const i=(await d.getClientForChain(o).simulateContract({address:a.quoterV2,abi:ou,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(i[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:i[0],sqrtPriceX96After:i[1],gasEstimate:i[3]}}async function Ti(e){const t=e.feeTiers??Ii,n=Jr(e.tokenIn,e.tokenOut,e.hubs??[],t,"out"),s=await Promise.allSettled([...t.map(async o=>({...await au({...e,fee:o}),fee:o})),...n.map(async o=>{const a=await mr(e.chainId,e.config,o,e.amountOut,"out");return{amountIn:a.amount,sqrtPriceX96After:0n,gasEstimate:a.gasEstimate,fee:0,path:o}})]);let r=null;for(const o of s)o.status==="fulfilled"&&(!r||o.value.amountIn<r.amountIn)&&(r=o.value);if(!r)throw new Error("No liquidity found for this pair on any fee tier.");return r}function iu(e){return e.type==="swap"}const hr=.02,cu=[1,8453,42161,10,137,43114,56],lu="https://api.1inch.dev/swap/v6.0";function Vo(e,t){return F.applySlippage(e,t)}function du(e){const t=e?.baseUrl??lu;return{name:"1inch",chainIds:e?.chainIds??cu,resolve:async(n,s,r)=>{const o=n.maxSlippage??hr,a=o*100,i=F.isNativeToken(n.tokenIn)?F.NATIVE_TOKEN_ADDRESS:n.tokenIn,l=F.isNativeToken(n.tokenOut)?F.NATIVE_TOKEN_ADDRESS:n.tokenOut,u=F.isNativeToken(n.tokenIn);try{const m=new URL(`${t}/${s}/swap`);m.searchParams.set("src",i),m.searchParams.set("dst",l),m.searchParams.set("amount",n.amountIn.toString()),m.searchParams.set("from",r),m.searchParams.set("slippage",a.toString()),m.searchParams.set("disableEstimate","true"),m.searchParams.set("allowPartialFill","false");const f={Accept:"application/json"};e?.apiKey&&(f.Authorization=`Bearer ${e.apiKey}`);const h=await fetch(m.toString(),{headers:f});if(!h.ok)throw new d.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${h.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${h.status}`});const y=await h.json();if(!y.dstAmount||!y.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const g=BigInt(y.dstAmount);if(g<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const x=Vo(g,o),w=[];return y.tx.to&&!u&&w.push({to:n.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[y.tx.to,n.amountIn]})}),w.push({to:y.tx.to,value:BigInt(y.tx.value||"0"),data:y.tx.data}),{venue:"1inch",amountOut:g,amountOutMinimum:x,calls:w}}catch(m){if(m instanceof d.SpiceflowError)throw m;const f=m instanceof Error?m.message:String(m);throw new d.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${f}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:f})}}}}const Ri=[4114,5115],Qo={name:"Satsuma",swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Bi={name:"Uniswap v3",swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Oi={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[1],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]},ji={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[42161],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","0xaf88d065e77c8cC2239327C5EDb3A432268e5831"]},uu={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[137],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270","0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"]},pu={name:"Uniswap v3",swapRouter:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",quoterV2:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",chainIds:[56],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c","0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"]},fu={name:"Uniswap v3",swapRouter:"0xfe31f71c1b106eac32f1a19239c9a9a72ddfb900",quoterV2:"0x661e93cca42afacb172121ef892830ca3b70f08d",chainIds:[143],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A","0x754704Bc059F8C67012fEd69BC8A327a5aafb603"]},Di={name:"Uniswap v3",swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Ni={name:"SushiSwap",swapRouter:"0x1e406484F1F204b23cE84B9901C0171a738fd406",quoterV2:"0x3E290e5E01818002A0b672148BdC7514D861C7B3",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"],routerHasDeadline:!0},Mi=M.parseAbi(["function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),Pi=M.parseAbi(["function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),mu=M.parseAbi(["function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),hu=M.parseAbi(["function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),Go=1800,Ui=[1,50,100,200,2e3],$r={name:"Aerodrome",swapRouter:"0xcbBb8035cAc7D4B3Ca7aBb74cF7BdF900215Ce0D",quoterV2:"0x3d4C22254F86f64B7eC90ab8F7aeC1FBFD271c6C",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]};function gr(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??Ui;return{name:t,chainIds:n,resolve:async(r,o,a)=>{if(F.isNativeToken(r.tokenIn)||F.isNativeToken(r.tokenOut))return null;const i=r.maxSlippage??hr,l=[...s.map(w=>M.encodePacked(["address","uint24","address"],[r.tokenIn,w,r.tokenOut])),...Jr(r.tokenIn,r.tokenOut,e.hubCurrencies??[],s,"in")],u={quoterV2:e.quoterV2},m=await Promise.allSettled(l.map(async w=>({path:w,amountOut:(await mr(o,u,w,r.amountIn,"in")).amount})));let f=null;for(const w of m)w.status==="fulfilled"&&(!f||w.value.amountOut>f.amountOut)&&(f=w.value);if(!f)return console.warn(`[AerodromeVenue] No viable route for ${r.tokenIn} \u2192 ${r.tokenOut} on chain ${o}.`),null;const h=Vo(f.amountOut,i),y=e.deadline??BigInt(Math.floor(Date.now()/1e3)+Go),g=M.encodeFunctionData({abi:mu,functionName:"exactInput",args:[{path:f.path,recipient:a,deadline:y,amountIn:r.amountIn,amountOutMinimum:h}]}),x=[{to:r.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[e.swapRouter,r.amountIn]})},{to:e.swapRouter,value:0n,data:g}];return{venue:t,amountOut:f.amountOut,amountOutMinimum:h,calls:x}}}}function Wi(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??Ui;return{name:t,chainIds:n,resolve:async(r,o,a)=>{if(F.isNativeToken(r.tokenIn)||F.isNativeToken(r.tokenOut))return null;const i=r.maxSlippage??hr,l=[...s.map(x=>M.encodePacked(["address","uint24","address"],[r.tokenOut,x,r.tokenIn])),...Jr(r.tokenIn,r.tokenOut,e.hubCurrencies??[],s,"out")],u={quoterV2:e.quoterV2},m=await Promise.allSettled(l.map(async x=>({path:x,amountIn:(await mr(o,u,x,r.amountOut,"out")).amount})));let f=null;for(const x of m)x.status==="fulfilled"&&(!f||x.value.amountIn<f.amountIn)&&(f=x.value);if(!f)return console.warn(`[AerodromeExactOutputVenue] No viable route for ${r.tokenIn} \u2192 ${r.tokenOut} on chain ${o}.`),null;const h=BigInt(Math.round(i*1e4)),y=f.amountIn+f.amountIn*h/10000n,g=e.deadline??BigInt(Math.floor(Date.now()/1e3)+Go);return{venue:t,amountIn:f.amountIn,amountInMax:y,amountOut:r.amountOut,calls:[{to:e.swapRouter,value:0n,data:M.encodeFunctionData({abi:hu,functionName:"exactOutput",args:[{path:f.path,recipient:a,deadline:g,amountOut:r.amountOut,amountInMaximum:y}]})}]}}}}function wr(e){const t=e.name??"Uniswap v3",n=e.chainIds??Ri;return{name:t,chainIds:n,resolve:async(s,r,o,a)=>{if(F.isNativeToken(s.tokenIn)||F.isNativeToken(s.tokenOut))return null;const i=s.maxSlippage??hr;let l;try{let g;if(a){if(a.venue!==t)return null;const x=a.calls.find(b=>b.to.toLowerCase()===e.swapRouter.toLowerCase());if(!x)return null;const w=M.decodeFunctionData({abi:e.routerHasDeadline?Pi:[...Mi,...F.uniV3SwapRouterAbi],data:x.data});if(w.functionName==="exactInput"){const{path:b}=w.args[0];if(b.slice(0,42).toLowerCase()!==s.tokenIn.toLowerCase()||`0x${b.slice(-40)}`.toLowerCase()!==s.tokenOut.toLowerCase())return null;g={path:b,fee:0}}else if(w.functionName==="exactInputSingle"){const{tokenIn:b,tokenOut:S,fee:T}=w.args[0];if(b.toLowerCase()!==s.tokenIn.toLowerCase()||S.toLowerCase()!==s.tokenOut.toLowerCase())return null;g={fee:T}}else return null}l=g?.path?{...g,amountOut:(await mr(r,e,g.path,s.amountIn,"in")).amount}:await Fi({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn,chainId:r,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:g?[g.fee]:e.feeTiers,hubs:g?[]:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return console.warn(`[UniV3Venue] No viable route for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${r}.`),null}const u=Vo(l.amountOut,i),m=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+Go)}:{},f=e.routerHasDeadline?Pi:l.path?Mi:F.uniV3SwapRouterAbi,h=l.path?M.encodeFunctionData({abi:f,functionName:"exactInput",args:[{path:l.path,recipient:o,...m,amountIn:s.amountIn,amountOutMinimum:u}]}):M.encodeFunctionData({abi:f,functionName:"exactInputSingle",args:[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:l.fee,recipient:o,...m,amountIn:s.amountIn,amountOutMinimum:u,sqrtPriceLimitX96:0n}]}),y=[{to:s.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[e.swapRouter,s.amountIn]})},{to:e.swapRouter,value:0n,data:h}];return{venue:t,amountOut:l.amountOut,amountOutMinimum:u,calls:y}}}}function Ko(e){const t=e.name??"Uniswap v3",n=e.chainIds??Ri;return{name:t,chainIds:n,resolve:async(s,r,o)=>{if(F.isNativeToken(s.tokenIn)||F.isNativeToken(s.tokenOut))return null;const a=s.maxSlippage??hr;let i;try{i=await Ti({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut,chainId:r,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return null}const l=BigInt(Math.round(a*1e4)),u=i.amountIn+i.amountIn*l/10000n;return{venue:t,amountIn:i.amountIn,amountInMax:u,amountOut:s.amountOut,calls:[Ei({config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},routerHasDeadline:e.routerHasDeadline,route:i,tokenIn:s.tokenIn,tokenOut:s.tokenOut,recipient:o,amountOut:s.amountOut,amountInMaximum:u})]}}}}function qi(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(wr(e.satsuma)),e?.aerodrome!==!1&&t.push(gr(e?.aerodrome??$r)),t.push(du(e?.oneInch));const n=t.map($d);function s(a){return n.find(i=>i.chainIds.includes(a))}async function r(a,i,l,u){const m=n.filter(g=>g.chainIds.includes(i));if(m.length===0)throw new d.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${i}. Cannot resolve swap ${a.tokenIn} \u2192 ${a.tokenOut}.`,{chainId:i,tokenIn:a.tokenIn,tokenOut:a.tokenOut,amountIn:a.amountIn.toString()});const f=await Promise.allSettled(m.map(g=>g.resolve(a,i,l,u)));let h=null;for(const g of f)u&&g.status==="fulfilled"&&g.value&&(g.value.venue!==u.venue||g.value.calls.length!==u.calls.length||g.value.calls.some((x,w)=>x.to.toLowerCase()!==u.calls[w].to.toLowerCase()||x.data.slice(0,10)!==u.calls[w].data.slice(0,10)))||g.status==="fulfilled"&&g.value&&(!h||g.value.amountOut>h.amountOut)&&(h=g.value);if(h)return h;const y=f.find(g=>g.status==="rejected");if(y)throw y.reason;return null}async function o(a,i,l){const u=[],m=[];for(const f of a){if(!iu(f)){u.push(f);continue}const h=await r(f,i,l);if(!h)throw new d.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${f.tokenIn} \u2192 ${f.tokenOut} on chain ${i}.`,{chainId:i,tokenIn:f.tokenIn,tokenOut:f.tokenOut,amountIn:f.amountIn.toString()});u.push(...h.calls),m.push(h)}return{calls:u,resolvedSwaps:m}}return{resolveSwapIntents:o,resolveSwap:r,getVenueForChain:s,venues:t}}const Xn="0x0000000000000000000000000000000000000000",Yo=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],Li=Xn,zi=.02,gu=1800,Hi={name:"Uniswap v4",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",Xn,"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Vi={name:"Uniswap v4",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",routerHasHopPrice:!0,chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",Xn,"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Qi=M.parseAbi(["struct PoolKey { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }","struct PathKey { address intermediateCurrency; uint24 fee; int24 tickSpacing; address hooks; bytes hookData; }","struct QuoteExactSingleParams { PoolKey poolKey; bool zeroForOne; uint128 exactAmount; bytes hookData; }","struct QuoteExactParams { address exactCurrency; PathKey[] path; uint128 exactAmount; }","function quoteExactInputSingle(QuoteExactSingleParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactInput(QuoteExactParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(QuoteExactSingleParams params) returns (uint256 amountIn, uint256 gasEstimate)","function quoteExactOutput(QuoteExactParams params) returns (uint256 amountIn, uint256 gasEstimate)"]),wu=M.parseAbi(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),xu=M.parseAbi(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),Gi="0x10",yu="04",bu="06",vu="07",Cu="08",ku="09",_r="0c",eo="0e",Su=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],Iu=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],rs=(e,t)=>e.toLowerCase()===t.toLowerCase();function to(e){return F.isNativeToken(e)?Xn:e}function Au(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function Ki(e,t,n,s,r){const o=[],[a,i]=Au(e,t);for(const{fee:u,tickSpacing:m}of Yo)o.push({kind:"single",poolKey:{currency0:a,currency1:i,fee:u,tickSpacing:m,hooks:Li},zeroForOne:rs(e,a)});const l=(u,m)=>!!r&&(rs(u,Xn)&&rs(m,r)||rs(u,r)&&rs(m,Xn));for(const u of n)if(!(rs(u,e)||rs(u,t))&&!(l(u,e)||l(u,t)))for(const m of Yo)for(const f of Yo){const h=(y,g)=>({intermediateCurrency:y,fee:g.fee,tickSpacing:g.tickSpacing,hooks:Li,hookData:"0x"});o.push({kind:"multi",path:s==="in"?[h(u,m),h(t,f)]:[h(e,m),h(u,f)]})}return o}async function Yi(e,t,n,s,r,o){const a=d.getClientForChain(e),i=(await Promise.allSettled(n.map(async l=>{const{result:u}=l.kind==="single"?await a.simulateContract({address:t.quoter,abi:Qi,functionName:o==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:l.poolKey,zeroForOne:l.zeroForOne,exactAmount:r,hookData:"0x"}]}):await a.simulateContract({address:t.quoter,abi:Qi,functionName:o==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:s,path:l.path,exactAmount:r}]}),m=u[0];if(m<=0n)throw new Error("zero quote");return{candidate:l,amount:m}}))).filter(l=>l.status==="fulfilled").map(l=>l.value);return i.length===0?null:(i.sort((l,u)=>l.amount<u.amount?-1:l.amount>u.amount?1:0),o==="in"?i[i.length-1]:i[0])}function Zi(e){const{candidate:t,direction:n,currencyIn:s,currencyOut:r,recipient:o,exactAmount:a,limitAmount:i,deadline:l,routerHasHopPrice:u,sweepNativeTo:m}=e;let f,h;t.kind==="single"?(f=n==="in"?`0x${bu}${_r}${eo}`:`0x${Cu}${_r}${eo}`,h=M.encodeAbiParameters([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:Su},{name:"zeroForOne",type:"bool"},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"},...u?[{name:"minHopPriceX36",type:"uint256"}]:[],{name:"hookData",type:"bytes"}]}],[{poolKey:t.poolKey,zeroForOne:t.zeroForOne,[n==="in"?"amountIn":"amountOut"]:a,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i,...u?{minHopPriceX36:0n}:{},hookData:"0x"}])):(f=n==="in"?`0x${vu}${_r}${eo}`:`0x${ku}${_r}${eo}`,h=M.encodeAbiParameters([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:Iu},...u?[{name:"minHopPriceX36",type:"uint256[]"}]:[],{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"}]}],[{[n==="in"?"currencyIn":"currencyOut"]:n==="in"?s:r,path:t.path,...u?{minHopPriceX36:[]}:{},[n==="in"?"amountIn":"amountOut"]:a,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i}]));const y=M.encodeAbiParameters([{type:"address"},{type:"uint256"}],[s,n==="in"?a:i]),g=M.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[r,o,0n]),x=M.encodeAbiParameters([{type:"bytes"},{type:"bytes[]"}],[f,[h,y,g]]),w=m?`${Gi}${yu}`:Gi,b=m?[x,M.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[Xn,m,0n])]:[x];return M.encodeFunctionData({abi:xu,functionName:"execute",args:[w,b,l]})}function Xi(){return BigInt(Math.floor(Date.now()/1e3)+gu)}function Ji(e,t,n,s){return{to:e.permit2,value:0n,data:M.encodeFunctionData({abi:wu,functionName:"approve",args:[t,e.universalRouter,n,Number(s)]})}}function $i(e){const t=e.name??"Uniswap v4",n=e.v3?wr({...e.v3,chainIds:e.chainIds}):null;return{name:t,chainIds:e.chainIds,resolve:async(s,r,o)=>{const a=s.maxSlippage??zi,i=to(s.tokenIn),l=to(s.tokenOut),u=F.isNativeToken(s.tokenIn),m=e.hubCurrencies??[Xn];let f=null;if(!rs(i,l)&&s.amountIn>0n){const h=await Yi(r,e,Ki(i,l,m,"in",qo(r)),i,s.amountIn,"in").catch(()=>null);if(h){const y=F.applySlippage(h.amount,a),g=Xi(),x=[];u||(x.push({to:s.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[e.permit2,s.amountIn]})}),x.push(Ji(e,s.tokenIn,s.amountIn,g))),x.push({to:e.universalRouter,value:u?s.amountIn:0n,data:Zi({candidate:h.candidate,direction:"in",currencyIn:i,currencyOut:l,recipient:o,exactAmount:s.amountIn,limitAmount:y,deadline:g,routerHasHopPrice:e.routerHasHopPrice})}),f={venue:t,amountOut:h.amount,amountOutMinimum:y,calls:x}}}return!f&&n?n.resolve(s,r,o):f}}}function _i(e){const t=e.name??"Uniswap v4";return{name:t,chainIds:e.chainIds,resolve:async(n,s,r)=>{const o=F.isNativeToken(n.tokenIn),a=to(n.tokenIn),i=to(n.tokenOut);if(rs(a,i)||n.amountOut<=0n)return null;const l=n.maxSlippage??zi,u=e.hubCurrencies??[Xn],m=await Yi(s,e,Ki(a,i,u,"out",qo(s)),i,n.amountOut,"out").catch(()=>null);if(!m)return null;const f=BigInt(Math.round(l*1e4)),h=m.amount+m.amount*f/10000n,y=Xi();return{venue:t,amountIn:m.amount,amountInMax:h,amountOut:n.amountOut,calls:[...o?[]:[Ji(e,n.tokenIn,h,y)],{to:e.universalRouter,value:o?h:0n,data:Zi({candidate:m.candidate,direction:"out",currencyIn:a,currencyOut:i,recipient:r,exactAmount:n.amountOut,limitAmount:h,deadline:y,routerHasHopPrice:e.routerHasHopPrice,sweepNativeTo:o?r:void 0})}]}}}}const Zo=[{...Qo,protocol:"uniswap-v3",chainId:4114},{...Qo,protocol:"uniswap-v3",chainId:5115},{...Bi,protocol:"uniswap-v3",chainId:8453},{...Oi,protocol:"uniswap-v3",chainId:1},{...ji,protocol:"uniswap-v3",chainId:42161},{...uu,protocol:"uniswap-v3",chainId:137},{...pu,protocol:"uniswap-v3",chainId:56},{...fu,protocol:"uniswap-v3",chainId:143},{...Di,protocol:"uniswap-v3",chainId:4663},{...Ni,protocol:"uniswap-v3",chainId:4663},{...Hi,protocol:"uniswap-v4",chainId:8453},{...Vi,protocol:"uniswap-v4",chainId:4663},{...$r,protocol:"aerodrome-slipstream",chainId:8453}];function Bs(e){const t=e?.includeDefaults===!1?e.venues??[]:[...Zo,...e?.venues??[]],n=[],s=[];for(const r of t){const o=[r.chainId];switch(r.protocol){case"uniswap-v3":{const a={...r,chainIds:o};n.push(wr(a)),s.push(Ko(a));break}case"uniswap-v4":{const a={...r,chainIds:o};n.push($i(a)),s.push(_i(a));break}case"aerodrome-slipstream":{const a={...r,chainIds:o};n.push(gr(a)),s.push(Wi(a));break}default:{const a=r;throw new d.SpiceflowError("INVALID_PARAMS",`Unsupported liquidity venue protocol: ${a.protocol}`,{protocol:a.protocol})}}}return{input:n,output:s}}const Xo=new Set(["WBTC","CBTC"]),ec=new Set(["btc","wbtc","wcbtc","cbtc"]);function tc(e,t){return!e||!t?!1:e===t?!0:Xo.has(e)&&Xo.has(t)}function An(e){const[t,n,s]=e.split(":");if(t!=="evm"||!n||!s)return null;const r=Number(n);if(!Number.isFinite(r))return null;const o=s.startsWith("0x")?s.toLowerCase():`0x${s.toLowerCase()}`;return{chainId:r,address:o}}function no(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function Eu(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(no).filter(Boolean))}function Fu(e,t){const n=Eu(e),s=[t.symbol,t.name,t.equivalenceGroup].map(no);if(s.some(a=>a&&n.has(a)))return!0;const r=[...n].some(a=>ec.has(a)),o=s.some(a=>ec.has(a))||Xo.has(t.equivalenceGroup??"");return r&&o}function nc(e,t,n){const s=new Set(t.map(no).filter(Boolean)),r=o=>{if(n&&d.addressesEqual(o.address,n))return 0;const a=[o.symbol,o.name,o.equivalenceGroup].map(no).findIndex(i=>i&&s.has(i));return a===-1?4:a+1};return[...e].sort((o,a)=>{const i=r(o)-r(a);return i!==0?i:o.address.toLowerCase().localeCompare(a.address.toLowerCase())})}function Vs(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],s=[];for(const r of n){const o=An(r);if(!o||o.chainId!==t)continue;const a=o.address,i=F.isNativeToken(a)?d.getChainConfig(t)?.nativeCurrency:void 0,l=F.getTokenByAddress(a,t)??(i?{...i}:void 0);l&&(!Jo(e,a,t)&&!(e.isUniversal&&Fu(e,l))||s.some(u=>d.addressesEqual(u,a))||s.push(a))}return nc(s.map(r=>{const o=F.getTokenByAddress(r,t);return{address:r,symbol:o?.symbol,name:o?.name,equivalenceGroup:o?.equivalenceGroup}}),[e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name],e.chainId===t&&!e.isUniversal?e.address:void 0).map(r=>r.address)}function Jo(e,t,n){return e.chainId===n&&d.addressesEqual(e.address,t)?!0:yr(e.address,e.chainId,t,n)}async function sc(e,t){const n=d.getClientForChain(e),s=F.getEscrowContractAddress(e);return F.isNativeToken(t)?n.getBalance({address:s}):await n.readContract({address:t,abi:M.erc20Abi,functionName:"balanceOf",args:[s]})}function $o(e,t,n){const s=F.getTokensForChain(n),r=s.find(a=>d.addressesEqual(a.address,e));if(r&&(t===n||!F.isNativeToken(e)))return r;const o=F.getTokenByAddress(e,t);if(o)return nc(s.filter(a=>tc(a.equivalenceGroup,o.equivalenceGroup)),[o.symbol,o.name,o.equivalenceGroup])[0]}function xr(e){return e.equivalenceGroup==="USDC"&&e.symbol.toUpperCase()!=="USDT"}function Os(e){const t=F.getEscrowContract(e);if(!t||t===F.ZERO_ADDRESS)return;const n=F.getTokensForChain(e).filter(xr);return n.find(s=>s.symbol.toUpperCase()==="USDC")??n[0]}function _o(e,t){if(e.chainId===t)return null;const n=F.getEscrowContract(e.chainId),s=F.getEscrowContract(t);if(!n||n===F.ZERO_ADDRESS||!s||s===F.ZERO_ADDRESS)return null;const r=!e.isNative&&!F.isNativeToken(e.address)?F.getTokenByAddress(e.address,e.chainId):void 0,o=r&&xr(r)?$o(e.address,e.chainId,t):void 0,a=o?r:Os(e.chainId),i=o??Os(t);if(!a||!i)return null;const l=u=>({address:u.address,symbol:u.symbol,decimals:u.decimals,chainId:u.chainId});return{source:l(a),destination:l(i)}}async function rc(e,t,n){const s=F.getTokensForChain(e.chainId).filter(xr),r=[s.find(i=>d.addressesEqual(i.address,t.address)),e,...s].filter((i,l,u)=>!!i&&u.findIndex(m=>m&&d.addressesEqual(m.address,i.address))===l);let o;for(const i of r){let l;try{l=await sc(e.chainId,i.address)}catch{continue}if(l<=0n)continue;const u={...i,address:i.address};let m;try{m=await n(u)}catch{m=null}if(d.addressesEqual(u.address,e.address)&&(o=m),m&&m.amount<=l)return{token:u,...m}}const a=o===void 0?await n(e):o;return a?{token:e,...a}:null}function Tu(e,t){return!!_o(e,t)}function Dn(e,t){if(e.chainId===t)return e.address;const n=$o(e.address,e.chainId,t);return n?n.address:null}async function Jn(e,t,n,s){const r=F.getTokenByAddress(t,n);return r?r.decimals:e?.chainId===n&&d.addressesEqual(e.address,t)&&!e.isUniversal?e.decimals:s?.chainId===n&&d.addressesEqual(s.address,t)?s.decimals:d.getTokenDecimals(n,t)}async function oc(e,t,n={}){const s=Dn(e,t),r=Vs(e,t);if(r.length===0)return s;if(r.length===1)return r[0];const o=n.requiredAmount??0n,a=i=>{const l=r.map(u=>({candidate:u,balance:i.get(F.isNativeToken(u)?"native":u.toLowerCase())??0n})).filter(u=>u.balance>0n).sort((u,m)=>u.balance===m.balance?0:u.balance>m.balance?-1:1);return l.length===0?null:((o>0n?l.find(u=>u.balance>=o):l[0])??l[0]).candidate};try{const i=await Promise.all(r.map(async m=>({key:F.isNativeToken(m)?"native":m.toLowerCase(),value:await sc(t,m)}))),l=new Map(i.map(({key:m,value:f})=>[m,f])),u=a(l);if(u)return u}catch{}return s}function yr(e,t,n,s){const r=F.getTokenByAddress(e,t),o=F.getTokenByAddress(n,s);return r&&o?tc(r.equivalenceGroup,o.equivalenceGroup):F.areEquivalent(e,n)}function so(e,t){return yr(e.address,e.chainId,t.address,t.chainId)}const ac=.01;function ic(e,t=!1){const n=Number.isFinite(e.balanceUsd)&&e.balanceUsd>0;return e.isDiscovered?n&&e.balanceUsd>=ac:!t||!n||e.balanceUsd>=ac}function Qs(e,t=!1){return!!e&&e._source==="wallet"&&(e.location==="external"||e._fundingWallet==="external"||!e.location&&!e._fundingWallet&&t)}function we(e){return e.positionId??`${e.owner?.toLowerCase()??""}:${e.location??e._source??""}:${e.chainId}:${e.receiptTokenId??F.normalizeNativeTokenAddress(e.address).toLowerCase()}`}function cc(e,t){if(!t?.length||e.symbol!==void 0&&d.isAssetAllowed({...e,symbol:e.symbol},t))return!0;const n=s=>t.some(r=>d.addressesEqual(F.normalizeNativeTokenAddress(r),F.normalizeNativeTokenAddress(s)));return n(e.address)||Object.keys(e.chainTokens??{}).some(s=>{const r=An(s);return r?n(r.address):!1})}function Yn(e,t,n,s,r,o){const a=(x,w=!1)=>({eligible:!1,reason:x,policyExcluded:w}),i=e._source==="wallet"||e.location==="external"||e.location==="embedded",l=t==="spend-source"&&i&&!!s&&e.chainId===s.chainId&&d.addressesEqual(F.normalizeNativeTokenAddress(e.address),F.normalizeNativeTokenAddress(s.address));if(n.isWhitelistGateActive||!l&&!d.isAssetAllowed(e,n.allowedTokens))return a("Asset excluded by client policy",!0);if(t!=="withdraw-destination"&&!l&&!ic(e))return a("Asset is unpriced or below the minimum value",!0);if(t==="holding")return{eligible:!0,reason:null};if(e.balanceError)return a(e.balanceError);if(!l&&!cc(e,r))return a("Asset excluded by action policy",!0);const u=new Set(s?[s.chainId]:[]);e._source!=="spice"&&e.location!=="rollup"&&u.add(e.chainId);for(const x of u)if(!d.getRpcUrlForChain(x,n.rpcOverrides)?.trim())return a(`Configure SpiceFlowProvider rpcOverrides[${x}] before using this asset.`);if(o?.requiresEscrow){const x=F.getTokenByAddress(e.address,e.chainId);if(!x||!xr(x))return a("This asset has no supported escrow mapping")}if(!s)return{eligible:!0,reason:null};const m=n.liquidityVenues?.includeDefaults===!1?n.liquidityVenues.venues??[]:[...Zo,...n.liquidityVenues?.venues??[]],f=x=>m.some(w=>w.chainId===x),h=i&&e.chainId!==s.chainId,y=h?_o(e,s.chainId):null;if(h&&!y)return a("No supported source route");if(y&&!d.addressesEqual(F.normalizeNativeTokenAddress(e.address),F.normalizeNativeTokenAddress(y.source.address))&&!f(e.chainId))return a("No conversion venue configured on the source chain");const g=y?.destination.address??Dn(e,s.chainId);return t==="withdraw-destination"?(e.chainTokens||e.receiptTokenId?Vs(e,s.chainId):g?[g]:[]).some(x=>d.addressesEqual(F.normalizeNativeTokenAddress(x),F.normalizeNativeTokenAddress(s.address)))?{eligible:!0,reason:null}:a("No supported withdrawal mapping"):g&&d.addressesEqual(F.normalizeNativeTokenAddress(g),F.normalizeNativeTokenAddress(s.address))?{eligible:!0,reason:null}:!g&&!Tu(e,s.chainId)?a("No supported destination route"):f(s.chainId)?{eligible:!0,reason:null}:a("No conversion venue configured on the destination chain")}function ro(){const e=p.useContext(d.SpiceFlowProviderContext),[t]=p.useState(d.createInventoryStore);return e?.inventory??t}function ea(e,t,n,s,r){const o=ro(),a=r??o,i=p.useMemo(()=>a.entry(e),[a,e]),[,l]=p.useState(0);p.useEffect(()=>{if(n)return i.subscribe(()=>l(m=>m+1),t,s)},[i,n,t,s]);const u=p.useCallback(()=>i.refresh(),[i]);return{...n?i.snapshot():d.EMPTY_INVENTORY,refresh:u}}var lc="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAA6lBMVEXc3NzX/v/1hRvZ2dnd3dzb29va7fpMaXHa1tPc3N35/v/c3Nzc3NzCrp/c3Nza2tp1PRbLsJzlr33uhSj0kTHcnWnUva7jdhuNX0B6Qhrsk0LOxMCFVDJ+RyGhfGTkeiGYVSHjdx3lij7khDPEsaPfoW/jgjLQuKXmgzB2PRb2hRvldhvjdRv4hhvpeRtwORb/ihryghvabhnsehrUaRjLXxXtfRt7PxXwexricRbRYhURFBeSTBe0XBrEZxmDRxiiVRrlgCbfzMAvLCmrWBgbMEh9UjBbOBe2pJi9byekk4nkgDHkgDJLNB7jlKArAAAAKXRSTlMzJv0TNSYsADUxKBwK/QUZ/URTx650/vqJ5YpMosxj3ezwkqa6/q3KrihQ98kAAAAJcEhZcwAACxMAAAsTAQCanBgAAATxSURBVHjapVeJcuI4EJXBdiRuw4JzDAFyzeIT22BsNgTIJNnM7Pz/90xLsmV5ChJm6SqqZOR+7teXWujsgLSqdU0jBCFCNK1ebR16D+39t1HXiKqqGDHBsCRavXEsQKutIVWln0aZ0BX8o7VbRwC06gS+LHQLIWAJqbc+A6iC+h7t3BCVVD8EaGgqOqSemaFqjcMA8PkP1RnEb0bIAPXD1peNqO8H0NQj1LkR2j6Ao/XLCOh/6JcQkOD/B/oUoV4GqGb6+HNdnCFUZYBG9nmsE/whBsZE5y9g0pAAcgcQQ1V0fAgDNnRFNQiW3cAA2lwfI3wxvunqyl4z4OOK3r0ZX2CUIbRzgFZOoHY9nW7NXt9QdFTGgCddMfq9cDudXteyLdLKAPII4NqXZcffzIPJQx8zDCFgev9hksw3fmf5pYalSCDJAGAw7Uz9zkuU2CNKRQiYPrIT76Xjwws5B/BjiwG0hQHAgIr/GHpeYvb+EtIzI88LH32+fy1MaDMAKOGCAUdYPnmmE82ERI7pPS25fsEB0UCgs4ZwVO08AwB5sT0zrmQSm7b94mff7yzPa8LBDQAQSSwo5DRsKxO7MF+mwNyIBAPwjHEhIQCNgOsHwnwmF4aeWwAcUEMO97DgABAvkUv13WgrqXeWQ7moGqiqFtkivJjTCADBDWTzZR9SE6pIquOSF6msGYdgPS0BSD4EJ6CikUB+DKcd2QkRB4hkF3SmQyyqHioKaViicF4AQEp7DqfgRJDCSwFxLlPQ5GMAAHJ9n4bRyQEcGkZ/HwColwBYHH3fXz6uHc+xnZgCxLDwnPXj0mcgUhRpOZSblTEE9c32ybMi27ELAHiILO9puwGIoXG48YEJ43UYzGYumG/LADbQcGezIFyPjRr+7aCREfTezLUqFtMB4QB87cSw4c56uqyPSz4A/S6UDuikqzkTmwLYfL1K4aFiVbolBCKHEWHlclahyRvMF4vFarWgOm5KV4vFnIbEqswuFUmD5oF0olAGFZ7+88VqvV05FMBZbderxZwXRqXEgSaSfCTp3cDiAIETvr2+riP64K1fX99ClhMA4AIH+YAqFVPGgGnFu+9v44Quk/Hb913suXyjzAGKSS7nnAEtgBg6WeAxLIjrLM56A+NQKueioVAGruW67OdWrCCwYqoS01XgZmLJHGhDkVqa3oXeSyUESaktvBrBJ5WU/sd3IxFI3tKKpkrwCDIQcjCkUfPAnIAJ+NSjcQ1tuuuNMCk11TORCVh5SEyWdXP2dmzxpk4TEzDnbMtM/lakligfLADQj3gOOysASNPd5l+QzS5NAWCVbUV9RTBol442cIIxsVnlwPthurtv/sOkeb9LQ2oS25qIcs6PNtmNvch0HBOKN/15P3h+5wDvz4P7/1IocNhzop7swvLxTjMpMm0viSa9m6/Pg+cf35j8gOXXm94kSjzbjIo8Esd7cbxCIBNzdNs3dAXdDQbN9ybIe3MwuEOKbvRvR2YigigNGNKMh28vu0ihswGp9ZuDJpNBs0+HFjjuUffyFpcnvfKQhbgym06wcnXHAe6umNWYjSlKkcXlMa8YpIrEIldMCMHyrLNvzDs0aBImxwyap4+6pw/bp4/71A/opAvH6Vee0y9dn1z70OfXvuziudcMSKdjLp786quecPWVL99Zfqt/ePkuX/8Jv/43Dl3/fwH9bPJ09nq7MQAAAABJRU5ErkJggg==",Ru="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAQlBMVEVMaXGGl/+Elf+HmP+Hmf+Hl/+Gl/+Flv+Glv+Gl/+Gl/+Gl/////+On/+Akv/4+f/v8f/i5v+9x//S2P+tuP+erP+W3PvUAAAAC3RSTlMArBlx7Isy/vvOXbb4wDYAAAAJcEhZcwAACxMAAAsTAQCanBgAAALuSURBVHjarVfbtqsgDOxu0UBpkOv//+pJRC0i2HZ58uTeqzOEyYXkduvY/Tn8KSEBpFB/w3O8/WTjoCSS6dn4S6rha477QxFGS0nHM56ckJL/ox73b+CDQAQJujKiQxTDR4qH4LN109gP8Ti/uyI46K4BUagTLZ4Cz+CZAsWzhx/oeP3RyImhjf/7ePzmxF8Hr7+zNsP3eL7GkWH4Bc8MlQ7P3/DMsIvFKHRLPzBsTWVBizIfVNMBg9H7mLQxTRdUkb9tfJxebNZjywuJW1bf2xcw4WXtzDF5bVqXuJ9HwETHNnPYeHRii0THgcwQyBxTBDQ9Fx7dEBr0TOCDYyeS6aigsFsCQIFgBh9YiVgxQA7EqM9KiCiS95nh5WsGPZ4k8ZZFRqfoY4shy9i8AaExxRgTMgcApuSODPMdRtn02wc7Z9HkPMsPa1ZVOsiRygga4udfZ5vTKKx/7GIBVFJHCUy0r705DNu3LQ9kEQ6NxMTXwWzhUTD7xlJr2MLvrZCBVazy2OD0iaC4BGh1k4cSLOSbbIuujKW4wT76aYefrGswuBJSEoBeUnaFk7nQcKEIJZRXMPsfM95O3p3KKAoRa/cJTh0pHKMybSqyiO8wMsG0wzODi7UK9u0Ah7FIJAj1+UyQcl4Gqi2uax+L/siJVKQyi+j251sbMoHTZrUqlctiojDGRX27WpivYNtdi4upKme0c/gXBmdzY7ZoOi/cWDeU7MJy+oKn3hzbT9/cFKt6pmKe9udnCoTeG103VW7EjrGZJMOD863GNzfVQ0EDP6aJUH61wBRHGZa23npYDDpuh8EnpPBRS6UUQOg9r8enzaDdmhmsPkH/da3bokkr/i0dwMmYU7lg0pRrwiVzNrW+n/dKhVzVVIbGnE9Jj86IA8glk87h+xGnGrJyzXwYNvdD1uUx7/qgeX3UvT5sXx/3ry8c11ee60vX9bXvvXjWfsC3i+d79YV19+WPH1bf/7B8Lxy8/isBINTp+v8Ph4CTcAywkiYAAAAASUVORK5CYII=",Bu="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAPFBMVEVMaXGZhueZh+eYhuWXheWYh+eYhuaXheCYhuaah+j//fmhjvOSf+Sdi+q8sOzNxO/m4fT08fapmuja0/Jb/wGxAAAACnRSTlMArEz/IYtsA87sGIEBYwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAmJJREFUeNqtV4uSgyAMRIECGhTk///1otTKG3s2Mzdz03aXbEJIQkhuYv9jIx+komhKDnxk4v1F1wT+SoxcUj3PWu8Ex39U8lH4bzt4QthL6tlDA8OP5Iv1vMADGFc5+uRQnDWdEES81EwbNquXqDuBx8va6ZcXktUYBOkc/3GixsBvwA8neFGGGO7hdyeGAsMXeM/wBJ8ziLv6LwYeisD4f4lHhiAXmH9FvzYV3AchOw6At9gFKW4KANDbsttGoSyCKd1Ab4uxkzezhBQaRfQygHB3oj2FhjwT9QgifErM6jiOrQgAXe2UmcuiIKSuHG+mki2XCH0kYqzgF1vETyYszLFaxLBMNdsgDGNFAazRoUcwrDMlDYz28RS0newGcCRlDa8TK4YgxuORGj9x8NYVEsxjKQSp/pNAw5YRcJI/JP5nYeqxjAxeIfCeRQQDyWOos/y5xR2V4NIgYhRJVkjgpralBPcvQH4PsBxIX0DjJqKRdgYLtsYPUyqh60CsACXEQew7ECvAICZp7DqwQEIQXaR+CkzaoeKr3FewQdqg4mIy36VgLyZWz4G96N5vs8sKj0UPSlJGy4fAbWX88SgGQYgJVjDXi7JaaxYo9Oj4UQ0lrHCGdN25ceiEfNoZSfIomjhcKN26DarT0q4gaiyfe2C9u9hWNUBvRghbG+yd1AZNFFrjmu+ucXMF2j60OObE7f0m+mrv/5qQkimpO+IU8fKXQ9bDMe/5oPl81P3BsP183EeGu3GoLBw/WHnuLF20sXQ9X/ueL57PV99w+Z7P5Vvj8j3fXr7j9X/f/5Vsrv9/K3NM7mGXOq0AAAAASUVORK5CYII=",br="data:image/svg+xml,%3csvg width='8' height='11' viewBox='57 6 8 11' fill='none' xmlns='http://www.w3.org/2000/svg'%3e %3cpath d='M62.7081 13.27C62.742 13.27 62.7642 13.3057 62.7491 13.3362V13.336L61.1229 16.6083C61.0892 16.6761 60.9926 16.6759 60.959 16.6083L59.3382 13.336C59.3232 13.3057 59.3453 13.27 59.3792 13.27H62.7081Z' fill='%23EA4B4B'/%3e %3cpath d='M61.0026 9.71913C61.0194 9.68524 61.0678 9.68524 61.0845 9.71913L62.747 13.0897C62.762 13.12 62.7399 13.1557 62.706 13.1557H59.3763C59.3424 13.1557 59.3203 13.12 59.3353 13.0897L61.0026 9.71913Z' fill='%23EA4B4B'/%3e %3cpath d='M60.8426 9.63827C60.8766 9.63827 60.8987 9.6741 60.8835 9.70444L59.2164 13.0594C59.1995 13.0932 59.1513 13.0932 59.1345 13.0594L57.5001 9.77047C57.47 9.70962 57.5142 9.63827 57.5821 9.63827H60.8426Z' fill='%23EA4B4B'/%3e %3cpath d='M64.5036 9.63617C64.5715 9.63618 64.6157 9.70753 64.5855 9.76838H64.5854L62.9512 13.0573C62.9344 13.0911 62.8862 13.0912 62.8692 13.0573L61.2021 9.70235C61.187 9.672 61.2091 9.63617 61.2431 9.63617H64.5036Z' fill='%23EA4B4B'/%3e %3cpath d='M62.8284 6.18281C62.862 6.11518 62.9586 6.11518 62.9922 6.18281L64.5855 9.38969C64.6157 9.45054 64.5715 9.52189 64.5036 9.52189H61.2431C61.2091 9.52189 61.187 9.48605 61.2021 9.45571L62.8283 6.18265L62.8284 6.18281Z' fill='%23EA4B4B'/%3e %3cpath d='M62.3131 6.13196C62.381 6.13196 62.4252 6.20331 62.3951 6.26416C62.154 6.74935 61.9128 7.23455 61.6718 7.71975H61.6716C61.4225 8.22125 61.1733 8.72259 60.9242 9.22409C60.9074 9.25799 60.859 9.25799 60.8422 9.22409L60.6305 8.79587C60.6275 8.78957 60.6259 8.78263 60.6259 8.77553V6.22349C60.6259 6.17297 60.6668 6.13196 60.7173 6.13196H62.3131Z' fill='%23EA4B4B'/%3e%3c/svg%3e";const vr=F.getChainMeta(1)?.logo??"",Ou=F.TOKENS.find(e=>e.symbol==="USDC")?.logo??"",ys=Object.fromEntries([...F.getMainnetChains(),...F.getTestnetChains()].map(e=>[e.id,e.logo])),Cr={metamask:lc,metaMask:lc,rabby:Ru,phantom:Bu},ta=Object.fromEntries(F.TOKENS.map(e=>[e.symbol.toUpperCase(),e.logo])),ju={usdc:[8453,1,42161,5115,4114],usdt:[1],btc:[4114,42161,1,5115],wbtc:[1],weth:[8453,1],eth:[8453,1,42161,4663,84532,46630],ctusd:[5115,4114],wcbtc:[5115,4114]},Du={btc:["wcbtc","cbtc","wbtc"]};function oo(e){return e.replace(/^test\s*/i,"").replace(/^spice/i,"").trim()}function os(e){return oo(e).toLowerCase()}function dc(e){return os(e??"").replace(/[^a-z0-9]/g,"")}function na(e){const t=os(e);return[t,...Du[t]??[]].filter(Boolean)}function Nu(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function uc(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function pc(e,t){const n=d.getChainConfig(e),s=t.toLowerCase();return s===F.ZERO_ADDRESS.toLowerCase()?n?.nativeCurrency.decimals??18:n?.supportedTokens?.find(r=>r.address.toLowerCase()===s)?.decimals??18}function Mu(e,t,n,s=[]){const r=pc(t,n),o=e.filter(i=>fc(i,t,n,s));if(o.length===0)return null;const a=o.reduce((i,l)=>Math.min(i,l.decimals??r),r);return{chainDecimals:r,receiptDecimals:a}}function fc(e,t,n,s){if(uc(e).some(o=>{const a=An(o);return a&&yr(a.address,a.chainId,n,t)}))return!0;const r=new Set(s.map(dc).filter(Boolean));return r.size===0?!1:r.has(dc(e.tokenName||e.receiptToken))}function mc(e,t,n,s=[]){const r=pc(t,n);return e.reduce((o,a)=>fc(a,t,n,s)?o+F.convertAmountBetweenDecimals(Nu(a),a.decimals??r,r):o,0n)}function hc(e,t){const n=new Set([...na(t),...na(oo(t))]);return[...e].sort((s,r)=>{const o=os(s.symbol),a=os(r.symbol),i=os(s.name),l=os(r.name),u=n.has(o)?0:n.has(i)?1:2,m=n.has(a)?0:n.has(l)?1:2;return u!==m?u-m:s.address.toLowerCase().localeCompare(r.address.toLowerCase())})[0]}function Pu(e){const t=e&&e.length>0?e:Object.keys(d.CHAIN_CONFIGS).map(Number).filter(Number.isFinite),n=new Map;for(const s of t){const r=d.getChainConfig(s);if(!r)continue;const o=`${s}:${F.ZERO_ADDRESS.toLowerCase()}`;n.has(o)||n.set(o,{address:F.ZERO_ADDRESS,chainId:s,symbol:r.nativeCurrency.symbol,name:r.nativeCurrency.name,decimals:r.nativeCurrency.decimals,isNative:!0,logoURI:ta[r.nativeCurrency.symbol.toUpperCase()]??r.logo});for(const a of r.supportedTokens??[]){const i=a.address.toLowerCase(),l=`${s}:${i}`;n.has(l)||n.set(l,{address:i,chainId:s,symbol:a.symbol,name:a.name,decimals:a.decimals,isNative:F.isNativeToken(i),logoURI:a.logo})}}return n}function Uu(e,t){const n=Pu(t),s=oo(e.tokenName),r=os(e.tokenName),o=na(e.tokenName),a=Array.isArray(e.chainTokens)?e.chainTokens.map(g=>[g,void 0]):Object.entries(e.chainTokens??{}),i=a.map(([g])=>An(g)).filter(g=>g!==null),l=new Map;for(const[g,x]of a){const w=An(g);if(!w||!Number.isSafeInteger(w.chainId)||w.chainId<0||!/^evm:[0-9]+:(?:0x)?[0-9a-fA-F]{40}$/.test(g)){if(!Array.isArray(e.chainTokens))throw new Error("Invalid chain token metadata identity");continue}if(x!==void 0&&(!x||typeof x!="object"||Array.isArray(x)||x.name!==void 0&&typeof x.name!="string"||x.decimals!==void 0&&(!Number.isInteger(x.decimals)||x.decimals<0||x.decimals>255)))throw new Error("Invalid chain token metadata");const b=`${w.chainId}:${w.address.toLowerCase()}`;if(l.has(b)){const S=l.get(b);if(S?.name!==x?.name||S?.decimals!==x?.decimals)throw new Error("Conflicting chain token metadata")}l.set(b,x)}const u=(g,x)=>{const w=l.get(`${x.chainId}:${x.address.toLowerCase()}`);return{...g,name:typeof w?.name=="string"&&w.name.length>0?w.name:g.name,decimals:typeof w?.decimals=="number"?w.decimals:g.decimals}},m=i.map(g=>{const x=n.get(`${g.chainId}:${g.address.toLowerCase()}`);return x?u(x,g):void 0}).filter(g=>g!==void 0),f=ju[r]??[];if(f.length>0)for(const g of f){const x=m.filter(w=>w.chainId===g);if(x.length>0)return hc(x,e.tokenName)}if(m.length>0)return hc(m,e.tokenName);const h=Array.from(n.values()).filter(g=>o.includes(os(g.symbol))||o.includes(os(g.name)));if(f.length>0)for(const g of f){const x=h.find(w=>w.chainId===g);if(x)return x}if(h.length>0)return h[0];const y=i[0];if(y){const g=l.get(`${y.chainId}:${y.address.toLowerCase()}`);return{address:y.address,chainId:y.chainId,symbol:s||e.tokenName,name:typeof g?.name=="string"&&g.name.length>0?g.name:s||e.tokenName,decimals:typeof g?.decimals=="number"?g.decimals:e.decimals??18,isNative:F.isNativeToken(y.address),logoURI:void 0}}}function Wu(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;if(t?.length){const g=uc(e).map(An).filter(x=>x!==null);if(g.length>0&&!g.some(x=>t.includes(x.chainId)))return null}let s;try{s=Uu(e,t)}catch{return null}const r=s?.decimals??e.decimals??18,o=e.decimals??r,a=F.convertAmountBetweenDecimals(n,o,r),i=s?.address??F.ZERO_ADDRESS,l=s?.chainId??0,u=oo(e.tokenName),m=s?.symbol??u,f=s?.name??u,h=parseFloat(M.formatUnits(a,r)),y=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:i,symbol:m,name:f,decimals:r,chainId:l,balance:a,balanceFormatted:h,balanceUsd:y,isNative:s?.isNative??F.isNativeToken(i),logoURI:s?.logoURI,displaySymbol:u||m,displayName:u||f,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||f,receiptTokenDecimals:o,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}const sa=6e4,qu=3e5,gc="https://api.g.alchemy.com/prices/v1",Gs=new Map;function ao(e,t){try{const n=t??d.getRpcUrlForChain(e);if(typeof n!="string")return null;const{hostname:s,pathname:r}=new URL(n);if(!s.endsWith(".g.alchemy.com"))return null;const o=r.split("/").filter(Boolean).pop();return o?{network:s.slice(0,-14),key:o}:null}catch{return null}}const kr=(e,t)=>`${e.network}:${e.key}:${t.toLowerCase()}`;function js(e,t){const n=Gs.get(kr(e,t));if(!n?.price||n.updatedAt===void 0)return;const s=Date.now()-n.updatedAt;if(!(s>=qu))return{price:n.price,stale:s>=sa}}function wc(e){const t=Number(e.prices?.find(n=>n.currency==="usd")?.value);return Number.isFinite(t)&&t>0?t:0}async function xc(e,t,n){const s=[],r=new Set,o=Date.now();for(const a of new Set(t.map(i=>i.toLowerCase()))){const i=Gs.get(kr(e,a));i?.pending?r.add(i.pending):(!i||o-i.attemptedAt>=sa&&(i.updatedAt===void 0||o-i.updatedAt>=sa))&&s.push(a)}for(let a=0;a<s.length;a+=25){const i=s.slice(a,a+25),l=Promise.resolve().then(async()=>{try{const u=await n(i);for(const m of i){const f=u.get(m);if(!f)continue;const h=Gs.get(kr(e,m));h.price=f,h.updatedAt=Date.now()}}catch{}finally{for(const u of i)Gs.get(kr(e,u)).pending=void 0}});for(const u of i){const m=kr(e,u);Gs.set(m,{...Gs.get(m),attemptedAt:o,pending:l})}r.add(l)}await Promise.all(r)}async function ra(e,t){return await xc(e,t,async n=>{const s=await fetch(`${gc}/${e.key}/tokens/by-address`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({addresses:n.map(a=>({network:e.network,address:a}))}),signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error("Provider price request failed");const r=await s.json(),o=new Map;for(const a of r?.data??[]){if(a.network&&a.network!==e.network)continue;const i=String(a.address).toLowerCase();n.includes(i)&&o.set(i,wc(a))}return o}),new Map(t.map(n=>[n.toLowerCase(),js(e,n)?.price??0]))}async function oa(e,t){const n=`native:${t}`;return await xc(e,[n],async()=>{const s=await fetch(`${gc}/${e.key}/tokens/by-symbol?symbols=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error("Provider native price request failed");const r=(await s.json())?.data?.find(o=>o.symbol?.toUpperCase()===t.toUpperCase());return new Map([[n.toLowerCase(),r?wc(r):0]])}),js(e,n)?.price??0}async function Lu(e,t){const n=t.supportedChains,s=e.map(r=>{const o=Object.keys(r.chainTokens??{}).map(An).filter(a=>!!a&&M.isAddress(a.address)&&!!n?.includes(a.chainId));return o.sort((a,i)=>{const l=u=>u===t.nativeChainId?-1:n.indexOf(u);return l(a.chainId)-l(i.chainId)||+!d.addressesEqual(a.address,r.address)-+!d.addressesEqual(i.address,r.address)}),o.flatMap(a=>{const i=t.rpcOverrides?.[a.chainId];if(!i)return[];const l=ao(a.chainId,i);if(!l)return[];const u=F.isNativeToken(a.address)?d.getChainConfig(a.chainId)?.nativeCurrency.symbol:void 0,m=u?`native:${u}`:a.address;return[{rpc:l,token:m,address:a.address,nativeSymbol:u}]})});return(typeof document>"u"||!document.hidden)&&await Promise.all(s.map(async r=>{for(const o of r)if(o.nativeSymbol?await oa(o.rpc,o.nativeSymbol).catch(()=>0):await ra(o.rpc,[o.address]).catch(()=>new Map),js(o.rpc,o.token)?.stale===!1)break})),e.map((r,o)=>{const a=s[o].map(l=>js(l.rpc,l.token)),i=a.find(l=>l&&!l.stale)??a.find(Boolean);return{...r,balanceUsd:i?r.balanceFormatted*i.price:Number.isFinite(r.balanceUsd)&&r.balanceUsd>0?r.balanceUsd:0,priceStatus:i?i.stale?"stale":"fresh":"unavailable"}})}function zu(e,t,n){const s=p.useContext(d.SpiceFlowProviderContext),[r,o]=p.useState(()=>typeof document>"u"||!document.hidden);p.useEffect(()=>{const m=()=>o(!document.hidden);return document.addEventListener("visibilitychange",m),()=>document.removeEventListener("visibilitychange",m)},[]);const a={supportedChains:n??s?.supportedChainIds,nativeChainId:s?.nativeChainId,rpcOverrides:s?.rpcOverrides},i=JSON.stringify([e,a],(m,f)=>typeof f=="bigint"?f.toString():f),l=p.useCallback(()=>Lu(e,a),[i]),u=ea(`prices:${i}`,l,t&&r&&e.length>0,6e4);return u.updatedAt?u.assets:e}function Hu(e){const t=e.chainTokens??e.chainTokenConfig;if(Array.isArray(t))return t.filter(n=>typeof n=="string");if(t&&typeof t=="object")return t}const yc=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:s,priceEnabled:r=!1})=>{const o=p.useContext(d.SpiceFlowProviderContext),a=o?.apiUrl||d.RELAYER_API_URL,i=ro(),l=o?.supportedChainIds??t,u=JSON.stringify([...l??[]].sort((O,I)=>O-I)),m=e?.toLowerCase(),f=p.useCallback(async()=>{const O=`${a}/wallets/${m}/balance`;let I,v;try{const E=await d.relayerFetch(O,{cache:"no-store"});if(I=E.status,v=E.requestId,!E.ok)throw new Error(`Failed to fetch balance: ${E.status}`);const R=await E.json();if(!Array.isArray(R.balances))throw new Error("Invalid balance response");return R.balances.map(B=>{const W=Wu({receiptToken:typeof B.receiptToken=="string"?B.receiptToken:void 0,tokenName:String(B.tokenName??""),balanceAvailable:String(B.balanceAvailable??"0"),chainTokens:Hu(B),decimals:typeof B.decimals=="number"?B.decimals:void 0,balanceUsd:typeof B.balanceUsd=="number"||typeof B.balanceUsd=="string"?B.balanceUsd:null},l);return W?{...W,owner:m,location:"rollup",_source:"spice",positionId:`${m}:rollup:${W.receiptTokenId??W.address}`}:null}).filter(B=>B!==null)}catch(E){const R=E instanceof Error?E.name:void 0,B=I===429?"Balance refresh is temporarily busy. Wait a moment and try again.":I===408||I===504||R==="TimeoutError"?"Balance refresh timed out. Try again.":R==="AbortError"?"Balance refresh was interrupted. Try again.":"Balances are unavailable. Check your connection and try again.",W=new d.SpiceflowError("RELAYER_STATUS_ERROR",B,{endpoint:O,httpStatus:I,requestId:v,cause:E});throw d.sanitizeError(W),W}},[m,a,u,o?.nativeChainId,o?.rpcOverrides]),{assets:h,loading:y,refreshing:g,error:x,updatedAt:w}=ea(`rollup:${m}:${a}:${u}`,f,n&&!!m,s??0,i),b=JSON.stringify(t??[]),S=p.useMemo(()=>x?h.map(O=>({...O,balanceError:x,balanceStatus:"stale"})):h,[h,x]),T=zu(S,n&&r,l),k=p.useMemo(()=>T.filter(O=>!t?.length||t.includes(O.chainId)||Object.keys(O.chainTokens??{}).some(I=>t.some(v=>I.startsWith(`evm:${v}:`)))),[T,b]),A=p.useCallback(O=>k.filter(I=>I.chainId===O),[k]);return{assets:k,loading:y,error:x,hasBalance:k.some(O=>O.balance>0n),refreshing:g,updatedAt:w,refetch:i.invalidate,getAssetsByChain:A}};async function Vu(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[s,r,o]=await Promise.all([Kn.readContract(e,{address:t,abi:M.erc20Abi,functionName:"decimals"}),Kn.readContract(e,{address:t,abi:M.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Kn.readContract(e,{address:t,abi:M.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);if(!Number.isInteger(Number(s))||Number(s)<0||Number(s)>255)throw new Error("Invalid token decimals");return{decimals:Number(s),symbol:r,name:o,logoURI:void 0}}const bc=async(e,t,n)=>{const s=d.getClientForChain(t,n),r=d.getChainConfig(t),o=await Kn.getBalance(s,{address:e}),a=r.nativeCurrency,i=r.supportedTokens?.find(l=>F.isNativeToken(l.address));return{address:F.ZERO_ADDRESS,name:a.name,symbol:a.symbol,decimals:a.decimals,balance:o,balanceFormatted:Number(M.formatUnits(o,a.decimals)),balanceUsd:0,priceStatus:"unavailable",logoURI:i?.logo||r.logo,isNative:!0,chainId:t}},Qu=async(e,t,n,s,r,o,a)=>{try{if(!M.isAddress(n))return null;const i=M.getAddress(n),l=M.isAddress(e)?M.getAddress(e):e,u=d.getClientForChain(t,a),m=await Kn.readContract(u,{address:i,abi:M.erc20Abi,functionName:"balanceOf",args:[l]}),f=Number(M.formatUnits(m,o));return m>0n?{address:i,name:s,symbol:r,decimals:o,balance:m,balanceFormatted:f,balanceUsd:0,priceStatus:"unavailable",logoURI:void 0,isNative:!1,chainId:t}:null}catch(i){throw i}},vc=(e,t)=>{const n=d.getChainConfig(t);if(!n)return e;const s=new Set(e.map(o=>o.address.toLowerCase())),r=e.some(o=>o.isNative);for(const o of n.supportedTokens||[])F.isNativeToken(o.address)&&r||s.has(o.address.toLowerCase())||e.push({address:o.address,name:o.name,symbol:o.symbol,decimals:o.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,priceStatus:"unavailable",logoURI:o.logo,isNative:F.isNativeToken(o.address),chainId:t});if(!e.find(o=>o.isNative)){const o=n.supportedTokens?.find(a=>F.isNativeToken(a.address));e.push({address:F.ZERO_ADDRESS,name:n.nativeCurrency.name,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,priceStatus:"unavailable",logoURI:o?.logo||n.logo,isNative:!0,chainId:t})}return e},Gu=async(e,t,n)=>{const s=[],r=async i=>{for(const l of i){const u=await Qu(e,t,l.address,l.name,l.symbol,l.decimals,n);u&&(u.logoURI=l.logo,s.push(u))}},o=await bc(e,t,n);o.balance>0n&&s.push(o);const a=(d.getChainConfig(t)?.supportedTokens||[]).filter(i=>!F.isNativeToken(i.address));if(a.length>0)try{const i=d.getClientForChain(t,n),l=M.getAddress(e),u=a.filter(y=>M.isAddress(y.address)).map(y=>({address:M.getAddress(y.address),abi:M.erc20Abi,functionName:"balanceOf",args:[l]})),m=await i.multicall({contracts:u}),f=a.filter(y=>M.isAddress(y.address)),h=[];m.forEach((y,g)=>{if(y.status==="success"){const x=y.result;if(x&&x>0n){const w=f[g],b=Number(M.formatUnits(x,w.decimals));x>0n&&s.push({address:M.getAddress(w.address),name:w.name,symbol:w.symbol,decimals:w.decimals,balance:x,balanceFormatted:b,balanceUsd:0,priceStatus:"unavailable",logoURI:w.logo,isNative:!1,chainId:t})}}else h.push(f[g])}),await r(h)}catch{await r(a)}return{tokens:vc(s,t),chainId:t}},Ku=async(e,t,n)=>{const s=new Map,r=ao(e,n?n[e]??"":void 0);if(!r)return s;const o=t.filter(u=>F.isNativeToken(u)),a=t.filter(u=>!F.isNativeToken(u)),[i,l]=await Promise.all([a.length?ra(r,a).catch(()=>new Map):new Map,o.length?oa(r,d.getChainConfig(e)?.nativeCurrency?.symbol??"ETH").catch(()=>0):0]);for(const[u,m]of i)m>0&&s.set(u,m);if(l>0)for(const u of o)s.set(u.toLowerCase(),l);return s},Yu=async(e,t,n,s=!0,r)=>{const o=d.getClientForChain(t,r),a=M.getAddress(e),i=[];let l;do{const x=await o.request({method:"alchemy_getTokenBalances",params:[a,"erc20",l?{pageKey:l}:{}]});i.push(...x.tokenBalances),l=x.pageKey||void 0}while(l);const u=i.filter(x=>M.isAddress(x.contractAddress)&&!!x.tokenBalance&&BigInt(x.tokenBalance)>0n),m=d.getChainConfig(t)?.supportedTokens||[],f=x=>m.find(w=>w.address.toLowerCase()===x.toLowerCase()),h=[],y=await bc(e,t,r),[g]=await Promise.all([Promise.all(u.map(async x=>{const w=f(x.contractAddress);return w?{name:w.name,symbol:w.symbol,decimals:w.decimals,logo:w.logo??null}:await o.request({method:"alchemy_getTokenMetadata",params:[x.contractAddress]})})),s?ra(n,u.map(x=>x.contractAddress)):void 0,s&&y.balanceFormatted>0?oa(n,y.symbol):void 0]);if(y.balance>0n){const x=js(n,`native:${y.symbol}`);h.push({...y,balanceUsd:(x?.price??0)*y.balanceFormatted,priceStatus:x?x.stale?"stale":"fresh":"unavailable"})}return u.forEach((x,w)=>{const b=g[w];if(!Number.isInteger(b.decimals)||b.decimals===null||b.decimals<0||b.decimals>255)throw new Error(`Invalid token metadata on chain ${t}`);const S=BigInt(x.tokenBalance),T=Number(M.formatUnits(S,b.decimals));if(S<=0n)return;const k=js(n,x.contractAddress),A=(k?.price??0)*T;h.push({address:M.getAddress(x.contractAddress),name:b.name||"Unknown",symbol:b.symbol||"UNKNOWN",decimals:b.decimals,balance:S,balanceFormatted:T,balanceUsd:A,priceStatus:k?k.stale?"stale":"fresh":"unavailable",isDiscovered:!f(x.contractAddress),logoURI:b.logo||void 0,isNative:!1,chainId:t})}),{tokens:vc(h,t),chainId:t}},Cc=new Set,Zu=async(e,t,n=!0,s)=>{try{const r=ao(t,s?s[t]??"":void 0);if(r)try{return await Yu(e,t,r,n&&(typeof document>"u"||!document.hidden),s)}catch(o){Cc.has(t)||(Cc.add(t),console.warn(`Token discovery unavailable on chain ${t}; listing configured tokens only.`,o))}return await Gu(e,t,s)}catch(r){throw r}},Ks=async(e,t,n=[],s)=>{if(!e)throw new Error("Wallet address is required");const r=d.getChainsForAssets(s),o=t?.length?[...new Set(t)]:Object.keys(r).map(Number),a=await Promise.allSettled(o.map(l=>Zu(e,l,!0,s))),i={};return a.forEach((l,u)=>{const m=o[u];i[m]=l.status==="fulfilled"?l.value:{chainId:m,tokens:[],error:`Unable to refresh balances on chain ${m}`}}),(await Promise.allSettled(n.map(async l=>{const u=i[l.chainId];if(!u||u.error||u.tokens.some(w=>F.normalizeNativeTokenAddress(w.address).toLowerCase()===F.normalizeNativeTokenAddress(l.address).toLowerCase()))return;const m=d.getClientForChain(l.chainId,s),f=await Vu(m,l.address,l.decimals!==void 0&&l.symbol?{decimals:l.decimals,symbol:l.symbol,name:l.name||l.symbol,logo:l.logoURI}:void 0),h=await Kn.readContract(m,{address:l.address,abi:M.erc20Abi,functionName:"balanceOf",args:[e]});await Ku(l.chainId,[l.address],s);const y=Number(M.formatUnits(h,f.decimals)),g=ao(l.chainId,s?s[l.chainId]??"":void 0),x=g?js(g,l.address):void 0;u.tokens.push({...f,...l,name:f.name,symbol:f.symbol,decimals:f.decimals,balance:h,balanceFormatted:y,balanceUsd:(x?.price??0)*y,priceStatus:x?x.stale?"stale":"fresh":"unavailable",isNative:!1})}))).forEach((l,u)=>{if(l.status==="rejected"){const m=i[n[u].chainId];m&&(m.error=`Unable to refresh token balances on chain ${m.chainId}`)}}),i},Sr=({address:e,supportedChains:t,fetchBalances:n=Ks,additionalTokens:s=[],enabled:r=!0,refreshInterval:o=0,priceEnabled:a=!0})=>{const i=p.useContext(d.SpiceFlowProviderContext),l=ro(),u=e?.toLowerCase(),m=JSON.stringify([...i?.supportedChainIds??t??[]].sort((S,T)=>S-T)),f=JSON.stringify(s);p.useEffect(()=>l.registerTokens(s),[l,f]);const h=u&&u===i?.embeddedWalletAddress?.toLowerCase()?"embedded":"external",y=`wallet:${JSON.stringify([i?.network,i?.apiUrl,i?.rpcOverrides])}:${u}:${h}:${m}:${l.fetcherId(n)}`,g=p.useCallback(async()=>{let S;try{S=await n(u,JSON.parse(m),l.tokens(),i?.rpcOverrides)}catch(O){const I=O instanceof Error?O.message:"Unable to refresh balances";S=Object.fromEntries(JSON.parse(m).map(v=>[v,{chainId:v,tokens:[],error:I}]))}const T=l.entry(y).snapshot().assets,k=JSON.parse(m).map(O=>S[O]??{chainId:O,tokens:[],error:`Unable to refresh balances on chain ${O}`}),A=k.flatMap(O=>O.error?[O.error]:[]);return{assets:k.flatMap(O=>O.error?T.filter(I=>I.chainId===O.chainId).map(I=>({...I,balanceError:O.error,balanceStatus:"stale"})):O.tokens.map(I=>({...I,owner:u,location:h,_fundingWallet:h,_source:"wallet",positionId:`${u}:${h}:${O.chainId}:${F.normalizeNativeTokenAddress(I.address).toLowerCase()}`}))),error:A.length?A.join("; "):null}},[l,u,m,n,h,y]),x=ea(y,g,r&&!!u,o,l),w=JSON.stringify(t&&[...t].sort((S,T)=>S-T)),b=p.useMemo(()=>t?x.assets.filter(S=>t.includes(S.chainId)):x.assets,[x.assets,w]);return p.useEffect(()=>{a&&r&&u&&x.refresh()},[a]),{...x,assets:b,refreshAssets:l.invalidate,getAssetsByChain:p.useCallback(S=>b.filter(T=>T.chainId===S),[b]),getNativeAssets:p.useCallback(()=>b.filter(S=>S.isNative),[b])}};function Ds(e){const t=p.useContext(d.SpiceFlowProviderContext),n=ro(),s=e.owner??((t?.mode||"7702")!=="7702"?t?.externalWalletAddress:t?.embeddedWalletAddress),r=s?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase(),o=e.sourceChains??t?.supportedChainIds??[],a=(e.enabled??!0)&&!t?.isWhitelistGateActive,i=p.useMemo(()=>{const h=[...t?.additionalSourceTokens??[],...e.additionalSourceTokens??[],...e.destination?[e.destination]:[]];for(const y of e.supportedSourceAssets??[])for(const g of o){const x=d.getChainConfig(g)?.supportedTokens?.find(w=>d.isAssetAllowed(w,[y]));x&&h.push({...x,address:x.address,chainId:g,logoURI:x.logo})}return h},[e.destination,JSON.stringify(t?.additionalSourceTokens),JSON.stringify(e.additionalSourceTokens),JSON.stringify(e.supportedSourceAssets),JSON.stringify(o)]),l=Sr({address:s,supportedChains:o,fetchBalances:Ks,additionalTokens:i,enabled:a&&e.includeWalletAssets!==!1,refreshInterval:3e4}),u=yc({address:s,supportedChains:o,enabled:a&&e.includeRollupAssets!==!1&&!!s&&s.toLowerCase()===t?.embeddedWalletAddress?.toLowerCase(),priceEnabled:a,refetchInterval:3e4}),m=p.useMemo(()=>a?[...(e.includeWalletAssets===!1?[]:l.assets).map(h=>({...h,owner:h.owner??s,location:h.location??(r?"external":"embedded"),_source:"wallet"})),...(e.includeRollupAssets===!1||s?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase()?[]:u.assets).map(h=>({...h,owner:h.owner??s,location:"rollup",_source:"spice"}))]:[],[a,l.assets,u.assets,e.includeWalletAssets,e.includeRollupAssets,s,r,t?.embeddedWalletAddress]),f=p.useMemo(()=>m.map(h=>({asset:h,...Yn(h,e.role??"holding",{allowedTokens:t?.allowedTokens,rpcOverrides:t?.rpcOverrides,liquidityVenues:t?.liquidityVenues,isWhitelistGateActive:!!t?.isWhitelistGateActive},e.destination,e.supportedSourceAssets,{requiresEscrow:e.requiresEscrow})})),[m,t?.allowedTokens,t?.rpcOverrides,t?.liquidityVenues,t?.isWhitelistGateActive,e.role,e.destination,e.supportedSourceAssets,e.requiresEscrow]);return{positions:f,assets:p.useMemo(()=>f.filter(h=>h.eligible&&h.asset.balance>0n).map(h=>h.asset),[f]),walletAssets:p.useMemo(()=>m.filter(h=>h._source==="wallet"),[m]),rollupAssets:p.useMemo(()=>m.filter(h=>h._source==="spice"),[m]),loading:l.loading||u.loading,refreshing:l.refreshing||u.refreshing,error:l.error||u.error,refresh:n.invalidate}}function io(e,t=!0,n){const s=n?.pendingOnly===!0,r=d.relayerService.getBaseUrl(),o=`${r}:${e?.toLowerCase()??""}:${s}`,[a,i]=p.useState({scope:o,actions:[],error:null,loading:t&&!!e,updatedAt:null,revision:0}),[l,u]=p.useState(0),m=p.useCallback(()=>u(h=>h+1),[]);p.useEffect(()=>{if(!t||!e){i(w=>w.scope===o&&w.actions.length===0&&!w.error&&!w.loading&&!w.updatedAt&&w.revision===0?w:{scope:o,actions:[],error:null,loading:!1,updatedAt:null,revision:0});return}const h=new AbortController,y=new d.RelayerService;y.setBaseUrl(r);let g;i(w=>({scope:o,actions:w.scope===o?w.actions:[],error:w.scope===o?w.error:null,loading:!0,updatedAt:w.scope===o?w.updatedAt:null,revision:w.scope===o?w.revision:0}));const x=async()=>{try{const w=await y.getWalletActions(e,{pendingOnly:s,signal:h.signal});h.signal.aborted||i(b=>({scope:o,actions:w,error:null,loading:!1,updatedAt:new Date().toISOString(),revision:b.scope===o?b.revision+1:1}))}catch(w){if(h.signal.aborted)return;const b=w instanceof d.SpiceflowError&&w.context.httpStatus===404;i(b&&!s?S=>({scope:o,actions:[],error:null,loading:!1,updatedAt:new Date().toISOString(),revision:S.scope===o?S.revision+1:1}):S=>({scope:o,actions:S.scope===o?S.actions:[],error:"Activity is temporarily unavailable. Refresh to check again.",loading:!1,updatedAt:S.scope===o?S.updatedAt:null,revision:S.scope===o?S.revision:0}))}h.signal.aborted||(g=setTimeout(x,5e3))};return x(),window.addEventListener("online",m),()=>{h.abort(),g&&clearTimeout(g),window.removeEventListener("online",m)}},[r,e,t,o,s,l,m]);const f=a.scope===o;return{actions:t&&e&&f?a.actions:[],error:f?a.error:null,loading:t&&!!e&&(!f||a.loading),updatedAt:f?a.updatedAt:null,revision:f?a.revision:0,refresh:m}}function aa(e){const t=p.useRef(0),n=p.useRef(null),s=p.useRef(e.run);s.current=e.run;const r=p.useRef(e.onSkip);r.current=e.onSkip;const o=p.useRef(e.onCleanup);o.current=e.onCleanup,p.useEffect(()=>{if(!e.shouldRun){t.current+=1,n.current?.abort(),r.current?.();return}let a=!1,i=!1;const l=async h=>{if(h&&i)return;n.current?.abort();const y=new AbortController;n.current=y;const g=++t.current;i=!0;try{await s.current({isBackground:h,isCurrent:()=>!a&&t.current===g,signal:y.signal})}finally{i=!1}},u=window.setTimeout(()=>void l(!1),e.delayMs??250),m=()=>{document.hidden||l(!0)},f=e.backgroundIntervalMs?window.setInterval(m,e.backgroundIntervalMs):void 0;return f!==void 0&&document.addEventListener("visibilitychange",m),()=>{a=!0,n.current?.abort(),clearTimeout(u),f!==void 0&&(window.clearInterval(f),document.removeEventListener("visibilitychange",m)),o.current?.()}},[e.shouldRun,e.delayMs,e.backgroundIntervalMs,...e.deps])}function kc(e,t){if(e.length!==t.length)return!1;const n=F.hashChainBatches(e),s=F.hashChainBatches(t);return n.every((r,o)=>r.hash===s[o]?.hash)}const Ln=e=>new Promise(t=>setTimeout(t,e)),Xu="0xa9059cbb";function Sc(e){const t=e.findIndex(r=>F.isSpicenetChainId(r.chainId));if(t<=0)return[];const n=new Map,s=(r,o,a)=>{if(a<=0n)return;const i=`${r}:${o.toLowerCase()}`,l=n.get(i);l?l.amount+=a:n.set(i,{chainId:r,token:o,amount:a})};for(const r of e.slice(0,t)){const o=F.getEscrowContract(r.chainId);if(!(!o||o===F.ZERO_ADDRESS)){for(const a of r.calls)if(a.value&&a.value>0n&&d.addressesEqual(a.to,o)&&s(r.chainId,F.ZERO_ADDRESS,a.value),!!a.data?.startsWith(Xu))try{const i=M.decodeFunctionData({abi:M.erc20Abi,data:a.data});if(i.functionName!=="transfer")continue;const[l,u]=i.args;d.addressesEqual(l,o)&&s(r.chainId,a.to,u)}catch{}}}return[...n.values()]}function Ic(e){const t=F.getTokenByAddress(e.token,e.chainId);return[t?.equivalenceGroup,t?.symbol,t?.name]}function Ac(e,t){return mc(e,t.chainId,t.token,Ic(t))}function Ju(e,t){const n=Mu(e,t.chainId,t.token,Ic(t));return!n||n.receiptDecimals>=n.chainDecimals?t.amount:F.convertAmountBetweenDecimals(F.convertAmountBetweenDecimals(t.amount,n.chainDecimals,n.receiptDecimals),n.receiptDecimals,n.chainDecimals)}async function Ec(e){const{deposits:t,baseline:n,fetchEntries:s,timeoutMs:r=12e4,intervalMs:o,signal:a,wait:i=Ln}=e;if(t.length===0)return!0;const l=new Map(t.map(f=>[f,Ac(n,f)])),u=Date.now(),m=u+r;for(;!a?.aborted;){try{const g=await s();if(t.every(x=>Ac(g,x)-l.get(x)>=Ju(g,x)))return!0}catch{}const f=Date.now();if(f>=m)return!1;const h=f-u,y=o??(h<5e3?250:h<15e3?1e3:3e3);await i(Math.min(y,m-f))}return!1}function ia(e,t){const n=F.hashChainBatches(e).map(s=>s.hash);return M.keccak256(M.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}async function ca(e,t,n,s,r){if(s?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const o={raw:ia(t,n)},a=r?await e.signMessage(o,r):await e.signMessage(o);console.debug("[SpiceFlow:execution]",{phase:"signature-returned",at:Date.now()});const i=typeof a=="string"?a:a.signature;if(!i)throw new d.SpiceflowError("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return i}function $u(e){return e.domain==="spicenet"||F.isSpicenetChainId(e.chainId)}const Fc=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;async function _u(e,t,n){const s=(m,f)=>new d.SpiceflowError("SIGNATURE_FAILED","The wallet returned an invalid authorization. Review the action and try again.",{chainId:t.chainId,reason:m,...f?{cause:f}:{}});if(!e||typeof e!="object")throw s("missing-authorization");const r=e;for(const m of["address","contractAddress"])if(r[m]!==void 0&&(typeof r[m]!="string"||r[m].toLowerCase()!==t.address.toLowerCase()))throw s("authorization-target-mismatch");for(const m of["chainId","nonce"]){const f=r[m];if(f!==void 0&&(typeof f=="bigint"?f!==BigInt(t[m]):typeof f!="number"||!Number.isSafeInteger(f)||f!==t[m]))throw s(`authorization-${m}-mismatch`)}const{r:o,s:a,yParity:i}=r;if(typeof o!="string"||typeof a!="string"||!/^0x[0-9a-fA-F]{64}$/.test(o)||!/^0x[0-9a-fA-F]{64}$/.test(a)||i!==0&&i!==1||BigInt(o)===0n||BigInt(o)>=Fc||BigInt(a)===0n||BigInt(a)>Fc/2n)throw s("invalid-signature");const l={...t,r:o,s:a,yParity:i};let u;try{u=await M.recoverAddress({hash:M.keccak256(M.concatHex(["0x05",M.toRlp([M.toHex(t.chainId),t.address,t.nonce===0?"0x":M.toHex(t.nonce)])])),signature:l})}catch(m){throw s("invalid-signature",m)}if(u.toLowerCase()!==n.toLowerCase())throw s("authorization-signer-mismatch");return l}async function la(e){const{chainBatches:t,signingAddress:n,actions:s,cache:r,signal:o,onSignatureRequested:a,beforeSign:i}=e;if(o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(typeof n!="string"||!M.isAddress(n,{strict:!1})||n.toLowerCase()===M.zeroAddress)throw new d.SpiceflowError("INVALID_PARAMS","A valid signing address is required.");for(const h of t)if(!Number.isSafeInteger(h.chainId)||h.chainId<=0)throw new d.SpiceflowError("INVALID_PARAMS","A valid authorization chain is required.");const l=[...new Set(t.filter(h=>!$u(h)).map(h=>h.chainId))].map(h=>{const y=d.getDelegateContractAddress(h);if(!M.isAddress(y,{strict:!1})||y.toLowerCase()===M.zeroAddress)throw new d.SpiceflowError("INVALID_PARAMS","A valid delegation target is required.");return{chainId:h,client:d.getClientForChain(h),delegateContract:y}}),[u]=await Promise.all([Promise.all(l.map(async({chainId:h,client:y,delegateContract:g})=>{const x=Number(await F.getAccountNonce(n,y));if(!Number.isSafeInteger(x)||x<0)throw new d.SpiceflowError("INVALID_PARAMS","The authorization nonce is invalid.");const w=[n.toLowerCase(),h,g.toLowerCase(),x].join(":");return{chainId:h,delegateContract:g,nonce:x,cacheKey:w,cached:r?.get(w)}})),l.length?s.prepareSigning?.():void 0]);if(await i?.(),o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const m=[];let f=!1;for(const{chainId:h,delegateContract:y,nonce:g,cacheKey:x,cached:w}of u){if(w===void 0&&f&&await i?.(),o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const b=w===void 0?await s.signAuthorization({contractAddress:y,chainId:h,nonce:g},a):w;let S;try{S=await _u(b,{address:y,chainId:h,nonce:g},n)}catch(T){throw r?.delete(x),T}if(o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");f=!0,r?.set(x,S),m.push(S)}return m}const Tc=15;function ep(e){return e.now-e.lastProgressAt>=e.pollTimeoutMs}function Rc(e,t){return{intentId:e,steps:t.map(n=>({...n,status:"pending"})),overallStatus:"processing"}}function co(e,t,n){const s=e.steps.map(i=>({...i})),r=s[t];if(!r)return e;n.status==="success"||n.status==="completed"?(s[t]={...r,status:"success",transactionHash:n.transactionHash},t+1<s.length&&s[t+1].status==="pending"&&(s[t+1]={...s[t+1],status:"processing"})):n.status==="reverted"||n.status==="error"?s[t]={...r,status:"failed",transactionHash:n.transactionHash,error:n.error}:s[t]={...r,status:"processing"};const o=s.some(i=>i.status==="failed"),a=s.every(i=>i.status==="success");return{...e,steps:s,overallStatus:o?"failed":a?"success":"processing"}}function tp({checkStepStatus:e,retryStep:t,maxRetries:n=3,pollingInterval:s=2500,pollTimeoutMs:r=3e5}){const[o,a]=p.useState(null),i=p.useRef(null),l=p.useRef(null),u=p.useRef(!1),m=p.useRef(!1),f=p.useRef(0),h=p.useRef({}),y=p.useRef(0),g=p.useCallback(k=>{i.current=k,a(k)},[]),x=p.useCallback(()=>{l.current&&(clearInterval(l.current),l.current=null)},[]),w=p.useCallback(()=>{f.current=0,h.current={},y.current=0,u.current=!0,x(),g(null)},[x,g]),b=p.useCallback((k,A)=>{x(),u.current=!1,g(Rc(k,A))},[x,g]),S=p.useCallback((k,A)=>{const O=i.current;O&&g(co(O,k,A))},[g]),T=p.useCallback((k,A)=>{x(),u.current=!1,m.current=!1,f.current=0,h.current={},y.current=Date.now(),g(Rc(k,A));const O=async()=>{if(!(u.current||m.current||!e)){m.current=!0;try{if(ep({now:Date.now(),lastProgressAt:y.current,pollTimeoutMs:r})){const E=i.current;E&&g({...E,steps:E.steps.map(R=>R.status==="success"?R:{...R,status:"failed",error:"Taking longer than expected. It may still complete - check the explorer, then refresh."}),overallStatus:"failed"}),u.current=!0,x();return}const I=i.current;if(!I)return;const v=I.steps.findIndex(E=>E.status!=="success");if(v===-1){u.current=!0,x();return}if(!(v===0||I.steps[v-1].status==="success"))return;try{const E=I.steps[v].stepId,{data:R}=await e(k,E);if(f.current=0,R.status==="success"&&(y.current=Date.now()),R.status==="reverted"){const W=h.current[E]||0;if(t&&W<n){h.current[E]=W+1;try{await t(k,E)}catch(j){console.error(`[intentStatus] retry failed for step ${E}:`,j)}g(co(i.current,v,{status:"executing"}));return}}const B=co(i.current,v,R);g(B),B.overallStatus!=="processing"&&(u.current=!0,x())}catch(E){f.current+=1,console.error(`[intentStatus] poll error (${f.current}/${Tc}):`,E),f.current>=Tc&&(g(co(i.current,v,{status:"error"})),u.current=!0,x())}}finally{m.current=!1}}};O(),l.current=setInterval(O,s)},[e,t,n,s,r,x,g]);return p.useEffect(()=>()=>x(),[x]),{intentStatus:o,startStatusPolling:T,beginStatusTracking:b,applyStepUpdate:S,stopStatusPolling:x,clearStatus:w}}function np(e,t){return(t||"").trim()||`Transaction ${e}. The transaction was rejected on-chain. This may be due to insufficient balance, price changes, or health factor constraints. Please verify your positions and try again.`}const sp=350,rp=2500;async function Bc(e){const{actionId:t,intentIndex:n,intentId:s,stepIndex:r,maxPolls:o=48,maxExecuteAttempts:a=3,pollsBeforeRetry:i=5,maxConsecutiveStatusErrors:l=15,onStatusMessage:u,onStepUpdate:m,signal:f,chainId:h,startWithExecute:y=!0,observeOnly:g=!1,relayer:x=d.relayerService,completeOnExecution:w=!1}=e;if(f?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");let b="pending",S,T,k=e.initialExecuteAttempts??0,A=0,O,I;const v=new Promise((R,B)=>{O=R,I=()=>B(new d.SpiceflowError("ABORT","Execution transaction aborted"))}),E=()=>{k++,e.onExecuteAttempt?.(k),x.executeStep(t,n,r,{action:"execute"}).then(R=>{R.transactionHash&&(S=R.transactionHash),R.status==="success"&&O({status:R.status,transactionHash:R.transactionHash})}).catch(R=>{const B=R instanceof Error?R.message:String(R);console.warn(`[execution] executeStep ${r} attempt ${k} error (will poll):`,B)})};f?.addEventListener("abort",I,{once:!0});try{y&&!g&&k<a&&E();for(let R=0;R<o;R++){const B=R===0?sp:rp;try{const j=await Promise.race([Ln(B).then(()=>{}),v]);if(f?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const N=j??await Promise.race([x.checkStepStatus(s,r,w).then(D=>D.data),v]);if(f?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");A=0,b=N.status,T=N.error;const C=N.transactionHash;C&&(S=C),w&&/^0x[0-9a-f]{64}$/i.test(C??"")&&(N.executionStatus==="success"||N.executionStatus==="reverted")&&(b=N.executionStatus,T=void 0),m?.({status:b,transactionHash:S,error:T})}catch(j){if(j instanceof Error&&(j.name==="AbortError"||j instanceof d.SpiceflowError&&j.code==="ABORT"))throw j;if(A++,A>=l){if(!g)throw j;u?.("Status is temporarily unavailable. The backend continues this action.",S)}continue}if(!g&&b==="created"&&R>=k*i&&k<a&&E(),b==="reverted"||b==="error")throw new d.SpiceflowError("ON_CHAIN_REVERT",np(b,T),{status:b,txHash:S,actionId:t,intentId:s,stepId:r,chainId:h});if(b==="success"||b==="completed")return S;let W="Waiting for solver...";b==="executing"?W="Transaction executing...":b==="submitted"?W="Transaction submitted...":b==="created"&&(W="Waiting for relayer..."),u?.(W,S)}throw new d.SpiceflowError("POLLING_EXHAUSTED",`Transaction is still processing (status: ${b}). This doesn't mean it failed \u2014 the solver may still complete it. Check your positions in a few minutes, or try refreshing the page.`,{actionId:t,intentId:s,stepId:r,lastStatus:b,pollAttempts:o,maxPolls:o,txHash:S})}finally{f?.removeEventListener("abort",I)}}async function op(e){const{actionId:t,intentIndex:n,intentId:s,totalSteps:r,observeOnly:o,delayBeforeSpicenetStepMs:a=5e3,isSpicenetStep:i,beforeStep:l,maxExecuteAttemptsForStep:u,maxPolls:m=48,onStatusMessage:f,onStepUpdate:h,signal:y}=e;let g;for(let x=e.startStep??0;x<r;x++){if(!o&&x>0&&i?.(x)&&a>0&&await Ln(a),o||await l?.(x),y?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const w=u?.(x)??3,b=await Bc({actionId:t,intentIndex:n,intentId:s,stepIndex:x,observeOnly:o,startWithExecute:e.startWithExecute,relayer:e.relayer,maxPolls:m,maxExecuteAttempts:w,initialExecuteAttempts:e.executeAttempts?.get(x),onExecuteAttempt:S=>e.executeAttempts?.set(x,S),maxConsecutiveStatusErrors:w===6?5:15,onStatusMessage:f,onStepUpdate:h?S=>h(x,S):void 0,signal:y,completeOnExecution:x===r-1&&i?.(x)===!1});b&&(g=b)}return g}const ap="0xa9059cbb",ip=[F.SPICE_COMBINED_FEE_RECIPIENT,F.SPICE_GAS_FEE_RECIPIENT,F.SPICE_PLATFORM_FEE_RECIPIENT];function Oc(e){return ip.some(t=>d.addressesEqual(e,t))}function lo(e,t){return e.map(n=>{if(n.domain==="spicenet"||F.isSpicenetChainId(n.chainId)||n.calls.length===0)return n;const s=new Set((n.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&d.addressesEqual(a.to,t)).map(a=>a.token.toLowerCase()));if(s.size===0)return n;const r=[...s].some(F.isNativeToken);let o=0;for(const a of n.calls){if(r&&a.value>0n&&a.data==="0x"&&Oc(a.to)){o+=1;continue}if(!a.data?.startsWith(ap))break;try{const i=M.decodeFunctionData({abi:M.erc20Abi,data:a.data});if(i.functionName!=="transfer")break;const[l]=i.args;if(!Oc(l)||!s.has(a.to.toLowerCase()))break;o+=1}catch{break}}return o===0?n:{...n,calls:n.calls.slice(o)}})}async function da(e,t,n){if(!t||!/^0x[0-9a-f]{64}$/i.test(t))throw new Error("The destination receipt is not available yet; reconcile the existing action before retrying.");const s=()=>new d.SpiceflowError("ABORT","Execution observation retired");if(n?.aborted)throw s();const r=await new Promise((o,a)=>{const i=()=>a(s());n?.addEventListener("abort",i,{once:!0}),Promise.resolve().then(()=>e.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1})).then(o,a).finally(()=>n?.removeEventListener("abort",i))});if(n?.aborted)throw s();if(r.transactionHash?.toLowerCase()===t.toLowerCase()&&r.status==="reverted")throw new d.SpiceflowError("ON_CHAIN_REVERT","The destination transaction reverted.",{status:"reverted",txHash:t});if(r.transactionHash?.toLowerCase()!==t.toLowerCase()||r.status!=="success")throw new Error("The destination transaction has not been confirmed successfully. Reconcile the existing action before retrying.");return t}async function uo(e){let t=e.hash,n=!1;const s=Date.now()+12e4,r=a=>a.transactionHash&&a.transactionHash.toLowerCase()!==t.toLowerCase();let o=await e.client.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1,onReplaced:a=>{const i=a.transaction,l=a.replacedTransaction;if(!(a.reason==="repriced"&&l?.hash?.toLowerCase()===t.toLowerCase()&&l?.to?.toLowerCase()===e.call.to.toLowerCase()&&(l.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(l.value??0)===e.call.value&&l?.from&&l.nonce!==void 0&&/^0x[0-9a-f]{64}$/i.test(i?.hash??"")&&i?.to?.toLowerCase()===e.call.to.toLowerCase()&&(i.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(i.value??0)===e.call.value&&i.from?.toLowerCase()===l?.from?.toLowerCase()&&i.nonce===l?.nonce)){n=!0,e.onCancelled?.();return}t=i.hash,e.onRepriced?.(t)}});if(n)throw new Error("Transaction was cancelled or replaced with a different action; retry the unfinished action");if((e.confirmations??1)>1&&!r(o)&&o.status==="success"&&(o=await e.client.waitForTransactionReceipt({hash:t,timeout:Math.max(s-Date.now(),1),pollingInterval:2e3,confirmations:e.confirmations})),r(o))throw new Error("Unexpected transaction receipt; recover the submitted transaction before retrying");return{receipt:o,hash:t}}const ua=10n,cp=5;function po(e,t,n){return n?.calls.length&&n.amountOutMinimum>0n?[{chainId:e,token:t,amount:n.amountOutMinimum}]:[]}function pa(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function fo({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[t,n]})}}function lp({chainBatches:e,token:t,amount:n}){const s=pa(e),r=s[s.length-1];if(!r)return s;const o=F.getEscrowContractAddress(r.chainId);return r.calls=[...r.calls,fo({token:t,recipient:o,amount:n})],s}function jc({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:r,policy:o}){const a=pa(e),i=a[a.length-1];if(!i)throw new d.SpiceflowError("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const l=d.calculateBpsFee(s,BigInt(o?.platformBps??ua)),u=r+l;if(u>=s)throw new d.SpiceflowError("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:s.toString(),gasFee:r.toString(),spicenetFee:l.toString()});const m=s-u,f=F.getEscrowContractAddress(i.chainId),h=[];return r>0n&&h.push(fo({token:n,recipient:o?.gasRecipient??F.SPICE_GAS_FEE_RECIPIENT,amount:r})),l>0n&&h.push(fo({token:n,recipient:o?.platformRecipient??F.SPICE_PLATFORM_FEE_RECIPIENT,amount:l})),i.calls=[...i.calls,...h,fo({token:n,recipient:f,amount:m})],i.tokenTransfers=[...i.tokenTransfers??[],...r>0n?[{from:t,to:F.SPICE_GAS_FEE_RECIPIENT,token:n,amount:r}]:[],...l>0n?[{from:t,to:F.SPICE_PLATFORM_FEE_RECIPIENT,token:n,amount:l}]:[],{from:t,to:f,token:n,amount:m}],{chainBatches:a,gasFee:r,spicenetFee:l,netEscrowAmount:m,outputCredit:{chainId:i.chainId,token:n,amount:s}}}async function Dc({chainBatches:e,user:t,token:n,grossAmount:s,chainAuthorizations:r}){let o=0n,a,i=jc({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:o});for(let l=0;l<cp;l+=1){const u=F.hashChainBatches(i.chainBatches),m=await d.relayerService.estimateBatchGas({user:t,outputToken:n,chainBatches:i.chainBatches.map((h,y)=>({...h,hash:u[y].hash})),chainAuthorizations:r}),f=m.gasFee;if(f===o&&JSON.stringify(m.policy)===JSON.stringify(a))return i;a=m.policy,o=f,i=jc({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:o,policy:a})}throw new d.SpiceflowError("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function $n(e){return F.isSpicenetChainId(e.chainId)}const dp="0xa9059cbb";function Ir(e,t){return`${e}:${F.normalizeNativeTokenAddress(t).toLowerCase()}`}function Nc(e,t){return t===F.ZERO_ADDRESS.toLowerCase()?{symbol:d.getChainName(e),decimals:18}:F.getTokenByAddress(t,e)??{symbol:"tokens",decimals:18}}function up(e,t){const n=F.getTokenByAddress(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function fa(e){return d.getWalletBalanceEntries(e)}async function ma(e,t,n){const s=new Map,r=new Map,o=[...n?.walletFundingRequirement?[n.walletFundingRequirement]:[],...n?.walletFundingRequirements??[]];for(const f of o){if(f.amount<0n)throw new Error("Accepted wallet funding must not be negative");const h=Ir(f.chainId,f.token);r.set(h,(r.get(h)??0n)+f.amount),s.set(h,0n)}const a=new Map,i=new Map,l=new Map,u=new Map;for(const f of n?.actionOutputCredits??[]){const h=Ir(f.chainId,f.token);u.set(h,(u.get(h)??0n)+f.amount)}for(const f of e){if($n(f))continue;for(const g of f.tokenTransfers??[]){if(g.from!=="escrow"&&g.from!=="solver"||!d.addressesEqual(g.to,t))continue;const x=BigInt(g.amount??0);if(x<=0n)continue;const w=Ir(f.chainId,g.token);a.set(w,(a.get(w)??0n)+x),g.from==="escrow"&&i.set(w,(i.get(w)??0n)+x)}const h=F.getEscrowContract(f.chainId),y=g=>!!h&&h!==F.ZERO_ADDRESS&&d.addressesEqual(g,h);for(const g of f.calls){if(g.value&&g.value>0n){const x=Ir(f.chainId,F.ZERO_ADDRESS);s.set(x,(s.get(x)??0n)+g.value),y(g.to)&&l.set(x,(l.get(x)??0n)+g.value)}if(g.data?.startsWith(dp))try{const x=M.decodeFunctionData({abi:M.erc20Abi,data:g.data});if(x.functionName!=="transfer")continue;const[w,b]=x.args,S=g.to.toLowerCase(),T=Ir(f.chainId,S);s.set(T,(s.get(T)??0n)+b),y(w)&&l.set(T,(l.get(T)??0n)+b)}catch{}}}let m=null;for(const[f,h]of i){const y=h-(l.get(f)??0n);if(y<=0n)continue;const[g,x]=f.split(":"),w=Number(g),b=Nc(w,x);m??(m=await fa(t));const S=mc(m,w,x,up(w,x));if(!(S>=y))throw new d.SpiceflowError("INVALID_PARAMS",`Insufficient Spice ${b.symbol}: needs ${M.formatUnits(y,b.decimals)}, has ${M.formatUnits(S,b.decimals)}.`,{chainId:w,token:x,userAddress:t,requiredAmount:y.toString(),balance:S.toString(),balanceSource:"spice"})}for(const[f,h]of s){const[y,g]=f.split(":"),x=Number(y);let w=h-(a.get(f)??0n)-(u.get(f)??0n);const b=r.get(f)??0n;if(b>w&&(w=b),w<=0n)continue;const S=d.getClientForChain(x),T=g===F.ZERO_ADDRESS.toLowerCase()?await S.getBalance({address:t}):await S.readContract({address:g,abi:M.erc20Abi,functionName:"balanceOf",args:[t]});if(T>=w)continue;const k=Nc(x,g);throw new d.SpiceflowError("INVALID_PARAMS",`Insufficient ${k.symbol} on ${d.getChainName(x)}: needs ${M.formatUnits(w,k.decimals)}, has ${M.formatUnits(T,k.decimals)}.`,{chainId:x,token:g,userAddress:t,requiredAmount:w.toString(),balance:T.toString(),balanceSource:"wallet"})}}function pp({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:s}){if(!(e.some($n)||!(s?e.some(r=>$n(r)?!1:(r.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount??0)>0n)):n>0n)))throw new d.SpiceflowError("INVALID_PARAMS","Payouts funded from Spice balance require a Spicenet funding batch before the destination chain batch. Deposits into Spice balance and gas-only actions do not need one.",{tokenAddress:t,tokenTransferAmount:n.toString(),useCustomTransfers:!!s})}function fp(e,t,n,s){t.forEach((r,o)=>{if(!r.to||!r.from||!r.token||r.amount===void 0)throw new d.SpiceflowError("INVALID_TOKEN_TRANSFER",`tokenTransfers[${o}] on chain ${e} is missing required fields (to/from/token/amount). This usually means the embedded wallet wasn't ready when the intent was built \u2014 please retry.`,{chainId:e,transferIndex:o,transfer:{from:r.from,to:r.to,token:r.token,amount:r.amount?.toString()},signingAddress:n,useCustomTransfers:s})})}function mo({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:s,exp:r,signature:o,chainAuthorizations:a,useCustomTransfers:i}){const l=t,u=F.hashChainBatches(l),m=l.filter(f=>!$n(f)).length;if(pp({chainBatches:l,tokenAddress:n,tokenTransferAmount:s,useCustomTransfers:i}),!i&&s>0n&&m>1)throw new d.SpiceflowError("INVALID_PARAMS","Multiple non-Spicenet batches require explicit tokenTransfers. Pass useCustomTransfers with per-batch transfers instead of relying on the default escrow payout injection.",{nonSpicenetBatchCount:m,tokenAddress:n,tokenTransferAmount:s.toString()});return{user:e,...a?{chainAuthorizations:a}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:o,nbf:0,exp:r,chainBatches:u.map((f,h)=>{const y=l[h],g=$n(y)?[]:i?y.tokenTransfers??[]:s>0n?[{from:"escrow",to:e,token:n,amount:s}]:[];return fp(Number(f.chainId),g,e,i),{hash:f.hash,chainId:Number(f.chainId),tokenTransfers:g,calls:f.calls}})}]}}function Mc(e,t){const n=t?.depositToEscrow?.gasFundingSource==="action-output"?t.depositToEscrow:null,s=t?.depositToEscrow&&!n?lp({chainBatches:e,token:t.depositToEscrow.token,amount:t.depositToEscrow.amount}):pa(e);return{actionOutputDeposit:n,batches:s}}let ha=!1;function Ys(){const{address:e,isConnected:t,isAuthenticated:n,actions:s}=d.useWallet(),r=p.useRef(null),o=p.useRef(0),a=p.useRef(null),{intentStatus:i,startStatusPolling:l,beginStatusTracking:u,applyStepUpdate:m,clearStatus:f}=tp({checkStepStatus:(T,k)=>d.relayerService.checkStepStatus(T,k),retryStep:async(T,k)=>{const[A,O]=T.split("/"),I=parseInt(O||"0",10);await d.relayerService.executeStep(A,I,k,{action:"execute"})}}),h=p.useCallback(()=>{o.current++,a.current=null,f()},[f]),y=p.useRef(s),g=p.useRef(new Map);y.current=s;const x=p.useCallback((T,k,A,O,I)=>la({chainBatches:T,signingAddress:k,actions:y.current,cache:g.current,signal:A,onSignatureRequested:O,beforeSign:I}),[]),w=p.useCallback((T,k,A,O)=>ca(y.current,T,k,A,O),[]),b=p.useCallback(async(T,k,A,O,I,v)=>{let E={},R={};const B=(j,N,C)=>{C?.actionId&&(E={actionId:C.actionId,intentId:C.intentId,intentIndex:C.intentIndex,totalSteps:C.totalSteps,autoContinue:C.autoContinue,user:v?.userOverride||e}),O?.({step:j,message:N,...R,...E,...C})};if(ha)throw new d.SpiceflowError("CONCURRENT_EXECUTION","A execution transaction is already in progress. Please wait.");ha=!0;const W=o.current;try{if(!e)throw new d.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const j=v?.userOverride||e,N=d.relayerService.getBaseUrl(),C=a.current;if(C&&d.addressesEqual(C.user,j)&&C.apiUrl===N){if(C.resume)return await C.resume(T,k,A,I,O,v);throw C.error}a.current=null;const D=ve=>F.hashConditionalExecutionPlan(ve.map(ze=>({...ze,tokenTransfers:ze.tokenTransfers??[]})),[]),P=D(T),L=ve=>new Map(Object.entries(ve??{}).filter(([ze,xe])=>ze!=="signal"&&(typeof xe!="function"||["prepareForSigning","adjustBatchesForEstimate","resolveActionOutputCredits"].includes(ze))).map(([ze,xe])=>[ze,typeof xe=="function"?xe:JSON.stringify(xe,(qe,de)=>typeof de=="bigint"?de.toString():de)])),Q=L(v),G=await d.relayerService.supportsAutomaticContinuation({signal:I}),{actionOutputDeposit:_,batches:J}=Mc(T,v);let K=J,ee=[],te=v?.useCustomTransfers,me=Sc(K),he=null;const ye=async()=>{(v?.walletFundingRequirement||v?.walletFundingRequirements?.length)&&await ma([],j,{walletFundingRequirement:v?.walletFundingRequirement,walletFundingRequirements:v?.walletFundingRequirements});for(let ve=0;me.length>0&&ve<3;ve++)try{he=await fa(j);break}catch(ze){if(I?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(ve===2)throw new d.SpiceflowError("RELAYER_ERROR","Unable to read your Spice balance. Please try again before submitting the transaction.",{cause:ze});await Ln(1e3)}await v?.validateBeforeSubmit?.(K)};B("building","Preparing your wallet and transaction...");const be=await x(K,j,I,()=>B("signing-delegation","Confirm the authorization in your wallet..."),ye);if(B("building","Checking transaction fees and balances..."),I?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const ne=BigInt(Math.floor(Date.now()/1e3)+3600);if(_){const ve=await Dc({chainBatches:T,user:j,token:_.token,grossAmount:_.amount,chainAuthorizations:be});K=ve.chainBatches,ee=[ve.outputCredit],te=!0}if(!v?.skipPreSubmitFeeEstimate){let ve=!1;if(v?.feeExecutionMode==="user-transfer"&&v.adjustBatchesForEstimate&&d.relayerService.canValidateActionFees()){const ze=await d.relayerService.validateActionFees(mo({user:j,chainBatches:K,tokenAddress:k,tokenTransferAmount:A,exp:Number(ne),signature:"0x00",chainAuthorizations:be,useCustomTransfers:te}),{signal:I});r.current=ze;const xe=await v.adjustBatchesForEstimate({feeEstimate:ze,chainBatches:K});ve=!xe||kc(K,xe),xe&&(K=xe)}for(let ze=0;!ve&&ze<10;ze++){const xe=v?.feeExecutionMode==="user-transfer"?lo(K,j):K,qe=mo({user:j,chainBatches:xe,tokenAddress:k,tokenTransferAmount:A,exp:Number(ne),signature:"0x00",chainAuthorizations:be,useCustomTransfers:te}),de=await d.relayerService.estimateActionFees(qe,{signal:I});r.current=de;const Ye=await v?.adjustBatchesForEstimate?.({feeEstimate:de,chainBatches:K}),dt=!!Ye&&kc(K,Ye);if(!Ye||dt){ve=!0;break}K=Ye}if(!ve)throw new d.SpiceflowError("INVALID_PARAMS","Fee estimate did not converge. Please retry.")}if(v?.prepareForSigning){const ve=await v.prepareForSigning(K);if(ve.length!==K.length||ve.some((ze,xe)=>ze.chainId!==K[xe].chainId||ze.domain!==K[xe].domain))throw new Error("The funded route changed before signing");K=ve}v?.resolveActionOutputCredits&&(ee=await v.resolveActionOutputCredits()),(!v?.skipUserFundingPreflight||v.walletFundingRequirement||v.walletFundingRequirements?.length)&&await ma(v?.skipUserFundingPreflight?[]:K,j,{actionOutputCredits:ee,walletFundingRequirement:v?.walletFundingRequirement,walletFundingRequirements:v?.walletFundingRequirements}),me=Sc(K),me.length&&!he&&(he=await d.getWalletBalanceEntries(j)),await v?.validateBeforeSubmit?.(K),B("building","Preparing the signing request...");const Y=await w(K,ne,I,()=>B("signing-intent","Confirm the transaction in your wallet..."));if(I?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(N!==d.relayerService.getBaseUrl())throw new d.SpiceflowError("RELAYER_ERROR","The network changed before submission. Review your balances before trying again.");const ie=mo({user:j,chainBatches:K,tokenAddress:k,tokenTransferAmount:A,exp:Number(ne),signature:Y,chainAuthorizations:be,useCustomTransfers:te});let q=K.length-1;for(;q>=0&&$n(K[q]);)q--;R={totalSteps:K.length},q>=0&&(R={...R,destinationChainId:Number(K[q].chainId),destinationStepIndex:q});const je=Date.now();if(B("submitting","Submitting to relayer..."),await v?.validateBeforeSubmit?.(K),I?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(N!==d.relayerService.getBaseUrl())throw new d.SpiceflowError("RELAYER_ERROR","The network changed before submission. Review your balances before trying again.");console.debug("[SpiceFlow:execution]",{phase:"submit-check-complete",at:Date.now(),durationMs:Date.now()-je});const Ie=K.length;let z;try{z=await d.relayerService.createAction({...ie,...v?.externalExecution?{externalExecution:v.externalExecution}:{}},{autoContinue:G,idempotencyKey:v?.idempotencyKey,signal:I,onAccepted:ve=>{const[ze,xe="0"]=ve.intentIds[0].split("/"),qe=parseInt(xe,10);B("executing","Executing on chain...",{actionId:ze,intentId:`${ze}/${qe}`,intentIndex:qe,totalSteps:Ie,autoContinue:ve.autoContinue===!0})}})}catch(ve){throw W===o.current&&ve instanceof d.SpiceflowError&&ve.context.submissionStatus==="unknown"&&(a.current={user:j,apiUrl:N,error:ve}),ve}const[H,se]=z.intentIds[0].split("/"),le=parseInt(se||"0",10),X=`${H}/${le}`;B("executing","Executing on chain..."),B("executing","Executing on chain...",{actionId:H,intentId:X,intentIndex:le,totalSteps:K.length,autoContinue:z.autoContinue===!0});const oe=new d.RelayerService;oe.setBaseUrl(N);let Re,We=0;const ke=new Map,Fe=async(ve,ze=O,xe=!1)=>{const qe=(de,Ye,dt)=>ze?.({step:de,message:Ye,...dt});try{if((!xe||!Re)&&(Re=await op({actionId:H,intentIndex:le,intentId:X,totalSteps:Ie,signal:ve,observeOnly:z.autoContinue===!0,startWithExecute:!xe,startStep:xe?We:0,executeAttempts:ke,onStepUpdate:(de,Ye)=>{(Ye.status==="success"||Ye.status==="completed")&&(We=Math.max(We,de+1))},relayer:z.autoContinue||xe?oe:d.relayerService,...he?{delayBeforeSpicenetStepMs:0}:{},isSpicenetStep:de=>$n(K[de]),beforeStep:async de=>{if(z.autoContinue===!0||!he||!$n(K[de]))return;const Ye=await Ec({deposits:me,baseline:he,fetchEntries:()=>fa(j),signal:ve});if(ve?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(!Ye)throw new d.SpiceflowError("POLLING_EXHAUSTED","Your deposit is still waiting for Spice credit. Check this transaction's status before trying again.",{actionId:H,intentId:X,stepId:de})},maxExecuteAttemptsForStep:de=>$n(K[de])?6:3,maxPolls:z.autoContinue?Number.POSITIVE_INFINITY:180,onStatusMessage:(de,Ye)=>{qe("executing",de,{txHash:Ye,actionId:H,intentId:X,intentIndex:le,totalSteps:Ie,autoContinue:z.autoContinue===!0})}})),v?.requireDestinationReceipt){const de=[...K].reverse().find(Ye=>!$n(Ye));if(!de)throw new Error("The action has no destination transaction to verify.");await da(d.getClientForChain(de.chainId),Re,ve)}return qe("success","Transaction successful!",{txHash:Re,actionId:H,intentId:X,intentIndex:le,totalSteps:Ie,autoContinue:z.autoContinue===!0}),a.current?.resume===Ne&&(a.current=null),Re||H}catch(de){if(de instanceof d.SpiceflowError&&de.code==="ON_CHAIN_REVERT"&&de.context.status==="reverted"&&(de.context.stepId===0||Ie===1))throw a.current?.resume===Ne&&(a.current=null),de;const Ye=new d.SpiceflowError(de instanceof d.SpiceflowError?de.code:"RELAYER_STATUS_ERROR",de instanceof d.SpiceflowError&&de.code==="ON_CHAIN_REVERT"?de.message:`Your action was accepted, but its completion could not be confirmed. Check the original action before trying again. ${de instanceof Error?de.message:""}`.trim(),{...de instanceof d.SpiceflowError?de.context:{},submissionStatus:"accepted",actionId:H,intentId:X,txHash:Re,cause:de});throw W===o.current&&(a.current={user:j,apiUrl:N,error:Ye,resume:Ne}),Ye}},Ne=async(ve,ze,xe,qe,de,Ye)=>{const dt=L(Ye);if(P!==D(ve)||Q.size!==dt.size||[...Q].some(([_e,$e])=>dt.get(_e)!==$e)||!d.addressesEqual(k,ze)||A!==xe)throw a.current.error;return Fe(qe,de,!0)};return await Fe(I,O)}catch(j){throw console.error("[Execution] Error:",j),B("error",j.message||"Transaction failed",{error:j.message,...j?.context?.submissionStatus==="unknown"?{submissionStatus:"unknown",...typeof j.context.idempotencyKey=="string"&&/^0x[0-9a-f]{64}$/i.test(j.context.idempotencyKey)?{idempotencyKey:j.context.idempotencyKey}:{},...typeof j.context.user=="string"&&/^0x[0-9a-f]{40}$/i.test(j.context.user)?{user:j.context.user}:{}}:{}}),j}finally{ha=!1}},[e,n,x,w]),S=p.useCallback(async(T,k,A,O)=>{if(!e&&(!O?.userOverride||O.signAuthorizationsForEstimate))throw new d.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const I=O?.userOverride||e,v=O?.validateFeeCalls===!0&&O.feeExecutionMode==="user-transfer"&&d.relayerService.canValidateActionFees(),{actionOutputDeposit:E,batches:R}=Mc(T,O);let B=R;const W=O?.feeExecutionMode==="user-transfer"&&!v?lo(B,I):B,j=O?.signAuthorizationsForEstimate?await x(W,I):void 0;let N=O?.useCustomTransfers;E&&(B=(await Dc({chainBatches:T,user:I,token:E.token,grossAmount:E.amount,chainAuthorizations:j})).chainBatches,N=!0);const C=O?.feeExecutionMode==="user-transfer"&&!v?lo(B,I):B,D=mo({user:I,chainBatches:C,tokenAddress:k,tokenTransferAmount:A,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:j,useCustomTransfers:N}),P=await(v?d.relayerService.validateActionFees(D,{signal:O?.signal}):d.relayerService.estimateActionFees(D,{signal:O?.signal}));return r.current=P,P},[e,x]);return{execute:b,estimate:S,lastFeeEstimate:r.current,hasEmbeddedWallet:t&&n,intentStatus:i,startStatusPolling:l,beginStatusTracking:u,applyStepUpdate:m,clearStatus:h}}function Kt(e,t,n,s){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const r=10n**BigInt(t-n);return s==="ceil"?(e+r-1n)/r:e/r}function ln(e,t){if(!Number.isInteger(t)||t<0||t>255)throw new Error("Invalid token decimals");if(!/^\d+(?:\.\d*)?$/.test(e))throw new Error("Enter a valid amount.");if((e.split(".")[1]?.replace(/0+$/,"")??"").length>t)throw new Error(`Use at most ${t} decimal places for this source.`);return M.parseUnits(e,t)}function sn(e,t,n){const s=Kt(e,t,n,"floor");if(Kt(s,n,t,"floor")!==e)throw new Error(`Use at most ${n} decimal places for this delivered token.`);return s}function mp(e){return`0x77${e.slice(4)}`}function Ar({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:s,withdrawalAmount:r,deliveryRecipient:o,deliveryTransfers:a,requestTimestampMs:i,expiresAt:l,metadata:u,requestNonce:m}){if(l!==void 0&&(!Number.isSafeInteger(l)||l<=0))throw new Error("Withdrawal expiry must be a positive Unix timestamp in seconds");const f=a?.length?a:[{token:n,recipient:o,amount:r??s}],h=f.reduce((b,S)=>b+S.amount,0n);if(h<=0n)return null;const y=i??Date.now(),g=BigInt(Math.floor(y/1e3)),x=e??o,w=mp(M.keccak256(M.encodeAbiParameters([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"},...m?[{type:"bytes32"}]:[]],[x,n,o,h,BigInt(t),BigInt(y),...m?[m]:[]])));return{chainId:F.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:[{to:F.ZERO_ADDRESS,value:0n,data:M.encodeFunctionData({abi:F.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:w,nbf:0n,exp:l===void 0?g+3600n:BigInt(l),metadata:u??"{}",transfers:f.map(b=>({token:M.getAddress(b.token).toLowerCase(),to:M.getAddress(b.recipient).toLowerCase(),amount:b.amount}))}]})}]}}const ga=e=>{const[t,n]=p.useState(!1),s=p.useContext(d.SpiceFlowProviderContext),{dark:r,dk:o}=d.useSpiceBrand();if(p.useEffect(()=>{n(!0)},[]),!t)return c.jsx("div",{className:e.className,children:c.jsx("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?o.hoverBg:"#ccc",color:r?o.textSecondary:"white",border:r?`1px solid ${o.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!s){const a='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return c.jsx("div",{className:e.className,children:c.jsx("button",{onClick:()=>{e.onAuthError&&e.onAuthError(a)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?o.errorBg:"#dc2626",color:r?o.errorText:"white",border:r?`1px solid ${o.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return c.jsx(d.PrivyLogin,{...e})},Er=({size:e=20,strokeWidth:t=2,color:n="currentColor",style:s})=>c.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:s,children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),Fr=(e,t,n,s)=>({width:e,height:e,fill:"none",className:t,"aria-hidden":n??!0,style:s}),Zs=({size:e=16,color:t="currentColor",strokeWidth:n=2,direction:s="down",className:r,style:o,"aria-hidden":a})=>c.jsx("svg",{...Fr(e,r,a,{transform:s==="up"?"rotate(180deg)":void 0,transition:"transform 0.3s ease",...o}),viewBox:"0 0 16 16",children:c.jsx("path",{d:"M4 6L8 10L12 6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),hp=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsxs("svg",{...Fr(e,s,o,r),viewBox:"0 0 24 24",children:[c.jsx("circle",{cx:"11",cy:"11",r:"8",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"m21 21-4.3-4.3",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})]}),gp=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsx("svg",{...Fr(e,s,o,r),viewBox:"0 0 24 24",children:c.jsx("path",{d:"m6 9 6 6 6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),wp=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsx("svg",{...Fr(e,s,o,r),viewBox:"0 0 24 24",children:c.jsx("path",{d:"m9 18 6-6-6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Pc=({size:e=14,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsx("svg",{...Fr(e,s,o,r),viewBox:"0 0 16 16",children:c.jsx("path",{d:"M3 8L6.5 11.5L13 5",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Uc=({isSuccess:e,type:t,chainName:n,explorerUrl:s,txHash:r,dark:o=!1,successBg:a="#d1fae5",successBorder:i="#6ee7b7",successText:l="#065f46",errorBg:u="#fee2e2",errorBorder:m="#fca5a5",errorText:f="#dc2626",textSecondary:h="#6b7280"})=>c.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?a:u,border:e?`1px solid ${i}`:`1px solid ${m}`},children:[c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[c.jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c.jsx("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),c.jsxs("div",{children:[c.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:d.font.mono,letterSpacing:"0.5px",color:e?l:f},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),c.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:h},children:["on ",n]})]})]}),s&&r&&c.jsxs("a",{href:`${s}/tx/${r}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:h,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[c.jsx("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),Wc=`
|
|
2
|
+
"use strict";var Wd=Object.create;var Ci=Object.defineProperty;var qd=Object.getOwnPropertyDescriptor;var Ld=Object.getOwnPropertyNames;var zd=Object.getPrototypeOf,Hd=Object.prototype.hasOwnProperty;var Vd=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ld(t))!Hd.call(e,r)&&r!==n&&Ci(e,r,{get:()=>t[r],enumerable:!(s=qd(t,r))||s.enumerable});return e};var Qd=(e,t,n)=>(n=e!=null?Wd(zd(e)):{},Vd(t||!e||!e.__esModule?Ci(n,"default",{value:e,enumerable:!0}):n,e));const c=require("react/jsx-runtime"),d=require("./privy-CBW14wMQ.cjs"),p=require("react"),F=require("@spicenet-io/spiceflow-core"),ss=require("wagmi"),M=require("viem"),Kn=require("viem/actions"),pr=require("@privy-io/react-auth"),fr=require("react-dom");require("@tanstack/react-query");const Gd="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@100;200;300;400;500;600;700&display=swap",Kd="spiceflow-ibm-plex-mono",Yd="spiceflow-preconnect-googleapis",Zd="spiceflow-preconnect-gstatic";function Wo(e,t){if(document.getElementById(e))return;const n=t();n.id=e,document.head.appendChild(n)}function Xd(){typeof document>"u"||(Wo(Yd,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.googleapis.com",e}),Wo(Zd,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="",e}),Wo(Kd,()=>{const e=document.createElement("link");return e.rel="stylesheet",e.href=Gd,e}))}const Jd={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",84532:"0x4200000000000000000000000000000000000006"},ki=M.parseAbi(["function deposit() payable","function withdraw(uint256 wad)"]);function qo(e){return d.getChainConfig(e)?.wrappedNativeTokenAddress??Jd[e]}const Lo=(e,t)=>({to:e,value:t,data:M.encodeFunctionData({abi:ki,functionName:"deposit"})}),zo=(e,t)=>({to:e,value:0n,data:M.encodeFunctionData({abi:ki,functionName:"withdraw",args:[t]})});function Ho(e,t,n){const s=F.isNativeToken(t),r=F.isNativeToken(n);if(!s&&!r)return null;const o=qo(e);return o?{weth:o,wrapIn:s,unwrapOut:r}:null}function Si(e,t,n,s){const r=Ho(e,t,n);return!r||s<=0n?null:r.wrapIn&&!r.unwrapOut&&n.toLowerCase()===r.weth.toLowerCase()?[Lo(r.weth,s)]:r.unwrapOut&&!r.wrapIn&&t.toLowerCase()===r.weth.toLowerCase()?[zo(r.weth,s)]:null}function $d(e){return{...e,resolve:async(t,n,s,r)=>{const o=Si(n,t.tokenIn,t.tokenOut,t.amountIn);if(o)return{venue:"native-wrap",amountOut:t.amountIn,amountOutMinimum:t.amountIn,calls:o};const a=await e.resolve(t,n,s,r);if(a)return a;const i=Ho(n,t.tokenIn,t.tokenOut);if(!i)return null;const l=await e.resolve({...t,tokenIn:i.wrapIn?i.weth:t.tokenIn,tokenOut:i.unwrapOut?i.weth:t.tokenOut},n,s,r);return l?{...l,calls:[...i.wrapIn?[Lo(i.weth,t.amountIn)]:[],...l.calls,...i.unwrapOut?[zo(i.weth,l.amountOutMinimum)]:[]]}:null}}}function _d(e){return{...e,resolve:async(t,n,s)=>{const r=Si(n,t.tokenIn,t.tokenOut,t.amountOut);if(r)return{venue:"native-wrap",amountIn:t.amountOut,amountInMax:t.amountOut,amountOut:t.amountOut,calls:r};const o=await e.resolve(t,n,s);if(o)return o;const a=Ho(n,t.tokenIn,t.tokenOut);if(!a)return null;const i=await e.resolve({...t,tokenIn:a.wrapIn?a.weth:t.tokenIn,tokenOut:a.unwrapOut?a.weth:t.tokenOut},n,s);return i?{...i,calls:[...a.wrapIn?[Lo(a.weth,i.amountInMax)]:[],...i.calls,...a.unwrapOut?[zo(a.weth,i.amountOut)]:[]]}:null}}}const Ii=[100,500,3e3,1e4];function Jr(e,t,n,s,r){const o=[];for(const a of n){const i=typeof a=="object"&&!Array.isArray(a)?a:void 0,l=i?i.tokens:Array.isArray(a)?a:[a];if(!l.length||l.length>2)throw new Error("A v3 route must have one or two intermediate tokens");const u=[e,...l,t];if(i&&(i.feeTiers.length!==u.length-1||i.feeTiers.some(f=>!f.length)))throw new Error("A v3 route needs fee tiers for every pool");if(new Set(u.map(f=>f.toLowerCase())).size!==u.length)continue;const m=(f,h)=>{if(f===u.length){o.push(r==="in"?h:Ai(h));return}for(const y of i?.feeTiers[f-1]??s)m(f+1,M.concatHex([h,M.encodePacked(["uint24","address"],[y,u[f]])]))};m(1,u[0])}return[...new Set(o)]}function Ai(e){const t=e.slice(2),n=[];for(let s=0;s<t.length;){const r=n.length%2===0?40:6;n.push(t.slice(s,s+r)),s+=r}return`0x${n.reverse().join("")}`}const eu=M.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),tu=M.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),nu=1800;function Ei(e){const{config:t,route:n,tokenIn:s,tokenOut:r,recipient:o,amountOut:a}=e,i=e.amountInMaximum,l=e.routerHasDeadline?tu:eu,u=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+nu)}:{},m=n.path?M.encodeFunctionData({abi:l,functionName:"exactOutput",args:[{path:n.path,recipient:o,...u,amountOut:a,amountInMaximum:i}]}):M.encodeFunctionData({abi:l,functionName:"exactOutputSingle",args:[{tokenIn:s,tokenOut:r,fee:n.fee,recipient:o,...u,amountOut:a,amountInMaximum:i,sqrtPriceLimitX96:0n}]});return{to:t.swapRouter,value:0n,data:m}}const su=M.parseAbi(["function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)","function quoteExactOutput(bytes path, uint256 amountOut) returns (uint256 amountIn, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]);async function mr(e,t,n,s,r){const o=d.getClientForChain(e),{result:a}=await o.simulateContract({address:t.quoterV2,abi:su,functionName:r==="in"?"quoteExactInput":"quoteExactOutput",args:[n,s]}),[i,,,l]=a;if(i<=0n)throw new Error("No liquidity along this path.");return{amount:i,gasEstimate:l}}async function ru(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:r,chainId:o,config:a}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const i=(await d.getClientForChain(o).simulateContract({address:a.quoterV2,abi:F.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(i[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:i[0],sqrtPriceX96After:i[1],gasEstimate:i[3]}}async function Fi(e){const t=e.feeTiers??Ii,n=Jr(e.tokenIn,e.tokenOut,e.hubs??[],t,"in"),s=await Promise.allSettled([...t.map(async o=>({...await ru({...e,fee:o}),fee:o})),...n.map(async o=>{const a=await mr(e.chainId,e.config,o,e.amountIn,"in");return{amountOut:a.amount,sqrtPriceX96After:0n,gasEstimate:a.gasEstimate,fee:0,path:o}})]);let r=null;for(const o of s)o.status==="fulfilled"&&(!r||o.value.amountOut>r.amountOut)&&(r=o.value);if(!r)throw new Error("No liquidity found for this pair on any fee tier.");return r}const ou=[{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 au(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:r,chainId:o,config:a}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const i=(await d.getClientForChain(o).simulateContract({address:a.quoterV2,abi:ou,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(i[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:i[0],sqrtPriceX96After:i[1],gasEstimate:i[3]}}async function Ti(e){const t=e.feeTiers??Ii,n=Jr(e.tokenIn,e.tokenOut,e.hubs??[],t,"out"),s=await Promise.allSettled([...t.map(async o=>({...await au({...e,fee:o}),fee:o})),...n.map(async o=>{const a=await mr(e.chainId,e.config,o,e.amountOut,"out");return{amountIn:a.amount,sqrtPriceX96After:0n,gasEstimate:a.gasEstimate,fee:0,path:o}})]);let r=null;for(const o of s)o.status==="fulfilled"&&(!r||o.value.amountIn<r.amountIn)&&(r=o.value);if(!r)throw new Error("No liquidity found for this pair on any fee tier.");return r}function iu(e){return e.type==="swap"}const hr=.02,cu=[1,8453,42161,10,137,43114,56],lu="https://api.1inch.dev/swap/v6.0";function Vo(e,t){return F.applySlippage(e,t)}function du(e){const t=e?.baseUrl??lu;return{name:"1inch",chainIds:e?.chainIds??cu,resolve:async(n,s,r)=>{const o=n.maxSlippage??hr,a=o*100,i=F.isNativeToken(n.tokenIn)?F.NATIVE_TOKEN_ADDRESS:n.tokenIn,l=F.isNativeToken(n.tokenOut)?F.NATIVE_TOKEN_ADDRESS:n.tokenOut,u=F.isNativeToken(n.tokenIn);try{const m=new URL(`${t}/${s}/swap`);m.searchParams.set("src",i),m.searchParams.set("dst",l),m.searchParams.set("amount",n.amountIn.toString()),m.searchParams.set("from",r),m.searchParams.set("slippage",a.toString()),m.searchParams.set("disableEstimate","true"),m.searchParams.set("allowPartialFill","false");const f={Accept:"application/json"};e?.apiKey&&(f.Authorization=`Bearer ${e.apiKey}`);const h=await fetch(m.toString(),{headers:f});if(!h.ok)throw new d.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${h.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${h.status}`});const y=await h.json();if(!y.dstAmount||!y.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const g=BigInt(y.dstAmount);if(g<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const x=Vo(g,o),w=[];return y.tx.to&&!u&&w.push({to:n.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[y.tx.to,n.amountIn]})}),w.push({to:y.tx.to,value:BigInt(y.tx.value||"0"),data:y.tx.data}),{venue:"1inch",amountOut:g,amountOutMinimum:x,calls:w}}catch(m){if(m instanceof d.SpiceflowError)throw m;const f=m instanceof Error?m.message:String(m);throw new d.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${f}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:f})}}}}const Ri=[4114,5115],Qo={name:"Satsuma",swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Bi={name:"Uniswap v3",swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Oi={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[1],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]},ji={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[42161],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","0xaf88d065e77c8cC2239327C5EDb3A432268e5831"]},uu={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[137],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270","0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"]},pu={name:"Uniswap v3",swapRouter:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",quoterV2:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",chainIds:[56],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c","0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"]},fu={name:"Uniswap v3",swapRouter:"0xfe31f71c1b106eac32f1a19239c9a9a72ddfb900",quoterV2:"0x661e93cca42afacb172121ef892830ca3b70f08d",chainIds:[143],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A","0x754704Bc059F8C67012fEd69BC8A327a5aafb603"]},Di={name:"Uniswap v3",swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Ni={name:"SushiSwap",swapRouter:"0x1e406484F1F204b23cE84B9901C0171a738fd406",quoterV2:"0x3E290e5E01818002A0b672148BdC7514D861C7B3",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"],routerHasDeadline:!0},Mi=M.parseAbi(["function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),Pi=M.parseAbi(["function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),mu=M.parseAbi(["function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),hu=M.parseAbi(["function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),Go=1800,Ui=[1,50,100,200,2e3],$r={name:"Aerodrome",swapRouter:"0xcbBb8035cAc7D4B3Ca7aBb74cF7BdF900215Ce0D",quoterV2:"0x3d4C22254F86f64B7eC90ab8F7aeC1FBFD271c6C",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]};function gr(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??Ui;return{name:t,chainIds:n,resolve:async(r,o,a)=>{if(F.isNativeToken(r.tokenIn)||F.isNativeToken(r.tokenOut))return null;const i=r.maxSlippage??hr,l=[...s.map(w=>M.encodePacked(["address","uint24","address"],[r.tokenIn,w,r.tokenOut])),...Jr(r.tokenIn,r.tokenOut,e.hubCurrencies??[],s,"in")],u={quoterV2:e.quoterV2},m=await Promise.allSettled(l.map(async w=>({path:w,amountOut:(await mr(o,u,w,r.amountIn,"in")).amount})));let f=null;for(const w of m)w.status==="fulfilled"&&(!f||w.value.amountOut>f.amountOut)&&(f=w.value);if(!f)return console.warn(`[AerodromeVenue] No viable route for ${r.tokenIn} \u2192 ${r.tokenOut} on chain ${o}.`),null;const h=Vo(f.amountOut,i),y=e.deadline??BigInt(Math.floor(Date.now()/1e3)+Go),g=M.encodeFunctionData({abi:mu,functionName:"exactInput",args:[{path:f.path,recipient:a,deadline:y,amountIn:r.amountIn,amountOutMinimum:h}]}),x=[{to:r.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[e.swapRouter,r.amountIn]})},{to:e.swapRouter,value:0n,data:g}];return{venue:t,amountOut:f.amountOut,amountOutMinimum:h,calls:x}}}}function Wi(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??Ui;return{name:t,chainIds:n,resolve:async(r,o,a)=>{if(F.isNativeToken(r.tokenIn)||F.isNativeToken(r.tokenOut))return null;const i=r.maxSlippage??hr,l=[...s.map(x=>M.encodePacked(["address","uint24","address"],[r.tokenOut,x,r.tokenIn])),...Jr(r.tokenIn,r.tokenOut,e.hubCurrencies??[],s,"out")],u={quoterV2:e.quoterV2},m=await Promise.allSettled(l.map(async x=>({path:x,amountIn:(await mr(o,u,x,r.amountOut,"out")).amount})));let f=null;for(const x of m)x.status==="fulfilled"&&(!f||x.value.amountIn<f.amountIn)&&(f=x.value);if(!f)return console.warn(`[AerodromeExactOutputVenue] No viable route for ${r.tokenIn} \u2192 ${r.tokenOut} on chain ${o}.`),null;const h=BigInt(Math.round(i*1e4)),y=f.amountIn+f.amountIn*h/10000n,g=e.deadline??BigInt(Math.floor(Date.now()/1e3)+Go);return{venue:t,amountIn:f.amountIn,amountInMax:y,amountOut:r.amountOut,calls:[{to:e.swapRouter,value:0n,data:M.encodeFunctionData({abi:hu,functionName:"exactOutput",args:[{path:f.path,recipient:a,deadline:g,amountOut:r.amountOut,amountInMaximum:y}]})}]}}}}function wr(e){const t=e.name??"Uniswap v3",n=e.chainIds??Ri;return{name:t,chainIds:n,resolve:async(s,r,o,a)=>{if(F.isNativeToken(s.tokenIn)||F.isNativeToken(s.tokenOut))return null;const i=s.maxSlippage??hr;let l;try{let g;if(a){if(a.venue!==t)return null;const x=a.calls.find(b=>b.to.toLowerCase()===e.swapRouter.toLowerCase());if(!x)return null;const w=M.decodeFunctionData({abi:e.routerHasDeadline?Pi:[...Mi,...F.uniV3SwapRouterAbi],data:x.data});if(w.functionName==="exactInput"){const{path:b}=w.args[0];if(b.slice(0,42).toLowerCase()!==s.tokenIn.toLowerCase()||`0x${b.slice(-40)}`.toLowerCase()!==s.tokenOut.toLowerCase())return null;g={path:b,fee:0}}else if(w.functionName==="exactInputSingle"){const{tokenIn:b,tokenOut:S,fee:T}=w.args[0];if(b.toLowerCase()!==s.tokenIn.toLowerCase()||S.toLowerCase()!==s.tokenOut.toLowerCase())return null;g={fee:T}}else return null}l=g?.path?{...g,amountOut:(await mr(r,e,g.path,s.amountIn,"in")).amount}:await Fi({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn,chainId:r,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:g?[g.fee]:e.feeTiers,hubs:g?[]:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return console.warn(`[UniV3Venue] No viable route for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${r}.`),null}const u=Vo(l.amountOut,i),m=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+Go)}:{},f=e.routerHasDeadline?Pi:l.path?Mi:F.uniV3SwapRouterAbi,h=l.path?M.encodeFunctionData({abi:f,functionName:"exactInput",args:[{path:l.path,recipient:o,...m,amountIn:s.amountIn,amountOutMinimum:u}]}):M.encodeFunctionData({abi:f,functionName:"exactInputSingle",args:[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:l.fee,recipient:o,...m,amountIn:s.amountIn,amountOutMinimum:u,sqrtPriceLimitX96:0n}]}),y=[{to:s.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[e.swapRouter,s.amountIn]})},{to:e.swapRouter,value:0n,data:h}];return{venue:t,amountOut:l.amountOut,amountOutMinimum:u,calls:y}}}}function Ko(e){const t=e.name??"Uniswap v3",n=e.chainIds??Ri;return{name:t,chainIds:n,resolve:async(s,r,o)=>{if(F.isNativeToken(s.tokenIn)||F.isNativeToken(s.tokenOut))return null;const a=s.maxSlippage??hr;let i;try{i=await Ti({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut,chainId:r,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return null}const l=BigInt(Math.round(a*1e4)),u=i.amountIn+i.amountIn*l/10000n;return{venue:t,amountIn:i.amountIn,amountInMax:u,amountOut:s.amountOut,calls:[Ei({config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},routerHasDeadline:e.routerHasDeadline,route:i,tokenIn:s.tokenIn,tokenOut:s.tokenOut,recipient:o,amountOut:s.amountOut,amountInMaximum:u})]}}}}function qi(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(wr(e.satsuma)),e?.aerodrome!==!1&&t.push(gr(e?.aerodrome??$r)),t.push(du(e?.oneInch));const n=t.map($d);function s(a){return n.find(i=>i.chainIds.includes(a))}async function r(a,i,l,u){const m=n.filter(g=>g.chainIds.includes(i));if(m.length===0)throw new d.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${i}. Cannot resolve swap ${a.tokenIn} \u2192 ${a.tokenOut}.`,{chainId:i,tokenIn:a.tokenIn,tokenOut:a.tokenOut,amountIn:a.amountIn.toString()});const f=await Promise.allSettled(m.map(g=>g.resolve(a,i,l,u)));let h=null;for(const g of f)u&&g.status==="fulfilled"&&g.value&&(g.value.venue!==u.venue||g.value.calls.length!==u.calls.length||g.value.calls.some((x,w)=>x.to.toLowerCase()!==u.calls[w].to.toLowerCase()||x.data.slice(0,10)!==u.calls[w].data.slice(0,10)))||g.status==="fulfilled"&&g.value&&(!h||g.value.amountOut>h.amountOut)&&(h=g.value);if(h)return h;const y=f.find(g=>g.status==="rejected");if(y)throw y.reason;return null}async function o(a,i,l){const u=[],m=[];for(const f of a){if(!iu(f)){u.push(f);continue}const h=await r(f,i,l);if(!h)throw new d.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${f.tokenIn} \u2192 ${f.tokenOut} on chain ${i}.`,{chainId:i,tokenIn:f.tokenIn,tokenOut:f.tokenOut,amountIn:f.amountIn.toString()});u.push(...h.calls),m.push(h)}return{calls:u,resolvedSwaps:m}}return{resolveSwapIntents:o,resolveSwap:r,getVenueForChain:s,venues:t}}const Xn="0x0000000000000000000000000000000000000000",Yo=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],Li=Xn,zi=.02,gu=1800,Hi={name:"Uniswap v4",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",Xn,"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Vi={name:"Uniswap v4",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",routerHasHopPrice:!0,chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",Xn,"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Qi=M.parseAbi(["struct PoolKey { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }","struct PathKey { address intermediateCurrency; uint24 fee; int24 tickSpacing; address hooks; bytes hookData; }","struct QuoteExactSingleParams { PoolKey poolKey; bool zeroForOne; uint128 exactAmount; bytes hookData; }","struct QuoteExactParams { address exactCurrency; PathKey[] path; uint128 exactAmount; }","function quoteExactInputSingle(QuoteExactSingleParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactInput(QuoteExactParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(QuoteExactSingleParams params) returns (uint256 amountIn, uint256 gasEstimate)","function quoteExactOutput(QuoteExactParams params) returns (uint256 amountIn, uint256 gasEstimate)"]),wu=M.parseAbi(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),xu=M.parseAbi(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),Gi="0x10",yu="04",bu="06",vu="07",Cu="08",ku="09",_r="0c",eo="0e",Su=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],Iu=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],rs=(e,t)=>e.toLowerCase()===t.toLowerCase();function to(e){return F.isNativeToken(e)?Xn:e}function Au(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function Ki(e,t,n,s,r){const o=[],[a,i]=Au(e,t);for(const{fee:u,tickSpacing:m}of Yo)o.push({kind:"single",poolKey:{currency0:a,currency1:i,fee:u,tickSpacing:m,hooks:Li},zeroForOne:rs(e,a)});const l=(u,m)=>!!r&&(rs(u,Xn)&&rs(m,r)||rs(u,r)&&rs(m,Xn));for(const u of n)if(!(rs(u,e)||rs(u,t))&&!(l(u,e)||l(u,t)))for(const m of Yo)for(const f of Yo){const h=(y,g)=>({intermediateCurrency:y,fee:g.fee,tickSpacing:g.tickSpacing,hooks:Li,hookData:"0x"});o.push({kind:"multi",path:s==="in"?[h(u,m),h(t,f)]:[h(e,m),h(u,f)]})}return o}async function Yi(e,t,n,s,r,o){const a=d.getClientForChain(e),i=(await Promise.allSettled(n.map(async l=>{const{result:u}=l.kind==="single"?await a.simulateContract({address:t.quoter,abi:Qi,functionName:o==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:l.poolKey,zeroForOne:l.zeroForOne,exactAmount:r,hookData:"0x"}]}):await a.simulateContract({address:t.quoter,abi:Qi,functionName:o==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:s,path:l.path,exactAmount:r}]}),m=u[0];if(m<=0n)throw new Error("zero quote");return{candidate:l,amount:m}}))).filter(l=>l.status==="fulfilled").map(l=>l.value);return i.length===0?null:(i.sort((l,u)=>l.amount<u.amount?-1:l.amount>u.amount?1:0),o==="in"?i[i.length-1]:i[0])}function Zi(e){const{candidate:t,direction:n,currencyIn:s,currencyOut:r,recipient:o,exactAmount:a,limitAmount:i,deadline:l,routerHasHopPrice:u,sweepNativeTo:m}=e;let f,h;t.kind==="single"?(f=n==="in"?`0x${bu}${_r}${eo}`:`0x${Cu}${_r}${eo}`,h=M.encodeAbiParameters([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:Su},{name:"zeroForOne",type:"bool"},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"},...u?[{name:"minHopPriceX36",type:"uint256"}]:[],{name:"hookData",type:"bytes"}]}],[{poolKey:t.poolKey,zeroForOne:t.zeroForOne,[n==="in"?"amountIn":"amountOut"]:a,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i,...u?{minHopPriceX36:0n}:{},hookData:"0x"}])):(f=n==="in"?`0x${vu}${_r}${eo}`:`0x${ku}${_r}${eo}`,h=M.encodeAbiParameters([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:Iu},...u?[{name:"minHopPriceX36",type:"uint256[]"}]:[],{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"}]}],[{[n==="in"?"currencyIn":"currencyOut"]:n==="in"?s:r,path:t.path,...u?{minHopPriceX36:[]}:{},[n==="in"?"amountIn":"amountOut"]:a,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i}]));const y=M.encodeAbiParameters([{type:"address"},{type:"uint256"}],[s,n==="in"?a:i]),g=M.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[r,o,0n]),x=M.encodeAbiParameters([{type:"bytes"},{type:"bytes[]"}],[f,[h,y,g]]),w=m?`${Gi}${yu}`:Gi,b=m?[x,M.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[Xn,m,0n])]:[x];return M.encodeFunctionData({abi:xu,functionName:"execute",args:[w,b,l]})}function Xi(){return BigInt(Math.floor(Date.now()/1e3)+gu)}function Ji(e,t,n,s){return{to:e.permit2,value:0n,data:M.encodeFunctionData({abi:wu,functionName:"approve",args:[t,e.universalRouter,n,Number(s)]})}}function $i(e){const t=e.name??"Uniswap v4",n=e.v3?wr({...e.v3,chainIds:e.chainIds}):null;return{name:t,chainIds:e.chainIds,resolve:async(s,r,o)=>{const a=s.maxSlippage??zi,i=to(s.tokenIn),l=to(s.tokenOut),u=F.isNativeToken(s.tokenIn),m=e.hubCurrencies??[Xn];let f=null;if(!rs(i,l)&&s.amountIn>0n){const h=await Yi(r,e,Ki(i,l,m,"in",qo(r)),i,s.amountIn,"in").catch(()=>null);if(h){const y=F.applySlippage(h.amount,a),g=Xi(),x=[];u||(x.push({to:s.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[e.permit2,s.amountIn]})}),x.push(Ji(e,s.tokenIn,s.amountIn,g))),x.push({to:e.universalRouter,value:u?s.amountIn:0n,data:Zi({candidate:h.candidate,direction:"in",currencyIn:i,currencyOut:l,recipient:o,exactAmount:s.amountIn,limitAmount:y,deadline:g,routerHasHopPrice:e.routerHasHopPrice})}),f={venue:t,amountOut:h.amount,amountOutMinimum:y,calls:x}}}return!f&&n?n.resolve(s,r,o):f}}}function _i(e){const t=e.name??"Uniswap v4";return{name:t,chainIds:e.chainIds,resolve:async(n,s,r)=>{const o=F.isNativeToken(n.tokenIn),a=to(n.tokenIn),i=to(n.tokenOut);if(rs(a,i)||n.amountOut<=0n)return null;const l=n.maxSlippage??zi,u=e.hubCurrencies??[Xn],m=await Yi(s,e,Ki(a,i,u,"out",qo(s)),i,n.amountOut,"out").catch(()=>null);if(!m)return null;const f=BigInt(Math.round(l*1e4)),h=m.amount+m.amount*f/10000n,y=Xi();return{venue:t,amountIn:m.amount,amountInMax:h,amountOut:n.amountOut,calls:[...o?[]:[Ji(e,n.tokenIn,h,y)],{to:e.universalRouter,value:o?h:0n,data:Zi({candidate:m.candidate,direction:"out",currencyIn:a,currencyOut:i,recipient:r,exactAmount:n.amountOut,limitAmount:h,deadline:y,routerHasHopPrice:e.routerHasHopPrice,sweepNativeTo:o?r:void 0})}]}}}}const Zo=[{...Qo,protocol:"uniswap-v3",chainId:4114},{...Qo,protocol:"uniswap-v3",chainId:5115},{...Bi,protocol:"uniswap-v3",chainId:8453},{...Oi,protocol:"uniswap-v3",chainId:1},{...ji,protocol:"uniswap-v3",chainId:42161},{...uu,protocol:"uniswap-v3",chainId:137},{...pu,protocol:"uniswap-v3",chainId:56},{...fu,protocol:"uniswap-v3",chainId:143},{...Di,protocol:"uniswap-v3",chainId:4663},{...Ni,protocol:"uniswap-v3",chainId:4663},{...Hi,protocol:"uniswap-v4",chainId:8453},{...Vi,protocol:"uniswap-v4",chainId:4663},{...$r,protocol:"aerodrome-slipstream",chainId:8453}];function Bs(e){const t=e?.includeDefaults===!1?e.venues??[]:[...Zo,...e?.venues??[]],n=[],s=[];for(const r of t){const o=[r.chainId];switch(r.protocol){case"uniswap-v3":{const a={...r,chainIds:o};n.push(wr(a)),s.push(Ko(a));break}case"uniswap-v4":{const a={...r,chainIds:o};n.push($i(a)),s.push(_i(a));break}case"aerodrome-slipstream":{const a={...r,chainIds:o};n.push(gr(a)),s.push(Wi(a));break}default:{const a=r;throw new d.SpiceflowError("INVALID_PARAMS",`Unsupported liquidity venue protocol: ${a.protocol}`,{protocol:a.protocol})}}}return{input:n,output:s}}const Xo=new Set(["WBTC","CBTC"]),ec=new Set(["btc","wbtc","wcbtc","cbtc"]);function tc(e,t){return!e||!t?!1:e===t?!0:Xo.has(e)&&Xo.has(t)}function An(e){const[t,n,s]=e.split(":");if(t!=="evm"||!n||!s)return null;const r=Number(n);if(!Number.isFinite(r))return null;const o=s.startsWith("0x")?s.toLowerCase():`0x${s.toLowerCase()}`;return{chainId:r,address:o}}function no(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function Eu(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(no).filter(Boolean))}function Fu(e,t){const n=Eu(e),s=[t.symbol,t.name,t.equivalenceGroup].map(no);if(s.some(a=>a&&n.has(a)))return!0;const r=[...n].some(a=>ec.has(a)),o=s.some(a=>ec.has(a))||Xo.has(t.equivalenceGroup??"");return r&&o}function nc(e,t,n){const s=new Set(t.map(no).filter(Boolean)),r=o=>{if(n&&d.addressesEqual(o.address,n))return 0;const a=[o.symbol,o.name,o.equivalenceGroup].map(no).findIndex(i=>i&&s.has(i));return a===-1?4:a+1};return[...e].sort((o,a)=>{const i=r(o)-r(a);return i!==0?i:o.address.toLowerCase().localeCompare(a.address.toLowerCase())})}function Vs(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],s=[];for(const r of n){const o=An(r);if(!o||o.chainId!==t)continue;const a=o.address,i=F.isNativeToken(a)?d.getChainConfig(t)?.nativeCurrency:void 0,l=F.getTokenByAddress(a,t)??(i?{...i}:void 0);l&&(!Jo(e,a,t)&&!(e.isUniversal&&Fu(e,l))||s.some(u=>d.addressesEqual(u,a))||s.push(a))}return nc(s.map(r=>{const o=F.getTokenByAddress(r,t);return{address:r,symbol:o?.symbol,name:o?.name,equivalenceGroup:o?.equivalenceGroup}}),[e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name],e.chainId===t&&!e.isUniversal?e.address:void 0).map(r=>r.address)}function Jo(e,t,n){return e.chainId===n&&d.addressesEqual(e.address,t)?!0:yr(e.address,e.chainId,t,n)}async function sc(e,t){const n=d.getClientForChain(e),s=F.getEscrowContractAddress(e);return F.isNativeToken(t)?n.getBalance({address:s}):await n.readContract({address:t,abi:M.erc20Abi,functionName:"balanceOf",args:[s]})}function $o(e,t,n){const s=F.getTokensForChain(n),r=s.find(a=>d.addressesEqual(a.address,e));if(r&&(t===n||!F.isNativeToken(e)))return r;const o=F.getTokenByAddress(e,t);if(o)return nc(s.filter(a=>tc(a.equivalenceGroup,o.equivalenceGroup)),[o.symbol,o.name,o.equivalenceGroup])[0]}function xr(e){return e.equivalenceGroup==="USDC"&&e.symbol.toUpperCase()!=="USDT"}function Os(e){const t=F.getEscrowContract(e);if(!t||t===F.ZERO_ADDRESS)return;const n=F.getTokensForChain(e).filter(xr);return n.find(s=>s.symbol.toUpperCase()==="USDC")??n[0]}function _o(e,t){if(e.chainId===t)return null;const n=F.getEscrowContract(e.chainId),s=F.getEscrowContract(t);if(!n||n===F.ZERO_ADDRESS||!s||s===F.ZERO_ADDRESS)return null;const r=!e.isNative&&!F.isNativeToken(e.address)?F.getTokenByAddress(e.address,e.chainId):void 0,o=r&&xr(r)?$o(e.address,e.chainId,t):void 0,a=o?r:Os(e.chainId),i=o??Os(t);if(!a||!i)return null;const l=u=>({address:u.address,symbol:u.symbol,decimals:u.decimals,chainId:u.chainId});return{source:l(a),destination:l(i)}}async function rc(e,t,n){const s=F.getTokensForChain(e.chainId).filter(xr),r=[s.find(i=>d.addressesEqual(i.address,t.address)),e,...s].filter((i,l,u)=>!!i&&u.findIndex(m=>m&&d.addressesEqual(m.address,i.address))===l);let o;for(const i of r){let l;try{l=await sc(e.chainId,i.address)}catch{continue}if(l<=0n)continue;const u={...i,address:i.address};let m;try{m=await n(u)}catch{m=null}if(d.addressesEqual(u.address,e.address)&&(o=m),m&&m.amount<=l)return{token:u,...m}}const a=o===void 0?await n(e):o;return a?{token:e,...a}:null}function Tu(e,t){return!!_o(e,t)}function Dn(e,t){if(e.chainId===t)return e.address;const n=$o(e.address,e.chainId,t);return n?n.address:null}async function Jn(e,t,n,s){const r=F.getTokenByAddress(t,n);return r?r.decimals:e?.chainId===n&&d.addressesEqual(e.address,t)&&!e.isUniversal?e.decimals:s?.chainId===n&&d.addressesEqual(s.address,t)?s.decimals:d.getTokenDecimals(n,t)}async function oc(e,t,n={}){const s=Dn(e,t),r=Vs(e,t);if(r.length===0)return s;if(r.length===1)return r[0];const o=n.requiredAmount??0n,a=i=>{const l=r.map(u=>({candidate:u,balance:i.get(F.isNativeToken(u)?"native":u.toLowerCase())??0n})).filter(u=>u.balance>0n).sort((u,m)=>u.balance===m.balance?0:u.balance>m.balance?-1:1);return l.length===0?null:((o>0n?l.find(u=>u.balance>=o):l[0])??l[0]).candidate};try{const i=await Promise.all(r.map(async m=>({key:F.isNativeToken(m)?"native":m.toLowerCase(),value:await sc(t,m)}))),l=new Map(i.map(({key:m,value:f})=>[m,f])),u=a(l);if(u)return u}catch{}return s}function yr(e,t,n,s){const r=F.getTokenByAddress(e,t),o=F.getTokenByAddress(n,s);return r&&o?tc(r.equivalenceGroup,o.equivalenceGroup):F.areEquivalent(e,n)}function so(e,t){return yr(e.address,e.chainId,t.address,t.chainId)}const ac=.01;function ic(e,t=!1){const n=Number.isFinite(e.balanceUsd)&&e.balanceUsd>0;return e.isDiscovered?n&&e.balanceUsd>=ac:!t||!n||e.balanceUsd>=ac}function Qs(e,t=!1){return!!e&&e._source==="wallet"&&(e.location==="external"||e._fundingWallet==="external"||!e.location&&!e._fundingWallet&&t)}function we(e){return e.positionId??`${e.owner?.toLowerCase()??""}:${e.location??e._source??""}:${e.chainId}:${e.receiptTokenId??F.normalizeNativeTokenAddress(e.address).toLowerCase()}`}function cc(e,t){if(!t?.length||e.symbol!==void 0&&d.isAssetAllowed({...e,symbol:e.symbol},t))return!0;const n=s=>t.some(r=>d.addressesEqual(F.normalizeNativeTokenAddress(r),F.normalizeNativeTokenAddress(s)));return n(e.address)||Object.keys(e.chainTokens??{}).some(s=>{const r=An(s);return r?n(r.address):!1})}function Yn(e,t,n,s,r,o){const a=(x,w=!1)=>({eligible:!1,reason:x,policyExcluded:w}),i=e._source==="wallet"||e.location==="external"||e.location==="embedded",l=t==="spend-source"&&i&&!!s&&e.chainId===s.chainId&&d.addressesEqual(F.normalizeNativeTokenAddress(e.address),F.normalizeNativeTokenAddress(s.address));if(n.isWhitelistGateActive||!l&&!d.isAssetAllowed(e,n.allowedTokens))return a("Asset excluded by client policy",!0);if(t!=="withdraw-destination"&&!l&&!ic(e))return a("Asset is unpriced or below the minimum value",!0);if(t==="holding")return{eligible:!0,reason:null};if(e.balanceError)return a(e.balanceError);if(!l&&!cc(e,r))return a("Asset excluded by action policy",!0);const u=new Set(s?[s.chainId]:[]);e._source!=="spice"&&e.location!=="rollup"&&u.add(e.chainId);for(const x of u)if(!d.getRpcUrlForChain(x,n.rpcOverrides)?.trim())return a(`Configure SpiceFlowProvider rpcOverrides[${x}] before using this asset.`);if(o?.requiresEscrow){const x=F.getTokenByAddress(e.address,e.chainId);if(!x||!xr(x))return a("This asset has no supported escrow mapping")}if(!s)return{eligible:!0,reason:null};const m=n.liquidityVenues?.includeDefaults===!1?n.liquidityVenues.venues??[]:[...Zo,...n.liquidityVenues?.venues??[]],f=x=>m.some(w=>w.chainId===x),h=i&&e.chainId!==s.chainId,y=h?_o(e,s.chainId):null;if(h&&!y)return a("No supported source route");if(y&&!d.addressesEqual(F.normalizeNativeTokenAddress(e.address),F.normalizeNativeTokenAddress(y.source.address))&&!f(e.chainId))return a("No conversion venue configured on the source chain");const g=y?.destination.address??Dn(e,s.chainId);return t==="withdraw-destination"?(e.chainTokens||e.receiptTokenId?Vs(e,s.chainId):g?[g]:[]).some(x=>d.addressesEqual(F.normalizeNativeTokenAddress(x),F.normalizeNativeTokenAddress(s.address)))?{eligible:!0,reason:null}:a("No supported withdrawal mapping"):g&&d.addressesEqual(F.normalizeNativeTokenAddress(g),F.normalizeNativeTokenAddress(s.address))?{eligible:!0,reason:null}:!g&&!Tu(e,s.chainId)?a("No supported destination route"):f(s.chainId)?{eligible:!0,reason:null}:a("No conversion venue configured on the destination chain")}function ro(){const e=p.useContext(d.SpiceFlowProviderContext),[t]=p.useState(d.createInventoryStore);return e?.inventory??t}function ea(e,t,n,s,r){const o=ro(),a=r??o,i=p.useMemo(()=>a.entry(e),[a,e]),[,l]=p.useState(0);p.useEffect(()=>{if(n)return i.subscribe(()=>l(m=>m+1),t,s)},[i,n,t,s]);const u=p.useCallback(()=>i.refresh(),[i]);return{...n?i.snapshot():d.EMPTY_INVENTORY,refresh:u}}var lc="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAA6lBMVEXc3NzX/v/1hRvZ2dnd3dzb29va7fpMaXHa1tPc3N35/v/c3Nzc3NzCrp/c3Nza2tp1PRbLsJzlr33uhSj0kTHcnWnUva7jdhuNX0B6Qhrsk0LOxMCFVDJ+RyGhfGTkeiGYVSHjdx3lij7khDPEsaPfoW/jgjLQuKXmgzB2PRb2hRvldhvjdRv4hhvpeRtwORb/ihryghvabhnsehrUaRjLXxXtfRt7PxXwexricRbRYhURFBeSTBe0XBrEZxmDRxiiVRrlgCbfzMAvLCmrWBgbMEh9UjBbOBe2pJi9byekk4nkgDHkgDJLNB7jlKArAAAAKXRSTlMzJv0TNSYsADUxKBwK/QUZ/URTx650/vqJ5YpMosxj3ezwkqa6/q3KrihQ98kAAAAJcEhZcwAACxMAAAsTAQCanBgAAATxSURBVHjapVeJcuI4EJXBdiRuw4JzDAFyzeIT22BsNgTIJNnM7Pz/90xLsmV5ChJm6SqqZOR+7teXWujsgLSqdU0jBCFCNK1ebR16D+39t1HXiKqqGDHBsCRavXEsQKutIVWln0aZ0BX8o7VbRwC06gS+LHQLIWAJqbc+A6iC+h7t3BCVVD8EaGgqOqSemaFqjcMA8PkP1RnEb0bIAPXD1peNqO8H0NQj1LkR2j6Ao/XLCOh/6JcQkOD/B/oUoV4GqGb6+HNdnCFUZYBG9nmsE/whBsZE5y9g0pAAcgcQQ1V0fAgDNnRFNQiW3cAA2lwfI3wxvunqyl4z4OOK3r0ZX2CUIbRzgFZOoHY9nW7NXt9QdFTGgCddMfq9cDudXteyLdLKAPII4NqXZcffzIPJQx8zDCFgev9hksw3fmf5pYalSCDJAGAw7Uz9zkuU2CNKRQiYPrIT76Xjwws5B/BjiwG0hQHAgIr/GHpeYvb+EtIzI88LH32+fy1MaDMAKOGCAUdYPnmmE82ERI7pPS25fsEB0UCgs4ZwVO08AwB5sT0zrmQSm7b94mff7yzPa8LBDQAQSSwo5DRsKxO7MF+mwNyIBAPwjHEhIQCNgOsHwnwmF4aeWwAcUEMO97DgABAvkUv13WgrqXeWQ7moGqiqFtkivJjTCADBDWTzZR9SE6pIquOSF6msGYdgPS0BSD4EJ6CikUB+DKcd2QkRB4hkF3SmQyyqHioKaViicF4AQEp7DqfgRJDCSwFxLlPQ5GMAAHJ9n4bRyQEcGkZ/HwColwBYHH3fXz6uHc+xnZgCxLDwnPXj0mcgUhRpOZSblTEE9c32ybMi27ELAHiILO9puwGIoXG48YEJ43UYzGYumG/LADbQcGezIFyPjRr+7aCREfTezLUqFtMB4QB87cSw4c56uqyPSz4A/S6UDuikqzkTmwLYfL1K4aFiVbolBCKHEWHlclahyRvMF4vFarWgOm5KV4vFnIbEqswuFUmD5oF0olAGFZ7+88VqvV05FMBZbderxZwXRqXEgSaSfCTp3cDiAIETvr2+riP64K1fX99ClhMA4AIH+YAqFVPGgGnFu+9v44Quk/Hb913suXyjzAGKSS7nnAEtgBg6WeAxLIjrLM56A+NQKueioVAGruW67OdWrCCwYqoS01XgZmLJHGhDkVqa3oXeSyUESaktvBrBJ5WU/sd3IxFI3tKKpkrwCDIQcjCkUfPAnIAJ+NSjcQ1tuuuNMCk11TORCVh5SEyWdXP2dmzxpk4TEzDnbMtM/lakligfLADQj3gOOysASNPd5l+QzS5NAWCVbUV9RTBol442cIIxsVnlwPthurtv/sOkeb9LQ2oS25qIcs6PNtmNvch0HBOKN/15P3h+5wDvz4P7/1IocNhzop7swvLxTjMpMm0viSa9m6/Pg+cf35j8gOXXm94kSjzbjIo8Esd7cbxCIBNzdNs3dAXdDQbN9ybIe3MwuEOKbvRvR2YigigNGNKMh28vu0ihswGp9ZuDJpNBs0+HFjjuUffyFpcnvfKQhbgym06wcnXHAe6umNWYjSlKkcXlMa8YpIrEIldMCMHyrLNvzDs0aBImxwyap4+6pw/bp4/71A/opAvH6Vee0y9dn1z70OfXvuziudcMSKdjLp786quecPWVL99Zfqt/ePkuX/8Jv/43Dl3/fwH9bPJ09nq7MQAAAABJRU5ErkJggg==",Ru="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAQlBMVEVMaXGGl/+Elf+HmP+Hmf+Hl/+Gl/+Flv+Glv+Gl/+Gl/+Gl/////+On/+Akv/4+f/v8f/i5v+9x//S2P+tuP+erP+W3PvUAAAAC3RSTlMArBlx7Isy/vvOXbb4wDYAAAAJcEhZcwAACxMAAAsTAQCanBgAAALuSURBVHjarVfbtqsgDOxu0UBpkOv//+pJRC0i2HZ58uTeqzOEyYXkduvY/Tn8KSEBpFB/w3O8/WTjoCSS6dn4S6rha477QxFGS0nHM56ckJL/ox73b+CDQAQJujKiQxTDR4qH4LN109gP8Ti/uyI46K4BUagTLZ4Cz+CZAsWzhx/oeP3RyImhjf/7ePzmxF8Hr7+zNsP3eL7GkWH4Bc8MlQ7P3/DMsIvFKHRLPzBsTWVBizIfVNMBg9H7mLQxTRdUkb9tfJxebNZjywuJW1bf2xcw4WXtzDF5bVqXuJ9HwETHNnPYeHRii0THgcwQyBxTBDQ9Fx7dEBr0TOCDYyeS6aigsFsCQIFgBh9YiVgxQA7EqM9KiCiS95nh5WsGPZ4k8ZZFRqfoY4shy9i8AaExxRgTMgcApuSODPMdRtn02wc7Z9HkPMsPa1ZVOsiRygga4udfZ5vTKKx/7GIBVFJHCUy0r705DNu3LQ9kEQ6NxMTXwWzhUTD7xlJr2MLvrZCBVazy2OD0iaC4BGh1k4cSLOSbbIuujKW4wT76aYefrGswuBJSEoBeUnaFk7nQcKEIJZRXMPsfM95O3p3KKAoRa/cJTh0pHKMybSqyiO8wMsG0wzODi7UK9u0Ah7FIJAj1+UyQcl4Gqi2uax+L/siJVKQyi+j251sbMoHTZrUqlctiojDGRX27WpivYNtdi4upKme0c/gXBmdzY7ZoOi/cWDeU7MJy+oKn3hzbT9/cFKt6pmKe9udnCoTeG103VW7EjrGZJMOD863GNzfVQ0EDP6aJUH61wBRHGZa23npYDDpuh8EnpPBRS6UUQOg9r8enzaDdmhmsPkH/da3bokkr/i0dwMmYU7lg0pRrwiVzNrW+n/dKhVzVVIbGnE9Jj86IA8glk87h+xGnGrJyzXwYNvdD1uUx7/qgeX3UvT5sXx/3ry8c11ee60vX9bXvvXjWfsC3i+d79YV19+WPH1bf/7B8Lxy8/isBINTp+v8Ph4CTcAywkiYAAAAASUVORK5CYII=",Bu="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAPFBMVEVMaXGZhueZh+eYhuWXheWYh+eYhuaXheCYhuaah+j//fmhjvOSf+Sdi+q8sOzNxO/m4fT08fapmuja0/Jb/wGxAAAACnRSTlMArEz/IYtsA87sGIEBYwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAmJJREFUeNqtV4uSgyAMRIECGhTk///1otTKG3s2Mzdz03aXbEJIQkhuYv9jIx+komhKDnxk4v1F1wT+SoxcUj3PWu8Ex39U8lH4bzt4QthL6tlDA8OP5Iv1vMADGFc5+uRQnDWdEES81EwbNquXqDuBx8va6ZcXktUYBOkc/3GixsBvwA8neFGGGO7hdyeGAsMXeM/wBJ8ziLv6LwYeisD4f4lHhiAXmH9FvzYV3AchOw6At9gFKW4KANDbsttGoSyCKd1Ab4uxkzezhBQaRfQygHB3oj2FhjwT9QgifErM6jiOrQgAXe2UmcuiIKSuHG+mki2XCH0kYqzgF1vETyYszLFaxLBMNdsgDGNFAazRoUcwrDMlDYz28RS0newGcCRlDa8TK4YgxuORGj9x8NYVEsxjKQSp/pNAw5YRcJI/JP5nYeqxjAxeIfCeRQQDyWOos/y5xR2V4NIgYhRJVkjgpralBPcvQH4PsBxIX0DjJqKRdgYLtsYPUyqh60CsACXEQew7ECvAICZp7DqwQEIQXaR+CkzaoeKr3FewQdqg4mIy36VgLyZWz4G96N5vs8sKj0UPSlJGy4fAbWX88SgGQYgJVjDXi7JaaxYo9Oj4UQ0lrHCGdN25ceiEfNoZSfIomjhcKN26DarT0q4gaiyfe2C9u9hWNUBvRghbG+yd1AZNFFrjmu+ucXMF2j60OObE7f0m+mrv/5qQkimpO+IU8fKXQ9bDMe/5oPl81P3BsP183EeGu3GoLBw/WHnuLF20sXQ9X/ueL57PV99w+Z7P5Vvj8j3fXr7j9X/f/5Vsrv9/K3NM7mGXOq0AAAAASUVORK5CYII=",br="data:image/svg+xml,%3csvg width='8' height='11' viewBox='57 6 8 11' fill='none' xmlns='http://www.w3.org/2000/svg'%3e %3cpath d='M62.7081 13.27C62.742 13.27 62.7642 13.3057 62.7491 13.3362V13.336L61.1229 16.6083C61.0892 16.6761 60.9926 16.6759 60.959 16.6083L59.3382 13.336C59.3232 13.3057 59.3453 13.27 59.3792 13.27H62.7081Z' fill='%23EA4B4B'/%3e %3cpath d='M61.0026 9.71913C61.0194 9.68524 61.0678 9.68524 61.0845 9.71913L62.747 13.0897C62.762 13.12 62.7399 13.1557 62.706 13.1557H59.3763C59.3424 13.1557 59.3203 13.12 59.3353 13.0897L61.0026 9.71913Z' fill='%23EA4B4B'/%3e %3cpath d='M60.8426 9.63827C60.8766 9.63827 60.8987 9.6741 60.8835 9.70444L59.2164 13.0594C59.1995 13.0932 59.1513 13.0932 59.1345 13.0594L57.5001 9.77047C57.47 9.70962 57.5142 9.63827 57.5821 9.63827H60.8426Z' fill='%23EA4B4B'/%3e %3cpath d='M64.5036 9.63617C64.5715 9.63618 64.6157 9.70753 64.5855 9.76838H64.5854L62.9512 13.0573C62.9344 13.0911 62.8862 13.0912 62.8692 13.0573L61.2021 9.70235C61.187 9.672 61.2091 9.63617 61.2431 9.63617H64.5036Z' fill='%23EA4B4B'/%3e %3cpath d='M62.8284 6.18281C62.862 6.11518 62.9586 6.11518 62.9922 6.18281L64.5855 9.38969C64.6157 9.45054 64.5715 9.52189 64.5036 9.52189H61.2431C61.2091 9.52189 61.187 9.48605 61.2021 9.45571L62.8283 6.18265L62.8284 6.18281Z' fill='%23EA4B4B'/%3e %3cpath d='M62.3131 6.13196C62.381 6.13196 62.4252 6.20331 62.3951 6.26416C62.154 6.74935 61.9128 7.23455 61.6718 7.71975H61.6716C61.4225 8.22125 61.1733 8.72259 60.9242 9.22409C60.9074 9.25799 60.859 9.25799 60.8422 9.22409L60.6305 8.79587C60.6275 8.78957 60.6259 8.78263 60.6259 8.77553V6.22349C60.6259 6.17297 60.6668 6.13196 60.7173 6.13196H62.3131Z' fill='%23EA4B4B'/%3e%3c/svg%3e";const vr=F.getChainMeta(1)?.logo??"",Ou=F.TOKENS.find(e=>e.symbol==="USDC")?.logo??"",ys=Object.fromEntries([...F.getMainnetChains(),...F.getTestnetChains()].map(e=>[e.id,e.logo])),Cr={metamask:lc,metaMask:lc,rabby:Ru,phantom:Bu},ta=Object.fromEntries(F.TOKENS.map(e=>[e.symbol.toUpperCase(),e.logo])),ju={usdc:[8453,1,42161,5115,4114],usdt:[1],btc:[4114,42161,1,5115],wbtc:[1],weth:[8453,1],eth:[8453,1,42161,4663,84532,46630],ctusd:[5115,4114],wcbtc:[5115,4114]},Du={btc:["wcbtc","cbtc","wbtc"]};function oo(e){return e.replace(/^test\s*/i,"").replace(/^spice/i,"").trim()}function os(e){return oo(e).toLowerCase()}function dc(e){return os(e??"").replace(/[^a-z0-9]/g,"")}function na(e){const t=os(e);return[t,...Du[t]??[]].filter(Boolean)}function Nu(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function uc(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function pc(e,t){const n=d.getChainConfig(e),s=t.toLowerCase();return s===F.ZERO_ADDRESS.toLowerCase()?n?.nativeCurrency.decimals??18:n?.supportedTokens?.find(r=>r.address.toLowerCase()===s)?.decimals??18}function Mu(e,t,n,s=[]){const r=pc(t,n),o=e.filter(i=>fc(i,t,n,s));if(o.length===0)return null;const a=o.reduce((i,l)=>Math.min(i,l.decimals??r),r);return{chainDecimals:r,receiptDecimals:a}}function fc(e,t,n,s){if(uc(e).some(o=>{const a=An(o);return a&&yr(a.address,a.chainId,n,t)}))return!0;const r=new Set(s.map(dc).filter(Boolean));return r.size===0?!1:r.has(dc(e.tokenName||e.receiptToken))}function mc(e,t,n,s=[]){const r=pc(t,n);return e.reduce((o,a)=>fc(a,t,n,s)?o+F.convertAmountBetweenDecimals(Nu(a),a.decimals??r,r):o,0n)}function hc(e,t){const n=new Set([...na(t),...na(oo(t))]);return[...e].sort((s,r)=>{const o=os(s.symbol),a=os(r.symbol),i=os(s.name),l=os(r.name),u=n.has(o)?0:n.has(i)?1:2,m=n.has(a)?0:n.has(l)?1:2;return u!==m?u-m:s.address.toLowerCase().localeCompare(r.address.toLowerCase())})[0]}function Pu(e){const t=e&&e.length>0?e:Object.keys(d.CHAIN_CONFIGS).map(Number).filter(Number.isFinite),n=new Map;for(const s of t){const r=d.getChainConfig(s);if(!r)continue;const o=`${s}:${F.ZERO_ADDRESS.toLowerCase()}`;n.has(o)||n.set(o,{address:F.ZERO_ADDRESS,chainId:s,symbol:r.nativeCurrency.symbol,name:r.nativeCurrency.name,decimals:r.nativeCurrency.decimals,isNative:!0,logoURI:ta[r.nativeCurrency.symbol.toUpperCase()]??r.logo});for(const a of r.supportedTokens??[]){const i=a.address.toLowerCase(),l=`${s}:${i}`;n.has(l)||n.set(l,{address:i,chainId:s,symbol:a.symbol,name:a.name,decimals:a.decimals,isNative:F.isNativeToken(i),logoURI:a.logo})}}return n}function Uu(e,t){const n=Pu(t),s=oo(e.tokenName),r=os(e.tokenName),o=na(e.tokenName),a=Array.isArray(e.chainTokens)?e.chainTokens.map(g=>[g,void 0]):Object.entries(e.chainTokens??{}),i=a.map(([g])=>An(g)).filter(g=>g!==null),l=new Map;for(const[g,x]of a){const w=An(g);if(!w||!Number.isSafeInteger(w.chainId)||w.chainId<0||!/^evm:[0-9]+:(?:0x)?[0-9a-fA-F]{40}$/.test(g)){if(!Array.isArray(e.chainTokens))throw new Error("Invalid chain token metadata identity");continue}if(x!==void 0&&(!x||typeof x!="object"||Array.isArray(x)||x.name!==void 0&&typeof x.name!="string"||x.decimals!==void 0&&(!Number.isInteger(x.decimals)||x.decimals<0||x.decimals>255)))throw new Error("Invalid chain token metadata");const b=`${w.chainId}:${w.address.toLowerCase()}`;if(l.has(b)){const S=l.get(b);if(S?.name!==x?.name||S?.decimals!==x?.decimals)throw new Error("Conflicting chain token metadata")}l.set(b,x)}const u=(g,x)=>{const w=l.get(`${x.chainId}:${x.address.toLowerCase()}`);return{...g,name:typeof w?.name=="string"&&w.name.length>0?w.name:g.name,decimals:typeof w?.decimals=="number"?w.decimals:g.decimals}},m=i.map(g=>{const x=n.get(`${g.chainId}:${g.address.toLowerCase()}`);return x?u(x,g):void 0}).filter(g=>g!==void 0),f=ju[r]??[];if(f.length>0)for(const g of f){const x=m.filter(w=>w.chainId===g);if(x.length>0)return hc(x,e.tokenName)}if(m.length>0)return hc(m,e.tokenName);const h=Array.from(n.values()).filter(g=>o.includes(os(g.symbol))||o.includes(os(g.name)));if(f.length>0)for(const g of f){const x=h.find(w=>w.chainId===g);if(x)return x}if(h.length>0)return h[0];const y=i[0];if(y){const g=l.get(`${y.chainId}:${y.address.toLowerCase()}`);return{address:y.address,chainId:y.chainId,symbol:s||e.tokenName,name:typeof g?.name=="string"&&g.name.length>0?g.name:s||e.tokenName,decimals:typeof g?.decimals=="number"?g.decimals:e.decimals??18,isNative:F.isNativeToken(y.address),logoURI:void 0}}}function Wu(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;if(t?.length){const g=uc(e).map(An).filter(x=>x!==null);if(g.length>0&&!g.some(x=>t.includes(x.chainId)))return null}let s;try{s=Uu(e,t)}catch{return null}const r=s?.decimals??e.decimals??18,o=e.decimals??r,a=F.convertAmountBetweenDecimals(n,o,r),i=s?.address??F.ZERO_ADDRESS,l=s?.chainId??0,u=oo(e.tokenName),m=s?.symbol??u,f=s?.name??u,h=parseFloat(M.formatUnits(a,r)),y=e.tokenName==="spiceUSDC"?h:typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:i,symbol:m,name:f,decimals:r,chainId:l,balance:a,balanceFormatted:h,balanceUsd:y,isNative:s?.isNative??F.isNativeToken(i),logoURI:s?.logoURI,displaySymbol:u||m,displayName:u||f,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||f,receiptTokenDecimals:o,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}const sa=6e4,qu=3e5,gc="https://api.g.alchemy.com/prices/v1",Gs=new Map;function ao(e,t){try{const n=t??d.getRpcUrlForChain(e);if(typeof n!="string")return null;const{hostname:s,pathname:r}=new URL(n);if(!s.endsWith(".g.alchemy.com"))return null;const o=r.split("/").filter(Boolean).pop();return o?{network:s.slice(0,-14),key:o}:null}catch{return null}}const kr=(e,t)=>`${e.network}:${e.key}:${t.toLowerCase()}`;function js(e,t){const n=Gs.get(kr(e,t));if(!n?.price||n.updatedAt===void 0)return;const s=Date.now()-n.updatedAt;if(!(s>=qu))return{price:n.price,stale:s>=sa}}function wc(e){const t=Number(e.prices?.find(n=>n.currency==="usd")?.value);return Number.isFinite(t)&&t>0?t:0}async function xc(e,t,n){const s=[],r=new Set,o=Date.now();for(const a of new Set(t.map(i=>i.toLowerCase()))){const i=Gs.get(kr(e,a));i?.pending?r.add(i.pending):(!i||o-i.attemptedAt>=sa&&(i.updatedAt===void 0||o-i.updatedAt>=sa))&&s.push(a)}for(let a=0;a<s.length;a+=25){const i=s.slice(a,a+25),l=Promise.resolve().then(async()=>{try{const u=await n(i);for(const m of i){const f=u.get(m);if(!f)continue;const h=Gs.get(kr(e,m));h.price=f,h.updatedAt=Date.now()}}catch{}finally{for(const u of i)Gs.get(kr(e,u)).pending=void 0}});for(const u of i){const m=kr(e,u);Gs.set(m,{...Gs.get(m),attemptedAt:o,pending:l})}r.add(l)}await Promise.all(r)}async function ra(e,t){return await xc(e,t,async n=>{const s=await fetch(`${gc}/${e.key}/tokens/by-address`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({addresses:n.map(a=>({network:e.network,address:a}))}),signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error("Provider price request failed");const r=await s.json(),o=new Map;for(const a of r?.data??[]){if(a.network&&a.network!==e.network)continue;const i=String(a.address).toLowerCase();n.includes(i)&&o.set(i,wc(a))}return o}),new Map(t.map(n=>[n.toLowerCase(),js(e,n)?.price??0]))}async function oa(e,t){const n=`native:${t}`;return await xc(e,[n],async()=>{const s=await fetch(`${gc}/${e.key}/tokens/by-symbol?symbols=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error("Provider native price request failed");const r=(await s.json())?.data?.find(o=>o.symbol?.toUpperCase()===t.toUpperCase());return new Map([[n.toLowerCase(),r?wc(r):0]])}),js(e,n)?.price??0}async function Lu(e,t){const n=t.supportedChains,s=e.map(r=>{if(r.receiptTokenName==="spiceUSDC")return[];const o=Object.keys(r.chainTokens??{}).map(An).filter(a=>!!a&&M.isAddress(a.address)&&!!n?.includes(a.chainId));return o.sort((a,i)=>{const l=u=>u===t.nativeChainId?-1:n.indexOf(u);return l(a.chainId)-l(i.chainId)||+!d.addressesEqual(a.address,r.address)-+!d.addressesEqual(i.address,r.address)}),o.flatMap(a=>{const i=t.rpcOverrides?.[a.chainId];if(!i)return[];const l=ao(a.chainId,i);if(!l)return[];const u=F.isNativeToken(a.address)?d.getChainConfig(a.chainId)?.nativeCurrency.symbol:void 0,m=u?`native:${u}`:a.address;return[{rpc:l,token:m,address:a.address,nativeSymbol:u}]})});return(typeof document>"u"||!document.hidden)&&await Promise.all(s.map(async r=>{for(const o of r)if(o.nativeSymbol?await oa(o.rpc,o.nativeSymbol).catch(()=>0):await ra(o.rpc,[o.address]).catch(()=>new Map),js(o.rpc,o.token)?.stale===!1)break})),e.map((r,o)=>{if(r.receiptTokenName==="spiceUSDC")return{...r,balanceUsd:r.balanceFormatted,priceStatus:"fresh"};const a=s[o].map(l=>js(l.rpc,l.token)),i=a.find(l=>l&&!l.stale)??a.find(Boolean);return{...r,balanceUsd:i?r.balanceFormatted*i.price:Number.isFinite(r.balanceUsd)&&r.balanceUsd>0?r.balanceUsd:0,priceStatus:i?i.stale?"stale":"fresh":"unavailable"}})}function zu(e,t,n){const s=p.useContext(d.SpiceFlowProviderContext),[r,o]=p.useState(()=>typeof document>"u"||!document.hidden);p.useEffect(()=>{const m=()=>o(!document.hidden);return document.addEventListener("visibilitychange",m),()=>document.removeEventListener("visibilitychange",m)},[]);const a={supportedChains:n??s?.supportedChainIds,nativeChainId:s?.nativeChainId,rpcOverrides:s?.rpcOverrides},i=JSON.stringify([e,a],(m,f)=>typeof f=="bigint"?f.toString():f),l=p.useCallback(()=>Lu(e,a),[i]),u=ea(`prices:${i}`,l,t&&r&&e.length>0,6e4);return u.updatedAt?u.assets:e}function Hu(e){const t=e.chainTokens??e.chainTokenConfig;if(Array.isArray(t))return t.filter(n=>typeof n=="string");if(t&&typeof t=="object")return t}const yc=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:s,priceEnabled:r=!1})=>{const o=p.useContext(d.SpiceFlowProviderContext),a=o?.apiUrl||d.RELAYER_API_URL,i=ro(),l=o?.supportedChainIds??t,u=JSON.stringify([...l??[]].sort((O,I)=>O-I)),m=e?.toLowerCase(),f=p.useCallback(async()=>{const O=`${a}/wallets/${m}/balance`;let I,v;try{const E=await d.relayerFetch(O,{cache:"no-store"});if(I=E.status,v=E.requestId,!E.ok)throw new Error(`Failed to fetch balance: ${E.status}`);const R=await E.json();if(!Array.isArray(R.balances))throw new Error("Invalid balance response");return R.balances.map(B=>{const W=Wu({receiptToken:typeof B.receiptToken=="string"?B.receiptToken:void 0,tokenName:String(B.tokenName??""),balanceAvailable:String(B.balanceAvailable??"0"),chainTokens:Hu(B),decimals:typeof B.decimals=="number"?B.decimals:void 0,balanceUsd:typeof B.balanceUsd=="number"||typeof B.balanceUsd=="string"?B.balanceUsd:null},l);return W?{...W,owner:m,location:"rollup",_source:"spice",positionId:`${m}:rollup:${W.receiptTokenId??W.address}`}:null}).filter(B=>B!==null)}catch(E){const R=E instanceof Error?E.name:void 0,B=I===429?"Balance refresh is temporarily busy. Wait a moment and try again.":I===408||I===504||R==="TimeoutError"?"Balance refresh timed out. Try again.":R==="AbortError"?"Balance refresh was interrupted. Try again.":"Balances are unavailable. Check your connection and try again.",W=new d.SpiceflowError("RELAYER_STATUS_ERROR",B,{endpoint:O,httpStatus:I,requestId:v,cause:E});throw d.sanitizeError(W),W}},[m,a,u,o?.nativeChainId,o?.rpcOverrides]),{assets:h,loading:y,refreshing:g,error:x,updatedAt:w}=ea(`rollup:${m}:${a}:${u}`,f,n&&!!m,s??0,i),b=JSON.stringify(t??[]),S=p.useMemo(()=>x?h.map(O=>({...O,balanceError:x,balanceStatus:"stale"})):h,[h,x]),T=zu(S,n&&r,l),k=p.useMemo(()=>T.filter(O=>!t?.length||t.includes(O.chainId)||Object.keys(O.chainTokens??{}).some(I=>t.some(v=>I.startsWith(`evm:${v}:`)))),[T,b]),A=p.useCallback(O=>k.filter(I=>I.chainId===O),[k]);return{assets:k,loading:y,error:x,hasBalance:k.some(O=>O.balance>0n),refreshing:g,updatedAt:w,refetch:i.invalidate,getAssetsByChain:A}};async function Vu(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[s,r,o]=await Promise.all([Kn.readContract(e,{address:t,abi:M.erc20Abi,functionName:"decimals"}),Kn.readContract(e,{address:t,abi:M.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Kn.readContract(e,{address:t,abi:M.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);if(!Number.isInteger(Number(s))||Number(s)<0||Number(s)>255)throw new Error("Invalid token decimals");return{decimals:Number(s),symbol:r,name:o,logoURI:void 0}}const bc=async(e,t,n)=>{const s=d.getClientForChain(t,n),r=d.getChainConfig(t),o=await Kn.getBalance(s,{address:e}),a=r.nativeCurrency,i=r.supportedTokens?.find(l=>F.isNativeToken(l.address));return{address:F.ZERO_ADDRESS,name:a.name,symbol:a.symbol,decimals:a.decimals,balance:o,balanceFormatted:Number(M.formatUnits(o,a.decimals)),balanceUsd:0,priceStatus:"unavailable",logoURI:i?.logo||r.logo,isNative:!0,chainId:t}},Qu=async(e,t,n,s,r,o,a)=>{try{if(!M.isAddress(n))return null;const i=M.getAddress(n),l=M.isAddress(e)?M.getAddress(e):e,u=d.getClientForChain(t,a),m=await Kn.readContract(u,{address:i,abi:M.erc20Abi,functionName:"balanceOf",args:[l]}),f=Number(M.formatUnits(m,o));return m>0n?{address:i,name:s,symbol:r,decimals:o,balance:m,balanceFormatted:f,balanceUsd:0,priceStatus:"unavailable",logoURI:void 0,isNative:!1,chainId:t}:null}catch(i){throw i}},vc=(e,t)=>{const n=d.getChainConfig(t);if(!n)return e;const s=new Set(e.map(o=>o.address.toLowerCase())),r=e.some(o=>o.isNative);for(const o of n.supportedTokens||[])F.isNativeToken(o.address)&&r||s.has(o.address.toLowerCase())||e.push({address:o.address,name:o.name,symbol:o.symbol,decimals:o.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,priceStatus:"unavailable",logoURI:o.logo,isNative:F.isNativeToken(o.address),chainId:t});if(!e.find(o=>o.isNative)){const o=n.supportedTokens?.find(a=>F.isNativeToken(a.address));e.push({address:F.ZERO_ADDRESS,name:n.nativeCurrency.name,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,priceStatus:"unavailable",logoURI:o?.logo||n.logo,isNative:!0,chainId:t})}return e},Gu=async(e,t,n)=>{const s=[],r=async i=>{for(const l of i){const u=await Qu(e,t,l.address,l.name,l.symbol,l.decimals,n);u&&(u.logoURI=l.logo,s.push(u))}},o=await bc(e,t,n);o.balance>0n&&s.push(o);const a=(d.getChainConfig(t)?.supportedTokens||[]).filter(i=>!F.isNativeToken(i.address));if(a.length>0)try{const i=d.getClientForChain(t,n),l=M.getAddress(e),u=a.filter(y=>M.isAddress(y.address)).map(y=>({address:M.getAddress(y.address),abi:M.erc20Abi,functionName:"balanceOf",args:[l]})),m=await i.multicall({contracts:u}),f=a.filter(y=>M.isAddress(y.address)),h=[];m.forEach((y,g)=>{if(y.status==="success"){const x=y.result;if(x&&x>0n){const w=f[g],b=Number(M.formatUnits(x,w.decimals));x>0n&&s.push({address:M.getAddress(w.address),name:w.name,symbol:w.symbol,decimals:w.decimals,balance:x,balanceFormatted:b,balanceUsd:0,priceStatus:"unavailable",logoURI:w.logo,isNative:!1,chainId:t})}}else h.push(f[g])}),await r(h)}catch{await r(a)}return{tokens:vc(s,t),chainId:t}},Ku=async(e,t,n)=>{const s=new Map,r=ao(e,n?n[e]??"":void 0);if(!r)return s;const o=t.filter(u=>F.isNativeToken(u)),a=t.filter(u=>!F.isNativeToken(u)),[i,l]=await Promise.all([a.length?ra(r,a).catch(()=>new Map):new Map,o.length?oa(r,d.getChainConfig(e)?.nativeCurrency?.symbol??"ETH").catch(()=>0):0]);for(const[u,m]of i)m>0&&s.set(u,m);if(l>0)for(const u of o)s.set(u.toLowerCase(),l);return s},Yu=async(e,t,n,s=!0,r)=>{const o=d.getClientForChain(t,r),a=M.getAddress(e),i=[];let l;do{const x=await o.request({method:"alchemy_getTokenBalances",params:[a,"erc20",l?{pageKey:l}:{}]});i.push(...x.tokenBalances),l=x.pageKey||void 0}while(l);const u=i.filter(x=>M.isAddress(x.contractAddress)&&!!x.tokenBalance&&BigInt(x.tokenBalance)>0n),m=d.getChainConfig(t)?.supportedTokens||[],f=x=>m.find(w=>w.address.toLowerCase()===x.toLowerCase()),h=[],y=await bc(e,t,r),[g]=await Promise.all([Promise.all(u.map(async x=>{const w=f(x.contractAddress);return w?{name:w.name,symbol:w.symbol,decimals:w.decimals,logo:w.logo??null}:await o.request({method:"alchemy_getTokenMetadata",params:[x.contractAddress]})})),s?ra(n,u.map(x=>x.contractAddress)):void 0,s&&y.balanceFormatted>0?oa(n,y.symbol):void 0]);if(y.balance>0n){const x=js(n,`native:${y.symbol}`);h.push({...y,balanceUsd:(x?.price??0)*y.balanceFormatted,priceStatus:x?x.stale?"stale":"fresh":"unavailable"})}return u.forEach((x,w)=>{const b=g[w];if(!Number.isInteger(b.decimals)||b.decimals===null||b.decimals<0||b.decimals>255)throw new Error(`Invalid token metadata on chain ${t}`);const S=BigInt(x.tokenBalance),T=Number(M.formatUnits(S,b.decimals));if(S<=0n)return;const k=js(n,x.contractAddress),A=(k?.price??0)*T;h.push({address:M.getAddress(x.contractAddress),name:b.name||"Unknown",symbol:b.symbol||"UNKNOWN",decimals:b.decimals,balance:S,balanceFormatted:T,balanceUsd:A,priceStatus:k?k.stale?"stale":"fresh":"unavailable",isDiscovered:!f(x.contractAddress),logoURI:b.logo||void 0,isNative:!1,chainId:t})}),{tokens:vc(h,t),chainId:t}},Cc=new Set,Zu=async(e,t,n=!0,s)=>{try{const r=ao(t,s?s[t]??"":void 0);if(r)try{return await Yu(e,t,r,n&&(typeof document>"u"||!document.hidden),s)}catch(o){Cc.has(t)||(Cc.add(t),console.warn(`Token discovery unavailable on chain ${t}; listing configured tokens only.`,o))}return await Gu(e,t,s)}catch(r){throw r}},Ks=async(e,t,n=[],s)=>{if(!e)throw new Error("Wallet address is required");const r=d.getChainsForAssets(s),o=t?.length?[...new Set(t)]:Object.keys(r).map(Number),a=await Promise.allSettled(o.map(l=>Zu(e,l,!0,s))),i={};return a.forEach((l,u)=>{const m=o[u];i[m]=l.status==="fulfilled"?l.value:{chainId:m,tokens:[],error:`Unable to refresh balances on chain ${m}`}}),(await Promise.allSettled(n.map(async l=>{const u=i[l.chainId];if(!u||u.error||u.tokens.some(w=>F.normalizeNativeTokenAddress(w.address).toLowerCase()===F.normalizeNativeTokenAddress(l.address).toLowerCase()))return;const m=d.getClientForChain(l.chainId,s),f=await Vu(m,l.address,l.decimals!==void 0&&l.symbol?{decimals:l.decimals,symbol:l.symbol,name:l.name||l.symbol,logo:l.logoURI}:void 0),h=await Kn.readContract(m,{address:l.address,abi:M.erc20Abi,functionName:"balanceOf",args:[e]});await Ku(l.chainId,[l.address],s);const y=Number(M.formatUnits(h,f.decimals)),g=ao(l.chainId,s?s[l.chainId]??"":void 0),x=g?js(g,l.address):void 0;u.tokens.push({...f,...l,name:f.name,symbol:f.symbol,decimals:f.decimals,balance:h,balanceFormatted:y,balanceUsd:(x?.price??0)*y,priceStatus:x?x.stale?"stale":"fresh":"unavailable",isNative:!1})}))).forEach((l,u)=>{if(l.status==="rejected"){const m=i[n[u].chainId];m&&(m.error=`Unable to refresh token balances on chain ${m.chainId}`)}}),i},Sr=({address:e,supportedChains:t,fetchBalances:n=Ks,additionalTokens:s=[],enabled:r=!0,refreshInterval:o=0,priceEnabled:a=!0})=>{const i=p.useContext(d.SpiceFlowProviderContext),l=ro(),u=e?.toLowerCase(),m=JSON.stringify([...i?.supportedChainIds??t??[]].sort((S,T)=>S-T)),f=JSON.stringify(s);p.useEffect(()=>l.registerTokens(s),[l,f]);const h=u&&u===i?.embeddedWalletAddress?.toLowerCase()?"embedded":"external",y=`wallet:${JSON.stringify([i?.network,i?.apiUrl,i?.rpcOverrides])}:${u}:${h}:${m}:${l.fetcherId(n)}`,g=p.useCallback(async()=>{let S;try{S=await n(u,JSON.parse(m),l.tokens(),i?.rpcOverrides)}catch(O){const I=O instanceof Error?O.message:"Unable to refresh balances";S=Object.fromEntries(JSON.parse(m).map(v=>[v,{chainId:v,tokens:[],error:I}]))}const T=l.entry(y).snapshot().assets,k=JSON.parse(m).map(O=>S[O]??{chainId:O,tokens:[],error:`Unable to refresh balances on chain ${O}`}),A=k.flatMap(O=>O.error?[O.error]:[]);return{assets:k.flatMap(O=>O.error?T.filter(I=>I.chainId===O.chainId).map(I=>({...I,balanceError:O.error,balanceStatus:"stale"})):O.tokens.map(I=>({...I,owner:u,location:h,_fundingWallet:h,_source:"wallet",positionId:`${u}:${h}:${O.chainId}:${F.normalizeNativeTokenAddress(I.address).toLowerCase()}`}))),error:A.length?A.join("; "):null}},[l,u,m,n,h,y]),x=ea(y,g,r&&!!u,o,l),w=JSON.stringify(t&&[...t].sort((S,T)=>S-T)),b=p.useMemo(()=>t?x.assets.filter(S=>t.includes(S.chainId)):x.assets,[x.assets,w]);return p.useEffect(()=>{a&&r&&u&&x.refresh()},[a]),{...x,assets:b,refreshAssets:l.invalidate,getAssetsByChain:p.useCallback(S=>b.filter(T=>T.chainId===S),[b]),getNativeAssets:p.useCallback(()=>b.filter(S=>S.isNative),[b])}};function Ds(e){const t=p.useContext(d.SpiceFlowProviderContext),n=ro(),s=e.owner??((t?.mode||"7702")!=="7702"?t?.externalWalletAddress:t?.embeddedWalletAddress),r=s?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase(),o=e.sourceChains??t?.supportedChainIds??[],a=(e.enabled??!0)&&!t?.isWhitelistGateActive,i=p.useMemo(()=>{const h=[...t?.additionalSourceTokens??[],...e.additionalSourceTokens??[],...e.destination?[e.destination]:[]];for(const y of e.supportedSourceAssets??[])for(const g of o){const x=d.getChainConfig(g)?.supportedTokens?.find(w=>d.isAssetAllowed(w,[y]));x&&h.push({...x,address:x.address,chainId:g,logoURI:x.logo})}return h},[e.destination,JSON.stringify(t?.additionalSourceTokens),JSON.stringify(e.additionalSourceTokens),JSON.stringify(e.supportedSourceAssets),JSON.stringify(o)]),l=Sr({address:s,supportedChains:o,fetchBalances:Ks,additionalTokens:i,enabled:a&&e.includeWalletAssets!==!1,refreshInterval:3e4}),u=yc({address:s,supportedChains:o,enabled:a&&e.includeRollupAssets!==!1&&!!s&&s.toLowerCase()===t?.embeddedWalletAddress?.toLowerCase(),priceEnabled:a,refetchInterval:3e4}),m=p.useMemo(()=>a?[...(e.includeWalletAssets===!1?[]:l.assets).map(h=>({...h,owner:h.owner??s,location:h.location??(r?"external":"embedded"),_source:"wallet"})),...(e.includeRollupAssets===!1||s?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase()?[]:u.assets).map(h=>({...h,owner:h.owner??s,location:"rollup",_source:"spice"}))]:[],[a,l.assets,u.assets,e.includeWalletAssets,e.includeRollupAssets,s,r,t?.embeddedWalletAddress]),f=p.useMemo(()=>m.map(h=>({asset:h,...Yn(h,e.role??"holding",{allowedTokens:t?.allowedTokens,rpcOverrides:t?.rpcOverrides,liquidityVenues:t?.liquidityVenues,isWhitelistGateActive:!!t?.isWhitelistGateActive},e.destination,e.supportedSourceAssets,{requiresEscrow:e.requiresEscrow})})),[m,t?.allowedTokens,t?.rpcOverrides,t?.liquidityVenues,t?.isWhitelistGateActive,e.role,e.destination,e.supportedSourceAssets,e.requiresEscrow]);return{positions:f,assets:p.useMemo(()=>f.filter(h=>h.eligible&&h.asset.balance>0n).map(h=>h.asset),[f]),walletAssets:p.useMemo(()=>m.filter(h=>h._source==="wallet"),[m]),rollupAssets:p.useMemo(()=>m.filter(h=>h._source==="spice"),[m]),loading:l.loading||u.loading,refreshing:l.refreshing||u.refreshing,error:l.error||u.error,refresh:n.invalidate}}function io(e,t=!0,n){const s=n?.pendingOnly===!0,r=d.relayerService.getBaseUrl(),o=`${r}:${e?.toLowerCase()??""}:${s}`,[a,i]=p.useState({scope:o,actions:[],error:null,loading:t&&!!e,updatedAt:null,revision:0}),[l,u]=p.useState(0),m=p.useCallback(()=>u(h=>h+1),[]);p.useEffect(()=>{if(!t||!e){i(w=>w.scope===o&&w.actions.length===0&&!w.error&&!w.loading&&!w.updatedAt&&w.revision===0?w:{scope:o,actions:[],error:null,loading:!1,updatedAt:null,revision:0});return}const h=new AbortController,y=new d.RelayerService;y.setBaseUrl(r);let g;i(w=>({scope:o,actions:w.scope===o?w.actions:[],error:w.scope===o?w.error:null,loading:!0,updatedAt:w.scope===o?w.updatedAt:null,revision:w.scope===o?w.revision:0}));const x=async()=>{try{const w=await y.getWalletActions(e,{pendingOnly:s,signal:h.signal});h.signal.aborted||i(b=>({scope:o,actions:w,error:null,loading:!1,updatedAt:new Date().toISOString(),revision:b.scope===o?b.revision+1:1}))}catch(w){if(h.signal.aborted)return;const b=w instanceof d.SpiceflowError&&w.context.httpStatus===404;i(b&&!s?S=>({scope:o,actions:[],error:null,loading:!1,updatedAt:new Date().toISOString(),revision:S.scope===o?S.revision+1:1}):S=>({scope:o,actions:S.scope===o?S.actions:[],error:"Activity is temporarily unavailable. Refresh to check again.",loading:!1,updatedAt:S.scope===o?S.updatedAt:null,revision:S.scope===o?S.revision:0}))}h.signal.aborted||(g=setTimeout(x,5e3))};return x(),window.addEventListener("online",m),()=>{h.abort(),g&&clearTimeout(g),window.removeEventListener("online",m)}},[r,e,t,o,s,l,m]);const f=a.scope===o;return{actions:t&&e&&f?a.actions:[],error:f?a.error:null,loading:t&&!!e&&(!f||a.loading),updatedAt:f?a.updatedAt:null,revision:f?a.revision:0,refresh:m}}function aa(e){const t=p.useRef(0),n=p.useRef(null),s=p.useRef(e.run);s.current=e.run;const r=p.useRef(e.onSkip);r.current=e.onSkip;const o=p.useRef(e.onCleanup);o.current=e.onCleanup,p.useEffect(()=>{if(!e.shouldRun){t.current+=1,n.current?.abort(),r.current?.();return}let a=!1,i=!1;const l=async h=>{if(h&&i)return;n.current?.abort();const y=new AbortController;n.current=y;const g=++t.current;i=!0;try{await s.current({isBackground:h,isCurrent:()=>!a&&t.current===g,signal:y.signal})}finally{i=!1}},u=window.setTimeout(()=>void l(!1),e.delayMs??250),m=()=>{document.hidden||l(!0)},f=e.backgroundIntervalMs?window.setInterval(m,e.backgroundIntervalMs):void 0;return f!==void 0&&document.addEventListener("visibilitychange",m),()=>{a=!0,n.current?.abort(),clearTimeout(u),f!==void 0&&(window.clearInterval(f),document.removeEventListener("visibilitychange",m)),o.current?.()}},[e.shouldRun,e.delayMs,e.backgroundIntervalMs,...e.deps])}function kc(e,t){if(e.length!==t.length)return!1;const n=F.hashChainBatches(e),s=F.hashChainBatches(t);return n.every((r,o)=>r.hash===s[o]?.hash)}const Ln=e=>new Promise(t=>setTimeout(t,e)),Xu="0xa9059cbb";function Sc(e){const t=e.findIndex(r=>F.isSpicenetChainId(r.chainId));if(t<=0)return[];const n=new Map,s=(r,o,a)=>{if(a<=0n)return;const i=`${r}:${o.toLowerCase()}`,l=n.get(i);l?l.amount+=a:n.set(i,{chainId:r,token:o,amount:a})};for(const r of e.slice(0,t)){const o=F.getEscrowContract(r.chainId);if(!(!o||o===F.ZERO_ADDRESS)){for(const a of r.calls)if(a.value&&a.value>0n&&d.addressesEqual(a.to,o)&&s(r.chainId,F.ZERO_ADDRESS,a.value),!!a.data?.startsWith(Xu))try{const i=M.decodeFunctionData({abi:M.erc20Abi,data:a.data});if(i.functionName!=="transfer")continue;const[l,u]=i.args;d.addressesEqual(l,o)&&s(r.chainId,a.to,u)}catch{}}}return[...n.values()]}function Ic(e){const t=F.getTokenByAddress(e.token,e.chainId);return[t?.equivalenceGroup,t?.symbol,t?.name]}function Ac(e,t){return mc(e,t.chainId,t.token,Ic(t))}function Ju(e,t){const n=Mu(e,t.chainId,t.token,Ic(t));return!n||n.receiptDecimals>=n.chainDecimals?t.amount:F.convertAmountBetweenDecimals(F.convertAmountBetweenDecimals(t.amount,n.chainDecimals,n.receiptDecimals),n.receiptDecimals,n.chainDecimals)}async function Ec(e){const{deposits:t,baseline:n,fetchEntries:s,timeoutMs:r=12e4,intervalMs:o,signal:a,wait:i=Ln}=e;if(t.length===0)return!0;const l=new Map(t.map(f=>[f,Ac(n,f)])),u=Date.now(),m=u+r;for(;!a?.aborted;){try{const g=await s();if(t.every(x=>Ac(g,x)-l.get(x)>=Ju(g,x)))return!0}catch{}const f=Date.now();if(f>=m)return!1;const h=f-u,y=o??(h<5e3?250:h<15e3?1e3:3e3);await i(Math.min(y,m-f))}return!1}function ia(e,t){const n=F.hashChainBatches(e).map(s=>s.hash);return M.keccak256(M.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}async function ca(e,t,n,s,r){if(s?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const o={raw:ia(t,n)},a=r?await e.signMessage(o,r):await e.signMessage(o);console.debug("[SpiceFlow:execution]",{phase:"signature-returned",at:Date.now()});const i=typeof a=="string"?a:a.signature;if(!i)throw new d.SpiceflowError("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return i}function $u(e){return e.domain==="spicenet"||F.isSpicenetChainId(e.chainId)}const Fc=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;async function _u(e,t,n){const s=(m,f)=>new d.SpiceflowError("SIGNATURE_FAILED","The wallet returned an invalid authorization. Review the action and try again.",{chainId:t.chainId,reason:m,...f?{cause:f}:{}});if(!e||typeof e!="object")throw s("missing-authorization");const r=e;for(const m of["address","contractAddress"])if(r[m]!==void 0&&(typeof r[m]!="string"||r[m].toLowerCase()!==t.address.toLowerCase()))throw s("authorization-target-mismatch");for(const m of["chainId","nonce"]){const f=r[m];if(f!==void 0&&(typeof f=="bigint"?f!==BigInt(t[m]):typeof f!="number"||!Number.isSafeInteger(f)||f!==t[m]))throw s(`authorization-${m}-mismatch`)}const{r:o,s:a,yParity:i}=r;if(typeof o!="string"||typeof a!="string"||!/^0x[0-9a-fA-F]{64}$/.test(o)||!/^0x[0-9a-fA-F]{64}$/.test(a)||i!==0&&i!==1||BigInt(o)===0n||BigInt(o)>=Fc||BigInt(a)===0n||BigInt(a)>Fc/2n)throw s("invalid-signature");const l={...t,r:o,s:a,yParity:i};let u;try{u=await M.recoverAddress({hash:M.keccak256(M.concatHex(["0x05",M.toRlp([M.toHex(t.chainId),t.address,t.nonce===0?"0x":M.toHex(t.nonce)])])),signature:l})}catch(m){throw s("invalid-signature",m)}if(u.toLowerCase()!==n.toLowerCase())throw s("authorization-signer-mismatch");return l}async function la(e){const{chainBatches:t,signingAddress:n,actions:s,cache:r,signal:o,onSignatureRequested:a,beforeSign:i}=e;if(o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(typeof n!="string"||!M.isAddress(n,{strict:!1})||n.toLowerCase()===M.zeroAddress)throw new d.SpiceflowError("INVALID_PARAMS","A valid signing address is required.");for(const h of t)if(!Number.isSafeInteger(h.chainId)||h.chainId<=0)throw new d.SpiceflowError("INVALID_PARAMS","A valid authorization chain is required.");const l=[...new Set(t.filter(h=>!$u(h)).map(h=>h.chainId))].map(h=>{const y=d.getDelegateContractAddress(h);if(!M.isAddress(y,{strict:!1})||y.toLowerCase()===M.zeroAddress)throw new d.SpiceflowError("INVALID_PARAMS","A valid delegation target is required.");return{chainId:h,client:d.getClientForChain(h),delegateContract:y}}),[u]=await Promise.all([Promise.all(l.map(async({chainId:h,client:y,delegateContract:g})=>{const x=Number(await F.getAccountNonce(n,y));if(!Number.isSafeInteger(x)||x<0)throw new d.SpiceflowError("INVALID_PARAMS","The authorization nonce is invalid.");const w=[n.toLowerCase(),h,g.toLowerCase(),x].join(":");return{chainId:h,delegateContract:g,nonce:x,cacheKey:w,cached:r?.get(w)}})),l.length?s.prepareSigning?.():void 0]);if(await i?.(),o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const m=[];let f=!1;for(const{chainId:h,delegateContract:y,nonce:g,cacheKey:x,cached:w}of u){if(w===void 0&&f&&await i?.(),o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const b=w===void 0?await s.signAuthorization({contractAddress:y,chainId:h,nonce:g},a):w;let S;try{S=await _u(b,{address:y,chainId:h,nonce:g},n)}catch(T){throw r?.delete(x),T}if(o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");f=!0,r?.set(x,S),m.push(S)}return m}const Tc=15;function ep(e){return e.now-e.lastProgressAt>=e.pollTimeoutMs}function Rc(e,t){return{intentId:e,steps:t.map(n=>({...n,status:"pending"})),overallStatus:"processing"}}function co(e,t,n){const s=e.steps.map(i=>({...i})),r=s[t];if(!r)return e;n.status==="success"||n.status==="completed"?(s[t]={...r,status:"success",transactionHash:n.transactionHash},t+1<s.length&&s[t+1].status==="pending"&&(s[t+1]={...s[t+1],status:"processing"})):n.status==="reverted"||n.status==="error"?s[t]={...r,status:"failed",transactionHash:n.transactionHash,error:n.error}:s[t]={...r,status:"processing"};const o=s.some(i=>i.status==="failed"),a=s.every(i=>i.status==="success");return{...e,steps:s,overallStatus:o?"failed":a?"success":"processing"}}function tp({checkStepStatus:e,retryStep:t,maxRetries:n=3,pollingInterval:s=2500,pollTimeoutMs:r=3e5}){const[o,a]=p.useState(null),i=p.useRef(null),l=p.useRef(null),u=p.useRef(!1),m=p.useRef(!1),f=p.useRef(0),h=p.useRef({}),y=p.useRef(0),g=p.useCallback(k=>{i.current=k,a(k)},[]),x=p.useCallback(()=>{l.current&&(clearInterval(l.current),l.current=null)},[]),w=p.useCallback(()=>{f.current=0,h.current={},y.current=0,u.current=!0,x(),g(null)},[x,g]),b=p.useCallback((k,A)=>{x(),u.current=!1,g(Rc(k,A))},[x,g]),S=p.useCallback((k,A)=>{const O=i.current;O&&g(co(O,k,A))},[g]),T=p.useCallback((k,A)=>{x(),u.current=!1,m.current=!1,f.current=0,h.current={},y.current=Date.now(),g(Rc(k,A));const O=async()=>{if(!(u.current||m.current||!e)){m.current=!0;try{if(ep({now:Date.now(),lastProgressAt:y.current,pollTimeoutMs:r})){const E=i.current;E&&g({...E,steps:E.steps.map(R=>R.status==="success"?R:{...R,status:"failed",error:"Taking longer than expected. It may still complete - check the explorer, then refresh."}),overallStatus:"failed"}),u.current=!0,x();return}const I=i.current;if(!I)return;const v=I.steps.findIndex(E=>E.status!=="success");if(v===-1){u.current=!0,x();return}if(!(v===0||I.steps[v-1].status==="success"))return;try{const E=I.steps[v].stepId,{data:R}=await e(k,E);if(f.current=0,R.status==="success"&&(y.current=Date.now()),R.status==="reverted"){const W=h.current[E]||0;if(t&&W<n){h.current[E]=W+1;try{await t(k,E)}catch(j){console.error(`[intentStatus] retry failed for step ${E}:`,j)}g(co(i.current,v,{status:"executing"}));return}}const B=co(i.current,v,R);g(B),B.overallStatus!=="processing"&&(u.current=!0,x())}catch(E){f.current+=1,console.error(`[intentStatus] poll error (${f.current}/${Tc}):`,E),f.current>=Tc&&(g(co(i.current,v,{status:"error"})),u.current=!0,x())}}finally{m.current=!1}}};O(),l.current=setInterval(O,s)},[e,t,n,s,r,x,g]);return p.useEffect(()=>()=>x(),[x]),{intentStatus:o,startStatusPolling:T,beginStatusTracking:b,applyStepUpdate:S,stopStatusPolling:x,clearStatus:w}}function np(e,t){return(t||"").trim()||`Transaction ${e}. The transaction was rejected on-chain. This may be due to insufficient balance, price changes, or health factor constraints. Please verify your positions and try again.`}const sp=350,rp=2500;async function Bc(e){const{actionId:t,intentIndex:n,intentId:s,stepIndex:r,maxPolls:o=48,maxExecuteAttempts:a=3,pollsBeforeRetry:i=5,maxConsecutiveStatusErrors:l=15,onStatusMessage:u,onStepUpdate:m,signal:f,chainId:h,startWithExecute:y=!0,observeOnly:g=!1,relayer:x=d.relayerService,completeOnExecution:w=!1}=e;if(f?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");let b="pending",S,T,k=e.initialExecuteAttempts??0,A=0,O,I;const v=new Promise((R,B)=>{O=R,I=()=>B(new d.SpiceflowError("ABORT","Execution transaction aborted"))}),E=()=>{k++,e.onExecuteAttempt?.(k),x.executeStep(t,n,r,{action:"execute"}).then(R=>{R.transactionHash&&(S=R.transactionHash),R.status==="success"&&O({status:R.status,transactionHash:R.transactionHash})}).catch(R=>{const B=R instanceof Error?R.message:String(R);console.warn(`[execution] executeStep ${r} attempt ${k} error (will poll):`,B)})};f?.addEventListener("abort",I,{once:!0});try{y&&!g&&k<a&&E();for(let R=0;R<o;R++){const B=R===0?sp:rp;try{const j=await Promise.race([Ln(B).then(()=>{}),v]);if(f?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const N=j??await Promise.race([x.checkStepStatus(s,r,w).then(D=>D.data),v]);if(f?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");A=0,b=N.status,T=N.error;const C=N.transactionHash;C&&(S=C),w&&/^0x[0-9a-f]{64}$/i.test(C??"")&&(N.executionStatus==="success"||N.executionStatus==="reverted")&&(b=N.executionStatus,T=void 0),m?.({status:b,transactionHash:S,error:T})}catch(j){if(j instanceof Error&&(j.name==="AbortError"||j instanceof d.SpiceflowError&&j.code==="ABORT"))throw j;if(A++,A>=l){if(!g)throw j;u?.("Status is temporarily unavailable. The backend continues this action.",S)}continue}if(!g&&b==="created"&&R>=k*i&&k<a&&E(),b==="reverted"||b==="error")throw new d.SpiceflowError("ON_CHAIN_REVERT",np(b,T),{status:b,txHash:S,actionId:t,intentId:s,stepId:r,chainId:h});if(b==="success"||b==="completed")return S;let W="Waiting for solver...";b==="executing"?W="Transaction executing...":b==="submitted"?W="Transaction submitted...":b==="created"&&(W="Waiting for relayer..."),u?.(W,S)}throw new d.SpiceflowError("POLLING_EXHAUSTED",`Transaction is still processing (status: ${b}). This doesn't mean it failed \u2014 the solver may still complete it. Check your positions in a few minutes, or try refreshing the page.`,{actionId:t,intentId:s,stepId:r,lastStatus:b,pollAttempts:o,maxPolls:o,txHash:S})}finally{f?.removeEventListener("abort",I)}}async function op(e){const{actionId:t,intentIndex:n,intentId:s,totalSteps:r,observeOnly:o,delayBeforeSpicenetStepMs:a=5e3,isSpicenetStep:i,beforeStep:l,maxExecuteAttemptsForStep:u,maxPolls:m=48,onStatusMessage:f,onStepUpdate:h,signal:y}=e;let g;for(let x=e.startStep??0;x<r;x++){if(!o&&x>0&&i?.(x)&&a>0&&await Ln(a),o||await l?.(x),y?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const w=u?.(x)??3,b=await Bc({actionId:t,intentIndex:n,intentId:s,stepIndex:x,observeOnly:o,startWithExecute:e.startWithExecute,relayer:e.relayer,maxPolls:m,maxExecuteAttempts:w,initialExecuteAttempts:e.executeAttempts?.get(x),onExecuteAttempt:S=>e.executeAttempts?.set(x,S),maxConsecutiveStatusErrors:w===6?5:15,onStatusMessage:f,onStepUpdate:h?S=>h(x,S):void 0,signal:y,completeOnExecution:x===r-1&&i?.(x)===!1});b&&(g=b)}return g}const ap="0xa9059cbb",ip=[F.SPICE_COMBINED_FEE_RECIPIENT,F.SPICE_GAS_FEE_RECIPIENT,F.SPICE_PLATFORM_FEE_RECIPIENT];function Oc(e){return ip.some(t=>d.addressesEqual(e,t))}function lo(e,t){return e.map(n=>{if(n.domain==="spicenet"||F.isSpicenetChainId(n.chainId)||n.calls.length===0)return n;const s=new Set((n.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&d.addressesEqual(a.to,t)).map(a=>a.token.toLowerCase()));if(s.size===0)return n;const r=[...s].some(F.isNativeToken);let o=0;for(const a of n.calls){if(r&&a.value>0n&&a.data==="0x"&&Oc(a.to)){o+=1;continue}if(!a.data?.startsWith(ap))break;try{const i=M.decodeFunctionData({abi:M.erc20Abi,data:a.data});if(i.functionName!=="transfer")break;const[l]=i.args;if(!Oc(l)||!s.has(a.to.toLowerCase()))break;o+=1}catch{break}}return o===0?n:{...n,calls:n.calls.slice(o)}})}async function da(e,t,n){if(!t||!/^0x[0-9a-f]{64}$/i.test(t))throw new Error("The destination receipt is not available yet; reconcile the existing action before retrying.");const s=()=>new d.SpiceflowError("ABORT","Execution observation retired");if(n?.aborted)throw s();const r=await new Promise((o,a)=>{const i=()=>a(s());n?.addEventListener("abort",i,{once:!0}),Promise.resolve().then(()=>e.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1})).then(o,a).finally(()=>n?.removeEventListener("abort",i))});if(n?.aborted)throw s();if(r.transactionHash?.toLowerCase()===t.toLowerCase()&&r.status==="reverted")throw new d.SpiceflowError("ON_CHAIN_REVERT","The destination transaction reverted.",{status:"reverted",txHash:t});if(r.transactionHash?.toLowerCase()!==t.toLowerCase()||r.status!=="success")throw new Error("The destination transaction has not been confirmed successfully. Reconcile the existing action before retrying.");return t}async function uo(e){let t=e.hash,n=!1;const s=Date.now()+12e4,r=a=>a.transactionHash&&a.transactionHash.toLowerCase()!==t.toLowerCase();let o=await e.client.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1,onReplaced:a=>{const i=a.transaction,l=a.replacedTransaction;if(!(a.reason==="repriced"&&l?.hash?.toLowerCase()===t.toLowerCase()&&l?.to?.toLowerCase()===e.call.to.toLowerCase()&&(l.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(l.value??0)===e.call.value&&l?.from&&l.nonce!==void 0&&/^0x[0-9a-f]{64}$/i.test(i?.hash??"")&&i?.to?.toLowerCase()===e.call.to.toLowerCase()&&(i.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(i.value??0)===e.call.value&&i.from?.toLowerCase()===l?.from?.toLowerCase()&&i.nonce===l?.nonce)){n=!0,e.onCancelled?.();return}t=i.hash,e.onRepriced?.(t)}});if(n)throw new Error("Transaction was cancelled or replaced with a different action; retry the unfinished action");if((e.confirmations??1)>1&&!r(o)&&o.status==="success"&&(o=await e.client.waitForTransactionReceipt({hash:t,timeout:Math.max(s-Date.now(),1),pollingInterval:2e3,confirmations:e.confirmations})),r(o))throw new Error("Unexpected transaction receipt; recover the submitted transaction before retrying");return{receipt:o,hash:t}}const ua=10n,cp=5;function po(e,t,n){return n?.calls.length&&n.amountOutMinimum>0n?[{chainId:e,token:t,amount:n.amountOutMinimum}]:[]}function pa(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function fo({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[t,n]})}}function lp({chainBatches:e,token:t,amount:n}){const s=pa(e),r=s[s.length-1];if(!r)return s;const o=F.getEscrowContractAddress(r.chainId);return r.calls=[...r.calls,fo({token:t,recipient:o,amount:n})],s}function jc({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:r,policy:o}){const a=pa(e),i=a[a.length-1];if(!i)throw new d.SpiceflowError("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const l=d.calculateBpsFee(s,BigInt(o?.platformBps??ua)),u=r+l;if(u>=s)throw new d.SpiceflowError("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:s.toString(),gasFee:r.toString(),spicenetFee:l.toString()});const m=s-u,f=F.getEscrowContractAddress(i.chainId),h=[];return r>0n&&h.push(fo({token:n,recipient:o?.gasRecipient??F.SPICE_GAS_FEE_RECIPIENT,amount:r})),l>0n&&h.push(fo({token:n,recipient:o?.platformRecipient??F.SPICE_PLATFORM_FEE_RECIPIENT,amount:l})),i.calls=[...i.calls,...h,fo({token:n,recipient:f,amount:m})],i.tokenTransfers=[...i.tokenTransfers??[],...r>0n?[{from:t,to:F.SPICE_GAS_FEE_RECIPIENT,token:n,amount:r}]:[],...l>0n?[{from:t,to:F.SPICE_PLATFORM_FEE_RECIPIENT,token:n,amount:l}]:[],{from:t,to:f,token:n,amount:m}],{chainBatches:a,gasFee:r,spicenetFee:l,netEscrowAmount:m,outputCredit:{chainId:i.chainId,token:n,amount:s}}}async function Dc({chainBatches:e,user:t,token:n,grossAmount:s,chainAuthorizations:r}){let o=0n,a,i=jc({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:o});for(let l=0;l<cp;l+=1){const u=F.hashChainBatches(i.chainBatches),m=await d.relayerService.estimateBatchGas({user:t,outputToken:n,chainBatches:i.chainBatches.map((h,y)=>({...h,hash:u[y].hash})),chainAuthorizations:r}),f=m.gasFee;if(f===o&&JSON.stringify(m.policy)===JSON.stringify(a))return i;a=m.policy,o=f,i=jc({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:o,policy:a})}throw new d.SpiceflowError("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function $n(e){return F.isSpicenetChainId(e.chainId)}const dp="0xa9059cbb";function Ir(e,t){return`${e}:${F.normalizeNativeTokenAddress(t).toLowerCase()}`}function Nc(e,t){return t===F.ZERO_ADDRESS.toLowerCase()?{symbol:d.getChainName(e),decimals:18}:F.getTokenByAddress(t,e)??{symbol:"tokens",decimals:18}}function up(e,t){const n=F.getTokenByAddress(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function fa(e){return d.getWalletBalanceEntries(e)}async function ma(e,t,n){const s=new Map,r=new Map,o=[...n?.walletFundingRequirement?[n.walletFundingRequirement]:[],...n?.walletFundingRequirements??[]];for(const f of o){if(f.amount<0n)throw new Error("Accepted wallet funding must not be negative");const h=Ir(f.chainId,f.token);r.set(h,(r.get(h)??0n)+f.amount),s.set(h,0n)}const a=new Map,i=new Map,l=new Map,u=new Map;for(const f of n?.actionOutputCredits??[]){const h=Ir(f.chainId,f.token);u.set(h,(u.get(h)??0n)+f.amount)}for(const f of e){if($n(f))continue;for(const g of f.tokenTransfers??[]){if(g.from!=="escrow"&&g.from!=="solver"||!d.addressesEqual(g.to,t))continue;const x=BigInt(g.amount??0);if(x<=0n)continue;const w=Ir(f.chainId,g.token);a.set(w,(a.get(w)??0n)+x),g.from==="escrow"&&i.set(w,(i.get(w)??0n)+x)}const h=F.getEscrowContract(f.chainId),y=g=>!!h&&h!==F.ZERO_ADDRESS&&d.addressesEqual(g,h);for(const g of f.calls){if(g.value&&g.value>0n){const x=Ir(f.chainId,F.ZERO_ADDRESS);s.set(x,(s.get(x)??0n)+g.value),y(g.to)&&l.set(x,(l.get(x)??0n)+g.value)}if(g.data?.startsWith(dp))try{const x=M.decodeFunctionData({abi:M.erc20Abi,data:g.data});if(x.functionName!=="transfer")continue;const[w,b]=x.args,S=g.to.toLowerCase(),T=Ir(f.chainId,S);s.set(T,(s.get(T)??0n)+b),y(w)&&l.set(T,(l.get(T)??0n)+b)}catch{}}}let m=null;for(const[f,h]of i){const y=h-(l.get(f)??0n);if(y<=0n)continue;const[g,x]=f.split(":"),w=Number(g),b=Nc(w,x);m??(m=await fa(t));const S=mc(m,w,x,up(w,x));if(!(S>=y))throw new d.SpiceflowError("INVALID_PARAMS",`Insufficient Spice ${b.symbol}: needs ${M.formatUnits(y,b.decimals)}, has ${M.formatUnits(S,b.decimals)}.`,{chainId:w,token:x,userAddress:t,requiredAmount:y.toString(),balance:S.toString(),balanceSource:"spice"})}for(const[f,h]of s){const[y,g]=f.split(":"),x=Number(y);let w=h-(a.get(f)??0n)-(u.get(f)??0n);const b=r.get(f)??0n;if(b>w&&(w=b),w<=0n)continue;const S=d.getClientForChain(x),T=g===F.ZERO_ADDRESS.toLowerCase()?await S.getBalance({address:t}):await S.readContract({address:g,abi:M.erc20Abi,functionName:"balanceOf",args:[t]});if(T>=w)continue;const k=Nc(x,g);throw new d.SpiceflowError("INVALID_PARAMS",`Insufficient ${k.symbol} on ${d.getChainName(x)}: needs ${M.formatUnits(w,k.decimals)}, has ${M.formatUnits(T,k.decimals)}.`,{chainId:x,token:g,userAddress:t,requiredAmount:w.toString(),balance:T.toString(),balanceSource:"wallet"})}}function pp({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:s}){if(!(e.some($n)||!(s?e.some(r=>$n(r)?!1:(r.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount??0)>0n)):n>0n)))throw new d.SpiceflowError("INVALID_PARAMS","Payouts funded from Spice balance require a Spicenet funding batch before the destination chain batch. Deposits into Spice balance and gas-only actions do not need one.",{tokenAddress:t,tokenTransferAmount:n.toString(),useCustomTransfers:!!s})}function fp(e,t,n,s){t.forEach((r,o)=>{if(!r.to||!r.from||!r.token||r.amount===void 0)throw new d.SpiceflowError("INVALID_TOKEN_TRANSFER",`tokenTransfers[${o}] on chain ${e} is missing required fields (to/from/token/amount). This usually means the embedded wallet wasn't ready when the intent was built \u2014 please retry.`,{chainId:e,transferIndex:o,transfer:{from:r.from,to:r.to,token:r.token,amount:r.amount?.toString()},signingAddress:n,useCustomTransfers:s})})}function mo({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:s,exp:r,signature:o,chainAuthorizations:a,useCustomTransfers:i}){const l=t,u=F.hashChainBatches(l),m=l.filter(f=>!$n(f)).length;if(pp({chainBatches:l,tokenAddress:n,tokenTransferAmount:s,useCustomTransfers:i}),!i&&s>0n&&m>1)throw new d.SpiceflowError("INVALID_PARAMS","Multiple non-Spicenet batches require explicit tokenTransfers. Pass useCustomTransfers with per-batch transfers instead of relying on the default escrow payout injection.",{nonSpicenetBatchCount:m,tokenAddress:n,tokenTransferAmount:s.toString()});return{user:e,...a?{chainAuthorizations:a}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:o,nbf:0,exp:r,chainBatches:u.map((f,h)=>{const y=l[h],g=$n(y)?[]:i?y.tokenTransfers??[]:s>0n?[{from:"escrow",to:e,token:n,amount:s}]:[];return fp(Number(f.chainId),g,e,i),{hash:f.hash,chainId:Number(f.chainId),tokenTransfers:g,calls:f.calls}})}]}}function Mc(e,t){const n=t?.depositToEscrow?.gasFundingSource==="action-output"?t.depositToEscrow:null,s=t?.depositToEscrow&&!n?lp({chainBatches:e,token:t.depositToEscrow.token,amount:t.depositToEscrow.amount}):pa(e);return{actionOutputDeposit:n,batches:s}}let ha=!1;function Ys(){const{address:e,isConnected:t,isAuthenticated:n,actions:s}=d.useWallet(),r=p.useRef(null),o=p.useRef(0),a=p.useRef(null),{intentStatus:i,startStatusPolling:l,beginStatusTracking:u,applyStepUpdate:m,clearStatus:f}=tp({checkStepStatus:(T,k)=>d.relayerService.checkStepStatus(T,k),retryStep:async(T,k)=>{const[A,O]=T.split("/"),I=parseInt(O||"0",10);await d.relayerService.executeStep(A,I,k,{action:"execute"})}}),h=p.useCallback(()=>{o.current++,a.current=null,f()},[f]),y=p.useRef(s),g=p.useRef(new Map);y.current=s;const x=p.useCallback((T,k,A,O,I)=>la({chainBatches:T,signingAddress:k,actions:y.current,cache:g.current,signal:A,onSignatureRequested:O,beforeSign:I}),[]),w=p.useCallback((T,k,A,O)=>ca(y.current,T,k,A,O),[]),b=p.useCallback(async(T,k,A,O,I,v)=>{let E={},R={};const B=(j,N,C)=>{C?.actionId&&(E={actionId:C.actionId,intentId:C.intentId,intentIndex:C.intentIndex,totalSteps:C.totalSteps,autoContinue:C.autoContinue,user:v?.userOverride||e}),O?.({step:j,message:N,...R,...E,...C})};if(ha)throw new d.SpiceflowError("CONCURRENT_EXECUTION","A execution transaction is already in progress. Please wait.");ha=!0;const W=o.current;try{if(!e)throw new d.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const j=v?.userOverride||e,N=d.relayerService.getBaseUrl(),C=a.current;if(C&&d.addressesEqual(C.user,j)&&C.apiUrl===N){if(C.resume)return await C.resume(T,k,A,I,O,v);throw C.error}a.current=null;const D=ve=>F.hashConditionalExecutionPlan(ve.map(ze=>({...ze,tokenTransfers:ze.tokenTransfers??[]})),[]),P=D(T),L=ve=>new Map(Object.entries(ve??{}).filter(([ze,xe])=>ze!=="signal"&&(typeof xe!="function"||["prepareForSigning","adjustBatchesForEstimate","resolveActionOutputCredits"].includes(ze))).map(([ze,xe])=>[ze,typeof xe=="function"?xe:JSON.stringify(xe,(qe,de)=>typeof de=="bigint"?de.toString():de)])),Q=L(v),G=await d.relayerService.supportsAutomaticContinuation({signal:I}),{actionOutputDeposit:_,batches:J}=Mc(T,v);let K=J,ee=[],te=v?.useCustomTransfers,me=Sc(K),he=null;const ye=async()=>{(v?.walletFundingRequirement||v?.walletFundingRequirements?.length)&&await ma([],j,{walletFundingRequirement:v?.walletFundingRequirement,walletFundingRequirements:v?.walletFundingRequirements});for(let ve=0;me.length>0&&ve<3;ve++)try{he=await fa(j);break}catch(ze){if(I?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(ve===2)throw new d.SpiceflowError("RELAYER_ERROR","Unable to read your Spice balance. Please try again before submitting the transaction.",{cause:ze});await Ln(1e3)}await v?.validateBeforeSubmit?.(K)};B("building","Preparing your wallet and transaction...");const be=await x(K,j,I,()=>B("signing-delegation","Confirm the authorization in your wallet..."),ye);if(B("building","Checking transaction fees and balances..."),I?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const ne=BigInt(Math.floor(Date.now()/1e3)+3600);if(_){const ve=await Dc({chainBatches:T,user:j,token:_.token,grossAmount:_.amount,chainAuthorizations:be});K=ve.chainBatches,ee=[ve.outputCredit],te=!0}if(!v?.skipPreSubmitFeeEstimate){let ve=!1;if(v?.feeExecutionMode==="user-transfer"&&v.adjustBatchesForEstimate&&d.relayerService.canValidateActionFees()){const ze=await d.relayerService.validateActionFees(mo({user:j,chainBatches:K,tokenAddress:k,tokenTransferAmount:A,exp:Number(ne),signature:"0x00",chainAuthorizations:be,useCustomTransfers:te}),{signal:I});r.current=ze;const xe=await v.adjustBatchesForEstimate({feeEstimate:ze,chainBatches:K});ve=!xe||kc(K,xe),xe&&(K=xe)}for(let ze=0;!ve&&ze<10;ze++){const xe=v?.feeExecutionMode==="user-transfer"?lo(K,j):K,qe=mo({user:j,chainBatches:xe,tokenAddress:k,tokenTransferAmount:A,exp:Number(ne),signature:"0x00",chainAuthorizations:be,useCustomTransfers:te}),de=await d.relayerService.estimateActionFees(qe,{signal:I});r.current=de;const Ye=await v?.adjustBatchesForEstimate?.({feeEstimate:de,chainBatches:K}),dt=!!Ye&&kc(K,Ye);if(!Ye||dt){ve=!0;break}K=Ye}if(!ve)throw new d.SpiceflowError("INVALID_PARAMS","Fee estimate did not converge. Please retry.")}if(v?.prepareForSigning){const ve=await v.prepareForSigning(K);if(ve.length!==K.length||ve.some((ze,xe)=>ze.chainId!==K[xe].chainId||ze.domain!==K[xe].domain))throw new Error("The funded route changed before signing");K=ve}v?.resolveActionOutputCredits&&(ee=await v.resolveActionOutputCredits()),(!v?.skipUserFundingPreflight||v.walletFundingRequirement||v.walletFundingRequirements?.length)&&await ma(v?.skipUserFundingPreflight?[]:K,j,{actionOutputCredits:ee,walletFundingRequirement:v?.walletFundingRequirement,walletFundingRequirements:v?.walletFundingRequirements}),me=Sc(K),me.length&&!he&&(he=await d.getWalletBalanceEntries(j)),await v?.validateBeforeSubmit?.(K),B("building","Preparing the signing request...");const Y=await w(K,ne,I,()=>B("signing-intent","Confirm the transaction in your wallet..."));if(I?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(N!==d.relayerService.getBaseUrl())throw new d.SpiceflowError("RELAYER_ERROR","The network changed before submission. Review your balances before trying again.");const ie=mo({user:j,chainBatches:K,tokenAddress:k,tokenTransferAmount:A,exp:Number(ne),signature:Y,chainAuthorizations:be,useCustomTransfers:te});let q=K.length-1;for(;q>=0&&$n(K[q]);)q--;R={totalSteps:K.length},q>=0&&(R={...R,destinationChainId:Number(K[q].chainId),destinationStepIndex:q});const je=Date.now();if(B("submitting","Submitting to relayer..."),await v?.validateBeforeSubmit?.(K),I?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(N!==d.relayerService.getBaseUrl())throw new d.SpiceflowError("RELAYER_ERROR","The network changed before submission. Review your balances before trying again.");console.debug("[SpiceFlow:execution]",{phase:"submit-check-complete",at:Date.now(),durationMs:Date.now()-je});const Ie=K.length;let z;try{z=await d.relayerService.createAction({...ie,...v?.externalExecution?{externalExecution:v.externalExecution}:{}},{autoContinue:G,idempotencyKey:v?.idempotencyKey,signal:I,onAccepted:ve=>{const[ze,xe="0"]=ve.intentIds[0].split("/"),qe=parseInt(xe,10);B("executing","Executing on chain...",{actionId:ze,intentId:`${ze}/${qe}`,intentIndex:qe,totalSteps:Ie,autoContinue:ve.autoContinue===!0})}})}catch(ve){throw W===o.current&&ve instanceof d.SpiceflowError&&ve.context.submissionStatus==="unknown"&&(a.current={user:j,apiUrl:N,error:ve}),ve}const[H,se]=z.intentIds[0].split("/"),le=parseInt(se||"0",10),X=`${H}/${le}`;B("executing","Executing on chain..."),B("executing","Executing on chain...",{actionId:H,intentId:X,intentIndex:le,totalSteps:K.length,autoContinue:z.autoContinue===!0});const oe=new d.RelayerService;oe.setBaseUrl(N);let Re,We=0;const ke=new Map,Fe=async(ve,ze=O,xe=!1)=>{const qe=(de,Ye,dt)=>ze?.({step:de,message:Ye,...dt});try{if((!xe||!Re)&&(Re=await op({actionId:H,intentIndex:le,intentId:X,totalSteps:Ie,signal:ve,observeOnly:z.autoContinue===!0,startWithExecute:!xe,startStep:xe?We:0,executeAttempts:ke,onStepUpdate:(de,Ye)=>{(Ye.status==="success"||Ye.status==="completed")&&(We=Math.max(We,de+1))},relayer:z.autoContinue||xe?oe:d.relayerService,...he?{delayBeforeSpicenetStepMs:0}:{},isSpicenetStep:de=>$n(K[de]),beforeStep:async de=>{if(z.autoContinue===!0||!he||!$n(K[de]))return;const Ye=await Ec({deposits:me,baseline:he,fetchEntries:()=>fa(j),signal:ve});if(ve?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(!Ye)throw new d.SpiceflowError("POLLING_EXHAUSTED","Your deposit is still waiting for Spice credit. Check this transaction's status before trying again.",{actionId:H,intentId:X,stepId:de})},maxExecuteAttemptsForStep:de=>$n(K[de])?6:3,maxPolls:z.autoContinue?Number.POSITIVE_INFINITY:180,onStatusMessage:(de,Ye)=>{qe("executing",de,{txHash:Ye,actionId:H,intentId:X,intentIndex:le,totalSteps:Ie,autoContinue:z.autoContinue===!0})}})),v?.requireDestinationReceipt){const de=[...K].reverse().find(Ye=>!$n(Ye));if(!de)throw new Error("The action has no destination transaction to verify.");await da(d.getClientForChain(de.chainId),Re,ve)}return qe("success","Transaction successful!",{txHash:Re,actionId:H,intentId:X,intentIndex:le,totalSteps:Ie,autoContinue:z.autoContinue===!0}),a.current?.resume===Ne&&(a.current=null),Re||H}catch(de){if(de instanceof d.SpiceflowError&&de.code==="ON_CHAIN_REVERT"&&de.context.status==="reverted"&&(de.context.stepId===0||Ie===1))throw a.current?.resume===Ne&&(a.current=null),de;const Ye=new d.SpiceflowError(de instanceof d.SpiceflowError?de.code:"RELAYER_STATUS_ERROR",de instanceof d.SpiceflowError&&de.code==="ON_CHAIN_REVERT"?de.message:`Your action was accepted, but its completion could not be confirmed. Check the original action before trying again. ${de instanceof Error?de.message:""}`.trim(),{...de instanceof d.SpiceflowError?de.context:{},submissionStatus:"accepted",actionId:H,intentId:X,txHash:Re,cause:de});throw W===o.current&&(a.current={user:j,apiUrl:N,error:Ye,resume:Ne}),Ye}},Ne=async(ve,ze,xe,qe,de,Ye)=>{const dt=L(Ye);if(P!==D(ve)||Q.size!==dt.size||[...Q].some(([_e,$e])=>dt.get(_e)!==$e)||!d.addressesEqual(k,ze)||A!==xe)throw a.current.error;return Fe(qe,de,!0)};return await Fe(I,O)}catch(j){throw console.error("[Execution] Error:",j),B("error",j.message||"Transaction failed",{error:j.message,...j?.context?.submissionStatus==="unknown"?{submissionStatus:"unknown",...typeof j.context.idempotencyKey=="string"&&/^0x[0-9a-f]{64}$/i.test(j.context.idempotencyKey)?{idempotencyKey:j.context.idempotencyKey}:{},...typeof j.context.user=="string"&&/^0x[0-9a-f]{40}$/i.test(j.context.user)?{user:j.context.user}:{}}:{}}),j}finally{ha=!1}},[e,n,x,w]),S=p.useCallback(async(T,k,A,O)=>{if(!e&&(!O?.userOverride||O.signAuthorizationsForEstimate))throw new d.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const I=O?.userOverride||e,v=O?.validateFeeCalls===!0&&O.feeExecutionMode==="user-transfer"&&d.relayerService.canValidateActionFees(),{actionOutputDeposit:E,batches:R}=Mc(T,O);let B=R;const W=O?.feeExecutionMode==="user-transfer"&&!v?lo(B,I):B,j=O?.signAuthorizationsForEstimate?await x(W,I):void 0;let N=O?.useCustomTransfers;E&&(B=(await Dc({chainBatches:T,user:I,token:E.token,grossAmount:E.amount,chainAuthorizations:j})).chainBatches,N=!0);const C=O?.feeExecutionMode==="user-transfer"&&!v?lo(B,I):B,D=mo({user:I,chainBatches:C,tokenAddress:k,tokenTransferAmount:A,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:j,useCustomTransfers:N}),P=await(v?d.relayerService.validateActionFees(D,{signal:O?.signal}):d.relayerService.estimateActionFees(D,{signal:O?.signal}));return r.current=P,P},[e,x]);return{execute:b,estimate:S,lastFeeEstimate:r.current,hasEmbeddedWallet:t&&n,intentStatus:i,startStatusPolling:l,beginStatusTracking:u,applyStepUpdate:m,clearStatus:h}}function Kt(e,t,n,s){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const r=10n**BigInt(t-n);return s==="ceil"?(e+r-1n)/r:e/r}function ln(e,t){if(!Number.isInteger(t)||t<0||t>255)throw new Error("Invalid token decimals");if(!/^\d+(?:\.\d*)?$/.test(e))throw new Error("Enter a valid amount.");if((e.split(".")[1]?.replace(/0+$/,"")??"").length>t)throw new Error(`Use at most ${t} decimal places for this source.`);return M.parseUnits(e,t)}function sn(e,t,n){const s=Kt(e,t,n,"floor");if(Kt(s,n,t,"floor")!==e)throw new Error(`Use at most ${n} decimal places for this delivered token.`);return s}function mp(e){return`0x77${e.slice(4)}`}function Ar({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:s,withdrawalAmount:r,deliveryRecipient:o,deliveryTransfers:a,requestTimestampMs:i,expiresAt:l,metadata:u,requestNonce:m}){if(l!==void 0&&(!Number.isSafeInteger(l)||l<=0))throw new Error("Withdrawal expiry must be a positive Unix timestamp in seconds");const f=a?.length?a:[{token:n,recipient:o,amount:r??s}],h=f.reduce((b,S)=>b+S.amount,0n);if(h<=0n)return null;const y=i??Date.now(),g=BigInt(Math.floor(y/1e3)),x=e??o,w=mp(M.keccak256(M.encodeAbiParameters([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"},...m?[{type:"bytes32"}]:[]],[x,n,o,h,BigInt(t),BigInt(y),...m?[m]:[]])));return{chainId:F.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:[{to:F.ZERO_ADDRESS,value:0n,data:M.encodeFunctionData({abi:F.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:w,nbf:0n,exp:l===void 0?g+3600n:BigInt(l),metadata:u??"{}",transfers:f.map(b=>({token:M.getAddress(b.token).toLowerCase(),to:M.getAddress(b.recipient).toLowerCase(),amount:b.amount}))}]})}]}}const ga=e=>{const[t,n]=p.useState(!1),s=p.useContext(d.SpiceFlowProviderContext),{dark:r,dk:o}=d.useSpiceBrand();if(p.useEffect(()=>{n(!0)},[]),!t)return c.jsx("div",{className:e.className,children:c.jsx("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?o.hoverBg:"#ccc",color:r?o.textSecondary:"white",border:r?`1px solid ${o.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!s){const a='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return c.jsx("div",{className:e.className,children:c.jsx("button",{onClick:()=>{e.onAuthError&&e.onAuthError(a)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?o.errorBg:"#dc2626",color:r?o.errorText:"white",border:r?`1px solid ${o.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return c.jsx(d.PrivyLogin,{...e})},Er=({size:e=20,strokeWidth:t=2,color:n="currentColor",style:s})=>c.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:s,children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),Fr=(e,t,n,s)=>({width:e,height:e,fill:"none",className:t,"aria-hidden":n??!0,style:s}),Zs=({size:e=16,color:t="currentColor",strokeWidth:n=2,direction:s="down",className:r,style:o,"aria-hidden":a})=>c.jsx("svg",{...Fr(e,r,a,{transform:s==="up"?"rotate(180deg)":void 0,transition:"transform 0.3s ease",...o}),viewBox:"0 0 16 16",children:c.jsx("path",{d:"M4 6L8 10L12 6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),hp=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsxs("svg",{...Fr(e,s,o,r),viewBox:"0 0 24 24",children:[c.jsx("circle",{cx:"11",cy:"11",r:"8",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"m21 21-4.3-4.3",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})]}),gp=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsx("svg",{...Fr(e,s,o,r),viewBox:"0 0 24 24",children:c.jsx("path",{d:"m6 9 6 6 6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),wp=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsx("svg",{...Fr(e,s,o,r),viewBox:"0 0 24 24",children:c.jsx("path",{d:"m9 18 6-6-6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Pc=({size:e=14,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsx("svg",{...Fr(e,s,o,r),viewBox:"0 0 16 16",children:c.jsx("path",{d:"M3 8L6.5 11.5L13 5",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Uc=({isSuccess:e,type:t,chainName:n,explorerUrl:s,txHash:r,dark:o=!1,successBg:a="#d1fae5",successBorder:i="#6ee7b7",successText:l="#065f46",errorBg:u="#fee2e2",errorBorder:m="#fca5a5",errorText:f="#dc2626",textSecondary:h="#6b7280"})=>c.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?a:u,border:e?`1px solid ${i}`:`1px solid ${m}`},children:[c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[c.jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c.jsx("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),c.jsxs("div",{children:[c.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:d.font.mono,letterSpacing:"0.5px",color:e?l:f},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),c.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:h},children:["on ",n]})]})]}),s&&r&&c.jsxs("a",{href:`${s}/tx/${r}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:h,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[c.jsx("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),Wc=`
|
|
3
3
|
@keyframes slideUp {
|
|
4
4
|
from { transform: translateY(100%); }
|
|
5
5
|
to { transform: translateY(0); }
|