@orbs-network/spot-react 2.1.8 → 2.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- (function(m,s){typeof exports=="object"&&typeof module<"u"?s(exports,require("@orbs-network/spot-ui"),require("react/jsx-runtime"),require("react"),require("zustand"),require("zustand/vanilla")):typeof define=="function"&&define.amd?define(["exports","@orbs-network/spot-ui","react/jsx-runtime","react","zustand","zustand/vanilla"],s):(m=typeof globalThis<"u"?globalThis:m||self,s(m.SpotReact={},m.SpotUI,m.jsxRuntime,m.React,m.Zustand,m.ZustandVanilla))})(this,(function(m,s,L,d,Se,he){"use strict";"use client";var Rt=Object.defineProperty;var Tt=(m,s,L)=>s in m?Rt(m,s,{enumerable:!0,configurable:!0,writable:!0,value:L}):m[s]=L;var oe=(m,s,L)=>Tt(m,typeof s!="symbol"?s+"":s,L);const Ee={version:"2.1.8"},se=d.createContext(null),Ie=({children:e,value:r})=>L.jsx(se.Provider,{value:r,children:e}),D=()=>{const e=d.useContext(se);if(e===null)throw new Error("useSpotRuntime must be used within SpotProvider");return e};var B=(e=>(e[e.LOADING=1]="LOADING",e[e.SUCCESS=2]="SUCCESS",e[e.FAILED=3]="FAILED",e))(B||{}),l=(e=>(e.IDLE="idle",e.PREPARING="preparing",e.WRAPPING="wrapping",e.APPROVING="approving",e.SIGNING="signing",e.SUBMITTING="submitting",e.SUCCESS="success",e.FAILED="failed",e.REJECTED="rejected",e))(l||{}),Q=(e=>(e.TRIGGER_MARKET_PRICE="triggerMarketPriceDisclaimer",e.MARKET_PRICE="marketOrderDisclaimer",e.LIMIT_PRICE="limitOrderDisclaimer",e))(Q||{}),H=(e=>(e.WRAP="wrap",e.APPROVE="approve",e.CREATE="create",e))(H||{});const Ae=new Set([l.PREPARING,l.WRAPPING,l.APPROVING,l.SIGNING,l.SUBMITTING]),Ce={[l.IDLE]:new Set,[l.PREPARING]:new Set([l.PREPARING,l.WRAPPING,l.APPROVING,l.SIGNING,l.FAILED,l.REJECTED]),[l.WRAPPING]:new Set([l.WRAPPING,l.APPROVING,l.SIGNING,l.FAILED,l.REJECTED]),[l.APPROVING]:new Set([l.APPROVING,l.SIGNING,l.FAILED,l.REJECTED]),[l.SIGNING]:new Set([l.SIGNING,l.SUBMITTING,l.FAILED,l.REJECTED]),[l.SUBMITTING]:new Set([l.SUCCESS,l.FAILED,l.REJECTED]),[l.SUCCESS]:new Set,[l.FAILED]:new Set,[l.REJECTED]:new Set},Y=e=>({phase:l.IDLE,completedWrap:e}),J=e=>Ae.has(e),ye=e=>e===l.IDLE||e===l.FAILED||e===l.REJECTED,ve=(e,r)=>Ce[e].has(r),we=e=>{if(J(e))return B.LOADING;if(e===l.SUCCESS)return B.SUCCESS;if(e===l.FAILED||e===l.REJECTED)return B.FAILED},Re=e=>{if(e===l.WRAPPING)return H.WRAP;if(e===l.APPROVING)return H.APPROVE;if(e===l.SIGNING||e===l.SUBMITTING)return H.CREATE},X=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(typeof e=="object"&&e!==null){const r=Reflect.get(e,"message");if(typeof r=="string")return r}return"Unknown error"},Te=e=>{if(typeof e!="object"||e===null)return 0;const r=Reflect.get(e,"code");return typeof r=="number"&&Number.isFinite(r)?r:typeof r=="string"&&/^-?\d+$/.test(r)?Number(r):0},$=e=>e instanceof Error?e:new Error(X(e)),ee=e=>{const r=X(e),n=r.match(/,\s*code\s*:\s*(-?\d+)/i);return{message:r.replace(/^error\s*:/i,"").replace(/,\s*code\s*:\s*-?\d+/i,"").trim()||"Unknown error",code:Te(e)||(n?Number(n[1]):0)}},I=e=>{if(e)try{const r=e();Promise.resolve(r).catch(()=>{})}catch{}},Le=({execution:e,account:r,chainId:n,inputTokenAddress:t,inputAmountRaw:o})=>{const i=e.completedWrap;if((i==null?void 0:i.account.toLowerCase())===r.toLowerCase()&&i.chainId===n&&i.inputTokenAddress.toLowerCase()===t.toLowerCase()&&Ne(i.inputAmountRaw,o))return i},Ne=(e,r)=>{try{return BigInt(e)>=BigInt(r)}catch{return!1}},pe=2e4,ae=new WeakMap,ce=e=>{const r=ae.get(e);if(r)return r;const n={all:[...e].sort((t,o)=>o.createdAt-t.createdAt),open:[],completed:[],cancelled:[],expired:[]};for(const t of n.all)switch(t.status){case s.OrderStatus.Open:n.open.push(t);break;case s.OrderStatus.Completed:n.completed.push(t);break;case s.OrderStatus.Cancelled:n.cancelled.push(t);break;case s.OrderStatus.Expired:n.expired.push(t);break}return ae.set(e,n),n},Fe=(e,r)=>{const n=new Set(e.map(o=>o.historyKey)),t=(r==null?void 0:r.filter(o=>o.version===1&&!n.has(o.historyKey)))??[];return[...e,...t]},Me=(e,r,n)=>{if(!e)return;const t=new Map(r.map(i=>[i.historyKey,i])),o=[];for(const i of e){if(i.version!==2)continue;const a=t.get(i.historyKey);!a||a.progress===i.progress||(o.push(a),a.status===s.OrderStatus.Completed&&I(()=>{var c;return(c=n==null?void 0:n.onOrderFilled)==null?void 0:c.call(n,a)}))}o.length>0&&I(()=>{var i;return(i=n==null?void 0:n.onOrdersProgressUpdate)==null?void 0:i.call(n,o)})},ue=e=>{if(e===null||typeof e!="object")return!1;const r=Object.getPrototypeOf(e);return r===Object.prototype||r===null},te=(e,r)=>{if(Object.is(e,r))return e;if(Array.isArray(e)&&Array.isArray(r)){const n=r.map((o,i)=>te(e[i],o));return e.length===n.length&&n.every((o,i)=>o===e[i])?e:n}if(ue(e)&&ue(r)){const n=Object.keys(e),t=Object.keys(r),o={};let i=n.length===t.length;for(const a of t){Object.prototype.hasOwnProperty.call(e,a)||(i=!1);const c=te(e[a],r[a]);o[a]=c,c!==e[a]&&(i=!1)}return i?e:o}return r},De=(e,r)=>e?te(e,r):r,re=e=>({tradeCount:e.tradeCount,tradeInterval:e.tradeInterval,orderDuration:e.orderDuration,limitPriceUi:e.limitPriceUi,triggerPriceUi:e.triggerPriceUi,triggerPricePercent:e.triggerPricePercent,limitPricePercent:e.limitPricePercent,isMarketOrder:e.isMarketOrder,isPriceInverted:void 0}),be=e=>({...re(e),cancelOrders:{},currentExecution:Y()}),de={isFetching:!1},le={isFetching:!1},Ge=e=>new Promise(r=>setTimeout(r,e)),xe=e=>{let r=0,n,t,o=0,i,a,c,u=!1,S=0,y=0,A,g,f;return he.createStore((P,h)=>{const F=async()=>{if(!n||!t)return;if(i)return i;const O=++o,E=t;P(C=>({client:{key:n,data:C.client.data,error:void 0,isFetching:!0}}));const v=(async()=>{let C;for(let w=0;w<3;w++){if(O!==o)return;try{const N=await E();return O!==o?void 0:(P({client:{key:n,data:N,isFetching:!1}}),N)}catch(N){if(C=N instanceof Error?N:new Error(String(N)),O!==o)return;w<2&&await Ge(2**w*1e3)}}O===o&&P({client:{key:n,error:C,isFetching:!1}})})();return i=v,v.finally(()=>{i===v&&(i=void 0)}),v},R=async(O=!1)=>{if(!O&&S===0||!a||!c)return h().orders.data;if(A)return A;const E=++y,v=c,C=h().orders.data,w=new AbortController;g=w,P(p=>({orders:{key:a,data:p.orders.data,error:void 0,isFetching:!0}}));const N=v(C,u,w.signal).then(({orders:p,legacyLoaded:b})=>{if(E!==y)return;u=b;const G=De(h().orders.data,p);return P({orders:{key:a,data:G,isFetching:!1}}),G}).catch(p=>{if(E!==y||w.signal.aborted)return;const b=p instanceof Error?p:new Error(String(p));P(G=>({orders:{key:a,data:G.orders.data,error:b,isFetching:!1}}))});return A=N,N.finally(()=>{A===N&&(A=void 0),g===w&&(g=void 0)}),N},W=()=>{R()},x=()=>{f&&(clearInterval(f),f=void 0),typeof window<"u"&&window.removeEventListener("focus",W),g==null||g.abort(),g=void 0,A=void 0,y++,P(O=>({orders:{...O.orders,isFetching:!1}}))},j=()=>{!a||!c||f||(R(!0),f=setInterval(()=>{R()},pe),typeof window<"u"&&window.addEventListener("focus",W))};return{client:de,orders:le,state:be(e),configureClient:(O,E)=>{if(n===O){t=E;return}n=O,t=E,o++,i=void 0,P({client:O?{key:O,isFetching:!1}:de}),O&&E&&F()},refetchClient:F,configureOrders:(O,E)=>{if(a===O){c=E;return}x(),a=O,c=E,u=!1,P({orders:O?{key:O,isFetching:!1}:le}),S>0&&j()},registerOrdersConsumer:()=>(S++,S===1&&j(),()=>{S=Math.max(0,S-1),S===0&&x()}),refetchOrders:R,addOrder:O=>{P(E=>{const v=E.orders.data;return v!=null&&v.some(C=>C.historyKey===O.historyKey)?E:{orders:{...E.orders,data:[O,...v??[]]}}})},updateOrderStatus:(O,E)=>{P(v=>{var C;return{orders:{...v.orders,data:(C=v.orders.data)==null?void 0:C.map(w=>w.historyKey===O?{...w,status:E}:w)}}})},updateState:O=>P(E=>({state:{...E.state,...O}})),beginExecution:O=>{let E;return P(v=>ye(v.state.currentExecution.phase)?(E={...O,executionId:++r,phase:l.PREPARING},{state:{...v.state,currentExecution:E}}):v),E},replaceExecution:(O,E)=>{let v=!1;return P(C=>{const w=C.state.currentExecution;return w.executionId!==O||E.executionId!==O||!ve(w.phase,E.phase)?C:(v=!0,{state:{...C.state,currentExecution:E}})}),v},returnToOrderForm:()=>{const O=h().state.currentExecution;return J(O.phase)||O.phase===l.SUCCESS?!1:(P(E=>({state:{...E.state,currentExecution:Y(O.completedWrap)}})),!0)},syncFormDefaults:O=>J(h().state.currentExecution.phase)?!1:(P(E=>({state:{...E.state,...re(O),currentExecution:Y()}})),!0),startNewOrder:O=>{const{state:E}=h();return J(E.currentExecution.phase)?!1:(P(v=>({state:{...v.state,...re(O),isMarketOrder:E.isMarketOrder,currentExecution:Y()}})),!0)}}})},me=e=>{var n;const r=(n=e.overrides)==null?void 0:n.state;return{isMarketOrder:e.module===s.Module.LIMIT?!1:r==null?void 0:r.isMarketOrder,tradeCount:r==null?void 0:r.tradeCount,tradeInterval:r==null?void 0:r.tradeInterval,orderDuration:r==null?void 0:r.orderDuration,limitPriceUi:r==null?void 0:r.limitPriceUi,triggerPriceUi:r==null?void 0:r.triggerPriceUi,triggerPricePercent:r==null?void 0:r.triggerPricePercent,limitPricePercent:r==null?void 0:r.limitPricePercent}},ge=d.createContext(null),_e=({children:e,initialState:r})=>{const[n]=d.useState(()=>xe(r));return L.jsx(ge.Provider,{value:n,children:e})},V=()=>{const e=d.useContext(ge);if(e===null)throw new Error("useSpotStore must be used within SpotProvider");return e},T=e=>{const r=V();return Se.useStore(r,e)},je={isFetching:!1},U=()=>{const{partner:e,chainId:r,isSupportedChain:n}=D(),t=V(),o=T(y=>y.client),i=!!(r&&n),a=i?`${e}:${r}`:void 0,c=o.key===a?o:je,u=d.useCallback(()=>r?s.createClient(e,r):Promise.reject(new Error("Spot is unavailable on the connected chain")),[r,e]);d.useEffect(()=>{t.getState().configureClient(a,i?u:void 0)},[i,a,u,t]);const S=d.useCallback(()=>{if(!i||!a)return Promise.resolve(void 0);const y=t.getState();return y.configureClient(a,u),y.refetchClient()},[i,a,u,t]);return d.useMemo(()=>({data:c.data,error:c.error,isLoading:i&&!c.data&&c.error===void 0,isFetching:c.isFetching,refetch:S}),[c,i,S])},Be=({error:e,retry:r,isRetrying:n})=>L.jsxs("div",{className:"spot-client-error-fallback",role:"alert",children:[L.jsx("p",{children:e.message||"Unable to load Spot configuration."}),L.jsx("button",{type:"button",className:"spot-client-error-retry",disabled:n,onClick:r,children:n?"Retrying…":"Retry"})]}),qe=({children:e,fallback:r=Be})=>{const{partner:n,chainId:t,isSupportedChain:o,minTradeSizeUsd:i}=D(),{data:a,error:c,isFetching:u,refetch:S}=U(),y=d.useCallback(async()=>{await S()},[S]);return d.useEffect(()=>{!a||!t||!o||s.analytics.onFetchedConfig(a.rePermitData,n,s.getTwapConfig(n,t),i)},[t,a,o,i,n]),L.jsxs(L.Fragment,{children:[e,!a&&c&&o?L.jsx(r,{error:c,retry:y,isRetrying:u}):null]})},We=({resetErrorBoundary:e})=>L.jsxs("div",{className:"twap-error-fallback",role:"alert",children:[L.jsx("p",{children:"Something went wrong"}),L.jsx("button",{type:"button",onClick:e,children:"Retry"})]}),Ve=({children:e,fallback:r=We})=>L.jsx(Ke,{fallback:r,children:e});class Ke extends d.Component{constructor(){super(...arguments);oe(this,"state",{});oe(this,"resetErrorBoundary",()=>{this.setState({error:void 0})})}static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n){s.analytics.onCrash(n)}render(){const{error:n}=this.state;if(n){const t=this.props.fallback;return L.jsx(t,{error:n,resetErrorBoundary:this.resetErrorBoundary})}return this.props.children}}const He=({children:e,defaults:r,scopeKey:n})=>{const t=V(),o=T(a=>a.state.currentExecution.phase),i=d.useRef(n);return d.useEffect(()=>{i.current===n||J(o)||t.getState().syncFormDefaults(r)&&(i.current=n)},[r,o,n,t]),e},Pe=d.createContext(null),ze=({children:e})=>{const{inputToken:r,outputToken:n,inputAmountUi:t,quotedOutputAmountRaw:o,inputTokenUsdPrice:i,outputTokenUsdPrice:a,minTradeSizeUsd:c,inputBalanceRaw:u,displayFeePercent:S,priceProtectionPercent:y,module:A}=D(),g=T(C=>C.state.tradeCount),f=T(C=>C.state.tradeInterval),P=T(C=>C.state.orderDuration),h=T(C=>C.state.limitPriceUi),F=T(C=>C.state.triggerPriceUi),R=T(C=>C.state.limitPricePercent),W=T(C=>C.state.triggerPricePercent),x=T(C=>C.state.isPriceInverted),j=T(C=>C.state.isMarketOrder),O=T(C=>{const w=C.state.currentExecution;return w.phase!==l.IDLE?w.form:void 0}),E=d.useMemo(()=>({module:A,inputTokenDecimals:(r==null?void 0:r.decimals)??0,outputTokenDecimals:(n==null?void 0:n.decimals)??0,quotedOutputAmountRaw:o,inputTokenUsdPrice:i,outputTokenUsdPrice:a,minTradeSizeUsd:c,priceProtectionPercent:y,displayFeePercent:S,inputBalanceRaw:u,userInput:{inputAmountUi:t,isMarketOrder:!!j,tradeCount:g,tradeInterval:f,orderDuration:P,limitPriceUi:h,limitPricePercent:R,triggerPriceUi:F,triggerPricePercent:W,isPriceInverted:x}}),[n==null?void 0:n.decimals,a,S,o,c,A,y,u,r==null?void 0:r.decimals,i,x,j,R,W,g,P,f,h,t,F]),v=d.useMemo(()=>{const C=s.calculateOrderForm(E);return r&&n?C:{...C,isReady:!1,canSubmit:!1}},[r,n,E]);return L.jsx(Pe.Provider,{value:O??v,children:e})},_=()=>{const e=d.useContext(Pe);if(!e)throw new Error("useOrderForm must be used within OrderFormProvider");return e},Je=(e,r)=>{d.useEffect(()=>{!e.chainId||!r||s.analytics.init(e.partner,e.minTradeSizeUsd,e.chainId,e.appId)},[e.appId,e.chainId,e.minTradeSizeUsd,e.partner,r])},Ue=e=>{var A,g,f,P,h,F,R,W,x,j,O,E;const r=d.useMemo(()=>s.getPartnerChains(e.partner),[e.partner]),n=!!(e.chainId&&r.includes(e.chainId)),t=(A=e.wrappedNativeToken)==null?void 0:A.address,o=!!(t&&(s.isNativeAddress((g=e.inputToken)==null?void 0:g.address)&&s.eqIgnoreCase(((f=e.outputToken)==null?void 0:f.address)||"",t)||s.eqIgnoreCase(((P=e.inputToken)==null?void 0:P.address)||"",t)&&s.isNativeAddress((h=e.outputToken)==null?void 0:h.address))),i=o?s.toAmountRaw(e.inputAmountUi,(F=e.outputToken)==null?void 0:F.decimals):e.marketQuote.isLoading?void 0:e.marketQuote.quotedOutputAmountRaw,a=o?!1:e.marketQuote.isLoading,c=o?!1:e.marketQuote.noLiquidity,u=d.useMemo(()=>me({module:e.module,overrides:e.overrides}),[e.module,e.overrides]),S=JSON.stringify([e.partner,e.chainId,e.module,(R=e.inputToken)==null?void 0:R.address,(W=e.inputToken)==null?void 0:W.decimals,(x=e.outputToken)==null?void 0:x.address,(j=e.outputToken)==null?void 0:j.decimals,(O=e.wrappedNativeToken)==null?void 0:O.address,(E=e.wrappedNativeToken)==null?void 0:E.decimals,u]),y=d.useMemo(()=>({inputAmountUi:e.inputAmountUi,minTradeSizeUsd:e.minTradeSizeUsd,account:e.account,walletInteractions:e.walletInteractions,quotedOutputAmountRaw:i,marketPriceLoading:a,noLiquidity:c,priceProtectionPercent:e.priceProtectionPercent,chainId:e.chainId,isSupportedChain:n,partner:e.partner,module:e.module,displayFeePercent:e.displayFeePercent??0,callbacks:e.callbacks,inputTokenUsdPrice:e.inputTokenUsdPrice,outputTokenUsdPrice:e.outputTokenUsdPrice,inputBalanceRaw:e.inputBalanceRaw,inputToken:e.inputToken,outputToken:e.outputToken,wrappedNativeToken:e.wrappedNativeToken,supportLegacyOrders:e.supportLegacyOrders??!1,overrides:e.overrides}),[e.account,e.callbacks,e.chainId,e.displayFeePercent,e.inputBalanceRaw,e.inputToken,e.inputTokenUsdPrice,e.minTradeSizeUsd,e.module,e.outputToken,e.outputTokenUsdPrice,e.wrappedNativeToken,e.overrides,e.partner,e.priceProtectionPercent,e.supportLegacyOrders,e.inputAmountUi,e.walletInteractions,n,a,c,i]);return{initialState:u,formScopeKey:S,runtime:y}},Qe=e=>{const{initialState:r,formScopeKey:n,runtime:t}=Ue(e);return Je(e,t.isSupportedChain),L.jsx(Ie,{value:t,children:L.jsx(_e,{initialState:r,children:L.jsx(Ve,{fallback:e.errorFallback,children:L.jsx(He,{defaults:r,scopeKey:n,children:L.jsx(qe,{fallback:e.clientErrorFallback,children:L.jsx(ze,{children:e.children})})})})})})},Ye=(e,r)=>d.useMemo(()=>s.toAmountUI(r,e),[e,r]),$e={isFetching:!1},ne=()=>{const{account:e,partner:r,chainId:n,supportLegacyOrders:t,callbacks:o}=D(),{data:i}=U(),a=V(),c=!!(e&&i),u=c?JSON.stringify([e,i==null?void 0:i.exchangeAddress,r,n,t]):void 0,S=d.useCallback(async(A,g,f)=>{if(!e||!i)return{orders:[],legacyLoaded:!1};const P=t&&!g,h=await i.getAccountOrders({signal:f,account:e,legacyOrders:P});return Me(A,h,o),{orders:t&&!P?Fe(h,A):h,legacyLoaded:g||P}},[e,o,i,t]);d.useEffect(()=>{a.getState().configureOrders(u,c?S:void 0)},[c,u,S,a]);const y=d.useCallback(()=>{if(!c||!u)return Promise.resolve(void 0);const A=a.getState();return A.configureOrders(u,S),A.refetchOrders(!0)},[c,u,S,a]);return{enabled:c,key:u,refetch:y}},ke=()=>{ne();const e=V();return d.useCallback(r=>e.getState().addOrder(r),[e])},Ze=()=>{const e=V();return d.useCallback((r,n)=>e.getState().updateOrderStatus(r,n),[e])},Xe=()=>{const e=V();return d.useCallback(()=>e.getState().refetchOrders(),[e])},et=()=>{const e=T(u=>u.orders),r=T(u=>u.registerOrdersConsumer),{enabled:n,key:t,refetch:o}=ne(),i=e.key===t?e:$e;d.useEffect(()=>r(),[r]);const a=d.useMemo(()=>i.data===void 0?void 0:ce(i.data),[i.data]),c=d.useCallback(async()=>{const u=await o();return u===void 0?void 0:ce(u)},[o]);return d.useMemo(()=>({data:a,error:i.error,isLoading:n&&a===void 0&&i.error===void 0,isFetching:i.isFetching,isRefetching:i.isFetching&&a!==void 0,refetch:c}),[i,a,n,c])},tt=60,rt=()=>{const{refetch:e}=ne();return d.useCallback(async r=>{for(let n=0;n<tt;n++){const t=await e();if(!t)throw new Error("orders not found");const o=t.find(i=>i.historyKey===r);if((o==null?void 0:o.status)===s.OrderStatus.Cancelled)return;await new Promise(i=>setTimeout(i,1e3))}throw new Error("Timed out waiting for order cancellation to be confirmed")},[e])},nt=()=>{const e=V(),r=T(t=>t.updateState);return{cancelOrders:T(t=>t.state.cancelOrders),setCancelOrder:(t,o)=>{const i=e.getState().state.cancelOrders;r({cancelOrders:{...i,[t]:o}})},clearCancelOrder:t=>{const o=e.getState().state.cancelOrders,{[t]:i,...a}=o;r({cancelOrders:a})}}},it=e=>({...e,status:s.OrderStatus.Cancelled}),ot=e=>{const{account:r,walletInteractions:n,callbacks:t}=D(),{data:o}=U(),i=rt(),a=Ze(),{cancelOrders:c,setCancelOrder:u,clearCancelOrder:S}=nt(),y=d.useCallback(async()=>{const g=e==null?void 0:e.historyKey;try{if(!r)throw new Error("missing account");if(!e)throw new Error("order is required");if(!o)throw new Error("Spot client is unavailable");const f=e.historyKey;u(f,{status:B.LOADING}),I(()=>{var R;return(R=t==null?void 0:t.onCancelOrderRequest)==null?void 0:R.call(t,e)}),I(()=>s.analytics.onCancelOrderRequest([e.version===1?e.id.toString():e.hash],e.version));const P=o.getCancelOrderRequest(e),h=await n.cancelOrder(P);if(!h)throw new Error("failed to cancel order");I(()=>s.analytics.onCancelOrderSuccess(h));const F=it(e);return a(f,s.OrderStatus.Cancelled),u(f,{status:B.SUCCESS,txHash:h}),I(()=>{var R;return(R=t==null?void 0:t.onCancelOrderSuccess)==null?void 0:R.call(t,{order:F,txHash:h})}),e.version!==1&&i(f).catch(R=>{console.warn("cancel status sync lagging",R)}),h}catch(f){s.isTxRejected(f)?g&&S(g):(g&&u(g,{status:B.FAILED,error:X(f)}),I(()=>s.analytics.onCancelOrderError(f))),I(()=>{var P;return(P=t==null?void 0:t.onCancelOrderFailed)==null?void 0:P.call(t,$(f))})}},[r,t,S,o,e,i,u,a,n]),A=d.useMemo(()=>{const g=c[(e==null?void 0:e.historyKey)||""];return{isLoading:(g==null?void 0:g.status)===B.LOADING,disabled:!!(e&&!o),isSuccess:(g==null?void 0:g.status)===B.SUCCESS,isError:(g==null?void 0:g.status)===B.FAILED,error:g==null?void 0:g.error,txHash:g==null?void 0:g.txHash}},[c,e,o]);return d.useMemo(()=>({cancelOrder:y,...A}),[y,A])},st=()=>{const{module:e,values:r}=_();if(r.isMarketOrder&&e===s.Module.STOP_LOSS)return Q.TRIGGER_MARKET_PRICE;if(e===s.Module.LIMIT||e===s.Module.TWAP)return r.isMarketOrder?Q.MARKET_PRICE:Q.LIMIT_PRICE},at=()=>{const{callbacks:e}=D(),r=T(c=>c.updateState),{schedule:n}=_(),{duration:t}=n,o=d.useCallback(c=>{r({orderDuration:c}),I(()=>{var u;return(u=e==null?void 0:e.onOrderDurationChange)==null?void 0:u.call(e,c)})},[e,r]),i=d.useCallback(c=>{const u=Number(c);Number.isFinite(u)&&o({unit:t.unit,value:u})},[t.unit,o]),a=d.useCallback(c=>{o({unit:c,value:t.value})},[t.value,o]);return d.useMemo(()=>({duration:t,onChange:o,milliseconds:n.durationMillis,onInputChange:i,onUnitSelect:a,error:n.durationError}),[t,o,i,a,n])},ct=()=>{const{callbacks:e}=D(),r=T(c=>c.updateState),{schedule:n}=_(),{fillDelay:t}=n,o=d.useCallback(c=>{r({tradeInterval:c}),I(()=>{var u;return(u=e==null?void 0:e.onTradeIntervalChange)==null?void 0:u.call(e,c)})},[e,r]),i=d.useCallback(c=>{const u=Number(c);Number.isFinite(u)&&o({unit:t.unit,value:u})},[t.unit,o]),a=d.useCallback(c=>o({unit:c,value:t.value}),[t.value,o]);return d.useMemo(()=>({onInputChange:i,onUnitSelect:a,onChange:o,milliseconds:n.fillDelayMillis,fillDelay:t,error:n.fillDelayError}),[t,o,i,a,n])},q=(e,r)=>({raw:e||"",ui:s.toAmountUI(e,r)}),ut=(e,r,n)=>d.useMemo(()=>!e||!r||!n?[]:e.map(t=>({rawFill:t,inputToken:r,outputToken:n,inputAmount:q(t.inAmount,r.decimals),outputAmount:q(t.outAmount,n.decimals),timestamp:t.timestamp,txHash:t.txHash,executionRate:s.getOrderExecutionRate(t.inAmount,t.outAmount,r.decimals,n.decimals)})),[e,r,n]),dt=(e,r,n)=>{const{chainId:t,partner:o}=D(),i=d.useMemo(()=>{if(!(!r||!n||!e||e.isMarketPrice))return s.getOrderLimitPriceRate(e,r.decimals,n.decimals)},[r,e,n]),a=d.useMemo(()=>{if(!(!r||!n||!e))return s.getTriggerPriceRate(e,r.decimals,n.decimals)},[r,e,n]),c=d.useMemo(()=>{if(!(!r||!n||!e))return s.getOrderExecutionRate(e.srcAmountFilled,e.dstAmountFilled,r.decimals,n.decimals)},[r,e,n]),u=d.useMemo(()=>e?s.getOrderFillDelayMillis(e,t?s.getTwapConfig(o,t):void 0):0,[e,o,t]),S=ut(e==null?void 0:e.fills,r,n);return d.useMemo(()=>{if(e!=null&&e.id)return{original:e,fills:S,inputToken:r,outputToken:n,orderType:e.type,createdAt:e.createdAt,deadline:e.deadline||0,totalTrades:e.totalTradesAmount||0,tradeInterval:u,recipient:e.maker||"",inputAmount:q(e.srcAmount,r==null?void 0:r.decimals),limitPrice:q(s.toAmountRaw(i,n==null?void 0:n.decimals),n==null?void 0:n.decimals),inputAmountPerTrade:q(e.srcAmountPerTrade,r==null?void 0:r.decimals),minOutputAmountPerTrade:q(e.dstMinAmountPerTrade,n==null?void 0:n.decimals),minOutputAmount:q(e.dstMinAmountTotal,n==null?void 0:n.decimals),triggerPrice:q(s.toAmountRaw(a,n==null?void 0:n.decimals),n==null?void 0:n.decimals),id:e.id,inputAmountFilled:q(e.srcAmountFilled,r==null?void 0:r.decimals),outputAmountFilled:q(e.dstAmountFilled,n==null?void 0:n.decimals),progress:e.progress,executionPrice:q(s.toAmountRaw(c,n==null?void 0:n.decimals),n==null?void 0:n.decimals),version:e.version}},[e,S,r,n,u,i,a,c])},lt=()=>{const{marketPriceLoading:e}=D(),r=_().errors.primary;return e?void 0:r},mt=()=>{const{marketPriceLoading:e,inputToken:r,outputToken:n,callbacks:t}=D(),{limitPrice:o,values:i,module:a,isInverted:c}=_(),u=T(P=>P.updateState),S=d.useCallback(P=>{u({limitPriceUi:P,limitPricePercent:null}),I(()=>{var h;return(h=t==null?void 0:t.onLimitPriceChange)==null?void 0:h.call(t,P||"")}),I(()=>{var h;return(h=t==null?void 0:t.onLimitPricePercentChange)==null?void 0:h.call(t,"")})},[t,u]),y=d.useCallback(P=>{u({limitPriceUi:void 0,limitPricePercent:P}),I(()=>{var h;return(h=t==null?void 0:t.onLimitPriceChange)==null?void 0:h.call(t,"")}),I(()=>{var h;return(h=t==null?void 0:t.onLimitPricePercentChange)==null?void 0:h.call(t,P||"")})},[t,u]),A=d.useCallback(()=>{u({limitPriceUi:void 0,limitPricePercent:void 0})},[u]),g=!i.isMarketOrder,f=d.useCallback(()=>{u({isMarketOrder:!i.isMarketOrder,...i.isMarketOrder?{}:{isPriceInverted:!1},...!i.isMarketOrder&&a===s.Module.STOP_LOSS?{limitPricePercent:void 0}:{}})},[a,u,i.isMarketOrder]);return d.useMemo(()=>({price:o.display,canonicalPriceRaw:o.raw,error:o.error,onInputChange:S,onPercentageChange:y,onReset:A,inputToken:r,outputToken:n,displayInputToken:c?n:r,displayOutputToken:c?r:n,percentage:o.percentage,isLoading:!!e,isEnabled:g,toggle:f,isTypedValue:o.isTypedValue}),[r,c,g,o,e,S,y,A,n,f])},gt=()=>{const{marketPriceLoading:e}=D(),{outputAmount:r}=_();return d.useMemo(()=>({amount:r,isLoading:!!e}),[e,r])},Pt=()=>{const{inputToken:e,outputToken:r}=D(),n=T(u=>u.updateState),{isInverted:t,values:o}=_(),i=T(u=>u.state.triggerPriceUi),a=T(u=>u.state.limitPriceUi),c=d.useCallback(()=>{n({isPriceInverted:!t,...i!==void 0?{triggerPriceUi:s.invertPriceInput(i)}:{},...a!==void 0?{limitPriceUi:s.invertPriceInput(a)}:{}})},[n,t,i,a]);return d.useMemo(()=>({onInvert:c,isInverted:t,inputToken:e,outputToken:r,displayInputToken:t?r:e,displayOutputToken:t?e:r,isMarketOrder:o.isMarketOrder}),[e,t,c,r,o.isMarketOrder])},fe=3,ft=3e3,Ot=e=>new Promise(r=>setTimeout(r,e)),ie=(e,r)=>{if(!/^\d+$/.test(e))throw new Error(`${r} must be a non-negative integer base-unit amount`);return BigInt(e)},Oe=async({client:e,walletInteractions:r,tokenAddress:n,inputAmountRaw:t})=>{const o=await r.getAllowance({tokenAddress:n,spenderAddress:e.spenderAddress});return ie(o||"0","Allowance")>=ie(t,"Input amount")},St=e=>{if(!e.client)throw new Error("Spot client is unavailable");if(!e.isSupportedChain||!e.chainId)throw new Error("Spot is unavailable on the connected chain");if(!e.account)throw new Error("missing account");if(!e.inputToken)throw new Error("missing inputToken");if(!e.outputToken)throw new Error("missing outputToken");const r=s.isNativeAddress(e.inputToken.address)?e.wrappedNativeToken:e.inputToken;if(!r||s.isNativeAddress(r.address))throw new Error("missing wrappedNativeToken for native input");if(!e.form.canSubmit)throw new Error("Order form is not submittable");const n=e.form.inputAmount.raw;return ie(n,"Input amount"),{account:e.account,chainId:e.chainId,inputToken:e.inputToken,orderInputToken:r,outputToken:e.outputToken,client:e.client,inputAmountRaw:n}},ht=({account:e,chainId:r,inputToken:n,outputToken:t,preparedOrder:o})=>{const{form:i,values:a}=o;I(()=>s.analytics.onRequestOrder({account:e,chainId:r,module:i.module,srcToken:n,dstToken:t,fromTokenAmount:a.inputAmount,srcChunkAmount:a.inputAmountPerTrade,triggerPricePerTrade:a.triggerOutputAmountPerTrade,deadline:a.deadlineMillis,fillDelay:a.fillDelayMillis,minDstAmountOutPerTrade:a.minOutputAmountPerTrade,slippage:i.values.slippageBps/100,isMarketOrder:a.isMarketOrder,chunksAmount:a.totalTrades}))},Et=async e=>{const{form:r,walletInteractions:n,callbacks:t,addNewOrder:o,refetchActiveOrders:i,getCurrentExecution:a,beginExecution:c,replaceExecution:u,wait:S=Ot}=e;let y;try{y=St(e)}catch(w){const N=$(w),p=ee(w),b=c({form:r,inputToken:e.inputToken,outputToken:e.outputToken,chainId:e.chainId});throw b&&u(b.executionId,{...b,phase:l.FAILED,error:N,parsedError:p}),I(()=>{var G;return(G=t==null?void 0:t.onSubmitOrderFailed)==null?void 0:G.call(t,p)}),N}const{account:A,chainId:g,inputToken:f,orderInputToken:P,outputToken:h,client:F,inputAmountRaw:R}=y,W=a(),x=Le({execution:W,account:A,chainId:g,inputTokenAddress:f.address,inputAmountRaw:R}),j=c({form:r,inputToken:f,outputToken:h,chainId:g,completedWrap:x,wrapTxHash:x==null?void 0:x.txHash});if(!j)return;const O=j.executionId;let E=j;const v=(w,N={})=>{const p={...E,...N,executionId:O,phase:w};if(!u(O,p))throw new Error("Execution is no longer current");E=p},C=(w,N={})=>{const p={...E,...N,executionId:O,phase:w};return u(O,p)?(E=p,!0):!1};try{const w=s.isNativeAddress(f.address)&&!x,N=!await Oe({client:F,walletInteractions:n,tokenAddress:P.address,inputAmountRaw:R}),p=[];w&&p.push(H.WRAP),N&&p.push(H.APPROVE),p.push(H.CREATE);let b=0;if(v(l.PREPARING,{pendingSteps:p,totalSteps:p.length,stepIndex:b,hasApproval:!N}),w){v(l.WRAPPING),I(()=>s.analytics.onWrapRequest()),I(t==null?void 0:t.onWrapRequest);const M=await n.wrapNativeToken(R);if(!M)throw new Error("failed to wrap input token");const z={account:A,chainId:g,inputTokenAddress:f.address,inputAmountRaw:R,txHash:M};b++,v(l.WRAPPING,{wrapTxHash:M,completedWrap:z,stepIndex:b}),I(()=>s.analytics.onWrapSuccess(M)),I(()=>{var K;return(K=t==null?void 0:t.onWrapSuccess)==null?void 0:K.call(t,{txHash:M,amount:s.toAmountUI(R,P.decimals)})})}if(N){v(l.APPROVING),I(()=>s.analytics.onApproveRequest()),I(t==null?void 0:t.onApproveRequest);const M=await n.approveToken({tokenAddress:P.address,amount:R,spenderAddress:F.spenderAddress});if(!M)throw new Error("failed to approve token");v(l.APPROVING,{approveTxHash:M});let z=!1;for(let K=0;K<fe&&(z=await Oe({client:F,walletInteractions:n,tokenAddress:P.address,inputAmountRaw:R}),!z);K++)K<fe-1&&await S(ft);if(!z)throw new Error(`Insufficient ${P.symbol} allowance to perform the swap. Please approve the token first.`);b++,v(l.APPROVING,{hasApproval:!0,stepIndex:b}),I(()=>s.analytics.onApproveSuccess(M)),I(()=>{var K;return(K=t==null?void 0:t.onApproveSuccess)==null?void 0:K.call(t,{txHash:M,token:P,amount:s.toAmountUI(R,P.decimals)})})}v(l.SIGNING);const G=F.prepareOrder({form:r,inputTokenAddress:P.address,outputTokenAddress:h.address,swapperAddress:A});v(l.SIGNING,{preparedOrder:G}),ht({account:A,chainId:g,inputToken:f,outputToken:h,preparedOrder:G}),I(()=>s.analytics.onSignOrderRequest(G.order)),I(t==null?void 0:t.onSignOrderRequest);let k;try{k=await n.signOrder(G.signingRequest),I(()=>s.analytics.onSignOrderSuccess(k)),I(()=>{var M;return(M=t==null?void 0:t.onSignOrderSuccess)==null?void 0:M.call(t,k)})}catch(M){throw I(()=>s.analytics.onSignOrderError(M)),I(()=>{var z;return(z=t==null?void 0:t.onSignOrderError)==null?void 0:z.call(t,$(M))}),M}v(l.SUBMITTING);const Z=await F.submitOrder(G.order,k);return v(l.SUCCESS,{orderId:Z.id.toString()}),I(()=>o(Z)),I(()=>i()),I(()=>{var M;return(M=t==null?void 0:t.onOrderCreated)==null?void 0:M.call(t,Z)}),Z}catch(w){const N=E.phase,p=$(w),b=s.isTxRejected(w);throw C(b?l.REJECTED:l.FAILED,{error:p,parsedError:ee(w)}),N===l.WRAPPING?I(()=>s.analytics.onWrapError(w)):N===l.APPROVING&&I(()=>s.analytics.onApproveError(w)),I(b?t==null?void 0:t.onSubmitOrderRejected:()=>{var G;return(G=t==null?void 0:t.onSubmitOrderFailed)==null?void 0:G.call(t,ee(w))}),p}},It=()=>{const{inputToken:e,outputToken:r,wrappedNativeToken:n,chainId:t,isSupportedChain:o,callbacks:i,account:a,walletInteractions:c}=D(),{data:u}=U(),S=ke(),y=Xe(),A=_(),g=V();return d.useCallback(()=>{Et({account:a,chainId:t,isSupportedChain:o,inputToken:e,outputToken:r,wrappedNativeToken:n,form:A,client:u,walletInteractions:c,callbacks:i,addNewOrder:S,refetchActiveOrders:y,getCurrentExecution:()=>g.getState().state.currentExecution,beginExecution:g.getState().beginExecution,replaceExecution:g.getState().replaceExecution}).catch(()=>{})},[a,S,i,t,u,A,e,o,r,n,y,g,c])},At=()=>{const e=T(n=>n.state.currentExecution),r=T(n=>n.returnToOrderForm);return d.useMemo(()=>({...e,returnToOrderForm:r}),[e,r])},Ct=()=>{const e=At(),{inputToken:r,outputToken:n,chainId:t,isSupportedChain:o,module:i,overrides:a}=D(),{data:c,isLoading:u}=U(),S=It(),y=T(F=>F.startNewOrder),A=d.useCallback(()=>S(),[S]),g=d.useCallback(()=>y(me({module:i,overrides:a})),[i,a,y]),f=we(e.phase),P=Re(e.phase),h=J(e.phase);return d.useMemo(()=>({phase:e.phase,status:f,error:e.parsedError,currentStep:P,currentStepIndex:e.stepIndex,approvalTxHash:e.approveTxHash,wrapTxHash:e.wrapTxHash,totalSteps:e.totalSteps,executionSteps:e.pendingSteps,inputToken:e.inputToken??r,outputToken:e.outputToken??n,chainId:e.chainId??t,submitOrder:A,startNewOrder:g,returnToOrderForm:e.returnToOrderForm,isExecuting:h,isSuccess:e.phase===l.SUCCESS,isFailed:e.phase===l.FAILED,isRejected:e.phase===l.REJECTED,isPreparingOrder:e.phase===l.PREPARING||o&&u&&!c,canDismiss:!h}),[c,P,r,n,t,u,h,o,g,A,f,e])},yt=()=>{const{inputToken:e,outputToken:r,wrappedNativeToken:n,inputBalanceRaw:t,noLiquidity:o,inputAmountUi:i,marketPriceLoading:a,isSupportedChain:c}=D(),u=_(),{data:S,isLoading:y}=U(),A=T(R=>R.state.currentExecution.phase),g=J(A),f=!!(e&&s.isNativeAddress(e.address)&&(!n||s.isNativeAddress(n.address))),P=a||!u.isReady||t===void 0,h=g||c&&y&&!S||!!(e&&r&&i&&P),F=!!(!u.canSubmit||g||!c||!S||o||h||!e||!r||f);return d.useMemo(()=>({disabled:F,loading:h}),[F,h])},vt=()=>{const{inputToken:e,outputToken:r,callbacks:n}=D(),t=T(a=>a.updateState),{trades:o}=_(),i=d.useCallback(a=>{t({tradeCount:a}),I(()=>{var c;return(c=n==null?void 0:n.onTradeCountChange)==null?void 0:c.call(n,a)})},[n,t]);return d.useMemo(()=>({totalTrades:o.totalTrades,maxTrades:o.maxTrades,inputAmountPerTrade:o.inputAmountPerTrade,minOutputAmountPerTrade:o.minOutputAmountPerTrade,triggerOutputAmountPerTrade:o.triggerOutputAmountPerTrade,onChange:i,error:o.error,inputToken:e,outputToken:r}),[e,i,r,o])},wt=()=>{const{marketPriceLoading:e,inputToken:r,outputToken:n,callbacks:t}=D(),{marketPrice:o,trades:i,triggerPrice:a,isInverted:c}=_(),u=T(g=>g.updateState),S=d.useCallback(g=>{u({triggerPriceUi:g,triggerPricePercent:null}),I(()=>{var f;return(f=t==null?void 0:t.onTriggerPriceChange)==null?void 0:f.call(t,g||"")}),I(()=>{var f;return(f=t==null?void 0:t.onTriggerPricePercentChange)==null?void 0:f.call(t,"")})},[t,u]),y=d.useCallback(g=>{u({triggerPriceUi:void 0,triggerPricePercent:g}),I(()=>{var f;return(f=t==null?void 0:t.onTriggerPriceChange)==null?void 0:f.call(t,"")}),I(()=>{var f;return(f=t==null?void 0:t.onTriggerPricePercentChange)==null?void 0:f.call(t,g||"")})},[t,u]),A=d.useCallback(()=>{u({triggerPricePercent:void 0,triggerPriceUi:void 0})},[u]);return d.useMemo(()=>({price:a.display,canonicalPriceRaw:a.raw,outputAmountPerTrade:i.triggerOutputAmountPerTrade,error:a.error,onInputChange:S,onPercentageChange:y,percentage:a.percentage,onReset:A,inputToken:r,outputToken:n,displayInputToken:c?n:r,displayOutputToken:c?r:n,isLoading:!!(e||!o.raw),isTypedValue:a.isTypedValue}),[r,c,o.raw,e,S,y,A,n,i.triggerOutputAmountPerTrade,a])};s.setUIVersion(Ee.version),Object.defineProperty(m,"DISCLAIMER_URL",{enumerable:!0,get:()=>s.DISCLAIMER_URL}),Object.defineProperty(m,"InputErrors",{enumerable:!0,get:()=>s.InputErrors}),Object.defineProperty(m,"Module",{enumerable:!0,get:()=>s.Module}),Object.defineProperty(m,"ORBS_LOGO",{enumerable:!0,get:()=>s.ORBS_LOGO}),Object.defineProperty(m,"ORBS_SLTP_FAQ_URL",{enumerable:!0,get:()=>s.ORBS_SLTP_FAQ_URL}),Object.defineProperty(m,"ORBS_TWAP_FAQ_URL",{enumerable:!0,get:()=>s.ORBS_TWAP_FAQ_URL}),Object.defineProperty(m,"ORBS_WEBSITE_URL",{enumerable:!0,get:()=>s.ORBS_WEBSITE_URL}),Object.defineProperty(m,"OrderFilter",{enumerable:!0,get:()=>s.OrderFilter}),Object.defineProperty(m,"OrderStatus",{enumerable:!0,get:()=>s.OrderStatus}),Object.defineProperty(m,"OrderType",{enumerable:!0,get:()=>s.OrderType}),Object.defineProperty(m,"Partners",{enumerable:!0,get:()=>s.Partners}),Object.defineProperty(m,"SPOT_VERSION",{enumerable:!0,get:()=>s.SPOT_VERSION}),Object.defineProperty(m,"TimeUnit",{enumerable:!0,get:()=>s.TimeUnit}),Object.defineProperty(m,"calculateOrderForm",{enumerable:!0,get:()=>s.calculateOrderForm}),Object.defineProperty(m,"createClient",{enumerable:!0,get:()=>s.createClient}),Object.defineProperty(m,"eqIgnoreCase",{enumerable:!0,get:()=>s.eqIgnoreCase}),Object.defineProperty(m,"getOrderExecutionRate",{enumerable:!0,get:()=>s.getOrderExecutionRate}),Object.defineProperty(m,"getOrderFillDelayMillis",{enumerable:!0,get:()=>s.getOrderFillDelayMillis}),Object.defineProperty(m,"getOrderLimitPriceRate",{enumerable:!0,get:()=>s.getOrderLimitPriceRate}),Object.defineProperty(m,"getPartnerChains",{enumerable:!0,get:()=>s.getPartnerChains}),Object.defineProperty(m,"getPartners",{enumerable:!0,get:()=>s.getPartners}),Object.defineProperty(m,"getTriggerPriceRate",{enumerable:!0,get:()=>s.getTriggerPriceRate}),Object.defineProperty(m,"getTwapConfig",{enumerable:!0,get:()=>s.getTwapConfig}),Object.defineProperty(m,"invertPriceInput",{enumerable:!0,get:()=>s.invertPriceInput}),Object.defineProperty(m,"isNativeAddress",{enumerable:!0,get:()=>s.isNativeAddress}),Object.defineProperty(m,"isTxRejected",{enumerable:!0,get:()=>s.isTxRejected}),Object.defineProperty(m,"toAmountRaw",{enumerable:!0,get:()=>s.toAmountRaw}),Object.defineProperty(m,"toAmountUI",{enumerable:!0,get:()=>s.toAmountUI}),m.Disclaimer=Q,m.ExecutionPhase=l,m.ExecutionStatus=B,m.SpotProvider=Qe,m.Steps=H,m.useAmountUi=Ye,m.useCancelOrder=ot,m.useClient=U,m.useDisclaimer=st,m.useDuration=at,m.useExecution=Ct,m.useFillDelay=ct,m.useHistoryOrder=dt,m.useInputErrors=lt,m.useLimitPrice=mt,m.useOrderForm=_,m.useOrders=et,m.useOutputAmount=gt,m.usePriceDisplay=Pt,m.useSubmitButton=yt,m.useTrades=vt,m.useTriggerPrice=wt,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(m,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@orbs-network/spot-ui"),require("react/jsx-runtime"),require("react"),require("zustand"),require("zustand/vanilla")):typeof define=="function"&&define.amd?define(["exports","@orbs-network/spot-ui","react/jsx-runtime","react","zustand","zustand/vanilla"],a):(m=typeof globalThis<"u"?globalThis:m||self,a(m.SpotReact={},m.SpotUI,m.jsxRuntime,m.React,m.Zustand,m.ZustandVanilla))})(this,(function(m,a,T,l,Se,Ee){"use strict";"use client";var wt=Object.defineProperty;var Rt=(m,a,T)=>a in m?wt(m,a,{enumerable:!0,configurable:!0,writable:!0,value:T}):m[a]=T;var oe=(m,a,T)=>Rt(m,typeof a!="symbol"?a+"":a,T);const he={version:"2.1.10"},se=l.createContext(null),Ie=({children:e,value:r})=>T.jsx(se.Provider,{value:r,children:e}),b=()=>{const e=l.useContext(se);if(e===null)throw new Error("useSpotRuntime must be used within SpotProvider");return e};var _=(e=>(e[e.LOADING=1]="LOADING",e[e.SUCCESS=2]="SUCCESS",e[e.FAILED=3]="FAILED",e))(_||{}),d=(e=>(e.IDLE="idle",e.PREPARING="preparing",e.WRAPPING="wrapping",e.APPROVING="approving",e.SIGNING="signing",e.SUBMITTING="submitting",e.SUCCESS="success",e.FAILED="failed",e.REJECTED="rejected",e))(d||{}),Y=(e=>(e.TRIGGER_MARKET_PRICE="triggerMarketPriceDisclaimer",e.MARKET_PRICE="marketOrderDisclaimer",e.LIMIT_PRICE="limitOrderDisclaimer",e))(Y||{}),H=(e=>(e.WRAP="wrap",e.APPROVE="approve",e.CREATE="create",e))(H||{});const Ae=new Set([d.PREPARING,d.WRAPPING,d.APPROVING,d.SIGNING,d.SUBMITTING]),Ce={[d.IDLE]:new Set,[d.PREPARING]:new Set([d.PREPARING,d.WRAPPING,d.APPROVING,d.SIGNING,d.FAILED,d.REJECTED]),[d.WRAPPING]:new Set([d.WRAPPING,d.APPROVING,d.SIGNING,d.FAILED,d.REJECTED]),[d.APPROVING]:new Set([d.APPROVING,d.SIGNING,d.FAILED,d.REJECTED]),[d.SIGNING]:new Set([d.SIGNING,d.SUBMITTING,d.FAILED,d.REJECTED]),[d.SUBMITTING]:new Set([d.SUCCESS,d.FAILED,d.REJECTED]),[d.SUCCESS]:new Set,[d.FAILED]:new Set,[d.REJECTED]:new Set},$=e=>({phase:d.IDLE,completedWrap:e}),U=e=>Ae.has(e),ye=e=>e===d.IDLE||e===d.FAILED||e===d.REJECTED,ve=(e,r)=>Ce[e].has(r),we=e=>{if(U(e))return _.LOADING;if(e===d.SUCCESS)return _.SUCCESS;if(e===d.FAILED||e===d.REJECTED)return _.FAILED},Re=e=>{if(e===d.WRAPPING)return H.WRAP;if(e===d.APPROVING)return H.APPROVE;if(e===d.SIGNING||e===d.SUBMITTING)return H.CREATE},X=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(typeof e=="object"&&e!==null){const r=Reflect.get(e,"message");if(typeof r=="string")return r}return"Unknown error"},Te=e=>{if(typeof e!="object"||e===null)return 0;const r=Reflect.get(e,"code");return typeof r=="number"&&Number.isFinite(r)?r:typeof r=="string"&&/^-?\d+$/.test(r)?Number(r):0},k=e=>e instanceof Error?e:new Error(X(e)),ee=e=>{const r=X(e),n=r.match(/,\s*code\s*:\s*(-?\d+)/i);return{message:r.replace(/^error\s*:/i,"").replace(/,\s*code\s*:\s*-?\d+/i,"").trim()||"Unknown error",code:Te(e)||(n?Number(n[1]):0)}},I=e=>{if(e)try{const r=e();Promise.resolve(r).catch(()=>{})}catch{}},Le=({execution:e,account:r,chainId:n,inputTokenAddress:t,inputAmountRaw:o})=>{const i=e.completedWrap;if((i==null?void 0:i.account.toLowerCase())===r.toLowerCase()&&i.chainId===n&&i.inputTokenAddress.toLowerCase()===t.toLowerCase()&&Ne(i.inputAmountRaw,o))return i},Ne=(e,r)=>{try{return BigInt(e)>=BigInt(r)}catch{return!1}},pe=2e4,ae=new WeakMap,ce=e=>{const r=ae.get(e);if(r)return r;const n={all:[...e].sort((t,o)=>o.createdAt-t.createdAt),open:[],completed:[],cancelled:[],expired:[]};for(const t of n.all)switch(t.status){case a.OrderStatus.Open:n.open.push(t);break;case a.OrderStatus.Completed:n.completed.push(t);break;case a.OrderStatus.Cancelled:n.cancelled.push(t);break;case a.OrderStatus.Expired:n.expired.push(t);break}return ae.set(e,n),n},Fe=(e,r)=>{const n=new Set(e.map(o=>o.historyKey)),t=(r==null?void 0:r.filter(o=>o.version===1&&!n.has(o.historyKey)))??[];return[...e,...t]},Me=(e,r,n)=>{if(!e)return;const t=new Map(r.map(i=>[i.historyKey,i])),o=[];for(const i of e){if(i.version!==2)continue;const s=t.get(i.historyKey);!s||s.progress===i.progress||(o.push(s),s.status===a.OrderStatus.Completed&&I(()=>{var c;return(c=n==null?void 0:n.onOrderFilled)==null?void 0:c.call(n,s)}))}o.length>0&&I(()=>{var i;return(i=n==null?void 0:n.onOrdersProgressUpdate)==null?void 0:i.call(n,o)})},ue=e=>{if(e===null||typeof e!="object")return!1;const r=Object.getPrototypeOf(e);return r===Object.prototype||r===null},te=(e,r)=>{if(Object.is(e,r))return e;if(Array.isArray(e)&&Array.isArray(r)){const n=r.map((o,i)=>te(e[i],o));return e.length===n.length&&n.every((o,i)=>o===e[i])?e:n}if(ue(e)&&ue(r)){const n=Object.keys(e),t=Object.keys(r),o={};let i=n.length===t.length;for(const s of t){Object.prototype.hasOwnProperty.call(e,s)||(i=!1);const c=te(e[s],r[s]);o[s]=c,c!==e[s]&&(i=!1)}return i?e:o}return r},De=(e,r)=>e?te(e,r):r,re=e=>({tradeCount:e.tradeCount,tradeInterval:e.tradeInterval,orderDuration:e.orderDuration,limitPriceUi:e.limitPriceUi,triggerPriceUi:e.triggerPriceUi,triggerPricePercent:e.triggerPricePercent,limitPricePercent:e.limitPricePercent,isMarketOrder:e.isMarketOrder,isPriceInverted:void 0}),be=e=>({...re(e),cancelOrders:{},currentExecution:$()}),de={isFetching:!1},le={isFetching:!1},Ge=e=>new Promise(r=>setTimeout(r,e)),xe=e=>{let r=0,n,t,o=0,i,s,c,u=!1,E=0,y=0,g,P,h;return Ee.createStore((f,A)=>{const L=async()=>{if(!n||!t)return;if(i)return i;const O=++o,S=t;f(C=>({client:{key:n,data:C.client.data,error:void 0,isFetching:!0}}));const v=(async()=>{let C;for(let w=0;w<3;w++){if(O!==o)return;try{const N=await S();return O!==o?void 0:(f({client:{key:n,data:N,isFetching:!1}}),N)}catch(N){if(C=N instanceof Error?N:new Error(String(N)),O!==o)return;w<2&&await Ge(2**w*1e3)}}O===o&&f({client:{key:n,error:C,isFetching:!1}})})();return i=v,v.finally(()=>{i===v&&(i=void 0)}),v},p=async(O=!1,S=!1)=>{if(!O&&E===0||!s||!c)return A().orders.data;if(g){if(!S)return g;const M=s;return await g,s!==M?void 0:p(O,S)}const v=++y,C=c,w=A().orders.data,N=new AbortController;P=N,f(M=>({orders:{key:s,data:M.orders.data,error:void 0,isFetching:!0}}));const F=C(w,S?!1:u,N.signal).then(({orders:M,legacyLoaded:G})=>{if(v!==y)return;u=G;const V=De(A().orders.data,M);return f({orders:{key:s,data:V,isFetching:!1}}),V}).catch(M=>{if(v!==y||N.signal.aborted)return;const G=M instanceof Error?M:new Error(String(M));f(V=>({orders:{key:s,data:V.orders.data,error:G,isFetching:!1}}))});return g=F,F.finally(()=>{g===F&&(g=void 0),P===N&&(P=void 0)}),F},W=()=>{p()},x=()=>{h&&(clearInterval(h),h=void 0),typeof window<"u"&&window.removeEventListener("focus",W),P==null||P.abort(),P=void 0,g=void 0,y++,f(O=>({orders:{...O.orders,isFetching:!1}}))},B=()=>{!s||!c||h||(p(!0),h=setInterval(()=>{p()},pe),typeof window<"u"&&window.addEventListener("focus",W))};return{client:de,orders:le,state:be(e),configureClient:(O,S)=>{if(n===O){t=S;return}n=O,t=S,o++,i=void 0,f({client:O?{key:O,isFetching:!1}:de}),O&&S&&L()},refetchClient:L,configureOrders:(O,S)=>{if(s===O){c=S;return}x(),s=O,c=S,u=!1,f({orders:O?{key:O,isFetching:!1}:le}),E>0&&B()},registerOrdersConsumer:()=>(E++,E===1&&B(),()=>{E=Math.max(0,E-1),E===0&&x()}),refetchOrders:p,addOrder:O=>{f(S=>{const v=S.orders.data;return v!=null&&v.some(C=>C.historyKey===O.historyKey)?S:{orders:{...S.orders,data:[O,...v??[]]}}})},updateOrderStatus:(O,S)=>{f(v=>{var C;return{orders:{...v.orders,data:(C=v.orders.data)==null?void 0:C.map(w=>w.historyKey===O?{...w,status:S}:w)}}})},updateState:O=>f(S=>({state:{...S.state,...O}})),beginExecution:O=>{let S;return f(v=>ye(v.state.currentExecution.phase)?(S={...O,executionId:++r,phase:d.PREPARING},{state:{...v.state,currentExecution:S}}):v),S},replaceExecution:(O,S)=>{let v=!1;return f(C=>{const w=C.state.currentExecution;return w.executionId!==O||S.executionId!==O||!ve(w.phase,S.phase)?C:(v=!0,{state:{...C.state,currentExecution:S}})}),v},returnToOrderForm:()=>{const O=A().state.currentExecution;return U(O.phase)||O.phase===d.SUCCESS?!1:(f(S=>({state:{...S.state,currentExecution:$(O.completedWrap)}})),!0)},syncFormDefaults:O=>U(A().state.currentExecution.phase)?!1:(f(S=>({state:{...S.state,...re(O),currentExecution:$()}})),!0),startNewOrder:O=>{const{state:S}=A();return U(S.currentExecution.phase)?!1:(f(v=>({state:{...v.state,...re(O),isMarketOrder:S.isMarketOrder,currentExecution:$()}})),!0)}}})},me=e=>{var n;const r=(n=e.overrides)==null?void 0:n.state;return{isMarketOrder:e.module===a.Module.LIMIT?!1:r==null?void 0:r.isMarketOrder,tradeCount:r==null?void 0:r.tradeCount,tradeInterval:r==null?void 0:r.tradeInterval,orderDuration:r==null?void 0:r.orderDuration,limitPriceUi:r==null?void 0:r.limitPriceUi,triggerPriceUi:r==null?void 0:r.triggerPriceUi,triggerPricePercent:r==null?void 0:r.triggerPricePercent,limitPricePercent:r==null?void 0:r.limitPricePercent}},ge=l.createContext(null),_e=({children:e,initialState:r})=>{const[n]=l.useState(()=>xe(r));return T.jsx(ge.Provider,{value:n,children:e})},z=()=>{const e=l.useContext(ge);if(e===null)throw new Error("useSpotStore must be used within SpotProvider");return e},R=e=>{const r=z();return Se.useStore(r,e)},je={isFetching:!1},Q=()=>{const{partner:e,chainId:r,isSupportedChain:n}=b(),t=z(),o=R(y=>y.client),i=!!(r&&n),s=i?`${e}:${r}`:void 0,c=o.key===s?o:je,u=l.useCallback(()=>r?a.createClient(e,r):Promise.reject(new Error("Spot is unavailable on the connected chain")),[r,e]);l.useEffect(()=>{t.getState().configureClient(s,i?u:void 0)},[i,s,u,t]);const E=l.useCallback(()=>{if(!i||!s)return Promise.resolve(void 0);const y=t.getState();return y.configureClient(s,u),y.refetchClient()},[i,s,u,t]);return l.useMemo(()=>({data:c.data,error:c.error,isLoading:i&&!c.data&&c.error===void 0,isFetching:c.isFetching,refetch:E}),[c,i,E])},Be=({error:e,retry:r,isRetrying:n})=>T.jsxs("div",{className:"spot-client-error-fallback",role:"alert",children:[T.jsx("p",{children:e.message||"Unable to load Spot configuration."}),T.jsx("button",{type:"button",className:"spot-client-error-retry",disabled:n,onClick:r,children:n?"Retrying…":"Retry"})]}),qe=({children:e,fallback:r=Be})=>{const{partner:n,chainId:t,isSupportedChain:o,minTradeSizeUsd:i}=b(),{data:s,error:c,isFetching:u,refetch:E}=Q(),y=l.useCallback(async()=>{await E()},[E]);return l.useEffect(()=>{!s||!t||!o||a.analytics.onFetchedConfig(s.rePermitData,n,a.getTwapConfig(n,t),i)},[t,s,o,i,n]),T.jsxs(T.Fragment,{children:[e,!s&&c&&o?T.jsx(r,{error:c,retry:y,isRetrying:u}):null]})},We=({resetErrorBoundary:e})=>T.jsxs("div",{className:"twap-error-fallback",role:"alert",children:[T.jsx("p",{children:"Something went wrong"}),T.jsx("button",{type:"button",onClick:e,children:"Retry"})]}),Ve=({children:e,fallback:r=We})=>T.jsx(Ke,{fallback:r,children:e});class Ke extends l.Component{constructor(){super(...arguments);oe(this,"state",{});oe(this,"resetErrorBoundary",()=>{this.setState({error:void 0})})}static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n){a.analytics.onCrash(n)}render(){const{error:n}=this.state;if(n){const t=this.props.fallback;return T.jsx(t,{error:n,resetErrorBoundary:this.resetErrorBoundary})}return this.props.children}}const He=({children:e,defaults:r,scopeKey:n})=>{const t=z(),o=R(s=>s.state.currentExecution.phase),i=l.useRef(n);return l.useEffect(()=>{i.current===n||U(o)||t.getState().syncFormDefaults(r)&&(i.current=n)},[r,o,n,t]),e},Pe=l.createContext(null),ze=({children:e})=>{const{inputToken:r,outputToken:n,inputAmountUi:t,quotedOutputAmountRaw:o,inputTokenUsdPrice:i,outputTokenUsdPrice:s,minTradeSizeUsd:c,inputBalanceRaw:u,displayFeePercent:E,priceProtectionPercent:y,module:g}=b(),P=R(C=>C.state.tradeCount),h=R(C=>C.state.tradeInterval),f=R(C=>C.state.orderDuration),A=R(C=>C.state.limitPriceUi),L=R(C=>C.state.triggerPriceUi),p=R(C=>C.state.limitPricePercent),W=R(C=>C.state.triggerPricePercent),x=R(C=>C.state.isPriceInverted),B=R(C=>C.state.isMarketOrder),O=R(C=>{const w=C.state.currentExecution;return w.phase!==d.IDLE?w.form:void 0}),S=l.useMemo(()=>({module:g,inputTokenDecimals:(r==null?void 0:r.decimals)??0,outputTokenDecimals:(n==null?void 0:n.decimals)??0,quotedOutputAmountRaw:o,inputTokenUsdPrice:i,outputTokenUsdPrice:s,minTradeSizeUsd:c,priceProtectionPercent:y,displayFeePercent:E,inputBalanceRaw:u,userInput:{inputAmountUi:t,isMarketOrder:!!B,tradeCount:P,tradeInterval:h,orderDuration:f,limitPriceUi:A,limitPricePercent:p,triggerPriceUi:L,triggerPricePercent:W,isPriceInverted:x}}),[n==null?void 0:n.decimals,s,E,o,c,g,y,u,r==null?void 0:r.decimals,i,x,B,p,W,P,f,h,A,t,L]),v=l.useMemo(()=>{const C=a.calculateOrderForm(S);return r&&n?C:{...C,isReady:!1,canSubmit:!1}},[r,n,S]);return T.jsx(Pe.Provider,{value:O??v,children:e})},j=()=>{const e=l.useContext(Pe);if(!e)throw new Error("useOrderForm must be used within OrderFormProvider");return e},Je=(e,r)=>{l.useEffect(()=>{!e.chainId||!r||a.analytics.init(e.partner,e.minTradeSizeUsd,e.chainId,e.appId)},[e.appId,e.chainId,e.minTradeSizeUsd,e.partner,r])},Ue=e=>{var g,P,h,f,A,L,p,W,x,B,O,S;const r=l.useMemo(()=>a.getPartnerChains(e.partner),[e.partner]),n=!!(e.chainId&&r.includes(e.chainId)),t=(g=e.wrappedNativeToken)==null?void 0:g.address,o=!!(t&&(a.isNativeAddress((P=e.inputToken)==null?void 0:P.address)&&a.eqIgnoreCase(((h=e.outputToken)==null?void 0:h.address)||"",t)||a.eqIgnoreCase(((f=e.inputToken)==null?void 0:f.address)||"",t)&&a.isNativeAddress((A=e.outputToken)==null?void 0:A.address))),i=o?a.toAmountRaw(e.inputAmountUi,(L=e.outputToken)==null?void 0:L.decimals):e.marketQuote.isLoading?void 0:e.marketQuote.quotedOutputAmountRaw,s=o?!1:e.marketQuote.isLoading,c=o?!1:e.marketQuote.noLiquidity,u=l.useMemo(()=>me({module:e.module,overrides:e.overrides}),[e.module,e.overrides]),E=JSON.stringify([e.partner,e.chainId,e.module,(p=e.inputToken)==null?void 0:p.address,(W=e.inputToken)==null?void 0:W.decimals,(x=e.outputToken)==null?void 0:x.address,(B=e.outputToken)==null?void 0:B.decimals,(O=e.wrappedNativeToken)==null?void 0:O.address,(S=e.wrappedNativeToken)==null?void 0:S.decimals,u]),y=l.useMemo(()=>({inputAmountUi:e.inputAmountUi,minTradeSizeUsd:e.minTradeSizeUsd,account:e.account,walletInteractions:e.walletInteractions,quotedOutputAmountRaw:i,marketPriceLoading:s,noLiquidity:c,priceProtectionPercent:e.priceProtectionPercent,chainId:e.chainId,isSupportedChain:n,partner:e.partner,module:e.module,displayFeePercent:e.displayFeePercent??0,callbacks:e.callbacks,inputTokenUsdPrice:e.inputTokenUsdPrice,outputTokenUsdPrice:e.outputTokenUsdPrice,inputBalanceRaw:e.inputBalanceRaw,inputToken:e.inputToken,outputToken:e.outputToken,wrappedNativeToken:e.wrappedNativeToken,supportLegacyOrders:e.supportLegacyOrders??!1,overrides:e.overrides}),[e.account,e.callbacks,e.chainId,e.displayFeePercent,e.inputBalanceRaw,e.inputToken,e.inputTokenUsdPrice,e.minTradeSizeUsd,e.module,e.outputToken,e.outputTokenUsdPrice,e.wrappedNativeToken,e.overrides,e.partner,e.priceProtectionPercent,e.supportLegacyOrders,e.inputAmountUi,e.walletInteractions,n,s,c,i]);return{initialState:u,formScopeKey:E,runtime:y}},Qe=e=>{const{initialState:r,formScopeKey:n,runtime:t}=Ue(e);return Je(e,t.isSupportedChain),T.jsx(Ie,{value:t,children:T.jsx(_e,{initialState:r,children:T.jsx(Ve,{fallback:e.errorFallback,children:T.jsx(He,{defaults:r,scopeKey:n,children:T.jsx(qe,{fallback:e.clientErrorFallback,children:T.jsx(ze,{children:e.children})})})})})})},Ye=(e,r)=>l.useMemo(()=>a.toAmountUI(r,e),[e,r]),$e={isFetching:!1},ne=()=>{const{account:e,partner:r,chainId:n,supportLegacyOrders:t,callbacks:o}=b(),{data:i}=Q(),s=z(),c=!!(e&&i),u=c?JSON.stringify([e,i==null?void 0:i.exchangeAddress,r,n,t]):void 0,E=l.useCallback(async(g,P,h)=>{if(!e||!i)return{orders:[],legacyLoaded:!1};const f=t&&!P,A=await i.getAccountOrders({signal:h,account:e,legacyOrders:f});return Me(g,A,o),{orders:t&&!f?Fe(A,g):A,legacyLoaded:P||f}},[e,o,i,t]);l.useEffect(()=>{s.getState().configureOrders(u,c?E:void 0)},[c,u,E,s]);const y=l.useCallback((g=!1)=>{if(!c||!u)return Promise.resolve(void 0);const P=s.getState();return P.configureOrders(u,E),P.refetchOrders(!0,g)},[c,u,E,s]);return{enabled:c,key:u,refetch:y}},ke=()=>{ne();const e=z();return l.useCallback(r=>e.getState().addOrder(r),[e])},Ze=()=>{const e=z();return l.useCallback(()=>e.getState().refetchOrders(),[e])},Xe=()=>{const e=R(u=>u.orders),r=R(u=>u.registerOrdersConsumer),{enabled:n,key:t,refetch:o}=ne(),i=e.key===t?e:$e;l.useEffect(()=>r(),[r]);const s=l.useMemo(()=>i.data===void 0?void 0:ce(i.data),[i.data]),c=l.useCallback(async()=>{const u=await o();return u===void 0?void 0:ce(u)},[o]);return l.useMemo(()=>({data:s,error:i.error,isLoading:n&&s===void 0&&i.error===void 0,isFetching:i.isFetching,isRefetching:i.isFetching&&s!==void 0,refetch:c}),[i,s,n,c])},et=60,tt=()=>{const{refetch:e}=ne();return l.useCallback(async(r,n=!1)=>{for(let t=0;t<et;t++){const o=await e(n);if(!o)throw new Error("orders not found");const i=o.find(s=>s.historyKey===r);if((i==null?void 0:i.status)===a.OrderStatus.Cancelled)return;await new Promise(s=>setTimeout(s,1e3))}throw new Error("Timed out waiting for order cancellation to be confirmed")},[e])},rt=()=>{const e=z(),r=R(t=>t.updateState);return{cancelOrders:R(t=>t.state.cancelOrders),setCancelOrder:(t,o)=>{const i=e.getState().state.cancelOrders;r({cancelOrders:{...i,[t]:o}})},clearCancelOrder:t=>{const o=e.getState().state.cancelOrders,{[t]:i,...s}=o;r({cancelOrders:s})}}},nt=e=>({...e,status:a.OrderStatus.Cancelled}),it=e=>{const{account:r,walletInteractions:n,callbacks:t}=b(),{data:o}=Q(),i=tt(),{cancelOrders:s,setCancelOrder:c,clearCancelOrder:u}=rt(),E=l.useCallback(async()=>{const g=e==null?void 0:e.historyKey;try{if(!r)throw new Error("missing account");if(!e)throw new Error("order is required");if(!o)throw new Error("Spot client is unavailable");const P=e.historyKey;c(P,{status:_.LOADING}),I(()=>{var L;return(L=t==null?void 0:t.onCancelOrderRequest)==null?void 0:L.call(t,e)}),I(()=>a.analytics.onCancelOrderRequest([e.version===1?e.id.toString():e.hash],e.version));const h=o.getCancelOrderRequest(e),f=await n.cancelOrder(h);if(!f)throw new Error("failed to cancel order");I(()=>a.analytics.onCancelOrderSuccess(f)),c(P,{status:_.LOADING,txHash:f}),await i(P,e.version===1);const A=nt(e);return c(P,{status:_.SUCCESS,txHash:f}),I(()=>{var L;return(L=t==null?void 0:t.onCancelOrderSuccess)==null?void 0:L.call(t,{order:A,txHash:f})}),f}catch(P){a.isTxRejected(P)?g&&u(g):(g&&c(g,{status:_.FAILED,error:X(P)}),I(()=>a.analytics.onCancelOrderError(P))),I(()=>{var h;return(h=t==null?void 0:t.onCancelOrderFailed)==null?void 0:h.call(t,k(P))})}},[r,t,u,o,e,i,c,n]),y=l.useMemo(()=>{const g=s[(e==null?void 0:e.historyKey)||""];return{isLoading:(g==null?void 0:g.status)===_.LOADING,disabled:!!(e&&!o),isSuccess:(g==null?void 0:g.status)===_.SUCCESS,isError:(g==null?void 0:g.status)===_.FAILED,error:g==null?void 0:g.error,txHash:g==null?void 0:g.txHash}},[s,e,o]);return l.useMemo(()=>({cancelOrder:E,...y}),[E,y])},ot=()=>{const{module:e,values:r}=j();if(r.isMarketOrder&&e===a.Module.STOP_LOSS)return Y.TRIGGER_MARKET_PRICE;if(e===a.Module.LIMIT||e===a.Module.TWAP)return r.isMarketOrder?Y.MARKET_PRICE:Y.LIMIT_PRICE},st=()=>{const{callbacks:e}=b(),r=R(c=>c.updateState),{schedule:n}=j(),{duration:t}=n,o=l.useCallback(c=>{r({orderDuration:c}),I(()=>{var u;return(u=e==null?void 0:e.onOrderDurationChange)==null?void 0:u.call(e,c)})},[e,r]),i=l.useCallback(c=>{const u=Number(c);Number.isFinite(u)&&o({unit:t.unit,value:u})},[t.unit,o]),s=l.useCallback(c=>{o({unit:c,value:t.value})},[t.value,o]);return l.useMemo(()=>({duration:t,onChange:o,milliseconds:n.durationMillis,onInputChange:i,onUnitSelect:s,error:n.durationError}),[t,o,i,s,n])},at=()=>{const{callbacks:e}=b(),r=R(c=>c.updateState),{schedule:n}=j(),{fillDelay:t}=n,o=l.useCallback(c=>{r({tradeInterval:c}),I(()=>{var u;return(u=e==null?void 0:e.onTradeIntervalChange)==null?void 0:u.call(e,c)})},[e,r]),i=l.useCallback(c=>{const u=Number(c);Number.isFinite(u)&&o({unit:t.unit,value:u})},[t.unit,o]),s=l.useCallback(c=>o({unit:c,value:t.value}),[t.value,o]);return l.useMemo(()=>({onInputChange:i,onUnitSelect:s,onChange:o,milliseconds:n.fillDelayMillis,fillDelay:t,error:n.fillDelayError}),[t,o,i,s,n])},q=(e,r)=>({raw:e||"",ui:a.toAmountUI(e,r)}),ct=(e,r,n)=>l.useMemo(()=>!e||!r||!n?[]:e.map(t=>({rawFill:t,inputToken:r,outputToken:n,inputAmount:q(t.inAmount,r.decimals),outputAmount:q(t.outAmount,n.decimals),timestamp:t.timestamp,txHash:t.txHash,executionRate:a.getOrderExecutionRate(t.inAmount,t.outAmount,r.decimals,n.decimals)})),[e,r,n]),ut=(e,r,n)=>{const{chainId:t,partner:o}=b(),i=l.useMemo(()=>{if(!(!r||!n||!e||e.isMarketPrice))return a.getOrderLimitPriceRate(e,r.decimals,n.decimals)},[r,e,n]),s=l.useMemo(()=>{if(!(!r||!n||!e))return a.getTriggerPriceRate(e,r.decimals,n.decimals)},[r,e,n]),c=l.useMemo(()=>{if(!(!r||!n||!e))return a.getOrderExecutionRate(e.srcAmountFilled,e.dstAmountFilled,r.decimals,n.decimals)},[r,e,n]),u=l.useMemo(()=>e?a.getOrderFillDelayMillis(e,t?a.getTwapConfig(o,t):void 0):0,[e,o,t]),E=ct(e==null?void 0:e.fills,r,n);return l.useMemo(()=>{if(e!=null&&e.id)return{original:e,fills:E,inputToken:r,outputToken:n,orderType:e.type,createdAt:e.createdAt,deadline:e.deadline||0,totalTrades:e.totalTradesAmount||0,tradeInterval:u,recipient:e.maker||"",inputAmount:q(e.srcAmount,r==null?void 0:r.decimals),limitPrice:q(a.toAmountRaw(i,n==null?void 0:n.decimals),n==null?void 0:n.decimals),inputAmountPerTrade:q(e.srcAmountPerTrade,r==null?void 0:r.decimals),minOutputAmountPerTrade:q(e.dstMinAmountPerTrade,n==null?void 0:n.decimals),minOutputAmount:q(e.dstMinAmountTotal,n==null?void 0:n.decimals),triggerPrice:q(a.toAmountRaw(s,n==null?void 0:n.decimals),n==null?void 0:n.decimals),id:e.id,inputAmountFilled:q(e.srcAmountFilled,r==null?void 0:r.decimals),outputAmountFilled:q(e.dstAmountFilled,n==null?void 0:n.decimals),progress:e.progress,executionPrice:q(a.toAmountRaw(c,n==null?void 0:n.decimals),n==null?void 0:n.decimals),version:e.version}},[e,E,r,n,u,i,s,c])},dt=()=>{const{marketPriceLoading:e}=b(),r=j().errors.primary;return e?void 0:r},lt=()=>{const{marketPriceLoading:e,inputToken:r,outputToken:n,callbacks:t}=b(),{limitPrice:o,values:i,module:s,isInverted:c}=j(),u=R(f=>f.updateState),E=l.useCallback(f=>{u({limitPriceUi:f,limitPricePercent:null}),I(()=>{var A;return(A=t==null?void 0:t.onLimitPriceChange)==null?void 0:A.call(t,f||"")}),I(()=>{var A;return(A=t==null?void 0:t.onLimitPricePercentChange)==null?void 0:A.call(t,"")})},[t,u]),y=l.useCallback(f=>{u({limitPriceUi:void 0,limitPricePercent:f}),I(()=>{var A;return(A=t==null?void 0:t.onLimitPriceChange)==null?void 0:A.call(t,"")}),I(()=>{var A;return(A=t==null?void 0:t.onLimitPricePercentChange)==null?void 0:A.call(t,f||"")})},[t,u]),g=l.useCallback(()=>{u({limitPriceUi:void 0,limitPricePercent:void 0})},[u]),P=!i.isMarketOrder,h=l.useCallback(()=>{u({isMarketOrder:!i.isMarketOrder,...i.isMarketOrder?{}:{isPriceInverted:!1},...!i.isMarketOrder&&s===a.Module.STOP_LOSS?{limitPricePercent:void 0}:{}})},[s,u,i.isMarketOrder]);return l.useMemo(()=>({price:o.display,canonicalPriceRaw:o.raw,error:o.error,onInputChange:E,onPercentageChange:y,onReset:g,inputToken:r,outputToken:n,displayInputToken:c?n:r,displayOutputToken:c?r:n,percentage:o.percentage,isLoading:!!e,isEnabled:P,toggle:h,isTypedValue:o.isTypedValue}),[r,c,P,o,e,E,y,g,n,h])},mt=()=>{const{marketPriceLoading:e}=b(),{outputAmount:r}=j();return l.useMemo(()=>({amount:r,isLoading:!!e}),[e,r])},gt=()=>{const{inputToken:e,outputToken:r}=b(),n=R(u=>u.updateState),{isInverted:t,values:o}=j(),i=R(u=>u.state.triggerPriceUi),s=R(u=>u.state.limitPriceUi),c=l.useCallback(()=>{n({isPriceInverted:!t,...i!==void 0?{triggerPriceUi:a.invertPriceInput(i)}:{},...s!==void 0?{limitPriceUi:a.invertPriceInput(s)}:{}})},[n,t,i,s]);return l.useMemo(()=>({onInvert:c,isInverted:t,inputToken:e,outputToken:r,displayInputToken:t?r:e,displayOutputToken:t?e:r,isMarketOrder:o.isMarketOrder}),[e,t,c,r,o.isMarketOrder])},fe=3,Pt=3e3,ft=e=>new Promise(r=>setTimeout(r,e)),ie=(e,r)=>{if(!/^\d+$/.test(e))throw new Error(`${r} must be a non-negative integer base-unit amount`);return BigInt(e)},Oe=async({client:e,walletInteractions:r,tokenAddress:n,inputAmountRaw:t})=>{const o=await r.getAllowance({tokenAddress:n,spenderAddress:e.spenderAddress});return ie(o||"0","Allowance")>=ie(t,"Input amount")},Ot=e=>{if(!e.client)throw new Error("Spot client is unavailable");if(!e.isSupportedChain||!e.chainId)throw new Error("Spot is unavailable on the connected chain");if(!e.account)throw new Error("missing account");if(!e.inputToken)throw new Error("missing inputToken");if(!e.outputToken)throw new Error("missing outputToken");const r=a.isNativeAddress(e.inputToken.address)?e.wrappedNativeToken:e.inputToken;if(!r||a.isNativeAddress(r.address))throw new Error("missing wrappedNativeToken for native input");if(!e.form.canSubmit)throw new Error("Order form is not submittable");const n=e.form.inputAmount.raw;return ie(n,"Input amount"),{account:e.account,chainId:e.chainId,inputToken:e.inputToken,orderInputToken:r,outputToken:e.outputToken,client:e.client,inputAmountRaw:n}},St=({account:e,chainId:r,inputToken:n,outputToken:t,preparedOrder:o})=>{const{form:i,values:s}=o;I(()=>a.analytics.onRequestOrder({account:e,chainId:r,module:i.module,srcToken:n,dstToken:t,fromTokenAmount:s.inputAmount,srcChunkAmount:s.inputAmountPerTrade,triggerPricePerTrade:s.triggerOutputAmountPerTrade,deadline:s.deadlineMillis,fillDelay:s.fillDelayMillis,minDstAmountOutPerTrade:s.minOutputAmountPerTrade,slippage:i.values.slippageBps/100,isMarketOrder:s.isMarketOrder,chunksAmount:s.totalTrades}))},Et=async e=>{const{form:r,walletInteractions:n,callbacks:t,addNewOrder:o,refetchActiveOrders:i,getCurrentExecution:s,beginExecution:c,replaceExecution:u,wait:E=ft}=e;let y;try{y=Ot(e)}catch(w){const N=k(w),F=ee(w),M=c({form:r,inputToken:e.inputToken,outputToken:e.outputToken,chainId:e.chainId});throw M&&u(M.executionId,{...M,phase:d.FAILED,error:N,parsedError:F}),I(()=>{var G;return(G=t==null?void 0:t.onSubmitOrderFailed)==null?void 0:G.call(t,F)}),N}const{account:g,chainId:P,inputToken:h,orderInputToken:f,outputToken:A,client:L,inputAmountRaw:p}=y,W=s(),x=Le({execution:W,account:g,chainId:P,inputTokenAddress:h.address,inputAmountRaw:p}),B=c({form:r,inputToken:h,outputToken:A,chainId:P,completedWrap:x,wrapTxHash:x==null?void 0:x.txHash});if(!B)return;const O=B.executionId;let S=B;const v=(w,N={})=>{const F={...S,...N,executionId:O,phase:w};if(!u(O,F))throw new Error("Execution is no longer current");S=F},C=(w,N={})=>{const F={...S,...N,executionId:O,phase:w};return u(O,F)?(S=F,!0):!1};try{const w=a.isNativeAddress(h.address)&&!x,N=!await Oe({client:L,walletInteractions:n,tokenAddress:f.address,inputAmountRaw:p}),F=[];w&&F.push(H.WRAP),N&&F.push(H.APPROVE),F.push(H.CREATE);let M=0;if(v(d.PREPARING,{pendingSteps:F,totalSteps:F.length,stepIndex:M,hasApproval:!N}),w){v(d.WRAPPING),I(()=>a.analytics.onWrapRequest()),I(t==null?void 0:t.onWrapRequest);const D=await n.wrapNativeToken(p);if(!D)throw new Error("failed to wrap input token");const J={account:g,chainId:P,inputTokenAddress:h.address,inputAmountRaw:p,txHash:D};M++,v(d.WRAPPING,{wrapTxHash:D,completedWrap:J,stepIndex:M}),I(()=>a.analytics.onWrapSuccess(D)),I(()=>{var K;return(K=t==null?void 0:t.onWrapSuccess)==null?void 0:K.call(t,{txHash:D,amount:a.toAmountUI(p,f.decimals)})})}if(N){v(d.APPROVING),I(()=>a.analytics.onApproveRequest()),I(t==null?void 0:t.onApproveRequest);const D=await n.approveToken({tokenAddress:f.address,amount:p,spenderAddress:L.spenderAddress});if(!D)throw new Error("failed to approve token");v(d.APPROVING,{approveTxHash:D});let J=!1;for(let K=0;K<fe&&(J=await Oe({client:L,walletInteractions:n,tokenAddress:f.address,inputAmountRaw:p}),!J);K++)K<fe-1&&await E(Pt);if(!J)throw new Error(`Insufficient ${f.symbol} allowance to perform the swap. Please approve the token first.`);M++,v(d.APPROVING,{hasApproval:!0,stepIndex:M}),I(()=>a.analytics.onApproveSuccess(D)),I(()=>{var K;return(K=t==null?void 0:t.onApproveSuccess)==null?void 0:K.call(t,{txHash:D,token:f,amount:a.toAmountUI(p,f.decimals)})})}v(d.SIGNING);const G=L.prepareOrder({form:r,inputTokenAddress:f.address,outputTokenAddress:A.address,swapperAddress:g});v(d.SIGNING,{preparedOrder:G}),St({account:g,chainId:P,inputToken:h,outputToken:A,preparedOrder:G}),I(()=>a.analytics.onSignOrderRequest(G.order)),I(t==null?void 0:t.onSignOrderRequest);let V;try{V=await n.signOrder(G.signingRequest),I(()=>a.analytics.onSignOrderSuccess(V)),I(()=>{var D;return(D=t==null?void 0:t.onSignOrderSuccess)==null?void 0:D.call(t,V)})}catch(D){throw I(()=>a.analytics.onSignOrderError(D)),I(()=>{var J;return(J=t==null?void 0:t.onSignOrderError)==null?void 0:J.call(t,k(D))}),D}v(d.SUBMITTING);const Z=await L.submitOrder(G.order,V);return v(d.SUCCESS,{orderId:Z.id.toString()}),I(()=>o(Z)),I(()=>i()),I(()=>{var D;return(D=t==null?void 0:t.onOrderCreated)==null?void 0:D.call(t,Z)}),Z}catch(w){const N=S.phase,F=k(w),M=a.isTxRejected(w);throw C(M?d.REJECTED:d.FAILED,{error:F,parsedError:ee(w)}),N===d.WRAPPING?I(()=>a.analytics.onWrapError(w)):N===d.APPROVING&&I(()=>a.analytics.onApproveError(w)),I(M?t==null?void 0:t.onSubmitOrderRejected:()=>{var G;return(G=t==null?void 0:t.onSubmitOrderFailed)==null?void 0:G.call(t,ee(w))}),F}},ht=()=>{const{inputToken:e,outputToken:r,wrappedNativeToken:n,chainId:t,isSupportedChain:o,callbacks:i,account:s,walletInteractions:c}=b(),{data:u}=Q(),E=ke(),y=Ze(),g=j(),P=z();return l.useCallback(()=>{Et({account:s,chainId:t,isSupportedChain:o,inputToken:e,outputToken:r,wrappedNativeToken:n,form:g,client:u,walletInteractions:c,callbacks:i,addNewOrder:E,refetchActiveOrders:y,getCurrentExecution:()=>P.getState().state.currentExecution,beginExecution:P.getState().beginExecution,replaceExecution:P.getState().replaceExecution}).catch(()=>{})},[s,E,i,t,u,g,e,o,r,n,y,P,c])},It=()=>{const e=R(n=>n.state.currentExecution),r=R(n=>n.returnToOrderForm);return l.useMemo(()=>({...e,returnToOrderForm:r}),[e,r])},At=()=>{const e=It(),{inputToken:r,outputToken:n,chainId:t,isSupportedChain:o,module:i,overrides:s}=b(),{data:c,isLoading:u}=Q(),E=ht(),y=R(L=>L.startNewOrder),g=l.useCallback(()=>E(),[E]),P=l.useCallback(()=>y(me({module:i,overrides:s})),[i,s,y]),h=we(e.phase),f=Re(e.phase),A=U(e.phase);return l.useMemo(()=>({phase:e.phase,status:h,error:e.parsedError,currentStep:f,currentStepIndex:e.stepIndex,approvalTxHash:e.approveTxHash,wrapTxHash:e.wrapTxHash,totalSteps:e.totalSteps,executionSteps:e.pendingSteps,inputToken:e.inputToken??r,outputToken:e.outputToken??n,chainId:e.chainId??t,submitOrder:g,startNewOrder:P,returnToOrderForm:e.returnToOrderForm,isExecuting:A,isSuccess:e.phase===d.SUCCESS,isFailed:e.phase===d.FAILED,isRejected:e.phase===d.REJECTED,isPreparingOrder:e.phase===d.PREPARING||o&&u&&!c,canDismiss:!A}),[c,f,r,n,t,u,A,o,P,g,h,e])},Ct=()=>{const{inputToken:e,outputToken:r,wrappedNativeToken:n,inputBalanceRaw:t,noLiquidity:o,inputAmountUi:i,marketPriceLoading:s,isSupportedChain:c}=b(),u=j(),{data:E,isLoading:y}=Q(),g=R(p=>p.state.currentExecution.phase),P=U(g),h=!!(e&&a.isNativeAddress(e.address)&&(!n||a.isNativeAddress(n.address))),f=s||!u.isReady||t===void 0,A=P||c&&y&&!E||!!(e&&r&&i&&f),L=!!(!u.canSubmit||P||!c||!E||o||A||!e||!r||h);return l.useMemo(()=>({disabled:L,loading:A}),[L,A])},yt=()=>{const{inputToken:e,outputToken:r,callbacks:n}=b(),t=R(s=>s.updateState),{trades:o}=j(),i=l.useCallback(s=>{t({tradeCount:s}),I(()=>{var c;return(c=n==null?void 0:n.onTradeCountChange)==null?void 0:c.call(n,s)})},[n,t]);return l.useMemo(()=>({totalTrades:o.totalTrades,maxTrades:o.maxTrades,inputAmountPerTrade:o.inputAmountPerTrade,minOutputAmountPerTrade:o.minOutputAmountPerTrade,triggerOutputAmountPerTrade:o.triggerOutputAmountPerTrade,onChange:i,error:o.error,inputToken:e,outputToken:r}),[e,i,r,o])},vt=()=>{const{marketPriceLoading:e,inputToken:r,outputToken:n,callbacks:t}=b(),{marketPrice:o,trades:i,triggerPrice:s,isInverted:c}=j(),u=R(P=>P.updateState),E=l.useCallback(P=>{u({triggerPriceUi:P,triggerPricePercent:null}),I(()=>{var h;return(h=t==null?void 0:t.onTriggerPriceChange)==null?void 0:h.call(t,P||"")}),I(()=>{var h;return(h=t==null?void 0:t.onTriggerPricePercentChange)==null?void 0:h.call(t,"")})},[t,u]),y=l.useCallback(P=>{u({triggerPriceUi:void 0,triggerPricePercent:P}),I(()=>{var h;return(h=t==null?void 0:t.onTriggerPriceChange)==null?void 0:h.call(t,"")}),I(()=>{var h;return(h=t==null?void 0:t.onTriggerPricePercentChange)==null?void 0:h.call(t,P||"")})},[t,u]),g=l.useCallback(()=>{u({triggerPricePercent:void 0,triggerPriceUi:void 0})},[u]);return l.useMemo(()=>({price:s.display,canonicalPriceRaw:s.raw,outputAmountPerTrade:i.triggerOutputAmountPerTrade,error:s.error,onInputChange:E,onPercentageChange:y,percentage:s.percentage,onReset:g,inputToken:r,outputToken:n,displayInputToken:c?n:r,displayOutputToken:c?r:n,isLoading:!!(e||!o.raw),isTypedValue:s.isTypedValue}),[r,c,o.raw,e,E,y,g,n,i.triggerOutputAmountPerTrade,s])};a.setUIVersion(he.version),Object.defineProperty(m,"DISCLAIMER_URL",{enumerable:!0,get:()=>a.DISCLAIMER_URL}),Object.defineProperty(m,"InputErrors",{enumerable:!0,get:()=>a.InputErrors}),Object.defineProperty(m,"Module",{enumerable:!0,get:()=>a.Module}),Object.defineProperty(m,"ORBS_LOGO",{enumerable:!0,get:()=>a.ORBS_LOGO}),Object.defineProperty(m,"ORBS_SLTP_FAQ_URL",{enumerable:!0,get:()=>a.ORBS_SLTP_FAQ_URL}),Object.defineProperty(m,"ORBS_TWAP_FAQ_URL",{enumerable:!0,get:()=>a.ORBS_TWAP_FAQ_URL}),Object.defineProperty(m,"ORBS_WEBSITE_URL",{enumerable:!0,get:()=>a.ORBS_WEBSITE_URL}),Object.defineProperty(m,"OrderFilter",{enumerable:!0,get:()=>a.OrderFilter}),Object.defineProperty(m,"OrderStatus",{enumerable:!0,get:()=>a.OrderStatus}),Object.defineProperty(m,"OrderType",{enumerable:!0,get:()=>a.OrderType}),Object.defineProperty(m,"Partners",{enumerable:!0,get:()=>a.Partners}),Object.defineProperty(m,"SPOT_VERSION",{enumerable:!0,get:()=>a.SPOT_VERSION}),Object.defineProperty(m,"TimeUnit",{enumerable:!0,get:()=>a.TimeUnit}),Object.defineProperty(m,"calculateOrderForm",{enumerable:!0,get:()=>a.calculateOrderForm}),Object.defineProperty(m,"createClient",{enumerable:!0,get:()=>a.createClient}),Object.defineProperty(m,"eqIgnoreCase",{enumerable:!0,get:()=>a.eqIgnoreCase}),Object.defineProperty(m,"getOrderExecutionRate",{enumerable:!0,get:()=>a.getOrderExecutionRate}),Object.defineProperty(m,"getOrderFillDelayMillis",{enumerable:!0,get:()=>a.getOrderFillDelayMillis}),Object.defineProperty(m,"getOrderLimitPriceRate",{enumerable:!0,get:()=>a.getOrderLimitPriceRate}),Object.defineProperty(m,"getPartnerChains",{enumerable:!0,get:()=>a.getPartnerChains}),Object.defineProperty(m,"getPartners",{enumerable:!0,get:()=>a.getPartners}),Object.defineProperty(m,"getTriggerPriceRate",{enumerable:!0,get:()=>a.getTriggerPriceRate}),Object.defineProperty(m,"getTwapConfig",{enumerable:!0,get:()=>a.getTwapConfig}),Object.defineProperty(m,"invertPriceInput",{enumerable:!0,get:()=>a.invertPriceInput}),Object.defineProperty(m,"isNativeAddress",{enumerable:!0,get:()=>a.isNativeAddress}),Object.defineProperty(m,"isTxRejected",{enumerable:!0,get:()=>a.isTxRejected}),Object.defineProperty(m,"toAmountRaw",{enumerable:!0,get:()=>a.toAmountRaw}),Object.defineProperty(m,"toAmountUI",{enumerable:!0,get:()=>a.toAmountUI}),m.Disclaimer=Y,m.ExecutionPhase=d,m.ExecutionStatus=_,m.SpotProvider=Qe,m.Steps=H,m.useAmountUi=Ye,m.useCancelOrder=it,m.useClient=Q,m.useDisclaimer=ot,m.useDuration=st,m.useExecution=At,m.useFillDelay=at,m.useHistoryOrder=ut,m.useInputErrors=dt,m.useLimitPrice=lt,m.useOrderForm=j,m.useOrders=Xe,m.useOutputAmount=mt,m.usePriceDisplay=gt,m.useSubmitButton=Ct,m.useTrades=yt,m.useTriggerPrice=vt,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": "2.1.8",
3
+ "version": "2.1.10",
4
4
  "description": "Spot React Components - React components for Spot SDK",
5
5
  "type": "module",
6
6
  "main": "./dist/spot-react.umd.cjs",