@orbs-network/spot-react 1.1.31 → 1.1.32
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spot-context.d.ts","sourceRoot":"","sources":["../../../src/spot-context.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAwD,MAAM,OAAO,CAAC;AAU7E,OAAO,EACL,SAAS,EACT,eAAe,EAEhB,MAAM,SAAS,CAAC;AAoCjB,eAAO,MAAM,WAAW,uCAA8C,CAAC;
|
|
1
|
+
{"version":3,"file":"spot-context.d.ts","sourceRoot":"","sources":["../../../src/spot-context.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAwD,MAAM,OAAO,CAAC;AAU7E,OAAO,EACL,SAAS,EACT,eAAe,EAEhB,MAAM,SAAS,CAAC;AAoCjB,eAAO,MAAM,WAAW,uCAA8C,CAAC;AAsLvE,eAAO,MAAM,YAAY,GAAI,OAAO,SAAS,4CAM5C,CAAC;AAEF,eAAO,MAAM,cAAc,uBAM1B,CAAC"}
|
package/dist/spot-react.js
CHANGED
|
@@ -2857,7 +2857,7 @@ const Ri = async ({
|
|
|
2857
2857
|
partner: s == null ? void 0 : s.partner,
|
|
2858
2858
|
isDev: o
|
|
2859
2859
|
})
|
|
2860
|
-
]).then(([T, y]) => [...T, ...y])).sort((T, y) => y.createdAt - T.createdAt), Mi = "1.1.
|
|
2860
|
+
]).then(([T, y]) => [...T, ...y])).sort((T, y) => y.createdAt - T.createdAt), Mi = "1.1.32", Li = {
|
|
2861
2861
|
version: Mi
|
|
2862
2862
|
}, Ir = (e) => {
|
|
2863
2863
|
let t;
|
|
@@ -6336,9 +6336,7 @@ const Ns = cr(null), wc = new Bo({
|
|
|
6336
6336
|
const t = In(), n = _(
|
|
6337
6337
|
() => Ua(e.partner),
|
|
6338
6338
|
[e.partner]
|
|
6339
|
-
)
|
|
6340
|
-
console.log({ supportedChains: n });
|
|
6341
|
-
const r = _(() => {
|
|
6339
|
+
), r = _(() => {
|
|
6342
6340
|
const u = n[0];
|
|
6343
6341
|
return e.chainId && n.includes(e.chainId) ? e.chainId : u;
|
|
6344
6342
|
}, [e.chainId, n]), s = _(
|
package/dist/spot-react.umd.cjs
CHANGED
|
@@ -61,4 +61,4 @@
|
|
|
61
61
|
dollarValueOut
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
-
`,extractResults:y=>{var b;return(((b=y.data)==null?void 0:b.orderFilleds)||[]).map(D=>({...D,timestamp:new Date(D.timestamp).getTime()}))}})};class di extends Error{constructor(){super("No graph endpoint found"),this.name="NoGraphEndpointError"}}const li=async({chainId:e,signal:t,page:n,limit:r,filters:s})=>{try{const a=await oi({chainId:e,signal:t,page:n,limit:r,filters:s}),[o,u]=await Promise.all([ui({chainId:e,orders:a,signal:t}),ci({chainId:e,orders:a,signal:t})]),p=a.map(w=>{const y=o==null?void 0:o.filter(b=>b.TWAP_id===Number(w.Contract_id)&>(b.exchange,w.exchange)&>(b.twapAddress,w.twapAddress));return ai(w,e,y,pi(w,y||[],u))}).sort((w,y)=>y.createdAt-w.createdAt),f=new Set;return p.filter(w=>f.has(w.id)?!1:(f.add(w.id),!0))}catch{return[]}},pi=(e,t,n)=>{var u;const r=(u=n==null?void 0:n.find(p=>p.twapId===e.Contract_id.toString()&>(p.twapAddress,e.twapAddress)))==null?void 0:u.status,a=jr(t).reduce((p,f)=>p.plus(f.inAmount),new v(0)).toFixed(),o=Gr(e.ask_srcAmount,a);return fi(o,e.ask_deadline*1e3,r)},Gr=(e,t)=>{if(!t||!e)return 0;const n=v(t).dividedBy(e).toNumber();return n>=.99?100:n<=0?0:Number((n*100).toFixed(2))},fi=(e,t,n)=>e===100?ue.Completed:n==="CANCELLED"?ue.Cancelled:n==="COMPLETED"?ue.Completed:t>Date.now()?ue.Open:ue.Expired,hi=async({signal:e,page:t,chainId:n,limit:r,config:s,account:a,isDev:o=!1,includeV1GraphOrders:u=!0})=>(await Promise.all([!s||!u?Promise.resolve([]):li({chainId:n,signal:e,page:t,limit:r,filters:{accounts:[a],configs:s.twapConfig?[s.twapConfig]:[]}}),ri({chainId:n,signal:e,account:a,exchange:s==null?void 0:s.adapter,partner:s==null?void 0:s.partner,isDev:o})]).then(([w,y])=>[...w,...y])).sort((w,y)=>y.createdAt-w.createdAt),mi={version:"1.1.31"},Xr=e=>{let t;const n=new Set,r=(f,w)=>{const y=typeof f=="function"?f(t):f;if(!Object.is(y,t)){const b=t;t=w??(typeof y!="object"||y===null)?y:Object.assign({},t,y),n.forEach(D=>D(t,b))}},s=()=>t,u={setState:r,getState:s,getInitialState:()=>p,subscribe:f=>(n.add(f),()=>n.delete(f))},p=t=e(r,s,u);return u},yi=(e=>e?Xr(e):Xr),gi=e=>e;function Ai(e,t=gi){const n=F.useSyncExternalStore(e.subscribe,F.useCallback(()=>t(e.getState()),[e,t]),F.useCallback(()=>t(e.getInitialState()),[e,t]));return F.useDebugValue(n),n}const Zr=e=>{const t=yi(e),n=r=>Ai(t,r);return Object.assign(n,t),n},Ei=(e=>e?Zr(e):Zr),An={},Yr={currentTime:Date.now(),cancelOrders:{},swapExecutions:[An],swapExecutionIndex:0},Q=Ei((e,t)=>({state:Yr,updateState:n=>e(r=>({state:{...r.state,...n}})),updateSwapExecutionAtIndex:(n,r)=>e(s=>{const a=[...s.state.swapExecutions];return a[n]={...a[n]??An,...r},{state:{...s.state,swapExecutions:a}}}),resetSwapExecutionAtIndex:()=>e(n=>{const r=[...n.state.swapExecutions];return r[n.state.swapExecutionIndex]=An,{state:{...n.state,swapExecutions:r}}}),resetState:()=>{const n=t().state;e({state:{...Yr,currentTime:Date.now(),isMarketOrder:n.isMarketOrder,swapExecutions:[...n.swapExecutions,An],swapExecutionIndex:n.swapExecutionIndex+1}})}}));var Se=(e=>(e[e.LOADING=1]="LOADING",e[e.SUCCESS=2]="SUCCESS",e[e.FAILED=3]="FAILED",e))(Se||{}),en=(e=>(e.TRIGGER_MARKET_PRICE="triggerMarketPriceDisclaimer",e.MARKET_PRICE="marketOrderDisclaimer",e.LIMIT_PRICE="limitOrderDisclaimer",e))(en||{}),nt=(e=>(e.WRAP="wrap",e.APPROVE="approve",e.CREATE="create",e))(nt||{});const rt=(e,t)=>!t||!e||v(e).isNaN()?"":v(e).multipliedBy(v(10).pow(t)).toFixed(0),Ee=(e,t)=>{try{return!t||!e||v(e).isNaN()?"":v(e).dividedBy(v(10).pow(t)).toFixed()}catch(n){return console.error(n),""}},bi=e=>{const t="An error occurred.";if(!e||!e.message)return t;try{return e.message.toLowerCase().includes("rejected")?"Transaction Rejected":t}catch{return t}},Xn=e=>{var t,n,r,s;if(e!=null&&e.message)return((n=(t=e.message)==null?void 0:t.toLowerCase())==null?void 0:n.includes("rejected"))||((s=(r=e.message)==null?void 0:r.toLowerCase())==null?void 0:s.includes("denied"))},Jr=(e,t)=>{const n=Et(t);return n&&Rt(e.address)?n.wToken:e};function Zn(e){return e?e/864e5:0}function En(e){return e?e/6e4:0}const Ci=(e,t)=>e?X.TWAP_MARKET:t===1?X.LIMIT:X.TWAP_LIMIT,Yn=(e,t,n)=>{const r=Et(n);return Rt((e==null?void 0:e.address)||"")&>((t==null?void 0:t.address)||"",(r==null?void 0:r.wToken.address)||"")},Jn=(e,t,n)=>{const r=Et(n);return gt((e==null?void 0:e.address)||"",(r==null?void 0:r.wToken.address)||"")&&Rt((t==null?void 0:t.address)||"")},Lt=(e,t)=>{if(!t)return"";const n=Et(t);return`${n==null?void 0:n.explorer}/tx/${e}`},er=(e,t)=>F.useMemo(()=>rt(t,e),[e,t]),bt=(e,t)=>F.useMemo(()=>Ee(t,e),[e,t]),bn=()=>{const{chainId:e}=q();return F.useMemo(()=>Et(e),[e])},Ti=e=>{const t=bn();return F.useMemo(()=>{if(!(!e||!t))return Lt(e,t.id)},[e,t])},qe=(e,t)=>F.useMemo(()=>!e||!t||v(e||"0").isZero()||v(t||"0").isZero()?"":v(e||"0").times(t).toFixed(),[e,t]),wi=()=>{const{srcToken:e,dstToken:t,chainId:n}=q();return F.useMemo(()=>Yn(e,t,n),[e,t,n])},xi=()=>{const{srcToken:e,dstToken:t,chainId:n}=q();return F.useMemo(()=>Jn(e,t,n),[e,t,n])},Si=()=>{const e=wi(),t=xi();return e||t},st=()=>{const{srcToken:e,typedInputAmount:t}=q();return{amount:er(e==null?void 0:e.decimals,t),amountUI:t,error:v(t||0).isZero()?"enterAmount":void 0}},vi=(e,t)=>{const{module:n,srcUsd1Token:r,marketPrice:s,minChunkSizeUsd:a,typedInputAmount:o}=q();return F.useMemo(()=>{if(v(o||"0").isZero()||!s||v(r||"0").isZero())return;if(!e)return{type:me.MIN_CHUNKS,value:1,args:{minChunks:"1"}};const{isError:u}=qa(e,t,n);if(u)return{type:me.MAX_CHUNKS,value:t,args:{maxChunks:`${t}`}};const{isError:p,value:f}=Na(o||"",r||"",a||0);if(p)return{type:me.MIN_TRADE_SIZE,value:f,args:{minTradeSize:`${f}`}}},[e,t,n,o,r,a,s])},Ke=()=>{const{srcToken:e,srcUsd1Token:t,module:n,minChunkSizeUsd:r}=q(),s=Q(O=>O.state.typedChunks),a=Q(O=>O.updateState),{amount:o,amountUI:u}=st(),p=F.useMemo(()=>Fa(u||"",t||"",r||0),[u,t,r]),f=F.useMemo(()=>va(p,n,s),[p,s,n]),w=F.useCallback(O=>a({typedChunks:O}),[a]),y=F.useMemo(()=>Oa(o||"",f),[o,f]),b=bt(e==null?void 0:e.decimals,y),D=F.useMemo(()=>t?v(b||"0").times(t||0).toString():"0",[b,t]);return{totalTrades:f,maxTrades:p,amountPerTradeUI:b,amountPerTrade:y,amountPerTradeUsd:D,onChange:w,error:vi(f,p)}},Fi=()=>{const{srcToken:e,dstToken:t}=q(),{onChange:n,totalTrades:r,amountPerTradeUsd:s,amountPerTradeUI:a,error:o,maxTrades:u,amountPerTrade:p}=Ke();return{error:o,maxTrades:u,totalTrades:r,amountPerTradeUI:a,amountPerTrade:p,onChange:n,amountPerTradeUsd:s,fromToken:e,toToken:t}},es=e=>{const t=Zn(e);if(t>=1)return`${t.toFixed(t%1?1:0)} ${t===1?"day":"days"}`;const n=En(e)/60;if(n>=1)return`${n.toFixed(n%1?1:0)} ${n===1?"hour":"hours"}`;const r=En(e);return`${r.toFixed(r%1?1:0)} ${r===1?"minute":"minutes"}`},Di=e=>{const{totalTrades:t}=Ke(),{marketPrice:n,typedInputAmount:r}=q(),s=F.useMemo(()=>{const{isError:o,value:u}=La(e);if(!(!o||v(r||"0").isZero()||!n))return{type:me.MIN_FILL_DELAY,value:u,args:{fillDelay:es(u)}}},[e,r,n]),a=F.useMemo(()=>{const{isError:o,value:u}=Ia(e,t);if(!(!o||v(r||"0").isZero()||!n))return{type:me.MAX_FILL_DELAY,value:u,args:{fillDelay:es(u)}}},[e,r,n,t]);return s||a},Nt=()=>{const{callbacks:e}=q(),t=Q(a=>a.state.typedFillDelay),n=Q(a=>a.updateState),r=F.useMemo(()=>t||Rn,[t]),s=Di(r);return{fillDelay:r,onChange:F.useCallback(a=>{var o;n({typedFillDelay:a}),(o=e==null?void 0:e.onFillDelayChange)==null||o.call(e,a)},[n,e]),error:s,milliseconds:r.unit*r.value}},Pi=()=>{const{onChange:e,fillDelay:t,error:n}=Nt(),r=F.useCallback(a=>e({unit:t.unit,value:Number(a)}),[e,t]),s=F.useCallback(a=>e({unit:a,value:t.value}),[e,t]);return{onInputChange:r,onUnitSelect:s,onChange:e,milliseconds:t.unit*t.value,fillDelay:t,error:n}},Oi=e=>{const{module:t,marketPrice:n}=q();return F.useMemo(()=>{const r=Ua(t,e),s=Ra(e);if(n){if(r.isError)return{type:me.MAX_ORDER_DURATION,value:r.value,args:{duration:`${Math.floor(Zn(r.value)).toFixed(0)} days`}};if(s.isError)return{type:me.MIN_ORDER_DURATION,value:s.value,args:{duration:`${Math.floor(En(s.value)).toFixed(0)} minutes`}}}},[e,t,n])},tr=()=>{const{module:e,callbacks:t}=q(),n=Q(p=>p.state.typedDuration),r=Q(p=>p.updateState),s=Ke().totalTrades,a=Nt().fillDelay,o=F.useMemo(()=>Sa(e,s,a,n),[s,a,n,e]),u=Oi(o);return{duration:o,setDuration:F.useCallback(p=>{var f;r({typedDuration:p}),(f=t==null?void 0:t.onDurationChange)==null||f.call(t,p)},[r,t]),error:u}},Ii=()=>{const{duration:e,setDuration:t,error:n}=tr(),r=F.useCallback(a=>{t({unit:e.unit,value:Number(a)})},[t,e]),s=F.useCallback(a=>{t({unit:a,value:e.value})},[t,e]);return{duration:e,onChange:t,milliseconds:e.unit*e.value,onInputChange:r,onUnitSelect:s,error:n}},Bi=()=>{const{module:e}=q();return F.useMemo(()=>e===j.STOP_LOSS?la:pa,[e])},nr=()=>{const{module:e}=q(),t=Q(n=>n.state.isMarketOrder);return F.useMemo(()=>e!==j.STOP_LOSS&&e!==j.TAKE_PROFIT||t?void 0:e===j.STOP_LOSS?fa:ha,[e,t])},ts=e=>{if(e===void 0||e==="")return e;const t=v(e);return t.isNaN()||t.isZero()?"0":v(1).div(t).toFixed()},Cn=()=>{const{srcToken:e,dstToken:t}=q(),n=Q(p=>p.updateState),r=Q(p=>p.state.isInvertedTrade),s=Q(p=>p.state.typedTriggerPrice),a=Q(p=>p.state.typedLimitPrice),o=Q(p=>p.state.isMarketOrder);return{onInvert:F.useCallback(()=>{n({isInvertedTrade:!r,...s!==void 0?{typedTriggerPrice:ts(s)}:{},...a!==void 0?{typedLimitPrice:ts(a)}:{}})},[n,r,s,a]),isInverted:r,fromToken:r?t:e,toToken:r?e:t,isMarketPrice:o}},Tn=e=>e?v(e).isNaN()?"":e:"",ns=({amount:e,typedValue:t,amountDecimals:n=18,invertedAmountDecimals:r=18,amountUsd:s,invertedAmountUsd:a,isInverted:o})=>{const u=F.useMemo(()=>{if(t!==void 0)return Tn(t);const w=Ee(e,n);return!w||v(w||"0").isZero()?"":o?v(1).div(w).toFixed():w},[e,n,o,t]),p=F.useMemo(()=>u?Tn(o?rt(u,r):e):"",[e,u,r,o]),f=qe(u||"0",o?a:s);return{amount:p,amountUI:u,usd:Tn(f)}},rs=({typedValue:e,tokenDecimals:t=18,initialPrice:n="0",percentage:r,setValue:s,setPercentage:a})=>{const{isInverted:o}=Cn(),u=F.useMemo(()=>v((()=>{if(e!==void 0){const b=o?v(e).isZero()?v(0):v(1).div(e):v(e);return rt(b.toFixed(),t)}if(r!==void 0&&v(n||"0").gt(0)&&!v(n||"0").isNaN()){const b=v(n||"0"),D=v(r||0).div(100);return b.plus(b.multipliedBy(D)).decimalPlaces(0).toFixed()}return v(n).gt(0)?n:""})()).decimalPlaces(0).toFixed(),[e,r,t,n,o]),p=F.useCallback(y=>{s(y),a(null)},[s,a]),f=F.useCallback(y=>{s(void 0),a(y)},[s,a]),w=F.useMemo(()=>{if(!n||v(n).isZero())return"";if(r!=null)return r;if(u){const y=v(n),D=v(u).minus(y).div(y).multipliedBy(100).decimalPlaces(2).toString();return v(D||"0").isZero()?"":D}return""},[u,n,r]);return{amount:v(u).isNaN()?"":u,typedValue:e,selectedPercentage:w,onChange:p,onPercentageChange:f,isTypedValue:e!==void 0}},Mi=(e="")=>{const{module:t,marketPrice:n,typedInputAmount:r}=q();return F.useMemo(()=>{if(v(r||"0").isZero()||!n||t!==j.STOP_LOSS&&t!==j.TAKE_PROFIT)return;const s=Ba(n||"",e||"",t);if(s!=null&&s.isError)return{type:me.STOP_LOSS_TRIGGER_PRICE_GREATER_THAN_MARKET_PRICE,value:s.value};const a=Ma(n||"",e||"",t);if(a!=null&&a.isError)return{type:me.TAKE_PROFIT_TRIGGER_PRICE_LESS_THAN_MARKET_PRICE,value:a.value};if(!e||v(e||0).isZero())return{type:me.EMPTY_TRIGGER_PRICE,value:e}},[n,e,t,r])},ki=e=>{const{srcToken:t,dstToken:n,module:r,dstUsd1Token:s}=q(),a=Ke().amountPerTrade,o=Q(f=>f.state.isMarketOrder),u=F.useMemo(()=>xa(r,a,e,(t==null?void 0:t.decimals)||0),[e,a,o,t==null?void 0:t.decimals,r]),p=bt((n==null?void 0:n.decimals)||0,u);return{amount:u,amountUI:p,usd:qe(p,s)}},Ct=()=>{const{dstToken:e,dstUsd1Token:t,marketPrice:n,module:r,callbacks:s}=q(),a=Q(_=>_.updateState),o=Bi(),u=Q(_=>_.state.triggerPricePercent),p=u===void 0?o:u,f=r===j.STOP_LOSS||r===j.TAKE_PROFIT,w=rs({typedValue:Q(_=>_.state.typedTriggerPrice),percentage:p,tokenDecimals:(e==null?void 0:e.decimals)||18,initialPrice:f?n:void 0,setValue:F.useCallback(_=>{var S;a({typedTriggerPrice:_}),(S=s==null?void 0:s.onTriggerPriceChange)==null||S.call(s,_||"")},[a,s]),setPercentage:F.useCallback(_=>{var S;a({triggerPricePercent:_}),(S=s==null?void 0:s.onTriggerPricePercentChange)==null||S.call(s,_||"")},[a,s])}),y=Mi(w.amount),b=bt((e==null?void 0:e.decimals)||18,w.amount),D=qe(b,t),{amount:O,amountUI:B,usd:k}=ki(w.amount);return F.useMemo(()=>({...w,amountUI:v(b).isNaN()?"":b,usd:v(D).isNaN()?"":D,error:y,pricePerChunk:O,pricePerChunkUI:B,pricePerChunkUsd:k}),[w,b,D,y,O,B,k])},_i=e=>{const{module:t,marketPrice:n,typedInputAmount:r}=q(),{amount:s}=Ct(),a=Q(o=>o.state.isMarketOrder);return F.useMemo(()=>{if(v(r||"0").isZero()||!s||!n)return;const o=ka(s,e,a,t),u=_a(s,e,a,t);if(o!=null&&o.isError)return{type:me.TRIGGER_LIMIT_PRICE_GREATER_THAN_TRIGGER_PRICE,value:o.value};if(u!=null&&u.isError)return{type:me.TRIGGER_LIMIT_PRICE_GREATER_THAN_TRIGGER_PRICE,value:u.value};if(e&&v(e||0).isZero())return{type:me.MISSING_LIMIT_PRICE,value:e||""}},[e,s,t,a,r,n])},wn=()=>{const{dstToken:e,dstUsd1Token:t,marketPrice:n,callbacks:r}=q(),s=Q(b=>b.updateState),a=nr(),o=Q(b=>b.state.limitPricePercent),u=o===void 0?a:o,p=rs({typedValue:Q(b=>b.state.typedLimitPrice),percentage:u,tokenDecimals:(e==null?void 0:e.decimals)||18,initialPrice:n,setValue:F.useCallback(b=>{var D;s({typedLimitPrice:b}),(D=r==null?void 0:r.onLimitPriceChange)==null||D.call(r,b||"")},[s,r]),setPercentage:F.useCallback(b=>{var D;s({limitPricePercent:b}),(D=r==null?void 0:r.onLimitPricePercentChange)==null||D.call(r,b||"")},[s,r])}),f=_i(p.amount),w=bt((e==null?void 0:e.decimals)||18,p.amount),y=qe(w,t);return F.useMemo(()=>({...p,amountUI:v(w).isNaN()?"":w,usd:v(y).isNaN()?"":y,error:f}),[p,w,y,f])},Ui=()=>{const{module:e}=q(),t=Q(u=>u.updateState),n=Q(u=>u.state.isMarketOrder),r=nr(),s=Q(u=>u.state.triggerPricePercent)||0,a=e===j.LIMIT,o=F.useCallback(()=>{!n&&e===j.STOP_LOSS&&t({limitPricePercent:r}),t({isMarketOrder:!n})},[t,s,e,n,r]);return{isLimitPrice:!n,toggleLimitPrice:o,hide:a}},Ri=()=>{const{module:e,marketPriceLoading:t,srcToken:n,dstToken:r,srcUsd1Token:s,dstUsd1Token:a}=q(),{amount:o,typedValue:u,onChange:p,onPercentageChange:f,selectedPercentage:w,error:y,isTypedValue:b}=wn(),D=Q(G=>G.updateState),O=nr(),{isLimitPrice:B,toggleLimitPrice:k}=Ui(),{fromToken:_,toToken:S,isInverted:K}=Cn(),U=ns({amount:o,typedValue:u,amountDecimals:(r==null?void 0:r.decimals)||18,invertedAmountDecimals:(n==null?void 0:n.decimals)||18,amountUsd:a,invertedAmountUsd:s,isInverted:K}),V=F.useCallback(()=>{D({typedLimitPrice:void 0}),D({limitPricePercent:O})},[D,e,O]);return{price:U.amount,priceUI:U.amountUI,error:y,onInputChange:p,onPercentageChange:f,onReset:V,usd:U.usd,srcToken:n,dstToken:r,invertedSrcToken:_,invertedDstToken:S,percentage:w,isLoading:t,isLimitPrice:B,toggleLimitPrice:k,isTypedValue:b}},Li=()=>{const{marketPrice:e,marketPriceLoading:t,srcToken:n,dstToken:r,srcUsd1Token:s,dstUsd1Token:a}=q(),{amount:o,typedValue:u,onChange:p,onPercentageChange:f,selectedPercentage:w,error:y,pricePerChunk:b,pricePerChunkUI:D,pricePerChunkUsd:O,isTypedValue:B}=Ct(),k=Q(G=>G.updateState),{fromToken:_,toToken:S,isInverted:K}=Cn(),U=ns({amount:o,typedValue:u,amountDecimals:(r==null?void 0:r.decimals)||18,invertedAmountDecimals:(n==null?void 0:n.decimals)||18,amountUsd:a,invertedAmountUsd:s,isInverted:K}),V=F.useCallback(()=>{k({triggerPricePercent:void 0,typedTriggerPrice:void 0})},[k]);return{price:U.amount,priceUI:U.amountUI,amountPerChunk:b,amountPerChunkUI:D,amountPerChunkUsd:O,error:y,onInputChange:p,onPercentageChange:f,percentage:w,onReset:V,usd:U.usd,srcToken:n,dstToken:r,invertedSrcToken:_,invertedDstToken:S,isLoading:t||!e,isTypedValue:B}},ss=()=>{const{module:e,marketPrice:t}=q(),n=wn().amount,r=Ct().amount,s=Q(a=>a.state.isMarketOrder);return e===j.LIMIT||!s?n||"":e===j.STOP_LOSS||e===j.TAKE_PROFIT?r||"":t||""},xn=()=>{const{srcToken:e,dstToken:t,dstUsd1Token:n}=q(),r=ss(),s=st().amount,a=F.useMemo(()=>Ta(s||"",r,(e==null?void 0:e.decimals)||0),[s,r,e==null?void 0:e.decimals]),o=bt(t==null?void 0:t.decimals,a);return{amount:a,amountUI:o,usd:qe(o,n)}},rr=()=>{const{srcToken:e,dstToken:t,dstUsd1Token:n}=q(),r=ss(),s=Ke().amountPerTrade,a=Q(p=>p.state.isMarketOrder),o=F.useMemo(()=>wa(s,r,!!a,(e==null?void 0:e.decimals)||0),[s,r,a,e==null?void 0:e.decimals]),u=bt(t==null?void 0:t.decimals,o);return{amount:o,amountUI:u,usd:qe(u,n)}},Ni=()=>{const{typedInputAmount:e,marketPriceLoading:t,dstToken:n}=q(),{amountUI:r,usd:s}=xn(),o=Si()?e:r,u=er(n==null?void 0:n.decimals,o);return{value:o,valueWei:u,isLoading:t,usd:s}},qi=()=>{const e=Q(s=>s.state.isMarketOrder),{module:t}=q(),n=F.useMemo(()=>{if(e&&t===j.STOP_LOSS)return en.TRIGGER_MARKET_PRICE},[e,t]),r=F.useMemo(()=>{if(!(t!==j.LIMIT&&t!==j.TWAP))return e?en.MARKET_PRICE:en.LIMIT_PRICE},[e,t]);return n||r},Ki=()=>{const{minChunkSizeUsd:e,typedInputAmount:t,srcUsd1Token:n}=q(),r=qe(t,n);return F.useMemo(()=>v(e).gt(v(r||"0"))?{type:me.MIN_TRADE_SIZE_ERROR,value:e}:void 0,[e,r])};function as(){const{marketPrice:e,marketPriceLoading:t,typedInputAmount:n,srcUsd1Token:r,srcBalance:s,chainId:a}=q(),{error:o}=Ct(),{error:u}=wn(),{error:p}=Ke(),{error:f}=Nt(),{error:w}=tr(),y=Ki(),b=st().amount,D=F.useMemo(()=>{if(s&&v(b).gt(s))return{type:me.INSUFFICIENT_BALANCE,value:s||""}},[s,b,a]);return F.useMemo(()=>Ha({marketPrice:e,typedInputAmount:n,srcUsd1Token:r,marketPriceLoading:t,triggerPriceError:o,limitPriceError:u,tradesError:p,fillDelayError:f,durationError:w,balanceError:D,minTradeSizeError:y}),[e,t,n,o,u,p,f,w,D,r,y])}var qt=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Hi={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Wi=(ks=class{constructor(){N(this,He,Hi);N(this,St,!1)}setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&l(this,St)&&e!==l(this,He)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:l(this,He),provider:e}),M(this,He,e),process.env.NODE_ENV!=="production"&&M(this,St,!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&M(this,St,!0),l(this,He).setTimeout(e,t)}clearTimeout(e){l(this,He).clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&M(this,St,!0),l(this,He).setInterval(e,t)}clearInterval(e){l(this,He).clearInterval(e)}},He=new WeakMap,St=new WeakMap,ks),Tt=new Wi;function Qi(e){setTimeout(e,0)}var wt=typeof window>"u"||"Deno"in globalThis;function be(){}function zi(e,t){return typeof e=="function"?e(t):e}function sr(e){return typeof e=="number"&&e>=0&&e!==1/0}function is(e,t){return Math.max(e+(t||0)-Date.now(),0)}function at(e,t){return typeof e=="function"?e(t):e}function Be(e,t){return typeof e=="function"?e(t):e}function os(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:a,queryKey:o,stale:u}=e;if(o){if(r){if(t.queryHash!==ar(o,t.options))return!1}else if(!tn(t.queryKey,o))return!1}if(n!=="all"){const p=t.isActive();if(n==="active"&&!p||n==="inactive"&&p)return!1}return!(typeof u=="boolean"&&t.isStale()!==u||s&&s!==t.state.fetchStatus||a&&!a(t))}function cs(e,t){const{exact:n,status:r,predicate:s,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(xt(t.options.mutationKey)!==xt(a))return!1}else if(!tn(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function ar(e,t){return((t==null?void 0:t.queryKeyHashFn)||xt)(e)}function xt(e){return JSON.stringify(e,(t,n)=>or(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function tn(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>tn(e[n],t[n])):!1}var $i=Object.prototype.hasOwnProperty;function ir(e,t){if(e===t)return e;const n=us(e)&&us(t);if(!n&&!(or(e)&&or(t)))return t;const s=(n?e:Object.keys(e)).length,a=n?t:Object.keys(t),o=a.length,u=n?new Array(o):{};let p=0;for(let f=0;f<o;f++){const w=n?f:a[f],y=e[w],b=t[w];if(y===b){u[w]=y,(n?f<s:$i.call(e,w))&&p++;continue}if(y===null||b===null||typeof y!="object"||typeof b!="object"){u[w]=b;continue}const D=ir(y,b);u[w]=D,D===y&&p++}return s===o&&p===s?e:u}function Sn(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function us(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function or(e){if(!ds(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!ds(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ds(e){return Object.prototype.toString.call(e)==="[object Object]"}function ji(e){return new Promise(t=>{Tt.setTimeout(t,e)})}function cr(e,t,n){if(typeof n.structuralSharing=="function")return n.structuralSharing(e,t);if(n.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return ir(e,t)}catch(r){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${n.queryHash}]: ${r}`),r}return ir(e,t)}return t}function Vi(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Gi(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var vn=Symbol();function ls(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===vn&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===vn?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ps(e,t){return typeof e=="function"?e(...t):!!e}var Xi=(_s=class extends qt{constructor(){super();N(this,vt);N(this,ot);N(this,Kt);M(this,Kt,t=>{if(!wt&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,ot)||this.setEventListener(l(this,Kt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ot))==null||t.call(this),M(this,ot,void 0))}setEventListener(t){var n;M(this,Kt,t),(n=l(this,ot))==null||n.call(this),M(this,ot,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,vt)!==t&&(M(this,vt,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof l(this,vt)=="boolean"?l(this,vt):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},vt=new WeakMap,ot=new WeakMap,Kt=new WeakMap,_s),ur=new Xi;function dr(){let e,t;const n=new Promise((s,a)=>{e=s,t=a});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var Zi=Qi;function Yi(){let e=[],t=0,n=u=>{u()},r=u=>{u()},s=Zi;const a=u=>{t?e.push(u):s(()=>{n(u)})},o=()=>{const u=e;e=[],u.length&&s(()=>{r(()=>{u.forEach(p=>{n(p)})})})};return{batch:u=>{let p;t++;try{p=u()}finally{t--,t||o()}return p},batchCalls:u=>(...p)=>{a(()=>{u(...p)})},schedule:a,setNotifyFunction:u=>{n=u},setBatchNotifyFunction:u=>{r=u},setScheduler:u=>{s=u}}}var de=Yi(),Ji=(Us=class extends qt{constructor(){super();N(this,Ht,!0);N(this,ct);N(this,Wt);M(this,Wt,t=>{if(!wt&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){l(this,ct)||this.setEventListener(l(this,Wt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ct))==null||t.call(this),M(this,ct,void 0))}setEventListener(t){var n;M(this,Wt,t),(n=l(this,ct))==null||n.call(this),M(this,ct,t(this.setOnline.bind(this)))}setOnline(t){l(this,Ht)!==t&&(M(this,Ht,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,Ht)}},Ht=new WeakMap,ct=new WeakMap,Wt=new WeakMap,Us),Fn=new Ji;function eo(e){return Math.min(1e3*2**e,3e4)}function fs(e){return(e??"online")==="online"?Fn.isOnline():!0}var lr=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function hs(e){let t=!1,n=0,r;const s=dr(),a=()=>s.status!=="pending",o=B=>{var k;if(!a()){const _=new lr(B);b(_),(k=e.onCancel)==null||k.call(e,_)}},u=()=>{t=!0},p=()=>{t=!1},f=()=>ur.isFocused()&&(e.networkMode==="always"||Fn.isOnline())&&e.canRun(),w=()=>fs(e.networkMode)&&e.canRun(),y=B=>{a()||(r==null||r(),s.resolve(B))},b=B=>{a()||(r==null||r(),s.reject(B))},D=()=>new Promise(B=>{var k;r=_=>{(a()||f())&&B(_)},(k=e.onPause)==null||k.call(e)}).then(()=>{var B;r=void 0,a()||(B=e.onContinue)==null||B.call(e)}),O=()=>{if(a())return;let B;const k=n===0?e.initialPromise:void 0;try{B=k??e.fn()}catch(_){B=Promise.reject(_)}Promise.resolve(B).then(y).catch(_=>{var G;if(a())return;const S=e.retry??(wt?0:3),K=e.retryDelay??eo,U=typeof K=="function"?K(n,_):K,V=S===!0||typeof S=="number"&&n<S||typeof S=="function"&&S(n,_);if(t||!V){b(_);return}n++,(G=e.onFail)==null||G.call(e,n,_),ji(U).then(()=>f()?void 0:D()).then(()=>{t?b(_):O()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r==null||r(),s),cancelRetry:u,continueRetry:p,canStart:w,start:()=>(w()?O():D().then(O),s)}}var ms=(Rs=class{constructor(){N(this,Ft)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),sr(this.gcTime)&&M(this,Ft,Tt.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(wt?1/0:300*1e3))}clearGcTimeout(){l(this,Ft)&&(Tt.clearTimeout(l(this,Ft)),M(this,Ft,void 0))}},Ft=new WeakMap,Rs),to=(Ls=class extends ms{constructor(t){super();N(this,Le);N(this,Dt);N(this,Qt);N(this,Me);N(this,Pt);N(this,he);N(this,sn);N(this,Ot);M(this,Ot,!1),M(this,sn,t.defaultOptions),this.setOptions(t.options),this.observers=[],M(this,Pt,t.client),M(this,Me,l(this,Pt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,M(this,Dt,As(this.options)),this.state=t.state??l(this,Dt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=l(this,he))==null?void 0:t.promise}setOptions(t){if(this.options={...l(this,sn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=As(this.options);n.data!==void 0&&(this.setState(gs(n.data,n.dataUpdatedAt)),M(this,Dt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Me).remove(this)}setData(t,n){const r=cr(this.state.data,t,this.options);return z(this,Le,et).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){z(this,Le,et).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,s;const n=(r=l(this,he))==null?void 0:r.promise;return(s=l(this,he))==null||s.cancel(t),n?n.then(be).catch(be):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(l(this,Dt))}isActive(){return this.observers.some(t=>Be(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===vn||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>at(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!is(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=l(this,he))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=l(this,he))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,Me).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(l(this,he)&&(l(this,Ot)?l(this,he).cancel({revert:!0}):l(this,he).cancelRetry()),this.scheduleGc()),l(this,Me).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||z(this,Le,et).call(this,{type:"invalidate"})}async fetch(t,n){var p,f,w,y,b,D,O,B,k,_,S,K;if(this.state.fetchStatus!=="idle"&&((p=l(this,he))==null?void 0:p.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(l(this,he))return l(this,he).continueRetry(),l(this,he).promise}if(t&&this.setOptions(t),!this.options.queryFn){const U=this.observers.find(V=>V.options.queryFn);U&&this.setOptions(U.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const r=new AbortController,s=U=>{Object.defineProperty(U,"signal",{enumerable:!0,get:()=>(M(this,Ot,!0),r.signal)})},a=()=>{const U=ls(this.options,n),G=(()=>{const oe={client:l(this,Pt),queryKey:this.queryKey,meta:this.meta};return s(oe),oe})();return M(this,Ot,!1),this.options.persister?this.options.persister(U,G,this):U(G)},u=(()=>{const U={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:l(this,Pt),state:this.state,fetchFn:a};return s(U),U})();(f=this.options.behavior)==null||f.onFetch(u,this),M(this,Qt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((w=u.fetchOptions)==null?void 0:w.meta))&&z(this,Le,et).call(this,{type:"fetch",meta:(y=u.fetchOptions)==null?void 0:y.meta}),M(this,he,hs({initialPromise:n==null?void 0:n.initialPromise,fn:u.fetchFn,onCancel:U=>{U instanceof lr&&U.revert&&this.setState({...l(this,Qt),fetchStatus:"idle"}),r.abort()},onFail:(U,V)=>{z(this,Le,et).call(this,{type:"failed",failureCount:U,error:V})},onPause:()=>{z(this,Le,et).call(this,{type:"pause"})},onContinue:()=>{z(this,Le,et).call(this,{type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0}));try{const U=await l(this,he).start();if(U===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(U),(D=(b=l(this,Me).config).onSuccess)==null||D.call(b,U,this),(B=(O=l(this,Me).config).onSettled)==null||B.call(O,U,this.state.error,this),U}catch(U){if(U instanceof lr){if(U.silent)return l(this,he).promise;if(U.revert){if(this.state.data===void 0)throw U;return this.state.data}}throw z(this,Le,et).call(this,{type:"error",error:U}),(_=(k=l(this,Me).config).onError)==null||_.call(k,U,this),(K=(S=l(this,Me).config).onSettled)==null||K.call(S,this.state.data,U,this),U}finally{this.scheduleGc()}}},Dt=new WeakMap,Qt=new WeakMap,Me=new WeakMap,Pt=new WeakMap,he=new WeakMap,sn=new WeakMap,Ot=new WeakMap,Le=new WeakSet,et=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...ys(r.data,this.options),fetchMeta:t.meta??null};case"success":const s={...r,...gs(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return M(this,Qt,t.manual?s:void 0),s;case"error":const a=t.error;return{...r,error:a,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),de.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),l(this,Me).notify({query:this,type:"updated",action:t})})},Ls);function ys(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:fs(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function gs(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function As(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var no=(Ns=class extends qt{constructor(t,n){super();N(this,ee);N(this,ve);N(this,Y);N(this,an);N(this,Ce);N(this,It);N(this,zt);N(this,Ge);N(this,ut);N(this,on);N(this,$t);N(this,jt);N(this,Bt);N(this,Mt);N(this,dt);N(this,Vt,new Set);this.options=n,M(this,ve,t),M(this,ut,null),M(this,Ge,dr()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,Y).addObserver(this),Es(l(this,Y),this.options)?z(this,ee,ln).call(this):this.updateResult(),z(this,ee,xr).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return pr(l(this,Y),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return pr(l(this,Y),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,z(this,ee,Sr).call(this),z(this,ee,vr).call(this),l(this,Y).removeObserver(this)}setOptions(t){const n=this.options,r=l(this,Y);if(this.options=l(this,ve).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Be(this.options.enabled,l(this,Y))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");z(this,ee,Fr).call(this),l(this,Y).setOptions(this.options),n._defaulted&&!Sn(this.options,n)&&l(this,ve).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,Y),observer:this});const s=this.hasListeners();s&&bs(l(this,Y),r,this.options,n)&&z(this,ee,ln).call(this),this.updateResult(),s&&(l(this,Y)!==r||Be(this.options.enabled,l(this,Y))!==Be(n.enabled,l(this,Y))||at(this.options.staleTime,l(this,Y))!==at(n.staleTime,l(this,Y)))&&z(this,ee,Cr).call(this);const a=z(this,ee,Tr).call(this);s&&(l(this,Y)!==r||Be(this.options.enabled,l(this,Y))!==Be(n.enabled,l(this,Y))||a!==l(this,dt))&&z(this,ee,wr).call(this,a)}getOptimisticResult(t){const n=l(this,ve).getQueryCache().build(l(this,ve),t),r=this.createResult(n,t);return so(this,r)&&(M(this,Ce,r),M(this,zt,this.options),M(this,It,l(this,Y).state)),r}getCurrentResult(){return l(this,Ce)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n==null||n(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&l(this,Ge).status==="pending"&&l(this,Ge).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,Vt).add(t)}getCurrentQuery(){return l(this,Y)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=l(this,ve).defaultQueryOptions(t),r=l(this,ve).getQueryCache().build(l(this,ve),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return z(this,ee,ln).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,Ce)))}createResult(t,n){var c;const r=l(this,Y),s=this.options,a=l(this,Ce),o=l(this,It),u=l(this,zt),f=t!==r?t.state:l(this,an),{state:w}=t;let y={...w},b=!1,D;if(n._optimisticResults){const d=this.hasListeners(),E=!d&&Es(t,n),m=d&&bs(t,r,n,s);(E||m)&&(y={...y,...ys(w.data,t.options)}),n._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:O,errorUpdatedAt:B,status:k}=y;D=y.data;let _=!1;if(n.placeholderData!==void 0&&D===void 0&&k==="pending"){let d;a!=null&&a.isPlaceholderData&&n.placeholderData===(u==null?void 0:u.placeholderData)?(d=a.data,_=!0):d=typeof n.placeholderData=="function"?n.placeholderData((c=l(this,jt))==null?void 0:c.state.data,l(this,jt)):n.placeholderData,d!==void 0&&(k="success",D=cr(a==null?void 0:a.data,d,n),b=!0)}if(n.select&&D!==void 0&&!_)if(a&&D===(o==null?void 0:o.data)&&n.select===l(this,on))D=l(this,$t);else try{M(this,on,n.select),D=n.select(D),D=cr(a==null?void 0:a.data,D,n),M(this,$t,D),M(this,ut,null)}catch(d){M(this,ut,d)}l(this,ut)&&(O=l(this,ut),D=l(this,$t),B=Date.now(),k="error");const S=y.fetchStatus==="fetching",K=k==="pending",U=k==="error",V=K&&S,G=D!==void 0,i={status:k,fetchStatus:y.fetchStatus,isPending:K,isSuccess:k==="success",isError:U,isInitialLoading:V,isLoading:V,data:D,dataUpdatedAt:y.dataUpdatedAt,error:O,errorUpdatedAt:B,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:y.dataUpdateCount>0||y.errorUpdateCount>0,isFetchedAfterMount:y.dataUpdateCount>f.dataUpdateCount||y.errorUpdateCount>f.errorUpdateCount,isFetching:S,isRefetching:S&&!K,isLoadingError:U&&!G,isPaused:y.fetchStatus==="paused",isPlaceholderData:b,isRefetchError:U&&G,isStale:fr(t,n),refetch:this.refetch,promise:l(this,Ge),isEnabled:Be(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const d=g=>{i.status==="error"?g.reject(i.error):i.data!==void 0&&g.resolve(i.data)},E=()=>{const g=M(this,Ge,i.promise=dr());d(g)},m=l(this,Ge);switch(m.status){case"pending":t.queryHash===r.queryHash&&d(m);break;case"fulfilled":(i.status==="error"||i.data!==m.value)&&E();break;case"rejected":(i.status!=="error"||i.error!==m.reason)&&E();break}}return i}updateResult(){const t=l(this,Ce),n=this.createResult(l(this,Y),this.options);if(M(this,It,l(this,Y).state),M(this,zt,this.options),l(this,It).data!==void 0&&M(this,jt,l(this,Y)),Sn(n,t))return;M(this,Ce,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:s}=this.options,a=typeof s=="function"?s():s;if(a==="all"||!a&&!l(this,Vt).size)return!0;const o=new Set(a??l(this,Vt));return this.options.throwOnError&&o.add("error"),Object.keys(l(this,Ce)).some(u=>{const p=u;return l(this,Ce)[p]!==t[p]&&o.has(p)})};z(this,ee,$s).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&z(this,ee,xr).call(this)}},ve=new WeakMap,Y=new WeakMap,an=new WeakMap,Ce=new WeakMap,It=new WeakMap,zt=new WeakMap,Ge=new WeakMap,ut=new WeakMap,on=new WeakMap,$t=new WeakMap,jt=new WeakMap,Bt=new WeakMap,Mt=new WeakMap,dt=new WeakMap,Vt=new WeakMap,ee=new WeakSet,ln=function(t){z(this,ee,Fr).call(this);let n=l(this,Y).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(be)),n},Cr=function(){z(this,ee,Sr).call(this);const t=at(this.options.staleTime,l(this,Y));if(wt||l(this,Ce).isStale||!sr(t))return;const r=is(l(this,Ce).dataUpdatedAt,t)+1;M(this,Bt,Tt.setTimeout(()=>{l(this,Ce).isStale||this.updateResult()},r))},Tr=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,Y)):this.options.refetchInterval)??!1},wr=function(t){z(this,ee,vr).call(this),M(this,dt,t),!(wt||Be(this.options.enabled,l(this,Y))===!1||!sr(l(this,dt))||l(this,dt)===0)&&M(this,Mt,Tt.setInterval(()=>{(this.options.refetchIntervalInBackground||ur.isFocused())&&z(this,ee,ln).call(this)},l(this,dt)))},xr=function(){z(this,ee,Cr).call(this),z(this,ee,wr).call(this,z(this,ee,Tr).call(this))},Sr=function(){l(this,Bt)&&(Tt.clearTimeout(l(this,Bt)),M(this,Bt,void 0))},vr=function(){l(this,Mt)&&(Tt.clearInterval(l(this,Mt)),M(this,Mt,void 0))},Fr=function(){const t=l(this,ve).getQueryCache().build(l(this,ve),this.options);if(t===l(this,Y))return;const n=l(this,Y);M(this,Y,t),M(this,an,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},$s=function(t){de.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,Ce))}),l(this,ve).getQueryCache().notify({query:l(this,Y),type:"observerResultsUpdated"})})},Ns);function ro(e,t){return Be(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Es(e,t){return ro(e,t)||e.state.data!==void 0&&pr(e,t,t.refetchOnMount)}function pr(e,t,n){if(Be(t.enabled,e)!==!1&&at(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&fr(e,t)}return!1}function bs(e,t,n,r){return(e!==t||Be(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&fr(e,n)}function fr(e,t){return Be(t.enabled,e)!==!1&&e.isStaleByTime(at(t.staleTime,e))}function so(e,t){return!Sn(e.getCurrentResult(),t)}function Cs(e){return{onFetch:(t,n)=>{var w,y,b,D,O;const r=t.options,s=(b=(y=(w=t.fetchOptions)==null?void 0:w.meta)==null?void 0:y.fetchMore)==null?void 0:b.direction,a=((D=t.state.data)==null?void 0:D.pages)||[],o=((O=t.state.data)==null?void 0:O.pageParams)||[];let u={pages:[],pageParams:[]},p=0;const f=async()=>{let B=!1;const k=K=>{Object.defineProperty(K,"signal",{enumerable:!0,get:()=>(t.signal.aborted?B=!0:t.signal.addEventListener("abort",()=>{B=!0}),t.signal)})},_=ls(t.options,t.fetchOptions),S=async(K,U,V)=>{if(B)return Promise.reject();if(U==null&&K.pages.length)return Promise.resolve(K);const oe=(()=>{const E={client:t.client,queryKey:t.queryKey,pageParam:U,direction:V?"backward":"forward",meta:t.options.meta};return k(E),E})(),i=await _(oe),{maxPages:c}=t.options,d=V?Gi:Vi;return{pages:d(K.pages,i,c),pageParams:d(K.pageParams,U,c)}};if(s&&a.length){const K=s==="backward",U=K?ao:Ts,V={pages:a,pageParams:o},G=U(r,V);u=await S(V,G,K)}else{const K=e??a.length;do{const U=p===0?o[0]??r.initialPageParam:Ts(r,u);if(p>0&&U==null)break;u=await S(u,U),p++}while(p<K)}return u};t.options.persister?t.fetchFn=()=>{var B,k;return(k=(B=t.options).persister)==null?void 0:k.call(B,f,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=f}}}function Ts(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function ao(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var io=(qs=class extends ms{constructor(t){super();N(this,Qe);N(this,cn);N(this,We);N(this,Te);N(this,kt);M(this,cn,t.client),this.mutationId=t.mutationId,M(this,Te,t.mutationCache),M(this,We,[]),this.state=t.state||ws(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){l(this,We).includes(t)||(l(this,We).push(t),this.clearGcTimeout(),l(this,Te).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){M(this,We,l(this,We).filter(n=>n!==t)),this.scheduleGc(),l(this,Te).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){l(this,We).length||(this.state.status==="pending"?this.scheduleGc():l(this,Te).remove(this))}continue(){var t;return((t=l(this,kt))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,u,p,f,w,y,b,D,O,B,k,_,S,K,U,V,G,oe,i,c;const n=()=>{z(this,Qe,mt).call(this,{type:"continue"})},r={client:l(this,cn),meta:this.options.meta,mutationKey:this.options.mutationKey};M(this,kt,hs({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(d,E)=>{z(this,Qe,mt).call(this,{type:"failed",failureCount:d,error:E})},onPause:()=>{z(this,Qe,mt).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,Te).canRun(this)}));const s=this.state.status==="pending",a=!l(this,kt).canStart();try{if(s)n();else{z(this,Qe,mt).call(this,{type:"pending",variables:t,isPaused:a}),await((u=(o=l(this,Te).config).onMutate)==null?void 0:u.call(o,t,this,r));const E=await((f=(p=this.options).onMutate)==null?void 0:f.call(p,t,r));E!==this.state.context&&z(this,Qe,mt).call(this,{type:"pending",context:E,variables:t,isPaused:a})}const d=await l(this,kt).start();return await((y=(w=l(this,Te).config).onSuccess)==null?void 0:y.call(w,d,t,this.state.context,this,r)),await((D=(b=this.options).onSuccess)==null?void 0:D.call(b,d,t,this.state.context,r)),await((B=(O=l(this,Te).config).onSettled)==null?void 0:B.call(O,d,null,this.state.variables,this.state.context,this,r)),await((_=(k=this.options).onSettled)==null?void 0:_.call(k,d,null,t,this.state.context,r)),z(this,Qe,mt).call(this,{type:"success",data:d}),d}catch(d){try{throw await((K=(S=l(this,Te).config).onError)==null?void 0:K.call(S,d,t,this.state.context,this,r)),await((V=(U=this.options).onError)==null?void 0:V.call(U,d,t,this.state.context,r)),await((oe=(G=l(this,Te).config).onSettled)==null?void 0:oe.call(G,void 0,d,this.state.variables,this.state.context,this,r)),await((c=(i=this.options).onSettled)==null?void 0:c.call(i,void 0,d,t,this.state.context,r)),d}finally{z(this,Qe,mt).call(this,{type:"error",error:d})}}finally{l(this,Te).runNext(this)}}},cn=new WeakMap,We=new WeakMap,Te=new WeakMap,kt=new WeakMap,Qe=new WeakSet,mt=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),de.batch(()=>{l(this,We).forEach(r=>{r.onMutationUpdate(t)}),l(this,Te).notify({mutation:this,type:"updated",action:t})})},qs);function ws(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var oo=(Ks=class extends qt{constructor(t={}){super();N(this,Xe);N(this,Ne);N(this,un);this.config=t,M(this,Xe,new Set),M(this,Ne,new Map),M(this,un,0)}build(t,n,r){const s=new io({client:t,mutationCache:this,mutationId:++Bn(this,un)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Xe).add(t);const n=Dn(t);if(typeof n=="string"){const r=l(this,Ne).get(n);r?r.push(t):l(this,Ne).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Xe).delete(t)){const n=Dn(t);if(typeof n=="string"){const r=l(this,Ne).get(n);if(r)if(r.length>1){const s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&l(this,Ne).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=Dn(t);if(typeof n=="string"){const r=l(this,Ne).get(n),s=r==null?void 0:r.find(a=>a.state.status==="pending");return!s||s===t}else return!0}runNext(t){var r;const n=Dn(t);if(typeof n=="string"){const s=(r=l(this,Ne).get(n))==null?void 0:r.find(a=>a!==t&&a.state.isPaused);return(s==null?void 0:s.continue())??Promise.resolve()}else return Promise.resolve()}clear(){de.batch(()=>{l(this,Xe).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Xe).clear(),l(this,Ne).clear()})}getAll(){return Array.from(l(this,Xe))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>cs(n,r))}findAll(t={}){return this.getAll().filter(n=>cs(t,n))}notify(t){de.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return de.batch(()=>Promise.all(t.map(n=>n.continue().catch(be))))}},Xe=new WeakMap,Ne=new WeakMap,un=new WeakMap,Ks);function Dn(e){var t;return(t=e.options.scope)==null?void 0:t.id}var co=(Hs=class extends qt{constructor(t,n){super();N(this,Je);N(this,Ze);N(this,lt);N(this,Fe);N(this,Ye);M(this,Ze,t),this.setOptions(n),this.bindMethods(),z(this,Je,Mn).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){var r;const n=this.options;this.options=l(this,Ze).defaultMutationOptions(t),Sn(this.options,n)||l(this,Ze).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,Fe),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&xt(n.mutationKey)!==xt(this.options.mutationKey)?this.reset():((r=l(this,Fe))==null?void 0:r.state.status)==="pending"&&l(this,Fe).setOptions(this.options)}onUnsubscribe(){var t;this.hasListeners()||(t=l(this,Fe))==null||t.removeObserver(this)}onMutationUpdate(t){z(this,Je,Mn).call(this),z(this,Je,Dr).call(this,t)}getCurrentResult(){return l(this,lt)}reset(){var t;(t=l(this,Fe))==null||t.removeObserver(this),M(this,Fe,void 0),z(this,Je,Mn).call(this),z(this,Je,Dr).call(this)}mutate(t,n){var r;return M(this,Ye,n),(r=l(this,Fe))==null||r.removeObserver(this),M(this,Fe,l(this,Ze).getMutationCache().build(l(this,Ze),this.options)),l(this,Fe).addObserver(this),l(this,Fe).execute(t)}},Ze=new WeakMap,lt=new WeakMap,Fe=new WeakMap,Ye=new WeakMap,Je=new WeakSet,Mn=function(){var n;const t=((n=l(this,Fe))==null?void 0:n.state)??ws();M(this,lt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Dr=function(t){de.batch(()=>{var n,r,s,a,o,u,p,f;if(l(this,Ye)&&this.hasListeners()){const w=l(this,lt).variables,y=l(this,lt).context,b={client:l(this,Ze),meta:this.options.meta,mutationKey:this.options.mutationKey};(t==null?void 0:t.type)==="success"?((r=(n=l(this,Ye)).onSuccess)==null||r.call(n,t.data,w,y,b),(a=(s=l(this,Ye)).onSettled)==null||a.call(s,t.data,null,w,y,b)):(t==null?void 0:t.type)==="error"&&((u=(o=l(this,Ye)).onError)==null||u.call(o,t.error,w,y,b),(f=(p=l(this,Ye)).onSettled)==null||f.call(p,void 0,t.error,w,y,b))}this.listeners.forEach(w=>{w(l(this,lt))})})},Hs),uo=(Ws=class extends qt{constructor(t={}){super();N(this,ze);this.config=t,M(this,ze,new Map)}build(t,n,r){const s=n.queryKey,a=n.queryHash??ar(s,n);let o=this.get(a);return o||(o=new to({client:t,queryKey:s,queryHash:a,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){l(this,ze).has(t.queryHash)||(l(this,ze).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=l(this,ze).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,ze).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){de.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,ze).get(t)}getAll(){return[...l(this,ze).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>os(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>os(t,r)):n}notify(t){de.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){de.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){de.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},ze=new WeakMap,Ws),lo=(Qs=class{constructor(e={}){N(this,se);N(this,pt);N(this,ft);N(this,Gt);N(this,Xt);N(this,ht);N(this,Zt);N(this,Yt);M(this,se,e.queryCache||new uo),M(this,pt,e.mutationCache||new oo),M(this,ft,e.defaultOptions||{}),M(this,Gt,new Map),M(this,Xt,new Map),M(this,ht,0)}mount(){Bn(this,ht)._++,l(this,ht)===1&&(M(this,Zt,ur.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,se).onFocus())})),M(this,Yt,Fn.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,se).onOnline())})))}unmount(){var e,t;Bn(this,ht)._--,l(this,ht)===0&&((e=l(this,Zt))==null||e.call(this),M(this,Zt,void 0),(t=l(this,Yt))==null||t.call(this),M(this,Yt,void 0))}isFetching(e){return l(this,se).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,pt).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=l(this,se).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=l(this,se).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(at(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,se).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=l(this,se).get(r.queryHash),a=s==null?void 0:s.state.data,o=zi(t,a);if(o!==void 0)return l(this,se).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return de.batch(()=>l(this,se).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=l(this,se).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=l(this,se);de.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=l(this,se);return de.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=de.batch(()=>l(this,se).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(be).catch(be)}invalidateQueries(e,t={}){return de.batch(()=>(l(this,se).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=de.batch(()=>l(this,se).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let a=s.fetch(void 0,n);return n.throwOnError||(a=a.catch(be)),s.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(be)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=l(this,se).build(this,t);return n.isStaleByTime(at(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(be).catch(be)}fetchInfiniteQuery(e){return e.behavior=Cs(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(be).catch(be)}ensureInfiniteQueryData(e){return e.behavior=Cs(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Fn.isOnline()?l(this,pt).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,se)}getMutationCache(){return l(this,pt)}getDefaultOptions(){return l(this,ft)}setDefaultOptions(e){M(this,ft,e)}setQueryDefaults(e,t){l(this,Gt).set(xt(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...l(this,Gt).values()],n={};return t.forEach(r=>{tn(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,Xt).set(xt(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...l(this,Xt).values()],n={};return t.forEach(r=>{tn(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...l(this,ft).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=ar(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===vn&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...l(this,ft).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,se).clear(),l(this,pt).clear()}},se=new WeakMap,pt=new WeakMap,ft=new WeakMap,Gt=new WeakMap,Xt=new WeakMap,ht=new WeakMap,Zt=new WeakMap,Yt=new WeakMap,Qs),xs=ce.createContext(void 0),nn=e=>{const t=ce.useContext(xs);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},po=({client:e,children:t})=>(ce.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),H.jsx(xs.Provider,{value:e,children:t})),Ss=ce.createContext(!1),fo=()=>ce.useContext(Ss);Ss.Provider;function ho(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var mo=ce.createContext(ho()),yo=()=>ce.useContext(mo),go=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Ao=e=>{ce.useEffect(()=>{e.clearReset()},[e])},Eo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||ps(n,[e.error,r])),bo=e=>{if(e.suspense){const n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Co=(e,t)=>e.isLoading&&e.isFetching&&!t,To=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,vs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function wo(e,t,n){var y,b,D,O,B;if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const r=fo(),s=yo(),a=nn(),o=a.defaultQueryOptions(e);(b=(y=a.getDefaultOptions().queries)==null?void 0:y._experimental_beforeQuery)==null||b.call(y,o),process.env.NODE_ENV!=="production"&&(o.queryFn||console.error(`[${o.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),o._optimisticResults=r?"isRestoring":"optimistic",bo(o),go(o,s),Ao(s);const u=!a.getQueryCache().get(o.queryHash),[p]=ce.useState(()=>new t(a,o)),f=p.getOptimisticResult(o),w=!r&&e.subscribed!==!1;if(ce.useSyncExternalStore(ce.useCallback(k=>{const _=w?p.subscribe(de.batchCalls(k)):be;return p.updateResult(),_},[p,w]),()=>p.getCurrentResult(),()=>p.getCurrentResult()),ce.useEffect(()=>{p.setOptions(o)},[o,p]),To(o,f))throw vs(o,p,s);if(Eo({result:f,errorResetBoundary:s,throwOnError:o.throwOnError,query:a.getQueryCache().get(o.queryHash),suspense:o.suspense}))throw f.error;if((O=(D=a.getDefaultOptions().queries)==null?void 0:D._experimental_afterQuery)==null||O.call(D,o,f),o.experimental_prefetchInRender&&!wt&&Co(f,r)){const k=u?vs(o,p,s):(B=a.getQueryCache().get(o.queryHash))==null?void 0:B.promise;k==null||k.catch(be).finally(()=>{p.updateResult()})}return o.notifyOnChangeProps?f:p.trackResult(f)}function xo(e,t){return wo(e,no)}function it(e,t){const n=nn(),[r]=ce.useState(()=>new co(n,e));ce.useEffect(()=>{r.setOptions(e)},[r,e]);const s=ce.useSyncExternalStore(ce.useCallback(o=>r.subscribe(de.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=ce.useCallback((o,u)=>{r.mutate(o,u).catch(be)},[r]);if(s.error&&ps(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:a,mutateAsync:s.mutate}}const rn=()=>{const e=Q(a=>a.state.swapExecutionIndex),t=Q(a=>a.state.swapExecutions[a.state.swapExecutionIndex]??{}),n=Q(a=>a.updateSwapExecutionAtIndex),r=Q(a=>a.resetSwapExecutionAtIndex),s=F.useCallback(a=>n(e,a),[n,e]);return F.useMemo(()=>({...t,update:s,resetSwap:r}),[t,s,r])},So=2e4,vo=()=>{const{module:e}=q(),t=Q(n=>n.state.isMarketOrder);return F.useMemo(()=>e===j.TWAP?t?X.TWAP_MARKET:X.TWAP_LIMIT:e===j.LIMIT?X.LIMIT:e===j.STOP_LOSS?t?X.STOP_LOSS_MARKET:X.STOP_LOSS_LIMIT:e===j.TAKE_PROFIT?t?X.TAKE_PROFIT_MARKET:X.TAKE_PROFIT_LIMIT:X.TWAP_MARKET,[e,t])},hr=()=>{const{account:e,config:t,chainId:n,isDev:r}=q();return F.useMemo(()=>["useTwapOrderHistoryManager",e,t==null?void 0:t.adapter,t==null?void 0:t.partner,n,r],[e,t,n,r])},Fo=()=>{const e=nn(),t=hr();return F.useCallback((n,r)=>{e.setQueryData(t,s=>s==null?void 0:s.map(a=>a.id===n?{...a,status:r}:a))},[e,t])},Do=()=>{const{callbacks:e}=q(),t=nn(),n=hr();return F.useCallback(r=>{var u;const s=t.getQueryData(n);let a=!1;const o=[];s&&s.filter(p=>p.version===2).forEach(p=>{var w;const f=r.find(y=>y.id===p.id);f&&f.progress!==p.progress&&(a=!0,o.push(f),f.status===ue.Completed&&((w=e==null?void 0:e.onOrderFilled)==null||w.call(e,f)))}),a&&((u=e==null?void 0:e.onOrdersProgressUpdate)==null||u.call(e,o))},[t,n,e])},Po=(e,t)=>{const n=new Set(e.map(s=>s.id)),r=(t==null?void 0:t.filter(s=>s.version===1&&!n.has(s.id)))??[];return[...e,...r].sort((s,a)=>a.createdAt-s.createdAt)},mr=()=>{const{account:e,config:t,chainId:n,isDev:r}=q(),s=nn(),a=hr(),o=Do();return xo({refetchInterval:So,refetchOnWindowFocus:!0,retry:!1,gcTime:1/0,staleTime:1/0,queryKey:a,queryFn:async({signal:p})=>{if(!e||!n||!t)return[];const f=s.getQueryData(a),w=!f,y=await hi({signal:p,chainId:n,config:t,account:e,isDev:r,includeV1GraphOrders:w});o(y);const b=y.map(D=>t!=null&&t.twapConfig?{...D,fillDelayMillis:Hn(D,t.twapConfig)}:D);return w?b:Po(b,f)}})},Oo=(e,t,n)=>F.useMemo(()=>{if(!(!e||!t||!n||n!=null&&n.isMarketPrice))return Nr(n,e==null?void 0:e.decimals,t==null?void 0:t.decimals)},[n,e,t]),Io=(e,t,n)=>F.useMemo(()=>{if(!(!e||!t||!n))return qr(n,e.decimals,t.decimals)},[n,e,t]),Bo=(e,t,n)=>F.useMemo(()=>{if(!(!e||!t||!n))return Wn(n.srcAmountFilled,n.dstAmountFilled,e.decimals,t.decimals)},[n,e,t]),Pn=(e,t)=>[...e.filter(r=>r.status===t)].sort((r,s)=>s.createdAt-r.createdAt),Mo=()=>{const{data:e,isLoading:t,refetch:n,isRefetching:r}=mr(),s=F.useCallback(()=>n().then(a=>a.data),[n]);return F.useMemo(()=>({orders:{all:e??[],open:Pn(e??[],ue.Open),completed:Pn(e??[],ue.Completed),cancelled:Pn(e??[],ue.Cancelled),expired:Pn(e??[],ue.Expired)},isLoading:t,isRefetching:r,refetchOrders:s}),[e,t,r,s])},yr=()=>{const e=Q(n=>n.state.currentTime),t=tr().duration;return F.useMemo(()=>Da(e,t),[e,t])},Fs=()=>{const{srcToken:e,dstToken:t,account:n,chainId:r,slippage:s,config:a,module:o,fees:u}=q(),{amount:p}=st(),{amountPerTrade:f,totalTrades:w}=Ke(),y=yr(),{amount:b}=rr(),{pricePerChunk:D}=Ct(),{milliseconds:O}=Nt();return F.useMemo(()=>{var B;return Wr({chainId:r,srcToken:Rt((e==null?void 0:e.address)||"")?((B=Et(r))==null?void 0:B.wToken.address)||"":(e==null?void 0:e.address)||"",dstToken:(t==null?void 0:t.address)||"",srcAmount:p,deadlineMillis:y,fillDelayMillis:!w||w===1?0:O,slippage:s*100,account:n,srcAmountPerTrade:f,dstMinAmountPerTrade:b,triggerAmountPerTrade:D,config:a,module:o})},[e,t,n,r,s,a,o,p,f,w,O,b,D,u])};function ko(e){const t=e.slice(2);if(t.length===128){const a=`0x${t.slice(0,64)}`,o=parseInt(t.charAt(64),16),u=(o>>3)+27,p=`0x${(o&7).toString(16)}${t.slice(65,128)}`;return{r:a,s:p,v:u}}const n=`0x${t.slice(0,64)}`,r=`0x${t.slice(64,128)}`,s=parseInt(t.slice(128,130),16);return{r:n,s:r,v:s}}const _o=()=>{var a;const{account:e,walletInteractions:t,callbacks:n,chainId:r}=q(),s=(a=bn())==null?void 0:a.wToken;return it({mutationFn:async({onHash:o,srcAmountWei:u})=>{var f,w;if(!e)throw new Error("missing account");if(!t)throw new Error("missing walletInteractions");if(!s)throw new Error("tokenAddress is not defined");fe.onWrapRequest();const p=await t.wrapNativeToken(u);return(f=n==null?void 0:n.onWrapRequest)==null||f.call(n),o==null||o(p),fe.onWrapSuccess(p),(w=n==null?void 0:n.onWrapSuccess)==null||w.call(n,{txHash:p,explorerUrl:Lt(p,r),amount:Ee(u,s.decimals)}),p},onError:o=>{throw fe.onWrapError(o),o}})},Ds=()=>{const{account:e,walletInteractions:t,chainId:n,callbacks:r,isDev:s}=q(),a=Fs(),{refetch:o}=mr();return it({mutationFn:async()=>{var B,k,_,S;if(!e)throw new Error("missing account");if(!t)throw new Error("missing walletInteractions");if(!n)throw new Error("missing chainId");const{order:u,domain:p,types:f,primaryType:w}=a;fe.onSignOrderRequest(u);let y;try{y=await t.signOrder({domain:p,types:f,primaryType:w,message:u,account:e})}catch(K){throw(B=r==null?void 0:r.onSignOrderError)==null||B.call(r,K),fe.onSignOrderError(K),K}fe.onSignOrderSuccess(y),(k=r==null?void 0:r.onSignOrderSuccess)==null||k.call(r,y);const b=ko(y),D={v:`0x${b.v.toString(16)}`,r:b.r,s:b.s};(_=r==null?void 0:r.onSignOrderRequest)==null||_.call(r);const O=await $r(u,D,s);return(S=r==null?void 0:r.onOrderCreated)==null||S.call(r,O),await o(),O}})},Ps=()=>{const{account:e,walletInteractions:t,config:n}=q();return it({mutationFn:async({tokenAddress:r,srcAmountWei:s})=>{if(!t)throw new Error("missing walletInteractions");if(!e)throw new Error("missing account");if(!n)throw new Error("missing config");const a=await t.getAllowance({tokenAddress:r,spenderAddress:n.repermit}),o=v(a||"0").lt(v(s).toString());return{allowance:a,approvalRequired:o}}})},Uo=()=>{const{account:e,walletInteractions:t,config:n,chainId:r,callbacks:s}=q(),{mutateAsync:a}=Ps();return it({onError:o=>{fe.onApproveError(o)},mutationFn:async({token:o,onHash:u,srcAmountWei:p})=>{var y,b;if(!e)throw new Error("missing account");if(!t)throw new Error("missing walletInteractions");if(!n)throw new Error("missing config");fe.onApproveRequest();const f=await t.approveToken({tokenAddress:o.address,amount:p,spenderAddress:n.repermit});if(!f)throw new Error("failed to approve token");(y=s==null?void 0:s.onApproveRequest)==null||y.call(s),u(f);let w=!1;for(let D=0;D<3;D++){const{approvalRequired:O}=await a({tokenAddress:o.address,srcAmountWei:p});if(!O){w=!0;break}D<2&&await new Promise(B=>setTimeout(B,3e3))}if(!w)throw new Error(`Insufficient ${o.symbol} allowance to perform the swap. Please approve the token first.`);return fe.onApproveSuccess(f),(b=s==null?void 0:s.onApproveSuccess)==null||b.call(s,{txHash:f,explorerUrl:Lt(f,r),token:o,amount:Ee(p,o.decimals)}),f}})},Ro=()=>{const{account:e,chainId:t,srcToken:n,dstToken:r,module:s,slippage:a}=q(),o=Ct(),u=st().amount,p=Ke().amountPerTrade,f=yr(),w=Ke().totalTrades,y=Nt().fillDelay,b=rr().amount,D=Q(O=>O.state.isMarketOrder);return it({mutationFn:async()=>{fe.onRequestOrder({account:e,chainId:t,module:s,srcToken:n,dstToken:r,fromTokenAmount:u,srcChunkAmount:p,triggerPricePerTrade:o.pricePerChunk,deadline:f,fillDelay:y.unit*y.value,minDstAmountOutPerTrade:b,slippage:a,isMarketOrder:D||!1,chunksAmount:w})}})};function Lo(e){const t=e.message,n=t.match(/,\s*code\s*:\s*(\d+)/i);return{message:t.replace(/^error\s*:/i,"").replace(/,\s*code\s*:\s*\d+/i,"").trim()||"",code:n?Number(n[1]):0}}const Os=()=>{const{srcToken:e,dstToken:t,chainId:n,callbacks:r,marketPrice:s}=q(),a=Uo().mutateAsync,o=_o().mutateAsync,u=Ds().mutateAsync,{mutateAsync:p}=Ps(),{update:f}=rn(),{amount:w}=st(),y=Ro().mutate;return it({mutationFn:async()=>{var D,O;const b=Rt((e==null?void 0:e.address)||" ");try{if(!e)throw new Error("missing srcToken");if(!t)throw new Error("missing dstToken");if(!n)throw new Error("missing chainId");const B=Jr(e,n);f({allowanceLoading:!0,wrapTxHash:void 0,approveTxHash:void 0,acceptedMarketPrice:s,acceptedSrcAmount:w,srcToken:e,dstToken:t,pendingSteps:[]});const{approvalRequired:k}=await p({tokenAddress:B.address,srcAmountWei:w});let _=0,S=1;b&&S++,k&&S++,f({totalSteps:S,stepIndex:_,allowanceLoading:!1,hasApproval:!k,status:Se.LOADING}),y();let K=[];b&&K.push(nt.WRAP),k&&K.push(nt.APPROVE),K.push(nt.CREATE),f({pendingSteps:K}),b&&(f({step:nt.WRAP}),await o({onHash:V=>f({wrapTxHash:V}),srcAmountWei:w}),_++,f({stepIndex:_})),k&&(f({step:nt.APPROVE}),await a({token:B,onHash:V=>f({approveTxHash:V}),srcAmountWei:w}),_++,f({stepIndex:_})),f({step:nt.CREATE});const U=await u();return f({status:Se.SUCCESS,orderId:U.id}),U}catch(B){if(Xn(B))(D=r==null?void 0:r.onSubmitOrderRejected)==null||D.call(r),f({step:void 0,status:void 0,stepIndex:void 0,error:B});else{const k=Lo(B);(O=r==null?void 0:r.onSubmitOrderFailed)==null||O.call(r,k),f({status:Se.FAILED,parsedError:k,error:B})}throw B}}})},No=()=>{const e=rn(),{srcToken:t,dstToken:n}=q(),r=Os(),s=Q(f=>f.resetState),a=F.useCallback(()=>r.mutateAsync(),[r]),{update:o,resetSwap:u,...p}=e;return F.useMemo(()=>({status:p.status,parsedError:p.parsedError,error:p.error,step:p.step,stepIndex:p.stepIndex,approveTxHash:p.approveTxHash,wrapTxHash:p.wrapTxHash,totalSteps:p.totalSteps,pendingSteps:p.pendingSteps,srcToken:t,dstToken:n,onSubmit:a,resetState:s,resetCurrentSwap:u,isLoading:(e==null?void 0:e.status)===Se.LOADING,isSuccess:(e==null?void 0:e.status)===Se.SUCCESS,isFailed:(e==null?void 0:e.status)===Se.FAILED,confirmButtonLoading:p.allowanceLoading}),[a,p,s,u,t,n])},qo=()=>{const{marketPrice:e,srcToken:t,dstToken:n,marketPriceLoading:r,srcBalance:s,srcUsd1Token:a,noLiquidity:o,typedInputAmount:u}=q(),p=r||v(a||"0").isZero()||s===void 0||v(e||"0").isZero(),f=!!(t&&n&&u&&p),y=!!(as()||o||f||v(u||"0").isZero()||!t||!n);return F.useMemo(()=>({disabled:y,loading:f}),[y,f])},Ko=()=>{const{srcUsd1Token:e,dstUsd1Token:t}=q(),n=st().amountUI,r=xn().amountUI,s=qe(n,e),a=qe(r,t);return{srcAmountUsd:s,dstAmountUsd:a}},Ho=()=>{const{fees:e,dstToken:t,dstUsd1Token:n}=q(),{amountUI:r}=xn(),s=F.useMemo(()=>!e||!r?"":v(r).multipliedBy(e).dividedBy(100).toFixed(),[r,e]),a=er((t==null?void 0:t.decimals)||0,s);return{amountUI:s,amount:a,percent:e,usd:qe(s,n)}},Wo=e=>{const t=F.useMemo(()=>!e.minDestAmountPerTrade||!e.totalTrades?"":v(e.minDestAmountPerTrade).multipliedBy(e.totalTrades).decimalPlaces(0).toFixed(),[e.minDestAmountPerTrade,e.totalTrades]),n=F.useMemo(()=>!e.minDestAmountPerTradeUI||!e.totalTrades?"":v(e.minDestAmountPerTradeUI).multipliedBy(e.totalTrades).toFixed(),[e.minDestAmountPerTradeUI,e.totalTrades]),r=F.useMemo(()=>!e.minDestAmountPerTradeUsd||!e.totalTrades?"":v(e.minDestAmountPerTradeUsd).multipliedBy(e.totalTrades).decimalPlaces(2).toFixed(),[e.minDestAmountPerTradeUsd,e.totalTrades]);return F.useMemo(()=>({srcToken:e.srcToken,dstToken:e.dstToken,orderType:e.orderType,createdAt:e.createdAt||0,deadline:e.deadline||0,totalTrades:e.totalTrades||0,tradeInterval:e.tradeInterval||0,recipient:e.account||"",srcAmount:e.srcAmount||"",srcAmountUI:e.srcAmountUI||"",srcAmountUsd:e.srcAmountUsd||"",dstAmount:e.dstAmount||"",dstAmountUI:e.dstAmountUI||"",dstAmountUsd:e.dstAmountUsd||"",limitPrice:e.limitPrice||"",limitPriceUI:e.limitPriceUI||"",limitPriceUsd:e.limitPriceUsd||"",sizePerTrade:e.srcAmountPerTrade||"",sizePerTradeUI:e.srcAmountPerTradeUI||"",sizePerTradeUsd:e.srcAmountPerTradeUsd,minDestAmountPerTrade:e.minDestAmountPerTrade||"",minDestAmountPerTradeUI:e.minDestAmountPerTradeUI||"",minDestAmountPerTradeUsd:e.minDestAmountPerTradeUsd,dstMinAmount:t,dstMinAmountUI:n,dstMinAmountUsd:r,triggerPrice:e.triggerPrice||"",triggerPriceUI:e.triggerPriceUI||"",triggerPriceUsd:e.triggerPriceUsd}),[e.srcToken,e.dstToken,e.orderType,e.createdAt,e.deadline,e.totalTrades,e.tradeInterval,e.account,e.srcAmount,e.srcAmountUI,e.srcAmountUsd,e.dstAmount,e.dstAmountUI,e.dstAmountUsd,e.limitPrice,e.limitPriceUI,e.limitPriceUsd,e.srcAmountPerTrade,e.srcAmountPerTradeUI,e.srcAmountPerTradeUsd,e.minDestAmountPerTrade,e.minDestAmountPerTradeUI,e.minDestAmountPerTradeUsd,t,n,r,e.triggerPrice,e.triggerPriceUI,e.triggerPriceUsd])},Qo=()=>{const{config:e}=q();return F.useMemo(()=>({spender:e.repermit}),[e])},zo=()=>{const{srcToken:e,dstToken:t,account:n,marketPrice:r}=q(),{spender:s}=Qo(),{amount:a}=st(),{amount:o,amountUI:u,usd:p}=wn(),{amountPerTrade:f,amountPerTradeUI:w,amountPerTradeUsd:y,totalTrades:b}=Ke(),D=yr(),{amount:O,amountUI:B,usd:k}=rr(),{amountUI:_,amount:S,usd:K}=Ct(),{milliseconds:U}=Nt(),{amount:V,amountUI:G}=xn(),{srcAmountUsd:oe,dstAmountUsd:i}=Ko(),{amount:c,amountUI:d,percent:E,usd:m}=Ho(),g=Fs(),x=Q(Z=>Z.state.isMarketOrder),h=Q(Z=>Z.state.currentTime),A=rn(),T=vo(),C=A.acceptedSrcAmount||a,P=Ee(r,(t==null?void 0:t.decimals)||0),R=F.useMemo(()=>T===X.TAKE_PROFIT_MARKET||T===X.TAKE_PROFIT_LIMIT||T===X.STOP_LOSS_LIMIT||T===X.STOP_LOSS_MARKET,[T]),L=Wo({srcToken:e,dstToken:t,account:n,orderType:T,createdAt:h,deadline:D,totalTrades:b,tradeInterval:U,srcAmount:C,srcAmountUI:Ee(C,(e==null?void 0:e.decimals)||0),srcAmountUsd:oe,dstAmount:V,dstAmountUI:G,dstAmountUsd:i,limitPrice:x?void 0:o,limitPriceUI:x?void 0:u,limitPriceUsd:x?void 0:p,srcAmountPerTrade:f,srcAmountPerTradeUI:w,srcAmountPerTradeUsd:y,minDestAmountPerTrade:O,minDestAmountPerTradeUI:B,minDestAmountPerTradeUsd:k,triggerPrice:S,triggerPriceUI:_,triggerPriceUsd:K});return F.useMemo(()=>({...L,feesAmountUI:d,feesAmount:c,feesUsd:m||"",feesPercentage:E,rePermitData:g,isTriggerPrice:R,isMarketOrder:x,marketPrice:r,marketPriceUi:P,spender:s}),[L,d,c,m,E,g,R,x,r,P,s])},$o=()=>{const{supportedChains:e}=q();return F.useMemo(()=>e,[e])},jo=60,Is=()=>{const{refetch:e}=mr();return it({mutationFn:async t=>{var n;for(let r=0;r<jo;r++){const s=(n=await e())==null?void 0:n.data;if(!s)throw new Error("orders not found");const a=s.find(o=>o.id===t);if((a==null?void 0:a.status)===ue.Cancelled)return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("Timed out waiting for order cancellation to be confirmed")}})},Vo=()=>{const e=Q(n=>n.updateState),t=Q(n=>n.state.cancelOrders);return{cancelOrders:t,setCancelOrder:(n,r)=>{e({cancelOrders:{...t,[n]:r}})},clearCancelOrder:n=>{const{[n]:r,...s}=t;e({cancelOrders:s})}}},Go=e=>{const{account:t,walletInteractions:n,config:r,callbacks:s,chainId:a}=q(),o=Is().mutateAsync,u=Fo(),{cancelOrders:p,setCancelOrder:f,clearCancelOrder:w}=Vo(),{mutateAsync:y}=it({mutationFn:async()=>{var B,k,_;if(!t||!n||!r)throw new Error("missing required parameters");if(!e)throw new Error("order is required");const O=e.id;try{(B=s==null?void 0:s.onCancelOrderRequest)==null||B.call(s,e),f(O,{status:Se.LOADING}),fe.onCancelOrderRequest([e.version===1?e.id.toString():e.hash],e.version);const S=await n.cancelOrder({order:e,contractAddress:e.version===1?e.twapAddress:r.repermit,args:e.version===1?[e.id]:[[e.repermitDigest]],abi:e.version===1?Gs:Vs});if(!S)throw new Error("failed to cancel order");return fe.onCancelOrderSuccess(S),e.version===1?u(e.id,ue.Cancelled):await o(e.id),(k=s==null?void 0:s.onCancelOrderSuccess)==null||k.call(s,{order:e.version===1?{...e,status:ue.Cancelled}:e,txHash:S,explorerUrl:Lt(S,a)}),f(O,{status:Se.SUCCESS,txHash:S}),S}catch(S){console.error("cancel order error",S),(_=s==null?void 0:s.onCancelOrderFailed)==null||_.call(s,S),Xn(S)?w(O):(f(O,{status:Se.FAILED,error:S.message}),fe.onCancelOrderError(S))}}}),b=F.useMemo(()=>{const O=p[(e==null?void 0:e.id)||""];return{isLoading:(O==null?void 0:O.status)===Se.LOADING,isSuccess:(O==null?void 0:O.status)===Se.SUCCESS,isError:(O==null?void 0:O.status)===Se.FAILED,error:O==null?void 0:O.error,txHash:O==null?void 0:O.txHash}},[p,e==null?void 0:e.id]),D=F.useCallback(async()=>y(),[y]);return F.useMemo(()=>({cancelOrder:D,...b}),[D,b])},Bs=F.createContext(null),Xo=({children:e})=>{const t=Fi(),n=Ii(),r=Pi(),s=Ri(),a=Li(),o=Cn(),u=Ni(),p=qi(),f=as(),w=qo(),y=zo(),b=Mo(),D=No(),O=$o(),B=Is(),{module:k}=q(),_={tradesAmountPanel:t,durationPanel:n,fillDelayPanel:r,limitPricePanel:s,triggerPricePanel:a,pricePanel:o,dstTokenPanel:u,disclaimerPanel:p,inputError:f,submitOrderButton:w,derivedFormData:y,orderHistoryPanel:b,orderExecutionPanel:D,supportedChains:O,refetchUntilStatusSynced:B,module:k};return H.jsx(Bs.Provider,{value:_,children:e})},Zo=()=>{const e=F.useContext(Bs);if(e===null)throw new Error("useSpot must be used within SpotProvider");return e},Yo=F.createContext(null),gr={didCatch:!1,error:null};class Jo extends F.Component{constructor(t){super(t),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=gr}static getDerivedStateFromError(t){return{didCatch:!0,error:t}}resetErrorBoundary(){const{error:t}=this.state;if(t!==null){for(var n,r,s=arguments.length,a=new Array(s),o=0;o<s;o++)a[o]=arguments[o];(n=(r=this.props).onReset)===null||n===void 0||n.call(r,{args:a,reason:"imperative-api"}),this.setState(gr)}}componentDidCatch(t,n){var r,s;(r=(s=this.props).onError)===null||r===void 0||r.call(s,t,n)}componentDidUpdate(t,n){const{didCatch:r}=this.state,{resetKeys:s}=this.props;if(r&&n.error!==null&&ec(t.resetKeys,s)){var a,o;(a=(o=this.props).onReset)===null||a===void 0||a.call(o,{next:s,prev:t.resetKeys,reason:"keys"}),this.setState(gr)}}render(){const{children:t,fallbackRender:n,FallbackComponent:r,fallback:s}=this.props,{didCatch:a,error:o}=this.state;let u=t;if(a){const p={error:o,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")u=n(p);else if(r)u=F.createElement(r,p);else if(s!==void 0)u=s;else throw o}return F.createElement(Yo.Provider,{value:{didCatch:a,error:o,resetErrorBoundary:this.resetErrorBoundary}},u)}}function ec(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return e.length!==t.length||e.some((n,r)=>!Object.is(n,t[r]))}const tc=()=>H.jsx("div",{className:"twap-error-fallback",children:H.jsx("p",{style:{fontSize:20,fontWeight:600,textAlign:"center",width:"100%",marginTop:40},children:"Something went wrong"})});function nc({children:e}){return H.jsx(Jo,{FallbackComponent:tc,onError:t=>fe.onCrash(t),children:H.jsx(H.Fragment,{children:e})})}const Ms=F.createContext(null),rc=new lo({defaultOptions:{queries:{refetchOnWindowFocus:!1}}}),sc=e=>{var r,s,a;const t=Q(o=>o.updateState),n=Q(o=>o.state.isMarketOrder);return F.useEffect(()=>{const o=setInterval(()=>{t({currentTime:Date.now()})},6e4);return()=>clearInterval(o)},[t]),F.useEffect(()=>{var u,p,f,w,y,b,D,O,B,k,_,S,K,U,V,G;const o=(p=(u=e.overrides)==null?void 0:u.state)==null?void 0:p.isMarketOrder;o!==void 0&&t({isMarketOrder:o}),t({typedChunks:(w=(f=e.overrides)==null?void 0:f.state)==null?void 0:w.chunks,typedFillDelay:(b=(y=e.overrides)==null?void 0:y.state)==null?void 0:b.fillDelay,typedDuration:(O=(D=e.overrides)==null?void 0:D.state)==null?void 0:O.duration,typedLimitPrice:(k=(B=e.overrides)==null?void 0:B.state)==null?void 0:k.limitPrice,typedTriggerPrice:(S=(_=e.overrides)==null?void 0:_.state)==null?void 0:S.triggerPrice,triggerPricePercent:(U=(K=e.overrides)==null?void 0:K.state)==null?void 0:U.triggerPricePercent,limitPricePercent:(G=(V=e.overrides)==null?void 0:V.state)==null?void 0:G.limitPricePercent})},[(r=e.overrides)==null?void 0:r.state,e.module]),F.useEffect(()=>{var o,u,p,f;t({typedLimitPrice:(u=(o=e.overrides)==null?void 0:o.state)==null?void 0:u.limitPrice,typedTriggerPrice:(f=(p=e.overrides)==null?void 0:p.state)==null?void 0:f.triggerPrice,triggerPricePercent:void 0,limitPricePercent:void 0})},[(s=e.srcToken)==null?void 0:s.address,(a=e.dstToken)==null?void 0:a.address]),F.useEffect(()=>{e.module===j.LIMIT&&t({isMarketOrder:!1})},[e.module]),F.useEffect(()=>{n&&t({isInvertedTrade:!1})},[n]),F.useEffect(()=>{t({typedChunks:void 0})},[e.typedInputAmount]),null},ac=({marketReferencePrice:e,srcToken:t,dstToken:n,chainId:r,typedInputAmount:s})=>F.useMemo(()=>{if(Yn(t,n,r)||Jn(t,n,r))return{isLoading:!1,noLiquidity:!1,value:rt(s||"0",t==null?void 0:t.decimals)};if(v(e.value||0).isZero()||v(s||0).isZero())return e;const a=v(e.value||0).dividedBy(s||0).decimalPlaces(0).toFixed();return{...e,value:a}},[e,s,t,n,r]),ic=e=>{const t=rn(),n=F.useMemo(()=>Lr(e.partner),[e.partner]);console.log({supportedChains:n});const r=F.useMemo(()=>{const u=n[0];return e.chainId&&n.includes(e.chainId)?e.chainId:u},[e.chainId,n]),s=F.useMemo(()=>Qn(e.partner,r),[e.partner,r]),a=ac(e),o=F.useMemo(()=>Hr(e.minChunkSizeUsd),[e.minChunkSizeUsd]);return F.useEffect(()=>{fe.init(s,o,r)},[s,r,o]),H.jsxs(Ms.Provider,{value:{typedInputAmount:e.typedInputAmount,minChunkSizeUsd:o,account:e.account,walletInteractions:e.walletInteractions,marketPrice:t.acceptedMarketPrice||a.value,marketPriceLoading:!t.acceptedMarketPrice&&a.isLoading,noLiquidity:!t.acceptedMarketPrice&&a.noLiquidity,config:s,slippage:e.priceProtection,supportedChains:n,chainId:r,partner:e.partner,module:e.module,fees:e.fees||0,overrides:e.overrides,callbacks:e.callbacks,srcUsd1Token:e.srcUsd1Token,dstUsd1Token:e.dstUsd1Token,srcBalance:e.srcBalance,dstBalance:e.dstBalance,srcToken:t.srcToken||e.srcToken,dstToken:t.dstToken||e.dstToken,isDev:e.isDev},children:[H.jsx(sc,{...e}),H.jsx(Xo,{children:H.jsx(nc,{children:e.children})})]})},oc=e=>H.jsx(po,{client:rc,children:H.jsx(ic,{...e})}),q=()=>{const e=F.useContext(Ms);if(e===null)throw new Error("useSpotContext must be used within SpotProvider");return e},cc=(e,t,n)=>{const r=bn();return F.useMemo(()=>e==null?void 0:e.map(s=>({rawFill:s,srcToken:t,dstToken:n,srcAmount:Ee(s.inAmount,t==null?void 0:t.decimals),dstAmount:Ee(s.outAmount,n==null?void 0:n.decimals),timestamp:s.timestamp,txHash:s.txHash,explorerUrl:Lt(s.txHash,r==null?void 0:r.id),executionRate:Wn(s.inAmount,s.outAmount,t==null?void 0:t.decimals,n==null?void 0:n.decimals)})).filter(s=>s.srcToken!==void 0&&s.dstToken!==void 0),[e,t,n,r])},uc=(e,t,n)=>{const{config:r}=q(),s=Oo(t,n,e),a=Io(t,n,e),o=Bo(t,n,e),u=F.useMemo(()=>e?e.version===2?e.fillDelay:r.twapConfig?Hn(e,r.twapConfig):0:0,[e,r]),p=cc(e==null?void 0:e.fills,t,n)??[];return F.useMemo(()=>{if(e!=null&&e.id)return{original:e,fills:p,srcToken:t,dstToken:n,orderType:e.type,createdAt:e.createdAt,deadline:e.deadline||0,totalTrades:e.totalTradesAmount||0,tradeInterval:u,recipient:e.maker||"",srcAmount:e.srcAmount||"",srcAmountUI:Ee(e.srcAmount,t==null?void 0:t.decimals),limitPrice:rt(s,n==null?void 0:n.decimals),limitPriceUI:s||"",sizePerTrade:e.srcAmountPerTrade||"",sizePerTradeUI:Ee(e.srcAmountPerTrade,t==null?void 0:t.decimals),minDestAmountPerTrade:e.dstMinAmountPerTrade||"",minDestAmountPerTradeUI:Ee(e.dstMinAmountPerTrade,n==null?void 0:n.decimals),dstMinAmount:e.dstMinAmountTotal,dstMinAmountUI:Ee(e.dstMinAmountTotal,n==null?void 0:n.decimals),triggerPrice:rt(a,n==null?void 0:n.decimals),triggerPriceUI:a||"",id:e.id,amountInFilled:e.srcAmountFilled,amountInFilledUI:Ee(e.srcAmountFilled,t==null?void 0:t.decimals),amountOutFilled:e.dstAmountFilled,amountOutFilledUI:Ee(e.dstAmountFilled,n==null?void 0:n.decimals),progress:e.progress,executionPrice:rt(o,n==null?void 0:n.decimals),executionPriceUI:o,version:e.version}},[e,p,t,n,u,s,a,o])};za(mi.version),I.DISCLAIMER_URL=da,I.Disclaimer=en,I.InputErrors=me,I.Module=j,I.ORBS_LOGO=ca,I.ORBS_SLTP_FAQ_URL=oa,I.ORBS_TWAP_FAQ_URL=ia,I.ORBS_WEBSITE_URL=ua,I.OrderFilter=Pr,I.OrderStatus=ue,I.OrderType=X,I.Partners=_e,I.SPOT_VERSION=fn,I.SpotProvider=oc,I.Steps=nt,I.SwapStatus=Se,I.TimeUnit=De,I.buildRePermitOrderData=Wr,I.ensureWrappedToken=Jr,I.eqIgnoreCase=gt,I.getConfig=Qn,I.getExplorerUrl=Lt,I.getMinChunkSizeUsd=Hr,I.getNetwork=Et,I.getOrderExecutionRate=Wn,I.getOrderFillDelayMillis=Hn,I.getOrderLimitPriceRate=Nr,I.getOrderType=Ci,I.getPartnerChains=Lr,I.getPartners=Kr,I.getTriggerPriceRate=qr,I.isNativeAddress=Rt,I.isTxRejected=Xn,I.millisToDays=Zn,I.millisToMinutes=En,I.networks=ye,I.parseError=bi,I.shouldUnwrapOnly=Jn,I.shouldWrapOnly=Yn,I.submitOrder=$r,I.toAmountUi=Ee,I.toAmountWei=rt,I.useAmountUi=bt,I.useCancelOrder=Go,I.useDerivedHistoryOrder=uc,I.useExplorerLink=Ti,I.useNetwork=bn,I.useSignOrder=Ds,I.useSpot=Zo,I.useSubmitOrder=Os,I.useSwapExecution=rn,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})}));
|
|
64
|
+
`,extractResults:y=>{var b;return(((b=y.data)==null?void 0:b.orderFilleds)||[]).map(D=>({...D,timestamp:new Date(D.timestamp).getTime()}))}})};class di extends Error{constructor(){super("No graph endpoint found"),this.name="NoGraphEndpointError"}}const li=async({chainId:e,signal:t,page:n,limit:r,filters:s})=>{try{const a=await oi({chainId:e,signal:t,page:n,limit:r,filters:s}),[o,u]=await Promise.all([ui({chainId:e,orders:a,signal:t}),ci({chainId:e,orders:a,signal:t})]),p=a.map(w=>{const y=o==null?void 0:o.filter(b=>b.TWAP_id===Number(w.Contract_id)&>(b.exchange,w.exchange)&>(b.twapAddress,w.twapAddress));return ai(w,e,y,pi(w,y||[],u))}).sort((w,y)=>y.createdAt-w.createdAt),f=new Set;return p.filter(w=>f.has(w.id)?!1:(f.add(w.id),!0))}catch{return[]}},pi=(e,t,n)=>{var u;const r=(u=n==null?void 0:n.find(p=>p.twapId===e.Contract_id.toString()&>(p.twapAddress,e.twapAddress)))==null?void 0:u.status,a=jr(t).reduce((p,f)=>p.plus(f.inAmount),new v(0)).toFixed(),o=Gr(e.ask_srcAmount,a);return fi(o,e.ask_deadline*1e3,r)},Gr=(e,t)=>{if(!t||!e)return 0;const n=v(t).dividedBy(e).toNumber();return n>=.99?100:n<=0?0:Number((n*100).toFixed(2))},fi=(e,t,n)=>e===100?ue.Completed:n==="CANCELLED"?ue.Cancelled:n==="COMPLETED"?ue.Completed:t>Date.now()?ue.Open:ue.Expired,hi=async({signal:e,page:t,chainId:n,limit:r,config:s,account:a,isDev:o=!1,includeV1GraphOrders:u=!0})=>(await Promise.all([!s||!u?Promise.resolve([]):li({chainId:n,signal:e,page:t,limit:r,filters:{accounts:[a],configs:s.twapConfig?[s.twapConfig]:[]}}),ri({chainId:n,signal:e,account:a,exchange:s==null?void 0:s.adapter,partner:s==null?void 0:s.partner,isDev:o})]).then(([w,y])=>[...w,...y])).sort((w,y)=>y.createdAt-w.createdAt),mi={version:"1.1.32"},Xr=e=>{let t;const n=new Set,r=(f,w)=>{const y=typeof f=="function"?f(t):f;if(!Object.is(y,t)){const b=t;t=w??(typeof y!="object"||y===null)?y:Object.assign({},t,y),n.forEach(D=>D(t,b))}},s=()=>t,u={setState:r,getState:s,getInitialState:()=>p,subscribe:f=>(n.add(f),()=>n.delete(f))},p=t=e(r,s,u);return u},yi=(e=>e?Xr(e):Xr),gi=e=>e;function Ai(e,t=gi){const n=F.useSyncExternalStore(e.subscribe,F.useCallback(()=>t(e.getState()),[e,t]),F.useCallback(()=>t(e.getInitialState()),[e,t]));return F.useDebugValue(n),n}const Zr=e=>{const t=yi(e),n=r=>Ai(t,r);return Object.assign(n,t),n},Ei=(e=>e?Zr(e):Zr),An={},Yr={currentTime:Date.now(),cancelOrders:{},swapExecutions:[An],swapExecutionIndex:0},Q=Ei((e,t)=>({state:Yr,updateState:n=>e(r=>({state:{...r.state,...n}})),updateSwapExecutionAtIndex:(n,r)=>e(s=>{const a=[...s.state.swapExecutions];return a[n]={...a[n]??An,...r},{state:{...s.state,swapExecutions:a}}}),resetSwapExecutionAtIndex:()=>e(n=>{const r=[...n.state.swapExecutions];return r[n.state.swapExecutionIndex]=An,{state:{...n.state,swapExecutions:r}}}),resetState:()=>{const n=t().state;e({state:{...Yr,currentTime:Date.now(),isMarketOrder:n.isMarketOrder,swapExecutions:[...n.swapExecutions,An],swapExecutionIndex:n.swapExecutionIndex+1}})}}));var Se=(e=>(e[e.LOADING=1]="LOADING",e[e.SUCCESS=2]="SUCCESS",e[e.FAILED=3]="FAILED",e))(Se||{}),en=(e=>(e.TRIGGER_MARKET_PRICE="triggerMarketPriceDisclaimer",e.MARKET_PRICE="marketOrderDisclaimer",e.LIMIT_PRICE="limitOrderDisclaimer",e))(en||{}),nt=(e=>(e.WRAP="wrap",e.APPROVE="approve",e.CREATE="create",e))(nt||{});const rt=(e,t)=>!t||!e||v(e).isNaN()?"":v(e).multipliedBy(v(10).pow(t)).toFixed(0),Ee=(e,t)=>{try{return!t||!e||v(e).isNaN()?"":v(e).dividedBy(v(10).pow(t)).toFixed()}catch(n){return console.error(n),""}},bi=e=>{const t="An error occurred.";if(!e||!e.message)return t;try{return e.message.toLowerCase().includes("rejected")?"Transaction Rejected":t}catch{return t}},Xn=e=>{var t,n,r,s;if(e!=null&&e.message)return((n=(t=e.message)==null?void 0:t.toLowerCase())==null?void 0:n.includes("rejected"))||((s=(r=e.message)==null?void 0:r.toLowerCase())==null?void 0:s.includes("denied"))},Jr=(e,t)=>{const n=Et(t);return n&&Rt(e.address)?n.wToken:e};function Zn(e){return e?e/864e5:0}function En(e){return e?e/6e4:0}const Ci=(e,t)=>e?X.TWAP_MARKET:t===1?X.LIMIT:X.TWAP_LIMIT,Yn=(e,t,n)=>{const r=Et(n);return Rt((e==null?void 0:e.address)||"")&>((t==null?void 0:t.address)||"",(r==null?void 0:r.wToken.address)||"")},Jn=(e,t,n)=>{const r=Et(n);return gt((e==null?void 0:e.address)||"",(r==null?void 0:r.wToken.address)||"")&&Rt((t==null?void 0:t.address)||"")},Lt=(e,t)=>{if(!t)return"";const n=Et(t);return`${n==null?void 0:n.explorer}/tx/${e}`},er=(e,t)=>F.useMemo(()=>rt(t,e),[e,t]),bt=(e,t)=>F.useMemo(()=>Ee(t,e),[e,t]),bn=()=>{const{chainId:e}=q();return F.useMemo(()=>Et(e),[e])},Ti=e=>{const t=bn();return F.useMemo(()=>{if(!(!e||!t))return Lt(e,t.id)},[e,t])},qe=(e,t)=>F.useMemo(()=>!e||!t||v(e||"0").isZero()||v(t||"0").isZero()?"":v(e||"0").times(t).toFixed(),[e,t]),wi=()=>{const{srcToken:e,dstToken:t,chainId:n}=q();return F.useMemo(()=>Yn(e,t,n),[e,t,n])},xi=()=>{const{srcToken:e,dstToken:t,chainId:n}=q();return F.useMemo(()=>Jn(e,t,n),[e,t,n])},Si=()=>{const e=wi(),t=xi();return e||t},st=()=>{const{srcToken:e,typedInputAmount:t}=q();return{amount:er(e==null?void 0:e.decimals,t),amountUI:t,error:v(t||0).isZero()?"enterAmount":void 0}},vi=(e,t)=>{const{module:n,srcUsd1Token:r,marketPrice:s,minChunkSizeUsd:a,typedInputAmount:o}=q();return F.useMemo(()=>{if(v(o||"0").isZero()||!s||v(r||"0").isZero())return;if(!e)return{type:me.MIN_CHUNKS,value:1,args:{minChunks:"1"}};const{isError:u}=qa(e,t,n);if(u)return{type:me.MAX_CHUNKS,value:t,args:{maxChunks:`${t}`}};const{isError:p,value:f}=Na(o||"",r||"",a||0);if(p)return{type:me.MIN_TRADE_SIZE,value:f,args:{minTradeSize:`${f}`}}},[e,t,n,o,r,a,s])},Ke=()=>{const{srcToken:e,srcUsd1Token:t,module:n,minChunkSizeUsd:r}=q(),s=Q(O=>O.state.typedChunks),a=Q(O=>O.updateState),{amount:o,amountUI:u}=st(),p=F.useMemo(()=>Fa(u||"",t||"",r||0),[u,t,r]),f=F.useMemo(()=>va(p,n,s),[p,s,n]),w=F.useCallback(O=>a({typedChunks:O}),[a]),y=F.useMemo(()=>Oa(o||"",f),[o,f]),b=bt(e==null?void 0:e.decimals,y),D=F.useMemo(()=>t?v(b||"0").times(t||0).toString():"0",[b,t]);return{totalTrades:f,maxTrades:p,amountPerTradeUI:b,amountPerTrade:y,amountPerTradeUsd:D,onChange:w,error:vi(f,p)}},Fi=()=>{const{srcToken:e,dstToken:t}=q(),{onChange:n,totalTrades:r,amountPerTradeUsd:s,amountPerTradeUI:a,error:o,maxTrades:u,amountPerTrade:p}=Ke();return{error:o,maxTrades:u,totalTrades:r,amountPerTradeUI:a,amountPerTrade:p,onChange:n,amountPerTradeUsd:s,fromToken:e,toToken:t}},es=e=>{const t=Zn(e);if(t>=1)return`${t.toFixed(t%1?1:0)} ${t===1?"day":"days"}`;const n=En(e)/60;if(n>=1)return`${n.toFixed(n%1?1:0)} ${n===1?"hour":"hours"}`;const r=En(e);return`${r.toFixed(r%1?1:0)} ${r===1?"minute":"minutes"}`},Di=e=>{const{totalTrades:t}=Ke(),{marketPrice:n,typedInputAmount:r}=q(),s=F.useMemo(()=>{const{isError:o,value:u}=La(e);if(!(!o||v(r||"0").isZero()||!n))return{type:me.MIN_FILL_DELAY,value:u,args:{fillDelay:es(u)}}},[e,r,n]),a=F.useMemo(()=>{const{isError:o,value:u}=Ia(e,t);if(!(!o||v(r||"0").isZero()||!n))return{type:me.MAX_FILL_DELAY,value:u,args:{fillDelay:es(u)}}},[e,r,n,t]);return s||a},Nt=()=>{const{callbacks:e}=q(),t=Q(a=>a.state.typedFillDelay),n=Q(a=>a.updateState),r=F.useMemo(()=>t||Rn,[t]),s=Di(r);return{fillDelay:r,onChange:F.useCallback(a=>{var o;n({typedFillDelay:a}),(o=e==null?void 0:e.onFillDelayChange)==null||o.call(e,a)},[n,e]),error:s,milliseconds:r.unit*r.value}},Pi=()=>{const{onChange:e,fillDelay:t,error:n}=Nt(),r=F.useCallback(a=>e({unit:t.unit,value:Number(a)}),[e,t]),s=F.useCallback(a=>e({unit:a,value:t.value}),[e,t]);return{onInputChange:r,onUnitSelect:s,onChange:e,milliseconds:t.unit*t.value,fillDelay:t,error:n}},Oi=e=>{const{module:t,marketPrice:n}=q();return F.useMemo(()=>{const r=Ua(t,e),s=Ra(e);if(n){if(r.isError)return{type:me.MAX_ORDER_DURATION,value:r.value,args:{duration:`${Math.floor(Zn(r.value)).toFixed(0)} days`}};if(s.isError)return{type:me.MIN_ORDER_DURATION,value:s.value,args:{duration:`${Math.floor(En(s.value)).toFixed(0)} minutes`}}}},[e,t,n])},tr=()=>{const{module:e,callbacks:t}=q(),n=Q(p=>p.state.typedDuration),r=Q(p=>p.updateState),s=Ke().totalTrades,a=Nt().fillDelay,o=F.useMemo(()=>Sa(e,s,a,n),[s,a,n,e]),u=Oi(o);return{duration:o,setDuration:F.useCallback(p=>{var f;r({typedDuration:p}),(f=t==null?void 0:t.onDurationChange)==null||f.call(t,p)},[r,t]),error:u}},Ii=()=>{const{duration:e,setDuration:t,error:n}=tr(),r=F.useCallback(a=>{t({unit:e.unit,value:Number(a)})},[t,e]),s=F.useCallback(a=>{t({unit:a,value:e.value})},[t,e]);return{duration:e,onChange:t,milliseconds:e.unit*e.value,onInputChange:r,onUnitSelect:s,error:n}},Bi=()=>{const{module:e}=q();return F.useMemo(()=>e===j.STOP_LOSS?la:pa,[e])},nr=()=>{const{module:e}=q(),t=Q(n=>n.state.isMarketOrder);return F.useMemo(()=>e!==j.STOP_LOSS&&e!==j.TAKE_PROFIT||t?void 0:e===j.STOP_LOSS?fa:ha,[e,t])},ts=e=>{if(e===void 0||e==="")return e;const t=v(e);return t.isNaN()||t.isZero()?"0":v(1).div(t).toFixed()},Cn=()=>{const{srcToken:e,dstToken:t}=q(),n=Q(p=>p.updateState),r=Q(p=>p.state.isInvertedTrade),s=Q(p=>p.state.typedTriggerPrice),a=Q(p=>p.state.typedLimitPrice),o=Q(p=>p.state.isMarketOrder);return{onInvert:F.useCallback(()=>{n({isInvertedTrade:!r,...s!==void 0?{typedTriggerPrice:ts(s)}:{},...a!==void 0?{typedLimitPrice:ts(a)}:{}})},[n,r,s,a]),isInverted:r,fromToken:r?t:e,toToken:r?e:t,isMarketPrice:o}},Tn=e=>e?v(e).isNaN()?"":e:"",ns=({amount:e,typedValue:t,amountDecimals:n=18,invertedAmountDecimals:r=18,amountUsd:s,invertedAmountUsd:a,isInverted:o})=>{const u=F.useMemo(()=>{if(t!==void 0)return Tn(t);const w=Ee(e,n);return!w||v(w||"0").isZero()?"":o?v(1).div(w).toFixed():w},[e,n,o,t]),p=F.useMemo(()=>u?Tn(o?rt(u,r):e):"",[e,u,r,o]),f=qe(u||"0",o?a:s);return{amount:p,amountUI:u,usd:Tn(f)}},rs=({typedValue:e,tokenDecimals:t=18,initialPrice:n="0",percentage:r,setValue:s,setPercentage:a})=>{const{isInverted:o}=Cn(),u=F.useMemo(()=>v((()=>{if(e!==void 0){const b=o?v(e).isZero()?v(0):v(1).div(e):v(e);return rt(b.toFixed(),t)}if(r!==void 0&&v(n||"0").gt(0)&&!v(n||"0").isNaN()){const b=v(n||"0"),D=v(r||0).div(100);return b.plus(b.multipliedBy(D)).decimalPlaces(0).toFixed()}return v(n).gt(0)?n:""})()).decimalPlaces(0).toFixed(),[e,r,t,n,o]),p=F.useCallback(y=>{s(y),a(null)},[s,a]),f=F.useCallback(y=>{s(void 0),a(y)},[s,a]),w=F.useMemo(()=>{if(!n||v(n).isZero())return"";if(r!=null)return r;if(u){const y=v(n),D=v(u).minus(y).div(y).multipliedBy(100).decimalPlaces(2).toString();return v(D||"0").isZero()?"":D}return""},[u,n,r]);return{amount:v(u).isNaN()?"":u,typedValue:e,selectedPercentage:w,onChange:p,onPercentageChange:f,isTypedValue:e!==void 0}},Mi=(e="")=>{const{module:t,marketPrice:n,typedInputAmount:r}=q();return F.useMemo(()=>{if(v(r||"0").isZero()||!n||t!==j.STOP_LOSS&&t!==j.TAKE_PROFIT)return;const s=Ba(n||"",e||"",t);if(s!=null&&s.isError)return{type:me.STOP_LOSS_TRIGGER_PRICE_GREATER_THAN_MARKET_PRICE,value:s.value};const a=Ma(n||"",e||"",t);if(a!=null&&a.isError)return{type:me.TAKE_PROFIT_TRIGGER_PRICE_LESS_THAN_MARKET_PRICE,value:a.value};if(!e||v(e||0).isZero())return{type:me.EMPTY_TRIGGER_PRICE,value:e}},[n,e,t,r])},ki=e=>{const{srcToken:t,dstToken:n,module:r,dstUsd1Token:s}=q(),a=Ke().amountPerTrade,o=Q(f=>f.state.isMarketOrder),u=F.useMemo(()=>xa(r,a,e,(t==null?void 0:t.decimals)||0),[e,a,o,t==null?void 0:t.decimals,r]),p=bt((n==null?void 0:n.decimals)||0,u);return{amount:u,amountUI:p,usd:qe(p,s)}},Ct=()=>{const{dstToken:e,dstUsd1Token:t,marketPrice:n,module:r,callbacks:s}=q(),a=Q(_=>_.updateState),o=Bi(),u=Q(_=>_.state.triggerPricePercent),p=u===void 0?o:u,f=r===j.STOP_LOSS||r===j.TAKE_PROFIT,w=rs({typedValue:Q(_=>_.state.typedTriggerPrice),percentage:p,tokenDecimals:(e==null?void 0:e.decimals)||18,initialPrice:f?n:void 0,setValue:F.useCallback(_=>{var S;a({typedTriggerPrice:_}),(S=s==null?void 0:s.onTriggerPriceChange)==null||S.call(s,_||"")},[a,s]),setPercentage:F.useCallback(_=>{var S;a({triggerPricePercent:_}),(S=s==null?void 0:s.onTriggerPricePercentChange)==null||S.call(s,_||"")},[a,s])}),y=Mi(w.amount),b=bt((e==null?void 0:e.decimals)||18,w.amount),D=qe(b,t),{amount:O,amountUI:B,usd:k}=ki(w.amount);return F.useMemo(()=>({...w,amountUI:v(b).isNaN()?"":b,usd:v(D).isNaN()?"":D,error:y,pricePerChunk:O,pricePerChunkUI:B,pricePerChunkUsd:k}),[w,b,D,y,O,B,k])},_i=e=>{const{module:t,marketPrice:n,typedInputAmount:r}=q(),{amount:s}=Ct(),a=Q(o=>o.state.isMarketOrder);return F.useMemo(()=>{if(v(r||"0").isZero()||!s||!n)return;const o=ka(s,e,a,t),u=_a(s,e,a,t);if(o!=null&&o.isError)return{type:me.TRIGGER_LIMIT_PRICE_GREATER_THAN_TRIGGER_PRICE,value:o.value};if(u!=null&&u.isError)return{type:me.TRIGGER_LIMIT_PRICE_GREATER_THAN_TRIGGER_PRICE,value:u.value};if(e&&v(e||0).isZero())return{type:me.MISSING_LIMIT_PRICE,value:e||""}},[e,s,t,a,r,n])},wn=()=>{const{dstToken:e,dstUsd1Token:t,marketPrice:n,callbacks:r}=q(),s=Q(b=>b.updateState),a=nr(),o=Q(b=>b.state.limitPricePercent),u=o===void 0?a:o,p=rs({typedValue:Q(b=>b.state.typedLimitPrice),percentage:u,tokenDecimals:(e==null?void 0:e.decimals)||18,initialPrice:n,setValue:F.useCallback(b=>{var D;s({typedLimitPrice:b}),(D=r==null?void 0:r.onLimitPriceChange)==null||D.call(r,b||"")},[s,r]),setPercentage:F.useCallback(b=>{var D;s({limitPricePercent:b}),(D=r==null?void 0:r.onLimitPricePercentChange)==null||D.call(r,b||"")},[s,r])}),f=_i(p.amount),w=bt((e==null?void 0:e.decimals)||18,p.amount),y=qe(w,t);return F.useMemo(()=>({...p,amountUI:v(w).isNaN()?"":w,usd:v(y).isNaN()?"":y,error:f}),[p,w,y,f])},Ui=()=>{const{module:e}=q(),t=Q(u=>u.updateState),n=Q(u=>u.state.isMarketOrder),r=nr(),s=Q(u=>u.state.triggerPricePercent)||0,a=e===j.LIMIT,o=F.useCallback(()=>{!n&&e===j.STOP_LOSS&&t({limitPricePercent:r}),t({isMarketOrder:!n})},[t,s,e,n,r]);return{isLimitPrice:!n,toggleLimitPrice:o,hide:a}},Ri=()=>{const{module:e,marketPriceLoading:t,srcToken:n,dstToken:r,srcUsd1Token:s,dstUsd1Token:a}=q(),{amount:o,typedValue:u,onChange:p,onPercentageChange:f,selectedPercentage:w,error:y,isTypedValue:b}=wn(),D=Q(G=>G.updateState),O=nr(),{isLimitPrice:B,toggleLimitPrice:k}=Ui(),{fromToken:_,toToken:S,isInverted:K}=Cn(),U=ns({amount:o,typedValue:u,amountDecimals:(r==null?void 0:r.decimals)||18,invertedAmountDecimals:(n==null?void 0:n.decimals)||18,amountUsd:a,invertedAmountUsd:s,isInverted:K}),V=F.useCallback(()=>{D({typedLimitPrice:void 0}),D({limitPricePercent:O})},[D,e,O]);return{price:U.amount,priceUI:U.amountUI,error:y,onInputChange:p,onPercentageChange:f,onReset:V,usd:U.usd,srcToken:n,dstToken:r,invertedSrcToken:_,invertedDstToken:S,percentage:w,isLoading:t,isLimitPrice:B,toggleLimitPrice:k,isTypedValue:b}},Li=()=>{const{marketPrice:e,marketPriceLoading:t,srcToken:n,dstToken:r,srcUsd1Token:s,dstUsd1Token:a}=q(),{amount:o,typedValue:u,onChange:p,onPercentageChange:f,selectedPercentage:w,error:y,pricePerChunk:b,pricePerChunkUI:D,pricePerChunkUsd:O,isTypedValue:B}=Ct(),k=Q(G=>G.updateState),{fromToken:_,toToken:S,isInverted:K}=Cn(),U=ns({amount:o,typedValue:u,amountDecimals:(r==null?void 0:r.decimals)||18,invertedAmountDecimals:(n==null?void 0:n.decimals)||18,amountUsd:a,invertedAmountUsd:s,isInverted:K}),V=F.useCallback(()=>{k({triggerPricePercent:void 0,typedTriggerPrice:void 0})},[k]);return{price:U.amount,priceUI:U.amountUI,amountPerChunk:b,amountPerChunkUI:D,amountPerChunkUsd:O,error:y,onInputChange:p,onPercentageChange:f,percentage:w,onReset:V,usd:U.usd,srcToken:n,dstToken:r,invertedSrcToken:_,invertedDstToken:S,isLoading:t||!e,isTypedValue:B}},ss=()=>{const{module:e,marketPrice:t}=q(),n=wn().amount,r=Ct().amount,s=Q(a=>a.state.isMarketOrder);return e===j.LIMIT||!s?n||"":e===j.STOP_LOSS||e===j.TAKE_PROFIT?r||"":t||""},xn=()=>{const{srcToken:e,dstToken:t,dstUsd1Token:n}=q(),r=ss(),s=st().amount,a=F.useMemo(()=>Ta(s||"",r,(e==null?void 0:e.decimals)||0),[s,r,e==null?void 0:e.decimals]),o=bt(t==null?void 0:t.decimals,a);return{amount:a,amountUI:o,usd:qe(o,n)}},rr=()=>{const{srcToken:e,dstToken:t,dstUsd1Token:n}=q(),r=ss(),s=Ke().amountPerTrade,a=Q(p=>p.state.isMarketOrder),o=F.useMemo(()=>wa(s,r,!!a,(e==null?void 0:e.decimals)||0),[s,r,a,e==null?void 0:e.decimals]),u=bt(t==null?void 0:t.decimals,o);return{amount:o,amountUI:u,usd:qe(u,n)}},Ni=()=>{const{typedInputAmount:e,marketPriceLoading:t,dstToken:n}=q(),{amountUI:r,usd:s}=xn(),o=Si()?e:r,u=er(n==null?void 0:n.decimals,o);return{value:o,valueWei:u,isLoading:t,usd:s}},qi=()=>{const e=Q(s=>s.state.isMarketOrder),{module:t}=q(),n=F.useMemo(()=>{if(e&&t===j.STOP_LOSS)return en.TRIGGER_MARKET_PRICE},[e,t]),r=F.useMemo(()=>{if(!(t!==j.LIMIT&&t!==j.TWAP))return e?en.MARKET_PRICE:en.LIMIT_PRICE},[e,t]);return n||r},Ki=()=>{const{minChunkSizeUsd:e,typedInputAmount:t,srcUsd1Token:n}=q(),r=qe(t,n);return F.useMemo(()=>v(e).gt(v(r||"0"))?{type:me.MIN_TRADE_SIZE_ERROR,value:e}:void 0,[e,r])};function as(){const{marketPrice:e,marketPriceLoading:t,typedInputAmount:n,srcUsd1Token:r,srcBalance:s,chainId:a}=q(),{error:o}=Ct(),{error:u}=wn(),{error:p}=Ke(),{error:f}=Nt(),{error:w}=tr(),y=Ki(),b=st().amount,D=F.useMemo(()=>{if(s&&v(b).gt(s))return{type:me.INSUFFICIENT_BALANCE,value:s||""}},[s,b,a]);return F.useMemo(()=>Ha({marketPrice:e,typedInputAmount:n,srcUsd1Token:r,marketPriceLoading:t,triggerPriceError:o,limitPriceError:u,tradesError:p,fillDelayError:f,durationError:w,balanceError:D,minTradeSizeError:y}),[e,t,n,o,u,p,f,w,D,r,y])}var qt=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Hi={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Wi=(ks=class{constructor(){N(this,He,Hi);N(this,St,!1)}setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&l(this,St)&&e!==l(this,He)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:l(this,He),provider:e}),M(this,He,e),process.env.NODE_ENV!=="production"&&M(this,St,!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&M(this,St,!0),l(this,He).setTimeout(e,t)}clearTimeout(e){l(this,He).clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&M(this,St,!0),l(this,He).setInterval(e,t)}clearInterval(e){l(this,He).clearInterval(e)}},He=new WeakMap,St=new WeakMap,ks),Tt=new Wi;function Qi(e){setTimeout(e,0)}var wt=typeof window>"u"||"Deno"in globalThis;function be(){}function zi(e,t){return typeof e=="function"?e(t):e}function sr(e){return typeof e=="number"&&e>=0&&e!==1/0}function is(e,t){return Math.max(e+(t||0)-Date.now(),0)}function at(e,t){return typeof e=="function"?e(t):e}function Be(e,t){return typeof e=="function"?e(t):e}function os(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:a,queryKey:o,stale:u}=e;if(o){if(r){if(t.queryHash!==ar(o,t.options))return!1}else if(!tn(t.queryKey,o))return!1}if(n!=="all"){const p=t.isActive();if(n==="active"&&!p||n==="inactive"&&p)return!1}return!(typeof u=="boolean"&&t.isStale()!==u||s&&s!==t.state.fetchStatus||a&&!a(t))}function cs(e,t){const{exact:n,status:r,predicate:s,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(xt(t.options.mutationKey)!==xt(a))return!1}else if(!tn(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function ar(e,t){return((t==null?void 0:t.queryKeyHashFn)||xt)(e)}function xt(e){return JSON.stringify(e,(t,n)=>or(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function tn(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>tn(e[n],t[n])):!1}var $i=Object.prototype.hasOwnProperty;function ir(e,t){if(e===t)return e;const n=us(e)&&us(t);if(!n&&!(or(e)&&or(t)))return t;const s=(n?e:Object.keys(e)).length,a=n?t:Object.keys(t),o=a.length,u=n?new Array(o):{};let p=0;for(let f=0;f<o;f++){const w=n?f:a[f],y=e[w],b=t[w];if(y===b){u[w]=y,(n?f<s:$i.call(e,w))&&p++;continue}if(y===null||b===null||typeof y!="object"||typeof b!="object"){u[w]=b;continue}const D=ir(y,b);u[w]=D,D===y&&p++}return s===o&&p===s?e:u}function Sn(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function us(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function or(e){if(!ds(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!ds(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ds(e){return Object.prototype.toString.call(e)==="[object Object]"}function ji(e){return new Promise(t=>{Tt.setTimeout(t,e)})}function cr(e,t,n){if(typeof n.structuralSharing=="function")return n.structuralSharing(e,t);if(n.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return ir(e,t)}catch(r){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${n.queryHash}]: ${r}`),r}return ir(e,t)}return t}function Vi(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Gi(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var vn=Symbol();function ls(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===vn&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===vn?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ps(e,t){return typeof e=="function"?e(...t):!!e}var Xi=(_s=class extends qt{constructor(){super();N(this,vt);N(this,ot);N(this,Kt);M(this,Kt,t=>{if(!wt&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,ot)||this.setEventListener(l(this,Kt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ot))==null||t.call(this),M(this,ot,void 0))}setEventListener(t){var n;M(this,Kt,t),(n=l(this,ot))==null||n.call(this),M(this,ot,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,vt)!==t&&(M(this,vt,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof l(this,vt)=="boolean"?l(this,vt):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},vt=new WeakMap,ot=new WeakMap,Kt=new WeakMap,_s),ur=new Xi;function dr(){let e,t;const n=new Promise((s,a)=>{e=s,t=a});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var Zi=Qi;function Yi(){let e=[],t=0,n=u=>{u()},r=u=>{u()},s=Zi;const a=u=>{t?e.push(u):s(()=>{n(u)})},o=()=>{const u=e;e=[],u.length&&s(()=>{r(()=>{u.forEach(p=>{n(p)})})})};return{batch:u=>{let p;t++;try{p=u()}finally{t--,t||o()}return p},batchCalls:u=>(...p)=>{a(()=>{u(...p)})},schedule:a,setNotifyFunction:u=>{n=u},setBatchNotifyFunction:u=>{r=u},setScheduler:u=>{s=u}}}var de=Yi(),Ji=(Us=class extends qt{constructor(){super();N(this,Ht,!0);N(this,ct);N(this,Wt);M(this,Wt,t=>{if(!wt&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){l(this,ct)||this.setEventListener(l(this,Wt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ct))==null||t.call(this),M(this,ct,void 0))}setEventListener(t){var n;M(this,Wt,t),(n=l(this,ct))==null||n.call(this),M(this,ct,t(this.setOnline.bind(this)))}setOnline(t){l(this,Ht)!==t&&(M(this,Ht,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,Ht)}},Ht=new WeakMap,ct=new WeakMap,Wt=new WeakMap,Us),Fn=new Ji;function eo(e){return Math.min(1e3*2**e,3e4)}function fs(e){return(e??"online")==="online"?Fn.isOnline():!0}var lr=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function hs(e){let t=!1,n=0,r;const s=dr(),a=()=>s.status!=="pending",o=B=>{var k;if(!a()){const _=new lr(B);b(_),(k=e.onCancel)==null||k.call(e,_)}},u=()=>{t=!0},p=()=>{t=!1},f=()=>ur.isFocused()&&(e.networkMode==="always"||Fn.isOnline())&&e.canRun(),w=()=>fs(e.networkMode)&&e.canRun(),y=B=>{a()||(r==null||r(),s.resolve(B))},b=B=>{a()||(r==null||r(),s.reject(B))},D=()=>new Promise(B=>{var k;r=_=>{(a()||f())&&B(_)},(k=e.onPause)==null||k.call(e)}).then(()=>{var B;r=void 0,a()||(B=e.onContinue)==null||B.call(e)}),O=()=>{if(a())return;let B;const k=n===0?e.initialPromise:void 0;try{B=k??e.fn()}catch(_){B=Promise.reject(_)}Promise.resolve(B).then(y).catch(_=>{var G;if(a())return;const S=e.retry??(wt?0:3),K=e.retryDelay??eo,U=typeof K=="function"?K(n,_):K,V=S===!0||typeof S=="number"&&n<S||typeof S=="function"&&S(n,_);if(t||!V){b(_);return}n++,(G=e.onFail)==null||G.call(e,n,_),ji(U).then(()=>f()?void 0:D()).then(()=>{t?b(_):O()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r==null||r(),s),cancelRetry:u,continueRetry:p,canStart:w,start:()=>(w()?O():D().then(O),s)}}var ms=(Rs=class{constructor(){N(this,Ft)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),sr(this.gcTime)&&M(this,Ft,Tt.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(wt?1/0:300*1e3))}clearGcTimeout(){l(this,Ft)&&(Tt.clearTimeout(l(this,Ft)),M(this,Ft,void 0))}},Ft=new WeakMap,Rs),to=(Ls=class extends ms{constructor(t){super();N(this,Le);N(this,Dt);N(this,Qt);N(this,Me);N(this,Pt);N(this,he);N(this,sn);N(this,Ot);M(this,Ot,!1),M(this,sn,t.defaultOptions),this.setOptions(t.options),this.observers=[],M(this,Pt,t.client),M(this,Me,l(this,Pt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,M(this,Dt,As(this.options)),this.state=t.state??l(this,Dt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=l(this,he))==null?void 0:t.promise}setOptions(t){if(this.options={...l(this,sn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=As(this.options);n.data!==void 0&&(this.setState(gs(n.data,n.dataUpdatedAt)),M(this,Dt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Me).remove(this)}setData(t,n){const r=cr(this.state.data,t,this.options);return z(this,Le,et).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){z(this,Le,et).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,s;const n=(r=l(this,he))==null?void 0:r.promise;return(s=l(this,he))==null||s.cancel(t),n?n.then(be).catch(be):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(l(this,Dt))}isActive(){return this.observers.some(t=>Be(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===vn||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>at(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!is(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=l(this,he))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=l(this,he))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,Me).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(l(this,he)&&(l(this,Ot)?l(this,he).cancel({revert:!0}):l(this,he).cancelRetry()),this.scheduleGc()),l(this,Me).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||z(this,Le,et).call(this,{type:"invalidate"})}async fetch(t,n){var p,f,w,y,b,D,O,B,k,_,S,K;if(this.state.fetchStatus!=="idle"&&((p=l(this,he))==null?void 0:p.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(l(this,he))return l(this,he).continueRetry(),l(this,he).promise}if(t&&this.setOptions(t),!this.options.queryFn){const U=this.observers.find(V=>V.options.queryFn);U&&this.setOptions(U.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const r=new AbortController,s=U=>{Object.defineProperty(U,"signal",{enumerable:!0,get:()=>(M(this,Ot,!0),r.signal)})},a=()=>{const U=ls(this.options,n),G=(()=>{const oe={client:l(this,Pt),queryKey:this.queryKey,meta:this.meta};return s(oe),oe})();return M(this,Ot,!1),this.options.persister?this.options.persister(U,G,this):U(G)},u=(()=>{const U={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:l(this,Pt),state:this.state,fetchFn:a};return s(U),U})();(f=this.options.behavior)==null||f.onFetch(u,this),M(this,Qt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((w=u.fetchOptions)==null?void 0:w.meta))&&z(this,Le,et).call(this,{type:"fetch",meta:(y=u.fetchOptions)==null?void 0:y.meta}),M(this,he,hs({initialPromise:n==null?void 0:n.initialPromise,fn:u.fetchFn,onCancel:U=>{U instanceof lr&&U.revert&&this.setState({...l(this,Qt),fetchStatus:"idle"}),r.abort()},onFail:(U,V)=>{z(this,Le,et).call(this,{type:"failed",failureCount:U,error:V})},onPause:()=>{z(this,Le,et).call(this,{type:"pause"})},onContinue:()=>{z(this,Le,et).call(this,{type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0}));try{const U=await l(this,he).start();if(U===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(U),(D=(b=l(this,Me).config).onSuccess)==null||D.call(b,U,this),(B=(O=l(this,Me).config).onSettled)==null||B.call(O,U,this.state.error,this),U}catch(U){if(U instanceof lr){if(U.silent)return l(this,he).promise;if(U.revert){if(this.state.data===void 0)throw U;return this.state.data}}throw z(this,Le,et).call(this,{type:"error",error:U}),(_=(k=l(this,Me).config).onError)==null||_.call(k,U,this),(K=(S=l(this,Me).config).onSettled)==null||K.call(S,this.state.data,U,this),U}finally{this.scheduleGc()}}},Dt=new WeakMap,Qt=new WeakMap,Me=new WeakMap,Pt=new WeakMap,he=new WeakMap,sn=new WeakMap,Ot=new WeakMap,Le=new WeakSet,et=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...ys(r.data,this.options),fetchMeta:t.meta??null};case"success":const s={...r,...gs(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return M(this,Qt,t.manual?s:void 0),s;case"error":const a=t.error;return{...r,error:a,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),de.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),l(this,Me).notify({query:this,type:"updated",action:t})})},Ls);function ys(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:fs(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function gs(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function As(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var no=(Ns=class extends qt{constructor(t,n){super();N(this,ee);N(this,ve);N(this,Y);N(this,an);N(this,Ce);N(this,It);N(this,zt);N(this,Ge);N(this,ut);N(this,on);N(this,$t);N(this,jt);N(this,Bt);N(this,Mt);N(this,dt);N(this,Vt,new Set);this.options=n,M(this,ve,t),M(this,ut,null),M(this,Ge,dr()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,Y).addObserver(this),Es(l(this,Y),this.options)?z(this,ee,ln).call(this):this.updateResult(),z(this,ee,xr).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return pr(l(this,Y),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return pr(l(this,Y),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,z(this,ee,Sr).call(this),z(this,ee,vr).call(this),l(this,Y).removeObserver(this)}setOptions(t){const n=this.options,r=l(this,Y);if(this.options=l(this,ve).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Be(this.options.enabled,l(this,Y))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");z(this,ee,Fr).call(this),l(this,Y).setOptions(this.options),n._defaulted&&!Sn(this.options,n)&&l(this,ve).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,Y),observer:this});const s=this.hasListeners();s&&bs(l(this,Y),r,this.options,n)&&z(this,ee,ln).call(this),this.updateResult(),s&&(l(this,Y)!==r||Be(this.options.enabled,l(this,Y))!==Be(n.enabled,l(this,Y))||at(this.options.staleTime,l(this,Y))!==at(n.staleTime,l(this,Y)))&&z(this,ee,Cr).call(this);const a=z(this,ee,Tr).call(this);s&&(l(this,Y)!==r||Be(this.options.enabled,l(this,Y))!==Be(n.enabled,l(this,Y))||a!==l(this,dt))&&z(this,ee,wr).call(this,a)}getOptimisticResult(t){const n=l(this,ve).getQueryCache().build(l(this,ve),t),r=this.createResult(n,t);return so(this,r)&&(M(this,Ce,r),M(this,zt,this.options),M(this,It,l(this,Y).state)),r}getCurrentResult(){return l(this,Ce)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n==null||n(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&l(this,Ge).status==="pending"&&l(this,Ge).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,Vt).add(t)}getCurrentQuery(){return l(this,Y)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=l(this,ve).defaultQueryOptions(t),r=l(this,ve).getQueryCache().build(l(this,ve),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return z(this,ee,ln).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,Ce)))}createResult(t,n){var c;const r=l(this,Y),s=this.options,a=l(this,Ce),o=l(this,It),u=l(this,zt),f=t!==r?t.state:l(this,an),{state:w}=t;let y={...w},b=!1,D;if(n._optimisticResults){const d=this.hasListeners(),E=!d&&Es(t,n),m=d&&bs(t,r,n,s);(E||m)&&(y={...y,...ys(w.data,t.options)}),n._optimisticResults==="isRestoring"&&(y.fetchStatus="idle")}let{error:O,errorUpdatedAt:B,status:k}=y;D=y.data;let _=!1;if(n.placeholderData!==void 0&&D===void 0&&k==="pending"){let d;a!=null&&a.isPlaceholderData&&n.placeholderData===(u==null?void 0:u.placeholderData)?(d=a.data,_=!0):d=typeof n.placeholderData=="function"?n.placeholderData((c=l(this,jt))==null?void 0:c.state.data,l(this,jt)):n.placeholderData,d!==void 0&&(k="success",D=cr(a==null?void 0:a.data,d,n),b=!0)}if(n.select&&D!==void 0&&!_)if(a&&D===(o==null?void 0:o.data)&&n.select===l(this,on))D=l(this,$t);else try{M(this,on,n.select),D=n.select(D),D=cr(a==null?void 0:a.data,D,n),M(this,$t,D),M(this,ut,null)}catch(d){M(this,ut,d)}l(this,ut)&&(O=l(this,ut),D=l(this,$t),B=Date.now(),k="error");const S=y.fetchStatus==="fetching",K=k==="pending",U=k==="error",V=K&&S,G=D!==void 0,i={status:k,fetchStatus:y.fetchStatus,isPending:K,isSuccess:k==="success",isError:U,isInitialLoading:V,isLoading:V,data:D,dataUpdatedAt:y.dataUpdatedAt,error:O,errorUpdatedAt:B,failureCount:y.fetchFailureCount,failureReason:y.fetchFailureReason,errorUpdateCount:y.errorUpdateCount,isFetched:y.dataUpdateCount>0||y.errorUpdateCount>0,isFetchedAfterMount:y.dataUpdateCount>f.dataUpdateCount||y.errorUpdateCount>f.errorUpdateCount,isFetching:S,isRefetching:S&&!K,isLoadingError:U&&!G,isPaused:y.fetchStatus==="paused",isPlaceholderData:b,isRefetchError:U&&G,isStale:fr(t,n),refetch:this.refetch,promise:l(this,Ge),isEnabled:Be(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const d=g=>{i.status==="error"?g.reject(i.error):i.data!==void 0&&g.resolve(i.data)},E=()=>{const g=M(this,Ge,i.promise=dr());d(g)},m=l(this,Ge);switch(m.status){case"pending":t.queryHash===r.queryHash&&d(m);break;case"fulfilled":(i.status==="error"||i.data!==m.value)&&E();break;case"rejected":(i.status!=="error"||i.error!==m.reason)&&E();break}}return i}updateResult(){const t=l(this,Ce),n=this.createResult(l(this,Y),this.options);if(M(this,It,l(this,Y).state),M(this,zt,this.options),l(this,It).data!==void 0&&M(this,jt,l(this,Y)),Sn(n,t))return;M(this,Ce,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:s}=this.options,a=typeof s=="function"?s():s;if(a==="all"||!a&&!l(this,Vt).size)return!0;const o=new Set(a??l(this,Vt));return this.options.throwOnError&&o.add("error"),Object.keys(l(this,Ce)).some(u=>{const p=u;return l(this,Ce)[p]!==t[p]&&o.has(p)})};z(this,ee,$s).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&z(this,ee,xr).call(this)}},ve=new WeakMap,Y=new WeakMap,an=new WeakMap,Ce=new WeakMap,It=new WeakMap,zt=new WeakMap,Ge=new WeakMap,ut=new WeakMap,on=new WeakMap,$t=new WeakMap,jt=new WeakMap,Bt=new WeakMap,Mt=new WeakMap,dt=new WeakMap,Vt=new WeakMap,ee=new WeakSet,ln=function(t){z(this,ee,Fr).call(this);let n=l(this,Y).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(be)),n},Cr=function(){z(this,ee,Sr).call(this);const t=at(this.options.staleTime,l(this,Y));if(wt||l(this,Ce).isStale||!sr(t))return;const r=is(l(this,Ce).dataUpdatedAt,t)+1;M(this,Bt,Tt.setTimeout(()=>{l(this,Ce).isStale||this.updateResult()},r))},Tr=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,Y)):this.options.refetchInterval)??!1},wr=function(t){z(this,ee,vr).call(this),M(this,dt,t),!(wt||Be(this.options.enabled,l(this,Y))===!1||!sr(l(this,dt))||l(this,dt)===0)&&M(this,Mt,Tt.setInterval(()=>{(this.options.refetchIntervalInBackground||ur.isFocused())&&z(this,ee,ln).call(this)},l(this,dt)))},xr=function(){z(this,ee,Cr).call(this),z(this,ee,wr).call(this,z(this,ee,Tr).call(this))},Sr=function(){l(this,Bt)&&(Tt.clearTimeout(l(this,Bt)),M(this,Bt,void 0))},vr=function(){l(this,Mt)&&(Tt.clearInterval(l(this,Mt)),M(this,Mt,void 0))},Fr=function(){const t=l(this,ve).getQueryCache().build(l(this,ve),this.options);if(t===l(this,Y))return;const n=l(this,Y);M(this,Y,t),M(this,an,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},$s=function(t){de.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,Ce))}),l(this,ve).getQueryCache().notify({query:l(this,Y),type:"observerResultsUpdated"})})},Ns);function ro(e,t){return Be(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Es(e,t){return ro(e,t)||e.state.data!==void 0&&pr(e,t,t.refetchOnMount)}function pr(e,t,n){if(Be(t.enabled,e)!==!1&&at(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&fr(e,t)}return!1}function bs(e,t,n,r){return(e!==t||Be(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&fr(e,n)}function fr(e,t){return Be(t.enabled,e)!==!1&&e.isStaleByTime(at(t.staleTime,e))}function so(e,t){return!Sn(e.getCurrentResult(),t)}function Cs(e){return{onFetch:(t,n)=>{var w,y,b,D,O;const r=t.options,s=(b=(y=(w=t.fetchOptions)==null?void 0:w.meta)==null?void 0:y.fetchMore)==null?void 0:b.direction,a=((D=t.state.data)==null?void 0:D.pages)||[],o=((O=t.state.data)==null?void 0:O.pageParams)||[];let u={pages:[],pageParams:[]},p=0;const f=async()=>{let B=!1;const k=K=>{Object.defineProperty(K,"signal",{enumerable:!0,get:()=>(t.signal.aborted?B=!0:t.signal.addEventListener("abort",()=>{B=!0}),t.signal)})},_=ls(t.options,t.fetchOptions),S=async(K,U,V)=>{if(B)return Promise.reject();if(U==null&&K.pages.length)return Promise.resolve(K);const oe=(()=>{const E={client:t.client,queryKey:t.queryKey,pageParam:U,direction:V?"backward":"forward",meta:t.options.meta};return k(E),E})(),i=await _(oe),{maxPages:c}=t.options,d=V?Gi:Vi;return{pages:d(K.pages,i,c),pageParams:d(K.pageParams,U,c)}};if(s&&a.length){const K=s==="backward",U=K?ao:Ts,V={pages:a,pageParams:o},G=U(r,V);u=await S(V,G,K)}else{const K=e??a.length;do{const U=p===0?o[0]??r.initialPageParam:Ts(r,u);if(p>0&&U==null)break;u=await S(u,U),p++}while(p<K)}return u};t.options.persister?t.fetchFn=()=>{var B,k;return(k=(B=t.options).persister)==null?void 0:k.call(B,f,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=f}}}function Ts(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function ao(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var io=(qs=class extends ms{constructor(t){super();N(this,Qe);N(this,cn);N(this,We);N(this,Te);N(this,kt);M(this,cn,t.client),this.mutationId=t.mutationId,M(this,Te,t.mutationCache),M(this,We,[]),this.state=t.state||ws(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){l(this,We).includes(t)||(l(this,We).push(t),this.clearGcTimeout(),l(this,Te).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){M(this,We,l(this,We).filter(n=>n!==t)),this.scheduleGc(),l(this,Te).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){l(this,We).length||(this.state.status==="pending"?this.scheduleGc():l(this,Te).remove(this))}continue(){var t;return((t=l(this,kt))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,u,p,f,w,y,b,D,O,B,k,_,S,K,U,V,G,oe,i,c;const n=()=>{z(this,Qe,mt).call(this,{type:"continue"})},r={client:l(this,cn),meta:this.options.meta,mutationKey:this.options.mutationKey};M(this,kt,hs({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(d,E)=>{z(this,Qe,mt).call(this,{type:"failed",failureCount:d,error:E})},onPause:()=>{z(this,Qe,mt).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,Te).canRun(this)}));const s=this.state.status==="pending",a=!l(this,kt).canStart();try{if(s)n();else{z(this,Qe,mt).call(this,{type:"pending",variables:t,isPaused:a}),await((u=(o=l(this,Te).config).onMutate)==null?void 0:u.call(o,t,this,r));const E=await((f=(p=this.options).onMutate)==null?void 0:f.call(p,t,r));E!==this.state.context&&z(this,Qe,mt).call(this,{type:"pending",context:E,variables:t,isPaused:a})}const d=await l(this,kt).start();return await((y=(w=l(this,Te).config).onSuccess)==null?void 0:y.call(w,d,t,this.state.context,this,r)),await((D=(b=this.options).onSuccess)==null?void 0:D.call(b,d,t,this.state.context,r)),await((B=(O=l(this,Te).config).onSettled)==null?void 0:B.call(O,d,null,this.state.variables,this.state.context,this,r)),await((_=(k=this.options).onSettled)==null?void 0:_.call(k,d,null,t,this.state.context,r)),z(this,Qe,mt).call(this,{type:"success",data:d}),d}catch(d){try{throw await((K=(S=l(this,Te).config).onError)==null?void 0:K.call(S,d,t,this.state.context,this,r)),await((V=(U=this.options).onError)==null?void 0:V.call(U,d,t,this.state.context,r)),await((oe=(G=l(this,Te).config).onSettled)==null?void 0:oe.call(G,void 0,d,this.state.variables,this.state.context,this,r)),await((c=(i=this.options).onSettled)==null?void 0:c.call(i,void 0,d,t,this.state.context,r)),d}finally{z(this,Qe,mt).call(this,{type:"error",error:d})}}finally{l(this,Te).runNext(this)}}},cn=new WeakMap,We=new WeakMap,Te=new WeakMap,kt=new WeakMap,Qe=new WeakSet,mt=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),de.batch(()=>{l(this,We).forEach(r=>{r.onMutationUpdate(t)}),l(this,Te).notify({mutation:this,type:"updated",action:t})})},qs);function ws(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var oo=(Ks=class extends qt{constructor(t={}){super();N(this,Xe);N(this,Ne);N(this,un);this.config=t,M(this,Xe,new Set),M(this,Ne,new Map),M(this,un,0)}build(t,n,r){const s=new io({client:t,mutationCache:this,mutationId:++Bn(this,un)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Xe).add(t);const n=Dn(t);if(typeof n=="string"){const r=l(this,Ne).get(n);r?r.push(t):l(this,Ne).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Xe).delete(t)){const n=Dn(t);if(typeof n=="string"){const r=l(this,Ne).get(n);if(r)if(r.length>1){const s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&l(this,Ne).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=Dn(t);if(typeof n=="string"){const r=l(this,Ne).get(n),s=r==null?void 0:r.find(a=>a.state.status==="pending");return!s||s===t}else return!0}runNext(t){var r;const n=Dn(t);if(typeof n=="string"){const s=(r=l(this,Ne).get(n))==null?void 0:r.find(a=>a!==t&&a.state.isPaused);return(s==null?void 0:s.continue())??Promise.resolve()}else return Promise.resolve()}clear(){de.batch(()=>{l(this,Xe).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Xe).clear(),l(this,Ne).clear()})}getAll(){return Array.from(l(this,Xe))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>cs(n,r))}findAll(t={}){return this.getAll().filter(n=>cs(t,n))}notify(t){de.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return de.batch(()=>Promise.all(t.map(n=>n.continue().catch(be))))}},Xe=new WeakMap,Ne=new WeakMap,un=new WeakMap,Ks);function Dn(e){var t;return(t=e.options.scope)==null?void 0:t.id}var co=(Hs=class extends qt{constructor(t,n){super();N(this,Je);N(this,Ze);N(this,lt);N(this,Fe);N(this,Ye);M(this,Ze,t),this.setOptions(n),this.bindMethods(),z(this,Je,Mn).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){var r;const n=this.options;this.options=l(this,Ze).defaultMutationOptions(t),Sn(this.options,n)||l(this,Ze).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,Fe),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&xt(n.mutationKey)!==xt(this.options.mutationKey)?this.reset():((r=l(this,Fe))==null?void 0:r.state.status)==="pending"&&l(this,Fe).setOptions(this.options)}onUnsubscribe(){var t;this.hasListeners()||(t=l(this,Fe))==null||t.removeObserver(this)}onMutationUpdate(t){z(this,Je,Mn).call(this),z(this,Je,Dr).call(this,t)}getCurrentResult(){return l(this,lt)}reset(){var t;(t=l(this,Fe))==null||t.removeObserver(this),M(this,Fe,void 0),z(this,Je,Mn).call(this),z(this,Je,Dr).call(this)}mutate(t,n){var r;return M(this,Ye,n),(r=l(this,Fe))==null||r.removeObserver(this),M(this,Fe,l(this,Ze).getMutationCache().build(l(this,Ze),this.options)),l(this,Fe).addObserver(this),l(this,Fe).execute(t)}},Ze=new WeakMap,lt=new WeakMap,Fe=new WeakMap,Ye=new WeakMap,Je=new WeakSet,Mn=function(){var n;const t=((n=l(this,Fe))==null?void 0:n.state)??ws();M(this,lt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Dr=function(t){de.batch(()=>{var n,r,s,a,o,u,p,f;if(l(this,Ye)&&this.hasListeners()){const w=l(this,lt).variables,y=l(this,lt).context,b={client:l(this,Ze),meta:this.options.meta,mutationKey:this.options.mutationKey};(t==null?void 0:t.type)==="success"?((r=(n=l(this,Ye)).onSuccess)==null||r.call(n,t.data,w,y,b),(a=(s=l(this,Ye)).onSettled)==null||a.call(s,t.data,null,w,y,b)):(t==null?void 0:t.type)==="error"&&((u=(o=l(this,Ye)).onError)==null||u.call(o,t.error,w,y,b),(f=(p=l(this,Ye)).onSettled)==null||f.call(p,void 0,t.error,w,y,b))}this.listeners.forEach(w=>{w(l(this,lt))})})},Hs),uo=(Ws=class extends qt{constructor(t={}){super();N(this,ze);this.config=t,M(this,ze,new Map)}build(t,n,r){const s=n.queryKey,a=n.queryHash??ar(s,n);let o=this.get(a);return o||(o=new to({client:t,queryKey:s,queryHash:a,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){l(this,ze).has(t.queryHash)||(l(this,ze).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=l(this,ze).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,ze).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){de.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,ze).get(t)}getAll(){return[...l(this,ze).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>os(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>os(t,r)):n}notify(t){de.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){de.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){de.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},ze=new WeakMap,Ws),lo=(Qs=class{constructor(e={}){N(this,se);N(this,pt);N(this,ft);N(this,Gt);N(this,Xt);N(this,ht);N(this,Zt);N(this,Yt);M(this,se,e.queryCache||new uo),M(this,pt,e.mutationCache||new oo),M(this,ft,e.defaultOptions||{}),M(this,Gt,new Map),M(this,Xt,new Map),M(this,ht,0)}mount(){Bn(this,ht)._++,l(this,ht)===1&&(M(this,Zt,ur.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,se).onFocus())})),M(this,Yt,Fn.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,se).onOnline())})))}unmount(){var e,t;Bn(this,ht)._--,l(this,ht)===0&&((e=l(this,Zt))==null||e.call(this),M(this,Zt,void 0),(t=l(this,Yt))==null||t.call(this),M(this,Yt,void 0))}isFetching(e){return l(this,se).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,pt).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=l(this,se).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=l(this,se).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(at(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,se).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),s=l(this,se).get(r.queryHash),a=s==null?void 0:s.state.data,o=zi(t,a);if(o!==void 0)return l(this,se).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return de.batch(()=>l(this,se).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=l(this,se).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=l(this,se);de.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=l(this,se);return de.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=de.batch(()=>l(this,se).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(be).catch(be)}invalidateQueries(e,t={}){return de.batch(()=>(l(this,se).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=de.batch(()=>l(this,se).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let a=s.fetch(void 0,n);return n.throwOnError||(a=a.catch(be)),s.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(be)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=l(this,se).build(this,t);return n.isStaleByTime(at(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(be).catch(be)}fetchInfiniteQuery(e){return e.behavior=Cs(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(be).catch(be)}ensureInfiniteQueryData(e){return e.behavior=Cs(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Fn.isOnline()?l(this,pt).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,se)}getMutationCache(){return l(this,pt)}getDefaultOptions(){return l(this,ft)}setDefaultOptions(e){M(this,ft,e)}setQueryDefaults(e,t){l(this,Gt).set(xt(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...l(this,Gt).values()],n={};return t.forEach(r=>{tn(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,Xt).set(xt(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...l(this,Xt).values()],n={};return t.forEach(r=>{tn(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...l(this,ft).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=ar(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===vn&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...l(this,ft).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,se).clear(),l(this,pt).clear()}},se=new WeakMap,pt=new WeakMap,ft=new WeakMap,Gt=new WeakMap,Xt=new WeakMap,ht=new WeakMap,Zt=new WeakMap,Yt=new WeakMap,Qs),xs=ce.createContext(void 0),nn=e=>{const t=ce.useContext(xs);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},po=({client:e,children:t})=>(ce.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),H.jsx(xs.Provider,{value:e,children:t})),Ss=ce.createContext(!1),fo=()=>ce.useContext(Ss);Ss.Provider;function ho(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var mo=ce.createContext(ho()),yo=()=>ce.useContext(mo),go=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Ao=e=>{ce.useEffect(()=>{e.clearReset()},[e])},Eo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||ps(n,[e.error,r])),bo=e=>{if(e.suspense){const n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Co=(e,t)=>e.isLoading&&e.isFetching&&!t,To=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,vs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function wo(e,t,n){var y,b,D,O,B;if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const r=fo(),s=yo(),a=nn(),o=a.defaultQueryOptions(e);(b=(y=a.getDefaultOptions().queries)==null?void 0:y._experimental_beforeQuery)==null||b.call(y,o),process.env.NODE_ENV!=="production"&&(o.queryFn||console.error(`[${o.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),o._optimisticResults=r?"isRestoring":"optimistic",bo(o),go(o,s),Ao(s);const u=!a.getQueryCache().get(o.queryHash),[p]=ce.useState(()=>new t(a,o)),f=p.getOptimisticResult(o),w=!r&&e.subscribed!==!1;if(ce.useSyncExternalStore(ce.useCallback(k=>{const _=w?p.subscribe(de.batchCalls(k)):be;return p.updateResult(),_},[p,w]),()=>p.getCurrentResult(),()=>p.getCurrentResult()),ce.useEffect(()=>{p.setOptions(o)},[o,p]),To(o,f))throw vs(o,p,s);if(Eo({result:f,errorResetBoundary:s,throwOnError:o.throwOnError,query:a.getQueryCache().get(o.queryHash),suspense:o.suspense}))throw f.error;if((O=(D=a.getDefaultOptions().queries)==null?void 0:D._experimental_afterQuery)==null||O.call(D,o,f),o.experimental_prefetchInRender&&!wt&&Co(f,r)){const k=u?vs(o,p,s):(B=a.getQueryCache().get(o.queryHash))==null?void 0:B.promise;k==null||k.catch(be).finally(()=>{p.updateResult()})}return o.notifyOnChangeProps?f:p.trackResult(f)}function xo(e,t){return wo(e,no)}function it(e,t){const n=nn(),[r]=ce.useState(()=>new co(n,e));ce.useEffect(()=>{r.setOptions(e)},[r,e]);const s=ce.useSyncExternalStore(ce.useCallback(o=>r.subscribe(de.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=ce.useCallback((o,u)=>{r.mutate(o,u).catch(be)},[r]);if(s.error&&ps(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:a,mutateAsync:s.mutate}}const rn=()=>{const e=Q(a=>a.state.swapExecutionIndex),t=Q(a=>a.state.swapExecutions[a.state.swapExecutionIndex]??{}),n=Q(a=>a.updateSwapExecutionAtIndex),r=Q(a=>a.resetSwapExecutionAtIndex),s=F.useCallback(a=>n(e,a),[n,e]);return F.useMemo(()=>({...t,update:s,resetSwap:r}),[t,s,r])},So=2e4,vo=()=>{const{module:e}=q(),t=Q(n=>n.state.isMarketOrder);return F.useMemo(()=>e===j.TWAP?t?X.TWAP_MARKET:X.TWAP_LIMIT:e===j.LIMIT?X.LIMIT:e===j.STOP_LOSS?t?X.STOP_LOSS_MARKET:X.STOP_LOSS_LIMIT:e===j.TAKE_PROFIT?t?X.TAKE_PROFIT_MARKET:X.TAKE_PROFIT_LIMIT:X.TWAP_MARKET,[e,t])},hr=()=>{const{account:e,config:t,chainId:n,isDev:r}=q();return F.useMemo(()=>["useTwapOrderHistoryManager",e,t==null?void 0:t.adapter,t==null?void 0:t.partner,n,r],[e,t,n,r])},Fo=()=>{const e=nn(),t=hr();return F.useCallback((n,r)=>{e.setQueryData(t,s=>s==null?void 0:s.map(a=>a.id===n?{...a,status:r}:a))},[e,t])},Do=()=>{const{callbacks:e}=q(),t=nn(),n=hr();return F.useCallback(r=>{var u;const s=t.getQueryData(n);let a=!1;const o=[];s&&s.filter(p=>p.version===2).forEach(p=>{var w;const f=r.find(y=>y.id===p.id);f&&f.progress!==p.progress&&(a=!0,o.push(f),f.status===ue.Completed&&((w=e==null?void 0:e.onOrderFilled)==null||w.call(e,f)))}),a&&((u=e==null?void 0:e.onOrdersProgressUpdate)==null||u.call(e,o))},[t,n,e])},Po=(e,t)=>{const n=new Set(e.map(s=>s.id)),r=(t==null?void 0:t.filter(s=>s.version===1&&!n.has(s.id)))??[];return[...e,...r].sort((s,a)=>a.createdAt-s.createdAt)},mr=()=>{const{account:e,config:t,chainId:n,isDev:r}=q(),s=nn(),a=hr(),o=Do();return xo({refetchInterval:So,refetchOnWindowFocus:!0,retry:!1,gcTime:1/0,staleTime:1/0,queryKey:a,queryFn:async({signal:p})=>{if(!e||!n||!t)return[];const f=s.getQueryData(a),w=!f,y=await hi({signal:p,chainId:n,config:t,account:e,isDev:r,includeV1GraphOrders:w});o(y);const b=y.map(D=>t!=null&&t.twapConfig?{...D,fillDelayMillis:Hn(D,t.twapConfig)}:D);return w?b:Po(b,f)}})},Oo=(e,t,n)=>F.useMemo(()=>{if(!(!e||!t||!n||n!=null&&n.isMarketPrice))return Nr(n,e==null?void 0:e.decimals,t==null?void 0:t.decimals)},[n,e,t]),Io=(e,t,n)=>F.useMemo(()=>{if(!(!e||!t||!n))return qr(n,e.decimals,t.decimals)},[n,e,t]),Bo=(e,t,n)=>F.useMemo(()=>{if(!(!e||!t||!n))return Wn(n.srcAmountFilled,n.dstAmountFilled,e.decimals,t.decimals)},[n,e,t]),Pn=(e,t)=>[...e.filter(r=>r.status===t)].sort((r,s)=>s.createdAt-r.createdAt),Mo=()=>{const{data:e,isLoading:t,refetch:n,isRefetching:r}=mr(),s=F.useCallback(()=>n().then(a=>a.data),[n]);return F.useMemo(()=>({orders:{all:e??[],open:Pn(e??[],ue.Open),completed:Pn(e??[],ue.Completed),cancelled:Pn(e??[],ue.Cancelled),expired:Pn(e??[],ue.Expired)},isLoading:t,isRefetching:r,refetchOrders:s}),[e,t,r,s])},yr=()=>{const e=Q(n=>n.state.currentTime),t=tr().duration;return F.useMemo(()=>Da(e,t),[e,t])},Fs=()=>{const{srcToken:e,dstToken:t,account:n,chainId:r,slippage:s,config:a,module:o,fees:u}=q(),{amount:p}=st(),{amountPerTrade:f,totalTrades:w}=Ke(),y=yr(),{amount:b}=rr(),{pricePerChunk:D}=Ct(),{milliseconds:O}=Nt();return F.useMemo(()=>{var B;return Wr({chainId:r,srcToken:Rt((e==null?void 0:e.address)||"")?((B=Et(r))==null?void 0:B.wToken.address)||"":(e==null?void 0:e.address)||"",dstToken:(t==null?void 0:t.address)||"",srcAmount:p,deadlineMillis:y,fillDelayMillis:!w||w===1?0:O,slippage:s*100,account:n,srcAmountPerTrade:f,dstMinAmountPerTrade:b,triggerAmountPerTrade:D,config:a,module:o})},[e,t,n,r,s,a,o,p,f,w,O,b,D,u])};function ko(e){const t=e.slice(2);if(t.length===128){const a=`0x${t.slice(0,64)}`,o=parseInt(t.charAt(64),16),u=(o>>3)+27,p=`0x${(o&7).toString(16)}${t.slice(65,128)}`;return{r:a,s:p,v:u}}const n=`0x${t.slice(0,64)}`,r=`0x${t.slice(64,128)}`,s=parseInt(t.slice(128,130),16);return{r:n,s:r,v:s}}const _o=()=>{var a;const{account:e,walletInteractions:t,callbacks:n,chainId:r}=q(),s=(a=bn())==null?void 0:a.wToken;return it({mutationFn:async({onHash:o,srcAmountWei:u})=>{var f,w;if(!e)throw new Error("missing account");if(!t)throw new Error("missing walletInteractions");if(!s)throw new Error("tokenAddress is not defined");fe.onWrapRequest();const p=await t.wrapNativeToken(u);return(f=n==null?void 0:n.onWrapRequest)==null||f.call(n),o==null||o(p),fe.onWrapSuccess(p),(w=n==null?void 0:n.onWrapSuccess)==null||w.call(n,{txHash:p,explorerUrl:Lt(p,r),amount:Ee(u,s.decimals)}),p},onError:o=>{throw fe.onWrapError(o),o}})},Ds=()=>{const{account:e,walletInteractions:t,chainId:n,callbacks:r,isDev:s}=q(),a=Fs(),{refetch:o}=mr();return it({mutationFn:async()=>{var B,k,_,S;if(!e)throw new Error("missing account");if(!t)throw new Error("missing walletInteractions");if(!n)throw new Error("missing chainId");const{order:u,domain:p,types:f,primaryType:w}=a;fe.onSignOrderRequest(u);let y;try{y=await t.signOrder({domain:p,types:f,primaryType:w,message:u,account:e})}catch(K){throw(B=r==null?void 0:r.onSignOrderError)==null||B.call(r,K),fe.onSignOrderError(K),K}fe.onSignOrderSuccess(y),(k=r==null?void 0:r.onSignOrderSuccess)==null||k.call(r,y);const b=ko(y),D={v:`0x${b.v.toString(16)}`,r:b.r,s:b.s};(_=r==null?void 0:r.onSignOrderRequest)==null||_.call(r);const O=await $r(u,D,s);return(S=r==null?void 0:r.onOrderCreated)==null||S.call(r,O),await o(),O}})},Ps=()=>{const{account:e,walletInteractions:t,config:n}=q();return it({mutationFn:async({tokenAddress:r,srcAmountWei:s})=>{if(!t)throw new Error("missing walletInteractions");if(!e)throw new Error("missing account");if(!n)throw new Error("missing config");const a=await t.getAllowance({tokenAddress:r,spenderAddress:n.repermit}),o=v(a||"0").lt(v(s).toString());return{allowance:a,approvalRequired:o}}})},Uo=()=>{const{account:e,walletInteractions:t,config:n,chainId:r,callbacks:s}=q(),{mutateAsync:a}=Ps();return it({onError:o=>{fe.onApproveError(o)},mutationFn:async({token:o,onHash:u,srcAmountWei:p})=>{var y,b;if(!e)throw new Error("missing account");if(!t)throw new Error("missing walletInteractions");if(!n)throw new Error("missing config");fe.onApproveRequest();const f=await t.approveToken({tokenAddress:o.address,amount:p,spenderAddress:n.repermit});if(!f)throw new Error("failed to approve token");(y=s==null?void 0:s.onApproveRequest)==null||y.call(s),u(f);let w=!1;for(let D=0;D<3;D++){const{approvalRequired:O}=await a({tokenAddress:o.address,srcAmountWei:p});if(!O){w=!0;break}D<2&&await new Promise(B=>setTimeout(B,3e3))}if(!w)throw new Error(`Insufficient ${o.symbol} allowance to perform the swap. Please approve the token first.`);return fe.onApproveSuccess(f),(b=s==null?void 0:s.onApproveSuccess)==null||b.call(s,{txHash:f,explorerUrl:Lt(f,r),token:o,amount:Ee(p,o.decimals)}),f}})},Ro=()=>{const{account:e,chainId:t,srcToken:n,dstToken:r,module:s,slippage:a}=q(),o=Ct(),u=st().amount,p=Ke().amountPerTrade,f=yr(),w=Ke().totalTrades,y=Nt().fillDelay,b=rr().amount,D=Q(O=>O.state.isMarketOrder);return it({mutationFn:async()=>{fe.onRequestOrder({account:e,chainId:t,module:s,srcToken:n,dstToken:r,fromTokenAmount:u,srcChunkAmount:p,triggerPricePerTrade:o.pricePerChunk,deadline:f,fillDelay:y.unit*y.value,minDstAmountOutPerTrade:b,slippage:a,isMarketOrder:D||!1,chunksAmount:w})}})};function Lo(e){const t=e.message,n=t.match(/,\s*code\s*:\s*(\d+)/i);return{message:t.replace(/^error\s*:/i,"").replace(/,\s*code\s*:\s*\d+/i,"").trim()||"",code:n?Number(n[1]):0}}const Os=()=>{const{srcToken:e,dstToken:t,chainId:n,callbacks:r,marketPrice:s}=q(),a=Uo().mutateAsync,o=_o().mutateAsync,u=Ds().mutateAsync,{mutateAsync:p}=Ps(),{update:f}=rn(),{amount:w}=st(),y=Ro().mutate;return it({mutationFn:async()=>{var D,O;const b=Rt((e==null?void 0:e.address)||" ");try{if(!e)throw new Error("missing srcToken");if(!t)throw new Error("missing dstToken");if(!n)throw new Error("missing chainId");const B=Jr(e,n);f({allowanceLoading:!0,wrapTxHash:void 0,approveTxHash:void 0,acceptedMarketPrice:s,acceptedSrcAmount:w,srcToken:e,dstToken:t,pendingSteps:[]});const{approvalRequired:k}=await p({tokenAddress:B.address,srcAmountWei:w});let _=0,S=1;b&&S++,k&&S++,f({totalSteps:S,stepIndex:_,allowanceLoading:!1,hasApproval:!k,status:Se.LOADING}),y();let K=[];b&&K.push(nt.WRAP),k&&K.push(nt.APPROVE),K.push(nt.CREATE),f({pendingSteps:K}),b&&(f({step:nt.WRAP}),await o({onHash:V=>f({wrapTxHash:V}),srcAmountWei:w}),_++,f({stepIndex:_})),k&&(f({step:nt.APPROVE}),await a({token:B,onHash:V=>f({approveTxHash:V}),srcAmountWei:w}),_++,f({stepIndex:_})),f({step:nt.CREATE});const U=await u();return f({status:Se.SUCCESS,orderId:U.id}),U}catch(B){if(Xn(B))(D=r==null?void 0:r.onSubmitOrderRejected)==null||D.call(r),f({step:void 0,status:void 0,stepIndex:void 0,error:B});else{const k=Lo(B);(O=r==null?void 0:r.onSubmitOrderFailed)==null||O.call(r,k),f({status:Se.FAILED,parsedError:k,error:B})}throw B}}})},No=()=>{const e=rn(),{srcToken:t,dstToken:n}=q(),r=Os(),s=Q(f=>f.resetState),a=F.useCallback(()=>r.mutateAsync(),[r]),{update:o,resetSwap:u,...p}=e;return F.useMemo(()=>({status:p.status,parsedError:p.parsedError,error:p.error,step:p.step,stepIndex:p.stepIndex,approveTxHash:p.approveTxHash,wrapTxHash:p.wrapTxHash,totalSteps:p.totalSteps,pendingSteps:p.pendingSteps,srcToken:t,dstToken:n,onSubmit:a,resetState:s,resetCurrentSwap:u,isLoading:(e==null?void 0:e.status)===Se.LOADING,isSuccess:(e==null?void 0:e.status)===Se.SUCCESS,isFailed:(e==null?void 0:e.status)===Se.FAILED,confirmButtonLoading:p.allowanceLoading}),[a,p,s,u,t,n])},qo=()=>{const{marketPrice:e,srcToken:t,dstToken:n,marketPriceLoading:r,srcBalance:s,srcUsd1Token:a,noLiquidity:o,typedInputAmount:u}=q(),p=r||v(a||"0").isZero()||s===void 0||v(e||"0").isZero(),f=!!(t&&n&&u&&p),y=!!(as()||o||f||v(u||"0").isZero()||!t||!n);return F.useMemo(()=>({disabled:y,loading:f}),[y,f])},Ko=()=>{const{srcUsd1Token:e,dstUsd1Token:t}=q(),n=st().amountUI,r=xn().amountUI,s=qe(n,e),a=qe(r,t);return{srcAmountUsd:s,dstAmountUsd:a}},Ho=()=>{const{fees:e,dstToken:t,dstUsd1Token:n}=q(),{amountUI:r}=xn(),s=F.useMemo(()=>!e||!r?"":v(r).multipliedBy(e).dividedBy(100).toFixed(),[r,e]),a=er((t==null?void 0:t.decimals)||0,s);return{amountUI:s,amount:a,percent:e,usd:qe(s,n)}},Wo=e=>{const t=F.useMemo(()=>!e.minDestAmountPerTrade||!e.totalTrades?"":v(e.minDestAmountPerTrade).multipliedBy(e.totalTrades).decimalPlaces(0).toFixed(),[e.minDestAmountPerTrade,e.totalTrades]),n=F.useMemo(()=>!e.minDestAmountPerTradeUI||!e.totalTrades?"":v(e.minDestAmountPerTradeUI).multipliedBy(e.totalTrades).toFixed(),[e.minDestAmountPerTradeUI,e.totalTrades]),r=F.useMemo(()=>!e.minDestAmountPerTradeUsd||!e.totalTrades?"":v(e.minDestAmountPerTradeUsd).multipliedBy(e.totalTrades).decimalPlaces(2).toFixed(),[e.minDestAmountPerTradeUsd,e.totalTrades]);return F.useMemo(()=>({srcToken:e.srcToken,dstToken:e.dstToken,orderType:e.orderType,createdAt:e.createdAt||0,deadline:e.deadline||0,totalTrades:e.totalTrades||0,tradeInterval:e.tradeInterval||0,recipient:e.account||"",srcAmount:e.srcAmount||"",srcAmountUI:e.srcAmountUI||"",srcAmountUsd:e.srcAmountUsd||"",dstAmount:e.dstAmount||"",dstAmountUI:e.dstAmountUI||"",dstAmountUsd:e.dstAmountUsd||"",limitPrice:e.limitPrice||"",limitPriceUI:e.limitPriceUI||"",limitPriceUsd:e.limitPriceUsd||"",sizePerTrade:e.srcAmountPerTrade||"",sizePerTradeUI:e.srcAmountPerTradeUI||"",sizePerTradeUsd:e.srcAmountPerTradeUsd,minDestAmountPerTrade:e.minDestAmountPerTrade||"",minDestAmountPerTradeUI:e.minDestAmountPerTradeUI||"",minDestAmountPerTradeUsd:e.minDestAmountPerTradeUsd,dstMinAmount:t,dstMinAmountUI:n,dstMinAmountUsd:r,triggerPrice:e.triggerPrice||"",triggerPriceUI:e.triggerPriceUI||"",triggerPriceUsd:e.triggerPriceUsd}),[e.srcToken,e.dstToken,e.orderType,e.createdAt,e.deadline,e.totalTrades,e.tradeInterval,e.account,e.srcAmount,e.srcAmountUI,e.srcAmountUsd,e.dstAmount,e.dstAmountUI,e.dstAmountUsd,e.limitPrice,e.limitPriceUI,e.limitPriceUsd,e.srcAmountPerTrade,e.srcAmountPerTradeUI,e.srcAmountPerTradeUsd,e.minDestAmountPerTrade,e.minDestAmountPerTradeUI,e.minDestAmountPerTradeUsd,t,n,r,e.triggerPrice,e.triggerPriceUI,e.triggerPriceUsd])},Qo=()=>{const{config:e}=q();return F.useMemo(()=>({spender:e.repermit}),[e])},zo=()=>{const{srcToken:e,dstToken:t,account:n,marketPrice:r}=q(),{spender:s}=Qo(),{amount:a}=st(),{amount:o,amountUI:u,usd:p}=wn(),{amountPerTrade:f,amountPerTradeUI:w,amountPerTradeUsd:y,totalTrades:b}=Ke(),D=yr(),{amount:O,amountUI:B,usd:k}=rr(),{amountUI:_,amount:S,usd:K}=Ct(),{milliseconds:U}=Nt(),{amount:V,amountUI:G}=xn(),{srcAmountUsd:oe,dstAmountUsd:i}=Ko(),{amount:c,amountUI:d,percent:E,usd:m}=Ho(),g=Fs(),x=Q(Z=>Z.state.isMarketOrder),h=Q(Z=>Z.state.currentTime),A=rn(),T=vo(),C=A.acceptedSrcAmount||a,P=Ee(r,(t==null?void 0:t.decimals)||0),R=F.useMemo(()=>T===X.TAKE_PROFIT_MARKET||T===X.TAKE_PROFIT_LIMIT||T===X.STOP_LOSS_LIMIT||T===X.STOP_LOSS_MARKET,[T]),L=Wo({srcToken:e,dstToken:t,account:n,orderType:T,createdAt:h,deadline:D,totalTrades:b,tradeInterval:U,srcAmount:C,srcAmountUI:Ee(C,(e==null?void 0:e.decimals)||0),srcAmountUsd:oe,dstAmount:V,dstAmountUI:G,dstAmountUsd:i,limitPrice:x?void 0:o,limitPriceUI:x?void 0:u,limitPriceUsd:x?void 0:p,srcAmountPerTrade:f,srcAmountPerTradeUI:w,srcAmountPerTradeUsd:y,minDestAmountPerTrade:O,minDestAmountPerTradeUI:B,minDestAmountPerTradeUsd:k,triggerPrice:S,triggerPriceUI:_,triggerPriceUsd:K});return F.useMemo(()=>({...L,feesAmountUI:d,feesAmount:c,feesUsd:m||"",feesPercentage:E,rePermitData:g,isTriggerPrice:R,isMarketOrder:x,marketPrice:r,marketPriceUi:P,spender:s}),[L,d,c,m,E,g,R,x,r,P,s])},$o=()=>{const{supportedChains:e}=q();return F.useMemo(()=>e,[e])},jo=60,Is=()=>{const{refetch:e}=mr();return it({mutationFn:async t=>{var n;for(let r=0;r<jo;r++){const s=(n=await e())==null?void 0:n.data;if(!s)throw new Error("orders not found");const a=s.find(o=>o.id===t);if((a==null?void 0:a.status)===ue.Cancelled)return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("Timed out waiting for order cancellation to be confirmed")}})},Vo=()=>{const e=Q(n=>n.updateState),t=Q(n=>n.state.cancelOrders);return{cancelOrders:t,setCancelOrder:(n,r)=>{e({cancelOrders:{...t,[n]:r}})},clearCancelOrder:n=>{const{[n]:r,...s}=t;e({cancelOrders:s})}}},Go=e=>{const{account:t,walletInteractions:n,config:r,callbacks:s,chainId:a}=q(),o=Is().mutateAsync,u=Fo(),{cancelOrders:p,setCancelOrder:f,clearCancelOrder:w}=Vo(),{mutateAsync:y}=it({mutationFn:async()=>{var B,k,_;if(!t||!n||!r)throw new Error("missing required parameters");if(!e)throw new Error("order is required");const O=e.id;try{(B=s==null?void 0:s.onCancelOrderRequest)==null||B.call(s,e),f(O,{status:Se.LOADING}),fe.onCancelOrderRequest([e.version===1?e.id.toString():e.hash],e.version);const S=await n.cancelOrder({order:e,contractAddress:e.version===1?e.twapAddress:r.repermit,args:e.version===1?[e.id]:[[e.repermitDigest]],abi:e.version===1?Gs:Vs});if(!S)throw new Error("failed to cancel order");return fe.onCancelOrderSuccess(S),e.version===1?u(e.id,ue.Cancelled):await o(e.id),(k=s==null?void 0:s.onCancelOrderSuccess)==null||k.call(s,{order:e.version===1?{...e,status:ue.Cancelled}:e,txHash:S,explorerUrl:Lt(S,a)}),f(O,{status:Se.SUCCESS,txHash:S}),S}catch(S){console.error("cancel order error",S),(_=s==null?void 0:s.onCancelOrderFailed)==null||_.call(s,S),Xn(S)?w(O):(f(O,{status:Se.FAILED,error:S.message}),fe.onCancelOrderError(S))}}}),b=F.useMemo(()=>{const O=p[(e==null?void 0:e.id)||""];return{isLoading:(O==null?void 0:O.status)===Se.LOADING,isSuccess:(O==null?void 0:O.status)===Se.SUCCESS,isError:(O==null?void 0:O.status)===Se.FAILED,error:O==null?void 0:O.error,txHash:O==null?void 0:O.txHash}},[p,e==null?void 0:e.id]),D=F.useCallback(async()=>y(),[y]);return F.useMemo(()=>({cancelOrder:D,...b}),[D,b])},Bs=F.createContext(null),Xo=({children:e})=>{const t=Fi(),n=Ii(),r=Pi(),s=Ri(),a=Li(),o=Cn(),u=Ni(),p=qi(),f=as(),w=qo(),y=zo(),b=Mo(),D=No(),O=$o(),B=Is(),{module:k}=q(),_={tradesAmountPanel:t,durationPanel:n,fillDelayPanel:r,limitPricePanel:s,triggerPricePanel:a,pricePanel:o,dstTokenPanel:u,disclaimerPanel:p,inputError:f,submitOrderButton:w,derivedFormData:y,orderHistoryPanel:b,orderExecutionPanel:D,supportedChains:O,refetchUntilStatusSynced:B,module:k};return H.jsx(Bs.Provider,{value:_,children:e})},Zo=()=>{const e=F.useContext(Bs);if(e===null)throw new Error("useSpot must be used within SpotProvider");return e},Yo=F.createContext(null),gr={didCatch:!1,error:null};class Jo extends F.Component{constructor(t){super(t),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=gr}static getDerivedStateFromError(t){return{didCatch:!0,error:t}}resetErrorBoundary(){const{error:t}=this.state;if(t!==null){for(var n,r,s=arguments.length,a=new Array(s),o=0;o<s;o++)a[o]=arguments[o];(n=(r=this.props).onReset)===null||n===void 0||n.call(r,{args:a,reason:"imperative-api"}),this.setState(gr)}}componentDidCatch(t,n){var r,s;(r=(s=this.props).onError)===null||r===void 0||r.call(s,t,n)}componentDidUpdate(t,n){const{didCatch:r}=this.state,{resetKeys:s}=this.props;if(r&&n.error!==null&&ec(t.resetKeys,s)){var a,o;(a=(o=this.props).onReset)===null||a===void 0||a.call(o,{next:s,prev:t.resetKeys,reason:"keys"}),this.setState(gr)}}render(){const{children:t,fallbackRender:n,FallbackComponent:r,fallback:s}=this.props,{didCatch:a,error:o}=this.state;let u=t;if(a){const p={error:o,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")u=n(p);else if(r)u=F.createElement(r,p);else if(s!==void 0)u=s;else throw o}return F.createElement(Yo.Provider,{value:{didCatch:a,error:o,resetErrorBoundary:this.resetErrorBoundary}},u)}}function ec(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return e.length!==t.length||e.some((n,r)=>!Object.is(n,t[r]))}const tc=()=>H.jsx("div",{className:"twap-error-fallback",children:H.jsx("p",{style:{fontSize:20,fontWeight:600,textAlign:"center",width:"100%",marginTop:40},children:"Something went wrong"})});function nc({children:e}){return H.jsx(Jo,{FallbackComponent:tc,onError:t=>fe.onCrash(t),children:H.jsx(H.Fragment,{children:e})})}const Ms=F.createContext(null),rc=new lo({defaultOptions:{queries:{refetchOnWindowFocus:!1}}}),sc=e=>{var r,s,a;const t=Q(o=>o.updateState),n=Q(o=>o.state.isMarketOrder);return F.useEffect(()=>{const o=setInterval(()=>{t({currentTime:Date.now()})},6e4);return()=>clearInterval(o)},[t]),F.useEffect(()=>{var u,p,f,w,y,b,D,O,B,k,_,S,K,U,V,G;const o=(p=(u=e.overrides)==null?void 0:u.state)==null?void 0:p.isMarketOrder;o!==void 0&&t({isMarketOrder:o}),t({typedChunks:(w=(f=e.overrides)==null?void 0:f.state)==null?void 0:w.chunks,typedFillDelay:(b=(y=e.overrides)==null?void 0:y.state)==null?void 0:b.fillDelay,typedDuration:(O=(D=e.overrides)==null?void 0:D.state)==null?void 0:O.duration,typedLimitPrice:(k=(B=e.overrides)==null?void 0:B.state)==null?void 0:k.limitPrice,typedTriggerPrice:(S=(_=e.overrides)==null?void 0:_.state)==null?void 0:S.triggerPrice,triggerPricePercent:(U=(K=e.overrides)==null?void 0:K.state)==null?void 0:U.triggerPricePercent,limitPricePercent:(G=(V=e.overrides)==null?void 0:V.state)==null?void 0:G.limitPricePercent})},[(r=e.overrides)==null?void 0:r.state,e.module]),F.useEffect(()=>{var o,u,p,f;t({typedLimitPrice:(u=(o=e.overrides)==null?void 0:o.state)==null?void 0:u.limitPrice,typedTriggerPrice:(f=(p=e.overrides)==null?void 0:p.state)==null?void 0:f.triggerPrice,triggerPricePercent:void 0,limitPricePercent:void 0})},[(s=e.srcToken)==null?void 0:s.address,(a=e.dstToken)==null?void 0:a.address]),F.useEffect(()=>{e.module===j.LIMIT&&t({isMarketOrder:!1})},[e.module]),F.useEffect(()=>{n&&t({isInvertedTrade:!1})},[n]),F.useEffect(()=>{t({typedChunks:void 0})},[e.typedInputAmount]),null},ac=({marketReferencePrice:e,srcToken:t,dstToken:n,chainId:r,typedInputAmount:s})=>F.useMemo(()=>{if(Yn(t,n,r)||Jn(t,n,r))return{isLoading:!1,noLiquidity:!1,value:rt(s||"0",t==null?void 0:t.decimals)};if(v(e.value||0).isZero()||v(s||0).isZero())return e;const a=v(e.value||0).dividedBy(s||0).decimalPlaces(0).toFixed();return{...e,value:a}},[e,s,t,n,r]),ic=e=>{const t=rn(),n=F.useMemo(()=>Lr(e.partner),[e.partner]),r=F.useMemo(()=>{const u=n[0];return e.chainId&&n.includes(e.chainId)?e.chainId:u},[e.chainId,n]),s=F.useMemo(()=>Qn(e.partner,r),[e.partner,r]),a=ac(e),o=F.useMemo(()=>Hr(e.minChunkSizeUsd),[e.minChunkSizeUsd]);return F.useEffect(()=>{fe.init(s,o,r)},[s,r,o]),H.jsxs(Ms.Provider,{value:{typedInputAmount:e.typedInputAmount,minChunkSizeUsd:o,account:e.account,walletInteractions:e.walletInteractions,marketPrice:t.acceptedMarketPrice||a.value,marketPriceLoading:!t.acceptedMarketPrice&&a.isLoading,noLiquidity:!t.acceptedMarketPrice&&a.noLiquidity,config:s,slippage:e.priceProtection,supportedChains:n,chainId:r,partner:e.partner,module:e.module,fees:e.fees||0,overrides:e.overrides,callbacks:e.callbacks,srcUsd1Token:e.srcUsd1Token,dstUsd1Token:e.dstUsd1Token,srcBalance:e.srcBalance,dstBalance:e.dstBalance,srcToken:t.srcToken||e.srcToken,dstToken:t.dstToken||e.dstToken,isDev:e.isDev},children:[H.jsx(sc,{...e}),H.jsx(Xo,{children:H.jsx(nc,{children:e.children})})]})},oc=e=>H.jsx(po,{client:rc,children:H.jsx(ic,{...e})}),q=()=>{const e=F.useContext(Ms);if(e===null)throw new Error("useSpotContext must be used within SpotProvider");return e},cc=(e,t,n)=>{const r=bn();return F.useMemo(()=>e==null?void 0:e.map(s=>({rawFill:s,srcToken:t,dstToken:n,srcAmount:Ee(s.inAmount,t==null?void 0:t.decimals),dstAmount:Ee(s.outAmount,n==null?void 0:n.decimals),timestamp:s.timestamp,txHash:s.txHash,explorerUrl:Lt(s.txHash,r==null?void 0:r.id),executionRate:Wn(s.inAmount,s.outAmount,t==null?void 0:t.decimals,n==null?void 0:n.decimals)})).filter(s=>s.srcToken!==void 0&&s.dstToken!==void 0),[e,t,n,r])},uc=(e,t,n)=>{const{config:r}=q(),s=Oo(t,n,e),a=Io(t,n,e),o=Bo(t,n,e),u=F.useMemo(()=>e?e.version===2?e.fillDelay:r.twapConfig?Hn(e,r.twapConfig):0:0,[e,r]),p=cc(e==null?void 0:e.fills,t,n)??[];return F.useMemo(()=>{if(e!=null&&e.id)return{original:e,fills:p,srcToken:t,dstToken:n,orderType:e.type,createdAt:e.createdAt,deadline:e.deadline||0,totalTrades:e.totalTradesAmount||0,tradeInterval:u,recipient:e.maker||"",srcAmount:e.srcAmount||"",srcAmountUI:Ee(e.srcAmount,t==null?void 0:t.decimals),limitPrice:rt(s,n==null?void 0:n.decimals),limitPriceUI:s||"",sizePerTrade:e.srcAmountPerTrade||"",sizePerTradeUI:Ee(e.srcAmountPerTrade,t==null?void 0:t.decimals),minDestAmountPerTrade:e.dstMinAmountPerTrade||"",minDestAmountPerTradeUI:Ee(e.dstMinAmountPerTrade,n==null?void 0:n.decimals),dstMinAmount:e.dstMinAmountTotal,dstMinAmountUI:Ee(e.dstMinAmountTotal,n==null?void 0:n.decimals),triggerPrice:rt(a,n==null?void 0:n.decimals),triggerPriceUI:a||"",id:e.id,amountInFilled:e.srcAmountFilled,amountInFilledUI:Ee(e.srcAmountFilled,t==null?void 0:t.decimals),amountOutFilled:e.dstAmountFilled,amountOutFilledUI:Ee(e.dstAmountFilled,n==null?void 0:n.decimals),progress:e.progress,executionPrice:rt(o,n==null?void 0:n.decimals),executionPriceUI:o,version:e.version}},[e,p,t,n,u,s,a,o])};za(mi.version),I.DISCLAIMER_URL=da,I.Disclaimer=en,I.InputErrors=me,I.Module=j,I.ORBS_LOGO=ca,I.ORBS_SLTP_FAQ_URL=oa,I.ORBS_TWAP_FAQ_URL=ia,I.ORBS_WEBSITE_URL=ua,I.OrderFilter=Pr,I.OrderStatus=ue,I.OrderType=X,I.Partners=_e,I.SPOT_VERSION=fn,I.SpotProvider=oc,I.Steps=nt,I.SwapStatus=Se,I.TimeUnit=De,I.buildRePermitOrderData=Wr,I.ensureWrappedToken=Jr,I.eqIgnoreCase=gt,I.getConfig=Qn,I.getExplorerUrl=Lt,I.getMinChunkSizeUsd=Hr,I.getNetwork=Et,I.getOrderExecutionRate=Wn,I.getOrderFillDelayMillis=Hn,I.getOrderLimitPriceRate=Nr,I.getOrderType=Ci,I.getPartnerChains=Lr,I.getPartners=Kr,I.getTriggerPriceRate=qr,I.isNativeAddress=Rt,I.isTxRejected=Xn,I.millisToDays=Zn,I.millisToMinutes=En,I.networks=ye,I.parseError=bi,I.shouldUnwrapOnly=Jn,I.shouldWrapOnly=Yn,I.submitOrder=$r,I.toAmountUi=Ee,I.toAmountWei=rt,I.useAmountUi=bt,I.useCancelOrder=Go,I.useDerivedHistoryOrder=uc,I.useExplorerLink=Ti,I.useNetwork=bn,I.useSignOrder=Ds,I.useSpot=Zo,I.useSubmitOrder=Os,I.useSwapExecution=rn,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})}));
|