@galacticcouncil/sdk 1.2.0 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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 ws={};as(ws,{AssetClient:()=>Le,AssetNotFound:()=>Nt,BASILISK_PARACHAIN_ID:()=>ds,BalanceClient:()=>Me,BigNumber:()=>fe,CachingPoolService:()=>Pt,DECIMAL_PLACES:()=>Gt,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:()=>It,PoolError:()=>_e,PoolFactory:()=>Ue,PoolNotFound:()=>Je,PoolService:()=>Ce,PoolType:()=>se,ProviderConfigNotFound:()=>Ft,RUNTIME_DECIMALS:()=>Re,RouteNotFound:()=>De,Router:()=>Fe,SYSTEM_ASSET_DECIMALS:()=>hs,SYSTEM_ASSET_ID:()=>Oe,StableMath:()=>ee,StableSwap:()=>Ne,StorageConfigNotFound:()=>At,SubscriptionNotSupported:()=>Tt,TRADEABLE_DEFAULT:()=>st,TradeRouter:()=>Ve,TradeType:()=>vt,XykMath:()=>ye,XykPool:()=>Ae,ZERO:()=>E,bnum:()=>I,buildRoute:()=>ut,calculateBuyFee:()=>Mt,calculateDiffToAvg:()=>Os,calculateDiffToRef:()=>ze,calculateSellFee:()=>Lt,scale:()=>Y});module.exports=us(ws);var Ke=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 Ke,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] ",Dt=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 Ct(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,A=!1,M=1,_=0,C={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},G="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(!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&&J)return f=new O(n),Q(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(Dt+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(Dt+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=Ct,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))A=a;else throw A=!a,Error(te+"crypto unavailable");else A=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")C=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))J=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:A,MODULO_MODE:M,POW_PRECISION:_,FORMAT:C,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),A)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 A=!1,Error(te+"crypto unavailable");if(!A)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,N,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),N=o(a,P,m,S?(p=G,n):(p=n,G)),b=f=N.length;N[--f]==0;N.pop());if(!N[0])return p.charAt(0);if(H<0?--b:(v.c=N,v.e=b,v.s=d,v=e(v,k,X,R,m),N=v.c,x=v.r,b=v.e),g=b+X+1,H=N[g],f=m/2,x=x||g<0||N[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&&N[g-1]&1||R==(v.s<0?8:7)),g<1||!N[0])a=x?xe(p.charAt(1),-X,p.charAt(0)):p.charAt(0);else{if(N.length=g,x)for(--m;++N[--g]>m;)N[g]=0,g||(++b,N=[1].concat(N));for(f=N.length;!N[--f];);for(H=0,a="";H<=f;a+=p.charAt(N[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,N=m/Be|0;for(P=P.slice();x--;)g=P[x]%Be,b=P[x]/Be|0,S=N*g+b*v,p=v*g+S%Be*Be+f,f=(p/d|0)+(S/Be|0)+N*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,N,k,H,X,R,D,V,Ze,bt,St,de,Xe,ne=P.s==m.s?1:-1,K=P.c,U=m.c;if(!K||!K[0]||!U||!U[0])return new O(!P.s||!m.s||(K?U&&K[0]==U[0]:!U)?NaN:K&&K[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]==(K[f]||0);f++);if(U[f]>(K[f]||0)&&b--,ne<0)X.push(1),x=!0;else{for(bt=K.length,de=U.length,f=0,ne+=2,v=ae(p/(U[0]+1)),v>1&&(U=n(U,v,p),K=n(K,v,p),de=U.length,bt=K.length),Ze=de,R=K.slice(0,de),D=R.length;D<de;R[D++]=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,D),g<0){if(V=R[0],de!=D&&(V=V*p+(R[1]||0)),v=ae(V/St),v>1)for(v>=p&&(v=p-1),N=n(U,v,p),k=N.length,D=R.length;o(N,R,k,D)==1;)v--,a(N,de<k?Xe:U,k,p),k=N.length,g=1;else v==0&&(g=v=1),N=U.slice(),k=N.length;if(k<D&&(N=[0].concat(N)),a(R,N,D,p),D=R.length,g==-1)for(;o(U,R,de,D)<1;)v++,a(R,de<D?Xe:U,D,p),D=R.length}else g===0&&(v++,R=[0]);X[f++]=v,R[0]?R[D++]=K[Ze]||0:(R=[K[Ze]],D=1)}while((Ze++<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++);Q(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=Q(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,N){return b=(N=N.toLowerCase())=="x"?16:N=="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 Q(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),Q(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),Q(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?Q(f,_,c,S):f)},r.integerValue=function(n){var o=new O(this);return n==null?n=c:q(n,0,8),Q(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,N,k,H,X,R=this,D=R.c,V=(n=new O(n,o)).c;if(!D||!V||!D[0]||!V[0])return!R.s||!n.s||D&&!D[0]&&!V||V&&!V[0]&&!D?n.c=n.e=n.s=null:(n.s*=R.s,!D||!V?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=D.length,x=V.length,g<x&&(k=D,D=V,V=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=V[m]%X,N=V[m]/X|0,S=g,d=m+S;d>m;)b=D[--S]%X,f=D[S]/X|0,p=N*b+f*v,b=v*b+p%X*X+k[d]+a,a=(b/H|0)+(p/X|0)+N*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),Q(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&&(Q(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")&&(Q(a,a.e+l+2,1),n=!a.times(a).eq(d));break}}return Q(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=C;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,N=v?f.slice(1):f,k=N.length;if(g&&(d=p,p=g,g=d,k-=d),p>0&&k>0){for(d=k%p||p,f=N.substr(0,d);d<k;d+=p)f+=b+N.substr(d,p);g>0&&(f+=b+N.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,N=this,k=N.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(N);for(o=new O(i),b=a=new O(i),P=g=new O(i),v=oe(k),d=o.e=v.length-N.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=N.s,d=d*2,x=e(b,P,d,c).minus(N).abs().comparedTo(e(g,a,d,c).minus(N).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&&J?(a=Q(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=Ct();var Gt=12;fe.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Gt});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 qt=require("@polkadot/util-crypto"),Ht=require("@polkadot/util"),Re=18,st=15,Oe="0",hs=12,gs=2034,Ee=63,ds=2090,rt=1e3,$e=(0,qt.encodeAddress)((0,Ht.stringToU8a)("modlomnipool".padEnd(32,"\0")),Ee);function Ut(u,e){let t;return JSON.stringify(u,(s,r)=>(r&&r[e]&&(t=r),r)),t}var Js=require("@polkadot/types/lookup");var js=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 Ks=require("@polkadot/api-base/types/submittable");var er=require("@polkadot/rpc-core/types/jsonrpc");var tr=require("@polkadot/api-base/types/calls");var ur=require("@polkadot/types/types/registry");var hr=require("@polkadot/types/lookup");var gr=require("@polkadot/api-base/types/consts");var dr=require("@polkadot/api-base/types/errors");var fr=require("@polkadot/api-base/types/events");var Pr=require("@polkadot/api-base/types/storage");var br=require("@polkadot/api-base/types/submittable");var Sr=require("@polkadot/rpc-core/types/jsonrpc");var yr=require("@polkadot/api-base/types/calls");var Ar=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"];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([])}}getTokens(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",existentialDeposit:B.toString()}}let{name:i,assetType:l,existentialDeposit:c}=t,{symbol:h,decimals:y}=s.get(e)??{},w=r?r.get(e):void 0;return{id:e,name:i.toHuman(),symbol:h,decimals:y,icon:h,type:l.toHuman(),origin:w&&this.parseLocation(w),existentialDeposit:c.toString()}}getBonds(e,t,s,r){let[i,l]=r,{assetType:c,existentialDeposit:h}=t,{symbol:y,decimals:w}=this.getTokens(i.toString(),t,s),B=l.toNumber(),A=new Intl.DateTimeFormat("en-GB"),M=[y,"Bond",A.format(B)].join(" ");return{id:e,name:M,symbol:y+"b",decimals:w,icon:y,type:c.toString(),existentialDeposit:h.toString()}}getShares(e,t,s,r){let{assets:i}=r,{name:l,symbol:c,assetType:h,existentialDeposit:y}=t,B=i.map(_=>_.toString()).map(_=>{let{symbol:C}=this.getTokens(_,t,s);return[_,C]}),A=Object.fromEntries(B),M=Object.values(A);return{id:e,name:M.join(", "),symbol:c?.isSome?c.toHuman():l.toHuman(),decimals:18,icon:M.join("/"),type:h.toString(),existentialDeposit:y.toString(),meta:A}}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=t.filter(([{args:[y]},w])=>{if(w.isNone)return!1;let B=w.unwrap(),A=e?.find(M=>M.id===y.toString());return this.isSupportedAsset(B,A)}),h=l.size?l:new Map(c.map(([{args:[y]},w])=>{let{decimals:B,symbol:A}=w.unwrap();return[y.toString(),{decimals:Number(B.toString()),symbol:A.toHuman()}]}));return c.map(([{args:[y]},w])=>{let B=w.unwrap(),{assetType:A}=B;switch(A.toString()){case"Bond":let M=i.get(y.toString());return this.getBonds(y.toString(),B,h,M);case"StableSwap":let _=r.get(y.toString());return this.getShares(y.toString(),B,h,_);case"External":let C=e?.find(J=>J.id===y.toString());return{...this.getTokens(y.toString(),B,new Map,s),...C};default:return this.getTokens(y.toString(),B,h,s)}})}isSupportedAsset(e,t){let s=e.assetType.toString();return this.SUPPORTED_TYPES.includes(s)||!!t&&s==="External"}parseLocation(e){if(e){let t=Ut(e.toJSON(),"parachain");return t&&t.parachain}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),[A,M]=l,_=A.toString(),C=I(B),G=M.toString(),J=this.MAX_FINAL_WEIGHT.minus(I(C)),[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:C,balance:pe.toString()},{id:G,weight:J,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:A}=y.unwrap(),M=await this.getBalance(t,h.toString());return{id:h.toString(),hubReserves:I(w.toString()),shares:I(B.toString()),tradeable:A.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"}},It=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"}},At=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Tt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Ft=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 fs=ct(()=>"illegal argument(s)"),Wt=u=>{throw new fs(u)};var Ps=ct(()=>"index out of bounds"),_t=u=>{throw new Ps(u)},pt=(u,e,t)=>(u<e||u>=t)&&_t(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 Rt=Math.random,Et=class extends mt{int(){return Rt()*4294967296>>>0}float(e=1){return Rt()*e}norm(e=1){return(Rt()-.5)*2*e}},$t=new Et;var Jt=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var jt=Object.getPrototypeOf({}),ht="function",Qt="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===Qt||typeof e===Qt?!1:(t=Object.getPrototypeOf(u),(t==null||t===jt)&&(t=Object.getPrototypeOf(e),t==null||t===jt)?xs(u,e):typeof u!==ht&&u.length!==void 0&&typeof e!==ht&&e.length!==void 0?bs(u,e):u instanceof Set&&e instanceof Set?Ss(u,e):u instanceof Map&&e instanceof Map?ys(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)},bs=(u,e,t=Ge)=>{let s=u.length;if(s===e.length)for(;s-- >0&&t(u[s],e[s]););return s<0},Ss=(u,e,t=Ge)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),ys=(u,e,t=Ge)=>u.size===e.size&&t([...u].sort(),[...e].sort()),xs=(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 Vt=(u,e)=>u!=null&&typeof u[e]=="function";var Zt=u=>Vt(u,"xform")?u.xform():u;var gt=Symbol(),kt=()=>{};var Kt=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=Zt(u)([kt,kt,(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 Qe(u,e){return Kt(e)?ts(Qe(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&&_t(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 Qe(e=>[e.k,e],this.items)}keys(){return Qe(e=>e.k,this.items)}values(){return Qe(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 A=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(A)&&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 A=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(A)&&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 Ne=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Ne(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 Z=require("@galacticcouncil/math-xyk"),ye=class{static getSpotPrice(e,t,s){return(0,Z.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,Z.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,Z.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,Z.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,Z.calculate_liquidity_in)(e,t,s)}static calculateShares(e,t,s){return(0,Z.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,Z.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,Z.calculate_liquidity_out_asset_b)(e,t,s,r)}};var Ae=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Ae(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 Ae.fromPool(e);case"Omnipool":return Ie.fromPool(e);case"Lbp":return ve.fromPool(e);case"Stableswap":return Ne.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,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 Os(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 Lt(u,e){return ie.minus(e.div(u)).multipliedBy(100).decimalPlaces(2)}function Mt(u,e){return e.div(u).minus(ie).multipliedBy(100).decimalPlaces(2)}var Ve=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],A=this.isDirectTrade(y),M=y.map(L=>L.spotPrice.shiftedBy(-1*L.assetOutDecimals)).reduce((L,n)=>L.multipliedBy(n)),_=Y(M,B.assetOutDecimals).decimalPlaces(0,1),C=A?B.calculatedOut:this.calculateDelta0Y(w.amountIn,y,i),G=B.amountOut,J=A?B.tradeFeePct:Lt(C,G).toNumber(),O=C.minus(G),pe=this.getRouteFeeRange(y),we=w.amountIn.shiftedBy(-1*w.assetInDecimals).multipliedBy(_),me=ze(C,we),Q=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:J,tradeFeeRange:pe,priceImpactPct:me.toNumber(),swaps:y,toTx:Q,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:J,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:A,feePct:M,errors:_}=c.validateAndSell(h,y,w),C=this.getPoolFeeRange(w),G=c.spotPriceOutGivenIn(h),J=y.shiftedBy(-1*h.decimalsIn).multipliedBy(G),O=ze(A,J);r.push({...l,assetInDecimals:h.decimalsIn,assetOutDecimals:h.decimalsOut,amountIn:y,calculatedOut:A,amountOut:B,spotPrice:G,tradeFeePct:M,tradeFeeRange:C,priceImpactPct:O.toNumber(),errors:_,toHuman(){return{...l,amountIn:j(y,h.decimalsIn),calculatedOut:j(A,h.decimalsOut),amountOut:j(B,h.decimalsOut),spotPrice:j(G,h.decimalsOut),tradeFeePct:M,tradeFeeRange:C,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 A=>await this.toSellSwaps("1",A,r)),c=await Promise.all(l),h=this.findBestSellRoute(c),y=h.map(A=>A.spotPrice.shiftedBy(-1*A.assetOutDecimals)).reduce((A,M)=>A.multipliedBy(M)),w=h[h.length-1].assetOutDecimals;return{amount:Y(y,w).decimalPlaces(0,1),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],A=this.isDirectTrade(y),M=y.map(L=>L.spotPrice.shiftedBy(-1*L.assetInDecimals)).reduce((L,n)=>L.multipliedBy(n)),_=Y(M,B.assetInDecimals).decimalPlaces(0,1),C=A?B.calculatedIn:this.calculateDelta0X(w.amountOut,y,i),G=B.amountIn,J=A?B.tradeFeePct:Mt(C,G),O=G.minus(C),pe=this.getRouteFeeRange(y),we=w.amountOut.shiftedBy(-1*w.assetOutDecimals).multipliedBy(_),me;C.isZero()?me=-100:me=ze(we,C).toNumber();let Q=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:J,tradeFeeRange:pe,priceImpactPct:me,swaps:y,toTx:Q,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:J,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:A,feePct:M,errors:_}=c.validateAndBuy(h,y,w),C=this.getPoolFeeRange(w),G=c.spotPriceInGivenOut(h),J=y.shiftedBy(-1*h.decimalsOut).multipliedBy(G),O;A.isZero()?O=-100:O=ze(J,A).toNumber(),r.unshift({...l,assetInDecimals:h.decimalsIn,assetOutDecimals:h.decimalsOut,amountOut:y,calculatedIn:A,amountIn:B,spotPrice:G,tradeFeePct:M,tradeFeeRange:C,priceImpactPct:O,errors:_,toHuman(){return{...l,amountOut:j(y,h.decimalsOut),calculatedIn:j(A,h.decimalsIn),amountIn:j(B,h.decimalsIn),spotPrice:j(G,h.decimalsIn),tradeFeePct:M,tradeFeeRange:C,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,scale});
|
|
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).decimalPlaces(0,1),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).decimalPlaces(0,1),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).decimalPlaces(0,1),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});
|