@galacticcouncil/sdk 2.0.0 → 2.0.1-beta.0
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/build/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use strict";var yt=Object.defineProperty;var is=Object.getOwnPropertyDescriptor;var ns=Object.getOwnPropertyNames;var os=Object.prototype.hasOwnProperty;var as=(u,e)=>{for(var t in e)yt(u,t,{get:e[t],enumerable:!0})},ls=(u,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ns(e))!os.call(u,r)&&r!==t&&yt(u,r,{get:()=>e[r],enumerable:!(s=is(e,r))||s.enumerable});return u};var us=u=>ls(yt({},"__esModule",{value:!0}),u);var Bs={};as(Bs,{AssetClient:()=>Le,AssetNotFound:()=>Nt,BASILISK_PARACHAIN_ID:()=>ds,BalanceClient:()=>Me,BigNumber:()=>fe,CachingPoolService:()=>Pt,DECIMAL_PLACES:()=>qt,DENOMINATOR:()=>rt,HYDRADX_OMNIPOOL_ADDRESS:()=>$e,HYDRADX_PARACHAIN_ID:()=>gs,HYDRADX_SS58_PREFIX:()=>Ee,INFINITY:()=>ms,LbpMath:()=>ue,LbpPool:()=>ve,ONE:()=>ie,OmniMath:()=>z,OmniPool:()=>Ie,PoolConfigNotFound:()=>At,PoolError:()=>_e,PoolFactory:()=>Ue,PoolNotFound:()=>Je,PoolService:()=>Ce,PoolType:()=>se,ProviderConfigNotFound:()=>_t,RUNTIME_DECIMALS:()=>Re,RouteNotFound:()=>De,Router:()=>Fe,SYSTEM_ASSET_DECIMALS:()=>hs,SYSTEM_ASSET_ID:()=>Oe,StableMath:()=>ee,StableSwap:()=>Ae,StorageConfigNotFound:()=>Tt,SubscriptionNotSupported:()=>Ft,TRADEABLE_DEFAULT:()=>st,TradeRouter:()=>Qe,TradeType:()=>vt,XykMath:()=>ye,XykPool:()=>Ne,ZERO:()=>E,bnum:()=>I,buildRoute:()=>ut,calculateBuyFee:()=>Dt,calculateDiffToAvg:()=>ws,calculateDiffToRef:()=>ze,calculateSellFee:()=>Mt,findNestedKey:()=>It,findNestedObj:()=>fs,scale:()=>Y});module.exports=us(Bs);var Ze=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var cs=5,We=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new Ze,l=[];for(l.push([t,""]),i.enqueue(l);i.size()>0;){let c=i.dequeue();if(c==null||c.length>cs)return r;let h=c[c.length-1];(s===null||h[0]===s)&&r.push(c),e.get(h[0])?.forEach(w=>{if(this.isNotVisited(w,c)){let B=[...c];B.push(w),i.enqueue(B)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,l]of t){let c=parseInt(i),h=parseInt(l);s.get(c)?.push([h,r])}return s}};function xt(u){let e={};for(let t of u){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let i=0;i<s;i++){if(r==i)continue;let l=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(l)}}}return e}var Ye=class{getProposals(e,t,s){let r=xt(s),i=Object.keys(r),l=i.map(w=>r[w]).flat(),c=new We,h=c.buildAndPopulateGraph(i,l),y=c.findPaths(h,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let l=s[i],c=s[i+1];if(c==null)break;r.push(this.toEdge(l,c))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ps=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ot=Math.ceil,ae=Math.floor,te="[BigNumber Error] ",Ct=te+"Number primitive has more than 15 significant digits: ",he=1e14,T=14,wt=9007199254740991,Bt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Be=1e7,W=1e9;function Gt(u){var e,t,s,r=O.prototype={constructor:O,toString:null,valueOf:null},i=new O(1),l=20,c=4,h=-7,y=21,w=-1e7,B=1e7,N=!1,M=1,_=0,D={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},G="0123456789abcdefghijklmnopqrstuvwxyz",V=!0;function O(n,o){var a,P,m,d,S,p,g,b,f=this;if(!(f instanceof O))return new O(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<w?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!ps.test(b=String(n)))return s(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(q(o,2,G.length,"Base"),o==10&&V)return f=new O(n),j(f,l+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return s(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,O.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Ct+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(a=G.slice(0,o),d=S=0,g=b.length;S<g;S++)if(a.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=g;continue}}else if(!m&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){m=!0,S=-1,d=0;continue}return s(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(g=b.length;b.charCodeAt(--g)===48;);if(b=b.slice(S,++g)){if(g-=S,p&&O.DEBUG&&g>15&&(n>wt||n!==ae(n)))throw Error(Ct+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<w)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%T,d<0&&(S+=T),S<g){for(S&&f.c.push(+b.slice(0,S)),g-=T;S<g;)f.c.push(+b.slice(S,S+=T));S=T-(b=b.slice(S)).length}else S-=g;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}O.clone=Gt,O.ROUND_UP=0,O.ROUND_DOWN=1,O.ROUND_CEIL=2,O.ROUND_FLOOR=3,O.ROUND_HALF_UP=4,O.ROUND_HALF_DOWN=5,O.ROUND_HALF_EVEN=6,O.ROUND_HALF_CEIL=7,O.ROUND_HALF_FLOOR=8,O.EUCLID=9,O.config=O.set=function(n){var o,a;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(a=n[o],q(a,0,W,o),l=a),n.hasOwnProperty(o="ROUNDING_MODE")&&(a=n[o],q(a,0,8,o),c=a),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(a=n[o],a&&a.pop?(q(a[0],-W,0,o),q(a[1],0,W,o),h=a[0],y=a[1]):(q(a,-W,W,o),h=-(y=a<0?-a:a))),n.hasOwnProperty(o="RANGE"))if(a=n[o],a&&a.pop)q(a[0],-W,-1,o),q(a[1],1,W,o),w=a[0],B=a[1];else if(q(a,-W,W,o),a)w=-(B=a<0?-a:a);else throw Error(te+o+" cannot be zero: "+a);if(n.hasOwnProperty(o="CRYPTO"))if(a=n[o],a===!!a)if(a)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))N=a;else throw N=!a,Error(te+"crypto unavailable");else N=a;else throw Error(te+o+" not true or false: "+a);if(n.hasOwnProperty(o="MODULO_MODE")&&(a=n[o],q(a,0,9,o),M=a),n.hasOwnProperty(o="POW_PRECISION")&&(a=n[o],q(a,0,W,o),_=a),n.hasOwnProperty(o="FORMAT"))if(a=n[o],typeof a=="object")D=a;else throw Error(te+o+" not an object: "+a);if(n.hasOwnProperty(o="ALPHABET"))if(a=n[o],typeof a=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(a))V=a.slice(0,10)=="0123456789",G=a;else throw Error(te+o+" invalid: "+a)}else throw Error(te+"Object expected: "+n);return{DECIMAL_PLACES:l,ROUNDING_MODE:c,EXPONENTIAL_AT:[h,y],RANGE:[w,B],CRYPTO:N,MODULO_MODE:M,POW_PRECISION:_,FORMAT:D,ALPHABET:G}},O.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!O.DEBUG)return!0;var o,a,P=n.c,m=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&m>=-W&&m<=W&&m===ae(m)){if(P[0]===0){if(m===0&&P.length===1)return!0;break e}if(o=(m+1)%T,o<1&&(o+=T),String(P[0]).length==o){for(o=0;o<P.length;o++)if(a=P[o],a<0||a>=he||a!==ae(a))break e;if(a!==0)return!0}}}else if(P===null&&m===null&&(d===null||d===1||d===-1))return!0;throw Error(te+"Invalid BigNumber: "+n)},O.maximum=O.max=function(){return we(arguments,-1)},O.minimum=O.min=function(){return we(arguments,1)},O.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ae(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(a){var P,m,d,S,p,g=0,b=[],f=new O(i);if(a==null?a=l:q(a,0,W),S=Ot(a/T),N)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));g<S;)p=P[g]*131072+(P[g+1]>>>11),p>=9e15?(m=crypto.getRandomValues(new Uint32Array(2)),P[g]=m[0],P[g+1]=m[1]):(b.push(p%1e14),g+=2);g=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);g<S;)p=(P[g]&31)*281474976710656+P[g+1]*1099511627776+P[g+2]*4294967296+P[g+3]*16777216+(P[g+4]<<16)+(P[g+5]<<8)+P[g+6],p>=9e15?crypto.randomBytes(7).copy(P,g):(b.push(p%1e14),g+=7);g=S/7}else throw N=!1,Error(te+"crypto unavailable");if(!N)for(;g<S;)p=o(),p<9e15&&(b[g++]=p%1e14);for(S=b[--g],a%=T,S&&a&&(p=Bt[T-a],b[g]=ae(S/p)*p);b[g]===0;b.pop(),g--);if(g<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=T);for(g=1,p=b[0];p>=10;p/=10,g++);g<T&&(d-=T-g)}return f.e=d,f.c=b,f}}(),O.sum=function(){for(var n=1,o=arguments,a=new O(o[0]);n<o.length;)a=a.plus(o[n++]);return a},t=function(){var n="0123456789";function o(a,P,m,d){for(var S,p=[0],g,b=0,f=a.length;b<f;){for(g=p.length;g--;p[g]*=P);for(p[0]+=d.indexOf(a.charAt(b++)),S=0;S<p.length;S++)p[S]>m-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/m|0,p[S]%=m)}return p.reverse()}return function(a,P,m,d,S){var p,g,b,f,x,v,A,k,H=a.indexOf("."),X=l,R=c;for(H>=0&&(f=_,_=0,a=a.replace(".",""),k=new O(P),v=k.pow(a.length-H),_=f,k.c=o(xe(oe(v.c),v.e,"0"),10,m,n),k.e=k.c.length),A=o(a,P,m,S?(p=G,n):(p=n,G)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(H<0?--b:(v.c=A,v.e=b,v.s=d,v=e(v,k,X,R,m),A=v.c,x=v.r,b=v.e),g=b+X+1,H=A[g],f=m/2,x=x||g<0||A[g+1]!=null,x=R<4?(H!=null||x)&&(R==0||R==(v.s<0?3:2)):H>f||H==f&&(R==4||x||R==6&&A[g-1]&1||R==(v.s<0?8:7)),g<1||!A[0])a=x?xe(p.charAt(1),-X,p.charAt(0)):p.charAt(0);else{if(A.length=g,x)for(--m;++A[--g]>m;)A[g]=0,g||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(H=0,a="";H<=f;a+=p.charAt(A[H++]));a=xe(a,b,p.charAt(0))}return a}}(),e=function(){function n(P,m,d){var S,p,g,b,f=0,x=P.length,v=m%Be,A=m/Be|0;for(P=P.slice();x--;)g=P[x]%Be,b=P[x]/Be|0,S=A*g+b*v,p=v*g+S%Be*Be+f,f=(p/d|0)+(S/Be|0)+A*b,P[x]=p%d;return f&&(P=[f].concat(P)),P}function o(P,m,d,S){var p,g;if(d!=S)g=d>S?1:-1;else for(p=g=0;p<d;p++)if(P[p]!=m[p]){g=P[p]>m[p]?1:-1;break}return g}function a(P,m,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<m[d]?1:0,P[d]=p*S+P[d]-m[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,m,d,S,p){var g,b,f,x,v,A,k,H,X,R,C,K,Ve,bt,St,de,Xe,ne=P.s==m.s?1:-1,Z=P.c,U=m.c;if(!Z||!Z[0]||!U||!U[0])return new O(!P.s||!m.s||(Z?U&&Z[0]==U[0]:!U)?NaN:Z&&Z[0]==0||!U?ne*0:ne/0);for(H=new O(ne),X=H.c=[],b=P.e-m.e,ne=d+b+1,p||(p=he,b=le(P.e/T)-le(m.e/T),ne=ne/T|0),f=0;U[f]==(Z[f]||0);f++);if(U[f]>(Z[f]||0)&&b--,ne<0)X.push(1),x=!0;else{for(bt=Z.length,de=U.length,f=0,ne+=2,v=ae(p/(U[0]+1)),v>1&&(U=n(U,v,p),Z=n(Z,v,p),de=U.length,bt=Z.length),Ve=de,R=Z.slice(0,de),C=R.length;C<de;R[C++]=0);Xe=U.slice(),Xe=[0].concat(Xe),St=U[0],U[1]>=p/2&&St++;do{if(v=0,g=o(U,R,de,C),g<0){if(K=R[0],de!=C&&(K=K*p+(R[1]||0)),v=ae(K/St),v>1)for(v>=p&&(v=p-1),A=n(U,v,p),k=A.length,C=R.length;o(A,R,k,C)==1;)v--,a(A,de<k?Xe:U,k,p),k=A.length,g=1;else v==0&&(g=v=1),A=U.slice(),k=A.length;if(k<C&&(A=[0].concat(A)),a(R,A,C,p),C=R.length,g==-1)for(;o(U,R,de,C)<1;)v++,a(R,de<C?Xe:U,C,p),C=R.length}else g===0&&(v++,R=[0]);X[f++]=v,R[0]?R[C++]=Z[Ve]||0:(R=[Z[Ve]],C=1)}while((Ve++<bt||R[0]!=null)&&ne--);x=R[0]!=null,X[0]||X.splice(0,1)}if(p==he){for(f=1,ne=X[0];ne>=10;ne/=10,f++);j(H,d+(H.e=f+b*T-1)+1,S,x)}else H.e=b,H.r=+x;return H}}();function pe(n,o,a,P){var m,d,S,p,g;if(a==null?a=c:q(a,0,8),!n.c)return n.toString();if(m=n.c[0],S=n.e,o==null)g=oe(n.c),g=P==1||P==2&&(S<=h||S>=y)?tt(g,S):xe(g,S,"0");else if(n=j(new O(n),o,a),d=n.e,g=oe(n.c),p=g.length,P==1||P==2&&(o<=d||d<=h)){for(;p<o;g+="0",p++);g=tt(g,d)}else if(o-=S,g=xe(g,d,"0"),d+1>p){if(--o>0)for(g+=".";o--;g+="0");}else if(o+=d-p,o>0)for(d+1==p&&(g+=".");o--;g+="0");return n.s<0&&m?"-"+g:g}function we(n,o){for(var a,P,m=1,d=new O(n[0]);m<n.length;m++)P=new O(n[m]),(!P.s||(a=Te(d,P))===o||a===0&&d.s===o)&&(d=P);return d}function me(n,o,a){for(var P=1,m=o.length;!o[--m];o.pop());for(m=o[0];m>=10;m/=10,P++);return(a=P+a*T-1)>B?n.c=n.e=null:a<w?n.c=[n.e=0]:(n.e=a,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,a=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,m=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,g){var b,f=p?S:S.replace(m,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(x,v,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!g||g==b?v:x}),g&&(b=g,f=f.replace(o,"$1").replace(a,"0.$1")),S!=f))return new O(f,b);if(O.DEBUG)throw Error(te+"Not a"+(g?" base "+g:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function j(n,o,a,P){var m,d,S,p,g,b,f,x=n.c,v=Bt;if(x){e:{for(m=1,p=x[0];p>=10;p/=10,m++);if(d=o-m,d<0)d+=T,S=o,g=x[b=0],f=ae(g/v[m-S-1]%10);else if(b=Ot((d+1)/T),b>=x.length)if(P){for(;x.length<=b;x.push(0));g=f=0,m=1,d%=T,S=d-T+1}else break e;else{for(g=p=x[b],m=1;p>=10;p/=10,m++);d%=T,S=d-T+m,f=S<0?0:ae(g/v[m-S-1]%10)}if(P=P||o<0||x[b+1]!=null||(S<0?g:g%v[m-S-1]),P=a<4?(f||P)&&(a==0||a==(n.s<0?3:2)):f>5||f==5&&(a==4||P||a==6&&(d>0?S>0?g/v[m-S]:0:x[b-1])%10&1||a==(n.s<0?8:7)),o<1||!x[0])return x.length=0,P?(o-=n.e+1,x[0]=v[(T-o%T)%T],n.e=-o||0):x[0]=n.e=0,n;if(d==0?(x.length=b,p=1,b--):(x.length=b+1,p=v[T-d],x[b]=S>0?ae(g/v[m-S]%v[S])*p:0),P)for(;;)if(b==0){for(d=1,S=x[0];S>=10;S/=10,d++);for(S=x[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,x[0]==he&&(x[0]=1));break}else{if(x[b]+=p,x[b]!=he)break;x[b--]=0,p=1}for(d=x.length;x[--d]===0;x.pop());}n.e>B?n.c=n.e=null:n.e<w&&(n.c=[n.e=0])}return n}function L(n){var o,a=n.e;return a===null?n.toString():(o=oe(n.c),o=a<=h||a>=y?tt(o,a):xe(o,a,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new O(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return Te(this,new O(n,o))},r.decimalPlaces=r.dp=function(n,o){var a,P,m,d=this;if(n!=null)return q(n,0,W),o==null?o=c:q(o,0,8),j(new O(d),n+d.e+1,o);if(!(a=d.c))return null;if(P=((m=a.length-1)-le(this.e/T))*T,m=a[m])for(;m%10==0;m/=10,P--);return P<0&&(P=0),P},r.dividedBy=r.div=function(n,o){return e(this,new O(n,o),l,c)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new O(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var a,P,m,d,S,p,g,b,f,x=this;if(n=new O(n),n.c&&!n.isInteger())throw Error(te+"Exponent not an integer: "+L(n));if(o!=null&&(o=new O(o)),p=n.e>14,!x.c||!x.c[0]||x.c[0]==1&&!x.e&&x.c.length==1||!n.c||!n.c[0])return f=new O(Math.pow(+L(x),p?n.s*(2-et(n)):+L(n))),o?f.mod(o):f;if(g=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new O(NaN);P=!g&&x.isInteger()&&o.isInteger(),P&&(x=x.mod(o))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||p&&x.c[1]>=24e7:x.c[0]<8e13||p&&x.c[0]<=9999975e7)))return d=x.s<0&&et(n)?-0:0,x.e>-1&&(d=1/d),new O(g?1/d:d);_&&(d=Ot(_/T+2))}for(p?(a=new O(.5),g&&(n.s=1),b=et(n)):(m=Math.abs(+L(n)),b=m%2),f=new O(i);;){if(b){if(f=f.times(x),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(m){if(m=ae(m/2),m===0)break;b=m%2}else if(n=n.times(a),j(n,n.e+1,1),n.e>14)b=et(n);else{if(m=+L(n),m===0)break;b=m%2}x=x.times(x),d?x.c&&x.c.length>d&&(x.c.length=d):P&&(x=x.mod(o))}return P?f:(g&&(f=i.div(f)),o?f.mod(o):d?j(f,_,c,S):f)},r.integerValue=function(n){var o=new O(this);return n==null?n=c:q(n,0,8),j(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return Te(this,new O(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return Te(this,new O(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=Te(this,new O(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&le(this.e/T)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return Te(this,new O(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=Te(this,new O(n,o)))===-1||o===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(n,o){var a,P,m,d,S=this,p=S.s;if(n=new O(n,o),o=n.s,!p||!o)return new O(NaN);if(p!=o)return n.s=-o,S.plus(n);var g=S.e/T,b=n.e/T,f=S.c,x=n.c;if(!g||!b){if(!f||!x)return f?(n.s=-o,n):new O(x?S:NaN);if(!f[0]||!x[0])return x[0]?(n.s=-o,n):new O(f[0]?S:c==3?-0:0)}if(g=le(g),b=le(b),f=f.slice(),p=g-b){for((d=p<0)?(p=-p,m=f):(b=g,m=x),m.reverse(),o=p;o--;m.push(0));m.reverse()}else for(P=(d=(p=f.length)<(o=x.length))?p:o,p=o=0;o<P;o++)if(f[o]!=x[o]){d=f[o]<x[o];break}if(d&&(m=f,f=x,x=m,n.s=-n.s),o=(P=x.length)-(a=f.length),o>0)for(;o--;f[a++]=0);for(o=he-1;P>p;){if(f[--P]<x[P]){for(a=P;a&&!f[--a];f[a]=o);--f[a],f[P]+=he}f[P]-=x[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?me(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var a,P,m=this;return n=new O(n,o),!m.c||!n.s||n.c&&!n.c[0]?new O(NaN):!n.c||m.c&&!m.c[0]?new O(m):(M==9?(P=n.s,n.s=1,a=e(m,n,0,3),n.s=P,a.s*=P):a=e(m,n,0,M),n=m.minus(a.times(n)),!n.c[0]&&M==1&&(n.s=m.s),n)},r.multipliedBy=r.times=function(n,o){var a,P,m,d,S,p,g,b,f,x,v,A,k,H,X,R=this,C=R.c,K=(n=new O(n,o)).c;if(!C||!K||!C[0]||!K[0])return!R.s||!n.s||C&&!C[0]&&!K||K&&!K[0]&&!C?n.c=n.e=n.s=null:(n.s*=R.s,!C||!K?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=le(R.e/T)+le(n.e/T),n.s*=R.s,g=C.length,x=K.length,g<x&&(k=C,C=K,K=k,m=g,g=x,x=m),m=g+x,k=[];m--;k.push(0));for(H=he,X=Be,m=x;--m>=0;){for(a=0,v=K[m]%X,A=K[m]/X|0,S=g,d=m+S;d>m;)b=C[--S]%X,f=C[S]/X|0,p=A*b+f*v,b=v*b+p%X*X+k[d]+a,a=(b/H|0)+(p/X|0)+A*f,k[d--]=b%H;k[d]=a}return a?++P:k.splice(0,1),me(n,k,P)},r.negated=function(){var n=new O(this);return n.s=-n.s||null,n},r.plus=function(n,o){var a,P=this,m=P.s;if(n=new O(n,o),o=n.s,!m||!o)return new O(NaN);if(m!=o)return n.s=-o,P.minus(n);var d=P.e/T,S=n.e/T,p=P.c,g=n.c;if(!d||!S){if(!p||!g)return new O(m/0);if(!p[0]||!g[0])return g[0]?n:new O(p[0]?P:m*0)}if(d=le(d),S=le(S),p=p.slice(),m=d-S){for(m>0?(S=d,a=g):(m=-m,a=p),a.reverse();m--;a.push(0));a.reverse()}for(m=p.length,o=g.length,m-o<0&&(a=g,g=p,p=a,o=m),m=0;o;)m=(p[--o]=p[o]+g[o]+m)/he|0,p[o]=he===p[o]?0:p[o]%he;return m&&(p=[m].concat(p),++S),me(n,p,S)},r.precision=r.sd=function(n,o){var a,P,m,d=this;if(n!=null&&n!==!!n)return q(n,1,W),o==null?o=c:q(o,0,8),j(new O(d),n,o);if(!(a=d.c))return null;if(m=a.length-1,P=m*T+1,m=a[m]){for(;m%10==0;m/=10,P--);for(m=a[0];m>=10;m/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return q(n,-wt,wt),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,a,P,m,d=this,S=d.c,p=d.s,g=d.e,b=l+4,f=new O("0.5");if(p!==1||!S||!S[0])return new O(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+L(d)),p==0||p==1/0?(o=oe(S),(o.length+g)%2==0&&(o+="0"),p=Math.sqrt(+o),g=le((g+1)/2)-(g<0||g%2),p==1/0?o="5e"+g:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+g),a=new O(o)):a=new O(p+""),a.c[0]){for(g=a.e,p=g+b,p<3&&(p=0);;)if(m=a,a=f.times(m.plus(e(d,m,b,1))),oe(m.c).slice(0,p)===(o=oe(a.c)).slice(0,p))if(a.e<g&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(j(m,m.e+l+2,0),m.times(m).eq(d))){a=m;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(j(a,a.e+l+2,1),n=!a.times(a).eq(d));break}}return j(a,a.e+l+1,c,n)},r.toExponential=function(n,o){return n!=null&&(q(n,0,W),n++),pe(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(q(n,0,W),n=n+this.e+1),pe(this,n,o)},r.toFormat=function(n,o,a){var P,m=this;if(a==null)n!=null&&o&&typeof o=="object"?(a=o,o=null):n&&typeof n=="object"?(a=n,n=o=null):a=D;else if(typeof a!="object")throw Error(te+"Argument not an object: "+a);if(P=m.toFixed(n,o),m.c){var d,S=P.split("."),p=+a.groupSize,g=+a.secondaryGroupSize,b=a.groupSeparator||"",f=S[0],x=S[1],v=m.s<0,A=v?f.slice(1):f,k=A.length;if(g&&(d=p,p=g,g=d,k-=d),p>0&&k>0){for(d=k%p||p,f=A.substr(0,d);d<k;d+=p)f+=b+A.substr(d,p);g>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=x?f+(a.decimalSeparator||"")+((g=+a.fractionGroupSize)?x.replace(new RegExp("\\d{"+g+"}\\B","g"),"$&"+(a.fractionGroupSeparator||"")):x):f}return(a.prefix||"")+P+(a.suffix||"")},r.toFraction=function(n){var o,a,P,m,d,S,p,g,b,f,x,v,A=this,k=A.c;if(n!=null&&(p=new O(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(te+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+L(p));if(!k)return new O(A);for(o=new O(i),b=a=new O(i),P=g=new O(i),v=oe(k),d=o.e=v.length-A.e-1,o.c[0]=Bt[(S=d%T)<0?T+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new O(v),g.c[0]=0;f=e(p,o,0,1),m=a.plus(f.times(P)),m.comparedTo(n)!=1;)a=P,P=m,b=g.plus(f.times(m=b)),g=m,o=p.minus(f.times(m=o)),p=m;return m=e(n.minus(a),P,0,1),g=g.plus(m.times(b)),a=a.plus(m.times(P)),g.s=b.s=A.s,d=d*2,x=e(b,P,d,c).minus(A).abs().comparedTo(e(g,a,d,c).minus(A).abs())<1?[b,P]:[g,a],B=S,x},r.toNumber=function(){return+L(this)},r.toPrecision=function(n,o){return n!=null&&q(n,1,W),pe(this,n,o,2)},r.toString=function(n){var o,a=this,P=a.s,m=a.e;return m===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=m<=h||m>=y?tt(oe(a.c),m):xe(oe(a.c),m,"0"):n===10&&V?(a=j(new O(a),l+m+1,c),o=xe(oe(a.c),a.e,"0")):(q(n,2,G.length,"Base"),o=t(xe(oe(a.c),m,"0"),10,n,P,!0)),P<0&&a.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return L(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,u!=null&&O.set(u),O}function le(u){var e=u|0;return u>0||u===e?e:e-1}function oe(u){for(var e,t,s=1,r=u.length,i=u[0]+"";s<r;){for(e=u[s++]+"",t=T-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function Te(u,e){var t,s,r=u.c,i=e.c,l=u.s,c=e.s,h=u.e,y=e.e;if(!l||!c)return null;if(t=r&&!r[0],s=i&&!i[0],t||s)return t?s?0:-c:l;if(l!=c)return l;if(t=l<0,s=h==y,!r||!i)return s?0:!r^t?1:-1;if(!s)return h>y^t?1:-1;for(c=(h=r.length)<(y=i.length)?h:y,l=0;l<c;l++)if(r[l]!=i[l])return r[l]>i[l]^t?1:-1;return h==y?0:h>y^t?1:-1}function q(u,e,t,s){if(u<e||u>t||u!==ae(u))throw Error(te+(s||"Argument")+(typeof u=="number"?u<e||u>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(u))}function et(u){var e=u.c.length-1;return le(u.e/T)==e&&u.c[e]%2!=0}function tt(u,e){return(u.length>1?u.charAt(0)+"."+u.slice(1):u)+(e<0?"e":"e+")+e}function xe(u,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);u=r+u}else if(s=u.length,++e>s){for(r=t,e-=s;--e;r+=t);u+=r}else e<s&&(u=u.slice(0,e)+"."+u.slice(e));return u}var fe=Gt();var qt=12;fe.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:qt});var E=I(0),ie=I(1),ms=I("Infinity");function Y(u,e){let t=new fe(e.toString()),s=new fe(10).pow(t);return u.times(s)}function I(u){return new fe(u.toString())}var se=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(se||{}),_e=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(_e||{}),vt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(vt||{});var Pe=require("@galacticcouncil/math-lbp"),ue=class{static getSpotPrice(e,t,s,r,i){return(0,Pe.get_spot_price)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return(0,Pe.calculate_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return(0,Pe.calculate_out_given_in)(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return(0,Pe.calculate_linear_weights)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,Pe.calculate_pool_trade_fee)(e,t,s)}};var Ht=require("@polkadot/util-crypto"),Ut=require("@polkadot/util"),Re=18,st=15,Oe="0",hs=12,gs=2034,Ee=63,ds=2090,rt=1e3,$e=(0,Ht.encodeAddress)((0,Ut.stringToU8a)("modlomnipool".padEnd(32,"\0")),Ee);function It(u,e){let t;return JSON.stringify(u,(s,r)=>(r&&r[e]&&(t=r),r)),t}function fs(u,e,t){let s;return JSON.stringify(u,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}var js=require("@polkadot/types/lookup");var Ks=require("@polkadot/api-base/types/consts");var Qs=require("@polkadot/api-base/types/errors");var Vs=require("@polkadot/api-base/types/events");var Zs=require("@polkadot/api-base/types/storage");var er=require("@polkadot/api-base/types/submittable");var tr=require("@polkadot/rpc-core/types/jsonrpc");var sr=require("@polkadot/api-base/types/calls");var cr=require("@polkadot/types/types/registry");var gr=require("@polkadot/types/lookup");var dr=require("@polkadot/api-base/types/consts");var fr=require("@polkadot/api-base/types/errors");var Pr=require("@polkadot/api-base/types/events");var br=require("@polkadot/api-base/types/storage");var Sr=require("@polkadot/api-base/types/submittable");var yr=require("@polkadot/rpc-core/types/jsonrpc");var xr=require("@polkadot/api-base/types/calls");var Tr=require("@polkadot/types/types/registry");var ke=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Le=class extends ke{SUPPORTED_TYPES=["StableSwap","Bond","Token","External"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getToken(e,t,s,r){if(e==Oe){let B=this.api.consts.balances.existentialDeposit;return{id:Oe,name:this.chainToken,symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:B.toString()}}let{name:i,assetType:l,isSufficient:c,existentialDeposit:h}=t,{symbol:y,decimals:w}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:y,decimals:w,icon:y,type:l.toHuman(),isSufficient:c?c.toHuman():!0,origin:this.parseLocation("parachain",r),existentialDeposit:h.toString()}}getBond(e,t,s,r){let[i,l]=r,{assetType:c,isSufficient:h,existentialDeposit:y}=t,{symbol:w,decimals:B}=this.getToken(i.toString(),t,s),N=l.toNumber(),M=new Intl.DateTimeFormat("en-GB"),_=[w,"Bond",M.format(N)].join(" ");return{id:e,name:_,symbol:w+"b",decimals:B,icon:w,type:c.toString(),isSufficient:h.toHuman(),existentialDeposit:y.toString()}}getShares(e,t,s,r){let{assets:i}=r,{name:l,symbol:c,assetType:h,isSufficient:y,existentialDeposit:w}=t,N=i.map(D=>D.toString()).map(D=>{let{symbol:G}=this.getToken(D,t,s);return[D,G]}),M=Object.fromEntries(N),_=Object.values(M);return{id:e,name:_.join(", "),symbol:c?.isSome?c.toHuman():l.toHuman(),decimals:18,icon:_.join("/"),type:h.toString(),isSufficient:y.toHuman(),existentialDeposit:w.toString(),meta:M}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),l=this.parseLocation("generalIndex",r),c=s?.find(h=>h.id===l?.toString());return c?{...i,decimals:c.decimals,name:c.name,symbol:c.symbol,icon:c.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:l}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:l.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e){let[t,s,r,i,l]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),c=this.getSupportedAssets(t),h=this.normalizeMetadata(c,l);return c.map(([{args:[y]},w])=>{let B=w.unwrap(),N=s.get(y.toString()),{assetType:M}=B;switch(M.toString()){case"Bond":let _=i.get(y.toString());return this.getBond(y.toString(),B,h,_);case"StableSwap":let D=r.get(y.toString());return this.getShares(y.toString(),B,h,D);case"External":return this.getExternal(y.toString(),B,e,N);default:return this.getToken(y.toString(),B,h,N)}}).filter(y=>this.isValidAsset(y))}isValidAsset(e){return!!e.symbol&&!!e.decimals}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let s=It(t.toJSON(),e);return s&&s[e]}else return}};var Me=class extends ke{constructor(e){super(e)}async getBalance(e,t){return t===Oe?await this.getSystemBalance(e):await this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeBalance(e,t,s){let r=t.filter(i=>i!==Oe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach(({free:l,reserved:c,frozen:h},y)=>{let w=this.calculateFreeBalance({free:l,feeFrozen:c,frozen:h}),B=r[y][1];s(B,w)})})}async subscribeTokenBalance(e,t,s){let r=t.filter(i=>i!==Oe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach((l,c)=>{let h=this.calculateFreeBalance(l),y=r[c][1];s(y,h)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(Oe,this.calculateFreeBalance(s)))}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,l=new fe(t),c=new fe(s||i),h=new fe(r||0),y=c.gt(h)?c:h;return l.minus(y)}};var be=class extends Me{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async s=>{let r=[await this.subscribePoolChange(s),await this.subscribeTokensPoolBalance(s),await this.subscribeSystemPoolBalance(s)];if(this.hasShareAsset(s)){let i=await this.subscribeSharePoolBalance(s);r.push(i)}return this.subscribeLog(s),r});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,s)=>t.id!==s))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance($e,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(s,r){let i=e.tokens.findIndex(l=>l.id==s);i>=0&&t(e,s)&&(e.tokens[i].balance=r.toString())}}};var it=class extends be{MAX_FINAL_WEIGHT=Y(I(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,l])=>this.isActivePool(l.unwrap(),s)).map(async([{args:[i]},l])=>{let c=l.unwrap(),h=i.toString(),y=await this.getPoolDelta(h,c,s.toString());return this.poolsData.set(i.toString(),c),{address:h,type:"Lbp",fee:c.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let l=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,l)}else{let l=this.pools.findIndex(c=>c.address==e.address);this.pools.splice(l,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:l,initialWeight:c,finalWeight:h,repayTarget:y,feeCollector:w}=t,B=ue.calculateLinearWeights(r.toString(),i.toString(),c.toString(),h.toString(),s),[N,M]=l,_=N.toString(),D=I(B),G=M.toString(),V=this.MAX_FINAL_WEIGHT.minus(I(D)),[O,pe,we]=await Promise.all([this.isRepayFeeApplied(_,y.toString(),w.toString()),this.getBalance(e,_),this.getBalance(e,G)]);return{repayFeeApply:O,tokens:[{id:_,weight:D,balance:pe.toString()},{id:G,weight:V,balance:we.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=I(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var zt=require("@polkadot/util-crypto"),Xt=require("@polkadot/util");function J(u,e){return u.shiftedBy(-1*e).toString()}function ce(u){return u[0]/u[1]*100}function re(u){return u[0]/u[1]}function ge(u){return[u/rt,rt]}var nt=class extends be{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),l=s.map(async([{args:[h]},y])=>{let{hubReserve:w,shares:B,tradable:N}=y.unwrap(),M=await this.getBalance(t,h.toString());return{id:h.toString(),hubReserves:I(w.toString()),shares:I(B.toString()),tradeable:N.bits.toNumber(),balance:M.toString()}}),c=await Promise.all(l);return c.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:c,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=await this.api.query.dynamicFees.assetFee(e),r=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,l=r.minFee.toNumber()+i.minFee.toNumber(),c=r.maxFee.toNumber()+i.maxFee.toNumber();if(s.isSome){let{assetFee:h,protocolFee:y}=s.unwrap();return{assetFee:ge(h.toNumber()),protocolFee:ge(y.toNumber()),min:ge(l),max:ge(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:ge(l),max:ge(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let l=e.tokens[i];if(r.isNone)return l;let c=r.unwrap();return this.updateTokenState(l,c)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i}=t;return{...e,hubReserves:I(s.toString()),shares:I(r.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return ge(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return ge(t)}getPoolId(){return(0,zt.encodeAddress)((0,Xt.stringToU8a)("modlomnipool".padEnd(32,"\0")),Ee)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var ot=class extends be{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[l,c]=r.unwrap(),[h,y]=await Promise.all([this.getBalance(i,l.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:l.toString(),balance:h.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var lt=require("@polkadot/util-crypto");var $=require("@galacticcouncil/math-stableswap"),ee=class{static getPoolAddress(e){return(0,$.pool_account_name)(e)}static calculateAmplification(e,t,s,r,i){return(0,$.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,l){return(0,$.calculate_in_given_out)(e,t,s,r,i,l)}static calculateAddOneAsset(e,t,s,r,i,l){return(0,$.calculate_add_one_asset)(e,t,s,r,i,l)}static calculateSharesForAmount(e,t,s,r,i,l){return(0,$.calculate_shares_for_amount)(e,t,s,r,i,l)}static calculateOutGivenIn(e,t,s,r,i,l){return(0,$.calculate_out_given_in)(e,t,s,r,i,l)}static calculateLiquidityOutOneAsset(e,t,s,r,i,l){return(0,$.calculate_liquidity_out_one_asset)(e,t,s,r,i,l)}static calculateShares(e,t,s,r,i){return(0,$.calculate_shares)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,$.calculate_pool_trade_fee)(e,t,s)}};var at=class extends be{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},l])=>{let c=l.unwrap(),h=i.toString(),y=this.getPoolAddress(h),[w,B]=await Promise.all([this.getPoolDelta(h,c,s.toString()),this.getPoolTokens(y,h,c)]);return this.stablePools.set(y,c),{address:y,id:h,type:"Stableswap",fee:ge(c.fee.toNumber()),tokens:B,...w,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toNumber(),r=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,r,s.toString());Object.assign(e,i)})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:l,finalBlock:c}=t,h=ee.calculateAmplification(r.toString(),i.toString(),l.toString(),c.toString(),s),y=await this.api.query.tokens.totalIssuance(e);return{amplification:h,totalIssuance:y.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async h=>{let[y,w]=await Promise.all([this.api.query.stableswap.assetTradability(t,h.toString()),this.getBalance(e,h.toString())]);return{id:h.toString(),tradeable:y.bits.toNumber(),balance:w.toString()}}),l=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:h}=c.unwrap(),y=await this.getBalance($e,t);l.push({id:t,tradeable:h.bits.toNumber(),balance:y.toString()})}return l}getPoolAddress(e){let t=Number(e),s=ee.getPoolAddress(t);return(0,lt.encodeAddress)((0,lt.blake2AsHex)(s),Ee)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function ut(u){return u.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var Je=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},At=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},De=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Tt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Ft=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},_t=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Ce=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new Le(this.api),this.xykClient=new ot(this.api),this.omniClient=new nt(this.api),this.lbpClient=new it(this.api),this.stableClient=new at(this.api)}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||(this.onChainAssets=await this.assetClient.getOnChainAssets(),this.onChainAssetsLoaded=!0),e.length==0){let l=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(c=>c.isSupported()).map(c=>c.getPools()))).flat();return this.withMetadata(l)}let t=[];e.forEach(i=>{switch(i){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break;case"Stableswap":t.push(this.stableClient.getPools());break}});let r=(await Promise.all(t)).flat();return this.withMetadata(r)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(s=>[s.id,s]));return e.filter(s=>s.type==="Xyk"?s.tokens.every(r=>t.get(r.id)):!0).map(s=>{let r=s.tokens.map(i=>{let l=t.get(i.id);return{...i,...l}});return{...s,tokens:r}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new Je(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let l;this.isDirectOmnipoolTrade(i)?l=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):l=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),ut(i));let c=()=>l;return{hex:l.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,s,r,i){let l;this.isDirectOmnipoolTrade(i)?l=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):l=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),ut(i));let c=()=>l;return{hex:l.toHex(),name:"RouterSell",get:c}}};var je=(u,e)=>u===e?0:u==null?e==null?0:-1:e==null?u==null?0:1:typeof u.compare=="function"?u.compare(e):typeof e.compare=="function"?-e.compare(u):u<e?-1:u>e?1:0;var ct=(u,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(u(t)+e(t))}};var Ps=ct(()=>"illegal argument(s)"),Wt=u=>{throw new Ps(u)};var bs=ct(()=>"index out of bounds"),Rt=u=>{throw new bs(u)},pt=(u,e,t)=>(u<e||u>=t)&&Rt(u);var Yt=23283064365386963e-26,mt=class{float(e=1){return this.int()*Yt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Yt-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var Et=Math.random,kt=class extends mt{int(){return Et()*4294967296>>>0}float(e=1){return Et()*e}norm(e=1){return(Et()-.5)*2*e}},$t=new kt;var Jt=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var jt=Object.getPrototypeOf({}),ht="function",Kt="string",Ge=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===ht)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===ht)return e.equiv(u)}else return u==e;return typeof u===Kt||typeof e===Kt?!1:(t=Object.getPrototypeOf(u),(t==null||t===jt)&&(t=Object.getPrototypeOf(e),t==null||t===jt)?Os(u,e):typeof u!==ht&&u.length!==void 0&&typeof e!==ht&&e.length!==void 0?Ss(u,e):u instanceof Set&&e instanceof Set?ys(u,e):u instanceof Map&&e instanceof Map?xs(u,e):u instanceof Date&&e instanceof Date?u.getTime()===e.getTime():u instanceof RegExp&&e instanceof RegExp?u.toString()===e.toString():u!==u&&e!==e)},Ss=(u,e,t=Ge)=>{let s=u.length;if(s===e.length)for(;s-- >0&&t(u[s],e[s]););return s<0},ys=(u,e,t=Ge)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),xs=(u,e,t=Ge)=>u.size===e.size&&t([...u].sort(),[...e].sort()),Os=(u,e,t=Ge)=>{if(Object.keys(u).length!==Object.keys(e).length)return!1;for(let s in u)if(!e.hasOwnProperty(s)||!t(u[s],e[s]))return!1;return!0};var Qt=(u,e)=>u!=null&&typeof u[e]=="function";var Vt=u=>Qt(u,"xform")?u.xform():u;var gt=Symbol(),Lt=()=>{};var Zt=u=>u!=null&&typeof u[Symbol.iterator]=="function";var dt=class{value;constructor(e){this.value=e}deref(){return this.value}};var ft=u=>u instanceof dt;var es=u=>u instanceof dt?u.deref():u;function*ts(u,e){let t=Vt(u)([Lt,Lt,(s,r)=>r])[2];for(let s of e){let r=t(gt,s);if(ft(r)){r=es(r.deref()),r!==gt&&(yield r);return}r!==gt&&(yield r)}}var ss=(u,e)=>[u[0],u[1],e];function Ke(u,e){return Zt(e)?ts(Ke(u),e):t=>{let s=t[2];return ss(t,(r,i)=>s(r,u(i)))}}var qe=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return rs("next",this._head)}reverseIterator(){return rs("prev",this.tail)}clear(){this.release()}compare(e,t=je){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,l=0;for(;s-- >0&&l===0;)l=t(r.value,i.value),r=r.next,i=i.next;return l}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof qe||Jt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!Ge(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||je;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!ft(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&Rt(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*rs(u,e){for(;e;)yield e.value,e=e[u]}var Se=class extends qe{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new Se(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new Se}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(pt(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(pt(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new Se,e)}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let s=this.nthCell(e),r=this.nthCell(t-1),i=l=>({first(){return l.value},next(){return l!==r&&l.next?i(l.next):void 0}});return s?i(s):void 0}shuffle(e,t=$t){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&Wt("invalid indices: ${from} / ${to}");let i=new Se,l=this.nthCell(s);for(;l&&++s<=r;)i.push(l.value),l=l.next;return i}sort(e=je){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,l=0;for(let h=0;h<t&&(l++,i=i.next,!!i);h++);let c=t;for(;l>0||c>0&&i;){let h;l===0?(h=i,i=i.next,c--):!i||c===0||e(s.value,i.value)<=0?(h=s,s=s.next,l--):(h=i,i=i.next,c--),this._tail?this._tail.next=h:this._head=h,h.prev=this._tail,this._tail=h}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),pt(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new Se;if(t>0)for(;r&&t-- >0;)this.remove(r),i.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let l of s)this.insertBefore(r,l);else for(let l of s)this.push(l);return i}};var He=class{map;items;opts;_size;constructor(e,t){let s=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=s.map(),this.items=new Se,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ke(e=>[e.k,e],this.items)}keys(){return Ke(e=>e.k,this.items)}values(){return Ke(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new He(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e);return this._size+=Math.max(0,s-(r?r.value.s:0)),this.ensureSize()&&this.doSetEntry(r,e,t,s),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let s=this.map.get(e);return s?Promise.resolve(this.resetEntry(s)):t().then(r=>this.set(e,r))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,s=this.opts.maxlen;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e&&e(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Pt=class extends Ce{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new He(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
-
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,l,c){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=l,this.repayFeeApply=c}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(h=>[h.id,h])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:l,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(l)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let c=this.calculateTradeFee(t,s),h=ce(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(c),w=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return w.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:w,calculatedIn:w,amountOut:t,feePct:h,errors:i}}else{let c=this.calculateInGivenOut(e,t),h=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(h)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(l)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let c=this.calculateOutGivenIn(e,t),h=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(h)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),h=this.calculateTradeFee(c,s),y=ce(this.repayFeeApply?s.repayFee:s.exchangeFee),w=c.minus(h),B=e.balanceOut.div(this.maxOutRatio);return w.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:w,feePct:y,errors:i}}}calculateInGivenOut(e,t){let s=ue.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=ue.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=ue.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),Y(ie,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=ue.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),Y(ie,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=ue.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(s)}};var F=require("@galacticcouncil/math-omnipool"),z=class{static calculateSpotPrice(e,t,s,r){return(0,F.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,F.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,l,c,h,y){return(0,F.calculate_in_given_out)(e,t,s,r,i,l,c,h,y)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,F.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,l,c,h,y){return(0,F.calculate_out_given_in)(e,t,s,r,i,l,c,h,y)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,F.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,F.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,F.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,l,c,h){return(0,F.calculate_liquidity_out)(e,t,s,r,i,l,c,h)}static calculateLiquidityLRNAOut(e,t,s,r,i,l,c,h){return(0,F.calculate_liquidity_lrna_out)(e,t,s,r,i,l,c,h)}static calculateCapDifference(e,t,s,r){return(0,F.calculate_cap_difference)(e,t,s,r)}static verifyAssetCap(e,t,s,r){return(0,F.verify_asset_cap)(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return(0,F.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,F.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,F.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,F.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,F.is_remove_liquidity_allowed)(e)}};var Ie=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new Ie(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,l){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=l}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(h=>[h.id,h])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:l,balanceOut:c,tradeableIn:r.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),l=i.minus(r),c=r===E?E:l.div(r).multipliedBy(100).decimalPlaces(2),h=[],y=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!y||!w)&&h.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&h.push("MaxOutRatioExceeded");let N=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(N)&&h.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:c.toNumber(),errors:h}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),c=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),h=[],y=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!y||!w)&&h.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&h.push("MaxInRatioExceeded");let N=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(N)&&h.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:c.toNumber(),errors:h}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=z.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?re(s.assetFee).toString():E.toString(),s?re(s.protocolFee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateLrnaInGivenOut(e,t,s){let r=z.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?re(s.assetFee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=z.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?re(s.assetFee).toString():E.toString(),s?re(s.protocolFee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateOutGivenLrnaIn(e,t,s){let r=z.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?re(s.assetFee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=z.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Re-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=z.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Re-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=z.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Re-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=z.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Re-e.decimalsIn)).decimalPlaces(0,1)}};var Ae=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Ae(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,i,l,c,h,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=l,this.id=c,this.fee=h,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(h=>[h.id,h])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:l,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?st:r.tradeable,tradeableOut:this.id===t?st:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),l=ce(s.fee),c=[],h=z.isSellAllowed(e.tradeableIn),y=z.isBuyAllowed(e.tradeableOut);return(!h||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:l,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),l=ce(s.fee),c=[],h=z.isSellAllowed(e.tradeableIn),y=z.isBuyAllowed(e.tradeableOut);return(!h||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:l,errors:c}}calculateIn(e,t,s){let r=ee.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?re(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateAddOneAsset(e,t,s){let r=ee.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?re(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateSharesForAmount(e,t,s){let r=ee.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?re(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=Y(ie,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,s){let r=ee.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?re(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateWithdrawOneAsset(e,t,s){let r=ee.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?re(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateShares(e,t,s){let r=ee.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?re(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=Y(ie,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=ee.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var Q=require("@galacticcouncil/math-xyk"),ye=class{static getSpotPrice(e,t,s){return(0,Q.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,Q.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,Q.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,Q.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,Q.calculate_liquidity_in)(e,t,s)}static calculateShares(e,t,s){return(0,Q.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,Q.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,Q.calculate_liquidity_out_asset_b)(e,t,s,r)}};var Ne=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Ne(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(h=>[h.id,h])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:l,balanceOut:c}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),l=ce(s.exchangeFee),c=r.plus(i),h=[];t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&h.push("MaxOutRatioExceeded");let w=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(w)&&h.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:r,amountOut:t,feePct:l,errors:h}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),l=ce(s.exchangeFee),c=r.minus(i),h=[];t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&h.push("MaxInRatioExceeded");let w=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(w)&&h.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:l,errors:h}}calculateInGivenOut(e,t){let s=ye.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=ye.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=ye.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),Y(ie,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=ye.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),Y(ie,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=ye.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(s)}};var Ue=class{static get(e){switch(e.type){case"Xyk":return Ne.fromPool(e);case"Omnipool":return Ie.fromPool(e);case"Lbp":return ve.fromPool(e);case"Stableswap":return Ae.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Fe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ye,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),l=this.getPaths(e,null,r,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(l)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,origin:r.origin,meta:r.meta}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(c=>this.validPath(c,s)).map(c=>this.toHops(c,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,Ue.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let l=t.get(s);return{poolAddress:s,poolId:l?.id,pool:l?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function ws(u,e){return u.minus(e).abs().div(u.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ze(u,e){return u.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Mt(u,e){return ie.minus(e.div(u)).multipliedBy(100).decimalPlaces(2)}function Dt(u,e){return e.div(u).minus(ie).multipliedBy(100).decimalPlaces(2)}var Qe=class extends Fe{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,l=r[r.length-1].amountOut;return i.isGreaterThan(l)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,l)=>i+l),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,l)=>i+l);return[s,r]}}getPoolFeeRange(e){let t=e.min?ce(e.min):void 0,s=e.max?ce(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,r),l=super.getPaths(e,t,i,r);if(l.length===0)throw new De(e,t);let c=l.map(async L=>await this.toSellSwaps(s,L,i)),h=await Promise.all(c),y=this.findBestSellRoute(h),w=y[0],B=y[y.length-1],N=this.isDirectTrade(y),M=y.map(L=>L.spotPrice.shiftedBy(-1*L.assetOutDecimals)).reduce((L,n)=>L.multipliedBy(n)),_=Y(M,B.assetOutDecimals),D=N?B.calculatedOut:this.calculateDelta0Y(w.amountIn,y,i),G=B.amountOut,V=N?B.tradeFeePct:Mt(D,G).toNumber(),O=D.minus(G),pe=this.getRouteFeeRange(y),we=w.amountIn.shiftedBy(-1*w.assetInDecimals).multipliedBy(_),me=ze(D,we),j=L=>this.poolService.buildSellTx(e,t,w.amountIn,L,y.map(n=>n));return{type:"Sell",amountIn:w.amountIn,amountOut:B.amountOut,spotPrice:_,tradeFee:O,tradeFeePct:V,tradeFeeRange:pe,priceImpactPct:me.toNumber(),swaps:y,toTx:j,toHuman(){return{type:"Sell",amountIn:J(w.amountIn,w.assetInDecimals),amountOut:J(B.amountOut,B.assetOutDecimals),spotPrice:J(_,B.assetOutDecimals),tradeFee:J(O,B.assetOutDecimals),tradeFeePct:V,tradeFeeRange:pe,priceImpactPct:me.toNumber(),swaps:y.map(L=>L.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let l=t[i],c=s.get(l.poolAddress);if(c==null)throw new Error("Pool does not exit");let h=c.parsePair(l.assetIn,l.assetOut),y;i>0?y=r[i-1]:y=e;let w=c.calculateOutGivenIn(h,y);r.push(w)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let l=t[i],c=s.get(l.poolAddress);if(c==null)throw new Error("Pool does not exit");let h=c.parsePair(l.assetIn,l.assetOut),y;i>0?y=r[i-1].amountOut:y=Y(I(e),h.decimalsIn).decimalPlaces(0,1);let w=await this.poolService.getPoolFees(h.assetOut,c),{amountOut:B,calculatedOut:N,feePct:M,errors:_}=c.validateAndSell(h,y,w),D=this.getPoolFeeRange(w),G=c.spotPriceOutGivenIn(h),V=y.shiftedBy(-1*h.decimalsIn).multipliedBy(G),O=ze(N,V);r.push({...l,assetInDecimals:h.decimalsIn,assetOutDecimals:h.decimalsOut,amountIn:y,calculatedOut:N,amountOut:B,spotPrice:G,tradeFeePct:M,tradeFeeRange:D,priceImpactPct:O.toNumber(),errors:_,toHuman(){return{...l,amountIn:J(y,h.decimalsIn),calculatedOut:J(N,h.decimalsOut),amountOut:J(B,h.decimalsOut),spotPrice:J(G,h.decimalsOut),tradeFeePct:M,tradeFeeRange:D,priceImpactPct:O.toNumber(),errors:_}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let l=i.map(async N=>await this.toSellSwaps("1",N,r)),c=await Promise.all(l),h=this.findBestSellRoute(c),y=h.map(N=>N.spotPrice.shiftedBy(-1*N.assetOutDecimals)).reduce((N,M)=>N.multipliedBy(M)),w=h[h.length-1].assetOutDecimals;return{amount:Y(y,w),decimals:w}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,l=r[0].amountIn;return i.isGreaterThan(l)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,r),l=super.getPaths(e,t,i,r);if(l.length===0)throw new De(e,t);let c=l.map(async L=>await this.toBuySwaps(s,L,i)),h=await Promise.all(c),y=this.findBestBuyRoute(h),w=y[y.length-1],B=y[0],N=this.isDirectTrade(y),M=y.map(L=>L.spotPrice.shiftedBy(-1*L.assetInDecimals)).reduce((L,n)=>L.multipliedBy(n)),_=Y(M,B.assetInDecimals),D=N?B.calculatedIn:this.calculateDelta0X(w.amountOut,y,i),G=B.amountIn,V=N?B.tradeFeePct:Dt(D,G),O=G.minus(D),pe=this.getRouteFeeRange(y),we=w.amountOut.shiftedBy(-1*w.assetOutDecimals).multipliedBy(_),me;D.isZero()?me=-100:me=ze(we,D).toNumber();let j=L=>this.poolService.buildBuyTx(e,t,w.amountOut,L,y.map(n=>n));return{type:"Buy",amountOut:w.amountOut,amountIn:B.amountIn,spotPrice:_,tradeFee:O,tradeFeePct:V,tradeFeeRange:pe,priceImpactPct:me,swaps:y,toTx:j,toHuman(){return{type:"Buy",amountOut:J(w.amountOut,w.assetOutDecimals),amountIn:J(B.amountIn,B.assetInDecimals),spotPrice:J(_,B.assetInDecimals),tradeFee:J(O,B.assetInDecimals),tradeFeePct:V,tradeFeeRange:pe,priceImpactPct:me,swaps:y.map(L=>L.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let l=t[i],c=s.get(l.poolAddress);if(c==null)throw new Error("Pool does not exit");let h=c.parsePair(l.assetIn,l.assetOut),y;i==t.length-1?y=e:y=r[0];let w=c.calculateInGivenOut(h,y);r.unshift(w)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let l=t[i],c=s.get(l.poolAddress);if(c==null)throw new Error("Pool does not exit");let h=c.parsePair(l.assetIn,l.assetOut),y;i==t.length-1?y=Y(I(e),h.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let w=await this.poolService.getPoolFees(h.assetOut,c),{amountIn:B,calculatedIn:N,feePct:M,errors:_}=c.validateAndBuy(h,y,w),D=this.getPoolFeeRange(w),G=c.spotPriceInGivenOut(h),V=y.shiftedBy(-1*h.decimalsOut).multipliedBy(G),O;N.isZero()?O=-100:O=ze(V,N).toNumber(),r.unshift({...l,assetInDecimals:h.decimalsIn,assetOutDecimals:h.decimalsOut,amountOut:y,calculatedIn:N,amountIn:B,spotPrice:G,tradeFeePct:M,tradeFeeRange:D,priceImpactPct:O,errors:_,toHuman(){return{...l,amountOut:J(y,h.decimalsOut),calculatedIn:J(N,h.decimalsIn),amountIn:J(B,h.decimalsIn),spotPrice:J(G,h.decimalsIn),tradeFeePct:M,tradeFeeRange:D,priceImpactPct:O,errors:_}}})}return r}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
|
|
2
|
+
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,l,c){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=l,this.repayFeeApply=c}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(h=>[h.id,h])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:l,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(l)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let c=this.calculateTradeFee(t,s),h=ce(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(c),w=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return w.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:w,calculatedIn:w,amountOut:t,feePct:h,errors:i}}else{let c=this.calculateInGivenOut(e,t),h=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(h)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(l)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let c=this.calculateOutGivenIn(e,t),h=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(h)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),h=this.calculateTradeFee(c,s),y=ce(this.repayFeeApply?s.repayFee:s.exchangeFee),w=c.minus(h),B=e.balanceOut.div(this.maxOutRatio);return w.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:w,feePct:y,errors:i}}}calculateInGivenOut(e,t){let s=ue.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=ue.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=ue.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),Y(ie,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=ue.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),Y(ie,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=ue.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(s)}};var F=require("@galacticcouncil/math-omnipool"),z=class{static calculateSpotPrice(e,t,s,r){return(0,F.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,F.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,l,c,h,y){return(0,F.calculate_in_given_out)(e,t,s,r,i,l,c,h,y)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,F.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,l,c,h,y){return(0,F.calculate_out_given_in)(e,t,s,r,i,l,c,h,y)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,F.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,F.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,F.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,l,c,h){return(0,F.calculate_liquidity_out)(e,t,s,r,i,l,c,h)}static calculateLiquidityLRNAOut(e,t,s,r,i,l,c,h){return(0,F.calculate_liquidity_lrna_out)(e,t,s,r,i,l,c,h)}static calculateCapDifference(e,t,s,r){return(0,F.calculate_cap_difference)(e,t,s,r)}static verifyAssetCap(e,t,s,r){return(0,F.verify_asset_cap)(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return(0,F.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,F.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,F.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,F.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,F.is_remove_liquidity_allowed)(e)}};var Ie=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new Ie(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,l){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=l}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(h=>[h.id,h])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:l,balanceOut:c,tradeableIn:r.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),l=i.minus(r),c=r===E?E:l.div(r).multipliedBy(100).decimalPlaces(2),h=[],y=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!y||!w)&&h.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&h.push("MaxOutRatioExceeded");let N=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(N)&&h.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:c.toNumber(),errors:h}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),c=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),h=[],y=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!y||!w)&&h.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&h.push("MaxInRatioExceeded");let N=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(N)&&h.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:c.toNumber(),errors:h}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=z.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?re(s.assetFee).toString():E.toString(),s?re(s.protocolFee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateLrnaInGivenOut(e,t,s){let r=z.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?re(s.assetFee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=z.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?re(s.assetFee).toString():E.toString(),s?re(s.protocolFee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateOutGivenLrnaIn(e,t,s){let r=z.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?re(s.assetFee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=z.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Re-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=z.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Re-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=z.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Re-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=z.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Re-e.decimalsIn)).decimalPlaces(0,1)}};var Ae=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Ae(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,i,l,c,h,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=l,this.id=c,this.fee=h,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(h=>[h.id,h])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:l,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?st:r.tradeable,tradeableOut:this.id===t?st:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),l=ce(s.fee),c=[],h=z.isSellAllowed(e.tradeableIn),y=z.isBuyAllowed(e.tradeableOut);return(!h||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:l,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),l=ce(s.fee),c=[],h=z.isSellAllowed(e.tradeableIn),y=z.isBuyAllowed(e.tradeableOut);return(!h||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:l,errors:c}}calculateIn(e,t,s){let r=ee.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?re(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateAddOneAsset(e,t,s){let r=ee.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?re(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateSharesForAmount(e,t,s){let r=ee.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?re(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=Y(ie,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,s){let r=ee.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?re(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateWithdrawOneAsset(e,t,s){let r=ee.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?re(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateShares(e,t,s){let r=ee.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?re(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=Y(ie,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=ee.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var Q=require("@galacticcouncil/math-xyk"),ye=class{static getSpotPrice(e,t,s){return(0,Q.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,Q.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,Q.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,Q.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,Q.calculate_liquidity_in)(e,t,s)}static calculateShares(e,t,s){return(0,Q.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,Q.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,Q.calculate_liquidity_out_asset_b)(e,t,s,r)}};var Ne=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Ne(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(h=>[h.id,h])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:l,balanceOut:c}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),l=ce(s.exchangeFee),c=r.plus(i),h=[];t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&h.push("MaxOutRatioExceeded");let w=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(w)&&h.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:r,amountOut:t,feePct:l,errors:h}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),l=ce(s.exchangeFee),c=r.minus(i),h=[];t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&h.push("MaxInRatioExceeded");let w=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(w)&&h.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:l,errors:h}}calculateInGivenOut(e,t){let s=ye.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=ye.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=ye.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),Y(ie,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=ye.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),Y(ie,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=ye.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(s)}};var Ue=class{static get(e){switch(e.type){case"Xyk":return Ne.fromPool(e);case"Omnipool":return Ie.fromPool(e);case"Lbp":return ve.fromPool(e);case"Stableswap":return Ae.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Fe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ye,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),l=this.getPaths(e,null,r,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(l)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,origin:r.origin,meta:r.meta}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(c=>this.validPath(c,s)).map(c=>this.toHops(c,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,Ue.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let l=t.get(s);return{poolAddress:s,poolId:l?.id,pool:l?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function ws(u,e){return u.minus(e).abs().div(u.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ze(u,e){return u.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Mt(u,e){return ie.minus(e.div(u)).multipliedBy(100).decimalPlaces(2)}function Dt(u,e){return e.div(u).minus(ie).multipliedBy(100).decimalPlaces(2)}var Qe=class extends Fe{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,l=r[r.length-1].amountOut;return i.isGreaterThan(l)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,l)=>i+l),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,l)=>i+l);return[s,r]}}getPoolFeeRange(e){let t=e.min?ce(e.min):void 0,s=e.max?ce(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,r),l=super.getPaths(e,t,i,r);if(l.length===0)throw new De(e,t);let c=l.map(async L=>await this.toSellSwaps(s,L,i)),h=await Promise.all(c),y=this.findBestSellRoute(h),w=y[0],B=y[y.length-1],N=this.isDirectTrade(y),M=y.map(L=>L.spotPrice.shiftedBy(-1*L.assetOutDecimals)).reduce((L,n)=>L.multipliedBy(n)),_=Y(M,B.assetOutDecimals),D=N?B.calculatedOut:this.calculateDelta0Y(w.amountIn,y,i),G=B.amountOut,V=N?B.tradeFeePct:Mt(D,G).toNumber(),O=D.minus(G),pe=this.getRouteFeeRange(y),we=w.amountIn.shiftedBy(-1*w.assetInDecimals).multipliedBy(_),me=ze(D,we),j=L=>this.poolService.buildSellTx(e,t,w.amountIn,L,y.map(n=>n));return{type:"Sell",amountIn:w.amountIn,amountOut:B.amountOut,spotPrice:_,tradeFee:O,tradeFeePct:V,tradeFeeRange:pe,priceImpactPct:me.toNumber(),swaps:y,toTx:j,toHuman(){return{type:"Sell",amountIn:J(w.amountIn,w.assetInDecimals),amountOut:J(B.amountOut,B.assetOutDecimals),spotPrice:J(_,B.assetOutDecimals),tradeFee:J(O,B.assetOutDecimals),tradeFeePct:V,tradeFeeRange:pe,priceImpactPct:me.toNumber(),swaps:y.map(L=>L.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let l=t[i],c=s.get(l.poolAddress);if(c==null)throw new Error("Pool does not exit");let h=c.parsePair(l.assetIn,l.assetOut),y;i>0?y=r[i-1]:y=e;let w=c.calculateOutGivenIn(h,y);r.push(w)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let l=t[i],c=s.get(l.poolAddress);if(c==null)throw new Error("Pool does not exit");let h=c.parsePair(l.assetIn,l.assetOut),y;i>0?y=r[i-1].amountOut:y=Y(I(e),h.decimalsIn).decimalPlaces(0,1);let w=await this.poolService.getPoolFees(h.assetOut,c),{amountOut:B,calculatedOut:N,feePct:M,errors:_}=c.validateAndSell(h,y,w),D=this.getPoolFeeRange(w),G=c.spotPriceOutGivenIn(h),V=y.shiftedBy(-1*h.decimalsIn).multipliedBy(G),O=ze(N,V);r.push({...l,assetInDecimals:h.decimalsIn,assetOutDecimals:h.decimalsOut,amountIn:y,calculatedOut:N,amountOut:B,spotPrice:G,tradeFeePct:M,tradeFeeRange:D,priceImpactPct:O.toNumber(),errors:_,toHuman(){return{...l,amountIn:J(y,h.decimalsIn),calculatedOut:J(N,h.decimalsOut),amountOut:J(B,h.decimalsOut),spotPrice:J(G,h.decimalsOut),tradeFeePct:M,tradeFeeRange:D,priceImpactPct:O.toNumber(),errors:_}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let l=i.map(async N=>await this.toSellSwaps("1",N,r)),c=await Promise.all(l),h=this.findBestSellRoute(c),y=h.map(N=>N.spotPrice.shiftedBy(-1*N.assetOutDecimals)).reduce((N,M)=>N.multipliedBy(M)),w=h[h.length-1].assetOutDecimals;return{amount:Y(y,w),decimals:w}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,l=r[0].amountIn;return i.isGreaterThan(l)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,r),l=super.getPaths(e,t,i,r);if(l.length===0)throw new De(e,t);let c=l.map(async L=>await this.toBuySwaps(s,L,i)),h=await Promise.all(c),y=this.findBestBuyRoute(h),w=y[y.length-1],B=y[0],N=this.isDirectTrade(y),M=y.map(L=>L.spotPrice.shiftedBy(-1*L.assetInDecimals)).reduce((L,n)=>L.multipliedBy(n)),_=Y(M,B.assetInDecimals),D=N?B.calculatedIn:this.calculateDelta0X(w.amountOut,y,i),G=B.amountIn,V=N?B.tradeFeePct:Dt(D,G).toNumber(),O=G.minus(D),pe=this.getRouteFeeRange(y),we=w.amountOut.shiftedBy(-1*w.assetOutDecimals).multipliedBy(_),me;D.isZero()?me=-100:me=ze(we,D).toNumber();let j=L=>this.poolService.buildBuyTx(e,t,w.amountOut,L,y.map(n=>n));return{type:"Buy",amountOut:w.amountOut,amountIn:B.amountIn,spotPrice:_,tradeFee:O,tradeFeePct:V,tradeFeeRange:pe,priceImpactPct:me,swaps:y,toTx:j,toHuman(){return{type:"Buy",amountOut:J(w.amountOut,w.assetOutDecimals),amountIn:J(B.amountIn,B.assetInDecimals),spotPrice:J(_,B.assetInDecimals),tradeFee:J(O,B.assetInDecimals),tradeFeePct:V,tradeFeeRange:pe,priceImpactPct:me,swaps:y.map(L=>L.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let l=t[i],c=s.get(l.poolAddress);if(c==null)throw new Error("Pool does not exit");let h=c.parsePair(l.assetIn,l.assetOut),y;i==t.length-1?y=e:y=r[0];let w=c.calculateInGivenOut(h,y);r.unshift(w)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let l=t[i],c=s.get(l.poolAddress);if(c==null)throw new Error("Pool does not exit");let h=c.parsePair(l.assetIn,l.assetOut),y;i==t.length-1?y=Y(I(e),h.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let w=await this.poolService.getPoolFees(h.assetOut,c),{amountIn:B,calculatedIn:N,feePct:M,errors:_}=c.validateAndBuy(h,y,w),D=this.getPoolFeeRange(w),G=c.spotPriceInGivenOut(h),V=y.shiftedBy(-1*h.decimalsOut).multipliedBy(G),O;N.isZero()?O=-100:O=ze(V,N).toNumber(),r.unshift({...l,assetInDecimals:h.decimalsIn,assetOutDecimals:h.decimalsOut,amountOut:y,calculatedIn:N,amountIn:B,spotPrice:G,tradeFeePct:M,tradeFeeRange:D,priceImpactPct:O,errors:_,toHuman(){return{...l,amountOut:J(y,h.decimalsOut),calculatedIn:J(N,h.decimalsIn),amountIn:J(B,h.decimalsIn),spotPrice:J(G,h.decimalsIn),tradeFeePct:M,tradeFeeRange:D,priceImpactPct:O,errors:_}}})}return r}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
|
package/build/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Jt=Object.defineProperty;var je=(n,A)=>{for(var j in A)Jt(n,j,{get:A[j],enumerable:!0})};var hj=class{constructor(A=1/0){this.capacity=A}storage=[];enqueue(A){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(A)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Qt=5,rj=class{isNotVisited(A,j){let e=!0;return j.forEach(t=>{(t[0]===A[0]||t[1]===A[1])&&(e=!1)}),e}findPaths(A,j,e){let t=[],r=new hj,s=[];for(s.push([j,""]),r.enqueue(s);r.size()>0;){let i=r.dequeue();if(i==null||i.length>Qt)return t;let a=i[i.length-1];(e===null||a[0]===e)&&t.push(i),A.get(a[0])?.forEach(f=>{if(this.isNotVisited(f,i)){let P=[...i];P.push(f),r.enqueue(P)}})}return t}buildAndPopulateGraph(A,j){let e=new Map;for(let t of A)e.set(parseInt(t),[]);for(let[t,r,s]of j){let i=parseInt(r),a=parseInt(s);e.get(i)?.push([a,t])}return e}};function ee(n){let A={};for(let j of n){let e=j.tokens.length;for(let t=0;t<e;t++){A[j.tokens[t].id]||(A[j.tokens[t].id]=[]);for(let r=0;r<e;r++){if(t==r)continue;let s=[j.address,j.tokens[t].id,j.tokens[r].id];A[j.tokens[t].id].push(s)}}}return A}var nj=class{getProposals(A,j,e){let t=ee(e),r=Object.keys(t),s=r.map(f=>t[f]).flat(),i=new rj,a=i.buildAndPopulateGraph(r,s),B=i.findPaths(a,parseInt(A),j?parseInt(j):null);return this.parsePaths(B)}parsePaths(A){let j=[];for(let e of A){let t=[];for(let r=0;r<e.length;r++){let s=e[r],i=e[r+1];if(i==null)break;t.push(this.toEdge(s,i))}j.push(t)}return j}toEdge(A,j){return[j[1],A[0].toString(),j[0].toString()]}};var Ut=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,te=Math.ceil,qA=Math.floor,fA="[BigNumber Error] ",me=fA+"Number primitive has more than 15 significant digits: ",yA=1e14,R=14,re=9007199254740991,ne=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],HA=1e7,lA=1e9;function ge(n){var A,j,e,t=E.prototype={constructor:E,toString:null,valueOf:null},r=new E(1),s=20,i=4,a=-7,B=21,f=-1e7,P=1e7,I=!1,$=1,T=0,v={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},x="0123456789abcdefghijklmnopqrstuvwxyz",N=!0;function E(o,l){var c,g,d,m,b,_,p,h,k=this;if(!(k instanceof E))return new E(o,l);if(l==null){if(o&&o._isBigNumber===!0){k.s=o.s,!o.c||o.e>P?k.c=k.e=null:o.e<f?k.c=[k.e=0]:(k.e=o.e,k.c=o.c.slice());return}if((_=typeof o=="number")&&o*0==0){if(k.s=1/o<0?(o=-o,-1):1,o===~~o){for(m=0,b=o;b>=10;b/=10,m++);m>P?k.c=k.e=null:(k.e=m,k.c=[o]);return}h=String(o)}else{if(!Ut.test(h=String(o)))return e(k,h,_);k.s=h.charCodeAt(0)==45?(h=h.slice(1),-1):1}(m=h.indexOf("."))>-1&&(h=h.replace(".","")),(b=h.search(/e/i))>0?(m<0&&(m=b),m+=+h.slice(b+1),h=h.substring(0,b)):m<0&&(m=h.length)}else{if(jA(l,2,x.length,"Base"),l==10&&N)return k=new E(o),W(k,s+k.e+1,i);if(h=String(o),_=typeof o=="number"){if(o*0!=0)return e(k,h,_,l);if(k.s=1/o<0?(h=h.slice(1),-1):1,E.DEBUG&&h.replace(/^0\.0*|\./,"").length>15)throw Error(me+o)}else k.s=h.charCodeAt(0)===45?(h=h.slice(1),-1):1;for(c=x.slice(0,l),m=b=0,p=h.length;b<p;b++)if(c.indexOf(g=h.charAt(b))<0){if(g=="."){if(b>m){m=p;continue}}else if(!d&&(h==h.toUpperCase()&&(h=h.toLowerCase())||h==h.toLowerCase()&&(h=h.toUpperCase()))){d=!0,b=-1,m=0;continue}return e(k,String(o),_,l)}_=!1,h=j(h,l,10,k.s),(m=h.indexOf("."))>-1?h=h.replace(".",""):m=h.length}for(b=0;h.charCodeAt(b)===48;b++);for(p=h.length;h.charCodeAt(--p)===48;);if(h=h.slice(b,++p)){if(p-=b,_&&E.DEBUG&&p>15&&(o>re||o!==qA(o)))throw Error(me+k.s*o);if((m=m-b-1)>P)k.c=k.e=null;else if(m<f)k.c=[k.e=0];else{if(k.e=m,k.c=[],b=(m+1)%R,m<0&&(b+=R),b<p){for(b&&k.c.push(+h.slice(0,b)),p-=R;b<p;)k.c.push(+h.slice(b,b+=R));b=R-(h=h.slice(b)).length}else b-=p;for(;b--;h+="0");k.c.push(+h)}}else k.c=[k.e=0]}E.clone=ge,E.ROUND_UP=0,E.ROUND_DOWN=1,E.ROUND_CEIL=2,E.ROUND_FLOOR=3,E.ROUND_HALF_UP=4,E.ROUND_HALF_DOWN=5,E.ROUND_HALF_EVEN=6,E.ROUND_HALF_CEIL=7,E.ROUND_HALF_FLOOR=8,E.EUCLID=9,E.config=E.set=function(o){var l,c;if(o!=null)if(typeof o=="object"){if(o.hasOwnProperty(l="DECIMAL_PLACES")&&(c=o[l],jA(c,0,lA,l),s=c),o.hasOwnProperty(l="ROUNDING_MODE")&&(c=o[l],jA(c,0,8,l),i=c),o.hasOwnProperty(l="EXPONENTIAL_AT")&&(c=o[l],c&&c.pop?(jA(c[0],-lA,0,l),jA(c[1],0,lA,l),a=c[0],B=c[1]):(jA(c,-lA,lA,l),a=-(B=c<0?-c:c))),o.hasOwnProperty(l="RANGE"))if(c=o[l],c&&c.pop)jA(c[0],-lA,-1,l),jA(c[1],1,lA,l),f=c[0],P=c[1];else if(jA(c,-lA,lA,l),c)f=-(P=c<0?-c:c);else throw Error(fA+l+" cannot be zero: "+c);if(o.hasOwnProperty(l="CRYPTO"))if(c=o[l],c===!!c)if(c)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))I=c;else throw I=!c,Error(fA+"crypto unavailable");else I=c;else throw Error(fA+l+" not true or false: "+c);if(o.hasOwnProperty(l="MODULO_MODE")&&(c=o[l],jA(c,0,9,l),$=c),o.hasOwnProperty(l="POW_PRECISION")&&(c=o[l],jA(c,0,lA,l),T=c),o.hasOwnProperty(l="FORMAT"))if(c=o[l],typeof c=="object")v=c;else throw Error(fA+l+" not an object: "+c);if(o.hasOwnProperty(l="ALPHABET"))if(c=o[l],typeof c=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(c))N=c.slice(0,10)=="0123456789",x=c;else throw Error(fA+l+" invalid: "+c)}else throw Error(fA+"Object expected: "+o);return{DECIMAL_PLACES:s,ROUNDING_MODE:i,EXPONENTIAL_AT:[a,B],RANGE:[f,P],CRYPTO:I,MODULO_MODE:$,POW_PRECISION:T,FORMAT:v,ALPHABET:x}},E.isBigNumber=function(o){if(!o||o._isBigNumber!==!0)return!1;if(!E.DEBUG)return!0;var l,c,g=o.c,d=o.e,m=o.s;A:if({}.toString.call(g)=="[object Array]"){if((m===1||m===-1)&&d>=-lA&&d<=lA&&d===qA(d)){if(g[0]===0){if(d===0&&g.length===1)return!0;break A}if(l=(d+1)%R,l<1&&(l+=R),String(g[0]).length==l){for(l=0;l<g.length;l++)if(c=g[l],c<0||c>=yA||c!==qA(c))break A;if(c!==0)return!0}}}else if(g===null&&d===null&&(m===null||m===1||m===-1))return!0;throw Error(fA+"Invalid BigNumber: "+o)},E.maximum=E.max=function(){return tA(arguments,-1)},E.minimum=E.min=function(){return tA(arguments,1)},E.random=function(){var o=9007199254740992,l=Math.random()*o&2097151?function(){return qA(Math.random()*o)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(c){var g,d,m,b,_,p=0,h=[],k=new E(r);if(c==null?c=s:jA(c,0,lA),b=te(c/R),I)if(crypto.getRandomValues){for(g=crypto.getRandomValues(new Uint32Array(b*=2));p<b;)_=g[p]*131072+(g[p+1]>>>11),_>=9e15?(d=crypto.getRandomValues(new Uint32Array(2)),g[p]=d[0],g[p+1]=d[1]):(h.push(_%1e14),p+=2);p=b/2}else if(crypto.randomBytes){for(g=crypto.randomBytes(b*=7);p<b;)_=(g[p]&31)*281474976710656+g[p+1]*1099511627776+g[p+2]*4294967296+g[p+3]*16777216+(g[p+4]<<16)+(g[p+5]<<8)+g[p+6],_>=9e15?crypto.randomBytes(7).copy(g,p):(h.push(_%1e14),p+=7);p=b/7}else throw I=!1,Error(fA+"crypto unavailable");if(!I)for(;p<b;)_=l(),_<9e15&&(h[p++]=_%1e14);for(b=h[--p],c%=R,b&&c&&(_=ne[R-c],h[p]=qA(b/_)*_);h[p]===0;h.pop(),p--);if(p<0)h=[m=0];else{for(m=-1;h[0]===0;h.splice(0,1),m-=R);for(p=1,_=h[0];_>=10;_/=10,p++);p<R&&(m-=R-p)}return k.e=m,k.c=h,k}}(),E.sum=function(){for(var o=1,l=arguments,c=new E(l[0]);o<l.length;)c=c.plus(l[o++]);return c},j=function(){var o="0123456789";function l(c,g,d,m){for(var b,_=[0],p,h=0,k=c.length;h<k;){for(p=_.length;p--;_[p]*=g);for(_[0]+=m.indexOf(c.charAt(h++)),b=0;b<_.length;b++)_[b]>d-1&&(_[b+1]==null&&(_[b+1]=0),_[b+1]+=_[b]/d|0,_[b]%=d)}return _.reverse()}return function(c,g,d,m,b){var _,p,h,k,q,S,G,J,rA=c.indexOf("."),aA=s,X=i;for(rA>=0&&(k=T,T=0,c=c.replace(".",""),J=new E(g),S=J.pow(c.length-rA),T=k,J.c=l(RA(wA(S.c),S.e,"0"),10,d,o),J.e=J.c.length),G=l(c,g,d,b?(_=x,o):(_=o,x)),h=k=G.length;G[--k]==0;G.pop());if(!G[0])return _.charAt(0);if(rA<0?--h:(S.c=G,S.e=h,S.s=m,S=A(S,J,aA,X,d),G=S.c,q=S.r,h=S.e),p=h+aA+1,rA=G[p],k=d/2,q=q||p<0||G[p+1]!=null,q=X<4?(rA!=null||q)&&(X==0||X==(S.s<0?3:2)):rA>k||rA==k&&(X==4||q||X==6&&G[p-1]&1||X==(S.s<0?8:7)),p<1||!G[0])c=q?RA(_.charAt(1),-aA,_.charAt(0)):_.charAt(0);else{if(G.length=p,q)for(--d;++G[--p]>d;)G[p]=0,p||(++h,G=[1].concat(G));for(k=G.length;!G[--k];);for(rA=0,c="";rA<=k;c+=_.charAt(G[rA++]));c=RA(c,h,_.charAt(0))}return c}}(),A=function(){function o(g,d,m){var b,_,p,h,k=0,q=g.length,S=d%HA,G=d/HA|0;for(g=g.slice();q--;)p=g[q]%HA,h=g[q]/HA|0,b=G*p+h*S,_=S*p+b%HA*HA+k,k=(_/m|0)+(b/HA|0)+G*h,g[q]=_%m;return k&&(g=[k].concat(g)),g}function l(g,d,m,b){var _,p;if(m!=b)p=m>b?1:-1;else for(_=p=0;_<m;_++)if(g[_]!=d[_]){p=g[_]>d[_]?1:-1;break}return p}function c(g,d,m,b){for(var _=0;m--;)g[m]-=_,_=g[m]<d[m]?1:0,g[m]=_*b+g[m]-d[m];for(;!g[0]&&g.length>1;g.splice(0,1));}return function(g,d,m,b,_){var p,h,k,q,S,G,J,rA,aA,X,U,dA,kj,Yj,Ae,SA,tj,PA=g.s==d.s?1:-1,mA=g.c,nA=d.c;if(!mA||!mA[0]||!nA||!nA[0])return new E(!g.s||!d.s||(mA?nA&&mA[0]==nA[0]:!nA)?NaN:mA&&mA[0]==0||!nA?PA*0:PA/0);for(rA=new E(PA),aA=rA.c=[],h=g.e-d.e,PA=m+h+1,_||(_=yA,h=IA(g.e/R)-IA(d.e/R),PA=PA/R|0),k=0;nA[k]==(mA[k]||0);k++);if(nA[k]>(mA[k]||0)&&h--,PA<0)aA.push(1),q=!0;else{for(Yj=mA.length,SA=nA.length,k=0,PA+=2,S=qA(_/(nA[0]+1)),S>1&&(nA=o(nA,S,_),mA=o(mA,S,_),SA=nA.length,Yj=mA.length),kj=SA,X=mA.slice(0,SA),U=X.length;U<SA;X[U++]=0);tj=nA.slice(),tj=[0].concat(tj),Ae=nA[0],nA[1]>=_/2&&Ae++;do{if(S=0,p=l(nA,X,SA,U),p<0){if(dA=X[0],SA!=U&&(dA=dA*_+(X[1]||0)),S=qA(dA/Ae),S>1)for(S>=_&&(S=_-1),G=o(nA,S,_),J=G.length,U=X.length;l(G,X,J,U)==1;)S--,c(G,SA<J?tj:nA,J,_),J=G.length,p=1;else S==0&&(p=S=1),G=nA.slice(),J=G.length;if(J<U&&(G=[0].concat(G)),c(X,G,U,_),U=X.length,p==-1)for(;l(nA,X,SA,U)<1;)S++,c(X,SA<U?tj:nA,U,_),U=X.length}else p===0&&(S++,X=[0]);aA[k++]=S,X[0]?X[U++]=mA[kj]||0:(X=[mA[kj]],U=1)}while((kj++<Yj||X[0]!=null)&&PA--);q=X[0]!=null,aA[0]||aA.splice(0,1)}if(_==yA){for(k=1,PA=aA[0];PA>=10;PA/=10,k++);W(rA,m+(rA.e=k+h*R-1)+1,b,q)}else rA.e=h,rA.r=+q;return rA}}();function M(o,l,c,g){var d,m,b,_,p;if(c==null?c=i:jA(c,0,8),!o.c)return o.toString();if(d=o.c[0],b=o.e,l==null)p=wA(o.c),p=g==1||g==2&&(b<=a||b>=B)?Ej(p,b):RA(p,b,"0");else if(o=W(new E(o),l,c),m=o.e,p=wA(o.c),_=p.length,g==1||g==2&&(l<=m||m<=a)){for(;_<l;p+="0",_++);p=Ej(p,m)}else if(l-=b,p=RA(p,m,"0"),m+1>_){if(--l>0)for(p+=".";l--;p+="0");}else if(l+=m-_,l>0)for(m+1==_&&(p+=".");l--;p+="0");return o.s<0&&d?"-"+p:p}function tA(o,l){for(var c,g,d=1,m=new E(o[0]);d<o.length;d++)g=new E(o[d]),(!g.s||(c=UA(m,g))===l||c===0&&m.s===l)&&(m=g);return m}function oA(o,l,c){for(var g=1,d=l.length;!l[--d];l.pop());for(d=l[0];d>=10;d/=10,g++);return(c=g+c*R-1)>P?o.c=o.e=null:c<f?o.c=[o.e=0]:(o.e=c,o.c=l),o}e=function(){var o=/^(-?)0([xbo])(?=\w[\w.]*$)/i,l=/^([^.]+)\.$/,c=/^\.([^.]+)$/,g=/^-?(Infinity|NaN)$/,d=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(m,b,_,p){var h,k=_?b:b.replace(d,"");if(g.test(k))m.s=isNaN(k)?null:k<0?-1:1;else{if(!_&&(k=k.replace(o,function(q,S,G){return h=(G=G.toLowerCase())=="x"?16:G=="b"?2:8,!p||p==h?S:q}),p&&(h=p,k=k.replace(l,"$1").replace(c,"0.$1")),b!=k))return new E(k,h);if(E.DEBUG)throw Error(fA+"Not a"+(p?" base "+p:"")+" number: "+b);m.s=null}m.c=m.e=null}}();function W(o,l,c,g){var d,m,b,_,p,h,k,q=o.c,S=ne;if(q){A:{for(d=1,_=q[0];_>=10;_/=10,d++);if(m=l-d,m<0)m+=R,b=l,p=q[h=0],k=qA(p/S[d-b-1]%10);else if(h=te((m+1)/R),h>=q.length)if(g){for(;q.length<=h;q.push(0));p=k=0,d=1,m%=R,b=m-R+1}else break A;else{for(p=_=q[h],d=1;_>=10;_/=10,d++);m%=R,b=m-R+d,k=b<0?0:qA(p/S[d-b-1]%10)}if(g=g||l<0||q[h+1]!=null||(b<0?p:p%S[d-b-1]),g=c<4?(k||g)&&(c==0||c==(o.s<0?3:2)):k>5||k==5&&(c==4||g||c==6&&(m>0?b>0?p/S[d-b]:0:q[h-1])%10&1||c==(o.s<0?8:7)),l<1||!q[0])return q.length=0,g?(l-=o.e+1,q[0]=S[(R-l%R)%R],o.e=-l||0):q[0]=o.e=0,o;if(m==0?(q.length=h,_=1,h--):(q.length=h+1,_=S[R-m],q[h]=b>0?qA(p/S[d-b]%S[b])*_:0),g)for(;;)if(h==0){for(m=1,b=q[0];b>=10;b/=10,m++);for(b=q[0]+=_,_=1;b>=10;b/=10,_++);m!=_&&(o.e++,q[0]==yA&&(q[0]=1));break}else{if(q[h]+=_,q[h]!=yA)break;q[h--]=0,_=1}for(m=q.length;q[--m]===0;q.pop());}o.e>P?o.c=o.e=null:o.e<f&&(o.c=[o.e=0])}return o}function D(o){var l,c=o.e;return c===null?o.toString():(l=wA(o.c),l=c<=a||c>=B?Ej(l,c):RA(l,c,"0"),o.s<0?"-"+l:l)}return t.absoluteValue=t.abs=function(){var o=new E(this);return o.s<0&&(o.s=1),o},t.comparedTo=function(o,l){return UA(this,new E(o,l))},t.decimalPlaces=t.dp=function(o,l){var c,g,d,m=this;if(o!=null)return jA(o,0,lA),l==null?l=i:jA(l,0,8),W(new E(m),o+m.e+1,l);if(!(c=m.c))return null;if(g=((d=c.length-1)-IA(this.e/R))*R,d=c[d])for(;d%10==0;d/=10,g--);return g<0&&(g=0),g},t.dividedBy=t.div=function(o,l){return A(this,new E(o,l),s,i)},t.dividedToIntegerBy=t.idiv=function(o,l){return A(this,new E(o,l),0,1)},t.exponentiatedBy=t.pow=function(o,l){var c,g,d,m,b,_,p,h,k,q=this;if(o=new E(o),o.c&&!o.isInteger())throw Error(fA+"Exponent not an integer: "+D(o));if(l!=null&&(l=new E(l)),_=o.e>14,!q.c||!q.c[0]||q.c[0]==1&&!q.e&&q.c.length==1||!o.c||!o.c[0])return k=new E(Math.pow(+D(q),_?o.s*(2-bj(o)):+D(o))),l?k.mod(l):k;if(p=o.s<0,l){if(l.c?!l.c[0]:!l.s)return new E(NaN);g=!p&&q.isInteger()&&l.isInteger(),g&&(q=q.mod(l))}else{if(o.e>9&&(q.e>0||q.e<-1||(q.e==0?q.c[0]>1||_&&q.c[1]>=24e7:q.c[0]<8e13||_&&q.c[0]<=9999975e7)))return m=q.s<0&&bj(o)?-0:0,q.e>-1&&(m=1/m),new E(p?1/m:m);T&&(m=te(T/R+2))}for(_?(c=new E(.5),p&&(o.s=1),h=bj(o)):(d=Math.abs(+D(o)),h=d%2),k=new E(r);;){if(h){if(k=k.times(q),!k.c)break;m?k.c.length>m&&(k.c.length=m):g&&(k=k.mod(l))}if(d){if(d=qA(d/2),d===0)break;h=d%2}else if(o=o.times(c),W(o,o.e+1,1),o.e>14)h=bj(o);else{if(d=+D(o),d===0)break;h=d%2}q=q.times(q),m?q.c&&q.c.length>m&&(q.c.length=m):g&&(q=q.mod(l))}return g?k:(p&&(k=r.div(k)),l?k.mod(l):m?W(k,T,i,b):k)},t.integerValue=function(o){var l=new E(this);return o==null?o=i:jA(o,0,8),W(l,l.e+1,o)},t.isEqualTo=t.eq=function(o,l){return UA(this,new E(o,l))===0},t.isFinite=function(){return!!this.c},t.isGreaterThan=t.gt=function(o,l){return UA(this,new E(o,l))>0},t.isGreaterThanOrEqualTo=t.gte=function(o,l){return(l=UA(this,new E(o,l)))===1||l===0},t.isInteger=function(){return!!this.c&&IA(this.e/R)>this.c.length-2},t.isLessThan=t.lt=function(o,l){return UA(this,new E(o,l))<0},t.isLessThanOrEqualTo=t.lte=function(o,l){return(l=UA(this,new E(o,l)))===-1||l===0},t.isNaN=function(){return!this.s},t.isNegative=function(){return this.s<0},t.isPositive=function(){return this.s>0},t.isZero=function(){return!!this.c&&this.c[0]==0},t.minus=function(o,l){var c,g,d,m,b=this,_=b.s;if(o=new E(o,l),l=o.s,!_||!l)return new E(NaN);if(_!=l)return o.s=-l,b.plus(o);var p=b.e/R,h=o.e/R,k=b.c,q=o.c;if(!p||!h){if(!k||!q)return k?(o.s=-l,o):new E(q?b:NaN);if(!k[0]||!q[0])return q[0]?(o.s=-l,o):new E(k[0]?b:i==3?-0:0)}if(p=IA(p),h=IA(h),k=k.slice(),_=p-h){for((m=_<0)?(_=-_,d=k):(h=p,d=q),d.reverse(),l=_;l--;d.push(0));d.reverse()}else for(g=(m=(_=k.length)<(l=q.length))?_:l,_=l=0;l<g;l++)if(k[l]!=q[l]){m=k[l]<q[l];break}if(m&&(d=k,k=q,q=d,o.s=-o.s),l=(g=q.length)-(c=k.length),l>0)for(;l--;k[c++]=0);for(l=yA-1;g>_;){if(k[--g]<q[g]){for(c=g;c&&!k[--c];k[c]=l);--k[c],k[g]+=yA}k[g]-=q[g]}for(;k[0]==0;k.splice(0,1),--h);return k[0]?oA(o,k,h):(o.s=i==3?-1:1,o.c=[o.e=0],o)},t.modulo=t.mod=function(o,l){var c,g,d=this;return o=new E(o,l),!d.c||!o.s||o.c&&!o.c[0]?new E(NaN):!o.c||d.c&&!d.c[0]?new E(d):($==9?(g=o.s,o.s=1,c=A(d,o,0,3),o.s=g,c.s*=g):c=A(d,o,0,$),o=d.minus(c.times(o)),!o.c[0]&&$==1&&(o.s=d.s),o)},t.multipliedBy=t.times=function(o,l){var c,g,d,m,b,_,p,h,k,q,S,G,J,rA,aA,X=this,U=X.c,dA=(o=new E(o,l)).c;if(!U||!dA||!U[0]||!dA[0])return!X.s||!o.s||U&&!U[0]&&!dA||dA&&!dA[0]&&!U?o.c=o.e=o.s=null:(o.s*=X.s,!U||!dA?o.c=o.e=null:(o.c=[0],o.e=0)),o;for(g=IA(X.e/R)+IA(o.e/R),o.s*=X.s,p=U.length,q=dA.length,p<q&&(J=U,U=dA,dA=J,d=p,p=q,q=d),d=p+q,J=[];d--;J.push(0));for(rA=yA,aA=HA,d=q;--d>=0;){for(c=0,S=dA[d]%aA,G=dA[d]/aA|0,b=p,m=d+b;m>d;)h=U[--b]%aA,k=U[b]/aA|0,_=G*h+k*S,h=S*h+_%aA*aA+J[m]+c,c=(h/rA|0)+(_/aA|0)+G*k,J[m--]=h%rA;J[m]=c}return c?++g:J.splice(0,1),oA(o,J,g)},t.negated=function(){var o=new E(this);return o.s=-o.s||null,o},t.plus=function(o,l){var c,g=this,d=g.s;if(o=new E(o,l),l=o.s,!d||!l)return new E(NaN);if(d!=l)return o.s=-l,g.minus(o);var m=g.e/R,b=o.e/R,_=g.c,p=o.c;if(!m||!b){if(!_||!p)return new E(d/0);if(!_[0]||!p[0])return p[0]?o:new E(_[0]?g:d*0)}if(m=IA(m),b=IA(b),_=_.slice(),d=m-b){for(d>0?(b=m,c=p):(d=-d,c=_),c.reverse();d--;c.push(0));c.reverse()}for(d=_.length,l=p.length,d-l<0&&(c=p,p=_,_=c,l=d),d=0;l;)d=(_[--l]=_[l]+p[l]+d)/yA|0,_[l]=yA===_[l]?0:_[l]%yA;return d&&(_=[d].concat(_),++b),oA(o,_,b)},t.precision=t.sd=function(o,l){var c,g,d,m=this;if(o!=null&&o!==!!o)return jA(o,1,lA),l==null?l=i:jA(l,0,8),W(new E(m),o,l);if(!(c=m.c))return null;if(d=c.length-1,g=d*R+1,d=c[d]){for(;d%10==0;d/=10,g--);for(d=c[0];d>=10;d/=10,g++);}return o&&m.e+1>g&&(g=m.e+1),g},t.shiftedBy=function(o){return jA(o,-re,re),this.times("1e"+o)},t.squareRoot=t.sqrt=function(){var o,l,c,g,d,m=this,b=m.c,_=m.s,p=m.e,h=s+4,k=new E("0.5");if(_!==1||!b||!b[0])return new E(!_||_<0&&(!b||b[0])?NaN:b?m:1/0);if(_=Math.sqrt(+D(m)),_==0||_==1/0?(l=wA(b),(l.length+p)%2==0&&(l+="0"),_=Math.sqrt(+l),p=IA((p+1)/2)-(p<0||p%2),_==1/0?l="5e"+p:(l=_.toExponential(),l=l.slice(0,l.indexOf("e")+1)+p),c=new E(l)):c=new E(_+""),c.c[0]){for(p=c.e,_=p+h,_<3&&(_=0);;)if(d=c,c=k.times(d.plus(A(m,d,h,1))),wA(d.c).slice(0,_)===(l=wA(c.c)).slice(0,_))if(c.e<p&&--_,l=l.slice(_-3,_+1),l=="9999"||!g&&l=="4999"){if(!g&&(W(d,d.e+s+2,0),d.times(d).eq(m))){c=d;break}h+=4,_+=4,g=1}else{(!+l||!+l.slice(1)&&l.charAt(0)=="5")&&(W(c,c.e+s+2,1),o=!c.times(c).eq(m));break}}return W(c,c.e+s+1,i,o)},t.toExponential=function(o,l){return o!=null&&(jA(o,0,lA),o++),M(this,o,l,1)},t.toFixed=function(o,l){return o!=null&&(jA(o,0,lA),o=o+this.e+1),M(this,o,l)},t.toFormat=function(o,l,c){var g,d=this;if(c==null)o!=null&&l&&typeof l=="object"?(c=l,l=null):o&&typeof o=="object"?(c=o,o=l=null):c=v;else if(typeof c!="object")throw Error(fA+"Argument not an object: "+c);if(g=d.toFixed(o,l),d.c){var m,b=g.split("."),_=+c.groupSize,p=+c.secondaryGroupSize,h=c.groupSeparator||"",k=b[0],q=b[1],S=d.s<0,G=S?k.slice(1):k,J=G.length;if(p&&(m=_,_=p,p=m,J-=m),_>0&&J>0){for(m=J%_||_,k=G.substr(0,m);m<J;m+=_)k+=h+G.substr(m,_);p>0&&(k+=h+G.slice(m)),S&&(k="-"+k)}g=q?k+(c.decimalSeparator||"")+((p=+c.fractionGroupSize)?q.replace(new RegExp("\\d{"+p+"}\\B","g"),"$&"+(c.fractionGroupSeparator||"")):q):k}return(c.prefix||"")+g+(c.suffix||"")},t.toFraction=function(o){var l,c,g,d,m,b,_,p,h,k,q,S,G=this,J=G.c;if(o!=null&&(_=new E(o),!_.isInteger()&&(_.c||_.s!==1)||_.lt(r)))throw Error(fA+"Argument "+(_.isInteger()?"out of range: ":"not an integer: ")+D(_));if(!J)return new E(G);for(l=new E(r),h=c=new E(r),g=p=new E(r),S=wA(J),m=l.e=S.length-G.e-1,l.c[0]=ne[(b=m%R)<0?R+b:b],o=!o||_.comparedTo(l)>0?m>0?l:h:_,b=P,P=1/0,_=new E(S),p.c[0]=0;k=A(_,l,0,1),d=c.plus(k.times(g)),d.comparedTo(o)!=1;)c=g,g=d,h=p.plus(k.times(d=h)),p=d,l=_.minus(k.times(d=l)),_=d;return d=A(o.minus(c),g,0,1),p=p.plus(d.times(h)),c=c.plus(d.times(g)),p.s=h.s=G.s,m=m*2,q=A(h,g,m,i).minus(G).abs().comparedTo(A(p,c,m,i).minus(G).abs())<1?[h,g]:[p,c],P=b,q},t.toNumber=function(){return+D(this)},t.toPrecision=function(o,l){return o!=null&&jA(o,1,lA),M(this,o,l,2)},t.toString=function(o){var l,c=this,g=c.s,d=c.e;return d===null?g?(l="Infinity",g<0&&(l="-"+l)):l="NaN":(o==null?l=d<=a||d>=B?Ej(wA(c.c),d):RA(wA(c.c),d,"0"):o===10&&N?(c=W(new E(c),s+d+1,i),l=RA(wA(c.c),c.e,"0")):(jA(o,2,x.length,"Base"),l=j(RA(wA(c.c),d,"0"),10,o,g,!0)),g<0&&c.c[0]&&(l="-"+l)),l},t.valueOf=t.toJSON=function(){return D(this)},t._isBigNumber=!0,t[Symbol.toStringTag]="BigNumber",t[Symbol.for("nodejs.util.inspect.custom")]=t.valueOf,n!=null&&E.set(n),E}function IA(n){var A=n|0;return n>0||n===A?A:A-1}function wA(n){for(var A,j,e=1,t=n.length,r=n[0]+"";e<t;){for(A=n[e++]+"",j=R-A.length;j--;A="0"+A);r+=A}for(t=r.length;r.charCodeAt(--t)===48;);return r.slice(0,t+1||1)}function UA(n,A){var j,e,t=n.c,r=A.c,s=n.s,i=A.s,a=n.e,B=A.e;if(!s||!i)return null;if(j=t&&!t[0],e=r&&!r[0],j||e)return j?e?0:-i:s;if(s!=i)return s;if(j=s<0,e=a==B,!t||!r)return e?0:!t^j?1:-1;if(!e)return a>B^j?1:-1;for(i=(a=t.length)<(B=r.length)?a:B,s=0;s<i;s++)if(t[s]!=r[s])return t[s]>r[s]^j?1:-1;return a==B?0:a>B^j?1:-1}function jA(n,A,j,e){if(n<A||n>j||n!==qA(n))throw Error(fA+(e||"Argument")+(typeof n=="number"?n<A||n>j?" out of range: ":" not an integer: ":" not a primitive number: ")+String(n))}function bj(n){var A=n.c.length-1;return IA(n.e/R)==A&&n.c[A]%2!=0}function Ej(n,A){return(n.length>1?n.charAt(0)+"."+n.slice(1):n)+(A<0?"e":"e+")+A}function RA(n,A,j){var e,t;if(A<0){for(t=j+".";++A;t+=j);n=t+n}else if(e=n.length,++A>e){for(t=j,A-=e;--A;t+=j);n+=t}else A<e&&(n=n.slice(0,A)+"."+n.slice(A));return n}var MA=ge();var Ct=12;MA.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Ct});var Q=K(0),$A=K(1),Wn=K("Infinity");function BA(n,A){let j=new MA(A.toString()),e=new MA(10).pow(j);return n.times(e)}function K(n){return new MA(n.toString())}var bA=(t=>(t.XYK="Xyk",t.LBP="Lbp",t.Stable="Stableswap",t.Omni="Omnipool",t))(bA||{}),sj=(r=>(r.UnknownError="UnknownError",r.InsufficientTradingAmount="InsufficientTradingAmount",r.MaxInRatioExceeded="MaxInRatioExceeded",r.MaxOutRatioExceeded="MaxOutRatioExceeded",r.TradeNotAllowed="TradeNotAllowed",r))(sj||{}),fe=(j=>(j.Buy="Buy",j.Sell="Sell",j))(fe||{});var se={};je(se,{__wbindgen_add_to_stack_pointer:()=>nr,__wbindgen_free:()=>or,__wbindgen_malloc:()=>sr,__wbindgen_realloc:()=>ir,calculate_in_given_out:()=>tr,calculate_linear_weights:()=>rr,calculate_out_given_in:()=>er,calculate_pool_trade_fee:()=>Ar,get_spot_price:()=>jr,instance:()=>xA,memory:()=>Yt,module:()=>Wt});var ke="./hydra_dx_wasm_bg-XLYSURO6.wasm";var Vt={};async function zt(n,A){if(typeof n=="string"){n.startsWith("./")&&(n=new URL(n,import.meta.url).href);let j=await fetch(n);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(j,A)}catch(e){if(j.headers.get("Content-Type")!="application/wasm")console.warn(e);else throw e}n=await j.arrayBuffer()}return await WebAssembly.instantiate(n,A)}var{instance:xA,module:Wt}=await zt(ke,Vt),Yt=xA.exports.memory,Ar=xA.exports.calculate_pool_trade_fee,jr=xA.exports.get_spot_price,er=xA.exports.calculate_out_given_in,tr=xA.exports.calculate_in_given_out,rr=xA.exports.calculate_linear_weights,nr=xA.exports.__wbindgen_add_to_stack_pointer,sr=xA.exports.__wbindgen_malloc,ir=xA.exports.__wbindgen_realloc,or=xA.exports.__wbindgen_free;var O;function he(n){O=n}var eA=0,Pj=null;function qj(){return(Pj===null||Pj.byteLength===0)&&(Pj=new Uint8Array(O.memory.buffer)),Pj}var ar=typeof TextEncoder>"u"?(0,module.require)("util").TextEncoder:TextEncoder,Ij=new ar("utf-8"),lr=typeof Ij.encodeInto=="function"?function(n,A){return Ij.encodeInto(n,A)}:function(n,A){let j=Ij.encode(n);return A.set(j),{read:n.length,written:j.length}};function sA(n,A,j){if(j===void 0){let i=Ij.encode(n),a=A(i.length,1)>>>0;return qj().subarray(a,a+i.length).set(i),eA=i.length,a}let e=n.length,t=A(e,1)>>>0,r=qj(),s=0;for(;s<e;s++){let i=n.charCodeAt(s);if(i>127)break;r[t+s]=i}if(s!==e){s!==0&&(n=n.slice(s)),t=j(t,e,e=s+n.length*3,1)>>>0;let i=qj().subarray(t+s,t+e),a=lr(n,i);s+=a.written}return eA=s,t}var wj=null;function GA(){return(wj===null||wj.byteLength===0)&&(wj=new Int32Array(O.memory.buffer)),wj}var cr=typeof TextDecoder>"u"?(0,module.require)("util").TextDecoder:TextDecoder,be=new cr("utf-8",{ignoreBOM:!0,fatal:!0});be.decode();function ij(n,A){return n=n>>>0,be.decode(qj().subarray(n,n+A))}function Ee(n,A,j){let e,t;try{let i=O.__wbindgen_add_to_stack_pointer(-16),a=sA(n,O.__wbindgen_malloc,O.__wbindgen_realloc),B=eA;O.calculate_pool_trade_fee(i,a,B,A,j);var r=GA()[i/4+0],s=GA()[i/4+1];return e=r,t=s,ij(r,s)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(e,t,1)}}function Pe(n,A,j,e,t){let r,s;try{let B=O.__wbindgen_add_to_stack_pointer(-16),f=sA(n,O.__wbindgen_malloc,O.__wbindgen_realloc),P=eA,I=sA(A,O.__wbindgen_malloc,O.__wbindgen_realloc),$=eA,T=sA(j,O.__wbindgen_malloc,O.__wbindgen_realloc),v=eA,x=sA(e,O.__wbindgen_malloc,O.__wbindgen_realloc),N=eA,E=sA(t,O.__wbindgen_malloc,O.__wbindgen_realloc),M=eA;O.get_spot_price(B,f,P,I,$,T,v,x,N,E,M);var i=GA()[B/4+0],a=GA()[B/4+1];return r=i,s=a,ij(i,a)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(r,s,1)}}function we(n,A,j,e,t){let r,s;try{let B=O.__wbindgen_add_to_stack_pointer(-16),f=sA(n,O.__wbindgen_malloc,O.__wbindgen_realloc),P=eA,I=sA(A,O.__wbindgen_malloc,O.__wbindgen_realloc),$=eA,T=sA(j,O.__wbindgen_malloc,O.__wbindgen_realloc),v=eA,x=sA(e,O.__wbindgen_malloc,O.__wbindgen_realloc),N=eA,E=sA(t,O.__wbindgen_malloc,O.__wbindgen_realloc),M=eA;O.calculate_out_given_in(B,f,P,I,$,T,v,x,N,E,M);var i=GA()[B/4+0],a=GA()[B/4+1];return r=i,s=a,ij(i,a)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(r,s,1)}}function qe(n,A,j,e,t){let r,s;try{let B=O.__wbindgen_add_to_stack_pointer(-16),f=sA(n,O.__wbindgen_malloc,O.__wbindgen_realloc),P=eA,I=sA(A,O.__wbindgen_malloc,O.__wbindgen_realloc),$=eA,T=sA(j,O.__wbindgen_malloc,O.__wbindgen_realloc),v=eA,x=sA(e,O.__wbindgen_malloc,O.__wbindgen_realloc),N=eA,E=sA(t,O.__wbindgen_malloc,O.__wbindgen_realloc),M=eA;O.calculate_in_given_out(B,f,P,I,$,T,v,x,N,E,M);var i=GA()[B/4+0],a=GA()[B/4+1];return r=i,s=a,ij(i,a)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(r,s,1)}}function Ie(n,A,j,e,t){let r,s;try{let B=O.__wbindgen_add_to_stack_pointer(-16),f=sA(n,O.__wbindgen_malloc,O.__wbindgen_realloc),P=eA,I=sA(A,O.__wbindgen_malloc,O.__wbindgen_realloc),$=eA,T=sA(j,O.__wbindgen_malloc,O.__wbindgen_realloc),v=eA,x=sA(e,O.__wbindgen_malloc,O.__wbindgen_realloc),N=eA,E=sA(t,O.__wbindgen_malloc,O.__wbindgen_realloc),M=eA;O.calculate_linear_weights(B,f,P,I,$,T,v,x,N,E,M);var i=GA()[B/4+0],a=GA()[B/4+1];return r=i,s=a,ij(i,a)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(r,s,1)}}he(se);var FA=class{static getSpotPrice(A,j,e,t,r){return Pe(A,j,e,t,r)}static calculateInGivenOut(A,j,e,t,r){return qe(A,j,e,t,r)}static calculateOutGivenIn(A,j,e,t,r){return we(A,j,e,t,r)}static calculateLinearWeights(A,j,e,t,r){return Ie(A,j,e,t,r)}static calculatePoolTradeFee(A,j,e){return Ee(A,j,e)}};import{encodeAddress as Br}from"@polkadot/util-crypto";import{stringToU8a as ur}from"@polkadot/util";var oj=18,ie=15,XA="0",cs=12,Bs=2034,aj=63,us=2090,oe=1e3,$j=Br(ur("modlomnipool".padEnd(32,"\0")),aj);function $e(n,A){let j;return JSON.stringify(n,(e,t)=>(t&&t[A]&&(j=t),t)),j}function ds(n,A,j){let e;return JSON.stringify(n,(t,r)=>(r&&r[A]===j&&(e=r),r)),e}import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";var WA=class{api;constructor(A){this.api=A}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var lj=class extends WA{SUPPORTED_TYPES=["StableSwap","Bond","Token","External"];constructor(A){super(A)}async safeSharesQuery(){try{let A=await this.api.query.stableswap.pools.entries();return new Map(A.map(([{args:[j]},e])=>[j.toString(),e.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let A=await this.api.query.bonds.bonds.entries();return new Map(A.map(([{args:[j]},e])=>[j.toString(),e.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let A=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(A.map(([{args:[j]},e])=>{let{decimals:t,symbol:r}=e.unwrap();return[j.toString(),{decimals:t.toNumber(),symbol:r.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let A=await this.api.query.assetRegistry.assetLocations.entries();return new Map(A.map(([{args:[j]},e])=>[j.toString(),e.unwrap()]))}catch{return new Map([])}}getToken(A,j,e,t){if(A==XA){let P=this.api.consts.balances.existentialDeposit;return{id:XA,name:this.chainToken,symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:P.toString()}}let{name:r,assetType:s,isSufficient:i,existentialDeposit:a}=j,{symbol:B,decimals:f}=e.get(A)??{};return{id:A,name:r.toHuman(),symbol:B,decimals:f,icon:B,type:s.toHuman(),isSufficient:i?i.toHuman():!0,origin:this.parseLocation("parachain",t),existentialDeposit:a.toString()}}getBond(A,j,e,t){let[r,s]=t,{assetType:i,isSufficient:a,existentialDeposit:B}=j,{symbol:f,decimals:P}=this.getToken(r.toString(),j,e),I=s.toNumber(),$=new Intl.DateTimeFormat("en-GB"),T=[f,"Bond",$.format(I)].join(" ");return{id:A,name:T,symbol:f+"b",decimals:P,icon:f,type:i.toString(),isSufficient:a.toHuman(),existentialDeposit:B.toString()}}getShares(A,j,e,t){let{assets:r}=t,{name:s,symbol:i,assetType:a,isSufficient:B,existentialDeposit:f}=j,I=r.map(v=>v.toString()).map(v=>{let{symbol:x}=this.getToken(v,j,e);return[v,x]}),$=Object.fromEntries(I),T=Object.values($);return{id:A,name:T.join(", "),symbol:i?.isSome?i.toHuman():s.toHuman(),decimals:18,icon:T.join("/"),type:a.toString(),isSufficient:B.toHuman(),existentialDeposit:f.toString(),meta:$}}getExternal(A,j,e,t){let r=this.getToken(A,j,new Map,t),s=this.parseLocation("generalIndex",t),i=e?.find(a=>a.id===s?.toString());return i?{...r,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol}:r}normalizeMetadata(A,j){return j.size?j:new Map(A.map(([{args:[e]},t])=>{let{decimals:r,symbol:s}=t.unwrap();return[e.toString(),{decimals:Number(r.toString()),symbol:s.toHuman()}]}))}getSupportedAssets(A){return A.filter(([j,e])=>{if(e.isNone)return!1;let t=e.unwrap();return this.isSupportedAsset(t)})}async getOnChainAssets(A){let[j,e,t,r,s]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),i=this.getSupportedAssets(j),a=this.normalizeMetadata(i,s);return i.map(([{args:[B]},f])=>{let P=f.unwrap(),I=e.get(B.toString()),{assetType:$}=P;switch($.toString()){case"Bond":let T=r.get(B.toString());return this.getBond(B.toString(),P,a,T);case"StableSwap":let v=t.get(B.toString());return this.getShares(B.toString(),P,a,v);case"External":return this.getExternal(B.toString(),P,A,I);default:return this.getToken(B.toString(),P,a,I)}}).filter(B=>this.isValidAsset(B))}isValidAsset(A){return!!A.symbol&&!!A.decimals}isSupportedAsset(A){let j=A.assetType.toString();return this.SUPPORTED_TYPES.includes(j)}parseLocation(A,j){if(j){let e=$e(j.toJSON(),A);return e&&e[A]}else return}};var cj=class extends WA{constructor(A){super(A)}async getBalance(A,j){return j===XA?await this.getSystemBalance(A):await this.getTokenBalance(A,j)}async getSystemBalance(A){let{data:j}=await this.api.query.system.account(A);return this.calculateFreeBalance(j)}async getTokenBalance(A,j){let{free:e,reserved:t,frozen:r}=await this.api.query.tokens.accounts(A,j);return this.calculateFreeBalance({free:e,feeFrozen:t,frozen:r})}async subscribeBalance(A,j,e){let t=j.filter(r=>r!==XA).map(r=>[A,r]);return this.api.query.tokens.accounts.multi(t,r=>{r.forEach(({free:s,reserved:i,frozen:a},B)=>{let f=this.calculateFreeBalance({free:s,feeFrozen:i,frozen:a}),P=t[B][1];e(P,f)})})}async subscribeTokenBalance(A,j,e){let t=j.filter(r=>r!==XA).map(r=>[A,r]);return this.api.query.tokens.accounts.multi(t,r=>{r.forEach((s,i)=>{let a=this.calculateFreeBalance(s),B=t[i][1];e(B,a)})})}async subscribeSystemBalance(A,j){return this.api.query.system.account(A,({data:e})=>j(XA,this.calculateFreeBalance(e)))}calculateFreeBalance(A){let{free:j,miscFrozen:e,feeFrozen:t,frozen:r}=A,s=new MA(j),i=new MA(e||r),a=new MA(t||0),B=i.gt(a)?i:a;return s.minus(B)}};var KA=class extends cj{pools=[];subs=[];poolsLoaded=!1;constructor(A){super(A)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let A=this.pools.map(async e=>{let t=[await this.subscribePoolChange(e),await this.subscribeTokensPoolBalance(e),await this.subscribeSystemPoolBalance(e)];if(this.hasShareAsset(e)){let r=await this.subscribeSharePoolBalance(e);t.push(r)}return this.subscribeLog(e),t});return(await Promise.all(A)).flat()}subscribeLog(A){let j=A.address.substring(0,10).concat("...");console.log(`${A.type} [${j}] balance subscribed`)}unsubscribe(){this.subs.forEach(A=>{A()})}hasShareAsset(A){return A.type==="Stableswap"&&A.id}subscribeTokensPoolBalance(A){return this.subscribeTokenBalance(A.address,A.tokens.map(j=>j.id),this.updateBalanceCallback(A,(j,e)=>j.id!==e))}subscribeSharePoolBalance(A){return this.subscribeTokenBalance($j,[A.id],this.updateBalanceCallback(A,()=>!0))}subscribeSystemPoolBalance(A){return this.subscribeSystemBalance(A.address,this.updateBalanceCallback(A,()=>!0))}updateBalanceCallback(A,j){return function(e,t){let r=A.tokens.findIndex(s=>s.id==e);r>=0&&j(A,e)&&(A.tokens[r].balance=t.toString())}}};var Tj=class extends KA{MAX_FINAL_WEIGHT=BA(K(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[A,j]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:e}=j.unwrap(),t=A.filter(([r,s])=>this.isActivePool(s.unwrap(),e)).map(async([{args:[r]},s])=>{let i=s.unwrap(),a=r.toString(),B=await this.getPoolDelta(a,i,e.toString());return this.poolsData.set(r.toString(),i),{address:a,type:"Lbp",fee:i.fee.toJSON(),...B,...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(A,j){let e=this.pools.find(t=>t.address===j);return{repayFee:this.getRepayFee(),exchangeFee:e.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(A){return this.api.query.parachainSystem.validationData(async j=>{let{relayParentNumber:e}=j.unwrap(),t=this.poolsData.get(A.address);if(this.isActivePool(t,e)){let s=await this.getPoolDelta(A.address,t,e.toString());Object.assign(A,s)}else{let s=this.pools.findIndex(i=>i.address==A.address);this.pools.splice(s,1)}})}async getPoolDelta(A,j,e){let{start:t,end:r,assets:s,initialWeight:i,finalWeight:a,repayTarget:B,feeCollector:f}=j,P=FA.calculateLinearWeights(t.toString(),r.toString(),i.toString(),a.toString(),e),[I,$]=s,T=I.toString(),v=K(P),x=$.toString(),N=this.MAX_FINAL_WEIGHT.minus(K(v)),[E,M,tA]=await Promise.all([this.isRepayFeeApplied(T,B.toString(),f.toString()),this.getBalance(A,T),this.getBalance(A,x)]);return{repayFeeApply:E,tokens:[{id:T,weight:v,balance:M.toString()},{id:x,weight:N,balance:tA.toString()}]}}isActivePool(A,j){if(A.start.isEmpty||A.end.isEmpty)return!1;let e=A.start.unwrap().toNumber(),t=A.end.unwrap().toNumber();return j.toNumber()>=e&&j.toNumber()<t}async isRepayFeeApplied(A,j,e){let t=K(j);if(t.isZero())return!1;try{return(await this.getBalance(A,e)).isLessThan(t)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let A=this.api.consts.lbp.maxInRatio.toJSON(),j=this.api.consts.lbp.maxOutRatio.toJSON(),e=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:A,maxOutRatio:j,minTradingLimit:e}}};import{encodeAddress as _r}from"@polkadot/util-crypto";import{stringToU8a as dr}from"@polkadot/util";function uA(n,A){return n.shiftedBy(-1*A).toString()}function TA(n){return n[0]/n[1]*100}function kA(n){return n[0]/n[1]}function OA(n){return[n/oe,oe]}var vj=class extends KA{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let A=this.api.consts.omnipool.hubAssetId.toString(),j=this.getPoolId(),[e,t,r]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(j,A)]),s=e.map(async([{args:[a]},B])=>{let{hubReserve:f,shares:P,tradable:I}=B.unwrap(),$=await this.getBalance(j,a.toString());return{id:a.toString(),hubReserves:K(f.toString()),shares:K(P.toString()),tradeable:I.bits.toNumber(),balance:$.toString()}}),i=await Promise.all(s);return i.push({id:A,tradeable:t.bits.toNumber(),balance:r.toString()}),[{address:j,type:"Omnipool",hubAssetId:A,tokens:i,...this.getPoolLimits()}]}async getPoolFees(A,j){let e=await this.api.query.dynamicFees.assetFee(A),t=this.api.consts.dynamicFees.assetFeeParameters,r=this.api.consts.dynamicFees.protocolFeeParameters,s=t.minFee.toNumber()+r.minFee.toNumber(),i=t.maxFee.toNumber()+r.maxFee.toNumber();if(e.isSome){let{assetFee:a,protocolFee:B}=e.unwrap();return{assetFee:OA(a.toNumber()),protocolFee:OA(B.toNumber()),min:OA(s),max:OA(i)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:OA(s),max:OA(i)}}getPoolType(){return"Omnipool"}async subscribePoolChange(A){let j=A.tokens.map(e=>e.id);return this.api.query.omnipool.assets.multi(j,e=>{A.tokens=e.map((t,r)=>{let s=A.tokens[r];if(t.isNone)return s;let i=t.unwrap();return this.updateTokenState(s,i)})})}updateTokenState(A,j){let{hubReserve:e,shares:t,tradable:r}=j;return{...A,hubReserves:K(e.toString()),shares:K(t.toString()),tradeable:r.bits.toNumber()}}getAssetFee(){let j=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return OA(j)}getProtocolFee(){let j=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return OA(j)}getPoolId(){return _r(dr("modlomnipool".padEnd(32,"\0")),aj)}getPoolLimits(){let A=this.api.consts.omnipool.maxInRatio.toJSON(),j=this.api.consts.omnipool.maxOutRatio.toJSON(),e=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:A,maxOutRatio:j,minTradingLimit:e}}};var yj=class extends KA{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let j=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[e]},t])=>{let r=e.toString(),[s,i]=t.unwrap(),[a,B]=await Promise.all([this.getBalance(r,s.toString()),this.getBalance(r,i.toString())]);return{address:r,type:"Xyk",tokens:[{id:s.toString(),balance:a.toString()},{id:i.toString(),balance:B.toString()}],...this.getPoolLimits()}});return Promise.all(j)}async getPoolFees(A,j){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(A){return this.api.query.xyk.poolAssets(A.address,j=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let A=this.api.consts.xyk.maxInRatio.toJSON(),j=this.api.consts.xyk.maxOutRatio.toJSON(),e=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:A,maxOutRatio:j,minTradingLimit:e}}};import{blake2AsHex as Nr,encodeAddress as Rr}from"@polkadot/util-crypto";var ae={};je(ae,{__wbindgen_add_to_stack_pointer:()=>vr,__wbindgen_free:()=>Fr,__wbindgen_malloc:()=>yr,__wbindgen_realloc:()=>xr,calculate_add_one_asset:()=>Ir,calculate_amplification:()=>Pr,calculate_in_given_out:()=>Er,calculate_liquidity_out_one_asset:()=>Tr,calculate_out_given_in:()=>br,calculate_pool_trade_fee:()=>hr,calculate_shares:()=>wr,calculate_shares_for_amount:()=>qr,instance:()=>gA,memory:()=>kr,module:()=>fr,pool_account_name:()=>$r});var Te="./hydra_dx_wasm_bg-ZZD3PUVC.wasm";var mr={};async function gr(n,A){if(typeof n=="string"){n.startsWith("./")&&(n=new URL(n,import.meta.url).href);let j=await fetch(n);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(j,A)}catch(e){if(j.headers.get("Content-Type")!="application/wasm")console.warn(e);else throw e}n=await j.arrayBuffer()}return await WebAssembly.instantiate(n,A)}var{instance:gA,module:fr}=await gr(Te,mr),kr=gA.exports.memory,hr=gA.exports.calculate_pool_trade_fee,br=gA.exports.calculate_out_given_in,Er=gA.exports.calculate_in_given_out,Pr=gA.exports.calculate_amplification,wr=gA.exports.calculate_shares,qr=gA.exports.calculate_shares_for_amount,Ir=gA.exports.calculate_add_one_asset,$r=gA.exports.pool_account_name,Tr=gA.exports.calculate_liquidity_out_one_asset,vr=gA.exports.__wbindgen_add_to_stack_pointer,yr=gA.exports.__wbindgen_malloc,xr=gA.exports.__wbindgen_realloc,Fr=gA.exports.__wbindgen_free;var w;function ve(n){w=n}var L=0,xj=null;function Bj(){return(xj===null||xj.byteLength===0)&&(xj=new Uint8Array(w.memory.buffer)),xj}var Or=typeof TextEncoder>"u"?(0,module.require)("util").TextEncoder:TextEncoder,Oj=new Or("utf-8"),Sr=typeof Oj.encodeInto=="function"?function(n,A){return Oj.encodeInto(n,A)}:function(n,A){let j=Oj.encode(n);return A.set(j),{read:n.length,written:j.length}};function H(n,A,j){if(j===void 0){let i=Oj.encode(n),a=A(i.length,1)>>>0;return Bj().subarray(a,a+i.length).set(i),L=i.length,a}let e=n.length,t=A(e,1)>>>0,r=Bj(),s=0;for(;s<e;s++){let i=n.charCodeAt(s);if(i>127)break;r[t+s]=i}if(s!==e){s!==0&&(n=n.slice(s)),t=j(t,e,e=s+n.length*3,1)>>>0;let i=Bj().subarray(t+s,t+e),a=Sr(n,i);s+=a.written}return L=s,t}var Fj=null;function cA(){return(Fj===null||Fj.byteLength===0)&&(Fj=new Int32Array(w.memory.buffer)),Fj}var Gr=typeof TextDecoder>"u"?(0,module.require)("util").TextDecoder:TextDecoder,ye=new Gr("utf-8",{ignoreBOM:!0,fatal:!0});ye.decode();function JA(n,A){return n=n>>>0,ye.decode(Bj().subarray(n,n+A))}function xe(n,A,j){let e,t;try{let i=w.__wbindgen_add_to_stack_pointer(-16),a=H(n,w.__wbindgen_malloc,w.__wbindgen_realloc),B=L;w.calculate_pool_trade_fee(i,a,B,A,j);var r=cA()[i/4+0],s=cA()[i/4+1];return e=r,t=s,JA(r,s)}finally{w.__wbindgen_add_to_stack_pointer(16),w.__wbindgen_free(e,t,1)}}function Fe(n,A,j,e,t,r){let s,i;try{let f=w.__wbindgen_add_to_stack_pointer(-16),P=H(n,w.__wbindgen_malloc,w.__wbindgen_realloc),I=L,$=H(e,w.__wbindgen_malloc,w.__wbindgen_realloc),T=L,v=H(t,w.__wbindgen_malloc,w.__wbindgen_realloc),x=L,N=H(r,w.__wbindgen_malloc,w.__wbindgen_realloc),E=L;w.calculate_out_given_in(f,P,I,A,j,$,T,v,x,N,E);var a=cA()[f/4+0],B=cA()[f/4+1];return s=a,i=B,JA(a,B)}finally{w.__wbindgen_add_to_stack_pointer(16),w.__wbindgen_free(s,i,1)}}function Oe(n,A,j,e,t,r){let s,i;try{let f=w.__wbindgen_add_to_stack_pointer(-16),P=H(n,w.__wbindgen_malloc,w.__wbindgen_realloc),I=L,$=H(e,w.__wbindgen_malloc,w.__wbindgen_realloc),T=L,v=H(t,w.__wbindgen_malloc,w.__wbindgen_realloc),x=L,N=H(r,w.__wbindgen_malloc,w.__wbindgen_realloc),E=L;w.calculate_in_given_out(f,P,I,A,j,$,T,v,x,N,E);var a=cA()[f/4+0],B=cA()[f/4+1];return s=a,i=B,JA(a,B)}finally{w.__wbindgen_add_to_stack_pointer(16),w.__wbindgen_free(s,i,1)}}function Se(n,A,j,e,t){let r,s;try{let B=w.__wbindgen_add_to_stack_pointer(-16),f=H(n,w.__wbindgen_malloc,w.__wbindgen_realloc),P=L,I=H(A,w.__wbindgen_malloc,w.__wbindgen_realloc),$=L,T=H(j,w.__wbindgen_malloc,w.__wbindgen_realloc),v=L,x=H(e,w.__wbindgen_malloc,w.__wbindgen_realloc),N=L,E=H(t,w.__wbindgen_malloc,w.__wbindgen_realloc),M=L;w.calculate_amplification(B,f,P,I,$,T,v,x,N,E,M);var i=cA()[B/4+0],a=cA()[B/4+1];return r=i,s=a,JA(i,a)}finally{w.__wbindgen_add_to_stack_pointer(16),w.__wbindgen_free(r,s,1)}}function Ge(n,A,j,e,t){let r,s;try{let B=w.__wbindgen_add_to_stack_pointer(-16),f=H(n,w.__wbindgen_malloc,w.__wbindgen_realloc),P=L,I=H(A,w.__wbindgen_malloc,w.__wbindgen_realloc),$=L,T=H(j,w.__wbindgen_malloc,w.__wbindgen_realloc),v=L,x=H(e,w.__wbindgen_malloc,w.__wbindgen_realloc),N=L,E=H(t,w.__wbindgen_malloc,w.__wbindgen_realloc),M=L;w.calculate_shares(B,f,P,I,$,T,v,x,N,E,M);var i=cA()[B/4+0],a=cA()[B/4+1];return r=i,s=a,JA(i,a)}finally{w.__wbindgen_add_to_stack_pointer(16),w.__wbindgen_free(r,s,1)}}function Ke(n,A,j,e,t,r){let s,i;try{let f=w.__wbindgen_add_to_stack_pointer(-16),P=H(n,w.__wbindgen_malloc,w.__wbindgen_realloc),I=L,$=H(j,w.__wbindgen_malloc,w.__wbindgen_realloc),T=L,v=H(e,w.__wbindgen_malloc,w.__wbindgen_realloc),x=L,N=H(t,w.__wbindgen_malloc,w.__wbindgen_realloc),E=L,M=H(r,w.__wbindgen_malloc,w.__wbindgen_realloc),tA=L;w.calculate_shares_for_amount(f,P,I,A,$,T,v,x,N,E,M,tA);var a=cA()[f/4+0],B=cA()[f/4+1];return s=a,i=B,JA(a,B)}finally{w.__wbindgen_add_to_stack_pointer(16),w.__wbindgen_free(s,i,1)}}function Ne(n,A,j,e,t,r){let s,i;try{let f=w.__wbindgen_add_to_stack_pointer(-16),P=H(n,w.__wbindgen_malloc,w.__wbindgen_realloc),I=L,$=H(A,w.__wbindgen_malloc,w.__wbindgen_realloc),T=L,v=H(e,w.__wbindgen_malloc,w.__wbindgen_realloc),x=L,N=H(t,w.__wbindgen_malloc,w.__wbindgen_realloc),E=L,M=H(r,w.__wbindgen_malloc,w.__wbindgen_realloc),tA=L;w.calculate_add_one_asset(f,P,I,$,T,j,v,x,N,E,M,tA);var a=cA()[f/4+0],B=cA()[f/4+1];return s=a,i=B,JA(a,B)}finally{w.__wbindgen_add_to_stack_pointer(16),w.__wbindgen_free(s,i,1)}}function Kr(n,A){return n=n>>>0,Bj().subarray(n/1,n/1+A)}function Re(n){try{let t=w.__wbindgen_add_to_stack_pointer(-16);w.pool_account_name(t,n);var A=cA()[t/4+0],j=cA()[t/4+1],e=Kr(A,j).slice();return w.__wbindgen_free(A,j*1),e}finally{w.__wbindgen_add_to_stack_pointer(16)}}function Me(n,A,j,e,t,r){let s,i;try{let f=w.__wbindgen_add_to_stack_pointer(-16),P=H(n,w.__wbindgen_malloc,w.__wbindgen_realloc),I=L,$=H(A,w.__wbindgen_malloc,w.__wbindgen_realloc),T=L,v=H(e,w.__wbindgen_malloc,w.__wbindgen_realloc),x=L,N=H(t,w.__wbindgen_malloc,w.__wbindgen_realloc),E=L,M=H(r,w.__wbindgen_malloc,w.__wbindgen_realloc),tA=L;w.calculate_liquidity_out_one_asset(f,P,I,$,T,j,v,x,N,E,M,tA);var a=cA()[f/4+0],B=cA()[f/4+1];return s=a,i=B,JA(a,B)}finally{w.__wbindgen_add_to_stack_pointer(16),w.__wbindgen_free(s,i,1)}}ve(ae);var hA=class{static getPoolAddress(A){return Re(A)}static calculateAmplification(A,j,e,t,r){return Se(A,j,e,t,r)}static calculateInGivenOut(A,j,e,t,r,s){return Oe(A,j,e,t,r,s)}static calculateAddOneAsset(A,j,e,t,r,s){return Ne(A,j,e,t,r,s)}static calculateSharesForAmount(A,j,e,t,r,s){return Ke(A,j,e,t,r,s)}static calculateOutGivenIn(A,j,e,t,r,s){return Fe(A,j,e,t,r,s)}static calculateLiquidityOutOneAsset(A,j,e,t,r,s){return Me(A,j,e,t,r,s)}static calculateShares(A,j,e,t,r){return Ge(A,j,e,t,r)}static calculatePoolTradeFee(A,j,e){return xe(A,j,e)}};var Sj=class extends KA{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[A,j]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),e=j.toNumber(),t=A.map(async([{args:[r]},s])=>{let i=s.unwrap(),a=r.toString(),B=this.getPoolAddress(a),[f,P]=await Promise.all([this.getPoolDelta(a,i,e.toString()),this.getPoolTokens(B,a,i)]);return this.stablePools.set(B,i),{address:B,id:a,type:"Stableswap",fee:OA(i.fee.toNumber()),tokens:P,...f,...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(A,j){return{fee:this.pools.find(t=>t.address===j).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(A){return this.api.query.system.number(async j=>{let e=j.toNumber(),t=this.stablePools.get(A.address),r=await this.getPoolDelta(A.id,t,e.toString());Object.assign(A,r)})}async getPoolDelta(A,j,e){let{initialAmplification:t,finalAmplification:r,initialBlock:s,finalBlock:i}=j,a=hA.calculateAmplification(t.toString(),r.toString(),s.toString(),i.toString(),e),B=await this.api.query.tokens.totalIssuance(A);return{amplification:a,totalIssuance:B.toString()}}async getPoolTokens(A,j,e){let{assets:t}=e,r=t.map(async a=>{let[B,f]=await Promise.all([this.api.query.stableswap.assetTradability(j,a.toString()),this.getBalance(A,a.toString())]);return{id:a.toString(),tradeable:B.bits.toNumber(),balance:f.toString()}}),s=await Promise.all(r),i=await this.api.query.omnipool.assets(j);if(i.isSome){let{tradable:a}=i.unwrap(),B=await this.getBalance($j,j);s.push({id:j,tradeable:a.bits.toNumber(),balance:B.toString()})}return s}getPoolAddress(A){let j=Number(A),e=hA.getPoolAddress(j);return Rr(Nr(e),aj)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function le(n){return n.map(({assetIn:A,assetOut:j,pool:e,poolId:t})=>e==="Stableswap"?{pool:{Stableswap:t},assetIn:A,assetOut:j}:{pool:e,assetIn:A,assetOut:j})}var Gj=class extends Error{constructor(A){super(),this.message=`${A} pool invalid`,this.name="PoolNotFound"}},De=class extends Error{constructor(A,j){super(),this.message=`${A} pool missing ${j}`,this.name="PoolConfigNotFound"}},uj=class extends Error{constructor(A,j){super(),this.message=`Route from ${A} to ${j} not found in pool configuration`,this.name="RouteNotFound"}},Le=class extends Error{constructor(A){super(),this.message=`Asset ${A} not available in current network`,this.name="AssetNotFound"}},He=class extends Error{constructor(A){super(),this.message=`Storage missing ${A}`,this.name="StorageConfigNotFound"}},Xe=class extends Error{constructor(A){super(),this.message=`Subscription type "${A}" not supported`,this.name="SubscriptionNotSupported"}},Je=class extends Error{constructor(A){super(),this.message=`${A}`,this.name="ProviderConfigNotFound"}};var _j=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(A){this.api=A,this.assetClient=new lj(this.api),this.xykClient=new yj(this.api),this.omniClient=new vj(this.api),this.lbpClient=new Tj(this.api),this.stableClient=new Sj(this.api)}async syncRegistry(A){this.onChainAssets=await this.assetClient.getOnChainAssets(A),this.onChainAssetsLoaded=!0}async getPools(A){if(this.onChainAssetsLoaded||(this.onChainAssets=await this.assetClient.getOnChainAssets(),this.onChainAssetsLoaded=!0),A.length==0){let s=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(i=>i.isSupported()).map(i=>i.getPools()))).flat();return this.withMetadata(s)}let j=[];A.forEach(r=>{switch(r){case"Xyk":j.push(this.xykClient.getPools());break;case"Omnipool":j.push(this.omniClient.getPools());break;case"Lbp":j.push(this.lbpClient.getPools());break;case"Stableswap":j.push(this.stableClient.getPools());break}});let t=(await Promise.all(j)).flat();return this.withMetadata(t)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(A){let j=new Map(this.onChainAssets.map(e=>[e.id,e]));return A.filter(e=>e.type==="Xyk"?e.tokens.every(t=>j.get(t.id)):!0).map(e=>{let t=e.tokens.map(r=>{let s=j.get(r.id);return{...r,...s}});return{...e,tokens:t}})}async getPoolFees(A,j){switch(j.type){case"Xyk":return this.xykClient.getPoolFees(A,j.address);case"Omnipool":return this.omniClient.getPoolFees(A,j.address);case"Lbp":return this.lbpClient.getPoolFees(A,j.address);case"Stableswap":return this.stableClient.getPoolFees(A,j.address);default:throw new Gj(j.type)}}isDirectOmnipoolTrade(A){return A.length==1&&A[0].pool=="Omnipool"}buildBuyTx(A,j,e,t,r){let s;this.isDirectOmnipoolTrade(r)?s=this.api.tx.omnipool.buy(j,A,e.toFixed(),t.toFixed()):s=this.api.tx.router.buy(A,j,e.toFixed(),t.toFixed(),le(r));let i=()=>s;return{hex:s.toHex(),name:"RouterBuy",get:i}}buildSellTx(A,j,e,t,r){let s;this.isDirectOmnipoolTrade(r)?s=this.api.tx.omnipool.sell(A,j,e.toFixed(),t.toFixed()):s=this.api.tx.router.sell(A,j,e.toFixed(),t.toFixed(),le(r));let i=()=>s;return{hex:s.toHex(),name:"RouterSell",get:i}}};var dj=(n,A)=>n===A?0:n==null?A==null?0:-1:A==null?n==null?0:1:typeof n.compare=="function"?n.compare(A):typeof A.compare=="function"?-A.compare(n):n<A?-1:n>A?1:0;var Kj=(n,A=j=>j!==void 0?": "+j:"")=>class extends Error{constructor(j){super(n(j)+A(j))}};var Mr=Kj(()=>"illegal argument(s)"),Qe=n=>{throw new Mr(n)};var Dr=Kj(()=>"index out of bounds"),ce=n=>{throw new Dr(n)},Nj=(n,A,j)=>(n<A||n>=j)&&ce(n);var Ue=23283064365386963e-26,Rj=class{float(A=1){return this.int()*Ue*A}probability(A){return this.float()<A}norm(A=1){return(this.int()*Ue-.5)*2*A}normMinMax(A,j){let e=this.minmax(A,j);return this.float()<.5?e:-e}minmax(A,j){return this.float()*(j-A)+A}minmaxInt(A,j){A|=0;let e=(j|0)-A;return e?A+this.int()%e:A}minmaxUint(A,j){A>>>=0;let e=(j>>>0)-A;return e?A+this.int()%e:A}};var Be=Math.random,ue=class extends Rj{int(){return Be()*4294967296>>>0}float(A=1){return Be()*A}norm(A=1){return(Be()-.5)*2*A}},Ce=new ue;var Ze=n=>n!=null&&typeof n!="function"&&n.length!==void 0;var Ve=Object.getPrototypeOf({}),Mj="function",ze="string",YA=(n,A)=>{let j;if(n===A)return!0;if(n!=null){if(typeof n.equiv===Mj)return n.equiv(A)}else return n==A;if(A!=null){if(typeof A.equiv===Mj)return A.equiv(n)}else return n==A;return typeof n===ze||typeof A===ze?!1:(j=Object.getPrototypeOf(n),(j==null||j===Ve)&&(j=Object.getPrototypeOf(A),j==null||j===Ve)?Jr(n,A):typeof n!==Mj&&n.length!==void 0&&typeof A!==Mj&&A.length!==void 0?Lr(n,A):n instanceof Set&&A instanceof Set?Hr(n,A):n instanceof Map&&A instanceof Map?Xr(n,A):n instanceof Date&&A instanceof Date?n.getTime()===A.getTime():n instanceof RegExp&&A instanceof RegExp?n.toString()===A.toString():n!==n&&A!==A)},Lr=(n,A,j=YA)=>{let e=n.length;if(e===A.length)for(;e-- >0&&j(n[e],A[e]););return e<0},Hr=(n,A,j=YA)=>n.size===A.size&&j([...n.keys()].sort(),[...A.keys()].sort()),Xr=(n,A,j=YA)=>n.size===A.size&&j([...n].sort(),[...A].sort()),Jr=(n,A,j=YA)=>{if(Object.keys(n).length!==Object.keys(A).length)return!1;for(let e in n)if(!A.hasOwnProperty(e)||!j(n[e],A[e]))return!1;return!0};var We=(n,A)=>n!=null&&typeof n[A]=="function";var Ye=n=>We(n,"xform")?n.xform():n;var Dj=Symbol(),_e=()=>{};var At=n=>n!=null&&typeof n[Symbol.iterator]=="function";var Lj=class{value;constructor(A){this.value=A}deref(){return this.value}};var Hj=n=>n instanceof Lj;var jt=n=>n instanceof Lj?n.deref():n;function*et(n,A){let j=Ye(n)([_e,_e,(e,t)=>t])[2];for(let e of A){let t=j(Dj,e);if(Hj(t)){t=jt(t.deref()),t!==Dj&&(yield t);return}t!==Dj&&(yield t)}}var tt=(n,A)=>[n[0],n[1],A];function pj(n,A){return At(A)?et(pj(n),A):j=>{let e=j[2];return tt(j,(t,r)=>e(t,n(r)))}}var Aj=class{_head;_length=0;constructor(A){A&&this.into(A)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return rt("next",this._head)}reverseIterator(){return rt("prev",this.tail)}clear(){this.release()}compare(A,j=dj){let e=this._length;if(e<A._length)return-1;if(e>A._length)return 1;if(e===0)return 0;{let t=this._head,r=A._head,s=0;for(;e-- >0&&s===0;)s=j(t.value,r.value),t=t.next,r=r.next;return s}}concat(...A){let j=this.copy();for(let e of A)j.into(e);return j}equiv(A){if(!(A instanceof Aj||Ze(A))||this._length!==A.length)return!1;if(!this._length||this===A)return!0;let j=A[Symbol.iterator](),e=this._head;for(let t=this._length;t-- >0;){if(!YA(e.value,j.next().value))return!1;e=e.next}return!0}filter(A){let j=this.empty();return this.traverse(e=>(A(e.value)&&j.append(e.value),!0)),j}find(A){return this.traverse(j=>j.value!==A)}findWith(A){return this.traverse(j=>!A(j.value))}first(){return this._head&&this._head.value}insertSorted(A,j){j=j||dj;for(let e=this._head,t=this._length;t-- >0;){if(j(A,e.value)<=0)return this.insertBefore(e,A);e=e.next}return this.append(A)}into(A){for(let j of A)this.append(j);return this}nth(A,j){let e=this.nthCell(A);return e?e.value:j}nthCellUnsafe(A){let j,e;for(A<=this._length>>>1?(j=this._head,e="next"):(j=this.tail,e="prev",A=this._length-A-1);A-- >0&&j;)j=j[e];return j}peek(){return this.tail&&this.tail.value}$reduce(A,j){let e=this._head;for(let t=this._length;t-- >0&&!Hj(j);)j=A(j,e.value),e=e.next;return j}reduce(A,j){return this.$reduce(A,j)}release(){let A=this._head;if(!A)return!0;let j;for(let e=this._length;e-- >0;)j=A.next,delete A.value,delete A.prev,delete A.next,A=j;return this._head=void 0,this._length=0,!0}reverse(){let A=this._head,j=this.tail,e=(this._length>>>1)+(this._length&1);for(;A&&j&&e>0;){let t=A.value;A.value=j.value,j.value=t,A=A.next,j=j.prev,e--}return this}setHead(A){let j=this._head;return j?(j.value=A,j):this.prepend(A)}setNth(A,j){let e=this.nthCell(A);return!e&&ce(A),e.value=j,e}setTail(A){let j=this.tail;return j?(j.value=A,j):this.append(A)}swap(A,j){if(A!==j){let e=A.value;A.value=j.value,j.value=e}return this}toArray(A=[]){return this.traverse(j=>(A.push(j.value),!0)),A}toJSON(){return this.toArray()}toString(){let A=[];return this.traverse(j=>(A.push(String(j.value)),!0)),A.join(", ")}traverse(A,j=this._head,e){if(!this._head)return;let t=j;do{if(!A(t))break;t=t.next}while(t!==e);return t}_map(A,j){return this.traverse(e=>(A.append(j(e.value)),!0)),A}};function*rt(n,A){for(;A;)yield A.value,A=A[n]}var NA=class extends Aj{_tail;constructor(A){super(),A&&this.into(A)}get tail(){return this._tail}append(A){if(this._tail){let j={value:A,prev:this._tail};return this._tail.next=j,this._tail=j,this._length++,j}else return this.prepend(A)}asHead(A){return A===this._head?this:(this.remove(A),this._head.prev=A,A.next=this._head,A.prev=void 0,this._head=A,this._length++,this)}asTail(A){return A===this._tail?this:(this.remove(A),this._tail.next=A,A.prev=this._tail,A.next=void 0,this._tail=A,this._length++,this)}cons(A){return this.prepend(A),this}copy(){return new NA(this)}*cycle(){for(;;)yield*this}drop(){let A=this._head;if(A)return this._head=A.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,A.value}empty(){return new NA}insertAfter(A,j){let e={value:j,next:A.next,prev:A};return A.next?A.next.prev=e:this._tail=e,A.next=e,this._length++,e}insertAfterNth(A,j){return A<0&&(A+=this._length),A>=this._length-1?this.append(j):(Nj(A,0,this._length),this.insertAfter(this.nthCellUnsafe(A),j))}insertBefore(A,j){let e={value:j,next:A,prev:A.prev};return A.prev?A.prev.next=e:this._head=e,A.prev=e,this._length++,e}insertBeforeNth(A,j){return A<0&&(A+=this._length),A<=0?this.prepend(j):(Nj(A,0,this._length),this.insertBefore(this.nthCellUnsafe(A),j))}map(A){return this._map(new NA,A)}nth(A,j){let e=this.nthCell(A);return e?e.value:j}nthCell(A){if(A<0&&(A+=this._length),!(A<0||A>=this._length))return this.nthCellUnsafe(A)}pop(){let A=this._tail;if(A)return this._tail=A.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,A.value}prepend(A){let j={value:A,next:this._head};return this._head?this._head.prev=j:this._tail=j,this._head=j,this._length++,j}push(A){return this.append(A),this}release(){return this._tail=void 0,super.release()}remove(A){return A.prev?A.prev.next=A.next:this._head=A.next,A.next?A.next.prev=A.prev:this._tail=A.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let A=this.peek();return this.pop(),this.prepend(A),this}}seq(A=0,j=this.length){if(A>=j||A<0)return;let e=this.nthCell(A),t=this.nthCell(j-1),r=s=>({first(){return s.value},next(){return s!==t&&s.next?r(s.next):void 0}});return e?r(e):void 0}shuffle(A,j=Ce){if(this._length<2)return this;for(A=A!==void 0?A:Math.ceil(1.5*Math.log2(this._length));A>0;A--){let e=this._head;for(;e;){let t=e.next;j.probability(.5)?this.asHead(e):this.asTail(e),e=t}}return this}slice(A=0,j=this.length){let e=A<0?A+this._length:A,t=j<0?j+this._length:j;(e<0||t<0)&&Qe("invalid indices: ${from} / ${to}");let r=new NA,s=this.nthCell(e);for(;s&&++e<=t;)r.push(s.value),s=s.next;return r}sort(A=dj){if(!this._length)return this;let j=1;for(;;){let e=this._head;this._head=void 0,this._tail=void 0;let t=0;for(;e;){t++;let r=e,s=0;for(let a=0;a<j&&(s++,r=r.next,!!r);a++);let i=j;for(;s>0||i>0&&r;){let a;s===0?(a=r,r=r.next,i--):!r||i===0||A(e.value,r.value)<=0?(a=e,e=e.next,s--):(a=r,r=r.next,i--),this._tail?this._tail.next=a:this._head=a,a.prev=this._tail,this._tail=a}e=r}if(this._tail.next=void 0,t<=1)return this;j*=2}}splice(A,j=0,e){let t;typeof A=="number"?(A<0&&(A+=this._length),Nj(A,0,this._length),t=this.nthCellUnsafe(A)):t=A;let r=new NA;if(j>0)for(;t&&j-- >0;)this.remove(t),r.push(t.value),t=t.next;else t&&(t=t.next);if(e)if(t)for(let s of e)this.insertBefore(t,s);else for(let s of e)this.push(s);return r}};var jj=class{map;items;opts;_size;constructor(A,j){let e=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},j);this.map=e.map(),this.items=new NA,this._size=0,this.opts=e,A&&this.into(A)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return pj(A=>[A.k,A],this.items)}keys(){return pj(A=>A.k,this.items)}values(){return pj(A=>A.v,this.items)}copy(){let A=this.empty();A.items=this.items.copy();let j=A.items.head;for(;j;)A.map.set(j.value.k,j),j=j.next;return A}empty(){return new jj(null,this.opts)}release(){this._size=0,this.map.clear();let A=this.opts.release;if(A){let j;for(;j=this.items.drop();)A(j.k,j.v);return!0}return this.items.release()}has(A){return this.map.has(A)}get(A,j){let e=this.map.get(A);return e?this.resetEntry(e):j}set(A,j){let e=this.opts.ksize(A)+this.opts.vsize(j),t=this.map.get(A);return this._size+=Math.max(0,e-(t?t.value.s:0)),this.ensureSize()&&this.doSetEntry(t,A,j,e),j}into(A){for(let j of A)this.set(j[0],j[1]);return this}getSet(A,j){let e=this.map.get(A);return e?Promise.resolve(this.resetEntry(e)):j().then(t=>this.set(A,t))}delete(A){let j=this.map.get(A);return j?(this.removeEntry(j),!0):!1}resetEntry(A){return this.items.asTail(A),A.value.v}ensureSize(){let A=this.opts.release,j=this.opts.maxsize,e=this.opts.maxlen;for(;this._size>j||this.length>=e;){let t=this.items.drop();if(!t)return!1;this.map.delete(t.k),A&&A(t.k,t.v),this._size-=t.s}return!0}removeEntry(A){let j=A.value;this.map.delete(j.k),this.items.remove(A),this.opts.release&&this.opts.release(j.k,j.v),this._size-=j.s}doSetEntry(A,j,e,t){A?(A.value.v=e,A.value.s=t,this.items.asTail(A)):(this.items.push({k:j,v:e,s:t}),this.map.set(j,this.items.tail))}};var de=class extends _j{feeCache;disconnectSubscribeNewHeads=null;constructor(A){super(A),this.feeCache=new jj(null),this.api.rpc.chain.subscribeNewHeads(async j=>{this.feeCache.release()}).then(j=>{this.disconnectSubscribeNewHeads=j})}async getPoolFees(A,j){let e=[j.address,A].join("-");if(this.feeCache.has(e))return this.feeCache.get(e);{let r=await super.getPoolFees(A,j);return this.feeCache.set(e,r),r}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
-
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var CA=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(A){return new CA(A.address,A.tokens,A.maxInRatio,A.maxOutRatio,A.minTradingLimit,A.fee,A.repayFeeApply)}constructor(A,j,e,t,r,s,i){this.type="Lbp",this.address=A,this.tokens=j,this.maxInRatio=e,this.maxOutRatio=t,this.minTradingLimit=r,this.fee=s,this.repayFeeApply=i}validatePair(A,j){return!0}parsePair(A,j){let e=new Map(this.tokens.map(a=>[a.id,a])),t=e.get(A),r=e.get(j);if(t==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");let s=K(t.balance),i=K(r.balance);return{assetIn:A,assetOut:j,balanceIn:s,balanceOut:i,decimalsIn:t.decimals,decimalsOut:r.decimals,weightIn:t.weight,weightOut:r.weight}}validateAndBuy(A,j,e){let t=this.tokens[0].id,r=[];j.isLessThan(this.minTradingLimit)&&r.push("InsufficientTradingAmount");let s=A.balanceOut.div(this.maxOutRatio);if(j.isGreaterThan(s)&&r.push("MaxOutRatioExceeded"),t===A.assetOut){let i=this.calculateTradeFee(j,e),a=TA(this.repayFeeApply?e.repayFee:e.exchangeFee),B=j.plus(i),f=this.calculateInGivenOut(A,B),P=A.balanceIn.div(this.maxInRatio);return f.isGreaterThan(P)&&r.push("MaxInRatioExceeded"),{amountIn:f,calculatedIn:f,amountOut:j,feePct:a,errors:r}}else{let i=this.calculateInGivenOut(A,j),a=A.balanceIn.div(this.maxInRatio);return i.isGreaterThan(a)&&r.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:i,amountOut:j,feePct:0,errors:r}}}validateAndSell(A,j,e){let t=this.tokens[0].id,r=[];j.isLessThan(this.minTradingLimit)&&r.push("InsufficientTradingAmount");let s=A.balanceIn.div(this.maxInRatio);if(j.isGreaterThan(s)&&r.push("MaxInRatioExceeded"),t===A.assetIn){let i=this.calculateOutGivenIn(A,j),a=A.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(a)&&r.push("MaxOutRatioExceeded"),{amountIn:j,calculatedOut:i,amountOut:i,feePct:0,errors:r}}else{let i=this.calculateOutGivenIn(A,j),a=this.calculateTradeFee(i,e),B=TA(this.repayFeeApply?e.repayFee:e.exchangeFee),f=i.minus(a),P=A.balanceOut.div(this.maxOutRatio);return f.isGreaterThan(P)&&r.push("MaxOutRatioExceeded"),{amountIn:j,calculatedOut:i,amountOut:f,feePct:B,errors:r}}}calculateInGivenOut(A,j){let e=FA.calculateInGivenOut(A.balanceIn.toString(),A.balanceOut.toString(),A.weightIn.toString(),A.weightOut.toString(),j.toFixed(0)),t=K(e);return t.isNegative()?Q:t}calculateOutGivenIn(A,j){let e=FA.calculateOutGivenIn(A.balanceIn.toString(),A.balanceOut.toString(),A.weightIn.toString(),A.weightOut.toString(),j.toFixed(0)),t=K(e);return t.isNegative()?Q:t}spotPriceInGivenOut(A){let j=FA.getSpotPrice(A.balanceOut.toString(),A.balanceIn.toString(),A.weightOut.toString(),A.weightIn.toString(),BA($A,A.decimalsOut).toString());return K(j)}spotPriceOutGivenIn(A){let j=FA.getSpotPrice(A.balanceIn.toString(),A.balanceOut.toString(),A.weightIn.toString(),A.weightOut.toString(),BA($A,A.decimalsIn).toString());return K(j)}calculateTradeFee(A,j){let e=FA.calculatePoolTradeFee(A.toString(),this.repayFeeApply?j.repayFee[0]:j.exchangeFee[0],this.repayFeeApply?j.repayFee[1]:j.exchangeFee[1]);return K(e)}};var pe={};je(pe,{__wbindgen_add_to_stack_pointer:()=>fn,__wbindgen_free:()=>bn,__wbindgen_malloc:()=>kn,__wbindgen_realloc:()=>hn,calculate_cap_difference:()=>ln,calculate_in_given_out:()=>nn,calculate_liquidity_hub_in:()=>un,calculate_liquidity_lrna_out:()=>An,calculate_liquidity_out:()=>Yr,calculate_lrna_in_given_out:()=>sn,calculate_lrna_spot_price:()=>an,calculate_out_given_in:()=>tn,calculate_out_given_lrna_in:()=>rn,calculate_pool_trade_fee:()=>gn,calculate_shares:()=>zr,calculate_spot_price:()=>on,calculate_tvl_cap_difference:()=>Bn,calculate_withdrawal_fee:()=>Wr,instance:()=>C,is_add_liquidity_allowed:()=>pn,is_buy_allowed:()=>dn,is_remove_liquidity_allowed:()=>mn,is_sell_allowed:()=>_n,memory:()=>Vr,module:()=>Zr,recalculate_asset_fee:()=>jn,recalculate_protocol_fee:()=>en,verify_asset_cap:()=>cn});var nt="./hydra_dx_wasm_bg-XWH3TUMG.wasm";var Ur={};async function Cr(n,A){if(typeof n=="string"){n.startsWith("./")&&(n=new URL(n,import.meta.url).href);let j=await fetch(n);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(j,A)}catch(e){if(j.headers.get("Content-Type")!="application/wasm")console.warn(e);else throw e}n=await j.arrayBuffer()}return await WebAssembly.instantiate(n,A)}var{instance:C,module:Zr}=await Cr(nt,Ur),Vr=C.exports.memory,zr=C.exports.calculate_shares,Wr=C.exports.calculate_withdrawal_fee,Yr=C.exports.calculate_liquidity_out,An=C.exports.calculate_liquidity_lrna_out,jn=C.exports.recalculate_asset_fee,en=C.exports.recalculate_protocol_fee,tn=C.exports.calculate_out_given_in,rn=C.exports.calculate_out_given_lrna_in,nn=C.exports.calculate_in_given_out,sn=C.exports.calculate_lrna_in_given_out,on=C.exports.calculate_spot_price,an=C.exports.calculate_lrna_spot_price,ln=C.exports.calculate_cap_difference,cn=C.exports.verify_asset_cap,Bn=C.exports.calculate_tvl_cap_difference,un=C.exports.calculate_liquidity_hub_in,_n=C.exports.is_sell_allowed,dn=C.exports.is_buy_allowed,pn=C.exports.is_add_liquidity_allowed,mn=C.exports.is_remove_liquidity_allowed,gn=C.exports.calculate_pool_trade_fee,fn=C.exports.__wbindgen_add_to_stack_pointer,kn=C.exports.__wbindgen_malloc,hn=C.exports.__wbindgen_realloc,bn=C.exports.__wbindgen_free;var u;function st(n){u=n}var y=0,Xj=null;function Qj(){return(Xj===null||Xj.byteLength===0)&&(Xj=new Uint8Array(u.memory.buffer)),Xj}var En=typeof TextEncoder>"u"?(0,module.require)("util").TextEncoder:TextEncoder,Uj=new En("utf-8"),Pn=typeof Uj.encodeInto=="function"?function(n,A){return Uj.encodeInto(n,A)}:function(n,A){let j=Uj.encode(n);return A.set(j),{read:n.length,written:j.length}};function F(n,A,j){if(j===void 0){let i=Uj.encode(n),a=A(i.length)>>>0;return Qj().subarray(a,a+i.length).set(i),y=i.length,a}let e=n.length,t=A(e)>>>0,r=Qj(),s=0;for(;s<e;s++){let i=n.charCodeAt(s);if(i>127)break;r[t+s]=i}if(s!==e){s!==0&&(n=n.slice(s)),t=j(t,e,e=s+n.length*3)>>>0;let i=Qj().subarray(t+s,t+e),a=Pn(n,i);s+=a.written}return y=s,t}var Jj=null;function Y(){return(Jj===null||Jj.byteLength===0)&&(Jj=new Int32Array(u.memory.buffer)),Jj}var wn=typeof TextDecoder>"u"?(0,module.require)("util").TextDecoder:TextDecoder,it=new wn("utf-8",{ignoreBOM:!0,fatal:!0});it.decode();function vA(n,A){return n=n>>>0,it.decode(Qj().subarray(n,n+A))}function ot(n,A,j,e){let t,r;try{let a=u.__wbindgen_add_to_stack_pointer(-16),B=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),f=y,P=F(A,u.__wbindgen_malloc,u.__wbindgen_realloc),I=y,$=F(j,u.__wbindgen_malloc,u.__wbindgen_realloc),T=y,v=F(e,u.__wbindgen_malloc,u.__wbindgen_realloc),x=y;u.calculate_shares(a,B,f,P,I,$,T,v,x);var s=Y()[a/4+0],i=Y()[a/4+1];return t=s,r=i,vA(s,i)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(t,r)}}function at(n,A,j,e,t,r,s,i){let a,B;try{let I=u.__wbindgen_add_to_stack_pointer(-16),$=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),T=y,v=F(A,u.__wbindgen_malloc,u.__wbindgen_realloc),x=y,N=F(j,u.__wbindgen_malloc,u.__wbindgen_realloc),E=y,M=F(e,u.__wbindgen_malloc,u.__wbindgen_realloc),tA=y,oA=F(t,u.__wbindgen_malloc,u.__wbindgen_realloc),W=y,D=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),o=y,l=F(s,u.__wbindgen_malloc,u.__wbindgen_realloc),c=y,g=F(i,u.__wbindgen_malloc,u.__wbindgen_realloc),d=y;u.calculate_liquidity_out(I,$,T,v,x,N,E,M,tA,oA,W,D,o,l,c,g,d);var f=Y()[I/4+0],P=Y()[I/4+1];return a=f,B=P,vA(f,P)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(a,B)}}function lt(n,A,j,e,t,r,s,i){let a,B;try{let I=u.__wbindgen_add_to_stack_pointer(-16),$=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),T=y,v=F(A,u.__wbindgen_malloc,u.__wbindgen_realloc),x=y,N=F(j,u.__wbindgen_malloc,u.__wbindgen_realloc),E=y,M=F(e,u.__wbindgen_malloc,u.__wbindgen_realloc),tA=y,oA=F(t,u.__wbindgen_malloc,u.__wbindgen_realloc),W=y,D=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),o=y,l=F(s,u.__wbindgen_malloc,u.__wbindgen_realloc),c=y,g=F(i,u.__wbindgen_malloc,u.__wbindgen_realloc),d=y;u.calculate_liquidity_lrna_out(I,$,T,v,x,N,E,M,tA,oA,W,D,o,l,c,g,d);var f=Y()[I/4+0],P=Y()[I/4+1];return a=f,B=P,vA(f,P)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(a,B)}}function ct(n,A,j,e,t,r,s,i,a){let B,f;try{let $=u.__wbindgen_add_to_stack_pointer(-16),T=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),v=y,x=F(A,u.__wbindgen_malloc,u.__wbindgen_realloc),N=y,E=F(j,u.__wbindgen_malloc,u.__wbindgen_realloc),M=y,tA=F(e,u.__wbindgen_malloc,u.__wbindgen_realloc),oA=y,W=F(t,u.__wbindgen_malloc,u.__wbindgen_realloc),D=y,o=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),l=y,c=F(s,u.__wbindgen_malloc,u.__wbindgen_realloc),g=y,d=F(i,u.__wbindgen_malloc,u.__wbindgen_realloc),m=y,b=F(a,u.__wbindgen_malloc,u.__wbindgen_realloc),_=y;u.calculate_out_given_in($,T,v,x,N,E,M,tA,oA,W,D,o,l,c,g,d,m,b,_);var P=Y()[$/4+0],I=Y()[$/4+1];return B=P,f=I,vA(P,I)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(B,f)}}function Bt(n,A,j,e,t){let r,s;try{let B=u.__wbindgen_add_to_stack_pointer(-16),f=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),P=y,I=F(A,u.__wbindgen_malloc,u.__wbindgen_realloc),$=y,T=F(j,u.__wbindgen_malloc,u.__wbindgen_realloc),v=y,x=F(e,u.__wbindgen_malloc,u.__wbindgen_realloc),N=y,E=F(t,u.__wbindgen_malloc,u.__wbindgen_realloc),M=y;u.calculate_out_given_lrna_in(B,f,P,I,$,T,v,x,N,E,M);var i=Y()[B/4+0],a=Y()[B/4+1];return r=i,s=a,vA(i,a)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(r,s)}}function ut(n,A,j,e,t,r,s,i,a){let B,f;try{let $=u.__wbindgen_add_to_stack_pointer(-16),T=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),v=y,x=F(A,u.__wbindgen_malloc,u.__wbindgen_realloc),N=y,E=F(j,u.__wbindgen_malloc,u.__wbindgen_realloc),M=y,tA=F(e,u.__wbindgen_malloc,u.__wbindgen_realloc),oA=y,W=F(t,u.__wbindgen_malloc,u.__wbindgen_realloc),D=y,o=F(r,u.__wbindgen_malloc,u.__wbindgen_realloc),l=y,c=F(s,u.__wbindgen_malloc,u.__wbindgen_realloc),g=y,d=F(i,u.__wbindgen_malloc,u.__wbindgen_realloc),m=y,b=F(a,u.__wbindgen_malloc,u.__wbindgen_realloc),_=y;u.calculate_in_given_out($,T,v,x,N,E,M,tA,oA,W,D,o,l,c,g,d,m,b,_);var P=Y()[$/4+0],I=Y()[$/4+1];return B=P,f=I,vA(P,I)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(B,f)}}function _t(n,A,j,e,t){let r,s;try{let B=u.__wbindgen_add_to_stack_pointer(-16),f=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),P=y,I=F(A,u.__wbindgen_malloc,u.__wbindgen_realloc),$=y,T=F(j,u.__wbindgen_malloc,u.__wbindgen_realloc),v=y,x=F(e,u.__wbindgen_malloc,u.__wbindgen_realloc),N=y,E=F(t,u.__wbindgen_malloc,u.__wbindgen_realloc),M=y;u.calculate_lrna_in_given_out(B,f,P,I,$,T,v,x,N,E,M);var i=Y()[B/4+0],a=Y()[B/4+1];return r=i,s=a,vA(i,a)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(r,s)}}function dt(n,A,j,e){let t,r;try{let a=u.__wbindgen_add_to_stack_pointer(-16),B=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),f=y,P=F(A,u.__wbindgen_malloc,u.__wbindgen_realloc),I=y,$=F(j,u.__wbindgen_malloc,u.__wbindgen_realloc),T=y,v=F(e,u.__wbindgen_malloc,u.__wbindgen_realloc),x=y;u.calculate_spot_price(a,B,f,P,I,$,T,v,x);var s=Y()[a/4+0],i=Y()[a/4+1];return t=s,r=i,vA(s,i)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(t,r)}}function pt(n,A){let j,e;try{let s=u.__wbindgen_add_to_stack_pointer(-16),i=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),a=y,B=F(A,u.__wbindgen_malloc,u.__wbindgen_realloc),f=y;u.calculate_lrna_spot_price(s,i,a,B,f);var t=Y()[s/4+0],r=Y()[s/4+1];return j=t,e=r,vA(t,r)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(j,e)}}function mt(n,A,j,e){let t,r;try{let a=u.__wbindgen_add_to_stack_pointer(-16),B=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),f=y,P=F(A,u.__wbindgen_malloc,u.__wbindgen_realloc),I=y,$=F(j,u.__wbindgen_malloc,u.__wbindgen_realloc),T=y,v=F(e,u.__wbindgen_malloc,u.__wbindgen_realloc),x=y;u.calculate_cap_difference(a,B,f,P,I,$,T,v,x);var s=Y()[a/4+0],i=Y()[a/4+1];return t=s,r=i,vA(s,i)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(t,r)}}function gt(n,A,j,e){let t=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),r=y,s=F(A,u.__wbindgen_malloc,u.__wbindgen_realloc),i=y,a=F(j,u.__wbindgen_malloc,u.__wbindgen_realloc),B=y,f=F(e,u.__wbindgen_malloc,u.__wbindgen_realloc),P=y;return u.verify_asset_cap(t,r,s,i,a,B,f,P)!==0}function ft(n,A,j,e){let t,r;try{let a=u.__wbindgen_add_to_stack_pointer(-16),B=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),f=y,P=F(A,u.__wbindgen_malloc,u.__wbindgen_realloc),I=y,$=F(j,u.__wbindgen_malloc,u.__wbindgen_realloc),T=y,v=F(e,u.__wbindgen_malloc,u.__wbindgen_realloc),x=y;u.calculate_liquidity_hub_in(a,B,f,P,I,$,T,v,x);var s=Y()[a/4+0],i=Y()[a/4+1];return t=s,r=i,vA(s,i)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(t,r)}}function kt(n){return u.is_sell_allowed(n)!==0}function ht(n){return u.is_buy_allowed(n)!==0}function bt(n){return u.is_add_liquidity_allowed(n)!==0}function Et(n){return u.is_remove_liquidity_allowed(n)!==0}function Pt(n,A,j){let e,t;try{let i=u.__wbindgen_add_to_stack_pointer(-16),a=F(n,u.__wbindgen_malloc,u.__wbindgen_realloc),B=y;u.calculate_pool_trade_fee(i,a,B,A,j);var r=Y()[i/4+0],s=Y()[i/4+1];return e=r,t=s,vA(r,s)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(e,t)}}st(pe);var iA=class{static calculateSpotPrice(A,j,e,t){return dt(A,j,e,t)}static calculateLrnaSpotPrice(A,j){return pt(A,j)}static calculateInGivenOut(A,j,e,t,r,s,i,a,B){return ut(A,j,e,t,r,s,i,a,B)}static calculateLrnaInGivenOut(A,j,e,t,r){return _t(A,j,e,t,r)}static calculateOutGivenIn(A,j,e,t,r,s,i,a,B){return ct(A,j,e,t,r,s,i,a,B)}static calculateOutGivenLrnaIn(A,j,e,t,r){return Bt(A,j,e,t,r)}static calculatePoolTradeFee(A,j,e){return Pt(A,j,e)}static calculateShares(A,j,e,t){return ot(A,j,e,t)}static calculateLiquidityOut(A,j,e,t,r,s,i,a){return at(A,j,e,t,r,s,i,a)}static calculateLiquidityLRNAOut(A,j,e,t,r,s,i,a){return lt(A,j,e,t,r,s,i,a)}static calculateCapDifference(A,j,e,t){return mt(A,j,e,t)}static verifyAssetCap(A,j,e,t){return gt(A,j,e,t)}static calculateLimitHubIn(A,j,e,t){return ft(A,j,e,t)}static isSellAllowed(A){return kt(A)}static isBuyAllowed(A){return ht(A)}static isAddLiquidityAllowed(A){return bt(A)}static isRemoveLiquidityAllowed(A){return Et(A)}};var ZA=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(A){return new ZA(A.address,A.tokens,A.maxInRatio,A.maxOutRatio,A.minTradingLimit,A.hubAssetId)}constructor(A,j,e,t,r,s){this.type="Omnipool",this.address=A,this.tokens=j,this.maxInRatio=e,this.maxOutRatio=t,this.minTradingLimit=r,this.hubAssetId=s}validatePair(A,j){return this.hubAssetId!=j}parsePair(A,j){let e=new Map(this.tokens.map(a=>[a.id,a])),t=e.get(A),r=e.get(j);if(t==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");let s=K(t.balance),i=K(r.balance);return{assetIn:A,assetOut:j,hubReservesIn:t.hubReserves,hubReservesOut:r.hubReserves,sharesIn:t.shares,sharesOut:r.shares,decimalsIn:t.decimals,decimalsOut:r.decimals,balanceIn:s,balanceOut:i,tradeableIn:t.tradeable,tradeableOut:r.tradeable}}validateAndBuy(A,j,e){let t=this.calculateInGivenOut(A,j),r=this.calculateInGivenOut(A,j,e),s=r.minus(t),i=t===Q?Q:s.div(t).multipliedBy(100).decimalPlaces(2),a=[],B=iA.isSellAllowed(A.tradeableIn),f=iA.isBuyAllowed(A.tradeableOut);(!B||!f)&&a.push("TradeNotAllowed"),j.isLessThan(this.minTradingLimit)&&a.push("InsufficientTradingAmount");let P=A.balanceOut.div(this.maxOutRatio);j.isGreaterThan(P)&&a.push("MaxOutRatioExceeded");let I=A.balanceIn.div(this.maxInRatio);return r.isGreaterThan(I)&&a.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:t,amountOut:j,feePct:i.toNumber(),errors:a}}validateAndSell(A,j,e){let t=this.calculateOutGivenIn(A,j),r=this.calculateOutGivenIn(A,j,e),i=t.minus(r).div(t).multipliedBy(100).decimalPlaces(2),a=[],B=iA.isSellAllowed(A.tradeableIn),f=iA.isBuyAllowed(A.tradeableOut);(!B||!f)&&a.push("TradeNotAllowed"),j.isLessThan(this.minTradingLimit)&&a.push("InsufficientTradingAmount");let P=A.balanceIn.div(this.maxInRatio);j.isGreaterThan(P)&&a.push("MaxInRatioExceeded");let I=A.balanceOut.div(this.maxOutRatio);return r.isGreaterThan(I)&&a.push("MaxOutRatioExceeded"),{amountIn:j,calculatedOut:t,amountOut:r,feePct:i.toNumber(),errors:a}}calculateInGivenOut(A,j,e){if(A.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(A,j,e);let t=iA.calculateInGivenOut(A.balanceIn.toString(),A.hubReservesIn.toString(),A.sharesIn.toString(),A.balanceOut.toString(),A.hubReservesOut.toString(),A.sharesOut.toString(),j.toFixed(0),e?kA(e.assetFee).toString():Q.toString(),e?kA(e.protocolFee).toString():Q.toString()),r=K(t);return r.isNegative()?Q:r}calculateLrnaInGivenOut(A,j,e){let t=iA.calculateLrnaInGivenOut(A.balanceOut.toString(),A.hubReservesOut.toString(),A.sharesOut.toString(),j.toFixed(0),e?kA(e.assetFee).toString():Q.toString()),r=K(t);return r.isNegative()?Q:r}calculateOutGivenIn(A,j,e){if(A.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(A,j,e);let t=iA.calculateOutGivenIn(A.balanceIn.toString(),A.hubReservesIn.toString(),A.sharesIn.toString(),A.balanceOut.toString(),A.hubReservesOut.toString(),A.sharesOut.toString(),j.toFixed(0),e?kA(e.assetFee).toString():Q.toString(),e?kA(e.protocolFee).toString():Q.toString()),r=K(t);return r.isNegative()?Q:r}calculateOutGivenLrnaIn(A,j,e){let t=iA.calculateOutGivenLrnaIn(A.balanceOut.toString(),A.hubReservesOut.toString(),A.sharesOut.toString(),j.toFixed(0),e?kA(e.assetFee).toString():Q.toString()),r=K(t);return r.isNegative()?Q:r}spotPriceInGivenOut(A){if(A.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(A);let j=iA.calculateSpotPrice(A.balanceOut.toString(),A.hubReservesOut.toString(),A.balanceIn.toString(),A.hubReservesIn.toString());return K(j).shiftedBy(-1*(oj-A.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(A){let j=iA.calculateLrnaSpotPrice(A.hubReservesOut.toString(),A.balanceOut.toString());return K(j).shiftedBy(-1*(oj-A.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(A){if(A.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(A);let j=iA.calculateSpotPrice(A.balanceIn.toString(),A.hubReservesIn.toString(),A.balanceOut.toString(),A.hubReservesOut.toString());return K(j).shiftedBy(-1*(oj-A.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(A){let j=iA.calculateLrnaSpotPrice(A.balanceOut.toString(),A.hubReservesOut.toString());return K(j).shiftedBy(-1*(oj-A.decimalsIn)).decimalPlaces(0,1)}};var VA=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(A){return new VA(A.address,A.tokens,A.maxInRatio,A.maxOutRatio,A.minTradingLimit,A.amplification,A.id,A.fee,A.totalIssuance)}constructor(A,j,e,t,r,s,i,a,B){this.type="Stableswap",this.address=A,this.tokens=j,this.maxInRatio=e,this.maxOutRatio=t,this.minTradingLimit=r,this.amplification=s,this.id=i,this.fee=a,this.totalIssuance=B}validatePair(A,j){return!0}parsePair(A,j){let e=new Map(this.tokens.map(a=>[a.id,a])),t=e.get(A),r=e.get(j);if(t==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");let s=K(t.balance),i=K(r.balance);return{assetIn:A,assetOut:j,balanceIn:s,balanceOut:i,decimalsIn:t.decimals,decimalsOut:r.decimals,tradeableIn:this.id===A?ie:t.tradeable,tradeableOut:this.id===j?ie:r.tradeable}}validateAndBuy(A,j,e){let t=this.calculateInGivenOut(A,j),r=this.calculateInGivenOut(A,j,e),s=TA(e.fee),i=[],a=iA.isSellAllowed(A.tradeableIn),B=iA.isBuyAllowed(A.tradeableOut);return(!a||!B)&&i.push("TradeNotAllowed"),j.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount"),{amountIn:r,calculatedIn:t,amountOut:j,feePct:s,errors:i}}validateAndSell(A,j,e){let t=this.calculateOutGivenIn(A,j),r=this.calculateOutGivenIn(A,j,e),s=TA(e.fee),i=[],a=iA.isSellAllowed(A.tradeableIn),B=iA.isBuyAllowed(A.tradeableOut);return(!a||!B)&&i.push("TradeNotAllowed"),j.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount"),{amountIn:j,calculatedOut:t,amountOut:r,feePct:s,errors:i}}calculateIn(A,j,e){let t=hA.calculateInGivenOut(this.getReserves(),Number(A.assetIn),Number(A.assetOut),j.toFixed(0),this.amplification,e?kA(e.fee).toString():Q.toString()),r=K(t);return r.isNegative()?Q:r}calculateAddOneAsset(A,j,e){let t=hA.calculateAddOneAsset(this.getReserves(),j.toFixed(0),Number(A.assetIn),this.amplification,this.totalIssuance,e?kA(e.fee).toString():Q.toString()),r=K(t);return r.isNegative()?Q:r}calculateSharesForAmount(A,j,e){let t=hA.calculateSharesForAmount(this.getReserves(),Number(A.assetOut),j.toFixed(0),this.amplification,this.totalIssuance,e?kA(e.fee).toString():Q.toString()),r=K(t);return r.isNegative()?Q:r}calculateInGivenOut(A,j,e){return A.assetOut==this.id?this.calculateAddOneAsset(A,j,e):A.assetIn==this.id?this.calculateSharesForAmount(A,j,e):this.calculateIn(A,j,e)}spotPriceInGivenOut(A){let j=BA($A,A.decimalsOut);return A.assetOut==this.id?this.calculateAddOneAsset(A,j):A.assetIn==this.id?this.calculateSharesForAmount(A,j):this.calculateIn(A,j)}calculateOut(A,j,e){let t=hA.calculateOutGivenIn(this.getReserves(),Number(A.assetIn),Number(A.assetOut),j.toFixed(0),this.amplification,e?kA(e.fee).toString():Q.toString()),r=K(t);return r.isNegative()?Q:r}calculateWithdrawOneAsset(A,j,e){let t=hA.calculateLiquidityOutOneAsset(this.getReserves(),j.toFixed(0),Number(A.assetOut),this.amplification,this.totalIssuance,e?kA(e.fee).toString():Q.toString()),r=K(t);return r.isNegative()?Q:r}calculateShares(A,j,e){let t=hA.calculateShares(this.getReserves(),this.getAssets(A.assetIn,j),this.amplification,this.totalIssuance,e?kA(e.fee).toString():Q.toString()),r=K(t);return r.isNegative()?Q:r}calculateOutGivenIn(A,j,e){return A.assetIn==this.id?this.calculateWithdrawOneAsset(A,j,e):A.assetOut==this.id?this.calculateShares(A,j,e):this.calculateOut(A,j,e)}spotPriceOutGivenIn(A){let j=BA($A,A.decimalsIn);return A.assetIn==this.id?this.calculateWithdrawOneAsset(A,j):A.assetOut==this.id?this.calculateShares(A,j):this.calculateOut(A,j)}calculateTradeFee(A,j){let e=hA.calculatePoolTradeFee(A.toString(),j.fee[0],j.fee[1]);return K(e)}getReserves(){let A=this.tokens.filter(j=>j.id!=this.id).map(({id:j,balance:e,decimals:t})=>({asset_id:Number(j),amount:e,decimals:t}));return JSON.stringify(A)}getAssets(A,j){let e={asset_id:Number(A),amount:j.toFixed(0)};return JSON.stringify([e])}};var wt="./hydra_dx_wasm_bg-ZX7K4FM7.wasm";var In={};async function $n(n,A){if(typeof n=="string"){n.startsWith("./")&&(n=new URL(n,import.meta.url).href);let j=await fetch(n);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(j,A)}catch(e){if(j.headers.get("Content-Type")!="application/wasm")console.warn(e);else throw e}n=await j.arrayBuffer()}return await WebAssembly.instantiate(n,A)}var{instance:EA,module:Fl}=await $n(wt,In),mj=EA.exports.memory,qt=EA.exports.calculate_pool_trade_fee,It=EA.exports.get_spot_price,$t=EA.exports.calculate_out_given_in,Tt=EA.exports.calculate_in_given_out,vt=EA.exports.calculate_liquidity_in,yt=EA.exports.calculate_shares,xt=EA.exports.calculate_liquidity_out_asset_a,Ft=EA.exports.calculate_liquidity_out_asset_b,_A=EA.exports.__wbindgen_add_to_stack_pointer,V=EA.exports.__wbindgen_malloc,z=EA.exports.__wbindgen_realloc,DA=EA.exports.__wbindgen_free;var Z=0,Cj=null;function Vj(){return(Cj===null||Cj.buffer!==mj.buffer)&&(Cj=new Uint8Array(mj.buffer)),Cj}var vn=typeof TextEncoder>"u"?(0,module.require)("util").TextEncoder:TextEncoder,zj=new vn("utf-8"),yn=typeof zj.encodeInto=="function"?function(n,A){return zj.encodeInto(n,A)}:function(n,A){let j=zj.encode(n);return A.set(j),{read:n.length,written:j.length}};function AA(n,A,j){if(j===void 0){let i=zj.encode(n),a=A(i.length);return Vj().subarray(a,a+i.length).set(i),Z=i.length,a}let e=n.length,t=A(e),r=Vj(),s=0;for(;s<e;s++){let i=n.charCodeAt(s);if(i>127)break;r[t+s]=i}if(s!==e){s!==0&&(n=n.slice(s)),t=j(t,e,e=s+n.length*3);let i=Vj().subarray(t+s,t+e),a=yn(n,i);s+=a.written}return Z=s,t}var Zj=null;function pA(){return(Zj===null||Zj.buffer!==mj.buffer)&&(Zj=new Int32Array(mj.buffer)),Zj}var xn=typeof TextDecoder>"u"?(0,module.require)("util").TextDecoder:TextDecoder,Ot=new xn("utf-8",{ignoreBOM:!0,fatal:!0});Ot.decode();function QA(n,A){return Ot.decode(Vj().subarray(n,n+A))}function St(n,A,j){try{let r=_A(-16),s=AA(n,V,z);qt(r,s,Z,A,j);var e=pA()[r/4+0],t=pA()[r/4+1];return QA(e,t)}finally{_A(16),DA(e,t)}}function Gt(n,A,j){try{let r=_A(-16),s=AA(n,V,z),i=Z,a=AA(A,V,z),B=Z,f=AA(j,V,z);It(r,s,i,a,B,f,Z);var e=pA()[r/4+0],t=pA()[r/4+1];return QA(e,t)}finally{_A(16),DA(e,t)}}function Kt(n,A,j){try{let r=_A(-16),s=AA(n,V,z),i=Z,a=AA(A,V,z),B=Z,f=AA(j,V,z);$t(r,s,i,a,B,f,Z);var e=pA()[r/4+0],t=pA()[r/4+1];return QA(e,t)}finally{_A(16),DA(e,t)}}function Nt(n,A,j){try{let r=_A(-16),s=AA(n,V,z),i=Z,a=AA(A,V,z),B=Z,f=AA(j,V,z);Tt(r,s,i,a,B,f,Z);var e=pA()[r/4+0],t=pA()[r/4+1];return QA(e,t)}finally{_A(16),DA(e,t)}}function Rt(n,A,j){try{let r=_A(-16),s=AA(n,V,z),i=Z,a=AA(A,V,z),B=Z,f=AA(j,V,z);vt(r,s,i,a,B,f,Z);var e=pA()[r/4+0],t=pA()[r/4+1];return QA(e,t)}finally{_A(16),DA(e,t)}}function Mt(n,A,j){try{let r=_A(-16),s=AA(n,V,z),i=Z,a=AA(A,V,z),B=Z,f=AA(j,V,z);yt(r,s,i,a,B,f,Z);var e=pA()[r/4+0],t=pA()[r/4+1];return QA(e,t)}finally{_A(16),DA(e,t)}}function Dt(n,A,j,e){try{let s=_A(-16),i=AA(n,V,z),a=Z,B=AA(A,V,z),f=Z,P=AA(j,V,z),I=Z,$=AA(e,V,z);xt(s,i,a,B,f,P,I,$,Z);var t=pA()[s/4+0],r=pA()[s/4+1];return QA(t,r)}finally{_A(16),DA(t,r)}}function Lt(n,A,j,e){try{let s=_A(-16),i=AA(n,V,z),a=Z,B=AA(A,V,z),f=Z,P=AA(j,V,z),I=Z,$=AA(e,V,z);Ft(s,i,a,B,f,P,I,$,Z);var t=pA()[s/4+0],r=pA()[s/4+1];return QA(t,r)}finally{_A(16),DA(t,r)}}var LA=class{static getSpotPrice(A,j,e){return Gt(A,j,e)}static calculateInGivenOut(A,j,e){return Nt(A,j,e)}static calculateOutGivenIn(A,j,e){return Kt(A,j,e)}static calculatePoolTradeFee(A,j,e){return St(A,j,e)}static calculateLiquidityIn(A,j,e){return Rt(A,j,e)}static calculateShares(A,j,e){return Mt(A,j,e)}static calculateLiquidityOutAssetA(A,j,e,t){return Dt(A,j,e,t)}static calculateLiquidityOutAssetB(A,j,e,t){return Lt(A,j,e,t)}};var zA=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(A){return new zA(A.address,A.tokens,A.maxInRatio,A.maxOutRatio,A.minTradingLimit)}constructor(A,j,e,t,r){this.type="Xyk",this.address=A,this.tokens=j,this.maxInRatio=e,this.maxOutRatio=t,this.minTradingLimit=r}validatePair(A,j){return!0}parsePair(A,j){let e=new Map(this.tokens.map(a=>[a.id,a])),t=e.get(A),r=e.get(j);if(t==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");let s=K(t.balance),i=K(r.balance);return{assetIn:A,assetOut:j,decimalsIn:t.decimals,decimalsOut:r.decimals,balanceIn:s,balanceOut:i}}validateAndBuy(A,j,e){let t=this.calculateInGivenOut(A,j),r=this.calculateTradeFee(t,e),s=TA(e.exchangeFee),i=t.plus(r),a=[];j.isLessThan(this.minTradingLimit)&&a.push("InsufficientTradingAmount");let B=A.balanceOut.div(this.maxOutRatio);j.isGreaterThan(B)&&a.push("MaxOutRatioExceeded");let f=A.balanceIn.div(this.maxInRatio);return i.isGreaterThan(f)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:t,amountOut:j,feePct:s,errors:a}}validateAndSell(A,j,e){let t=this.calculateOutGivenIn(A,j),r=this.calculateTradeFee(t,e),s=TA(e.exchangeFee),i=t.minus(r),a=[];j.isLessThan(this.minTradingLimit)&&a.push("InsufficientTradingAmount");let B=A.balanceIn.div(this.maxInRatio);j.isGreaterThan(B)&&a.push("MaxInRatioExceeded");let f=A.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(f)&&a.push("MaxOutRatioExceeded"),{amountIn:j,calculatedOut:t,amountOut:i,feePct:s,errors:a}}calculateInGivenOut(A,j){let e=LA.calculateInGivenOut(A.balanceIn.toString(),A.balanceOut.toString(),j.toFixed(0)),t=K(e);return t.isNegative()?Q:t}calculateOutGivenIn(A,j){let e=LA.calculateOutGivenIn(A.balanceIn.toString(),A.balanceOut.toString(),j.toFixed(0)),t=K(e);return t.isNegative()?Q:t}spotPriceInGivenOut(A){let j=LA.getSpotPrice(A.balanceOut.toString(),A.balanceIn.toString(),BA($A,A.decimalsOut).toString());return K(j)}spotPriceOutGivenIn(A){let j=LA.getSpotPrice(A.balanceIn.toString(),A.balanceOut.toString(),BA($A,A.decimalsIn).toString());return K(j)}calculateTradeFee(A,j){let e=LA.calculatePoolTradeFee(A.toString(),j.exchangeFee[0],j.exchangeFee[1]);return K(e)}};var gj=class{static get(A){switch(A.type){case"Xyk":return zA.fromPool(A);case"Omnipool":return ZA.fromPool(A);case"Lbp":return CA.fromPool(A);case"Stableswap":return VA.fromPool(A);default:throw new Error("Pool type "+A.type+" is not supported yet")}}};var ej=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(A,j){this.poolService=A,this.routeSuggester=new nj,this.routerOptions={...this.defaultRouterOptions,...j}}async getPools(){let A=this.routerOptions.includeOnly;return await this.poolService.getPools(A)}async getAllAssets(){let A=await this.getPools();if(A.length===0)throw new Error("No pools configured");let j=await this.getAssets(A);return[...new Map(j).values()]}async getAssetPairs(A){let j=await this.getPools();if(j.length===0)throw new Error("No pools configured");let{assets:e,poolsMap:t}=await this.validateToken(A,j),s=this.getPaths(A,null,t,j).map(i=>i[i.length-1].assetOut);return this.toAssets([...new Set(s)],e)}async getAllPaths(A,j){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let{poolsMap:t}=await this.validateTokenPair(A,j,e);return this.getPaths(A,j,t,e)}async getAssets(A){let j=A.map(e=>e.tokens.map(t=>({id:t.id,name:t.name,symbol:t.symbol,decimals:t.decimals,icon:t.icon,type:t.type,isSufficient:t.isSufficient,existentialDeposit:t.existentialDeposit,origin:t.origin,meta:t.meta}))).flat();return new Map(j.map(e=>[e.id,e]))}getPaths(A,j,e,t){return this.routeSuggester.getProposals(A,j,t).filter(i=>this.validPath(i,e)).map(i=>this.toHops(i,e))}async validateTokenPair(A,j,e){let t=await this.getAssets(e);if(t.get(A)==null)throw new Error(A+" is not supported token");if(t.get(j)==null)throw new Error(j+" is not supported token");let r=this.getPoolMap(e);return{assets:t,poolsMap:r}}async validateToken(A,j){let e=await this.getAssets(j);if(e.get(A)==null)throw new Error(A+" is not supported token");let t=this.getPoolMap(j);return{assets:e,poolsMap:t}}getPoolMap(A){return new Map(A.map(j=>[j.address,gj.get(j)]))}validPath(A,j){return A.length>0&&A.map(e=>this.validEdge(e,j)).reduce((e,t)=>e&&t)}validEdge([A,j,e],t){return t.get(A)?.validatePair(j,e)||!1}toHops(A,j){return A.map(([e,t,r])=>{let s=j.get(e);return{poolAddress:e,poolId:s?.id,pool:s?.type,assetIn:t,assetOut:r}})}toAssets(A,j){return A.map(e=>j.get(e))}};function T6(n,A){return n.minus(A).abs().div(n.plus(A).div(2)).multipliedBy(100).decimalPlaces(2)}function fj(n,A){return n.minus(A).div(A).multipliedBy(100).decimalPlaces(2)}function Ht(n,A){return $A.minus(A.div(n)).multipliedBy(100).decimalPlaces(2)}function Xt(n,A){return A.div(n).minus($A).multipliedBy(100).decimalPlaces(2)}var Wj=class extends ej{isDirectTrade(A){return A.length==1}findBestSellRoute(A){let j=A.sort((e,t)=>{let r=e[e.length-1].amountOut,s=t[t.length-1].amountOut;return r.isGreaterThan(s)?-1:1});return j.find(e=>e.every(t=>t.errors.length==0))||j[0]}getRouteFeeRange(A){if(A.filter(e=>e.tradeFeeRange).length>0){let e=A.map(r=>r.tradeFeeRange?.[0]??r.tradeFeePct).reduce((r,s)=>r+s),t=A.map(r=>r.tradeFeeRange?.[1]??r.tradeFeePct).reduce((r,s)=>r+s);return[e,t]}}getPoolFeeRange(A){let j=A.min?TA(A.min):void 0,e=A.max?TA(A.max):void 0;if(j&&e)return[j,e]}async getBestSell(A,j,e){let t=await super.getPools();if(t.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(A,j,t),s=super.getPaths(A,j,r,t);if(s.length===0)throw new uj(A,j);let i=s.map(async D=>await this.toSellSwaps(e,D,r)),a=await Promise.all(i),B=this.findBestSellRoute(a),f=B[0],P=B[B.length-1],I=this.isDirectTrade(B),$=B.map(D=>D.spotPrice.shiftedBy(-1*D.assetOutDecimals)).reduce((D,o)=>D.multipliedBy(o)),T=BA($,P.assetOutDecimals),v=I?P.calculatedOut:this.calculateDelta0Y(f.amountIn,B,r),x=P.amountOut,N=I?P.tradeFeePct:Ht(v,x).toNumber(),E=v.minus(x),M=this.getRouteFeeRange(B),tA=f.amountIn.shiftedBy(-1*f.assetInDecimals).multipliedBy(T),oA=fj(v,tA),W=D=>this.poolService.buildSellTx(A,j,f.amountIn,D,B.map(o=>o));return{type:"Sell",amountIn:f.amountIn,amountOut:P.amountOut,spotPrice:T,tradeFee:E,tradeFeePct:N,tradeFeeRange:M,priceImpactPct:oA.toNumber(),swaps:B,toTx:W,toHuman(){return{type:"Sell",amountIn:uA(f.amountIn,f.assetInDecimals),amountOut:uA(P.amountOut,P.assetOutDecimals),spotPrice:uA(T,P.assetOutDecimals),tradeFee:uA(E,P.assetOutDecimals),tradeFeePct:N,tradeFeeRange:M,priceImpactPct:oA.toNumber(),swaps:B.map(D=>D.toHuman())}}}}calculateDelta0Y(A,j,e){let t=[];for(let r=0;r<j.length;r++){let s=j[r],i=e.get(s.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(s.assetIn,s.assetOut),B;r>0?B=t[r-1]:B=A;let f=i.calculateOutGivenIn(a,B);t.push(f)}return t[t.length-1]}async toSellSwaps(A,j,e){let t=[];for(let r=0;r<j.length;r++){let s=j[r],i=e.get(s.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(s.assetIn,s.assetOut),B;r>0?B=t[r-1].amountOut:B=BA(K(A),a.decimalsIn).decimalPlaces(0,1);let f=await this.poolService.getPoolFees(a.assetOut,i),{amountOut:P,calculatedOut:I,feePct:$,errors:T}=i.validateAndSell(a,B,f),v=this.getPoolFeeRange(f),x=i.spotPriceOutGivenIn(a),N=B.shiftedBy(-1*a.decimalsIn).multipliedBy(x),E=fj(I,N);t.push({...s,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:B,calculatedOut:I,amountOut:P,spotPrice:x,tradeFeePct:$,tradeFeeRange:v,priceImpactPct:E.toNumber(),errors:T,toHuman(){return{...s,amountIn:uA(B,a.decimalsIn),calculatedOut:uA(I,a.decimalsOut),amountOut:uA(P,a.decimalsOut),spotPrice:uA(x,a.decimalsOut),tradeFeePct:$,tradeFeeRange:v,priceImpactPct:E.toNumber(),errors:T}}})}return t}async getBestSpotPrice(A,j){let e=await super.getPools();if(e.length===0)throw new Error("No pools configured");let{poolsMap:t}=await super.validateTokenPair(A,j,e),r=super.getPaths(A,j,t,e);if(r.length===0)return Promise.resolve(void 0);let s=r.map(async I=>await this.toSellSwaps("1",I,t)),i=await Promise.all(s),a=this.findBestSellRoute(i),B=a.map(I=>I.spotPrice.shiftedBy(-1*I.assetOutDecimals)).reduce((I,$)=>I.multipliedBy($)),f=a[a.length-1].assetOutDecimals;return{amount:BA(B,f),decimals:f}}findBestBuyRoute(A){let j=A.sort((e,t)=>{let r=e[0].amountIn,s=t[0].amountIn;return r.isGreaterThan(s)?1:-1});return j.find(e=>e.every(t=>t.errors.length==0))||j[0]}async getBestBuy(A,j,e){let t=await super.getPools();if(t.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(A,j,t),s=super.getPaths(A,j,r,t);if(s.length===0)throw new uj(A,j);let i=s.map(async D=>await this.toBuySwaps(e,D,r)),a=await Promise.all(i),B=this.findBestBuyRoute(a),f=B[B.length-1],P=B[0],I=this.isDirectTrade(B),$=B.map(D=>D.spotPrice.shiftedBy(-1*D.assetInDecimals)).reduce((D,o)=>D.multipliedBy(o)),T=BA($,P.assetInDecimals),v=I?P.calculatedIn:this.calculateDelta0X(f.amountOut,B,r),x=P.amountIn,N=I?P.tradeFeePct:Xt(v,x),E=x.minus(v),M=this.getRouteFeeRange(B),tA=f.amountOut.shiftedBy(-1*f.assetOutDecimals).multipliedBy(T),oA;v.isZero()?oA=-100:oA=fj(tA,v).toNumber();let W=D=>this.poolService.buildBuyTx(A,j,f.amountOut,D,B.map(o=>o));return{type:"Buy",amountOut:f.amountOut,amountIn:P.amountIn,spotPrice:T,tradeFee:E,tradeFeePct:N,tradeFeeRange:M,priceImpactPct:oA,swaps:B,toTx:W,toHuman(){return{type:"Buy",amountOut:uA(f.amountOut,f.assetOutDecimals),amountIn:uA(P.amountIn,P.assetInDecimals),spotPrice:uA(T,P.assetInDecimals),tradeFee:uA(E,P.assetInDecimals),tradeFeePct:N,tradeFeeRange:M,priceImpactPct:oA,swaps:B.map(D=>D.toHuman())}}}}calculateDelta0X(A,j,e){let t=[];for(let r=j.length-1;r>=0;r--){let s=j[r],i=e.get(s.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(s.assetIn,s.assetOut),B;r==j.length-1?B=A:B=t[0];let f=i.calculateInGivenOut(a,B);t.unshift(f)}return t[0]}async toBuySwaps(A,j,e){let t=[];for(let r=j.length-1;r>=0;r--){let s=j[r],i=e.get(s.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(s.assetIn,s.assetOut),B;r==j.length-1?B=BA(K(A),a.decimalsOut).decimalPlaces(0,1):B=t[0].amountIn;let f=await this.poolService.getPoolFees(a.assetOut,i),{amountIn:P,calculatedIn:I,feePct:$,errors:T}=i.validateAndBuy(a,B,f),v=this.getPoolFeeRange(f),x=i.spotPriceInGivenOut(a),N=B.shiftedBy(-1*a.decimalsOut).multipliedBy(x),E;I.isZero()?E=-100:E=fj(N,I).toNumber(),t.unshift({...s,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:B,calculatedIn:I,amountIn:P,spotPrice:x,tradeFeePct:$,tradeFeeRange:v,priceImpactPct:E,errors:T,toHuman(){return{...s,amountOut:uA(B,a.decimalsOut),calculatedIn:uA(I,a.decimalsIn),amountIn:uA(P,a.decimalsIn),spotPrice:uA(x,a.decimalsIn),tradeFeePct:$,tradeFeeRange:v,priceImpactPct:E,errors:T}}})}return t}};export{lj as AssetClient,Le as AssetNotFound,us as BASILISK_PARACHAIN_ID,cj as BalanceClient,MA as BigNumber,de as CachingPoolService,Ct as DECIMAL_PLACES,oe as DENOMINATOR,$j as HYDRADX_OMNIPOOL_ADDRESS,Bs as HYDRADX_PARACHAIN_ID,aj as HYDRADX_SS58_PREFIX,Wn as INFINITY,FA as LbpMath,CA as LbpPool,$A as ONE,iA as OmniMath,ZA as OmniPool,De as PoolConfigNotFound,sj as PoolError,gj as PoolFactory,Gj as PoolNotFound,_j as PoolService,bA as PoolType,Je as ProviderConfigNotFound,oj as RUNTIME_DECIMALS,uj as RouteNotFound,ej as Router,cs as SYSTEM_ASSET_DECIMALS,XA as SYSTEM_ASSET_ID,hA as StableMath,VA as StableSwap,He as StorageConfigNotFound,Xe as SubscriptionNotSupported,ie as TRADEABLE_DEFAULT,Wj as TradeRouter,fe as TradeType,LA as XykMath,zA as XykPool,Q as ZERO,K as bnum,le as buildRoute,Xt as calculateBuyFee,T6 as calculateDiffToAvg,fj as calculateDiffToRef,Ht as calculateSellFee,$e as findNestedKey,ds as findNestedObj,BA as scale};
|
|
1
|
+
var Ye=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var $t=5,Re=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new Ye,l=[];for(l.push([t,""]),i.enqueue(l);i.size()>0;){let u=i.dequeue();if(u==null||u.length>$t)return r;let h=u[u.length-1];(s===null||h[0]===s)&&r.push(u),e.get(h[0])?.forEach(w=>{if(this.isNotVisited(w,u)){let B=[...u];B.push(w),i.enqueue(B)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,l]of t){let u=parseInt(i),h=parseInt(l);s.get(u)?.push([h,r])}return s}};function pt(c){let e={};for(let t of c){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let i=0;i<s;i++){if(r==i)continue;let l=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(l)}}}return e}var Ee=class{getProposals(e,t,s){let r=pt(s),i=Object.keys(r),l=i.map(w=>r[w]).flat(),u=new Re,h=u.buildAndPopulateGraph(i,l),y=u.findPaths(h,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let l=s[i],u=s[i+1];if(u==null)break;r.push(this.toEdge(l,u))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var Jt=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,mt=Math.ceil,re=Math.floor,Q="[BigNumber Error] ",wt=Q+"Number primitive has more than 15 significant digits: ",ue=1e14,T=14,ht=9007199254740991,gt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Se=1e7,X=1e9;function Bt(c){var e,t,s,r=O.prototype={constructor:O,toString:null,valueOf:null},i=new O(1),l=20,u=4,h=-7,y=21,w=-1e7,B=1e7,N=!1,L=1,F=0,M={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},C="0123456789abcdefghijklmnopqrstuvwxyz",j=!0;function O(n,o){var a,P,m,d,S,p,g,b,f=this;if(!(f instanceof O))return new O(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<w?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!Jt.test(b=String(n)))return s(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(G(o,2,C.length,"Base"),o==10&&j)return f=new O(n),$(f,l+f.e+1,u);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return s(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,O.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(wt+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(a=C.slice(0,o),d=S=0,g=b.length;S<g;S++)if(a.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=g;continue}}else if(!m&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){m=!0,S=-1,d=0;continue}return s(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(g=b.length;b.charCodeAt(--g)===48;);if(b=b.slice(S,++g)){if(g-=S,p&&O.DEBUG&&g>15&&(n>ht||n!==re(n)))throw Error(wt+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<w)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%T,d<0&&(S+=T),S<g){for(S&&f.c.push(+b.slice(0,S)),g-=T;S<g;)f.c.push(+b.slice(S,S+=T));S=T-(b=b.slice(S)).length}else S-=g;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}O.clone=Bt,O.ROUND_UP=0,O.ROUND_DOWN=1,O.ROUND_CEIL=2,O.ROUND_FLOOR=3,O.ROUND_HALF_UP=4,O.ROUND_HALF_DOWN=5,O.ROUND_HALF_EVEN=6,O.ROUND_HALF_CEIL=7,O.ROUND_HALF_FLOOR=8,O.EUCLID=9,O.config=O.set=function(n){var o,a;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(a=n[o],G(a,0,X,o),l=a),n.hasOwnProperty(o="ROUNDING_MODE")&&(a=n[o],G(a,0,8,o),u=a),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(a=n[o],a&&a.pop?(G(a[0],-X,0,o),G(a[1],0,X,o),h=a[0],y=a[1]):(G(a,-X,X,o),h=-(y=a<0?-a:a))),n.hasOwnProperty(o="RANGE"))if(a=n[o],a&&a.pop)G(a[0],-X,-1,o),G(a[1],1,X,o),w=a[0],B=a[1];else if(G(a,-X,X,o),a)w=-(B=a<0?-a:a);else throw Error(Q+o+" cannot be zero: "+a);if(n.hasOwnProperty(o="CRYPTO"))if(a=n[o],a===!!a)if(a)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))N=a;else throw N=!a,Error(Q+"crypto unavailable");else N=a;else throw Error(Q+o+" not true or false: "+a);if(n.hasOwnProperty(o="MODULO_MODE")&&(a=n[o],G(a,0,9,o),L=a),n.hasOwnProperty(o="POW_PRECISION")&&(a=n[o],G(a,0,X,o),F=a),n.hasOwnProperty(o="FORMAT"))if(a=n[o],typeof a=="object")M=a;else throw Error(Q+o+" not an object: "+a);if(n.hasOwnProperty(o="ALPHABET"))if(a=n[o],typeof a=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(a))j=a.slice(0,10)=="0123456789",C=a;else throw Error(Q+o+" invalid: "+a)}else throw Error(Q+"Object expected: "+n);return{DECIMAL_PLACES:l,ROUNDING_MODE:u,EXPONENTIAL_AT:[h,y],RANGE:[w,B],CRYPTO:N,MODULO_MODE:L,POW_PRECISION:F,FORMAT:M,ALPHABET:C}},O.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!O.DEBUG)return!0;var o,a,P=n.c,m=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&m>=-X&&m<=X&&m===re(m)){if(P[0]===0){if(m===0&&P.length===1)return!0;break e}if(o=(m+1)%T,o<1&&(o+=T),String(P[0]).length==o){for(o=0;o<P.length;o++)if(a=P[o],a<0||a>=ue||a!==re(a))break e;if(a!==0)return!0}}}else if(P===null&&m===null&&(d===null||d===1||d===-1))return!0;throw Error(Q+"Invalid BigNumber: "+n)},O.maximum=O.max=function(){return be(arguments,-1)},O.minimum=O.min=function(){return be(arguments,1)},O.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return re(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(a){var P,m,d,S,p,g=0,b=[],f=new O(i);if(a==null?a=l:G(a,0,X),S=mt(a/T),N)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));g<S;)p=P[g]*131072+(P[g+1]>>>11),p>=9e15?(m=crypto.getRandomValues(new Uint32Array(2)),P[g]=m[0],P[g+1]=m[1]):(b.push(p%1e14),g+=2);g=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);g<S;)p=(P[g]&31)*281474976710656+P[g+1]*1099511627776+P[g+2]*4294967296+P[g+3]*16777216+(P[g+4]<<16)+(P[g+5]<<8)+P[g+6],p>=9e15?crypto.randomBytes(7).copy(P,g):(b.push(p%1e14),g+=7);g=S/7}else throw N=!1,Error(Q+"crypto unavailable");if(!N)for(;g<S;)p=o(),p<9e15&&(b[g++]=p%1e14);for(S=b[--g],a%=T,S&&a&&(p=gt[T-a],b[g]=re(S/p)*p);b[g]===0;b.pop(),g--);if(g<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=T);for(g=1,p=b[0];p>=10;p/=10,g++);g<T&&(d-=T-g)}return f.e=d,f.c=b,f}}(),O.sum=function(){for(var n=1,o=arguments,a=new O(o[0]);n<o.length;)a=a.plus(o[n++]);return a},t=function(){var n="0123456789";function o(a,P,m,d){for(var S,p=[0],g,b=0,f=a.length;b<f;){for(g=p.length;g--;p[g]*=P);for(p[0]+=d.indexOf(a.charAt(b++)),S=0;S<p.length;S++)p[S]>m-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/m|0,p[S]%=m)}return p.reverse()}return function(a,P,m,d,S){var p,g,b,f,x,v,I,R,q=a.indexOf("."),z=l,_=u;for(q>=0&&(f=F,F=0,a=a.replace(".",""),R=new O(P),v=R.pow(a.length-q),F=f,R.c=o(de(se(v.c),v.e,"0"),10,m,n),R.e=R.c.length),I=o(a,P,m,S?(p=C,n):(p=n,C)),b=f=I.length;I[--f]==0;I.pop());if(!I[0])return p.charAt(0);if(q<0?--b:(v.c=I,v.e=b,v.s=d,v=e(v,R,z,_,m),I=v.c,x=v.r,b=v.e),g=b+z+1,q=I[g],f=m/2,x=x||g<0||I[g+1]!=null,x=_<4?(q!=null||x)&&(_==0||_==(v.s<0?3:2)):q>f||q==f&&(_==4||x||_==6&&I[g-1]&1||_==(v.s<0?8:7)),g<1||!I[0])a=x?de(p.charAt(1),-z,p.charAt(0)):p.charAt(0);else{if(I.length=g,x)for(--m;++I[--g]>m;)I[g]=0,g||(++b,I=[1].concat(I));for(f=I.length;!I[--f];);for(q=0,a="";q<=f;a+=p.charAt(I[q++]));a=de(a,b,p.charAt(0))}return a}}(),e=function(){function n(P,m,d){var S,p,g,b,f=0,x=P.length,v=m%Se,I=m/Se|0;for(P=P.slice();x--;)g=P[x]%Se,b=P[x]/Se|0,S=I*g+b*v,p=v*g+S%Se*Se+f,f=(p/d|0)+(S/Se|0)+I*b,P[x]=p%d;return f&&(P=[f].concat(P)),P}function o(P,m,d,S){var p,g;if(d!=S)g=d>S?1:-1;else for(p=g=0;p<d;p++)if(P[p]!=m[p]){g=P[p]>m[p]?1:-1;break}return g}function a(P,m,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<m[d]?1:0,P[d]=p*S+P[d]-m[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,m,d,S,p){var g,b,f,x,v,I,R,q,z,_,D,J,We,ut,ct,me,_e,te=P.s==m.s?1:-1,K=P.c,H=m.c;if(!K||!K[0]||!H||!H[0])return new O(!P.s||!m.s||(K?H&&K[0]==H[0]:!H)?NaN:K&&K[0]==0||!H?te*0:te/0);for(q=new O(te),z=q.c=[],b=P.e-m.e,te=d+b+1,p||(p=ue,b=ie(P.e/T)-ie(m.e/T),te=te/T|0),f=0;H[f]==(K[f]||0);f++);if(H[f]>(K[f]||0)&&b--,te<0)z.push(1),x=!0;else{for(ut=K.length,me=H.length,f=0,te+=2,v=re(p/(H[0]+1)),v>1&&(H=n(H,v,p),K=n(K,v,p),me=H.length,ut=K.length),We=me,_=K.slice(0,me),D=_.length;D<me;_[D++]=0);_e=H.slice(),_e=[0].concat(_e),ct=H[0],H[1]>=p/2&&ct++;do{if(v=0,g=o(H,_,me,D),g<0){if(J=_[0],me!=D&&(J=J*p+(_[1]||0)),v=re(J/ct),v>1)for(v>=p&&(v=p-1),I=n(H,v,p),R=I.length,D=_.length;o(I,_,R,D)==1;)v--,a(I,me<R?_e:H,R,p),R=I.length,g=1;else v==0&&(g=v=1),I=H.slice(),R=I.length;if(R<D&&(I=[0].concat(I)),a(_,I,D,p),D=_.length,g==-1)for(;o(H,_,me,D)<1;)v++,a(_,me<D?_e:H,D,p),D=_.length}else g===0&&(v++,_=[0]);z[f++]=v,_[0]?_[D++]=K[We]||0:(_=[K[We]],D=1)}while((We++<ut||_[0]!=null)&&te--);x=_[0]!=null,z[0]||z.splice(0,1)}if(p==ue){for(f=1,te=z[0];te>=10;te/=10,f++);$(q,d+(q.e=f+b*T-1)+1,S,x)}else q.e=b,q.r=+x;return q}}();function ae(n,o,a,P){var m,d,S,p,g;if(a==null?a=u:G(a,0,8),!n.c)return n.toString();if(m=n.c[0],S=n.e,o==null)g=se(n.c),g=P==1||P==2&&(S<=h||S>=y)?Je(g,S):de(g,S,"0");else if(n=$(new O(n),o,a),d=n.e,g=se(n.c),p=g.length,P==1||P==2&&(o<=d||d<=h)){for(;p<o;g+="0",p++);g=Je(g,d)}else if(o-=S,g=de(g,d,"0"),d+1>p){if(--o>0)for(g+=".";o--;g+="0");}else if(o+=d-p,o>0)for(d+1==p&&(g+=".");o--;g+="0");return n.s<0&&m?"-"+g:g}function be(n,o){for(var a,P,m=1,d=new O(n[0]);m<n.length;m++)P=new O(n[m]),(!P.s||(a=xe(d,P))===o||a===0&&d.s===o)&&(d=P);return d}function le(n,o,a){for(var P=1,m=o.length;!o[--m];o.pop());for(m=o[0];m>=10;m/=10,P++);return(a=P+a*T-1)>B?n.c=n.e=null:a<w?n.c=[n.e=0]:(n.e=a,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,a=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,m=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,g){var b,f=p?S:S.replace(m,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(x,v,I){return b=(I=I.toLowerCase())=="x"?16:I=="b"?2:8,!g||g==b?v:x}),g&&(b=g,f=f.replace(o,"$1").replace(a,"0.$1")),S!=f))return new O(f,b);if(O.DEBUG)throw Error(Q+"Not a"+(g?" base "+g:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function $(n,o,a,P){var m,d,S,p,g,b,f,x=n.c,v=gt;if(x){e:{for(m=1,p=x[0];p>=10;p/=10,m++);if(d=o-m,d<0)d+=T,S=o,g=x[b=0],f=re(g/v[m-S-1]%10);else if(b=mt((d+1)/T),b>=x.length)if(P){for(;x.length<=b;x.push(0));g=f=0,m=1,d%=T,S=d-T+1}else break e;else{for(g=p=x[b],m=1;p>=10;p/=10,m++);d%=T,S=d-T+m,f=S<0?0:re(g/v[m-S-1]%10)}if(P=P||o<0||x[b+1]!=null||(S<0?g:g%v[m-S-1]),P=a<4?(f||P)&&(a==0||a==(n.s<0?3:2)):f>5||f==5&&(a==4||P||a==6&&(d>0?S>0?g/v[m-S]:0:x[b-1])%10&1||a==(n.s<0?8:7)),o<1||!x[0])return x.length=0,P?(o-=n.e+1,x[0]=v[(T-o%T)%T],n.e=-o||0):x[0]=n.e=0,n;if(d==0?(x.length=b,p=1,b--):(x.length=b+1,p=v[T-d],x[b]=S>0?re(g/v[m-S]%v[S])*p:0),P)for(;;)if(b==0){for(d=1,S=x[0];S>=10;S/=10,d++);for(S=x[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,x[0]==ue&&(x[0]=1));break}else{if(x[b]+=p,x[b]!=ue)break;x[b--]=0,p=1}for(d=x.length;x[--d]===0;x.pop());}n.e>B?n.c=n.e=null:n.e<w&&(n.c=[n.e=0])}return n}function k(n){var o,a=n.e;return a===null?n.toString():(o=se(n.c),o=a<=h||a>=y?Je(o,a):de(o,a,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new O(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return xe(this,new O(n,o))},r.decimalPlaces=r.dp=function(n,o){var a,P,m,d=this;if(n!=null)return G(n,0,X),o==null?o=u:G(o,0,8),$(new O(d),n+d.e+1,o);if(!(a=d.c))return null;if(P=((m=a.length-1)-ie(this.e/T))*T,m=a[m])for(;m%10==0;m/=10,P--);return P<0&&(P=0),P},r.dividedBy=r.div=function(n,o){return e(this,new O(n,o),l,u)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new O(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var a,P,m,d,S,p,g,b,f,x=this;if(n=new O(n),n.c&&!n.isInteger())throw Error(Q+"Exponent not an integer: "+k(n));if(o!=null&&(o=new O(o)),p=n.e>14,!x.c||!x.c[0]||x.c[0]==1&&!x.e&&x.c.length==1||!n.c||!n.c[0])return f=new O(Math.pow(+k(x),p?n.s*(2-$e(n)):+k(n))),o?f.mod(o):f;if(g=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new O(NaN);P=!g&&x.isInteger()&&o.isInteger(),P&&(x=x.mod(o))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||p&&x.c[1]>=24e7:x.c[0]<8e13||p&&x.c[0]<=9999975e7)))return d=x.s<0&&$e(n)?-0:0,x.e>-1&&(d=1/d),new O(g?1/d:d);F&&(d=mt(F/T+2))}for(p?(a=new O(.5),g&&(n.s=1),b=$e(n)):(m=Math.abs(+k(n)),b=m%2),f=new O(i);;){if(b){if(f=f.times(x),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(m){if(m=re(m/2),m===0)break;b=m%2}else if(n=n.times(a),$(n,n.e+1,1),n.e>14)b=$e(n);else{if(m=+k(n),m===0)break;b=m%2}x=x.times(x),d?x.c&&x.c.length>d&&(x.c.length=d):P&&(x=x.mod(o))}return P?f:(g&&(f=i.div(f)),o?f.mod(o):d?$(f,F,u,S):f)},r.integerValue=function(n){var o=new O(this);return n==null?n=u:G(n,0,8),$(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return xe(this,new O(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return xe(this,new O(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=xe(this,new O(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&ie(this.e/T)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return xe(this,new O(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=xe(this,new O(n,o)))===-1||o===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(n,o){var a,P,m,d,S=this,p=S.s;if(n=new O(n,o),o=n.s,!p||!o)return new O(NaN);if(p!=o)return n.s=-o,S.plus(n);var g=S.e/T,b=n.e/T,f=S.c,x=n.c;if(!g||!b){if(!f||!x)return f?(n.s=-o,n):new O(x?S:NaN);if(!f[0]||!x[0])return x[0]?(n.s=-o,n):new O(f[0]?S:u==3?-0:0)}if(g=ie(g),b=ie(b),f=f.slice(),p=g-b){for((d=p<0)?(p=-p,m=f):(b=g,m=x),m.reverse(),o=p;o--;m.push(0));m.reverse()}else for(P=(d=(p=f.length)<(o=x.length))?p:o,p=o=0;o<P;o++)if(f[o]!=x[o]){d=f[o]<x[o];break}if(d&&(m=f,f=x,x=m,n.s=-n.s),o=(P=x.length)-(a=f.length),o>0)for(;o--;f[a++]=0);for(o=ue-1;P>p;){if(f[--P]<x[P]){for(a=P;a&&!f[--a];f[a]=o);--f[a],f[P]+=ue}f[P]-=x[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?le(n,f,b):(n.s=u==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var a,P,m=this;return n=new O(n,o),!m.c||!n.s||n.c&&!n.c[0]?new O(NaN):!n.c||m.c&&!m.c[0]?new O(m):(L==9?(P=n.s,n.s=1,a=e(m,n,0,3),n.s=P,a.s*=P):a=e(m,n,0,L),n=m.minus(a.times(n)),!n.c[0]&&L==1&&(n.s=m.s),n)},r.multipliedBy=r.times=function(n,o){var a,P,m,d,S,p,g,b,f,x,v,I,R,q,z,_=this,D=_.c,J=(n=new O(n,o)).c;if(!D||!J||!D[0]||!J[0])return!_.s||!n.s||D&&!D[0]&&!J||J&&!J[0]&&!D?n.c=n.e=n.s=null:(n.s*=_.s,!D||!J?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=ie(_.e/T)+ie(n.e/T),n.s*=_.s,g=D.length,x=J.length,g<x&&(R=D,D=J,J=R,m=g,g=x,x=m),m=g+x,R=[];m--;R.push(0));for(q=ue,z=Se,m=x;--m>=0;){for(a=0,v=J[m]%z,I=J[m]/z|0,S=g,d=m+S;d>m;)b=D[--S]%z,f=D[S]/z|0,p=I*b+f*v,b=v*b+p%z*z+R[d]+a,a=(b/q|0)+(p/z|0)+I*f,R[d--]=b%q;R[d]=a}return a?++P:R.splice(0,1),le(n,R,P)},r.negated=function(){var n=new O(this);return n.s=-n.s||null,n},r.plus=function(n,o){var a,P=this,m=P.s;if(n=new O(n,o),o=n.s,!m||!o)return new O(NaN);if(m!=o)return n.s=-o,P.minus(n);var d=P.e/T,S=n.e/T,p=P.c,g=n.c;if(!d||!S){if(!p||!g)return new O(m/0);if(!p[0]||!g[0])return g[0]?n:new O(p[0]?P:m*0)}if(d=ie(d),S=ie(S),p=p.slice(),m=d-S){for(m>0?(S=d,a=g):(m=-m,a=p),a.reverse();m--;a.push(0));a.reverse()}for(m=p.length,o=g.length,m-o<0&&(a=g,g=p,p=a,o=m),m=0;o;)m=(p[--o]=p[o]+g[o]+m)/ue|0,p[o]=ue===p[o]?0:p[o]%ue;return m&&(p=[m].concat(p),++S),le(n,p,S)},r.precision=r.sd=function(n,o){var a,P,m,d=this;if(n!=null&&n!==!!n)return G(n,1,X),o==null?o=u:G(o,0,8),$(new O(d),n,o);if(!(a=d.c))return null;if(m=a.length-1,P=m*T+1,m=a[m]){for(;m%10==0;m/=10,P--);for(m=a[0];m>=10;m/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return G(n,-ht,ht),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,a,P,m,d=this,S=d.c,p=d.s,g=d.e,b=l+4,f=new O("0.5");if(p!==1||!S||!S[0])return new O(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+k(d)),p==0||p==1/0?(o=se(S),(o.length+g)%2==0&&(o+="0"),p=Math.sqrt(+o),g=ie((g+1)/2)-(g<0||g%2),p==1/0?o="5e"+g:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+g),a=new O(o)):a=new O(p+""),a.c[0]){for(g=a.e,p=g+b,p<3&&(p=0);;)if(m=a,a=f.times(m.plus(e(d,m,b,1))),se(m.c).slice(0,p)===(o=se(a.c)).slice(0,p))if(a.e<g&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&($(m,m.e+l+2,0),m.times(m).eq(d))){a=m;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&($(a,a.e+l+2,1),n=!a.times(a).eq(d));break}}return $(a,a.e+l+1,u,n)},r.toExponential=function(n,o){return n!=null&&(G(n,0,X),n++),ae(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(G(n,0,X),n=n+this.e+1),ae(this,n,o)},r.toFormat=function(n,o,a){var P,m=this;if(a==null)n!=null&&o&&typeof o=="object"?(a=o,o=null):n&&typeof n=="object"?(a=n,n=o=null):a=M;else if(typeof a!="object")throw Error(Q+"Argument not an object: "+a);if(P=m.toFixed(n,o),m.c){var d,S=P.split("."),p=+a.groupSize,g=+a.secondaryGroupSize,b=a.groupSeparator||"",f=S[0],x=S[1],v=m.s<0,I=v?f.slice(1):f,R=I.length;if(g&&(d=p,p=g,g=d,R-=d),p>0&&R>0){for(d=R%p||p,f=I.substr(0,d);d<R;d+=p)f+=b+I.substr(d,p);g>0&&(f+=b+I.slice(d)),v&&(f="-"+f)}P=x?f+(a.decimalSeparator||"")+((g=+a.fractionGroupSize)?x.replace(new RegExp("\\d{"+g+"}\\B","g"),"$&"+(a.fractionGroupSeparator||"")):x):f}return(a.prefix||"")+P+(a.suffix||"")},r.toFraction=function(n){var o,a,P,m,d,S,p,g,b,f,x,v,I=this,R=I.c;if(n!=null&&(p=new O(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(Q+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+k(p));if(!R)return new O(I);for(o=new O(i),b=a=new O(i),P=g=new O(i),v=se(R),d=o.e=v.length-I.e-1,o.c[0]=gt[(S=d%T)<0?T+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new O(v),g.c[0]=0;f=e(p,o,0,1),m=a.plus(f.times(P)),m.comparedTo(n)!=1;)a=P,P=m,b=g.plus(f.times(m=b)),g=m,o=p.minus(f.times(m=o)),p=m;return m=e(n.minus(a),P,0,1),g=g.plus(m.times(b)),a=a.plus(m.times(P)),g.s=b.s=I.s,d=d*2,x=e(b,P,d,u).minus(I).abs().comparedTo(e(g,a,d,u).minus(I).abs())<1?[b,P]:[g,a],B=S,x},r.toNumber=function(){return+k(this)},r.toPrecision=function(n,o){return n!=null&&G(n,1,X),ae(this,n,o,2)},r.toString=function(n){var o,a=this,P=a.s,m=a.e;return m===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=m<=h||m>=y?Je(se(a.c),m):de(se(a.c),m,"0"):n===10&&j?(a=$(new O(a),l+m+1,u),o=de(se(a.c),a.e,"0")):(G(n,2,C.length,"Base"),o=t(de(se(a.c),m,"0"),10,n,P,!0)),P<0&&a.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return k(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,c!=null&&O.set(c),O}function ie(c){var e=c|0;return c>0||c===e?e:e-1}function se(c){for(var e,t,s=1,r=c.length,i=c[0]+"";s<r;){for(e=c[s++]+"",t=T-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function xe(c,e){var t,s,r=c.c,i=e.c,l=c.s,u=e.s,h=c.e,y=e.e;if(!l||!u)return null;if(t=r&&!r[0],s=i&&!i[0],t||s)return t?s?0:-u:l;if(l!=u)return l;if(t=l<0,s=h==y,!r||!i)return s?0:!r^t?1:-1;if(!s)return h>y^t?1:-1;for(u=(h=r.length)<(y=i.length)?h:y,l=0;l<u;l++)if(r[l]!=i[l])return r[l]>i[l]^t?1:-1;return h==y?0:h>y^t?1:-1}function G(c,e,t,s){if(c<e||c>t||c!==re(c))throw Error(Q+(s||"Argument")+(typeof c=="number"?c<e||c>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(c))}function $e(c){var e=c.c.length-1;return ie(c.e/T)==e&&c.c[e]%2!=0}function Je(c,e){return(c.length>1?c.charAt(0)+"."+c.slice(1):c)+(e<0?"e":"e+")+e}function de(c,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);c=r+c}else if(s=c.length,++e>s){for(r=t,e-=s;--e;r+=t);c+=r}else e<s&&(c=c.slice(0,e)+"."+c.slice(e));return c}var fe=Bt();var jt=12;fe.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:jt});var E=A(0),ne=A(1),pr=A("Infinity");function W(c,e){let t=new fe(e.toString()),s=new fe(10).pow(t);return c.times(s)}function A(c){return new fe(c.toString())}var ee=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(ee||{}),ke=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(ke||{}),vt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(vt||{});import{calculate_in_given_out as Kt,calculate_out_given_in as Qt,calculate_linear_weights as Vt,calculate_pool_trade_fee as Zt,get_spot_price as es}from"@galacticcouncil/math-lbp";var ce=class{static getSpotPrice(e,t,s,r,i){return es(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return Kt(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return Qt(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return Vt(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Zt(e,t,s)}};import{encodeAddress as ts}from"@polkadot/util-crypto";import{stringToU8a as ss}from"@polkadot/util";var Le=18,dt=15,ye="0",br=12,Sr=2034,Me=63,yr=2090,ft=1e3,je=ts(ss("modlomnipool".padEnd(32,"\0")),Me);function It(c,e){let t;return JSON.stringify(c,(s,r)=>(r&&r[e]&&(t=r),r)),t}function Or(c,e,t){let s;return JSON.stringify(c,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";var Ie=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var De=class extends Ie{SUPPORTED_TYPES=["StableSwap","Bond","Token","External"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getToken(e,t,s,r){if(e==ye){let B=this.api.consts.balances.existentialDeposit;return{id:ye,name:this.chainToken,symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:B.toString()}}let{name:i,assetType:l,isSufficient:u,existentialDeposit:h}=t,{symbol:y,decimals:w}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:y,decimals:w,icon:y,type:l.toHuman(),isSufficient:u?u.toHuman():!0,origin:this.parseLocation("parachain",r),existentialDeposit:h.toString()}}getBond(e,t,s,r){let[i,l]=r,{assetType:u,isSufficient:h,existentialDeposit:y}=t,{symbol:w,decimals:B}=this.getToken(i.toString(),t,s),N=l.toNumber(),L=new Intl.DateTimeFormat("en-GB"),F=[w,"Bond",L.format(N)].join(" ");return{id:e,name:F,symbol:w+"b",decimals:B,icon:w,type:u.toString(),isSufficient:h.toHuman(),existentialDeposit:y.toString()}}getShares(e,t,s,r){let{assets:i}=r,{name:l,symbol:u,assetType:h,isSufficient:y,existentialDeposit:w}=t,N=i.map(M=>M.toString()).map(M=>{let{symbol:C}=this.getToken(M,t,s);return[M,C]}),L=Object.fromEntries(N),F=Object.values(L);return{id:e,name:F.join(", "),symbol:u?.isSome?u.toHuman():l.toHuman(),decimals:18,icon:F.join("/"),type:h.toString(),isSufficient:y.toHuman(),existentialDeposit:w.toString(),meta:L}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),l=this.parseLocation("generalIndex",r),u=s?.find(h=>h.id===l?.toString());return u?{...i,decimals:u.decimals,name:u.name,symbol:u.symbol,icon:u.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:l}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:l.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e){let[t,s,r,i,l]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),u=this.getSupportedAssets(t),h=this.normalizeMetadata(u,l);return u.map(([{args:[y]},w])=>{let B=w.unwrap(),N=s.get(y.toString()),{assetType:L}=B;switch(L.toString()){case"Bond":let F=i.get(y.toString());return this.getBond(y.toString(),B,h,F);case"StableSwap":let M=r.get(y.toString());return this.getShares(y.toString(),B,h,M);case"External":return this.getExternal(y.toString(),B,e,N);default:return this.getToken(y.toString(),B,h,N)}}).filter(y=>this.isValidAsset(y))}isValidAsset(e){return!!e.symbol&&!!e.decimals}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let s=It(t.toJSON(),e);return s&&s[e]}else return}};var Ce=class extends Ie{constructor(e){super(e)}async getBalance(e,t){return t===ye?await this.getSystemBalance(e):await this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeBalance(e,t,s){let r=t.filter(i=>i!==ye).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach(({free:l,reserved:u,frozen:h},y)=>{let w=this.calculateFreeBalance({free:l,feeFrozen:u,frozen:h}),B=r[y][1];s(B,w)})})}async subscribeTokenBalance(e,t,s){let r=t.filter(i=>i!==ye).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach((l,u)=>{let h=this.calculateFreeBalance(l),y=r[u][1];s(y,h)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(ye,this.calculateFreeBalance(s)))}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,l=new fe(t),u=new fe(s||i),h=new fe(r||0),y=u.gt(h)?u:h;return l.minus(y)}};var he=class extends Ce{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async s=>{let r=[await this.subscribePoolChange(s),await this.subscribeTokensPoolBalance(s),await this.subscribeSystemPoolBalance(s)];if(this.hasShareAsset(s)){let i=await this.subscribeSharePoolBalance(s);r.push(i)}return this.subscribeLog(s),r});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,s)=>t.id!==s))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance(je,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(s,r){let i=e.tokens.findIndex(l=>l.id==s);i>=0&&t(e,s)&&(e.tokens[i].balance=r.toString())}}};var Ke=class extends he{MAX_FINAL_WEIGHT=W(A(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,l])=>this.isActivePool(l.unwrap(),s)).map(async([{args:[i]},l])=>{let u=l.unwrap(),h=i.toString(),y=await this.getPoolDelta(h,u,s.toString());return this.poolsData.set(i.toString(),u),{address:h,type:"Lbp",fee:u.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let l=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,l)}else{let l=this.pools.findIndex(u=>u.address==e.address);this.pools.splice(l,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:l,initialWeight:u,finalWeight:h,repayTarget:y,feeCollector:w}=t,B=ce.calculateLinearWeights(r.toString(),i.toString(),u.toString(),h.toString(),s),[N,L]=l,F=N.toString(),M=A(B),C=L.toString(),j=this.MAX_FINAL_WEIGHT.minus(A(M)),[O,ae,be]=await Promise.all([this.isRepayFeeApplied(F,y.toString(),w.toString()),this.getBalance(e,F),this.getBalance(e,C)]);return{repayFeeApply:O,tokens:[{id:F,weight:M,balance:ae.toString()},{id:C,weight:j,balance:be.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=A(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{encodeAddress as rs}from"@polkadot/util-crypto";import{stringToU8a as is}from"@polkadot/util";function Y(c,e){return c.shiftedBy(-1*e).toString()}function oe(c){return c[0]/c[1]*100}function V(c){return c[0]/c[1]}function pe(c){return[c/ft,ft]}var Qe=class extends he{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),l=s.map(async([{args:[h]},y])=>{let{hubReserve:w,shares:B,tradable:N}=y.unwrap(),L=await this.getBalance(t,h.toString());return{id:h.toString(),hubReserves:A(w.toString()),shares:A(B.toString()),tradeable:N.bits.toNumber(),balance:L.toString()}}),u=await Promise.all(l);return u.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:u,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=await this.api.query.dynamicFees.assetFee(e),r=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,l=r.minFee.toNumber()+i.minFee.toNumber(),u=r.maxFee.toNumber()+i.maxFee.toNumber();if(s.isSome){let{assetFee:h,protocolFee:y}=s.unwrap();return{assetFee:pe(h.toNumber()),protocolFee:pe(y.toNumber()),min:pe(l),max:pe(u)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:pe(l),max:pe(u)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let l=e.tokens[i];if(r.isNone)return l;let u=r.unwrap();return this.updateTokenState(l,u)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i}=t;return{...e,hubReserves:A(s.toString()),shares:A(r.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return pe(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return pe(t)}getPoolId(){return rs(is("modlomnipool".padEnd(32,"\0")),Me)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var Ve=class extends he{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[l,u]=r.unwrap(),[h,y]=await Promise.all([this.getBalance(i,l.toString()),this.getBalance(i,u.toString())]);return{address:i,type:"Xyk",tokens:[{id:l.toString(),balance:h.toString()},{id:u.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{blake2AsHex as gs,encodeAddress as ds}from"@polkadot/util-crypto";import{calculate_in_given_out as ns,calculate_out_given_in as os,calculate_amplification as as,calculate_add_one_asset as ls,calculate_liquidity_out_one_asset as us,calculate_pool_trade_fee as cs,calculate_shares as ps,calculate_shares_for_amount as ms,pool_account_name as hs}from"@galacticcouncil/math-stableswap";var Z=class{static getPoolAddress(e){return hs(e)}static calculateAmplification(e,t,s,r,i){return as(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,l){return ns(e,t,s,r,i,l)}static calculateAddOneAsset(e,t,s,r,i,l){return ls(e,t,s,r,i,l)}static calculateSharesForAmount(e,t,s,r,i,l){return ms(e,t,s,r,i,l)}static calculateOutGivenIn(e,t,s,r,i,l){return os(e,t,s,r,i,l)}static calculateLiquidityOutOneAsset(e,t,s,r,i,l){return us(e,t,s,r,i,l)}static calculateShares(e,t,s,r,i){return ps(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return cs(e,t,s)}};var Ze=class extends he{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},l])=>{let u=l.unwrap(),h=i.toString(),y=this.getPoolAddress(h),[w,B]=await Promise.all([this.getPoolDelta(h,u,s.toString()),this.getPoolTokens(y,h,u)]);return this.stablePools.set(y,u),{address:y,id:h,type:"Stableswap",fee:pe(u.fee.toNumber()),tokens:B,...w,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toNumber(),r=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,r,s.toString());Object.assign(e,i)})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:l,finalBlock:u}=t,h=Z.calculateAmplification(r.toString(),i.toString(),l.toString(),u.toString(),s),y=await this.api.query.tokens.totalIssuance(e);return{amplification:h,totalIssuance:y.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async h=>{let[y,w]=await Promise.all([this.api.query.stableswap.assetTradability(t,h.toString()),this.getBalance(e,h.toString())]);return{id:h.toString(),tradeable:y.bits.toNumber(),balance:w.toString()}}),l=await Promise.all(i),u=await this.api.query.omnipool.assets(t);if(u.isSome){let{tradable:h}=u.unwrap(),y=await this.getBalance(je,t);l.push({id:t,tradeable:h.bits.toNumber(),balance:y.toString()})}return l}getPoolAddress(e){let t=Number(e),s=Z.getPoolAddress(t);return ds(gs(s),Me)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function Pt(c){return c.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var et=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},At=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ge=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Tt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Ft=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},_t=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var qe=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new De(this.api),this.xykClient=new Ve(this.api),this.omniClient=new Qe(this.api),this.lbpClient=new Ke(this.api),this.stableClient=new Ze(this.api)}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||(this.onChainAssets=await this.assetClient.getOnChainAssets(),this.onChainAssetsLoaded=!0),e.length==0){let l=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(u=>u.isSupported()).map(u=>u.getPools()))).flat();return this.withMetadata(l)}let t=[];e.forEach(i=>{switch(i){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break;case"Stableswap":t.push(this.stableClient.getPools());break}});let r=(await Promise.all(t)).flat();return this.withMetadata(r)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(s=>[s.id,s]));return e.filter(s=>s.type==="Xyk"?s.tokens.every(r=>t.get(r.id)):!0).map(s=>{let r=s.tokens.map(i=>{let l=t.get(i.id);return{...i,...l}});return{...s,tokens:r}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new et(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let l;this.isDirectOmnipoolTrade(i)?l=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):l=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),Pt(i));let u=()=>l;return{hex:l.toHex(),name:"RouterBuy",get:u}}buildSellTx(e,t,s,r,i){let l;this.isDirectOmnipoolTrade(i)?l=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):l=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),Pt(i));let u=()=>l;return{hex:l.toHex(),name:"RouterSell",get:u}}};var He=(c,e)=>c===e?0:c==null?e==null?0:-1:e==null?c==null?0:1:typeof c.compare=="function"?c.compare(e):typeof e.compare=="function"?-e.compare(c):c<e?-1:c>e?1:0;var tt=(c,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(c(t)+e(t))}};var fs=tt(()=>"illegal argument(s)"),Rt=c=>{throw new fs(c)};var Ps=tt(()=>"index out of bounds"),bt=c=>{throw new Ps(c)},st=(c,e,t)=>(c<e||c>=t)&&bt(c);var Et=23283064365386963e-26,rt=class{float(e=1){return this.int()*Et*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Et-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var St=Math.random,yt=class extends rt{int(){return St()*4294967296>>>0}float(e=1){return St()*e}norm(e=1){return(St()-.5)*2*e}},kt=new yt;var Lt=c=>c!=null&&typeof c!="function"&&c.length!==void 0;var Mt=Object.getPrototypeOf({}),it="function",Dt="string",Ae=(c,e)=>{let t;if(c===e)return!0;if(c!=null){if(typeof c.equiv===it)return c.equiv(e)}else return c==e;if(e!=null){if(typeof e.equiv===it)return e.equiv(c)}else return c==e;return typeof c===Dt||typeof e===Dt?!1:(t=Object.getPrototypeOf(c),(t==null||t===Mt)&&(t=Object.getPrototypeOf(e),t==null||t===Mt)?xs(c,e):typeof c!==it&&c.length!==void 0&&typeof e!==it&&e.length!==void 0?bs(c,e):c instanceof Set&&e instanceof Set?Ss(c,e):c instanceof Map&&e instanceof Map?ys(c,e):c instanceof Date&&e instanceof Date?c.getTime()===e.getTime():c instanceof RegExp&&e instanceof RegExp?c.toString()===e.toString():c!==c&&e!==e)},bs=(c,e,t=Ae)=>{let s=c.length;if(s===e.length)for(;s-- >0&&t(c[s],e[s]););return s<0},Ss=(c,e,t=Ae)=>c.size===e.size&&t([...c.keys()].sort(),[...e.keys()].sort()),ys=(c,e,t=Ae)=>c.size===e.size&&t([...c].sort(),[...e].sort()),xs=(c,e,t=Ae)=>{if(Object.keys(c).length!==Object.keys(e).length)return!1;for(let s in c)if(!e.hasOwnProperty(s)||!t(c[s],e[s]))return!1;return!0};var Ct=(c,e)=>c!=null&&typeof c[e]=="function";var Gt=c=>Ct(c,"xform")?c.xform():c;var nt=Symbol(),xt=()=>{};var qt=c=>c!=null&&typeof c[Symbol.iterator]=="function";var ot=class{value;constructor(e){this.value=e}deref(){return this.value}};var at=c=>c instanceof ot;var Ht=c=>c instanceof ot?c.deref():c;function*Ut(c,e){let t=Gt(c)([xt,xt,(s,r)=>r])[2];for(let s of e){let r=t(nt,s);if(at(r)){r=Ht(r.deref()),r!==nt&&(yield r);return}r!==nt&&(yield r)}}var zt=(c,e)=>[c[0],c[1],e];function Ue(c,e){return qt(e)?Ut(Ue(c),e):t=>{let s=t[2];return zt(t,(r,i)=>s(r,c(i)))}}var Ne=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Xt("next",this._head)}reverseIterator(){return Xt("prev",this.tail)}clear(){this.release()}compare(e,t=He){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,l=0;for(;s-- >0&&l===0;)l=t(r.value,i.value),r=r.next,i=i.next;return l}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof Ne||Lt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!Ae(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||He;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!at(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&bt(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*Xt(c,e){for(;e;)yield e.value,e=e[c]}var ge=class extends Ne{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new ge(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new ge}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(st(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(st(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new ge,e)}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let s=this.nthCell(e),r=this.nthCell(t-1),i=l=>({first(){return l.value},next(){return l!==r&&l.next?i(l.next):void 0}});return s?i(s):void 0}shuffle(e,t=kt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&Rt("invalid indices: ${from} / ${to}");let i=new ge,l=this.nthCell(s);for(;l&&++s<=r;)i.push(l.value),l=l.next;return i}sort(e=He){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,l=0;for(let h=0;h<t&&(l++,i=i.next,!!i);h++);let u=t;for(;l>0||u>0&&i;){let h;l===0?(h=i,i=i.next,u--):!i||u===0||e(s.value,i.value)<=0?(h=s,s=s.next,l--):(h=i,i=i.next,u--),this._tail?this._tail.next=h:this._head=h,h.prev=this._tail,this._tail=h}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),st(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new ge;if(t>0)for(;r&&t-- >0;)this.remove(r),i.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let l of s)this.insertBefore(r,l);else for(let l of s)this.push(l);return i}};var Te=class{map;items;opts;_size;constructor(e,t){let s=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=s.map(),this.items=new ge,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ue(e=>[e.k,e],this.items)}keys(){return Ue(e=>e.k,this.items)}values(){return Ue(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new Te(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e);return this._size+=Math.max(0,s-(r?r.value.s:0)),this.ensureSize()&&this.doSetEntry(r,e,t,s),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let s=this.map.get(e);return s?Promise.resolve(this.resetEntry(s)):t().then(r=>this.set(e,r))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,s=this.opts.maxlen;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e&&e(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Ot=class extends qe{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Te(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
+
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Oe=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Oe(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,l,u){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=l,this.repayFeeApply=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(h=>[h.id,h])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=A(r.balance),u=A(i.balance);return{assetIn:e,assetOut:t,balanceIn:l,balanceOut:u,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(l)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let u=this.calculateTradeFee(t,s),h=oe(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(u),w=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return w.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:w,calculatedIn:w,amountOut:t,feePct:h,errors:i}}else{let u=this.calculateInGivenOut(e,t),h=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(h)&&i.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(l)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let u=this.calculateOutGivenIn(e,t),h=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(h)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:u,amountOut:u,feePct:0,errors:i}}else{let u=this.calculateOutGivenIn(e,t),h=this.calculateTradeFee(u,s),y=oe(this.repayFeeApply?s.repayFee:s.exchangeFee),w=u.minus(h),B=e.balanceOut.div(this.maxOutRatio);return w.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:u,amountOut:w,feePct:y,errors:i}}}calculateInGivenOut(e,t){let s=ce.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=A(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=ce.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=A(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=ce.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),W(ne,e.decimalsOut).toString());return A(t)}spotPriceOutGivenIn(e){let t=ce.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),W(ne,e.decimalsIn).toString());return A(t)}calculateTradeFee(e,t){let s=ce.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return A(s)}};import{calculate_in_given_out as Os,calculate_lrna_in_given_out as ws,calculate_out_given_in as Bs,calculate_out_given_lrna_in as vs,calculate_pool_trade_fee as Is,calculate_spot_price as As,calculate_lrna_spot_price as Ns,calculate_shares as Ts,calculate_liquidity_out as Fs,calculate_liquidity_lrna_out as _s,calculate_cap_difference as Rs,verify_asset_cap as Es,calculate_liquidity_hub_in as ks,is_sell_allowed as Ls,is_buy_allowed as Ms,is_add_liquidity_allowed as Ds,is_remove_liquidity_allowed as Cs}from"@galacticcouncil/math-omnipool";var U=class{static calculateSpotPrice(e,t,s,r){return As(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return Ns(e,t)}static calculateInGivenOut(e,t,s,r,i,l,u,h,y){return Os(e,t,s,r,i,l,u,h,y)}static calculateLrnaInGivenOut(e,t,s,r,i){return ws(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,l,u,h,y){return Bs(e,t,s,r,i,l,u,h,y)}static calculateOutGivenLrnaIn(e,t,s,r,i){return vs(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Is(e,t,s)}static calculateShares(e,t,s,r){return Ts(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,l,u,h){return Fs(e,t,s,r,i,l,u,h)}static calculateLiquidityLRNAOut(e,t,s,r,i,l,u,h){return _s(e,t,s,r,i,l,u,h)}static calculateCapDifference(e,t,s,r){return Rs(e,t,s,r)}static verifyAssetCap(e,t,s,r){return Es(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return ks(e,t,s,r)}static isSellAllowed(e){return Ls(e)}static isBuyAllowed(e){return Ms(e)}static isAddLiquidityAllowed(e){return Ds(e)}static isRemoveLiquidityAllowed(e){return Cs(e)}};var we=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new we(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,l){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=l}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(h=>[h.id,h])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=A(r.balance),u=A(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:l,balanceOut:u,tradeableIn:r.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),l=i.minus(r),u=r===E?E:l.div(r).multipliedBy(100).decimalPlaces(2),h=[],y=U.isSellAllowed(e.tradeableIn),w=U.isBuyAllowed(e.tradeableOut);(!y||!w)&&h.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&h.push("MaxOutRatioExceeded");let N=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(N)&&h.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:u.toNumber(),errors:h}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),u=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),h=[],y=U.isSellAllowed(e.tradeableIn),w=U.isBuyAllowed(e.tradeableOut);(!y||!w)&&h.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&h.push("MaxInRatioExceeded");let N=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(N)&&h.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:u.toNumber(),errors:h}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=U.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?V(s.assetFee).toString():E.toString(),s?V(s.protocolFee).toString():E.toString()),i=A(r);return i.isNegative()?E:i}calculateLrnaInGivenOut(e,t,s){let r=U.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?V(s.assetFee).toString():E.toString()),i=A(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=U.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?V(s.assetFee).toString():E.toString(),s?V(s.protocolFee).toString():E.toString()),i=A(r);return i.isNegative()?E:i}calculateOutGivenLrnaIn(e,t,s){let r=U.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?V(s.assetFee).toString():E.toString()),i=A(r);return i.isNegative()?E:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=U.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return A(t).shiftedBy(-1*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=U.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return A(t).shiftedBy(-1*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=U.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return A(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=U.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return A(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}};var Be=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Be(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,i,l,u,h,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=l,this.id=u,this.fee=h,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(h=>[h.id,h])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=A(r.balance),u=A(i.balance);return{assetIn:e,assetOut:t,balanceIn:l,balanceOut:u,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?dt:r.tradeable,tradeableOut:this.id===t?dt:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),l=oe(s.fee),u=[],h=U.isSellAllowed(e.tradeableIn),y=U.isBuyAllowed(e.tradeableOut);return(!h||!y)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:l,errors:u}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),l=oe(s.fee),u=[],h=U.isSellAllowed(e.tradeableIn),y=U.isBuyAllowed(e.tradeableOut);return(!h||!y)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:l,errors:u}}calculateIn(e,t,s){let r=Z.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?V(s.fee).toString():E.toString()),i=A(r);return i.isNegative()?E:i}calculateAddOneAsset(e,t,s){let r=Z.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?V(s.fee).toString():E.toString()),i=A(r);return i.isNegative()?E:i}calculateSharesForAmount(e,t,s){let r=Z.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?V(s.fee).toString():E.toString()),i=A(r);return i.isNegative()?E:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=W(ne,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,s){let r=Z.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?V(s.fee).toString():E.toString()),i=A(r);return i.isNegative()?E:i}calculateWithdrawOneAsset(e,t,s){let r=Z.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?V(s.fee).toString():E.toString()),i=A(r);return i.isNegative()?E:i}calculateShares(e,t,s){let r=Z.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?V(s.fee).toString():E.toString()),i=A(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=W(ne,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=Z.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return A(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{calculate_in_given_out as Gs,calculate_out_given_in as qs,calculate_pool_trade_fee as Hs,get_spot_price as Us,calculate_liquidity_in as zs,calculate_shares as Xs,calculate_liquidity_out_asset_a as Ws,calculate_liquidity_out_asset_b as Ys}from"@galacticcouncil/math-xyk";var Pe=class{static getSpotPrice(e,t,s){return Us(e,t,s)}static calculateInGivenOut(e,t,s){return Gs(e,t,s)}static calculateOutGivenIn(e,t,s){return qs(e,t,s)}static calculatePoolTradeFee(e,t,s){return Hs(e,t,s)}static calculateLiquidityIn(e,t,s){return zs(e,t,s)}static calculateShares(e,t,s){return Xs(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return Ws(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Ys(e,t,s,r)}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(h=>[h.id,h])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=A(r.balance),u=A(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:l,balanceOut:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),l=oe(s.exchangeFee),u=r.plus(i),h=[];t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&h.push("MaxOutRatioExceeded");let w=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(w)&&h.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:r,amountOut:t,feePct:l,errors:h}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),l=oe(s.exchangeFee),u=r.minus(i),h=[];t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&h.push("MaxInRatioExceeded");let w=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(w)&&h.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:u,feePct:l,errors:h}}calculateInGivenOut(e,t){let s=Pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=A(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=Pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=A(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=Pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),W(ne,e.decimalsOut).toString());return A(t)}spotPriceOutGivenIn(e){let t=Pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),W(ne,e.decimalsIn).toString());return A(t)}calculateTradeFee(e,t){let s=Pe.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return A(s)}};var ze=class{static get(e){switch(e.type){case"Xyk":return ve.fromPool(e);case"Omnipool":return we.fromPool(e);case"Lbp":return Oe.fromPool(e);case"Stableswap":return Be.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Fe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ee,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),l=this.getPaths(e,null,r,t).map(u=>u[u.length-1].assetOut);return this.toAssets([...new Set(l)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,origin:r.origin,meta:r.meta}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(u=>this.validPath(u,s)).map(u=>this.toHops(u,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,ze.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let l=t.get(s);return{poolAddress:s,poolId:l?.id,pool:l?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function bl(c,e){return c.minus(e).abs().div(c.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Xe(c,e){return c.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Wt(c,e){return ne.minus(e.div(c)).multipliedBy(100).decimalPlaces(2)}function Yt(c,e){return e.div(c).minus(ne).multipliedBy(100).decimalPlaces(2)}var lt=class extends Fe{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,l=r[r.length-1].amountOut;return i.isGreaterThan(l)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,l)=>i+l),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,l)=>i+l);return[s,r]}}getPoolFeeRange(e){let t=e.min?oe(e.min):void 0,s=e.max?oe(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,r),l=super.getPaths(e,t,i,r);if(l.length===0)throw new Ge(e,t);let u=l.map(async k=>await this.toSellSwaps(s,k,i)),h=await Promise.all(u),y=this.findBestSellRoute(h),w=y[0],B=y[y.length-1],N=this.isDirectTrade(y),L=y.map(k=>k.spotPrice.shiftedBy(-1*k.assetOutDecimals)).reduce((k,n)=>k.multipliedBy(n)),F=W(L,B.assetOutDecimals),M=N?B.calculatedOut:this.calculateDelta0Y(w.amountIn,y,i),C=B.amountOut,j=N?B.tradeFeePct:Wt(M,C).toNumber(),O=M.minus(C),ae=this.getRouteFeeRange(y),be=w.amountIn.shiftedBy(-1*w.assetInDecimals).multipliedBy(F),le=Xe(M,be),$=k=>this.poolService.buildSellTx(e,t,w.amountIn,k,y.map(n=>n));return{type:"Sell",amountIn:w.amountIn,amountOut:B.amountOut,spotPrice:F,tradeFee:O,tradeFeePct:j,tradeFeeRange:ae,priceImpactPct:le.toNumber(),swaps:y,toTx:$,toHuman(){return{type:"Sell",amountIn:Y(w.amountIn,w.assetInDecimals),amountOut:Y(B.amountOut,B.assetOutDecimals),spotPrice:Y(F,B.assetOutDecimals),tradeFee:Y(O,B.assetOutDecimals),tradeFeePct:j,tradeFeeRange:ae,priceImpactPct:le.toNumber(),swaps:y.map(k=>k.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let l=t[i],u=s.get(l.poolAddress);if(u==null)throw new Error("Pool does not exit");let h=u.parsePair(l.assetIn,l.assetOut),y;i>0?y=r[i-1]:y=e;let w=u.calculateOutGivenIn(h,y);r.push(w)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let l=t[i],u=s.get(l.poolAddress);if(u==null)throw new Error("Pool does not exit");let h=u.parsePair(l.assetIn,l.assetOut),y;i>0?y=r[i-1].amountOut:y=W(A(e),h.decimalsIn).decimalPlaces(0,1);let w=await this.poolService.getPoolFees(h.assetOut,u),{amountOut:B,calculatedOut:N,feePct:L,errors:F}=u.validateAndSell(h,y,w),M=this.getPoolFeeRange(w),C=u.spotPriceOutGivenIn(h),j=y.shiftedBy(-1*h.decimalsIn).multipliedBy(C),O=Xe(N,j);r.push({...l,assetInDecimals:h.decimalsIn,assetOutDecimals:h.decimalsOut,amountIn:y,calculatedOut:N,amountOut:B,spotPrice:C,tradeFeePct:L,tradeFeeRange:M,priceImpactPct:O.toNumber(),errors:F,toHuman(){return{...l,amountIn:Y(y,h.decimalsIn),calculatedOut:Y(N,h.decimalsOut),amountOut:Y(B,h.decimalsOut),spotPrice:Y(C,h.decimalsOut),tradeFeePct:L,tradeFeeRange:M,priceImpactPct:O.toNumber(),errors:F}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let l=i.map(async N=>await this.toSellSwaps("1",N,r)),u=await Promise.all(l),h=this.findBestSellRoute(u),y=h.map(N=>N.spotPrice.shiftedBy(-1*N.assetOutDecimals)).reduce((N,L)=>N.multipliedBy(L)),w=h[h.length-1].assetOutDecimals;return{amount:W(y,w),decimals:w}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,l=r[0].amountIn;return i.isGreaterThan(l)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,r),l=super.getPaths(e,t,i,r);if(l.length===0)throw new Ge(e,t);let u=l.map(async k=>await this.toBuySwaps(s,k,i)),h=await Promise.all(u),y=this.findBestBuyRoute(h),w=y[y.length-1],B=y[0],N=this.isDirectTrade(y),L=y.map(k=>k.spotPrice.shiftedBy(-1*k.assetInDecimals)).reduce((k,n)=>k.multipliedBy(n)),F=W(L,B.assetInDecimals),M=N?B.calculatedIn:this.calculateDelta0X(w.amountOut,y,i),C=B.amountIn,j=N?B.tradeFeePct:Yt(M,C).toNumber(),O=C.minus(M),ae=this.getRouteFeeRange(y),be=w.amountOut.shiftedBy(-1*w.assetOutDecimals).multipliedBy(F),le;M.isZero()?le=-100:le=Xe(be,M).toNumber();let $=k=>this.poolService.buildBuyTx(e,t,w.amountOut,k,y.map(n=>n));return{type:"Buy",amountOut:w.amountOut,amountIn:B.amountIn,spotPrice:F,tradeFee:O,tradeFeePct:j,tradeFeeRange:ae,priceImpactPct:le,swaps:y,toTx:$,toHuman(){return{type:"Buy",amountOut:Y(w.amountOut,w.assetOutDecimals),amountIn:Y(B.amountIn,B.assetInDecimals),spotPrice:Y(F,B.assetInDecimals),tradeFee:Y(O,B.assetInDecimals),tradeFeePct:j,tradeFeeRange:ae,priceImpactPct:le,swaps:y.map(k=>k.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let l=t[i],u=s.get(l.poolAddress);if(u==null)throw new Error("Pool does not exit");let h=u.parsePair(l.assetIn,l.assetOut),y;i==t.length-1?y=e:y=r[0];let w=u.calculateInGivenOut(h,y);r.unshift(w)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let l=t[i],u=s.get(l.poolAddress);if(u==null)throw new Error("Pool does not exit");let h=u.parsePair(l.assetIn,l.assetOut),y;i==t.length-1?y=W(A(e),h.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let w=await this.poolService.getPoolFees(h.assetOut,u),{amountIn:B,calculatedIn:N,feePct:L,errors:F}=u.validateAndBuy(h,y,w),M=this.getPoolFeeRange(w),C=u.spotPriceInGivenOut(h),j=y.shiftedBy(-1*h.decimalsOut).multipliedBy(C),O;N.isZero()?O=-100:O=Xe(j,N).toNumber(),r.unshift({...l,assetInDecimals:h.decimalsIn,assetOutDecimals:h.decimalsOut,amountOut:y,calculatedIn:N,amountIn:B,spotPrice:C,tradeFeePct:L,tradeFeeRange:M,priceImpactPct:O,errors:F,toHuman(){return{...l,amountOut:Y(y,h.decimalsOut),calculatedIn:Y(N,h.decimalsIn),amountIn:Y(B,h.decimalsIn),spotPrice:Y(C,h.decimalsIn),tradeFeePct:L,tradeFeeRange:M,priceImpactPct:O,errors:F}}})}return r}};export{De as AssetClient,Nt as AssetNotFound,yr as BASILISK_PARACHAIN_ID,Ce as BalanceClient,fe as BigNumber,Ot as CachingPoolService,jt as DECIMAL_PLACES,ft as DENOMINATOR,je as HYDRADX_OMNIPOOL_ADDRESS,Sr as HYDRADX_PARACHAIN_ID,Me as HYDRADX_SS58_PREFIX,pr as INFINITY,ce as LbpMath,Oe as LbpPool,ne as ONE,U as OmniMath,we as OmniPool,At as PoolConfigNotFound,ke as PoolError,ze as PoolFactory,et as PoolNotFound,qe as PoolService,ee as PoolType,_t as ProviderConfigNotFound,Le as RUNTIME_DECIMALS,Ge as RouteNotFound,Fe as Router,br as SYSTEM_ASSET_DECIMALS,ye as SYSTEM_ASSET_ID,Z as StableMath,Be as StableSwap,Tt as StorageConfigNotFound,Ft as SubscriptionNotSupported,dt as TRADEABLE_DEFAULT,lt as TradeRouter,vt as TradeType,Pe as XykMath,ve as XykPool,E as ZERO,A as bnum,Pt as buildRoute,Yt as calculateBuyFee,bl as calculateDiffToAvg,Xe as calculateDiffToRef,Wt as calculateSellFee,It as findNestedKey,Or as findNestedObj,W as scale};
|
package/package.json
CHANGED
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|