@orbs-network/spot-react 1.1.42 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/spot-react.js
CHANGED
|
@@ -2747,7 +2747,7 @@ const Mi = async ({
|
|
|
2747
2747
|
partner: a,
|
|
2748
2748
|
isDev: f
|
|
2749
2749
|
}) : Promise.resolve([])
|
|
2750
|
-
]).then(([v, P]) => [...v, ...P])).sort((v, P) => P.createdAt - v.createdAt), qi = "
|
|
2750
|
+
]).then(([v, P]) => [...v, ...P])).sort((v, P) => P.createdAt - v.createdAt), qi = "2.0.1", Hi = {
|
|
2751
2751
|
version: qi
|
|
2752
2752
|
}, Ur = (e) => {
|
|
2753
2753
|
let t;
|
package/dist/spot-react.umd.cjs
CHANGED
|
@@ -61,4 +61,4 @@
|
|
|
61
61
|
dollarValueOut
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
-
`,extractResults:b=>{var x;return(((x=b.data)==null?void 0:x.orderFilleds)||[]).map(v=>({...v,timestamp:new Date(v.timestamp).getTime()}))}})};class pi extends Error{constructor(){super("No graph endpoint found"),this.name="NoGraphEndpointError"}}const mi=async({chainId:e,signal:t,page:n,limit:r,filters:s})=>{try{const a=await li({chainId:e,signal:t,page:n,limit:r,filters:s}),[i,u]=await Promise.all([hi({chainId:e,orders:a,signal:t}),fi({chainId:e,orders:a,signal:t})]),f=a.map(T=>{const b=i==null?void 0:i.filter(x=>x.TWAP_id===Number(T.Contract_id)&>(x.exchange,T.exchange)&>(x.twapAddress,T.twapAddress));return ui(T,e,b,yi(T,b||[],u))}).sort((T,b)=>b.createdAt-T.createdAt),h=new Set;return f.filter(T=>h.has(T.id)?!1:(h.add(T.id),!0))}catch{return[]}},yi=(e,t,n)=>{var u;const r=(u=n==null?void 0:n.find(f=>f.twapId===e.Contract_id.toString()&>(f.twapAddress,e.twapAddress)))==null?void 0:u.status,a=Gr(t).reduce((f,h)=>f.plus(h.inAmount),new D(0)).toFixed(),i=Zr(e.ask_srcAmount,a);return Ai(i,e.ask_deadline*1e3,r)},Zr=(e,t)=>{if(!t||!e)return 0;const n=D(t).dividedBy(e).toNumber();return n>=.99?100:n<=0?0:Number((n*100).toFixed(2))},Ai=(e,t,n)=>e===100?ue.Completed:n==="CANCELLED"?ue.Cancelled:n==="COMPLETED"?ue.Completed:t>Date.now()?ue.Open:ue.Expired,gi=async({signal:e,page:t,chainId:n,limit:r,exchange:s,partner:a,twapConfig:i,account:u,isDev:f=!1,includeV1GraphOrders:h=!0,includeV2Orders:T=!0})=>(await Promise.all([!i||!h?Promise.resolve([]):mi({chainId:n,signal:e,page:t,limit:r,filters:{accounts:[u],configs:[i]}}),T?oi({chainId:n,signal:e,account:u,exchange:s,partner:a,isDev:f}):Promise.resolve([])]).then(([v,O])=>[...v,...O])).sort((v,O)=>O.createdAt-v.createdAt),bi={version:"1.1.42"},Yr=e=>{let t;const n=new Set,r=(h,T)=>{const b=typeof h=="function"?h(t):h;if(!Object.is(b,t)){const x=t;t=T??(typeof b!="object"||b===null)?b:Object.assign({},t,b),n.forEach(v=>v(t,x))}},s=()=>t,u={setState:r,getState:s,getInitialState:()=>f,subscribe:h=>(n.add(h),()=>n.delete(h))},f=t=e(r,s,u);return u},Ei=(e=>e?Yr(e):Yr),xi=e=>e;function Ci(e,t=xi){const n=S.useSyncExternalStore(e.subscribe,S.useCallback(()=>t(e.getState()),[e,t]),S.useCallback(()=>t(e.getInitialState()),[e,t]));return S.useDebugValue(n),n}const Jr=e=>{const t=Ei(e),n=r=>Ci(t,r);return Object.assign(n,t),n},Ti=(e=>e?Jr(e):Jr),wn={},es={currentTime:Date.now(),cancelOrders:{},swapExecutions:[wn],swapExecutionIndex:0},H=Ti((e,t)=>({state:es,updateState:n=>e(r=>({state:{...r.state,...n}})),updateSwapExecutionAtIndex:(n,r)=>e(s=>{const a=[...s.state.swapExecutions];return a[n]={...a[n]??wn,...r},{state:{...s.state,swapExecutions:a}}}),resetSwapExecutionAtIndex:()=>e(n=>{const r=[...n.state.swapExecutions];return r[n.state.swapExecutionIndex]=wn,{state:{...n.state,swapExecutions:r}}}),resetState:()=>{const n=t().state;e({state:{...es,currentTime:Date.now(),isMarketOrder:n.isMarketOrder,swapExecutions:[...n.swapExecutions,wn],swapExecutionIndex:n.swapExecutionIndex+1}})}}));var Ae=(e=>(e[e.LOADING=1]="LOADING",e[e.SUCCESS=2]="SUCCESS",e[e.FAILED=3]="FAILED",e))(Ae||{}),sn=(e=>(e.TRIGGER_MARKET_PRICE="triggerMarketPriceDisclaimer",e.MARKET_PRICE="marketOrderDisclaimer",e.LIMIT_PRICE="limitOrderDisclaimer",e))(sn||{}),rt=(e=>(e.WRAP="wrap",e.APPROVE="approve",e.CREATE="create",e))(rt||{});const st=(e,t)=>t==null||!e||D(e).isNaN()?"":D(e).multipliedBy(D(10).pow(t)).toFixed(0),ge=(e,t)=>{try{return t==null||!e||D(e).isNaN()?"":D(e).dividedBy(D(10).pow(t)).toFixed()}catch(n){return console.error(n),""}},wi=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}},tr=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"))},ts=(e,t)=>{const n=Et(t);return n&&Rt(e.address)?n.wToken:e};function nr(e){return e?e/864e5:0}function Fn(e){return e?e/6e4:0}const Fi=(e,t)=>e?X.TWAP_MARKET:t===1?X.LIMIT:X.TWAP_LIMIT,rr=(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)||"")},sr=(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)||"")},Nt=(e,t)=>{if(!t)return"";const n=Et(t);return n!=null&&n.explorer?`${n.explorer}/tx/${e}`:""},ar=(e,t)=>S.useMemo(()=>st(t,e),[e,t]),xt=(e,t)=>S.useMemo(()=>ge(t,e),[e,t]),Sn=()=>{const{chainId:e}=K();return S.useMemo(()=>Et(e),[e])},Si=e=>{const t=Sn();return S.useMemo(()=>{if(!(!e||!t))return Nt(e,t.id)},[e,t])},qe=(e,t)=>S.useMemo(()=>!e||!t||D(e||"0").isZero()||D(t||"0").isZero()?"":D(e||"0").times(t).toFixed(),[e,t]),Di=()=>{const{srcToken:e,dstToken:t,chainId:n}=K();return S.useMemo(()=>rr(e,t,n),[e,t,n])},vi=()=>{const{srcToken:e,dstToken:t,chainId:n}=K();return S.useMemo(()=>sr(e,t,n),[e,t,n])},Pi=()=>{const e=Di(),t=vi();return e||t},Oi={},Kt=()=>{const e=H(a=>a.state.swapExecutionIndex),t=H(a=>a.state.swapExecutions[a.state.swapExecutionIndex]??Oi),n=H(a=>a.updateSwapExecutionAtIndex),r=H(a=>a.resetSwapExecutionAtIndex),s=S.useCallback(a=>n(e,a),[n,e]);return S.useMemo(()=>({...t,update:s,resetSwap:r}),[t,s,r])},at=()=>{const{srcToken:e,typedInputAmount:t}=K(),n=Kt(),r=ar(e==null?void 0:e.decimals,t),s=n.status===Ae.LOADING&&n.acceptedSrcAmount?n.acceptedSrcAmount:void 0,a=s??r,i=s?ge(s,e==null?void 0:e.decimals):t;return{amount:a,amountUI:i,error:D(a||0).isZero()?"enterAmount":void 0}},Bi=(e,t)=>{const{module:n,srcUsd1Token:r,marketPrice:s,minChunkSizeUsd:a,typedInputAmount:i}=K();return S.useMemo(()=>{if(D(i||"0").isZero()||!s||D(r||"0").isZero())return;if(!e)return{type:me.MIN_CHUNKS,value:1,args:{minChunks:"1"}};const{isError:u}=za(e,t,n);if(u)return{type:me.MAX_CHUNKS,value:t,args:{maxChunks:`${t}`}};const{isError:f,value:h}=Wa(i||"",r||"",a||0);if(f)return{type:me.MIN_TRADE_SIZE,value:h,args:{minTradeSize:`${h}`}}},[e,t,n,i,r,a,s])},He=()=>{const{srcToken:e,srcUsd1Token:t,module:n,minChunkSizeUsd:r}=K(),s=H(O=>O.state.typedChunks),a=H(O=>O.updateState),{amount:i,amountUI:u}=at(),f=S.useMemo(()=>Ia(u||"",t||"",r||0),[u,t,r]),h=S.useMemo(()=>Ba(f,n,s),[f,s,n]),T=S.useCallback(O=>a({typedChunks:O}),[a]),b=S.useMemo(()=>_a(i||"",h),[i,h]),x=xt(e==null?void 0:e.decimals,b),v=S.useMemo(()=>t?D(x||"0").times(t||0).toString():"0",[x,t]);return{totalTrades:h,maxTrades:f,amountPerTradeUI:x,amountPerTrade:b,amountPerTradeUsd:v,onChange:T,error:Bi(h,f)}},Ii=()=>{const{srcToken:e,dstToken:t}=K(),{onChange:n,totalTrades:r,amountPerTradeUsd:s,amountPerTradeUI:a,error:i,maxTrades:u,amountPerTrade:f}=He();return{error:i,maxTrades:u,totalTrades:r,amountPerTradeUI:a,amountPerTrade:f,onChange:n,amountPerTradeUsd:s,fromToken:e,toToken:t}},ns=e=>{const t=nr(e);if(t>=1)return`${t.toFixed(t%1?1:0)} ${t===1?"day":"days"}`;const n=Fn(e)/60;if(n>=1)return`${n.toFixed(n%1?1:0)} ${n===1?"hour":"hours"}`;const r=Fn(e);return`${r.toFixed(r%1?1:0)} ${r===1?"minute":"minutes"}`},Mi=e=>{const{totalTrades:t}=He(),{marketPrice:n,typedInputAmount:r}=K(),s=S.useMemo(()=>{const{isError:i,value:u}=$a(e);if(!(!i||D(r||"0").isZero()||!n))return{type:me.MIN_FILL_DELAY,value:u,args:{fillDelay:ns(u)}}},[e,r,n]),a=S.useMemo(()=>{const{isError:i,value:u}=Ua(e,t);if(!(!i||D(r||"0").isZero()||!n))return{type:me.MAX_FILL_DELAY,value:u,args:{fillDelay:ns(u)}}},[e,r,n,t]);return s||a},qt=()=>{const{callbacks:e}=K(),t=H(a=>a.state.typedFillDelay),n=H(a=>a.updateState),r=S.useMemo(()=>t||Wn,[t]),s=Mi(r);return{fillDelay:r,onChange:S.useCallback(a=>{var i;n({typedFillDelay:a}),(i=e==null?void 0:e.onFillDelayChange)==null||i.call(e,a)},[n,e]),error:s,milliseconds:r.unit*r.value}},ki=()=>{const{onChange:e,fillDelay:t,error:n}=qt(),r=S.useCallback(a=>e({unit:t.unit,value:Number(a)}),[e,t]),s=S.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}},_i=e=>{const{module:t,marketPrice:n}=K();return S.useMemo(()=>{const r=qa(t,e),s=Ha(e);if(n){if(r.isError)return{type:me.MAX_ORDER_DURATION,value:r.value,args:{duration:`${Math.floor(nr(r.value)).toFixed(0)} days`}};if(s.isError)return{type:me.MIN_ORDER_DURATION,value:s.value,args:{duration:`${Math.floor(Fn(s.value)).toFixed(0)} minutes`}}}},[e,t,n])},ir=()=>{const{module:e,callbacks:t}=K(),n=H(f=>f.state.typedDuration),r=H(f=>f.updateState),s=He().totalTrades,a=qt().fillDelay,i=S.useMemo(()=>Oa(e,s,a,n),[s,a,n,e]),u=_i(i);return{duration:i,setDuration:S.useCallback(f=>{var h;r({typedDuration:f}),(h=t==null?void 0:t.onDurationChange)==null||h.call(t,f)},[r,t]),error:u}},Ui=()=>{const{duration:e,setDuration:t,error:n}=ir(),r=S.useCallback(a=>{t({unit:e.unit,value:Number(a)})},[t,e]),s=S.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}},Li=()=>{const{module:e}=K();return S.useMemo(()=>e===G.STOP_LOSS?pa:ma,[e])},or=()=>{const{module:e}=K(),t=H(n=>n.state.isMarketOrder);return S.useMemo(()=>e!==G.STOP_LOSS&&e!==G.TAKE_PROFIT||t?void 0:e===G.STOP_LOSS?ya:Aa,[e,t])},rs=e=>{if(e===void 0||e==="")return e;const t=D(e);return t.isNaN()||t.isZero()?"0":D(1).div(t).toFixed()},Dn=()=>{const{srcToken:e,dstToken:t}=K(),n=H(f=>f.updateState),r=H(f=>f.state.isInvertedTrade),s=H(f=>f.state.typedTriggerPrice),a=H(f=>f.state.typedLimitPrice),i=H(f=>f.state.isMarketOrder);return{onInvert:S.useCallback(()=>{n({isInvertedTrade:!r,...s!==void 0?{typedTriggerPrice:rs(s)}:{},...a!==void 0?{typedLimitPrice:rs(a)}:{}})},[n,r,s,a]),isInverted:r,fromToken:r?t:e,toToken:r?e:t,isMarketPrice:i}},vn=e=>e?D(e).isNaN()?"":e:"",ss=({amount:e,typedValue:t,amountDecimals:n=18,invertedAmountDecimals:r=18,amountUsd:s,invertedAmountUsd:a,isInverted:i})=>{const u=S.useMemo(()=>{if(t!==void 0)return vn(t);const T=ge(e,n);return!T||D(T||"0").isZero()?"":i?D(1).div(T).toFixed():T},[e,n,i,t]),f=S.useMemo(()=>u?vn(i?st(u,r):e):"",[e,u,r,i]),h=qe(u||"0",i?a:s);return{amount:f,amountUI:u,usd:vn(h)}},as=({typedValue:e,tokenDecimals:t=18,initialPrice:n="0",percentage:r,setValue:s,setPercentage:a})=>{const{isInverted:i}=Dn(),u=S.useMemo(()=>D((()=>{if(e!==void 0){const x=i?D(e).isZero()?D(0):D(1).div(e):D(e);return st(x.toFixed(),t)}if(r!==void 0&&D(n||"0").gt(0)&&!D(n||"0").isNaN()){const x=D(n||"0"),v=D(r||0).div(100);return x.plus(x.multipliedBy(v)).decimalPlaces(0).toFixed()}return D(n).gt(0)?n:""})()).decimalPlaces(0).toFixed(),[e,r,t,n,i]),f=S.useCallback(b=>{s(b),a(null)},[s,a]),h=S.useCallback(b=>{s(void 0),a(b)},[s,a]),T=S.useMemo(()=>{if(!n||D(n).isZero())return"";if(r!=null)return r;if(u){const b=D(n),v=D(u).minus(b).div(b).multipliedBy(100).decimalPlaces(2).toString();return D(v||"0").isZero()?"":v}return""},[u,n,r]);return{amount:D(u).isNaN()?"":u,typedValue:e,selectedPercentage:T,onChange:f,onPercentageChange:h,isTypedValue:e!==void 0}},Ri=(e="")=>{const{module:t,marketPrice:n,typedInputAmount:r}=K();return S.useMemo(()=>{if(D(r||"0").isZero()||!n||t!==G.STOP_LOSS&&t!==G.TAKE_PROFIT)return;const s=La(n||"",e||"",t);if(s!=null&&s.isError)return{type:me.STOP_LOSS_TRIGGER_PRICE_GREATER_THAN_MARKET_PRICE,value:s.value};const a=Ra(n||"",e||"",t);if(a!=null&&a.isError)return{type:me.TAKE_PROFIT_TRIGGER_PRICE_LESS_THAN_MARKET_PRICE,value:a.value};if(!e||D(e||0).isZero())return{type:me.EMPTY_TRIGGER_PRICE,value:e}},[n,e,t,r])},Ni=e=>{const{srcToken:t,dstToken:n,module:r,dstUsd1Token:s}=K(),a=He().amountPerTrade,i=H(h=>h.state.isMarketOrder),u=S.useMemo(()=>Pa(r,a,e,(t==null?void 0:t.decimals)||0),[e,a,i,t==null?void 0:t.decimals,r]),f=xt((n==null?void 0:n.decimals)||0,u);return{amount:u,amountUI:f,usd:qe(f,s)}},Ct=()=>{const{dstToken:e,dstUsd1Token:t,marketPrice:n,module:r,callbacks:s}=K(),a=H(_=>_.updateState),i=Li(),u=H(_=>_.state.triggerPricePercent),f=u===void 0?i:u,h=r===G.STOP_LOSS||r===G.TAKE_PROFIT,T=as({typedValue:H(_=>_.state.typedTriggerPrice),percentage:f,tokenDecimals:(e==null?void 0:e.decimals)||18,initialPrice:h?n:void 0,setValue:S.useCallback(_=>{var F;a({typedTriggerPrice:_}),(F=s==null?void 0:s.onTriggerPriceChange)==null||F.call(s,_||"")},[a,s]),setPercentage:S.useCallback(_=>{var F;a({triggerPricePercent:_}),(F=s==null?void 0:s.onTriggerPricePercentChange)==null||F.call(s,_||"")},[a,s])}),b=Ri(T.amount),x=xt((e==null?void 0:e.decimals)||18,T.amount),v=qe(x,t),{amount:O,amountUI:I,usd:B}=Ni(T.amount);return S.useMemo(()=>({...T,amountUI:D(x).isNaN()?"":x,usd:D(v).isNaN()?"":v,error:b,pricePerChunk:O,pricePerChunkUI:I,pricePerChunkUsd:B}),[T,x,v,b,O,I,B])},Ki=e=>{const{module:t,marketPrice:n,typedInputAmount:r}=K(),{amount:s}=Ct(),a=H(i=>i.state.isMarketOrder);return S.useMemo(()=>{if(D(r||"0").isZero()||!s||!n)return;const i=Na(s,e,a,t),u=Ka(s,e,a,t);if(i!=null&&i.isError)return{type:me.TRIGGER_LIMIT_PRICE_GREATER_THAN_TRIGGER_PRICE,value:i.value};if(u!=null&&u.isError)return{type:me.TRIGGER_LIMIT_PRICE_GREATER_THAN_TRIGGER_PRICE,value:u.value};if(e&&D(e||0).isZero())return{type:me.MISSING_LIMIT_PRICE,value:e||""}},[e,s,t,a,r,n])},Pn=()=>{const{dstToken:e,dstUsd1Token:t,marketPrice:n,callbacks:r}=K(),s=H(x=>x.updateState),a=or(),i=H(x=>x.state.limitPricePercent),u=i===void 0?a:i,f=as({typedValue:H(x=>x.state.typedLimitPrice),percentage:u,tokenDecimals:(e==null?void 0:e.decimals)||18,initialPrice:n,setValue:S.useCallback(x=>{var v;s({typedLimitPrice:x}),(v=r==null?void 0:r.onLimitPriceChange)==null||v.call(r,x||"")},[s,r]),setPercentage:S.useCallback(x=>{var v;s({limitPricePercent:x}),(v=r==null?void 0:r.onLimitPricePercentChange)==null||v.call(r,x||"")},[s,r])}),h=Ki(f.amount),T=xt((e==null?void 0:e.decimals)||18,f.amount),b=qe(T,t);return S.useMemo(()=>({...f,amountUI:D(T).isNaN()?"":T,usd:D(b).isNaN()?"":b,error:h}),[f,T,b,h])},qi=()=>{const{module:e}=K(),t=H(u=>u.updateState),n=H(u=>u.state.isMarketOrder),r=or(),s=H(u=>u.state.triggerPricePercent)||0,a=e===G.LIMIT,i=S.useCallback(()=>{!n&&e===G.STOP_LOSS&&t({limitPricePercent:r}),t({isMarketOrder:!n})},[t,s,e,n,r]);return{isLimitPrice:!n,toggleLimitPrice:i,hide:a}},Hi=()=>{const{module:e,marketPriceLoading:t,srcToken:n,dstToken:r,srcUsd1Token:s,dstUsd1Token:a}=K(),{amount:i,typedValue:u,onChange:f,onPercentageChange:h,selectedPercentage:T,error:b,isTypedValue:x}=Pn(),v=H(z=>z.updateState),O=or(),{isLimitPrice:I,toggleLimitPrice:B}=qi(),{fromToken:_,toToken:F,isInverted:q}=Dn(),k=ss({amount:i,typedValue:u,amountDecimals:(r==null?void 0:r.decimals)||18,invertedAmountDecimals:(n==null?void 0:n.decimals)||18,amountUsd:a,invertedAmountUsd:s,isInverted:q}),Q=S.useCallback(()=>{v({typedLimitPrice:void 0}),v({limitPricePercent:O})},[v,e,O]);return{price:k.amount,priceUI:k.amountUI,error:b,onInputChange:f,onPercentageChange:h,onReset:Q,usd:k.usd,srcToken:n,dstToken:r,invertedSrcToken:_,invertedDstToken:F,percentage:T,isLoading:t,isLimitPrice:I,toggleLimitPrice:B,isTypedValue:x}},$i=()=>{const{marketPrice:e,marketPriceLoading:t,srcToken:n,dstToken:r,srcUsd1Token:s,dstUsd1Token:a}=K(),{amount:i,typedValue:u,onChange:f,onPercentageChange:h,selectedPercentage:T,error:b,pricePerChunk:x,pricePerChunkUI:v,pricePerChunkUsd:O,isTypedValue:I}=Ct(),B=H(z=>z.updateState),{fromToken:_,toToken:F,isInverted:q}=Dn(),k=ss({amount:i,typedValue:u,amountDecimals:(r==null?void 0:r.decimals)||18,invertedAmountDecimals:(n==null?void 0:n.decimals)||18,amountUsd:a,invertedAmountUsd:s,isInverted:q}),Q=S.useCallback(()=>{B({triggerPricePercent:void 0,typedTriggerPrice:void 0})},[B]);return{price:k.amount,priceUI:k.amountUI,amountPerChunk:x,amountPerChunkUI:v,amountPerChunkUsd:O,error:b,onInputChange:f,onPercentageChange:h,percentage:T,onReset:Q,usd:k.usd,srcToken:n,dstToken:r,invertedSrcToken:_,invertedDstToken:F,isLoading:t||!e,isTypedValue:I}},is=()=>{const{module:e,marketPrice:t}=K(),n=Pn().amount,r=Ct().amount,s=H(a=>a.state.isMarketOrder);return e===G.LIMIT||!s?n||"":e===G.STOP_LOSS||e===G.TAKE_PROFIT?r||"":t||""},On=()=>{const{srcToken:e,dstToken:t,dstUsd1Token:n}=K(),r=is(),s=at().amount,a=S.useMemo(()=>Da(s||"",r,(e==null?void 0:e.decimals)||0),[s,r,e==null?void 0:e.decimals]),i=xt(t==null?void 0:t.decimals,a);return{amount:a,amountUI:i,usd:qe(i,n)}},cr=()=>{const{srcToken:e,dstToken:t,dstUsd1Token:n}=K(),r=is(),s=He().amountPerTrade,a=H(f=>f.state.isMarketOrder),i=S.useMemo(()=>va(s,r,!!a,(e==null?void 0:e.decimals)||0),[s,r,a,e==null?void 0:e.decimals]),u=xt(t==null?void 0:t.decimals,i);return{amount:i,amountUI:u,usd:qe(u,n)}},Wi=()=>{const{typedInputAmount:e,marketPriceLoading:t,dstToken:n}=K(),{amountUI:r,usd:s}=On(),i=Pi()?e:r,u=ar(n==null?void 0:n.decimals,i);return{value:i,valueWei:u,isLoading:t,usd:s}},zi=()=>{const e=H(s=>s.state.isMarketOrder),{module:t}=K(),n=S.useMemo(()=>{if(e&&t===G.STOP_LOSS)return sn.TRIGGER_MARKET_PRICE},[e,t]),r=S.useMemo(()=>{if(!(t!==G.LIMIT&&t!==G.TWAP))return e?sn.MARKET_PRICE:sn.LIMIT_PRICE},[e,t]);return n||r},Qi=()=>{const{minChunkSizeUsd:e,typedInputAmount:t,srcUsd1Token:n}=K(),r=qe(t,n);return S.useMemo(()=>{if(!(!D(t||0).gt(0)||!r))return D(e).gt(D(r))?{type:me.MIN_TRADE_SIZE_ERROR,value:e,args:{minTradeSize:`${e}`}}:void 0},[e,t,r])};function os(){const{marketPrice:e,marketPriceLoading:t,typedInputAmount:n,srcUsd1Token:r,srcBalance:s,chainId:a}=K(),{error:i}=Ct(),{error:u}=Pn(),{error:f}=He(),{error:h}=qt(),{error:T}=ir(),b=Qi(),x=at().amount,v=S.useMemo(()=>{if(s&&D(x).gt(s))return{type:me.INSUFFICIENT_BALANCE,value:s||""}},[s,x,a]);return S.useMemo(()=>Qa({marketPrice:e,typedInputAmount:n,srcUsd1Token:r,marketPriceLoading:t,triggerPriceError:i,limitPriceError:u,tradesError:f,fillDelayError:h,durationError:T,balanceError:v,minTradeSizeError:b}),[e,t,n,i,u,f,h,T,v,r,b])}var Ht=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(){}},ji={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Vi=(Rs=class{constructor(){N(this,$e,ji);N(this,St,!1)}setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&l(this,St)&&e!==l(this,$e)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:l(this,$e),provider:e}),U(this,$e,e),process.env.NODE_ENV!=="production"&&U(this,St,!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&U(this,St,!0),l(this,$e).setTimeout(e,t)}clearTimeout(e){l(this,$e).clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&U(this,St,!0),l(this,$e).setInterval(e,t)}clearInterval(e){l(this,$e).clearInterval(e)}},$e=new WeakMap,St=new WeakMap,Rs),Tt=new Vi;function Gi(e){setTimeout(e,0)}var wt=typeof window>"u"||"Deno"in globalThis;function xe(){}function Xi(e,t){return typeof e=="function"?e(t):e}function ur(e){return typeof e=="number"&&e>=0&&e!==1/0}function cs(e,t){return Math.max(e+(t||0)-Date.now(),0)}function it(e,t){return typeof e=="function"?e(t):e}function Me(e,t){return typeof e=="function"?e(t):e}function us(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:a,queryKey:i,stale:u}=e;if(i){if(r){if(t.queryHash!==dr(i,t.options))return!1}else if(!an(t.queryKey,i))return!1}if(n!=="all"){const f=t.isActive();if(n==="active"&&!f||n==="inactive"&&f)return!1}return!(typeof u=="boolean"&&t.isStale()!==u||s&&s!==t.state.fetchStatus||a&&!a(t))}function ds(e,t){const{exact:n,status:r,predicate:s,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Ft(t.options.mutationKey)!==Ft(a))return!1}else if(!an(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function dr(e,t){return((t==null?void 0:t.queryKeyHashFn)||Ft)(e)}function Ft(e){return JSON.stringify(e,(t,n)=>fr(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function an(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>an(e[n],t[n])):!1}var Zi=Object.prototype.hasOwnProperty;function lr(e,t){if(e===t)return e;const n=ls(e)&&ls(t);if(!n&&!(fr(e)&&fr(t)))return t;const s=(n?e:Object.keys(e)).length,a=n?t:Object.keys(t),i=a.length,u=n?new Array(i):{};let f=0;for(let h=0;h<i;h++){const T=n?h:a[h],b=e[T],x=t[T];if(b===x){u[T]=b,(n?h<s:Zi.call(e,T))&&f++;continue}if(b===null||x===null||typeof b!="object"||typeof x!="object"){u[T]=x;continue}const v=lr(b,x);u[T]=v,v===b&&f++}return s===i&&f===s?e:u}function Bn(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 ls(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function fr(e){if(!fs(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!fs(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function fs(e){return Object.prototype.toString.call(e)==="[object Object]"}function Yi(e){return new Promise(t=>{Tt.setTimeout(t,e)})}function hr(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 lr(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 lr(e,t)}return t}function Ji(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function eo(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var In=Symbol();function hs(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===In&&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===In?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ps(e,t){return typeof e=="function"?e(...t):!!e}var to=(Ns=class extends Ht{constructor(){super();N(this,Dt);N(this,ct);N(this,Wt);U(this,Wt,t=>{if(!wt&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,ct)||this.setEventListener(l(this,Wt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ct))==null||t.call(this),U(this,ct,void 0))}setEventListener(t){var n;U(this,Wt,t),(n=l(this,ct))==null||n.call(this),U(this,ct,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,Dt)!==t&&(U(this,Dt,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof l(this,Dt)=="boolean"?l(this,Dt):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Dt=new WeakMap,ct=new WeakMap,Wt=new WeakMap,Ns),pr=new to;function mr(){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 no=Gi;function ro(){let e=[],t=0,n=u=>{u()},r=u=>{u()},s=no;const a=u=>{t?e.push(u):s(()=>{n(u)})},i=()=>{const u=e;e=[],u.length&&s(()=>{r(()=>{u.forEach(f=>{n(f)})})})};return{batch:u=>{let f;t++;try{f=u()}finally{t--,t||i()}return f},batchCalls:u=>(...f)=>{a(()=>{u(...f)})},schedule:a,setNotifyFunction:u=>{n=u},setBatchNotifyFunction:u=>{r=u},setScheduler:u=>{s=u}}}var le=ro(),so=(Ks=class extends Ht{constructor(){super();N(this,zt,!0);N(this,ut);N(this,Qt);U(this,Qt,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,ut)||this.setEventListener(l(this,Qt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ut))==null||t.call(this),U(this,ut,void 0))}setEventListener(t){var n;U(this,Qt,t),(n=l(this,ut))==null||n.call(this),U(this,ut,t(this.setOnline.bind(this)))}setOnline(t){l(this,zt)!==t&&(U(this,zt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,zt)}},zt=new WeakMap,ut=new WeakMap,Qt=new WeakMap,Ks),Mn=new so;function ao(e){return Math.min(1e3*2**e,3e4)}function ms(e){return(e??"online")==="online"?Mn.isOnline():!0}var yr=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function ys(e){let t=!1,n=0,r;const s=mr(),a=()=>s.status!=="pending",i=I=>{var B;if(!a()){const _=new yr(I);x(_),(B=e.onCancel)==null||B.call(e,_)}},u=()=>{t=!0},f=()=>{t=!1},h=()=>pr.isFocused()&&(e.networkMode==="always"||Mn.isOnline())&&e.canRun(),T=()=>ms(e.networkMode)&&e.canRun(),b=I=>{a()||(r==null||r(),s.resolve(I))},x=I=>{a()||(r==null||r(),s.reject(I))},v=()=>new Promise(I=>{var B;r=_=>{(a()||h())&&I(_)},(B=e.onPause)==null||B.call(e)}).then(()=>{var I;r=void 0,a()||(I=e.onContinue)==null||I.call(e)}),O=()=>{if(a())return;let I;const B=n===0?e.initialPromise:void 0;try{I=B??e.fn()}catch(_){I=Promise.reject(_)}Promise.resolve(I).then(b).catch(_=>{var z;if(a())return;const F=e.retry??(wt?0:3),q=e.retryDelay??ao,k=typeof q=="function"?q(n,_):q,Q=F===!0||typeof F=="number"&&n<F||typeof F=="function"&&F(n,_);if(t||!Q){x(_);return}n++,(z=e.onFail)==null||z.call(e,n,_),Yi(k).then(()=>h()?void 0:v()).then(()=>{t?x(_):O()})})};return{promise:s,status:()=>s.status,cancel:i,continue:()=>(r==null||r(),s),cancelRetry:u,continueRetry:f,canStart:T,start:()=>(T()?O():v().then(O),s)}}var As=(qs=class{constructor(){N(this,vt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ur(this.gcTime)&&U(this,vt,Tt.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(wt?1/0:300*1e3))}clearGcTimeout(){l(this,vt)&&(Tt.clearTimeout(l(this,vt)),U(this,vt,void 0))}},vt=new WeakMap,qs),io=(Hs=class extends As{constructor(t){super();N(this,Ne);N(this,Pt);N(this,jt);N(this,ke);N(this,Ot);N(this,pe);N(this,on);N(this,Bt);U(this,Bt,!1),U(this,on,t.defaultOptions),this.setOptions(t.options),this.observers=[],U(this,Ot,t.client),U(this,ke,l(this,Ot).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,U(this,Pt,Es(this.options)),this.state=t.state??l(this,Pt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=l(this,pe))==null?void 0:t.promise}setOptions(t){if(this.options={...l(this,on),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=Es(this.options);n.data!==void 0&&(this.setState(bs(n.data,n.dataUpdatedAt)),U(this,Pt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,ke).remove(this)}setData(t,n){const r=hr(this.state.data,t,this.options);return j(this,Ne,tt).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){j(this,Ne,tt).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,s;const n=(r=l(this,pe))==null?void 0:r.promise;return(s=l(this,pe))==null||s.cancel(t),n?n.then(xe).catch(xe):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(l(this,Pt))}isActive(){return this.observers.some(t=>Me(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===In||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>it(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:!cs(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=l(this,pe))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=l(this,pe))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,ke).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,pe)&&(l(this,Bt)?l(this,pe).cancel({revert:!0}):l(this,pe).cancelRetry()),this.scheduleGc()),l(this,ke).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||j(this,Ne,tt).call(this,{type:"invalidate"})}async fetch(t,n){var f,h,T,b,x,v,O,I,B,_,F,q;if(this.state.fetchStatus!=="idle"&&((f=l(this,pe))==null?void 0:f.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(l(this,pe))return l(this,pe).continueRetry(),l(this,pe).promise}if(t&&this.setOptions(t),!this.options.queryFn){const k=this.observers.find(Q=>Q.options.queryFn);k&&this.setOptions(k.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=k=>{Object.defineProperty(k,"signal",{enumerable:!0,get:()=>(U(this,Bt,!0),r.signal)})},a=()=>{const k=hs(this.options,n),z=(()=>{const re={client:l(this,Ot),queryKey:this.queryKey,meta:this.meta};return s(re),re})();return U(this,Bt,!1),this.options.persister?this.options.persister(k,z,this):k(z)},u=(()=>{const k={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:l(this,Ot),state:this.state,fetchFn:a};return s(k),k})();(h=this.options.behavior)==null||h.onFetch(u,this),U(this,jt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((T=u.fetchOptions)==null?void 0:T.meta))&&j(this,Ne,tt).call(this,{type:"fetch",meta:(b=u.fetchOptions)==null?void 0:b.meta}),U(this,pe,ys({initialPromise:n==null?void 0:n.initialPromise,fn:u.fetchFn,onCancel:k=>{k instanceof yr&&k.revert&&this.setState({...l(this,jt),fetchStatus:"idle"}),r.abort()},onFail:(k,Q)=>{j(this,Ne,tt).call(this,{type:"failed",failureCount:k,error:Q})},onPause:()=>{j(this,Ne,tt).call(this,{type:"pause"})},onContinue:()=>{j(this,Ne,tt).call(this,{type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0}));try{const k=await l(this,pe).start();if(k===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(k),(v=(x=l(this,ke).config).onSuccess)==null||v.call(x,k,this),(I=(O=l(this,ke).config).onSettled)==null||I.call(O,k,this.state.error,this),k}catch(k){if(k instanceof yr){if(k.silent)return l(this,pe).promise;if(k.revert){if(this.state.data===void 0)throw k;return this.state.data}}throw j(this,Ne,tt).call(this,{type:"error",error:k}),(_=(B=l(this,ke).config).onError)==null||_.call(B,k,this),(q=(F=l(this,ke).config).onSettled)==null||q.call(F,this.state.data,k,this),k}finally{this.scheduleGc()}}},Pt=new WeakMap,jt=new WeakMap,ke=new WeakMap,Ot=new WeakMap,pe=new WeakMap,on=new WeakMap,Bt=new WeakMap,Ne=new WeakSet,tt=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,...gs(r.data,this.options),fetchMeta:t.meta??null};case"success":const s={...r,...bs(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return U(this,jt,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),le.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),l(this,ke).notify({query:this,type:"updated",action:t})})},Hs);function gs(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ms(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function bs(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Es(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 oo=($s=class extends Ht{constructor(t,n){super();N(this,ee);N(this,Se);N(this,Y);N(this,cn);N(this,Ce);N(this,It);N(this,Vt);N(this,Xe);N(this,dt);N(this,un);N(this,Gt);N(this,Xt);N(this,Mt);N(this,kt);N(this,lt);N(this,Zt,new Set);this.options=n,U(this,Se,t),U(this,dt,null),U(this,Xe,mr()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,Y).addObserver(this),xs(l(this,Y),this.options)?j(this,ee,hn).call(this):this.updateResult(),j(this,ee,vr).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ar(l(this,Y),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ar(l(this,Y),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,j(this,ee,Pr).call(this),j(this,ee,Or).call(this),l(this,Y).removeObserver(this)}setOptions(t){const n=this.options,r=l(this,Y);if(this.options=l(this,Se).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Me(this.options.enabled,l(this,Y))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");j(this,ee,Br).call(this),l(this,Y).setOptions(this.options),n._defaulted&&!Bn(this.options,n)&&l(this,Se).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,Y),observer:this});const s=this.hasListeners();s&&Cs(l(this,Y),r,this.options,n)&&j(this,ee,hn).call(this),this.updateResult(),s&&(l(this,Y)!==r||Me(this.options.enabled,l(this,Y))!==Me(n.enabled,l(this,Y))||it(this.options.staleTime,l(this,Y))!==it(n.staleTime,l(this,Y)))&&j(this,ee,Fr).call(this);const a=j(this,ee,Sr).call(this);s&&(l(this,Y)!==r||Me(this.options.enabled,l(this,Y))!==Me(n.enabled,l(this,Y))||a!==l(this,lt))&&j(this,ee,Dr).call(this,a)}getOptimisticResult(t){const n=l(this,Se).getQueryCache().build(l(this,Se),t),r=this.createResult(n,t);return uo(this,r)&&(U(this,Ce,r),U(this,Vt,this.options),U(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,Xe).status==="pending"&&l(this,Xe).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,Zt).add(t)}getCurrentQuery(){return l(this,Y)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=l(this,Se).defaultQueryOptions(t),r=l(this,Se).getQueryCache().build(l(this,Se),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return j(this,ee,hn).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),i=l(this,It),u=l(this,Vt),h=t!==r?t.state:l(this,cn),{state:T}=t;let b={...T},x=!1,v;if(n._optimisticResults){const d=this.hasListeners(),g=!d&&xs(t,n),m=d&&Cs(t,r,n,s);(g||m)&&(b={...b,...gs(T.data,t.options)}),n._optimisticResults==="isRestoring"&&(b.fetchStatus="idle")}let{error:O,errorUpdatedAt:I,status:B}=b;v=b.data;let _=!1;if(n.placeholderData!==void 0&&v===void 0&&B==="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,Xt))==null?void 0:c.state.data,l(this,Xt)):n.placeholderData,d!==void 0&&(B="success",v=hr(a==null?void 0:a.data,d,n),x=!0)}if(n.select&&v!==void 0&&!_)if(a&&v===(i==null?void 0:i.data)&&n.select===l(this,un))v=l(this,Gt);else try{U(this,un,n.select),v=n.select(v),v=hr(a==null?void 0:a.data,v,n),U(this,Gt,v),U(this,dt,null)}catch(d){U(this,dt,d)}l(this,dt)&&(O=l(this,dt),v=l(this,Gt),I=Date.now(),B="error");const F=b.fetchStatus==="fetching",q=B==="pending",k=B==="error",Q=q&&F,z=v!==void 0,o={status:B,fetchStatus:b.fetchStatus,isPending:q,isSuccess:B==="success",isError:k,isInitialLoading:Q,isLoading:Q,data:v,dataUpdatedAt:b.dataUpdatedAt,error:O,errorUpdatedAt:I,failureCount:b.fetchFailureCount,failureReason:b.fetchFailureReason,errorUpdateCount:b.errorUpdateCount,isFetched:b.dataUpdateCount>0||b.errorUpdateCount>0,isFetchedAfterMount:b.dataUpdateCount>h.dataUpdateCount||b.errorUpdateCount>h.errorUpdateCount,isFetching:F,isRefetching:F&&!q,isLoadingError:k&&!z,isPaused:b.fetchStatus==="paused",isPlaceholderData:x,isRefetchError:k&&z,isStale:gr(t,n),refetch:this.refetch,promise:l(this,Xe),isEnabled:Me(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const d=y=>{o.status==="error"?y.reject(o.error):o.data!==void 0&&y.resolve(o.data)},g=()=>{const y=U(this,Xe,o.promise=mr());d(y)},m=l(this,Xe);switch(m.status){case"pending":t.queryHash===r.queryHash&&d(m);break;case"fulfilled":(o.status==="error"||o.data!==m.value)&&g();break;case"rejected":(o.status!=="error"||o.error!==m.reason)&&g();break}}return o}updateResult(){const t=l(this,Ce),n=this.createResult(l(this,Y),this.options);if(U(this,It,l(this,Y).state),U(this,Vt,this.options),l(this,It).data!==void 0&&U(this,Xt,l(this,Y)),Bn(n,t))return;U(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,Zt).size)return!0;const i=new Set(a??l(this,Zt));return this.options.throwOnError&&i.add("error"),Object.keys(l(this,Ce)).some(u=>{const f=u;return l(this,Ce)[f]!==t[f]&&i.has(f)})};j(this,ee,Xs).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&j(this,ee,vr).call(this)}},Se=new WeakMap,Y=new WeakMap,cn=new WeakMap,Ce=new WeakMap,It=new WeakMap,Vt=new WeakMap,Xe=new WeakMap,dt=new WeakMap,un=new WeakMap,Gt=new WeakMap,Xt=new WeakMap,Mt=new WeakMap,kt=new WeakMap,lt=new WeakMap,Zt=new WeakMap,ee=new WeakSet,hn=function(t){j(this,ee,Br).call(this);let n=l(this,Y).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(xe)),n},Fr=function(){j(this,ee,Pr).call(this);const t=it(this.options.staleTime,l(this,Y));if(wt||l(this,Ce).isStale||!ur(t))return;const r=cs(l(this,Ce).dataUpdatedAt,t)+1;U(this,Mt,Tt.setTimeout(()=>{l(this,Ce).isStale||this.updateResult()},r))},Sr=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,Y)):this.options.refetchInterval)??!1},Dr=function(t){j(this,ee,Or).call(this),U(this,lt,t),!(wt||Me(this.options.enabled,l(this,Y))===!1||!ur(l(this,lt))||l(this,lt)===0)&&U(this,kt,Tt.setInterval(()=>{(this.options.refetchIntervalInBackground||pr.isFocused())&&j(this,ee,hn).call(this)},l(this,lt)))},vr=function(){j(this,ee,Fr).call(this),j(this,ee,Dr).call(this,j(this,ee,Sr).call(this))},Pr=function(){l(this,Mt)&&(Tt.clearTimeout(l(this,Mt)),U(this,Mt,void 0))},Or=function(){l(this,kt)&&(Tt.clearInterval(l(this,kt)),U(this,kt,void 0))},Br=function(){const t=l(this,Se).getQueryCache().build(l(this,Se),this.options);if(t===l(this,Y))return;const n=l(this,Y);U(this,Y,t),U(this,cn,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},Xs=function(t){le.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,Ce))}),l(this,Se).getQueryCache().notify({query:l(this,Y),type:"observerResultsUpdated"})})},$s);function co(e,t){return Me(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function xs(e,t){return co(e,t)||e.state.data!==void 0&&Ar(e,t,t.refetchOnMount)}function Ar(e,t,n){if(Me(t.enabled,e)!==!1&&it(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&gr(e,t)}return!1}function Cs(e,t,n,r){return(e!==t||Me(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&gr(e,n)}function gr(e,t){return Me(t.enabled,e)!==!1&&e.isStaleByTime(it(t.staleTime,e))}function uo(e,t){return!Bn(e.getCurrentResult(),t)}function Ts(e){return{onFetch:(t,n)=>{var T,b,x,v,O;const r=t.options,s=(x=(b=(T=t.fetchOptions)==null?void 0:T.meta)==null?void 0:b.fetchMore)==null?void 0:x.direction,a=((v=t.state.data)==null?void 0:v.pages)||[],i=((O=t.state.data)==null?void 0:O.pageParams)||[];let u={pages:[],pageParams:[]},f=0;const h=async()=>{let I=!1;const B=q=>{Object.defineProperty(q,"signal",{enumerable:!0,get:()=>(t.signal.aborted?I=!0:t.signal.addEventListener("abort",()=>{I=!0}),t.signal)})},_=hs(t.options,t.fetchOptions),F=async(q,k,Q)=>{if(I)return Promise.reject();if(k==null&&q.pages.length)return Promise.resolve(q);const re=(()=>{const g={client:t.client,queryKey:t.queryKey,pageParam:k,direction:Q?"backward":"forward",meta:t.options.meta};return B(g),g})(),o=await _(re),{maxPages:c}=t.options,d=Q?eo:Ji;return{pages:d(q.pages,o,c),pageParams:d(q.pageParams,k,c)}};if(s&&a.length){const q=s==="backward",k=q?lo:ws,Q={pages:a,pageParams:i},z=k(r,Q);u=await F(Q,z,q)}else{const q=e??a.length;do{const k=f===0?i[0]??r.initialPageParam:ws(r,u);if(f>0&&k==null)break;u=await F(u,k),f++}while(f<q)}return u};t.options.persister?t.fetchFn=()=>{var I,B;return(B=(I=t.options).persister)==null?void 0:B.call(I,h,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=h}}}function ws(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 lo(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 fo=(Ws=class extends As{constructor(t){super();N(this,ze);N(this,dn);N(this,We);N(this,Te);N(this,_t);U(this,dn,t.client),this.mutationId=t.mutationId,U(this,Te,t.mutationCache),U(this,We,[]),this.state=t.state||Fs(),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){U(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,_t))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,u,f,h,T,b,x,v,O,I,B,_,F,q,k,Q,z,re,o,c;const n=()=>{j(this,ze,yt).call(this,{type:"continue"})},r={client:l(this,dn),meta:this.options.meta,mutationKey:this.options.mutationKey};U(this,_t,ys({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(d,g)=>{j(this,ze,yt).call(this,{type:"failed",failureCount:d,error:g})},onPause:()=>{j(this,ze,yt).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,_t).canStart();try{if(s)n();else{j(this,ze,yt).call(this,{type:"pending",variables:t,isPaused:a}),await((u=(i=l(this,Te).config).onMutate)==null?void 0:u.call(i,t,this,r));const g=await((h=(f=this.options).onMutate)==null?void 0:h.call(f,t,r));g!==this.state.context&&j(this,ze,yt).call(this,{type:"pending",context:g,variables:t,isPaused:a})}const d=await l(this,_t).start();return await((b=(T=l(this,Te).config).onSuccess)==null?void 0:b.call(T,d,t,this.state.context,this,r)),await((v=(x=this.options).onSuccess)==null?void 0:v.call(x,d,t,this.state.context,r)),await((I=(O=l(this,Te).config).onSettled)==null?void 0:I.call(O,d,null,this.state.variables,this.state.context,this,r)),await((_=(B=this.options).onSettled)==null?void 0:_.call(B,d,null,t,this.state.context,r)),j(this,ze,yt).call(this,{type:"success",data:d}),d}catch(d){try{throw await((q=(F=l(this,Te).config).onError)==null?void 0:q.call(F,d,t,this.state.context,this,r)),await((Q=(k=this.options).onError)==null?void 0:Q.call(k,d,t,this.state.context,r)),await((re=(z=l(this,Te).config).onSettled)==null?void 0:re.call(z,void 0,d,this.state.variables,this.state.context,this,r)),await((c=(o=this.options).onSettled)==null?void 0:c.call(o,void 0,d,t,this.state.context,r)),d}finally{j(this,ze,yt).call(this,{type:"error",error:d})}}finally{l(this,Te).runNext(this)}}},dn=new WeakMap,We=new WeakMap,Te=new WeakMap,_t=new WeakMap,ze=new WeakSet,yt=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),le.batch(()=>{l(this,We).forEach(r=>{r.onMutationUpdate(t)}),l(this,Te).notify({mutation:this,type:"updated",action:t})})},Ws);function Fs(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ho=(zs=class extends Ht{constructor(t={}){super();N(this,Ze);N(this,Ke);N(this,ln);this.config=t,U(this,Ze,new Set),U(this,Ke,new Map),U(this,ln,0)}build(t,n,r){const s=new fo({client:t,mutationCache:this,mutationId:++Rn(this,ln)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Ze).add(t);const n=kn(t);if(typeof n=="string"){const r=l(this,Ke).get(n);r?r.push(t):l(this,Ke).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Ze).delete(t)){const n=kn(t);if(typeof n=="string"){const r=l(this,Ke).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,Ke).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=kn(t);if(typeof n=="string"){const r=l(this,Ke).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=kn(t);if(typeof n=="string"){const s=(r=l(this,Ke).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(){le.batch(()=>{l(this,Ze).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Ze).clear(),l(this,Ke).clear()})}getAll(){return Array.from(l(this,Ze))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>ds(n,r))}findAll(t={}){return this.getAll().filter(n=>ds(t,n))}notify(t){le.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return le.batch(()=>Promise.all(t.map(n=>n.continue().catch(xe))))}},Ze=new WeakMap,Ke=new WeakMap,ln=new WeakMap,zs);function kn(e){var t;return(t=e.options.scope)==null?void 0:t.id}var po=(Qs=class extends Ht{constructor(t,n){super();N(this,et);N(this,Ye);N(this,ft);N(this,De);N(this,Je);U(this,Ye,t),this.setOptions(n),this.bindMethods(),j(this,et,Nn).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,Ye).defaultMutationOptions(t),Bn(this.options,n)||l(this,Ye).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,De),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&Ft(n.mutationKey)!==Ft(this.options.mutationKey)?this.reset():((r=l(this,De))==null?void 0:r.state.status)==="pending"&&l(this,De).setOptions(this.options)}onUnsubscribe(){var t;this.hasListeners()||(t=l(this,De))==null||t.removeObserver(this)}onMutationUpdate(t){j(this,et,Nn).call(this),j(this,et,Ir).call(this,t)}getCurrentResult(){return l(this,ft)}reset(){var t;(t=l(this,De))==null||t.removeObserver(this),U(this,De,void 0),j(this,et,Nn).call(this),j(this,et,Ir).call(this)}mutate(t,n){var r;return U(this,Je,n),(r=l(this,De))==null||r.removeObserver(this),U(this,De,l(this,Ye).getMutationCache().build(l(this,Ye),this.options)),l(this,De).addObserver(this),l(this,De).execute(t)}},Ye=new WeakMap,ft=new WeakMap,De=new WeakMap,Je=new WeakMap,et=new WeakSet,Nn=function(){var n;const t=((n=l(this,De))==null?void 0:n.state)??Fs();U(this,ft,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Ir=function(t){le.batch(()=>{var n,r,s,a,i,u,f,h;if(l(this,Je)&&this.hasListeners()){const T=l(this,ft).variables,b=l(this,ft).context,x={client:l(this,Ye),meta:this.options.meta,mutationKey:this.options.mutationKey};(t==null?void 0:t.type)==="success"?((r=(n=l(this,Je)).onSuccess)==null||r.call(n,t.data,T,b,x),(a=(s=l(this,Je)).onSettled)==null||a.call(s,t.data,null,T,b,x)):(t==null?void 0:t.type)==="error"&&((u=(i=l(this,Je)).onError)==null||u.call(i,t.error,T,b,x),(h=(f=l(this,Je)).onSettled)==null||h.call(f,void 0,t.error,T,b,x))}this.listeners.forEach(T=>{T(l(this,ft))})})},Qs),mo=(js=class extends Ht{constructor(t={}){super();N(this,Qe);this.config=t,U(this,Qe,new Map)}build(t,n,r){const s=n.queryKey,a=n.queryHash??dr(s,n);let i=this.get(a);return i||(i=new io({client:t,queryKey:s,queryHash:a,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(i)),i}add(t){l(this,Qe).has(t.queryHash)||(l(this,Qe).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=l(this,Qe).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,Qe).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){le.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,Qe).get(t)}getAll(){return[...l(this,Qe).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>us(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>us(t,r)):n}notify(t){le.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){le.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){le.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Qe=new WeakMap,js),yo=(Vs=class{constructor(e={}){N(this,ae);N(this,ht);N(this,pt);N(this,Yt);N(this,Jt);N(this,mt);N(this,en);N(this,tn);U(this,ae,e.queryCache||new mo),U(this,ht,e.mutationCache||new ho),U(this,pt,e.defaultOptions||{}),U(this,Yt,new Map),U(this,Jt,new Map),U(this,mt,0)}mount(){Rn(this,mt)._++,l(this,mt)===1&&(U(this,en,pr.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,ae).onFocus())})),U(this,tn,Mn.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,ae).onOnline())})))}unmount(){var e,t;Rn(this,mt)._--,l(this,mt)===0&&((e=l(this,en))==null||e.call(this),U(this,en,void 0),(t=l(this,tn))==null||t.call(this),U(this,tn,void 0))}isFetching(e){return l(this,ae).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,ht).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=l(this,ae).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=l(this,ae).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(it(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,ae).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,ae).get(r.queryHash),a=s==null?void 0:s.state.data,i=Xi(t,a);if(i!==void 0)return l(this,ae).build(this,r).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return le.batch(()=>l(this,ae).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,ae).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=l(this,ae);le.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=l(this,ae);return le.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=le.batch(()=>l(this,ae).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(xe).catch(xe)}invalidateQueries(e,t={}){return le.batch(()=>(l(this,ae).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=le.batch(()=>l(this,ae).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let a=s.fetch(void 0,n);return n.throwOnError||(a=a.catch(xe)),s.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(xe)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=l(this,ae).build(this,t);return n.isStaleByTime(it(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(xe).catch(xe)}fetchInfiniteQuery(e){return e.behavior=Ts(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(xe).catch(xe)}ensureInfiniteQueryData(e){return e.behavior=Ts(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Mn.isOnline()?l(this,ht).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,ae)}getMutationCache(){return l(this,ht)}getDefaultOptions(){return l(this,pt)}setDefaultOptions(e){U(this,pt,e)}setQueryDefaults(e,t){l(this,Yt).set(Ft(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...l(this,Yt).values()],n={};return t.forEach(r=>{an(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,Jt).set(Ft(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...l(this,Jt).values()],n={};return t.forEach(r=>{an(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...l(this,pt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=dr(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===In&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...l(this,pt).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,ae).clear(),l(this,ht).clear()}},ae=new WeakMap,ht=new WeakMap,pt=new WeakMap,Yt=new WeakMap,Jt=new WeakMap,mt=new WeakMap,en=new WeakMap,tn=new WeakMap,Vs),Ss=ce.createContext(void 0),$t=e=>{const t=ce.useContext(Ss);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Ao=({client:e,children:t})=>(ce.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),$.jsx(Ss.Provider,{value:e,children:t})),Ds=ce.createContext(!1),go=()=>ce.useContext(Ds);Ds.Provider;function bo(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Eo=ce.createContext(bo()),xo=()=>ce.useContext(Eo),Co=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},To=e=>{ce.useEffect(()=>{e.clearReset()},[e])},wo=({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])),Fo=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))}},So=(e,t)=>e.isLoading&&e.isFetching&&!t,Do=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,vs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function vo(e,t,n){var b,x,v,O,I;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=go(),s=xo(),a=$t(),i=a.defaultQueryOptions(e);(x=(b=a.getDefaultOptions().queries)==null?void 0:b._experimental_beforeQuery)==null||x.call(b,i),process.env.NODE_ENV!=="production"&&(i.queryFn||console.error(`[${i.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`)),i._optimisticResults=r?"isRestoring":"optimistic",Fo(i),Co(i,s),To(s);const u=!a.getQueryCache().get(i.queryHash),[f]=ce.useState(()=>new t(a,i)),h=f.getOptimisticResult(i),T=!r&&e.subscribed!==!1;if(ce.useSyncExternalStore(ce.useCallback(B=>{const _=T?f.subscribe(le.batchCalls(B)):xe;return f.updateResult(),_},[f,T]),()=>f.getCurrentResult(),()=>f.getCurrentResult()),ce.useEffect(()=>{f.setOptions(i)},[i,f]),Do(i,h))throw vs(i,f,s);if(wo({result:h,errorResetBoundary:s,throwOnError:i.throwOnError,query:a.getQueryCache().get(i.queryHash),suspense:i.suspense}))throw h.error;if((O=(v=a.getDefaultOptions().queries)==null?void 0:v._experimental_afterQuery)==null||O.call(v,i,h),i.experimental_prefetchInRender&&!wt&&So(h,r)){const B=u?vs(i,f,s):(I=a.getQueryCache().get(i.queryHash))==null?void 0:I.promise;B==null||B.catch(xe).finally(()=>{f.updateResult()})}return i.notifyOnChangeProps?h:f.trackResult(h)}function Ps(e,t){return vo(e,oo)}function ot(e,t){const n=$t(),[r]=ce.useState(()=>new po(n,e));ce.useEffect(()=>{r.setOptions(e)},[r,e]);const s=ce.useSyncExternalStore(ce.useCallback(i=>r.subscribe(le.batchCalls(i)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=ce.useCallback((i,u)=>{r.mutate(i,u).catch(xe)},[r]);if(s.error&&ps(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:a,mutateAsync:s.mutate}}const Po=2e4,Re=()=>{const{partner:e,chainId:t,isDev:n=!1,minChunkSizeUsd:r}=K(),{data:s,error:a,isFetching:i,isLoading:u,refetch:f}=Ps({queryKey:["repermit-data",e,t,n],queryFn:()=>{if(!Gn(e).includes(t))throw new Error(`Partner "${e}" is not supported on chain ${t}`);return zr(e,t,n)},staleTime:1/0,gcTime:1/0,retry:2}),h=u||i;return S.useEffect(()=>{s&&de.onFetchedConfig(s,e,Zn(e,t),r,n)},[t,s,n,r,e]),S.useMemo(()=>({data:s,error:a,isLoading:h,refetch:f}),[s,a,h,f])},Oo=()=>{const{module:e}=K(),t=H(n=>n.state.isMarketOrder);return S.useMemo(()=>e===G.TWAP?t?X.TWAP_MARKET:X.TWAP_LIMIT:e===G.LIMIT?X.LIMIT:e===G.STOP_LOSS?t?X.STOP_LOSS_MARKET:X.STOP_LOSS_LIMIT:e===G.TAKE_PROFIT?t?X.TAKE_PROFIT_MARKET:X.TAKE_PROFIT_LIMIT:X.TWAP_MARKET,[e,t])},Os=(e,t,n,r,s,a)=>["useTwapOrderHistoryManager",e,t,n,r,s,a],_n=()=>{const{account:e,partner:t,chainId:n,isDev:r,supportLegacyOrders:s}=K(),{data:a}=Re(),i=a==null?void 0:a.order.witness.exchange.adapter;return S.useMemo(()=>Os(e,i,t,n,r,s),[e,i,t,n,r,s])},Bo=()=>{const{account:e,partner:t,chainId:n,isDev:r,supportLegacyOrders:s}=K();return S.useMemo(()=>Os(e,void 0,t,n,r,s),[e,t,n,r,s])},Io=()=>{const e=$t(),{account:t}=K(),n=_n();return S.useCallback(r=>{e.setQueryData(n,s=>s?s!=null&&s.some(a=>a.id===r.id)?s:[r,...s]:[r])},[e,n,t])},Mo=()=>{const e=$t(),t=_n();return S.useCallback((n,r)=>{e.setQueryData(t,s=>s==null?void 0:s.map(a=>a.id===n?{...a,status:r}:a))},[e,t])},ko=()=>{const{callbacks:e}=K(),t=$t(),n=_n();return S.useCallback(r=>{var u;const s=t.getQueryData(n);let a=!1;const i=[];s&&s.filter(f=>f.version===2).forEach(f=>{var T;const h=r.find(b=>b.id===f.id);h&&h.progress!==f.progress&&(a=!0,i.push(h),h.status===ue.Completed&&((T=e==null?void 0:e.onOrderFilled)==null||T.call(e,h)))}),a&&((u=e==null?void 0:e.onOrdersProgressUpdate)==null||u.call(e,i))},[t,n,e])},_o=(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)},br=()=>{const{account:e,partner:t,chainId:n,isDev:r,supportLegacyOrders:s}=K(),{data:a}=Re(),i=$t(),u=S.useMemo(()=>s?Zn(t,n):void 0,[n,t,s]),f=_n(),h=Bo(),T=ko();return Ps({refetchInterval:Po,refetchOnWindowFocus:!0,retry:!1,gcTime:1/0,staleTime:1/0,queryKey:f,enabled:!!(e&&n),queryFn:async({signal:x})=>{if(!e||!n)return[];const v=i.getQueryData(f)??i.getQueryData(h),O=s&&!v,I=await gi({signal:x,chainId:n,exchange:a==null?void 0:a.order.witness.exchange.adapter,partner:t,twapConfig:u,account:e,isDev:r,includeV1GraphOrders:O,includeV2Orders:!!a});return T(I),!s||O?I:_o(I,v)}})},Uo=(e,t,n)=>S.useMemo(()=>{if(!(!e||!t||!n||n!=null&&n.isMarketPrice))return qr(n,e==null?void 0:e.decimals,t==null?void 0:t.decimals)},[n,e,t]),Lo=(e,t,n)=>S.useMemo(()=>{if(!(!e||!t||!n))return Hr(n,e.decimals,t.decimals)},[n,e,t]),Ro=(e,t,n)=>S.useMemo(()=>{if(!(!e||!t||!n))return Xn(n.srcAmountFilled,n.dstAmountFilled,e.decimals,t.decimals)},[n,e,t]),Un=(e,t)=>[...e.filter(r=>r.status===t)].sort((r,s)=>s.createdAt-r.createdAt),No=()=>{const{data:e,isLoading:t,refetch:n,isRefetching:r}=br(),s=S.useCallback(()=>n().then(a=>a.data),[n]);return S.useMemo(()=>({orders:{all:e??[],open:Un(e??[],ue.Open),completed:Un(e??[],ue.Completed),cancelled:Un(e??[],ue.Cancelled),expired:Un(e??[],ue.Expired)},isLoading:t,isRefetching:r,refetchOrders:s}),[e,t,r,s])},Er=()=>{const e=H(n=>n.state.currentTime),t=ir().duration;return S.useMemo(()=>Ma(e,t),[e,t])},Bs=()=>{const{srcToken:e,dstToken:t,account:n,chainId:r,slippage:s,module:a}=K(),i=H(F=>F.state.currentTime),{amount:u}=at(),{amountPerTrade:f,totalTrades:h}=He(),T=Er(),{amount:b}=cr(),{pricePerChunk:x}=Ct(),{milliseconds:v}=qt(),{data:O,error:I,isLoading:B}=Re(),_=S.useMemo(()=>{if(O)return Qr({chainId:r,srcTokenAddress:(e==null?void 0:e.address)||"",dstTokenAddress:(t==null?void 0:t.address)||"",totalSrcAmount:u,currentTimeMillis:i,deadlineMillis:T,fillDelayMillis:v,totalTrades:h,slippageBps:s*100,swapperAddress:n,srcAmountPerTrade:f,minDstAmountPerTrade:b,triggerAmountPerTrade:x,permitData:O,module:a})},[O,e,t,n,r,i,s,a,u,f,h,T,v,b,x]);return S.useMemo(()=>({data:_,error:I,isLoading:B}),[_,I,B])};function Ko(e){const t=e.slice(2);if(t.length===128){const a=`0x${t.slice(0,64)}`,i=parseInt(t.charAt(64),16),u=(i>>3)+27,f=`0x${(i&7).toString(16)}${t.slice(65,128)}`;return{r:a,s:f,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 qo=()=>{var a;const{account:e,walletInteractions:t,callbacks:n,chainId:r}=K(),s=(a=Sn())==null?void 0:a.wToken;return ot({mutationFn:async({onHash:i,srcAmountWei:u})=>{var h,T;if(!e)throw new Error("missing account");if(!t)throw new Error("missing walletInteractions");if(!s)throw new Error("tokenAddress is not defined");de.onWrapRequest();const f=await t.wrapNativeToken(u);return(h=n==null?void 0:n.onWrapRequest)==null||h.call(n),i==null||i(f),de.onWrapSuccess(f),(T=n==null?void 0:n.onWrapSuccess)==null||T.call(n,{txHash:f,explorerUrl:Nt(f,r),amount:ge(u,s.decimals)}),f},onError:i=>{throw de.onWrapError(i),i}})},Is=()=>{const{account:e,walletInteractions:t,chainId:n,callbacks:r,isDev:s}=K(),{data:a,error:i,isLoading:u}=Bs(),{refetch:f}=br(),h=Io();return ot({mutationFn:async()=>{var F,q,k,Q;if(!e)throw new Error("missing account");if(!t)throw new Error("missing walletInteractions");if(!n)throw new Error("missing chainId");if(i)throw i;if(u||!a)throw new Error("RePermit data is unavailable");const{order:T,domain:b,types:x,primaryType:v}=a;de.onSignOrderRequest(T);let O;try{O=await t.signOrder({domain:b,types:x,primaryType:v,message:T,account:e})}catch(z){throw(F=r==null?void 0:r.onSignOrderError)==null||F.call(r,z),de.onSignOrderError(z),z}de.onSignOrderSuccess(O),(q=r==null?void 0:r.onSignOrderSuccess)==null||q.call(r,O);const I=Ko(O),B={v:`0x${I.v.toString(16)}`,r:I.r,s:I.s};(k=r==null?void 0:r.onSignOrderRequest)==null||k.call(r);const _=await Vr(T,B,s);return(Q=r==null?void 0:r.onOrderCreated)==null||Q.call(r,_),h(_),f(),_}})},Ms=()=>{const{account:e,walletInteractions:t}=K(),{data:n}=Re();return ot({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("RePermit data is unavailable");const a=await t.getAllowance({tokenAddress:r,spenderAddress:n.domain.verifyingContract}),i=D(a||"0").lt(D(s).toString());return{allowance:a,approvalRequired:i}}})},Ho=()=>{const{account:e,walletInteractions:t,chainId:n,callbacks:r}=K(),{data:s}=Re(),{mutateAsync:a}=Ms();return ot({onError:i=>{de.onApproveError(i)},mutationFn:async({token:i,onHash:u,srcAmountWei:f})=>{var b,x;if(!e)throw new Error("missing account");if(!t)throw new Error("missing walletInteractions");if(!s)throw new Error("RePermit data is unavailable");de.onApproveRequest();const h=await t.approveToken({tokenAddress:i.address,amount:f,spenderAddress:s.domain.verifyingContract});if(!h)throw new Error("failed to approve token");(b=r==null?void 0:r.onApproveRequest)==null||b.call(r),u(h);let T=!1;for(let v=0;v<3;v++){const{approvalRequired:O}=await a({tokenAddress:i.address,srcAmountWei:f});if(!O){T=!0;break}v<2&&await new Promise(I=>setTimeout(I,3e3))}if(!T)throw new Error(`Insufficient ${i.symbol} allowance to perform the swap. Please approve the token first.`);return de.onApproveSuccess(h),(x=r==null?void 0:r.onApproveSuccess)==null||x.call(r,{txHash:h,explorerUrl:Nt(h,n),token:i,amount:ge(f,i.decimals)}),h}})},$o=()=>{const{account:e,chainId:t,srcToken:n,dstToken:r,module:s,slippage:a}=K(),i=Ct(),u=at().amount,f=He().amountPerTrade,h=Er(),T=He().totalTrades,b=qt().fillDelay,x=cr().amount,v=H(O=>O.state.isMarketOrder);return ot({mutationFn:async()=>{de.onRequestOrder({account:e,chainId:t,module:s,srcToken:n,dstToken:r,fromTokenAmount:u,srcChunkAmount:f,triggerPricePerTrade:i.pricePerChunk,deadline:h,fillDelay:b.unit*b.value,minDstAmountOutPerTrade:x,slippage:a,isMarketOrder:v||!1,chunksAmount:T})}})};function Wo(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 ks=()=>{const{srcToken:e,dstToken:t,chainId:n,callbacks:r,marketPrice:s}=K(),a=Ho().mutateAsync,i=qo().mutateAsync,u=Is().mutateAsync,{mutateAsync:f}=Ms(),{update:h}=Kt(),{amount:T}=at(),b=$o().mutate,{isLoading:x}=Re();return ot({mutationFn:async()=>{var I,B;const v=H.getState().state.swapExecutions[H.getState().state.swapExecutionIndex];if(x||(v==null?void 0:v.status)===Ae.LOADING||v!=null&&v.allowanceLoading)return;const O=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 _=ts(e,n);h({allowanceLoading:!0,wrapTxHash:void 0,approveTxHash:void 0,acceptedMarketPrice:s,acceptedSrcAmount:T,srcToken:e,dstToken:t,pendingSteps:[]});const{approvalRequired:F}=await f({tokenAddress:_.address,srcAmountWei:T});let q=0,k=1;O&&k++,F&&k++,h({totalSteps:k,stepIndex:q,allowanceLoading:!1,hasApproval:!F,status:Ae.LOADING}),b();let Q=[];O&&Q.push(rt.WRAP),F&&Q.push(rt.APPROVE),Q.push(rt.CREATE),h({pendingSteps:Q}),O&&(h({step:rt.WRAP}),await i({onHash:re=>h({wrapTxHash:re}),srcAmountWei:T}),q++,h({stepIndex:q})),F&&(h({step:rt.APPROVE}),await a({token:_,onHash:re=>h({approveTxHash:re}),srcAmountWei:T}),q++,h({stepIndex:q})),h({step:rt.CREATE});const z=await u();return h({status:Ae.SUCCESS,orderId:z.id}),z}catch(_){if(tr(_))(I=r==null?void 0:r.onSubmitOrderRejected)==null||I.call(r),h({step:void 0,status:void 0,stepIndex:void 0,allowanceLoading:!1,error:_});else{const F=Wo(_);(B=r==null?void 0:r.onSubmitOrderFailed)==null||B.call(r,F),h({status:Ae.FAILED,allowanceLoading:!1,parsedError:F,error:_})}throw _}}})},zo=()=>{const e=Kt(),{srcToken:t,dstToken:n}=K(),{isLoading:r}=Re(),s=ks(),a=H(T=>T.resetState),i=S.useCallback(()=>s.mutateAsync(),[s]),{update:u,resetSwap:f,...h}=e;return S.useMemo(()=>({status:h.status,parsedError:h.parsedError,error:h.error,step:h.step,stepIndex:h.stepIndex,approveTxHash:h.approveTxHash,wrapTxHash:h.wrapTxHash,totalSteps:h.totalSteps,pendingSteps:h.pendingSteps,srcToken:t,dstToken:n,onSubmit:i,resetState:a,resetCurrentSwap:f,isLoading:(e==null?void 0:e.status)===Ae.LOADING,isSuccess:(e==null?void 0:e.status)===Ae.SUCCESS,isFailed:(e==null?void 0:e.status)===Ae.FAILED,confirmButtonLoading:h.allowanceLoading||r}),[i,h,a,f,t,n,r])},Qo=()=>{const{marketPrice:e,srcToken:t,dstToken:n,marketPriceLoading:r,srcBalance:s,srcUsd1Token:a,noLiquidity:i,typedInputAmount:u}=K(),{error:f,isLoading:h,refetch:T}=Re(),b=r||D(a||"0").isZero()||s===void 0||D(e||"0").isZero(),x=h||!!(t&&n&&u&&b),O=!!(os()||f||i||x||D(u||"0").isZero()||!t||!n);return S.useMemo(()=>({disabled:O,error:f,loading:x,retry:T}),[O,x,f,T])},jo=()=>{const{srcUsd1Token:e,dstUsd1Token:t}=K(),n=at().amountUI,r=On().amountUI,s=qe(n,e),a=qe(r,t);return{srcAmountUsd:s,dstAmountUsd:a}},Vo=()=>{const{fees:e,dstToken:t,dstUsd1Token:n}=K(),{amountUI:r}=On(),s=S.useMemo(()=>!e||!r?"":D(r).multipliedBy(e).dividedBy(100).toFixed(),[r,e]),a=ar((t==null?void 0:t.decimals)||0,s);return{amountUI:s,amount:a,percent:e,usd:qe(s,n)}},Go=e=>{const t=S.useMemo(()=>!e.minDestAmountPerTrade||!e.totalTrades?"":D(e.minDestAmountPerTrade).multipliedBy(e.totalTrades).decimalPlaces(0).toFixed(),[e.minDestAmountPerTrade,e.totalTrades]),n=S.useMemo(()=>!e.minDestAmountPerTradeUI||!e.totalTrades?"":D(e.minDestAmountPerTradeUI).multipliedBy(e.totalTrades).toFixed(),[e.minDestAmountPerTradeUI,e.totalTrades]),r=S.useMemo(()=>!e.minDestAmountPerTradeUsd||!e.totalTrades?"":D(e.minDestAmountPerTradeUsd).multipliedBy(e.totalTrades).decimalPlaces(2).toFixed(),[e.minDestAmountPerTradeUsd,e.totalTrades]);return S.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])},Xo=()=>{const{srcToken:e,dstToken:t,account:n,marketPrice:r}=K(),{amount:s}=at(),{amount:a,amountUI:i,usd:u}=Pn(),{amountPerTrade:f,amountPerTradeUI:h,amountPerTradeUsd:T,totalTrades:b}=He(),x=Er(),{amount:v,amountUI:O,usd:I}=cr(),{amountUI:B,amount:_,usd:F}=Ct(),{milliseconds:q}=qt(),{amount:k,amountUI:Q}=On(),{srcAmountUsd:z,dstAmountUsd:re}=jo(),{amount:o,amountUI:c,percent:d,usd:g}=Vo(),{data:m}=Bs(),{data:y}=Re(),w=H(Z=>Z.state.isMarketOrder),p=H(Z=>Z.state.currentTime),A=Kt(),C=Oo(),E=A.acceptedSrcAmount||s,P=ge(r,(t==null?void 0:t.decimals)||0),L=S.useMemo(()=>C===X.TAKE_PROFIT_MARKET||C===X.TAKE_PROFIT_LIMIT||C===X.STOP_LOSS_LIMIT||C===X.STOP_LOSS_MARKET,[C]),R=Go({srcToken:e,dstToken:t,account:n,orderType:C,createdAt:p,deadline:x,totalTrades:b,tradeInterval:q,srcAmount:E,srcAmountUI:ge(E,(e==null?void 0:e.decimals)||0),srcAmountUsd:z,dstAmount:k,dstAmountUI:Q,dstAmountUsd:re,limitPrice:w?void 0:a,limitPriceUI:w?void 0:i,limitPriceUsd:w?void 0:u,srcAmountPerTrade:f,srcAmountPerTradeUI:h,srcAmountPerTradeUsd:T,minDestAmountPerTrade:v,minDestAmountPerTradeUI:O,minDestAmountPerTradeUsd:I,triggerPrice:_,triggerPriceUI:B,triggerPriceUsd:F});return S.useMemo(()=>({...R,feesAmountUI:c,feesAmount:o,feesUsd:g||"",feesPercentage:d,rePermitData:m,isTriggerPrice:L,isMarketOrder:w,marketPrice:r,marketPriceUi:P,spender:(y==null?void 0:y.domain.verifyingContract)||""}),[R,c,o,g,d,m,L,w,r,P,y])},Zo=()=>{const{supportedChains:e}=K();return S.useMemo(()=>e,[e])},Yo=60,_s=()=>{const{refetch:e}=br();return ot({mutationFn:async t=>{var n;for(let r=0;r<Yo;r++){const s=(n=await e())==null?void 0:n.data;if(!s)throw new Error("orders not found");const a=s.find(i=>i.id===t);if((a==null?void 0:a.status)===ue.Cancelled)return;await new Promise(i=>setTimeout(i,1e3))}throw new Error("Timed out waiting for order cancellation to be confirmed")}})},Jo=()=>{const e=H(n=>n.updateState);return{cancelOrders:H(n=>n.state.cancelOrders),setCancelOrder:(n,r)=>{const s=H.getState().state.cancelOrders;e({cancelOrders:{...s,[n]:r}})},clearCancelOrder:n=>{const r=H.getState().state.cancelOrders,{[n]:s,...a}=r;e({cancelOrders:a})}}},ec=e=>{const{account:t,walletInteractions:n,callbacks:r,chainId:s}=K(),{data:a,error:i,isLoading:u}=Re(),f=_s().mutateAsync,h=Mo(),{cancelOrders:T,setCancelOrder:b,clearCancelOrder:x}=Jo(),{mutateAsync:v}=ot({mutationFn:async()=>{var _,F,q;if(!t||!n)throw new Error("missing required parameters");if(!e)throw new Error("order is required");if(e.version!==1&&!a)throw new Error("RePermit data is unavailable");const B=e.id;try{(_=r==null?void 0:r.onCancelOrderRequest)==null||_.call(r,e),b(B,{status:Ae.LOADING}),de.onCancelOrderRequest([e.version===1?e.id.toString():e.hash],e.version);const k=await n.cancelOrder({order:e,contractAddress:e.version===1?e.twapAddress:a.domain.verifyingContract,args:e.version===1?[e.id]:[[e.repermitDigest]],abi:e.version===1?Js:Ys});if(!k)throw new Error("failed to cancel order");if(de.onCancelOrderSuccess(k),h(e.id,ue.Cancelled),e.version!==1)try{await f(e.id)}catch(Q){console.warn("cancel status sync lagging",Q)}return(F=r==null?void 0:r.onCancelOrderSuccess)==null||F.call(r,{order:e.version===1?{...e,status:ue.Cancelled}:e,txHash:k,explorerUrl:Nt(k,s)}),b(B,{status:Ae.SUCCESS,txHash:k}),k}catch(k){console.error("cancel order error",k),(q=r==null?void 0:r.onCancelOrderFailed)==null||q.call(r,k),tr(k)?x(B):(b(B,{status:Ae.FAILED,error:k.message}),de.onCancelOrderError(k))}}}),O=S.useMemo(()=>{const B=T[(e==null?void 0:e.id)||""],_=!!(e&&e.version!==1);return{isLoading:(B==null?void 0:B.status)===Ae.LOADING,disabled:_&&(u||!!i||!a),isSuccess:(B==null?void 0:B.status)===Ae.SUCCESS,isError:(B==null?void 0:B.status)===Ae.FAILED,error:B==null?void 0:B.error,txHash:B==null?void 0:B.txHash}},[T,e,a,i,u]),I=S.useCallback(async()=>v(),[v]);return S.useMemo(()=>({cancelOrder:I,...O}),[I,O])},Us=S.createContext(null),tc=({children:e})=>{const t=Ii(),n=Ui(),r=ki(),s=Hi(),a=$i(),i=Dn(),u=Wi(),f=zi(),h=os(),T=Qo(),b=Xo(),x=No(),v=zo(),O=Zo(),I=_s(),{module:B}=K(),_=S.useMemo(()=>({tradesAmountPanel:t,durationPanel:n,fillDelayPanel:r,limitPricePanel:s,triggerPricePanel:a,pricePanel:i,dstTokenPanel:u,disclaimerPanel:f,inputError:h,submitOrderButton:T,derivedFormData:b,orderHistoryPanel:x,orderExecutionPanel:v,supportedChains:O,refetchUntilStatusSynced:I,module:B}),[t,n,r,s,a,i,u,f,h,T,b,x,v,O,I,B]);return $.jsx(Us.Provider,{value:_,children:e})},nc=()=>{const e=S.useContext(Us);if(e===null)throw new Error("useSpot must be used within SpotProvider");return e},rc=S.createContext(null),xr={didCatch:!1,error:null};class sc extends S.Component{constructor(t){super(t),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=xr}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),i=0;i<s;i++)a[i]=arguments[i];(n=(r=this.props).onReset)===null||n===void 0||n.call(r,{args:a,reason:"imperative-api"}),this.setState(xr)}}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&&ac(t.resetKeys,s)){var a,i;(a=(i=this.props).onReset)===null||a===void 0||a.call(i,{next:s,prev:t.resetKeys,reason:"keys"}),this.setState(xr)}}render(){const{children:t,fallbackRender:n,FallbackComponent:r,fallback:s}=this.props,{didCatch:a,error:i}=this.state;let u=t;if(a){const f={error:i,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")u=n(f);else if(r)u=S.createElement(r,f);else if(s!==void 0)u=s;else throw i}return S.createElement(rc.Provider,{value:{didCatch:a,error:i,resetErrorBoundary:this.resetErrorBoundary}},u)}}function ac(){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 ic=()=>$.jsx("div",{className:"twap-error-fallback",children:$.jsx("p",{style:{fontSize:20,fontWeight:600,textAlign:"center",width:"100%",marginTop:40},children:"Something went wrong"})});function oc({children:e}){return $.jsx(sc,{FallbackComponent:ic,onError:t=>de.onCrash(t),children:$.jsx($.Fragment,{children:e})})}const Ls=S.createContext(null),cc=new yo({defaultOptions:{queries:{refetchOnWindowFocus:!1}}}),uc=e=>{var x,v,O;const t=H(I=>I.updateState),n=H(I=>I.state.isMarketOrder);S.useEffect(()=>{const I=setInterval(()=>{t({currentTime:Date.now()})},6e4);return()=>clearInterval(I)},[t]);const r=(x=e.overrides)==null?void 0:x.state,{isMarketOrder:s,chunks:a,fillDelay:i,duration:u,limitPrice:f,triggerPrice:h,triggerPricePercent:T,limitPricePercent:b}=r??{};return S.useEffect(()=>{s!==void 0&&t({isMarketOrder:s}),t({typedChunks:a,typedFillDelay:i,typedDuration:u,typedLimitPrice:f,typedTriggerPrice:h,triggerPricePercent:T,limitPricePercent:b})},[t,s,a,i,u,f,h,T,b]),S.useEffect(()=>{var I,B,_,F;t({typedLimitPrice:(B=(I=e.overrides)==null?void 0:I.state)==null?void 0:B.limitPrice,typedTriggerPrice:(F=(_=e.overrides)==null?void 0:_.state)==null?void 0:F.triggerPrice,triggerPricePercent:void 0,limitPricePercent:void 0})},[(v=e.srcToken)==null?void 0:v.address,(O=e.dstToken)==null?void 0:O.address]),S.useEffect(()=>{e.module===G.LIMIT&&t({isMarketOrder:!1})},[e.module]),S.useEffect(()=>{n&&t({isInvertedTrade:!1})},[n]),S.useEffect(()=>{t({typedChunks:void 0})},[e.typedInputAmount]),null},dc=({marketReferencePrice:e,srcToken:t,dstToken:n,chainId:r,typedInputAmount:s})=>S.useMemo(()=>{if(rr(t,n,r)||sr(t,n,r))return{isLoading:!1,noLiquidity:!1,value:st(s||"0",t==null?void 0:t.decimals)};if(D(e.value||0).isZero()||D(s||0).isZero())return e;const a=D(e.value||0).dividedBy(s||0).toFixed();return{...e,value:a}},[e,s,t,n,r]),lc=e=>{const t=Kt(),n=S.useMemo(()=>Gn(e.partner),[e.partner]),r=S.useMemo(()=>{const u=n[0];return e.chainId&&n.includes(e.chainId)?e.chainId:u},[e.chainId,n]),s=dc(e),a=S.useMemo(()=>Wr(e.minChunkSizeUsd),[e.minChunkSizeUsd]);S.useEffect(()=>{de.init(e.partner,a,r,e.appId)},[e.partner,r,a,e.appId]);const i=S.useMemo(()=>({typedInputAmount:e.typedInputAmount,minChunkSizeUsd:a,account:e.account,walletInteractions:e.walletInteractions,marketPrice:t.acceptedMarketPrice||s.value,marketPriceLoading:!t.acceptedMarketPrice&&s.isLoading,noLiquidity:!t.acceptedMarketPrice&&s.noLiquidity,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,supportLegacyOrders:e.supportLegacyOrders??!1}),[e.typedInputAmount,a,e.account,e.walletInteractions,t.acceptedMarketPrice,t.srcToken,t.dstToken,s.value,s.isLoading,s.noLiquidity,e.priceProtection,n,r,e.partner,e.module,e.fees,e.overrides,e.callbacks,e.srcUsd1Token,e.dstUsd1Token,e.srcBalance,e.dstBalance,e.srcToken,e.dstToken,e.isDev,e.supportLegacyOrders]);return $.jsxs(Ls.Provider,{value:i,children:[$.jsx(uc,{...e}),$.jsx(tc,{children:$.jsx(oc,{children:e.children})})]})},fc=e=>$.jsx(Ao,{client:cc,children:$.jsx(lc,{...e})}),K=()=>{const e=S.useContext(Ls);if(e===null)throw new Error("useSpotContext must be used within SpotProvider");return e},hc=(e,t,n)=>{const r=Sn();return S.useMemo(()=>e==null?void 0:e.map(s=>({rawFill:s,srcToken:t,dstToken:n,srcAmount:ge(s.inAmount,t==null?void 0:t.decimals),dstAmount:ge(s.outAmount,n==null?void 0:n.decimals),timestamp:s.timestamp,txHash:s.txHash,explorerUrl:Nt(s.txHash,r==null?void 0:r.id),executionRate:Xn(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])},pc=(e,t,n)=>{const{chainId:r,partner:s}=K(),a=Uo(t,n,e),i=Lo(t,n,e),u=Ro(t,n,e),f=S.useMemo(()=>e?e.version===2?e.fillDelay:Kr(e,Zn(s,r)):0,[e,s,r]),h=hc(e==null?void 0:e.fills,t,n)??[];return S.useMemo(()=>{if(e!=null&&e.id)return{original:e,fills:h,srcToken:t,dstToken:n,orderType:e.type,createdAt:e.createdAt,deadline:e.deadline||0,totalTrades:e.totalTradesAmount||0,tradeInterval:f,recipient:e.maker||"",srcAmount:e.srcAmount||"",srcAmountUI:ge(e.srcAmount,t==null?void 0:t.decimals),limitPrice:st(a,n==null?void 0:n.decimals),limitPriceUI:a||"",sizePerTrade:e.srcAmountPerTrade||"",sizePerTradeUI:ge(e.srcAmountPerTrade,t==null?void 0:t.decimals),minDestAmountPerTrade:e.dstMinAmountPerTrade||"",minDestAmountPerTradeUI:ge(e.dstMinAmountPerTrade,n==null?void 0:n.decimals),dstMinAmount:e.dstMinAmountTotal,dstMinAmountUI:ge(e.dstMinAmountTotal,n==null?void 0:n.decimals),triggerPrice:st(i,n==null?void 0:n.decimals),triggerPriceUI:i||"",id:e.id,amountInFilled:e.srcAmountFilled,amountInFilledUI:ge(e.srcAmountFilled,t==null?void 0:t.decimals),amountOutFilled:e.dstAmountFilled,amountOutFilledUI:ge(e.dstAmountFilled,n==null?void 0:n.decimals),progress:e.progress,executionPrice:st(u,n==null?void 0:n.decimals),executionPriceUI:u,version:e.version}},[e,h,t,n,f,a,i,u])};Va(bi.version),M.DISCLAIMER_URL=ha,M.Disclaimer=sn,M.InputErrors=me,M.Module=G,M.ORBS_LOGO=la,M.ORBS_SLTP_FAQ_URL=da,M.ORBS_TWAP_FAQ_URL=ua,M.ORBS_WEBSITE_URL=fa,M.OrderFilter=Mr,M.OrderStatus=ue,M.OrderType=X,M.Partners=Pe,M.SPOT_VERSION=yn,M.SpotProvider=fc,M.Steps=rt,M.SwapStatus=Ae,M.TimeUnit=ve,M.buildRePermitOrderData=Qr,M.ensureWrappedToken=ts,M.eqIgnoreCase=gt,M.fetchRePermitData=zr,M.getExplorerUrl=Nt,M.getMinChunkSizeUsd=Wr,M.getNetwork=Et,M.getOrderExecutionRate=Xn,M.getOrderFillDelayMillis=Kr,M.getOrderLimitPriceRate=qr,M.getOrderType=Fi,M.getPartnerChains=Gn,M.getPartners=$r,M.getTriggerPriceRate=Hr,M.isNativeAddress=Rt,M.isTxRejected=tr,M.millisToDays=nr,M.millisToMinutes=Fn,M.networks=ye,M.parseError=wi,M.shouldUnwrapOnly=sr,M.shouldWrapOnly=rr,M.submitOrder=Vr,M.toAmountUi=ge,M.toAmountWei=st,M.useAmountUi=xt,M.useCancelOrder=ec,M.useDerivedHistoryOrder=pc,M.useExplorerLink=Si,M.useNetwork=Sn,M.useRePermitData=Re,M.useSignOrder=Is,M.useSpot=nc,M.useSubmitOrder=ks,M.useSwapExecution=Kt,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"})}));
|
|
64
|
+
`,extractResults:b=>{var x;return(((x=b.data)==null?void 0:x.orderFilleds)||[]).map(v=>({...v,timestamp:new Date(v.timestamp).getTime()}))}})};class pi extends Error{constructor(){super("No graph endpoint found"),this.name="NoGraphEndpointError"}}const mi=async({chainId:e,signal:t,page:n,limit:r,filters:s})=>{try{const a=await li({chainId:e,signal:t,page:n,limit:r,filters:s}),[i,u]=await Promise.all([hi({chainId:e,orders:a,signal:t}),fi({chainId:e,orders:a,signal:t})]),f=a.map(T=>{const b=i==null?void 0:i.filter(x=>x.TWAP_id===Number(T.Contract_id)&>(x.exchange,T.exchange)&>(x.twapAddress,T.twapAddress));return ui(T,e,b,yi(T,b||[],u))}).sort((T,b)=>b.createdAt-T.createdAt),h=new Set;return f.filter(T=>h.has(T.id)?!1:(h.add(T.id),!0))}catch{return[]}},yi=(e,t,n)=>{var u;const r=(u=n==null?void 0:n.find(f=>f.twapId===e.Contract_id.toString()&>(f.twapAddress,e.twapAddress)))==null?void 0:u.status,a=Gr(t).reduce((f,h)=>f.plus(h.inAmount),new D(0)).toFixed(),i=Zr(e.ask_srcAmount,a);return Ai(i,e.ask_deadline*1e3,r)},Zr=(e,t)=>{if(!t||!e)return 0;const n=D(t).dividedBy(e).toNumber();return n>=.99?100:n<=0?0:Number((n*100).toFixed(2))},Ai=(e,t,n)=>e===100?ue.Completed:n==="CANCELLED"?ue.Cancelled:n==="COMPLETED"?ue.Completed:t>Date.now()?ue.Open:ue.Expired,gi=async({signal:e,page:t,chainId:n,limit:r,exchange:s,partner:a,twapConfig:i,account:u,isDev:f=!1,includeV1GraphOrders:h=!0,includeV2Orders:T=!0})=>(await Promise.all([!i||!h?Promise.resolve([]):mi({chainId:n,signal:e,page:t,limit:r,filters:{accounts:[u],configs:[i]}}),T?oi({chainId:n,signal:e,account:u,exchange:s,partner:a,isDev:f}):Promise.resolve([])]).then(([v,O])=>[...v,...O])).sort((v,O)=>O.createdAt-v.createdAt),bi={version:"2.0.1"},Yr=e=>{let t;const n=new Set,r=(h,T)=>{const b=typeof h=="function"?h(t):h;if(!Object.is(b,t)){const x=t;t=T??(typeof b!="object"||b===null)?b:Object.assign({},t,b),n.forEach(v=>v(t,x))}},s=()=>t,u={setState:r,getState:s,getInitialState:()=>f,subscribe:h=>(n.add(h),()=>n.delete(h))},f=t=e(r,s,u);return u},Ei=(e=>e?Yr(e):Yr),xi=e=>e;function Ci(e,t=xi){const n=S.useSyncExternalStore(e.subscribe,S.useCallback(()=>t(e.getState()),[e,t]),S.useCallback(()=>t(e.getInitialState()),[e,t]));return S.useDebugValue(n),n}const Jr=e=>{const t=Ei(e),n=r=>Ci(t,r);return Object.assign(n,t),n},Ti=(e=>e?Jr(e):Jr),wn={},es={currentTime:Date.now(),cancelOrders:{},swapExecutions:[wn],swapExecutionIndex:0},H=Ti((e,t)=>({state:es,updateState:n=>e(r=>({state:{...r.state,...n}})),updateSwapExecutionAtIndex:(n,r)=>e(s=>{const a=[...s.state.swapExecutions];return a[n]={...a[n]??wn,...r},{state:{...s.state,swapExecutions:a}}}),resetSwapExecutionAtIndex:()=>e(n=>{const r=[...n.state.swapExecutions];return r[n.state.swapExecutionIndex]=wn,{state:{...n.state,swapExecutions:r}}}),resetState:()=>{const n=t().state;e({state:{...es,currentTime:Date.now(),isMarketOrder:n.isMarketOrder,swapExecutions:[...n.swapExecutions,wn],swapExecutionIndex:n.swapExecutionIndex+1}})}}));var Ae=(e=>(e[e.LOADING=1]="LOADING",e[e.SUCCESS=2]="SUCCESS",e[e.FAILED=3]="FAILED",e))(Ae||{}),sn=(e=>(e.TRIGGER_MARKET_PRICE="triggerMarketPriceDisclaimer",e.MARKET_PRICE="marketOrderDisclaimer",e.LIMIT_PRICE="limitOrderDisclaimer",e))(sn||{}),rt=(e=>(e.WRAP="wrap",e.APPROVE="approve",e.CREATE="create",e))(rt||{});const st=(e,t)=>t==null||!e||D(e).isNaN()?"":D(e).multipliedBy(D(10).pow(t)).toFixed(0),ge=(e,t)=>{try{return t==null||!e||D(e).isNaN()?"":D(e).dividedBy(D(10).pow(t)).toFixed()}catch(n){return console.error(n),""}},wi=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}},tr=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"))},ts=(e,t)=>{const n=Et(t);return n&&Rt(e.address)?n.wToken:e};function nr(e){return e?e/864e5:0}function Fn(e){return e?e/6e4:0}const Fi=(e,t)=>e?X.TWAP_MARKET:t===1?X.LIMIT:X.TWAP_LIMIT,rr=(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)||"")},sr=(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)||"")},Nt=(e,t)=>{if(!t)return"";const n=Et(t);return n!=null&&n.explorer?`${n.explorer}/tx/${e}`:""},ar=(e,t)=>S.useMemo(()=>st(t,e),[e,t]),xt=(e,t)=>S.useMemo(()=>ge(t,e),[e,t]),Sn=()=>{const{chainId:e}=K();return S.useMemo(()=>Et(e),[e])},Si=e=>{const t=Sn();return S.useMemo(()=>{if(!(!e||!t))return Nt(e,t.id)},[e,t])},qe=(e,t)=>S.useMemo(()=>!e||!t||D(e||"0").isZero()||D(t||"0").isZero()?"":D(e||"0").times(t).toFixed(),[e,t]),Di=()=>{const{srcToken:e,dstToken:t,chainId:n}=K();return S.useMemo(()=>rr(e,t,n),[e,t,n])},vi=()=>{const{srcToken:e,dstToken:t,chainId:n}=K();return S.useMemo(()=>sr(e,t,n),[e,t,n])},Pi=()=>{const e=Di(),t=vi();return e||t},Oi={},Kt=()=>{const e=H(a=>a.state.swapExecutionIndex),t=H(a=>a.state.swapExecutions[a.state.swapExecutionIndex]??Oi),n=H(a=>a.updateSwapExecutionAtIndex),r=H(a=>a.resetSwapExecutionAtIndex),s=S.useCallback(a=>n(e,a),[n,e]);return S.useMemo(()=>({...t,update:s,resetSwap:r}),[t,s,r])},at=()=>{const{srcToken:e,typedInputAmount:t}=K(),n=Kt(),r=ar(e==null?void 0:e.decimals,t),s=n.status===Ae.LOADING&&n.acceptedSrcAmount?n.acceptedSrcAmount:void 0,a=s??r,i=s?ge(s,e==null?void 0:e.decimals):t;return{amount:a,amountUI:i,error:D(a||0).isZero()?"enterAmount":void 0}},Bi=(e,t)=>{const{module:n,srcUsd1Token:r,marketPrice:s,minChunkSizeUsd:a,typedInputAmount:i}=K();return S.useMemo(()=>{if(D(i||"0").isZero()||!s||D(r||"0").isZero())return;if(!e)return{type:me.MIN_CHUNKS,value:1,args:{minChunks:"1"}};const{isError:u}=za(e,t,n);if(u)return{type:me.MAX_CHUNKS,value:t,args:{maxChunks:`${t}`}};const{isError:f,value:h}=Wa(i||"",r||"",a||0);if(f)return{type:me.MIN_TRADE_SIZE,value:h,args:{minTradeSize:`${h}`}}},[e,t,n,i,r,a,s])},He=()=>{const{srcToken:e,srcUsd1Token:t,module:n,minChunkSizeUsd:r}=K(),s=H(O=>O.state.typedChunks),a=H(O=>O.updateState),{amount:i,amountUI:u}=at(),f=S.useMemo(()=>Ia(u||"",t||"",r||0),[u,t,r]),h=S.useMemo(()=>Ba(f,n,s),[f,s,n]),T=S.useCallback(O=>a({typedChunks:O}),[a]),b=S.useMemo(()=>_a(i||"",h),[i,h]),x=xt(e==null?void 0:e.decimals,b),v=S.useMemo(()=>t?D(x||"0").times(t||0).toString():"0",[x,t]);return{totalTrades:h,maxTrades:f,amountPerTradeUI:x,amountPerTrade:b,amountPerTradeUsd:v,onChange:T,error:Bi(h,f)}},Ii=()=>{const{srcToken:e,dstToken:t}=K(),{onChange:n,totalTrades:r,amountPerTradeUsd:s,amountPerTradeUI:a,error:i,maxTrades:u,amountPerTrade:f}=He();return{error:i,maxTrades:u,totalTrades:r,amountPerTradeUI:a,amountPerTrade:f,onChange:n,amountPerTradeUsd:s,fromToken:e,toToken:t}},ns=e=>{const t=nr(e);if(t>=1)return`${t.toFixed(t%1?1:0)} ${t===1?"day":"days"}`;const n=Fn(e)/60;if(n>=1)return`${n.toFixed(n%1?1:0)} ${n===1?"hour":"hours"}`;const r=Fn(e);return`${r.toFixed(r%1?1:0)} ${r===1?"minute":"minutes"}`},Mi=e=>{const{totalTrades:t}=He(),{marketPrice:n,typedInputAmount:r}=K(),s=S.useMemo(()=>{const{isError:i,value:u}=$a(e);if(!(!i||D(r||"0").isZero()||!n))return{type:me.MIN_FILL_DELAY,value:u,args:{fillDelay:ns(u)}}},[e,r,n]),a=S.useMemo(()=>{const{isError:i,value:u}=Ua(e,t);if(!(!i||D(r||"0").isZero()||!n))return{type:me.MAX_FILL_DELAY,value:u,args:{fillDelay:ns(u)}}},[e,r,n,t]);return s||a},qt=()=>{const{callbacks:e}=K(),t=H(a=>a.state.typedFillDelay),n=H(a=>a.updateState),r=S.useMemo(()=>t||Wn,[t]),s=Mi(r);return{fillDelay:r,onChange:S.useCallback(a=>{var i;n({typedFillDelay:a}),(i=e==null?void 0:e.onFillDelayChange)==null||i.call(e,a)},[n,e]),error:s,milliseconds:r.unit*r.value}},ki=()=>{const{onChange:e,fillDelay:t,error:n}=qt(),r=S.useCallback(a=>e({unit:t.unit,value:Number(a)}),[e,t]),s=S.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}},_i=e=>{const{module:t,marketPrice:n}=K();return S.useMemo(()=>{const r=qa(t,e),s=Ha(e);if(n){if(r.isError)return{type:me.MAX_ORDER_DURATION,value:r.value,args:{duration:`${Math.floor(nr(r.value)).toFixed(0)} days`}};if(s.isError)return{type:me.MIN_ORDER_DURATION,value:s.value,args:{duration:`${Math.floor(Fn(s.value)).toFixed(0)} minutes`}}}},[e,t,n])},ir=()=>{const{module:e,callbacks:t}=K(),n=H(f=>f.state.typedDuration),r=H(f=>f.updateState),s=He().totalTrades,a=qt().fillDelay,i=S.useMemo(()=>Oa(e,s,a,n),[s,a,n,e]),u=_i(i);return{duration:i,setDuration:S.useCallback(f=>{var h;r({typedDuration:f}),(h=t==null?void 0:t.onDurationChange)==null||h.call(t,f)},[r,t]),error:u}},Ui=()=>{const{duration:e,setDuration:t,error:n}=ir(),r=S.useCallback(a=>{t({unit:e.unit,value:Number(a)})},[t,e]),s=S.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}},Li=()=>{const{module:e}=K();return S.useMemo(()=>e===G.STOP_LOSS?pa:ma,[e])},or=()=>{const{module:e}=K(),t=H(n=>n.state.isMarketOrder);return S.useMemo(()=>e!==G.STOP_LOSS&&e!==G.TAKE_PROFIT||t?void 0:e===G.STOP_LOSS?ya:Aa,[e,t])},rs=e=>{if(e===void 0||e==="")return e;const t=D(e);return t.isNaN()||t.isZero()?"0":D(1).div(t).toFixed()},Dn=()=>{const{srcToken:e,dstToken:t}=K(),n=H(f=>f.updateState),r=H(f=>f.state.isInvertedTrade),s=H(f=>f.state.typedTriggerPrice),a=H(f=>f.state.typedLimitPrice),i=H(f=>f.state.isMarketOrder);return{onInvert:S.useCallback(()=>{n({isInvertedTrade:!r,...s!==void 0?{typedTriggerPrice:rs(s)}:{},...a!==void 0?{typedLimitPrice:rs(a)}:{}})},[n,r,s,a]),isInverted:r,fromToken:r?t:e,toToken:r?e:t,isMarketPrice:i}},vn=e=>e?D(e).isNaN()?"":e:"",ss=({amount:e,typedValue:t,amountDecimals:n=18,invertedAmountDecimals:r=18,amountUsd:s,invertedAmountUsd:a,isInverted:i})=>{const u=S.useMemo(()=>{if(t!==void 0)return vn(t);const T=ge(e,n);return!T||D(T||"0").isZero()?"":i?D(1).div(T).toFixed():T},[e,n,i,t]),f=S.useMemo(()=>u?vn(i?st(u,r):e):"",[e,u,r,i]),h=qe(u||"0",i?a:s);return{amount:f,amountUI:u,usd:vn(h)}},as=({typedValue:e,tokenDecimals:t=18,initialPrice:n="0",percentage:r,setValue:s,setPercentage:a})=>{const{isInverted:i}=Dn(),u=S.useMemo(()=>D((()=>{if(e!==void 0){const x=i?D(e).isZero()?D(0):D(1).div(e):D(e);return st(x.toFixed(),t)}if(r!==void 0&&D(n||"0").gt(0)&&!D(n||"0").isNaN()){const x=D(n||"0"),v=D(r||0).div(100);return x.plus(x.multipliedBy(v)).decimalPlaces(0).toFixed()}return D(n).gt(0)?n:""})()).decimalPlaces(0).toFixed(),[e,r,t,n,i]),f=S.useCallback(b=>{s(b),a(null)},[s,a]),h=S.useCallback(b=>{s(void 0),a(b)},[s,a]),T=S.useMemo(()=>{if(!n||D(n).isZero())return"";if(r!=null)return r;if(u){const b=D(n),v=D(u).minus(b).div(b).multipliedBy(100).decimalPlaces(2).toString();return D(v||"0").isZero()?"":v}return""},[u,n,r]);return{amount:D(u).isNaN()?"":u,typedValue:e,selectedPercentage:T,onChange:f,onPercentageChange:h,isTypedValue:e!==void 0}},Ri=(e="")=>{const{module:t,marketPrice:n,typedInputAmount:r}=K();return S.useMemo(()=>{if(D(r||"0").isZero()||!n||t!==G.STOP_LOSS&&t!==G.TAKE_PROFIT)return;const s=La(n||"",e||"",t);if(s!=null&&s.isError)return{type:me.STOP_LOSS_TRIGGER_PRICE_GREATER_THAN_MARKET_PRICE,value:s.value};const a=Ra(n||"",e||"",t);if(a!=null&&a.isError)return{type:me.TAKE_PROFIT_TRIGGER_PRICE_LESS_THAN_MARKET_PRICE,value:a.value};if(!e||D(e||0).isZero())return{type:me.EMPTY_TRIGGER_PRICE,value:e}},[n,e,t,r])},Ni=e=>{const{srcToken:t,dstToken:n,module:r,dstUsd1Token:s}=K(),a=He().amountPerTrade,i=H(h=>h.state.isMarketOrder),u=S.useMemo(()=>Pa(r,a,e,(t==null?void 0:t.decimals)||0),[e,a,i,t==null?void 0:t.decimals,r]),f=xt((n==null?void 0:n.decimals)||0,u);return{amount:u,amountUI:f,usd:qe(f,s)}},Ct=()=>{const{dstToken:e,dstUsd1Token:t,marketPrice:n,module:r,callbacks:s}=K(),a=H(_=>_.updateState),i=Li(),u=H(_=>_.state.triggerPricePercent),f=u===void 0?i:u,h=r===G.STOP_LOSS||r===G.TAKE_PROFIT,T=as({typedValue:H(_=>_.state.typedTriggerPrice),percentage:f,tokenDecimals:(e==null?void 0:e.decimals)||18,initialPrice:h?n:void 0,setValue:S.useCallback(_=>{var F;a({typedTriggerPrice:_}),(F=s==null?void 0:s.onTriggerPriceChange)==null||F.call(s,_||"")},[a,s]),setPercentage:S.useCallback(_=>{var F;a({triggerPricePercent:_}),(F=s==null?void 0:s.onTriggerPricePercentChange)==null||F.call(s,_||"")},[a,s])}),b=Ri(T.amount),x=xt((e==null?void 0:e.decimals)||18,T.amount),v=qe(x,t),{amount:O,amountUI:I,usd:B}=Ni(T.amount);return S.useMemo(()=>({...T,amountUI:D(x).isNaN()?"":x,usd:D(v).isNaN()?"":v,error:b,pricePerChunk:O,pricePerChunkUI:I,pricePerChunkUsd:B}),[T,x,v,b,O,I,B])},Ki=e=>{const{module:t,marketPrice:n,typedInputAmount:r}=K(),{amount:s}=Ct(),a=H(i=>i.state.isMarketOrder);return S.useMemo(()=>{if(D(r||"0").isZero()||!s||!n)return;const i=Na(s,e,a,t),u=Ka(s,e,a,t);if(i!=null&&i.isError)return{type:me.TRIGGER_LIMIT_PRICE_GREATER_THAN_TRIGGER_PRICE,value:i.value};if(u!=null&&u.isError)return{type:me.TRIGGER_LIMIT_PRICE_GREATER_THAN_TRIGGER_PRICE,value:u.value};if(e&&D(e||0).isZero())return{type:me.MISSING_LIMIT_PRICE,value:e||""}},[e,s,t,a,r,n])},Pn=()=>{const{dstToken:e,dstUsd1Token:t,marketPrice:n,callbacks:r}=K(),s=H(x=>x.updateState),a=or(),i=H(x=>x.state.limitPricePercent),u=i===void 0?a:i,f=as({typedValue:H(x=>x.state.typedLimitPrice),percentage:u,tokenDecimals:(e==null?void 0:e.decimals)||18,initialPrice:n,setValue:S.useCallback(x=>{var v;s({typedLimitPrice:x}),(v=r==null?void 0:r.onLimitPriceChange)==null||v.call(r,x||"")},[s,r]),setPercentage:S.useCallback(x=>{var v;s({limitPricePercent:x}),(v=r==null?void 0:r.onLimitPricePercentChange)==null||v.call(r,x||"")},[s,r])}),h=Ki(f.amount),T=xt((e==null?void 0:e.decimals)||18,f.amount),b=qe(T,t);return S.useMemo(()=>({...f,amountUI:D(T).isNaN()?"":T,usd:D(b).isNaN()?"":b,error:h}),[f,T,b,h])},qi=()=>{const{module:e}=K(),t=H(u=>u.updateState),n=H(u=>u.state.isMarketOrder),r=or(),s=H(u=>u.state.triggerPricePercent)||0,a=e===G.LIMIT,i=S.useCallback(()=>{!n&&e===G.STOP_LOSS&&t({limitPricePercent:r}),t({isMarketOrder:!n})},[t,s,e,n,r]);return{isLimitPrice:!n,toggleLimitPrice:i,hide:a}},Hi=()=>{const{module:e,marketPriceLoading:t,srcToken:n,dstToken:r,srcUsd1Token:s,dstUsd1Token:a}=K(),{amount:i,typedValue:u,onChange:f,onPercentageChange:h,selectedPercentage:T,error:b,isTypedValue:x}=Pn(),v=H(z=>z.updateState),O=or(),{isLimitPrice:I,toggleLimitPrice:B}=qi(),{fromToken:_,toToken:F,isInverted:q}=Dn(),k=ss({amount:i,typedValue:u,amountDecimals:(r==null?void 0:r.decimals)||18,invertedAmountDecimals:(n==null?void 0:n.decimals)||18,amountUsd:a,invertedAmountUsd:s,isInverted:q}),Q=S.useCallback(()=>{v({typedLimitPrice:void 0}),v({limitPricePercent:O})},[v,e,O]);return{price:k.amount,priceUI:k.amountUI,error:b,onInputChange:f,onPercentageChange:h,onReset:Q,usd:k.usd,srcToken:n,dstToken:r,invertedSrcToken:_,invertedDstToken:F,percentage:T,isLoading:t,isLimitPrice:I,toggleLimitPrice:B,isTypedValue:x}},$i=()=>{const{marketPrice:e,marketPriceLoading:t,srcToken:n,dstToken:r,srcUsd1Token:s,dstUsd1Token:a}=K(),{amount:i,typedValue:u,onChange:f,onPercentageChange:h,selectedPercentage:T,error:b,pricePerChunk:x,pricePerChunkUI:v,pricePerChunkUsd:O,isTypedValue:I}=Ct(),B=H(z=>z.updateState),{fromToken:_,toToken:F,isInverted:q}=Dn(),k=ss({amount:i,typedValue:u,amountDecimals:(r==null?void 0:r.decimals)||18,invertedAmountDecimals:(n==null?void 0:n.decimals)||18,amountUsd:a,invertedAmountUsd:s,isInverted:q}),Q=S.useCallback(()=>{B({triggerPricePercent:void 0,typedTriggerPrice:void 0})},[B]);return{price:k.amount,priceUI:k.amountUI,amountPerChunk:x,amountPerChunkUI:v,amountPerChunkUsd:O,error:b,onInputChange:f,onPercentageChange:h,percentage:T,onReset:Q,usd:k.usd,srcToken:n,dstToken:r,invertedSrcToken:_,invertedDstToken:F,isLoading:t||!e,isTypedValue:I}},is=()=>{const{module:e,marketPrice:t}=K(),n=Pn().amount,r=Ct().amount,s=H(a=>a.state.isMarketOrder);return e===G.LIMIT||!s?n||"":e===G.STOP_LOSS||e===G.TAKE_PROFIT?r||"":t||""},On=()=>{const{srcToken:e,dstToken:t,dstUsd1Token:n}=K(),r=is(),s=at().amount,a=S.useMemo(()=>Da(s||"",r,(e==null?void 0:e.decimals)||0),[s,r,e==null?void 0:e.decimals]),i=xt(t==null?void 0:t.decimals,a);return{amount:a,amountUI:i,usd:qe(i,n)}},cr=()=>{const{srcToken:e,dstToken:t,dstUsd1Token:n}=K(),r=is(),s=He().amountPerTrade,a=H(f=>f.state.isMarketOrder),i=S.useMemo(()=>va(s,r,!!a,(e==null?void 0:e.decimals)||0),[s,r,a,e==null?void 0:e.decimals]),u=xt(t==null?void 0:t.decimals,i);return{amount:i,amountUI:u,usd:qe(u,n)}},Wi=()=>{const{typedInputAmount:e,marketPriceLoading:t,dstToken:n}=K(),{amountUI:r,usd:s}=On(),i=Pi()?e:r,u=ar(n==null?void 0:n.decimals,i);return{value:i,valueWei:u,isLoading:t,usd:s}},zi=()=>{const e=H(s=>s.state.isMarketOrder),{module:t}=K(),n=S.useMemo(()=>{if(e&&t===G.STOP_LOSS)return sn.TRIGGER_MARKET_PRICE},[e,t]),r=S.useMemo(()=>{if(!(t!==G.LIMIT&&t!==G.TWAP))return e?sn.MARKET_PRICE:sn.LIMIT_PRICE},[e,t]);return n||r},Qi=()=>{const{minChunkSizeUsd:e,typedInputAmount:t,srcUsd1Token:n}=K(),r=qe(t,n);return S.useMemo(()=>{if(!(!D(t||0).gt(0)||!r))return D(e).gt(D(r))?{type:me.MIN_TRADE_SIZE_ERROR,value:e,args:{minTradeSize:`${e}`}}:void 0},[e,t,r])};function os(){const{marketPrice:e,marketPriceLoading:t,typedInputAmount:n,srcUsd1Token:r,srcBalance:s,chainId:a}=K(),{error:i}=Ct(),{error:u}=Pn(),{error:f}=He(),{error:h}=qt(),{error:T}=ir(),b=Qi(),x=at().amount,v=S.useMemo(()=>{if(s&&D(x).gt(s))return{type:me.INSUFFICIENT_BALANCE,value:s||""}},[s,x,a]);return S.useMemo(()=>Qa({marketPrice:e,typedInputAmount:n,srcUsd1Token:r,marketPriceLoading:t,triggerPriceError:i,limitPriceError:u,tradesError:f,fillDelayError:h,durationError:T,balanceError:v,minTradeSizeError:b}),[e,t,n,i,u,f,h,T,v,r,b])}var Ht=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(){}},ji={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Vi=(Rs=class{constructor(){N(this,$e,ji);N(this,St,!1)}setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&l(this,St)&&e!==l(this,$e)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:l(this,$e),provider:e}),U(this,$e,e),process.env.NODE_ENV!=="production"&&U(this,St,!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&U(this,St,!0),l(this,$e).setTimeout(e,t)}clearTimeout(e){l(this,$e).clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&U(this,St,!0),l(this,$e).setInterval(e,t)}clearInterval(e){l(this,$e).clearInterval(e)}},$e=new WeakMap,St=new WeakMap,Rs),Tt=new Vi;function Gi(e){setTimeout(e,0)}var wt=typeof window>"u"||"Deno"in globalThis;function xe(){}function Xi(e,t){return typeof e=="function"?e(t):e}function ur(e){return typeof e=="number"&&e>=0&&e!==1/0}function cs(e,t){return Math.max(e+(t||0)-Date.now(),0)}function it(e,t){return typeof e=="function"?e(t):e}function Me(e,t){return typeof e=="function"?e(t):e}function us(e,t){const{type:n="all",exact:r,fetchStatus:s,predicate:a,queryKey:i,stale:u}=e;if(i){if(r){if(t.queryHash!==dr(i,t.options))return!1}else if(!an(t.queryKey,i))return!1}if(n!=="all"){const f=t.isActive();if(n==="active"&&!f||n==="inactive"&&f)return!1}return!(typeof u=="boolean"&&t.isStale()!==u||s&&s!==t.state.fetchStatus||a&&!a(t))}function ds(e,t){const{exact:n,status:r,predicate:s,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(Ft(t.options.mutationKey)!==Ft(a))return!1}else if(!an(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function dr(e,t){return((t==null?void 0:t.queryKeyHashFn)||Ft)(e)}function Ft(e){return JSON.stringify(e,(t,n)=>fr(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function an(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>an(e[n],t[n])):!1}var Zi=Object.prototype.hasOwnProperty;function lr(e,t){if(e===t)return e;const n=ls(e)&&ls(t);if(!n&&!(fr(e)&&fr(t)))return t;const s=(n?e:Object.keys(e)).length,a=n?t:Object.keys(t),i=a.length,u=n?new Array(i):{};let f=0;for(let h=0;h<i;h++){const T=n?h:a[h],b=e[T],x=t[T];if(b===x){u[T]=b,(n?h<s:Zi.call(e,T))&&f++;continue}if(b===null||x===null||typeof b!="object"||typeof x!="object"){u[T]=x;continue}const v=lr(b,x);u[T]=v,v===b&&f++}return s===i&&f===s?e:u}function Bn(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 ls(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function fr(e){if(!fs(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!fs(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function fs(e){return Object.prototype.toString.call(e)==="[object Object]"}function Yi(e){return new Promise(t=>{Tt.setTimeout(t,e)})}function hr(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 lr(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 lr(e,t)}return t}function Ji(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function eo(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var In=Symbol();function hs(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===In&&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===In?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ps(e,t){return typeof e=="function"?e(...t):!!e}var to=(Ns=class extends Ht{constructor(){super();N(this,Dt);N(this,ct);N(this,Wt);U(this,Wt,t=>{if(!wt&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,ct)||this.setEventListener(l(this,Wt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ct))==null||t.call(this),U(this,ct,void 0))}setEventListener(t){var n;U(this,Wt,t),(n=l(this,ct))==null||n.call(this),U(this,ct,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,Dt)!==t&&(U(this,Dt,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof l(this,Dt)=="boolean"?l(this,Dt):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Dt=new WeakMap,ct=new WeakMap,Wt=new WeakMap,Ns),pr=new to;function mr(){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 no=Gi;function ro(){let e=[],t=0,n=u=>{u()},r=u=>{u()},s=no;const a=u=>{t?e.push(u):s(()=>{n(u)})},i=()=>{const u=e;e=[],u.length&&s(()=>{r(()=>{u.forEach(f=>{n(f)})})})};return{batch:u=>{let f;t++;try{f=u()}finally{t--,t||i()}return f},batchCalls:u=>(...f)=>{a(()=>{u(...f)})},schedule:a,setNotifyFunction:u=>{n=u},setBatchNotifyFunction:u=>{r=u},setScheduler:u=>{s=u}}}var le=ro(),so=(Ks=class extends Ht{constructor(){super();N(this,zt,!0);N(this,ut);N(this,Qt);U(this,Qt,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,ut)||this.setEventListener(l(this,Qt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ut))==null||t.call(this),U(this,ut,void 0))}setEventListener(t){var n;U(this,Qt,t),(n=l(this,ut))==null||n.call(this),U(this,ut,t(this.setOnline.bind(this)))}setOnline(t){l(this,zt)!==t&&(U(this,zt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,zt)}},zt=new WeakMap,ut=new WeakMap,Qt=new WeakMap,Ks),Mn=new so;function ao(e){return Math.min(1e3*2**e,3e4)}function ms(e){return(e??"online")==="online"?Mn.isOnline():!0}var yr=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function ys(e){let t=!1,n=0,r;const s=mr(),a=()=>s.status!=="pending",i=I=>{var B;if(!a()){const _=new yr(I);x(_),(B=e.onCancel)==null||B.call(e,_)}},u=()=>{t=!0},f=()=>{t=!1},h=()=>pr.isFocused()&&(e.networkMode==="always"||Mn.isOnline())&&e.canRun(),T=()=>ms(e.networkMode)&&e.canRun(),b=I=>{a()||(r==null||r(),s.resolve(I))},x=I=>{a()||(r==null||r(),s.reject(I))},v=()=>new Promise(I=>{var B;r=_=>{(a()||h())&&I(_)},(B=e.onPause)==null||B.call(e)}).then(()=>{var I;r=void 0,a()||(I=e.onContinue)==null||I.call(e)}),O=()=>{if(a())return;let I;const B=n===0?e.initialPromise:void 0;try{I=B??e.fn()}catch(_){I=Promise.reject(_)}Promise.resolve(I).then(b).catch(_=>{var z;if(a())return;const F=e.retry??(wt?0:3),q=e.retryDelay??ao,k=typeof q=="function"?q(n,_):q,Q=F===!0||typeof F=="number"&&n<F||typeof F=="function"&&F(n,_);if(t||!Q){x(_);return}n++,(z=e.onFail)==null||z.call(e,n,_),Yi(k).then(()=>h()?void 0:v()).then(()=>{t?x(_):O()})})};return{promise:s,status:()=>s.status,cancel:i,continue:()=>(r==null||r(),s),cancelRetry:u,continueRetry:f,canStart:T,start:()=>(T()?O():v().then(O),s)}}var As=(qs=class{constructor(){N(this,vt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ur(this.gcTime)&&U(this,vt,Tt.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(wt?1/0:300*1e3))}clearGcTimeout(){l(this,vt)&&(Tt.clearTimeout(l(this,vt)),U(this,vt,void 0))}},vt=new WeakMap,qs),io=(Hs=class extends As{constructor(t){super();N(this,Ne);N(this,Pt);N(this,jt);N(this,ke);N(this,Ot);N(this,pe);N(this,on);N(this,Bt);U(this,Bt,!1),U(this,on,t.defaultOptions),this.setOptions(t.options),this.observers=[],U(this,Ot,t.client),U(this,ke,l(this,Ot).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,U(this,Pt,Es(this.options)),this.state=t.state??l(this,Pt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=l(this,pe))==null?void 0:t.promise}setOptions(t){if(this.options={...l(this,on),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=Es(this.options);n.data!==void 0&&(this.setState(bs(n.data,n.dataUpdatedAt)),U(this,Pt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,ke).remove(this)}setData(t,n){const r=hr(this.state.data,t,this.options);return j(this,Ne,tt).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){j(this,Ne,tt).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,s;const n=(r=l(this,pe))==null?void 0:r.promise;return(s=l(this,pe))==null||s.cancel(t),n?n.then(xe).catch(xe):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(l(this,Pt))}isActive(){return this.observers.some(t=>Me(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===In||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>it(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:!cs(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=l(this,pe))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=l(this,pe))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,ke).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,pe)&&(l(this,Bt)?l(this,pe).cancel({revert:!0}):l(this,pe).cancelRetry()),this.scheduleGc()),l(this,ke).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||j(this,Ne,tt).call(this,{type:"invalidate"})}async fetch(t,n){var f,h,T,b,x,v,O,I,B,_,F,q;if(this.state.fetchStatus!=="idle"&&((f=l(this,pe))==null?void 0:f.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(l(this,pe))return l(this,pe).continueRetry(),l(this,pe).promise}if(t&&this.setOptions(t),!this.options.queryFn){const k=this.observers.find(Q=>Q.options.queryFn);k&&this.setOptions(k.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=k=>{Object.defineProperty(k,"signal",{enumerable:!0,get:()=>(U(this,Bt,!0),r.signal)})},a=()=>{const k=hs(this.options,n),z=(()=>{const re={client:l(this,Ot),queryKey:this.queryKey,meta:this.meta};return s(re),re})();return U(this,Bt,!1),this.options.persister?this.options.persister(k,z,this):k(z)},u=(()=>{const k={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:l(this,Ot),state:this.state,fetchFn:a};return s(k),k})();(h=this.options.behavior)==null||h.onFetch(u,this),U(this,jt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((T=u.fetchOptions)==null?void 0:T.meta))&&j(this,Ne,tt).call(this,{type:"fetch",meta:(b=u.fetchOptions)==null?void 0:b.meta}),U(this,pe,ys({initialPromise:n==null?void 0:n.initialPromise,fn:u.fetchFn,onCancel:k=>{k instanceof yr&&k.revert&&this.setState({...l(this,jt),fetchStatus:"idle"}),r.abort()},onFail:(k,Q)=>{j(this,Ne,tt).call(this,{type:"failed",failureCount:k,error:Q})},onPause:()=>{j(this,Ne,tt).call(this,{type:"pause"})},onContinue:()=>{j(this,Ne,tt).call(this,{type:"continue"})},retry:u.options.retry,retryDelay:u.options.retryDelay,networkMode:u.options.networkMode,canRun:()=>!0}));try{const k=await l(this,pe).start();if(k===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(k),(v=(x=l(this,ke).config).onSuccess)==null||v.call(x,k,this),(I=(O=l(this,ke).config).onSettled)==null||I.call(O,k,this.state.error,this),k}catch(k){if(k instanceof yr){if(k.silent)return l(this,pe).promise;if(k.revert){if(this.state.data===void 0)throw k;return this.state.data}}throw j(this,Ne,tt).call(this,{type:"error",error:k}),(_=(B=l(this,ke).config).onError)==null||_.call(B,k,this),(q=(F=l(this,ke).config).onSettled)==null||q.call(F,this.state.data,k,this),k}finally{this.scheduleGc()}}},Pt=new WeakMap,jt=new WeakMap,ke=new WeakMap,Ot=new WeakMap,pe=new WeakMap,on=new WeakMap,Bt=new WeakMap,Ne=new WeakSet,tt=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,...gs(r.data,this.options),fetchMeta:t.meta??null};case"success":const s={...r,...bs(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return U(this,jt,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),le.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),l(this,ke).notify({query:this,type:"updated",action:t})})},Hs);function gs(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ms(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function bs(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Es(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 oo=($s=class extends Ht{constructor(t,n){super();N(this,ee);N(this,Se);N(this,Y);N(this,cn);N(this,Ce);N(this,It);N(this,Vt);N(this,Xe);N(this,dt);N(this,un);N(this,Gt);N(this,Xt);N(this,Mt);N(this,kt);N(this,lt);N(this,Zt,new Set);this.options=n,U(this,Se,t),U(this,dt,null),U(this,Xe,mr()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,Y).addObserver(this),xs(l(this,Y),this.options)?j(this,ee,hn).call(this):this.updateResult(),j(this,ee,vr).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ar(l(this,Y),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ar(l(this,Y),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,j(this,ee,Pr).call(this),j(this,ee,Or).call(this),l(this,Y).removeObserver(this)}setOptions(t){const n=this.options,r=l(this,Y);if(this.options=l(this,Se).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Me(this.options.enabled,l(this,Y))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");j(this,ee,Br).call(this),l(this,Y).setOptions(this.options),n._defaulted&&!Bn(this.options,n)&&l(this,Se).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,Y),observer:this});const s=this.hasListeners();s&&Cs(l(this,Y),r,this.options,n)&&j(this,ee,hn).call(this),this.updateResult(),s&&(l(this,Y)!==r||Me(this.options.enabled,l(this,Y))!==Me(n.enabled,l(this,Y))||it(this.options.staleTime,l(this,Y))!==it(n.staleTime,l(this,Y)))&&j(this,ee,Fr).call(this);const a=j(this,ee,Sr).call(this);s&&(l(this,Y)!==r||Me(this.options.enabled,l(this,Y))!==Me(n.enabled,l(this,Y))||a!==l(this,lt))&&j(this,ee,Dr).call(this,a)}getOptimisticResult(t){const n=l(this,Se).getQueryCache().build(l(this,Se),t),r=this.createResult(n,t);return uo(this,r)&&(U(this,Ce,r),U(this,Vt,this.options),U(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,Xe).status==="pending"&&l(this,Xe).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,Zt).add(t)}getCurrentQuery(){return l(this,Y)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=l(this,Se).defaultQueryOptions(t),r=l(this,Se).getQueryCache().build(l(this,Se),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return j(this,ee,hn).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),i=l(this,It),u=l(this,Vt),h=t!==r?t.state:l(this,cn),{state:T}=t;let b={...T},x=!1,v;if(n._optimisticResults){const d=this.hasListeners(),g=!d&&xs(t,n),m=d&&Cs(t,r,n,s);(g||m)&&(b={...b,...gs(T.data,t.options)}),n._optimisticResults==="isRestoring"&&(b.fetchStatus="idle")}let{error:O,errorUpdatedAt:I,status:B}=b;v=b.data;let _=!1;if(n.placeholderData!==void 0&&v===void 0&&B==="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,Xt))==null?void 0:c.state.data,l(this,Xt)):n.placeholderData,d!==void 0&&(B="success",v=hr(a==null?void 0:a.data,d,n),x=!0)}if(n.select&&v!==void 0&&!_)if(a&&v===(i==null?void 0:i.data)&&n.select===l(this,un))v=l(this,Gt);else try{U(this,un,n.select),v=n.select(v),v=hr(a==null?void 0:a.data,v,n),U(this,Gt,v),U(this,dt,null)}catch(d){U(this,dt,d)}l(this,dt)&&(O=l(this,dt),v=l(this,Gt),I=Date.now(),B="error");const F=b.fetchStatus==="fetching",q=B==="pending",k=B==="error",Q=q&&F,z=v!==void 0,o={status:B,fetchStatus:b.fetchStatus,isPending:q,isSuccess:B==="success",isError:k,isInitialLoading:Q,isLoading:Q,data:v,dataUpdatedAt:b.dataUpdatedAt,error:O,errorUpdatedAt:I,failureCount:b.fetchFailureCount,failureReason:b.fetchFailureReason,errorUpdateCount:b.errorUpdateCount,isFetched:b.dataUpdateCount>0||b.errorUpdateCount>0,isFetchedAfterMount:b.dataUpdateCount>h.dataUpdateCount||b.errorUpdateCount>h.errorUpdateCount,isFetching:F,isRefetching:F&&!q,isLoadingError:k&&!z,isPaused:b.fetchStatus==="paused",isPlaceholderData:x,isRefetchError:k&&z,isStale:gr(t,n),refetch:this.refetch,promise:l(this,Xe),isEnabled:Me(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const d=y=>{o.status==="error"?y.reject(o.error):o.data!==void 0&&y.resolve(o.data)},g=()=>{const y=U(this,Xe,o.promise=mr());d(y)},m=l(this,Xe);switch(m.status){case"pending":t.queryHash===r.queryHash&&d(m);break;case"fulfilled":(o.status==="error"||o.data!==m.value)&&g();break;case"rejected":(o.status!=="error"||o.error!==m.reason)&&g();break}}return o}updateResult(){const t=l(this,Ce),n=this.createResult(l(this,Y),this.options);if(U(this,It,l(this,Y).state),U(this,Vt,this.options),l(this,It).data!==void 0&&U(this,Xt,l(this,Y)),Bn(n,t))return;U(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,Zt).size)return!0;const i=new Set(a??l(this,Zt));return this.options.throwOnError&&i.add("error"),Object.keys(l(this,Ce)).some(u=>{const f=u;return l(this,Ce)[f]!==t[f]&&i.has(f)})};j(this,ee,Xs).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&j(this,ee,vr).call(this)}},Se=new WeakMap,Y=new WeakMap,cn=new WeakMap,Ce=new WeakMap,It=new WeakMap,Vt=new WeakMap,Xe=new WeakMap,dt=new WeakMap,un=new WeakMap,Gt=new WeakMap,Xt=new WeakMap,Mt=new WeakMap,kt=new WeakMap,lt=new WeakMap,Zt=new WeakMap,ee=new WeakSet,hn=function(t){j(this,ee,Br).call(this);let n=l(this,Y).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(xe)),n},Fr=function(){j(this,ee,Pr).call(this);const t=it(this.options.staleTime,l(this,Y));if(wt||l(this,Ce).isStale||!ur(t))return;const r=cs(l(this,Ce).dataUpdatedAt,t)+1;U(this,Mt,Tt.setTimeout(()=>{l(this,Ce).isStale||this.updateResult()},r))},Sr=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,Y)):this.options.refetchInterval)??!1},Dr=function(t){j(this,ee,Or).call(this),U(this,lt,t),!(wt||Me(this.options.enabled,l(this,Y))===!1||!ur(l(this,lt))||l(this,lt)===0)&&U(this,kt,Tt.setInterval(()=>{(this.options.refetchIntervalInBackground||pr.isFocused())&&j(this,ee,hn).call(this)},l(this,lt)))},vr=function(){j(this,ee,Fr).call(this),j(this,ee,Dr).call(this,j(this,ee,Sr).call(this))},Pr=function(){l(this,Mt)&&(Tt.clearTimeout(l(this,Mt)),U(this,Mt,void 0))},Or=function(){l(this,kt)&&(Tt.clearInterval(l(this,kt)),U(this,kt,void 0))},Br=function(){const t=l(this,Se).getQueryCache().build(l(this,Se),this.options);if(t===l(this,Y))return;const n=l(this,Y);U(this,Y,t),U(this,cn,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},Xs=function(t){le.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,Ce))}),l(this,Se).getQueryCache().notify({query:l(this,Y),type:"observerResultsUpdated"})})},$s);function co(e,t){return Me(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function xs(e,t){return co(e,t)||e.state.data!==void 0&&Ar(e,t,t.refetchOnMount)}function Ar(e,t,n){if(Me(t.enabled,e)!==!1&&it(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&gr(e,t)}return!1}function Cs(e,t,n,r){return(e!==t||Me(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&gr(e,n)}function gr(e,t){return Me(t.enabled,e)!==!1&&e.isStaleByTime(it(t.staleTime,e))}function uo(e,t){return!Bn(e.getCurrentResult(),t)}function Ts(e){return{onFetch:(t,n)=>{var T,b,x,v,O;const r=t.options,s=(x=(b=(T=t.fetchOptions)==null?void 0:T.meta)==null?void 0:b.fetchMore)==null?void 0:x.direction,a=((v=t.state.data)==null?void 0:v.pages)||[],i=((O=t.state.data)==null?void 0:O.pageParams)||[];let u={pages:[],pageParams:[]},f=0;const h=async()=>{let I=!1;const B=q=>{Object.defineProperty(q,"signal",{enumerable:!0,get:()=>(t.signal.aborted?I=!0:t.signal.addEventListener("abort",()=>{I=!0}),t.signal)})},_=hs(t.options,t.fetchOptions),F=async(q,k,Q)=>{if(I)return Promise.reject();if(k==null&&q.pages.length)return Promise.resolve(q);const re=(()=>{const g={client:t.client,queryKey:t.queryKey,pageParam:k,direction:Q?"backward":"forward",meta:t.options.meta};return B(g),g})(),o=await _(re),{maxPages:c}=t.options,d=Q?eo:Ji;return{pages:d(q.pages,o,c),pageParams:d(q.pageParams,k,c)}};if(s&&a.length){const q=s==="backward",k=q?lo:ws,Q={pages:a,pageParams:i},z=k(r,Q);u=await F(Q,z,q)}else{const q=e??a.length;do{const k=f===0?i[0]??r.initialPageParam:ws(r,u);if(f>0&&k==null)break;u=await F(u,k),f++}while(f<q)}return u};t.options.persister?t.fetchFn=()=>{var I,B;return(B=(I=t.options).persister)==null?void 0:B.call(I,h,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=h}}}function ws(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 lo(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 fo=(Ws=class extends As{constructor(t){super();N(this,ze);N(this,dn);N(this,We);N(this,Te);N(this,_t);U(this,dn,t.client),this.mutationId=t.mutationId,U(this,Te,t.mutationCache),U(this,We,[]),this.state=t.state||Fs(),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){U(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,_t))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,u,f,h,T,b,x,v,O,I,B,_,F,q,k,Q,z,re,o,c;const n=()=>{j(this,ze,yt).call(this,{type:"continue"})},r={client:l(this,dn),meta:this.options.meta,mutationKey:this.options.mutationKey};U(this,_t,ys({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(d,g)=>{j(this,ze,yt).call(this,{type:"failed",failureCount:d,error:g})},onPause:()=>{j(this,ze,yt).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,_t).canStart();try{if(s)n();else{j(this,ze,yt).call(this,{type:"pending",variables:t,isPaused:a}),await((u=(i=l(this,Te).config).onMutate)==null?void 0:u.call(i,t,this,r));const g=await((h=(f=this.options).onMutate)==null?void 0:h.call(f,t,r));g!==this.state.context&&j(this,ze,yt).call(this,{type:"pending",context:g,variables:t,isPaused:a})}const d=await l(this,_t).start();return await((b=(T=l(this,Te).config).onSuccess)==null?void 0:b.call(T,d,t,this.state.context,this,r)),await((v=(x=this.options).onSuccess)==null?void 0:v.call(x,d,t,this.state.context,r)),await((I=(O=l(this,Te).config).onSettled)==null?void 0:I.call(O,d,null,this.state.variables,this.state.context,this,r)),await((_=(B=this.options).onSettled)==null?void 0:_.call(B,d,null,t,this.state.context,r)),j(this,ze,yt).call(this,{type:"success",data:d}),d}catch(d){try{throw await((q=(F=l(this,Te).config).onError)==null?void 0:q.call(F,d,t,this.state.context,this,r)),await((Q=(k=this.options).onError)==null?void 0:Q.call(k,d,t,this.state.context,r)),await((re=(z=l(this,Te).config).onSettled)==null?void 0:re.call(z,void 0,d,this.state.variables,this.state.context,this,r)),await((c=(o=this.options).onSettled)==null?void 0:c.call(o,void 0,d,t,this.state.context,r)),d}finally{j(this,ze,yt).call(this,{type:"error",error:d})}}finally{l(this,Te).runNext(this)}}},dn=new WeakMap,We=new WeakMap,Te=new WeakMap,_t=new WeakMap,ze=new WeakSet,yt=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),le.batch(()=>{l(this,We).forEach(r=>{r.onMutationUpdate(t)}),l(this,Te).notify({mutation:this,type:"updated",action:t})})},Ws);function Fs(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ho=(zs=class extends Ht{constructor(t={}){super();N(this,Ze);N(this,Ke);N(this,ln);this.config=t,U(this,Ze,new Set),U(this,Ke,new Map),U(this,ln,0)}build(t,n,r){const s=new fo({client:t,mutationCache:this,mutationId:++Rn(this,ln)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Ze).add(t);const n=kn(t);if(typeof n=="string"){const r=l(this,Ke).get(n);r?r.push(t):l(this,Ke).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Ze).delete(t)){const n=kn(t);if(typeof n=="string"){const r=l(this,Ke).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,Ke).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=kn(t);if(typeof n=="string"){const r=l(this,Ke).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=kn(t);if(typeof n=="string"){const s=(r=l(this,Ke).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(){le.batch(()=>{l(this,Ze).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Ze).clear(),l(this,Ke).clear()})}getAll(){return Array.from(l(this,Ze))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>ds(n,r))}findAll(t={}){return this.getAll().filter(n=>ds(t,n))}notify(t){le.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return le.batch(()=>Promise.all(t.map(n=>n.continue().catch(xe))))}},Ze=new WeakMap,Ke=new WeakMap,ln=new WeakMap,zs);function kn(e){var t;return(t=e.options.scope)==null?void 0:t.id}var po=(Qs=class extends Ht{constructor(t,n){super();N(this,et);N(this,Ye);N(this,ft);N(this,De);N(this,Je);U(this,Ye,t),this.setOptions(n),this.bindMethods(),j(this,et,Nn).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,Ye).defaultMutationOptions(t),Bn(this.options,n)||l(this,Ye).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,De),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&Ft(n.mutationKey)!==Ft(this.options.mutationKey)?this.reset():((r=l(this,De))==null?void 0:r.state.status)==="pending"&&l(this,De).setOptions(this.options)}onUnsubscribe(){var t;this.hasListeners()||(t=l(this,De))==null||t.removeObserver(this)}onMutationUpdate(t){j(this,et,Nn).call(this),j(this,et,Ir).call(this,t)}getCurrentResult(){return l(this,ft)}reset(){var t;(t=l(this,De))==null||t.removeObserver(this),U(this,De,void 0),j(this,et,Nn).call(this),j(this,et,Ir).call(this)}mutate(t,n){var r;return U(this,Je,n),(r=l(this,De))==null||r.removeObserver(this),U(this,De,l(this,Ye).getMutationCache().build(l(this,Ye),this.options)),l(this,De).addObserver(this),l(this,De).execute(t)}},Ye=new WeakMap,ft=new WeakMap,De=new WeakMap,Je=new WeakMap,et=new WeakSet,Nn=function(){var n;const t=((n=l(this,De))==null?void 0:n.state)??Fs();U(this,ft,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Ir=function(t){le.batch(()=>{var n,r,s,a,i,u,f,h;if(l(this,Je)&&this.hasListeners()){const T=l(this,ft).variables,b=l(this,ft).context,x={client:l(this,Ye),meta:this.options.meta,mutationKey:this.options.mutationKey};(t==null?void 0:t.type)==="success"?((r=(n=l(this,Je)).onSuccess)==null||r.call(n,t.data,T,b,x),(a=(s=l(this,Je)).onSettled)==null||a.call(s,t.data,null,T,b,x)):(t==null?void 0:t.type)==="error"&&((u=(i=l(this,Je)).onError)==null||u.call(i,t.error,T,b,x),(h=(f=l(this,Je)).onSettled)==null||h.call(f,void 0,t.error,T,b,x))}this.listeners.forEach(T=>{T(l(this,ft))})})},Qs),mo=(js=class extends Ht{constructor(t={}){super();N(this,Qe);this.config=t,U(this,Qe,new Map)}build(t,n,r){const s=n.queryKey,a=n.queryHash??dr(s,n);let i=this.get(a);return i||(i=new io({client:t,queryKey:s,queryHash:a,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(i)),i}add(t){l(this,Qe).has(t.queryHash)||(l(this,Qe).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=l(this,Qe).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,Qe).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){le.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,Qe).get(t)}getAll(){return[...l(this,Qe).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>us(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>us(t,r)):n}notify(t){le.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){le.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){le.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Qe=new WeakMap,js),yo=(Vs=class{constructor(e={}){N(this,ae);N(this,ht);N(this,pt);N(this,Yt);N(this,Jt);N(this,mt);N(this,en);N(this,tn);U(this,ae,e.queryCache||new mo),U(this,ht,e.mutationCache||new ho),U(this,pt,e.defaultOptions||{}),U(this,Yt,new Map),U(this,Jt,new Map),U(this,mt,0)}mount(){Rn(this,mt)._++,l(this,mt)===1&&(U(this,en,pr.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,ae).onFocus())})),U(this,tn,Mn.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,ae).onOnline())})))}unmount(){var e,t;Rn(this,mt)._--,l(this,mt)===0&&((e=l(this,en))==null||e.call(this),U(this,en,void 0),(t=l(this,tn))==null||t.call(this),U(this,tn,void 0))}isFetching(e){return l(this,ae).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,ht).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=l(this,ae).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=l(this,ae).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(it(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,ae).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,ae).get(r.queryHash),a=s==null?void 0:s.state.data,i=Xi(t,a);if(i!==void 0)return l(this,ae).build(this,r).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return le.batch(()=>l(this,ae).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,ae).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=l(this,ae);le.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=l(this,ae);return le.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=le.batch(()=>l(this,ae).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(xe).catch(xe)}invalidateQueries(e,t={}){return le.batch(()=>(l(this,ae).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=le.batch(()=>l(this,ae).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let a=s.fetch(void 0,n);return n.throwOnError||(a=a.catch(xe)),s.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(xe)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=l(this,ae).build(this,t);return n.isStaleByTime(it(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(xe).catch(xe)}fetchInfiniteQuery(e){return e.behavior=Ts(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(xe).catch(xe)}ensureInfiniteQueryData(e){return e.behavior=Ts(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Mn.isOnline()?l(this,ht).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,ae)}getMutationCache(){return l(this,ht)}getDefaultOptions(){return l(this,pt)}setDefaultOptions(e){U(this,pt,e)}setQueryDefaults(e,t){l(this,Yt).set(Ft(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...l(this,Yt).values()],n={};return t.forEach(r=>{an(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,Jt).set(Ft(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...l(this,Jt).values()],n={};return t.forEach(r=>{an(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...l(this,pt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=dr(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===In&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...l(this,pt).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,ae).clear(),l(this,ht).clear()}},ae=new WeakMap,ht=new WeakMap,pt=new WeakMap,Yt=new WeakMap,Jt=new WeakMap,mt=new WeakMap,en=new WeakMap,tn=new WeakMap,Vs),Ss=ce.createContext(void 0),$t=e=>{const t=ce.useContext(Ss);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Ao=({client:e,children:t})=>(ce.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),$.jsx(Ss.Provider,{value:e,children:t})),Ds=ce.createContext(!1),go=()=>ce.useContext(Ds);Ds.Provider;function bo(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Eo=ce.createContext(bo()),xo=()=>ce.useContext(Eo),Co=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},To=e=>{ce.useEffect(()=>{e.clearReset()},[e])},wo=({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])),Fo=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))}},So=(e,t)=>e.isLoading&&e.isFetching&&!t,Do=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,vs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function vo(e,t,n){var b,x,v,O,I;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=go(),s=xo(),a=$t(),i=a.defaultQueryOptions(e);(x=(b=a.getDefaultOptions().queries)==null?void 0:b._experimental_beforeQuery)==null||x.call(b,i),process.env.NODE_ENV!=="production"&&(i.queryFn||console.error(`[${i.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`)),i._optimisticResults=r?"isRestoring":"optimistic",Fo(i),Co(i,s),To(s);const u=!a.getQueryCache().get(i.queryHash),[f]=ce.useState(()=>new t(a,i)),h=f.getOptimisticResult(i),T=!r&&e.subscribed!==!1;if(ce.useSyncExternalStore(ce.useCallback(B=>{const _=T?f.subscribe(le.batchCalls(B)):xe;return f.updateResult(),_},[f,T]),()=>f.getCurrentResult(),()=>f.getCurrentResult()),ce.useEffect(()=>{f.setOptions(i)},[i,f]),Do(i,h))throw vs(i,f,s);if(wo({result:h,errorResetBoundary:s,throwOnError:i.throwOnError,query:a.getQueryCache().get(i.queryHash),suspense:i.suspense}))throw h.error;if((O=(v=a.getDefaultOptions().queries)==null?void 0:v._experimental_afterQuery)==null||O.call(v,i,h),i.experimental_prefetchInRender&&!wt&&So(h,r)){const B=u?vs(i,f,s):(I=a.getQueryCache().get(i.queryHash))==null?void 0:I.promise;B==null||B.catch(xe).finally(()=>{f.updateResult()})}return i.notifyOnChangeProps?h:f.trackResult(h)}function Ps(e,t){return vo(e,oo)}function ot(e,t){const n=$t(),[r]=ce.useState(()=>new po(n,e));ce.useEffect(()=>{r.setOptions(e)},[r,e]);const s=ce.useSyncExternalStore(ce.useCallback(i=>r.subscribe(le.batchCalls(i)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=ce.useCallback((i,u)=>{r.mutate(i,u).catch(xe)},[r]);if(s.error&&ps(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:a,mutateAsync:s.mutate}}const Po=2e4,Re=()=>{const{partner:e,chainId:t,isDev:n=!1,minChunkSizeUsd:r}=K(),{data:s,error:a,isFetching:i,isLoading:u,refetch:f}=Ps({queryKey:["repermit-data",e,t,n],queryFn:()=>{if(!Gn(e).includes(t))throw new Error(`Partner "${e}" is not supported on chain ${t}`);return zr(e,t,n)},staleTime:1/0,gcTime:1/0,retry:2}),h=u||i;return S.useEffect(()=>{s&&de.onFetchedConfig(s,e,Zn(e,t),r,n)},[t,s,n,r,e]),S.useMemo(()=>({data:s,error:a,isLoading:h,refetch:f}),[s,a,h,f])},Oo=()=>{const{module:e}=K(),t=H(n=>n.state.isMarketOrder);return S.useMemo(()=>e===G.TWAP?t?X.TWAP_MARKET:X.TWAP_LIMIT:e===G.LIMIT?X.LIMIT:e===G.STOP_LOSS?t?X.STOP_LOSS_MARKET:X.STOP_LOSS_LIMIT:e===G.TAKE_PROFIT?t?X.TAKE_PROFIT_MARKET:X.TAKE_PROFIT_LIMIT:X.TWAP_MARKET,[e,t])},Os=(e,t,n,r,s,a)=>["useTwapOrderHistoryManager",e,t,n,r,s,a],_n=()=>{const{account:e,partner:t,chainId:n,isDev:r,supportLegacyOrders:s}=K(),{data:a}=Re(),i=a==null?void 0:a.order.witness.exchange.adapter;return S.useMemo(()=>Os(e,i,t,n,r,s),[e,i,t,n,r,s])},Bo=()=>{const{account:e,partner:t,chainId:n,isDev:r,supportLegacyOrders:s}=K();return S.useMemo(()=>Os(e,void 0,t,n,r,s),[e,t,n,r,s])},Io=()=>{const e=$t(),{account:t}=K(),n=_n();return S.useCallback(r=>{e.setQueryData(n,s=>s?s!=null&&s.some(a=>a.id===r.id)?s:[r,...s]:[r])},[e,n,t])},Mo=()=>{const e=$t(),t=_n();return S.useCallback((n,r)=>{e.setQueryData(t,s=>s==null?void 0:s.map(a=>a.id===n?{...a,status:r}:a))},[e,t])},ko=()=>{const{callbacks:e}=K(),t=$t(),n=_n();return S.useCallback(r=>{var u;const s=t.getQueryData(n);let a=!1;const i=[];s&&s.filter(f=>f.version===2).forEach(f=>{var T;const h=r.find(b=>b.id===f.id);h&&h.progress!==f.progress&&(a=!0,i.push(h),h.status===ue.Completed&&((T=e==null?void 0:e.onOrderFilled)==null||T.call(e,h)))}),a&&((u=e==null?void 0:e.onOrdersProgressUpdate)==null||u.call(e,i))},[t,n,e])},_o=(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)},br=()=>{const{account:e,partner:t,chainId:n,isDev:r,supportLegacyOrders:s}=K(),{data:a}=Re(),i=$t(),u=S.useMemo(()=>s?Zn(t,n):void 0,[n,t,s]),f=_n(),h=Bo(),T=ko();return Ps({refetchInterval:Po,refetchOnWindowFocus:!0,retry:!1,gcTime:1/0,staleTime:1/0,queryKey:f,enabled:!!(e&&n),queryFn:async({signal:x})=>{if(!e||!n)return[];const v=i.getQueryData(f)??i.getQueryData(h),O=s&&!v,I=await gi({signal:x,chainId:n,exchange:a==null?void 0:a.order.witness.exchange.adapter,partner:t,twapConfig:u,account:e,isDev:r,includeV1GraphOrders:O,includeV2Orders:!!a});return T(I),!s||O?I:_o(I,v)}})},Uo=(e,t,n)=>S.useMemo(()=>{if(!(!e||!t||!n||n!=null&&n.isMarketPrice))return qr(n,e==null?void 0:e.decimals,t==null?void 0:t.decimals)},[n,e,t]),Lo=(e,t,n)=>S.useMemo(()=>{if(!(!e||!t||!n))return Hr(n,e.decimals,t.decimals)},[n,e,t]),Ro=(e,t,n)=>S.useMemo(()=>{if(!(!e||!t||!n))return Xn(n.srcAmountFilled,n.dstAmountFilled,e.decimals,t.decimals)},[n,e,t]),Un=(e,t)=>[...e.filter(r=>r.status===t)].sort((r,s)=>s.createdAt-r.createdAt),No=()=>{const{data:e,isLoading:t,refetch:n,isRefetching:r}=br(),s=S.useCallback(()=>n().then(a=>a.data),[n]);return S.useMemo(()=>({orders:{all:e??[],open:Un(e??[],ue.Open),completed:Un(e??[],ue.Completed),cancelled:Un(e??[],ue.Cancelled),expired:Un(e??[],ue.Expired)},isLoading:t,isRefetching:r,refetchOrders:s}),[e,t,r,s])},Er=()=>{const e=H(n=>n.state.currentTime),t=ir().duration;return S.useMemo(()=>Ma(e,t),[e,t])},Bs=()=>{const{srcToken:e,dstToken:t,account:n,chainId:r,slippage:s,module:a}=K(),i=H(F=>F.state.currentTime),{amount:u}=at(),{amountPerTrade:f,totalTrades:h}=He(),T=Er(),{amount:b}=cr(),{pricePerChunk:x}=Ct(),{milliseconds:v}=qt(),{data:O,error:I,isLoading:B}=Re(),_=S.useMemo(()=>{if(O)return Qr({chainId:r,srcTokenAddress:(e==null?void 0:e.address)||"",dstTokenAddress:(t==null?void 0:t.address)||"",totalSrcAmount:u,currentTimeMillis:i,deadlineMillis:T,fillDelayMillis:v,totalTrades:h,slippageBps:s*100,swapperAddress:n,srcAmountPerTrade:f,minDstAmountPerTrade:b,triggerAmountPerTrade:x,permitData:O,module:a})},[O,e,t,n,r,i,s,a,u,f,h,T,v,b,x]);return S.useMemo(()=>({data:_,error:I,isLoading:B}),[_,I,B])};function Ko(e){const t=e.slice(2);if(t.length===128){const a=`0x${t.slice(0,64)}`,i=parseInt(t.charAt(64),16),u=(i>>3)+27,f=`0x${(i&7).toString(16)}${t.slice(65,128)}`;return{r:a,s:f,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 qo=()=>{var a;const{account:e,walletInteractions:t,callbacks:n,chainId:r}=K(),s=(a=Sn())==null?void 0:a.wToken;return ot({mutationFn:async({onHash:i,srcAmountWei:u})=>{var h,T;if(!e)throw new Error("missing account");if(!t)throw new Error("missing walletInteractions");if(!s)throw new Error("tokenAddress is not defined");de.onWrapRequest();const f=await t.wrapNativeToken(u);return(h=n==null?void 0:n.onWrapRequest)==null||h.call(n),i==null||i(f),de.onWrapSuccess(f),(T=n==null?void 0:n.onWrapSuccess)==null||T.call(n,{txHash:f,explorerUrl:Nt(f,r),amount:ge(u,s.decimals)}),f},onError:i=>{throw de.onWrapError(i),i}})},Is=()=>{const{account:e,walletInteractions:t,chainId:n,callbacks:r,isDev:s}=K(),{data:a,error:i,isLoading:u}=Bs(),{refetch:f}=br(),h=Io();return ot({mutationFn:async()=>{var F,q,k,Q;if(!e)throw new Error("missing account");if(!t)throw new Error("missing walletInteractions");if(!n)throw new Error("missing chainId");if(i)throw i;if(u||!a)throw new Error("RePermit data is unavailable");const{order:T,domain:b,types:x,primaryType:v}=a;de.onSignOrderRequest(T);let O;try{O=await t.signOrder({domain:b,types:x,primaryType:v,message:T,account:e})}catch(z){throw(F=r==null?void 0:r.onSignOrderError)==null||F.call(r,z),de.onSignOrderError(z),z}de.onSignOrderSuccess(O),(q=r==null?void 0:r.onSignOrderSuccess)==null||q.call(r,O);const I=Ko(O),B={v:`0x${I.v.toString(16)}`,r:I.r,s:I.s};(k=r==null?void 0:r.onSignOrderRequest)==null||k.call(r);const _=await Vr(T,B,s);return(Q=r==null?void 0:r.onOrderCreated)==null||Q.call(r,_),h(_),f(),_}})},Ms=()=>{const{account:e,walletInteractions:t}=K(),{data:n}=Re();return ot({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("RePermit data is unavailable");const a=await t.getAllowance({tokenAddress:r,spenderAddress:n.domain.verifyingContract}),i=D(a||"0").lt(D(s).toString());return{allowance:a,approvalRequired:i}}})},Ho=()=>{const{account:e,walletInteractions:t,chainId:n,callbacks:r}=K(),{data:s}=Re(),{mutateAsync:a}=Ms();return ot({onError:i=>{de.onApproveError(i)},mutationFn:async({token:i,onHash:u,srcAmountWei:f})=>{var b,x;if(!e)throw new Error("missing account");if(!t)throw new Error("missing walletInteractions");if(!s)throw new Error("RePermit data is unavailable");de.onApproveRequest();const h=await t.approveToken({tokenAddress:i.address,amount:f,spenderAddress:s.domain.verifyingContract});if(!h)throw new Error("failed to approve token");(b=r==null?void 0:r.onApproveRequest)==null||b.call(r),u(h);let T=!1;for(let v=0;v<3;v++){const{approvalRequired:O}=await a({tokenAddress:i.address,srcAmountWei:f});if(!O){T=!0;break}v<2&&await new Promise(I=>setTimeout(I,3e3))}if(!T)throw new Error(`Insufficient ${i.symbol} allowance to perform the swap. Please approve the token first.`);return de.onApproveSuccess(h),(x=r==null?void 0:r.onApproveSuccess)==null||x.call(r,{txHash:h,explorerUrl:Nt(h,n),token:i,amount:ge(f,i.decimals)}),h}})},$o=()=>{const{account:e,chainId:t,srcToken:n,dstToken:r,module:s,slippage:a}=K(),i=Ct(),u=at().amount,f=He().amountPerTrade,h=Er(),T=He().totalTrades,b=qt().fillDelay,x=cr().amount,v=H(O=>O.state.isMarketOrder);return ot({mutationFn:async()=>{de.onRequestOrder({account:e,chainId:t,module:s,srcToken:n,dstToken:r,fromTokenAmount:u,srcChunkAmount:f,triggerPricePerTrade:i.pricePerChunk,deadline:h,fillDelay:b.unit*b.value,minDstAmountOutPerTrade:x,slippage:a,isMarketOrder:v||!1,chunksAmount:T})}})};function Wo(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 ks=()=>{const{srcToken:e,dstToken:t,chainId:n,callbacks:r,marketPrice:s}=K(),a=Ho().mutateAsync,i=qo().mutateAsync,u=Is().mutateAsync,{mutateAsync:f}=Ms(),{update:h}=Kt(),{amount:T}=at(),b=$o().mutate,{isLoading:x}=Re();return ot({mutationFn:async()=>{var I,B;const v=H.getState().state.swapExecutions[H.getState().state.swapExecutionIndex];if(x||(v==null?void 0:v.status)===Ae.LOADING||v!=null&&v.allowanceLoading)return;const O=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 _=ts(e,n);h({allowanceLoading:!0,wrapTxHash:void 0,approveTxHash:void 0,acceptedMarketPrice:s,acceptedSrcAmount:T,srcToken:e,dstToken:t,pendingSteps:[]});const{approvalRequired:F}=await f({tokenAddress:_.address,srcAmountWei:T});let q=0,k=1;O&&k++,F&&k++,h({totalSteps:k,stepIndex:q,allowanceLoading:!1,hasApproval:!F,status:Ae.LOADING}),b();let Q=[];O&&Q.push(rt.WRAP),F&&Q.push(rt.APPROVE),Q.push(rt.CREATE),h({pendingSteps:Q}),O&&(h({step:rt.WRAP}),await i({onHash:re=>h({wrapTxHash:re}),srcAmountWei:T}),q++,h({stepIndex:q})),F&&(h({step:rt.APPROVE}),await a({token:_,onHash:re=>h({approveTxHash:re}),srcAmountWei:T}),q++,h({stepIndex:q})),h({step:rt.CREATE});const z=await u();return h({status:Ae.SUCCESS,orderId:z.id}),z}catch(_){if(tr(_))(I=r==null?void 0:r.onSubmitOrderRejected)==null||I.call(r),h({step:void 0,status:void 0,stepIndex:void 0,allowanceLoading:!1,error:_});else{const F=Wo(_);(B=r==null?void 0:r.onSubmitOrderFailed)==null||B.call(r,F),h({status:Ae.FAILED,allowanceLoading:!1,parsedError:F,error:_})}throw _}}})},zo=()=>{const e=Kt(),{srcToken:t,dstToken:n}=K(),{isLoading:r}=Re(),s=ks(),a=H(T=>T.resetState),i=S.useCallback(()=>s.mutateAsync(),[s]),{update:u,resetSwap:f,...h}=e;return S.useMemo(()=>({status:h.status,parsedError:h.parsedError,error:h.error,step:h.step,stepIndex:h.stepIndex,approveTxHash:h.approveTxHash,wrapTxHash:h.wrapTxHash,totalSteps:h.totalSteps,pendingSteps:h.pendingSteps,srcToken:t,dstToken:n,onSubmit:i,resetState:a,resetCurrentSwap:f,isLoading:(e==null?void 0:e.status)===Ae.LOADING,isSuccess:(e==null?void 0:e.status)===Ae.SUCCESS,isFailed:(e==null?void 0:e.status)===Ae.FAILED,confirmButtonLoading:h.allowanceLoading||r}),[i,h,a,f,t,n,r])},Qo=()=>{const{marketPrice:e,srcToken:t,dstToken:n,marketPriceLoading:r,srcBalance:s,srcUsd1Token:a,noLiquidity:i,typedInputAmount:u}=K(),{error:f,isLoading:h,refetch:T}=Re(),b=r||D(a||"0").isZero()||s===void 0||D(e||"0").isZero(),x=h||!!(t&&n&&u&&b),O=!!(os()||f||i||x||D(u||"0").isZero()||!t||!n);return S.useMemo(()=>({disabled:O,error:f,loading:x,retry:T}),[O,x,f,T])},jo=()=>{const{srcUsd1Token:e,dstUsd1Token:t}=K(),n=at().amountUI,r=On().amountUI,s=qe(n,e),a=qe(r,t);return{srcAmountUsd:s,dstAmountUsd:a}},Vo=()=>{const{fees:e,dstToken:t,dstUsd1Token:n}=K(),{amountUI:r}=On(),s=S.useMemo(()=>!e||!r?"":D(r).multipliedBy(e).dividedBy(100).toFixed(),[r,e]),a=ar((t==null?void 0:t.decimals)||0,s);return{amountUI:s,amount:a,percent:e,usd:qe(s,n)}},Go=e=>{const t=S.useMemo(()=>!e.minDestAmountPerTrade||!e.totalTrades?"":D(e.minDestAmountPerTrade).multipliedBy(e.totalTrades).decimalPlaces(0).toFixed(),[e.minDestAmountPerTrade,e.totalTrades]),n=S.useMemo(()=>!e.minDestAmountPerTradeUI||!e.totalTrades?"":D(e.minDestAmountPerTradeUI).multipliedBy(e.totalTrades).toFixed(),[e.minDestAmountPerTradeUI,e.totalTrades]),r=S.useMemo(()=>!e.minDestAmountPerTradeUsd||!e.totalTrades?"":D(e.minDestAmountPerTradeUsd).multipliedBy(e.totalTrades).decimalPlaces(2).toFixed(),[e.minDestAmountPerTradeUsd,e.totalTrades]);return S.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])},Xo=()=>{const{srcToken:e,dstToken:t,account:n,marketPrice:r}=K(),{amount:s}=at(),{amount:a,amountUI:i,usd:u}=Pn(),{amountPerTrade:f,amountPerTradeUI:h,amountPerTradeUsd:T,totalTrades:b}=He(),x=Er(),{amount:v,amountUI:O,usd:I}=cr(),{amountUI:B,amount:_,usd:F}=Ct(),{milliseconds:q}=qt(),{amount:k,amountUI:Q}=On(),{srcAmountUsd:z,dstAmountUsd:re}=jo(),{amount:o,amountUI:c,percent:d,usd:g}=Vo(),{data:m}=Bs(),{data:y}=Re(),w=H(Z=>Z.state.isMarketOrder),p=H(Z=>Z.state.currentTime),A=Kt(),C=Oo(),E=A.acceptedSrcAmount||s,P=ge(r,(t==null?void 0:t.decimals)||0),L=S.useMemo(()=>C===X.TAKE_PROFIT_MARKET||C===X.TAKE_PROFIT_LIMIT||C===X.STOP_LOSS_LIMIT||C===X.STOP_LOSS_MARKET,[C]),R=Go({srcToken:e,dstToken:t,account:n,orderType:C,createdAt:p,deadline:x,totalTrades:b,tradeInterval:q,srcAmount:E,srcAmountUI:ge(E,(e==null?void 0:e.decimals)||0),srcAmountUsd:z,dstAmount:k,dstAmountUI:Q,dstAmountUsd:re,limitPrice:w?void 0:a,limitPriceUI:w?void 0:i,limitPriceUsd:w?void 0:u,srcAmountPerTrade:f,srcAmountPerTradeUI:h,srcAmountPerTradeUsd:T,minDestAmountPerTrade:v,minDestAmountPerTradeUI:O,minDestAmountPerTradeUsd:I,triggerPrice:_,triggerPriceUI:B,triggerPriceUsd:F});return S.useMemo(()=>({...R,feesAmountUI:c,feesAmount:o,feesUsd:g||"",feesPercentage:d,rePermitData:m,isTriggerPrice:L,isMarketOrder:w,marketPrice:r,marketPriceUi:P,spender:(y==null?void 0:y.domain.verifyingContract)||""}),[R,c,o,g,d,m,L,w,r,P,y])},Zo=()=>{const{supportedChains:e}=K();return S.useMemo(()=>e,[e])},Yo=60,_s=()=>{const{refetch:e}=br();return ot({mutationFn:async t=>{var n;for(let r=0;r<Yo;r++){const s=(n=await e())==null?void 0:n.data;if(!s)throw new Error("orders not found");const a=s.find(i=>i.id===t);if((a==null?void 0:a.status)===ue.Cancelled)return;await new Promise(i=>setTimeout(i,1e3))}throw new Error("Timed out waiting for order cancellation to be confirmed")}})},Jo=()=>{const e=H(n=>n.updateState);return{cancelOrders:H(n=>n.state.cancelOrders),setCancelOrder:(n,r)=>{const s=H.getState().state.cancelOrders;e({cancelOrders:{...s,[n]:r}})},clearCancelOrder:n=>{const r=H.getState().state.cancelOrders,{[n]:s,...a}=r;e({cancelOrders:a})}}},ec=e=>{const{account:t,walletInteractions:n,callbacks:r,chainId:s}=K(),{data:a,error:i,isLoading:u}=Re(),f=_s().mutateAsync,h=Mo(),{cancelOrders:T,setCancelOrder:b,clearCancelOrder:x}=Jo(),{mutateAsync:v}=ot({mutationFn:async()=>{var _,F,q;if(!t||!n)throw new Error("missing required parameters");if(!e)throw new Error("order is required");if(e.version!==1&&!a)throw new Error("RePermit data is unavailable");const B=e.id;try{(_=r==null?void 0:r.onCancelOrderRequest)==null||_.call(r,e),b(B,{status:Ae.LOADING}),de.onCancelOrderRequest([e.version===1?e.id.toString():e.hash],e.version);const k=await n.cancelOrder({order:e,contractAddress:e.version===1?e.twapAddress:a.domain.verifyingContract,args:e.version===1?[e.id]:[[e.repermitDigest]],abi:e.version===1?Js:Ys});if(!k)throw new Error("failed to cancel order");if(de.onCancelOrderSuccess(k),h(e.id,ue.Cancelled),e.version!==1)try{await f(e.id)}catch(Q){console.warn("cancel status sync lagging",Q)}return(F=r==null?void 0:r.onCancelOrderSuccess)==null||F.call(r,{order:e.version===1?{...e,status:ue.Cancelled}:e,txHash:k,explorerUrl:Nt(k,s)}),b(B,{status:Ae.SUCCESS,txHash:k}),k}catch(k){console.error("cancel order error",k),(q=r==null?void 0:r.onCancelOrderFailed)==null||q.call(r,k),tr(k)?x(B):(b(B,{status:Ae.FAILED,error:k.message}),de.onCancelOrderError(k))}}}),O=S.useMemo(()=>{const B=T[(e==null?void 0:e.id)||""],_=!!(e&&e.version!==1);return{isLoading:(B==null?void 0:B.status)===Ae.LOADING,disabled:_&&(u||!!i||!a),isSuccess:(B==null?void 0:B.status)===Ae.SUCCESS,isError:(B==null?void 0:B.status)===Ae.FAILED,error:B==null?void 0:B.error,txHash:B==null?void 0:B.txHash}},[T,e,a,i,u]),I=S.useCallback(async()=>v(),[v]);return S.useMemo(()=>({cancelOrder:I,...O}),[I,O])},Us=S.createContext(null),tc=({children:e})=>{const t=Ii(),n=Ui(),r=ki(),s=Hi(),a=$i(),i=Dn(),u=Wi(),f=zi(),h=os(),T=Qo(),b=Xo(),x=No(),v=zo(),O=Zo(),I=_s(),{module:B}=K(),_=S.useMemo(()=>({tradesAmountPanel:t,durationPanel:n,fillDelayPanel:r,limitPricePanel:s,triggerPricePanel:a,pricePanel:i,dstTokenPanel:u,disclaimerPanel:f,inputError:h,submitOrderButton:T,derivedFormData:b,orderHistoryPanel:x,orderExecutionPanel:v,supportedChains:O,refetchUntilStatusSynced:I,module:B}),[t,n,r,s,a,i,u,f,h,T,b,x,v,O,I,B]);return $.jsx(Us.Provider,{value:_,children:e})},nc=()=>{const e=S.useContext(Us);if(e===null)throw new Error("useSpot must be used within SpotProvider");return e},rc=S.createContext(null),xr={didCatch:!1,error:null};class sc extends S.Component{constructor(t){super(t),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=xr}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),i=0;i<s;i++)a[i]=arguments[i];(n=(r=this.props).onReset)===null||n===void 0||n.call(r,{args:a,reason:"imperative-api"}),this.setState(xr)}}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&&ac(t.resetKeys,s)){var a,i;(a=(i=this.props).onReset)===null||a===void 0||a.call(i,{next:s,prev:t.resetKeys,reason:"keys"}),this.setState(xr)}}render(){const{children:t,fallbackRender:n,FallbackComponent:r,fallback:s}=this.props,{didCatch:a,error:i}=this.state;let u=t;if(a){const f={error:i,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")u=n(f);else if(r)u=S.createElement(r,f);else if(s!==void 0)u=s;else throw i}return S.createElement(rc.Provider,{value:{didCatch:a,error:i,resetErrorBoundary:this.resetErrorBoundary}},u)}}function ac(){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 ic=()=>$.jsx("div",{className:"twap-error-fallback",children:$.jsx("p",{style:{fontSize:20,fontWeight:600,textAlign:"center",width:"100%",marginTop:40},children:"Something went wrong"})});function oc({children:e}){return $.jsx(sc,{FallbackComponent:ic,onError:t=>de.onCrash(t),children:$.jsx($.Fragment,{children:e})})}const Ls=S.createContext(null),cc=new yo({defaultOptions:{queries:{refetchOnWindowFocus:!1}}}),uc=e=>{var x,v,O;const t=H(I=>I.updateState),n=H(I=>I.state.isMarketOrder);S.useEffect(()=>{const I=setInterval(()=>{t({currentTime:Date.now()})},6e4);return()=>clearInterval(I)},[t]);const r=(x=e.overrides)==null?void 0:x.state,{isMarketOrder:s,chunks:a,fillDelay:i,duration:u,limitPrice:f,triggerPrice:h,triggerPricePercent:T,limitPricePercent:b}=r??{};return S.useEffect(()=>{s!==void 0&&t({isMarketOrder:s}),t({typedChunks:a,typedFillDelay:i,typedDuration:u,typedLimitPrice:f,typedTriggerPrice:h,triggerPricePercent:T,limitPricePercent:b})},[t,s,a,i,u,f,h,T,b]),S.useEffect(()=>{var I,B,_,F;t({typedLimitPrice:(B=(I=e.overrides)==null?void 0:I.state)==null?void 0:B.limitPrice,typedTriggerPrice:(F=(_=e.overrides)==null?void 0:_.state)==null?void 0:F.triggerPrice,triggerPricePercent:void 0,limitPricePercent:void 0})},[(v=e.srcToken)==null?void 0:v.address,(O=e.dstToken)==null?void 0:O.address]),S.useEffect(()=>{e.module===G.LIMIT&&t({isMarketOrder:!1})},[e.module]),S.useEffect(()=>{n&&t({isInvertedTrade:!1})},[n]),S.useEffect(()=>{t({typedChunks:void 0})},[e.typedInputAmount]),null},dc=({marketReferencePrice:e,srcToken:t,dstToken:n,chainId:r,typedInputAmount:s})=>S.useMemo(()=>{if(rr(t,n,r)||sr(t,n,r))return{isLoading:!1,noLiquidity:!1,value:st(s||"0",t==null?void 0:t.decimals)};if(D(e.value||0).isZero()||D(s||0).isZero())return e;const a=D(e.value||0).dividedBy(s||0).toFixed();return{...e,value:a}},[e,s,t,n,r]),lc=e=>{const t=Kt(),n=S.useMemo(()=>Gn(e.partner),[e.partner]),r=S.useMemo(()=>{const u=n[0];return e.chainId&&n.includes(e.chainId)?e.chainId:u},[e.chainId,n]),s=dc(e),a=S.useMemo(()=>Wr(e.minChunkSizeUsd),[e.minChunkSizeUsd]);S.useEffect(()=>{de.init(e.partner,a,r,e.appId)},[e.partner,r,a,e.appId]);const i=S.useMemo(()=>({typedInputAmount:e.typedInputAmount,minChunkSizeUsd:a,account:e.account,walletInteractions:e.walletInteractions,marketPrice:t.acceptedMarketPrice||s.value,marketPriceLoading:!t.acceptedMarketPrice&&s.isLoading,noLiquidity:!t.acceptedMarketPrice&&s.noLiquidity,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,supportLegacyOrders:e.supportLegacyOrders??!1}),[e.typedInputAmount,a,e.account,e.walletInteractions,t.acceptedMarketPrice,t.srcToken,t.dstToken,s.value,s.isLoading,s.noLiquidity,e.priceProtection,n,r,e.partner,e.module,e.fees,e.overrides,e.callbacks,e.srcUsd1Token,e.dstUsd1Token,e.srcBalance,e.dstBalance,e.srcToken,e.dstToken,e.isDev,e.supportLegacyOrders]);return $.jsxs(Ls.Provider,{value:i,children:[$.jsx(uc,{...e}),$.jsx(tc,{children:$.jsx(oc,{children:e.children})})]})},fc=e=>$.jsx(Ao,{client:cc,children:$.jsx(lc,{...e})}),K=()=>{const e=S.useContext(Ls);if(e===null)throw new Error("useSpotContext must be used within SpotProvider");return e},hc=(e,t,n)=>{const r=Sn();return S.useMemo(()=>e==null?void 0:e.map(s=>({rawFill:s,srcToken:t,dstToken:n,srcAmount:ge(s.inAmount,t==null?void 0:t.decimals),dstAmount:ge(s.outAmount,n==null?void 0:n.decimals),timestamp:s.timestamp,txHash:s.txHash,explorerUrl:Nt(s.txHash,r==null?void 0:r.id),executionRate:Xn(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])},pc=(e,t,n)=>{const{chainId:r,partner:s}=K(),a=Uo(t,n,e),i=Lo(t,n,e),u=Ro(t,n,e),f=S.useMemo(()=>e?e.version===2?e.fillDelay:Kr(e,Zn(s,r)):0,[e,s,r]),h=hc(e==null?void 0:e.fills,t,n)??[];return S.useMemo(()=>{if(e!=null&&e.id)return{original:e,fills:h,srcToken:t,dstToken:n,orderType:e.type,createdAt:e.createdAt,deadline:e.deadline||0,totalTrades:e.totalTradesAmount||0,tradeInterval:f,recipient:e.maker||"",srcAmount:e.srcAmount||"",srcAmountUI:ge(e.srcAmount,t==null?void 0:t.decimals),limitPrice:st(a,n==null?void 0:n.decimals),limitPriceUI:a||"",sizePerTrade:e.srcAmountPerTrade||"",sizePerTradeUI:ge(e.srcAmountPerTrade,t==null?void 0:t.decimals),minDestAmountPerTrade:e.dstMinAmountPerTrade||"",minDestAmountPerTradeUI:ge(e.dstMinAmountPerTrade,n==null?void 0:n.decimals),dstMinAmount:e.dstMinAmountTotal,dstMinAmountUI:ge(e.dstMinAmountTotal,n==null?void 0:n.decimals),triggerPrice:st(i,n==null?void 0:n.decimals),triggerPriceUI:i||"",id:e.id,amountInFilled:e.srcAmountFilled,amountInFilledUI:ge(e.srcAmountFilled,t==null?void 0:t.decimals),amountOutFilled:e.dstAmountFilled,amountOutFilledUI:ge(e.dstAmountFilled,n==null?void 0:n.decimals),progress:e.progress,executionPrice:st(u,n==null?void 0:n.decimals),executionPriceUI:u,version:e.version}},[e,h,t,n,f,a,i,u])};Va(bi.version),M.DISCLAIMER_URL=ha,M.Disclaimer=sn,M.InputErrors=me,M.Module=G,M.ORBS_LOGO=la,M.ORBS_SLTP_FAQ_URL=da,M.ORBS_TWAP_FAQ_URL=ua,M.ORBS_WEBSITE_URL=fa,M.OrderFilter=Mr,M.OrderStatus=ue,M.OrderType=X,M.Partners=Pe,M.SPOT_VERSION=yn,M.SpotProvider=fc,M.Steps=rt,M.SwapStatus=Ae,M.TimeUnit=ve,M.buildRePermitOrderData=Qr,M.ensureWrappedToken=ts,M.eqIgnoreCase=gt,M.fetchRePermitData=zr,M.getExplorerUrl=Nt,M.getMinChunkSizeUsd=Wr,M.getNetwork=Et,M.getOrderExecutionRate=Xn,M.getOrderFillDelayMillis=Kr,M.getOrderLimitPriceRate=qr,M.getOrderType=Fi,M.getPartnerChains=Gn,M.getPartners=$r,M.getTriggerPriceRate=Hr,M.isNativeAddress=Rt,M.isTxRejected=tr,M.millisToDays=nr,M.millisToMinutes=Fn,M.networks=ye,M.parseError=wi,M.shouldUnwrapOnly=sr,M.shouldWrapOnly=rr,M.submitOrder=Vr,M.toAmountUi=ge,M.toAmountWei=st,M.useAmountUi=xt,M.useCancelOrder=ec,M.useDerivedHistoryOrder=pc,M.useExplorerLink=Si,M.useNetwork=Sn,M.useRePermitData=Re,M.useSignOrder=Is,M.useSpot=nc,M.useSubmitOrder=ks,M.useSwapExecution=Kt,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"})}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orbs-network/spot-react",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"description": "Spot React Components - React components for Spot SDK",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/spot-react.umd.cjs",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"zustand": "^5.0.9"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@orbs-network/spot-ui": "
|
|
36
|
+
"@orbs-network/spot-ui": "2.0.1"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"@types/react": "^19.0.2",
|