@galacticcouncil/sdk 2.2.3 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var St=Object.defineProperty;var is=Object.getOwnPropertyDescriptor;var ns=Object.getOwnPropertyNames;var os=Object.prototype.hasOwnProperty;var as=(u,e)=>{for(var t in e)St(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&&St(u,r,{get:()=>e[r],enumerable:!(s=is(e,r))||s.enumerable});return u};var us=u=>ls(St({},"__esModule",{value:!0}),u);var Bs={};as(Bs,{AssetClient:()=>Le,AssetNotFound:()=>Nt,BASILISK_PARACHAIN_ID:()=>ds,BalanceClient:()=>Me,BigNumber:()=>V,CachingPoolService:()=>Pt,DECIMAL_PLACES:()=>qt,DENOMINATOR:()=>rt,HYDRADX_OMNIPOOL_ADDRESS:()=>$e,HYDRADX_PARACHAIN_ID:()=>hs,HYDRADX_SS58_PREFIX:()=>Ee,INFINITY:()=>ms,LbpMath:()=>me,LbpPool:()=>Be,ONE:()=>oe,OmniMath:()=>z,OmniPool:()=>ve,PoolConfigNotFound:()=>At,PoolError:()=>_e,PoolFactory:()=>Ue,PoolNotFound:()=>Je,PoolService:()=>Ce,PoolType:()=>ie,ProviderConfigNotFound:()=>_t,RUNTIME_DECIMALS:()=>Re,RouteNotFound:()=>De,Router:()=>Fe,SYSTEM_ASSET_DECIMALS:()=>gs,SYSTEM_ASSET_ID:()=>Oe,StableMath:()=>se,StableSwap:()=>Ie,StorageConfigNotFound:()=>Tt,SubscriptionNotSupported:()=>Ft,TRADEABLE_DEFAULT:()=>st,TradeRouter:()=>Qe,TradeType:()=>vt,XykMath:()=>Se,XykPool:()=>Ae,ZERO:()=>E,bnum:()=>I,buildRoute:()=>ut,calculateBuyFee:()=>Dt,calculateDiffToAvg:()=>ws,calculateDiffToRef:()=>ze,calculateSellFee:()=>Mt,findNestedKey:()=>It,findNestedObj:()=>fs,scale:()=>$});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,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>cs)return r;let p=c[c.length-1];(s===null||p[0]===s)&&r.push(c),e.get(p[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,a]of t){let c=parseInt(i),p=parseInt(a);s.get(c)?.push([p,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 a=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(a)}}}return e}var Ye=class{getProposals(e,t,s){let r=xt(s),i=Object.keys(r),a=i.map(w=>r[w]).flat(),c=new We,p=c.buildAndPopulateGraph(i,a),S=c.findPaths(p,parseInt(e),t?parseInt(t):null);return this.parsePaths(S)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let a=s[i],c=s[i+1];if(c==null)break;r.push(this.toEdge(a,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,ce=Math.floor,re="[BigNumber Error] ",Ct=re+"Number primitive has more than 15 significant digits: ",he=1e14,N=14,wt=9007199254740991,Bt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],we=1e7,Y=1e9;function Gt(u){var e,t,s,r=x.prototype={constructor:x,toString:null,valueOf:null},i=new x(1),a=20,c=4,p=-7,S=21,w=-1e7,B=1e7,T=!1,k=1,F=0,G={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},D="0123456789abcdefghijklmnopqrstuvwxyz",K=!0;function x(n,o){var l,P,g,d,y,m,h,b,f=this;if(!(f instanceof x))return new x(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((m=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,y=n;y>=10;y/=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,m);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(y=b.search(/e/i))>0?(d<0&&(d=y),d+=+b.slice(y+1),b=b.substring(0,y)):d<0&&(d=b.length)}else{if(q(o,2,D.length,"Base"),o==10&&K)return f=new x(n),_(f,a+f.e+1,c);if(b=String(n),m=typeof n=="number"){if(n*0!=0)return s(f,b,m,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,x.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(l=D.slice(0,o),d=y=0,h=b.length;y<h;y++)if(l.indexOf(P=b.charAt(y))<0){if(P=="."){if(y>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,y=-1,d=0;continue}return s(f,String(n),m,o)}m=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(y=0;b.charCodeAt(y)===48;y++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(y,++h)){if(h-=y,m&&x.DEBUG&&h>15&&(n>wt||n!==ce(n)))throw Error(Ct+f.s*n);if((d=d-y-1)>B)f.c=f.e=null;else if(d<w)f.c=[f.e=0];else{if(f.e=d,f.c=[],y=(d+1)%N,d<0&&(y+=N),y<h){for(y&&f.c.push(+b.slice(0,y)),h-=N;y<h;)f.c.push(+b.slice(y,y+=N));y=N-(b=b.slice(y)).length}else y-=h;for(;y--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}x.clone=Gt,x.ROUND_UP=0,x.ROUND_DOWN=1,x.ROUND_CEIL=2,x.ROUND_FLOOR=3,x.ROUND_HALF_UP=4,x.ROUND_HALF_DOWN=5,x.ROUND_HALF_EVEN=6,x.ROUND_HALF_CEIL=7,x.ROUND_HALF_FLOOR=8,x.EUCLID=9,x.config=x.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],q(l,0,Y,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],q(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(q(l[0],-Y,0,o),q(l[1],0,Y,o),p=l[0],S=l[1]):(q(l,-Y,Y,o),p=-(S=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)q(l[0],-Y,-1,o),q(l[1],1,Y,o),w=l[0],B=l[1];else if(q(l,-Y,Y,o),l)w=-(B=l<0?-l:l);else throw Error(re+o+" cannot be zero: "+l);if(n.hasOwnProperty(o="CRYPTO"))if(l=n[o],l===!!l)if(l)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))T=l;else throw T=!l,Error(re+"crypto unavailable");else T=l;else throw Error(re+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],q(l,0,9,o),k=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],q(l,0,Y,o),F=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")G=l;else throw Error(re+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))K=l.slice(0,10)=="0123456789",D=l;else throw Error(re+o+" invalid: "+l)}else throw Error(re+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[p,S],RANGE:[w,B],CRYPTO:T,MODULO_MODE:k,POW_PRECISION:F,FORMAT:G,ALPHABET:D}},x.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!x.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-Y&&g<=Y&&g===ce(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%N,o<1&&(o+=N),String(P[0]).length==o){for(o=0;o<P.length;o++)if(l=P[o],l<0||l>=he||l!==ce(l))break e;if(l!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(re+"Invalid BigNumber: "+n)},x.maximum=x.max=function(){return ae(arguments,-1)},x.minimum=x.min=function(){return ae(arguments,1)},x.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ce(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,y,m,h=0,b=[],f=new x(i);if(l==null?l=a:q(l,0,Y),y=Ot(l/N),T)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(y*=2));h<y;)m=P[h]*131072+(P[h+1]>>>11),m>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(m%1e14),h+=2);h=y/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(y*=7);h<y;)m=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],m>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(m%1e14),h+=7);h=y/7}else throw T=!1,Error(re+"crypto unavailable");if(!T)for(;h<y;)m=o(),m<9e15&&(b[h++]=m%1e14);for(y=b[--h],l%=N,y&&l&&(m=Bt[N-l],b[h]=ce(y/m)*m);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=N);for(h=1,m=b[0];m>=10;m/=10,h++);h<N&&(d-=N-h)}return f.e=d,f.c=b,f}}(),x.sum=function(){for(var n=1,o=arguments,l=new x(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var y,m=[0],h,b=0,f=l.length;b<f;){for(h=m.length;h--;m[h]*=P);for(m[0]+=d.indexOf(l.charAt(b++)),y=0;y<m.length;y++)m[y]>g-1&&(m[y+1]==null&&(m[y+1]=0),m[y+1]+=m[y]/g|0,m[y]%=g)}return m.reverse()}return function(l,P,g,d,y){var m,h,b,f,O,v,A,L,H=l.indexOf("."),W=a,R=c;for(H>=0&&(f=F,F=0,l=l.replace(".",""),L=new x(P),v=L.pow(l.length-H),F=f,L.c=o(xe(ue(v.c),v.e,"0"),10,g,n),L.e=L.c.length),A=o(l,P,g,y?(m=D,n):(m=n,D)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return m.charAt(0);if(H<0?--b:(v.c=A,v.e=b,v.s=d,v=e(v,L,W,R,g),A=v.c,O=v.r,b=v.e),h=b+W+1,H=A[h],f=g/2,O=O||h<0||A[h+1]!=null,O=R<4?(H!=null||O)&&(R==0||R==(v.s<0?3:2)):H>f||H==f&&(R==4||O||R==6&&A[h-1]&1||R==(v.s<0?8:7)),h<1||!A[0])l=O?xe(m.charAt(1),-W,m.charAt(0)):m.charAt(0);else{if(A.length=h,O)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(H=0,l="";H<=f;l+=m.charAt(A[H++]));l=xe(l,b,m.charAt(0))}return l}}(),e=function(){function n(P,g,d){var y,m,h,b,f=0,O=P.length,v=g%we,A=g/we|0;for(P=P.slice();O--;)h=P[O]%we,b=P[O]/we|0,y=A*h+b*v,m=v*h+y%we*we+f,f=(m/d|0)+(y/we|0)+A*b,P[O]=m%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,y){var m,h;if(d!=y)h=d>y?1:-1;else for(m=h=0;m<d;m++)if(P[m]!=g[m]){h=P[m]>g[m]?1:-1;break}return h}function l(P,g,d,y){for(var m=0;d--;)P[d]-=m,m=P[d]<g[d]?1:0,P[d]=m*y+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,y,m){var h,b,f,O,v,A,L,H,W,R,C,Q,Ve,bt,yt,fe,Xe,le=P.s==g.s?1:-1,te=P.c,U=g.c;if(!te||!te[0]||!U||!U[0])return new x(!P.s||!g.s||(te?U&&te[0]==U[0]:!U)?NaN:te&&te[0]==0||!U?le*0:le/0);for(H=new x(le),W=H.c=[],b=P.e-g.e,le=d+b+1,m||(m=he,b=pe(P.e/N)-pe(g.e/N),le=le/N|0),f=0;U[f]==(te[f]||0);f++);if(U[f]>(te[f]||0)&&b--,le<0)W.push(1),O=!0;else{for(bt=te.length,fe=U.length,f=0,le+=2,v=ce(m/(U[0]+1)),v>1&&(U=n(U,v,m),te=n(te,v,m),fe=U.length,bt=te.length),Ve=fe,R=te.slice(0,fe),C=R.length;C<fe;R[C++]=0);Xe=U.slice(),Xe=[0].concat(Xe),yt=U[0],U[1]>=m/2&&yt++;do{if(v=0,h=o(U,R,fe,C),h<0){if(Q=R[0],fe!=C&&(Q=Q*m+(R[1]||0)),v=ce(Q/yt),v>1)for(v>=m&&(v=m-1),A=n(U,v,m),L=A.length,C=R.length;o(A,R,L,C)==1;)v--,l(A,fe<L?Xe:U,L,m),L=A.length,h=1;else v==0&&(h=v=1),A=U.slice(),L=A.length;if(L<C&&(A=[0].concat(A)),l(R,A,C,m),C=R.length,h==-1)for(;o(U,R,fe,C)<1;)v++,l(R,fe<C?Xe:U,C,m),C=R.length}else h===0&&(v++,R=[0]);W[f++]=v,R[0]?R[C++]=te[Ve]||0:(R=[te[Ve]],C=1)}while((Ve++<bt||R[0]!=null)&&le--);O=R[0]!=null,W[0]||W.splice(0,1)}if(m==he){for(f=1,le=W[0];le>=10;le/=10,f++);_(H,d+(H.e=f+b*N-1)+1,y,O)}else H.e=b,H.r=+O;return H}}();function ee(n,o,l,P){var g,d,y,m,h;if(l==null?l=c:q(l,0,8),!n.c)return n.toString();if(g=n.c[0],y=n.e,o==null)h=ue(n.c),h=P==1||P==2&&(y<=p||y>=S)?tt(h,y):xe(h,y,"0");else if(n=_(new x(n),o,l),d=n.e,h=ue(n.c),m=h.length,P==1||P==2&&(o<=d||d<=p)){for(;m<o;h+="0",m++);h=tt(h,d)}else if(o-=y,h=xe(h,d,"0"),d+1>m){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-m,o>0)for(d+1==m&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function ae(n,o){for(var l,P,g=1,d=new x(n[0]);g<n.length;g++)P=new x(n[g]),(!P.s||(l=Te(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function Ne(n,o,l){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(l=P+l*N-1)>B?n.c=n.e=null:l<w?n.c=[n.e=0]:(n.e=l,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,y,m,h){var b,f=m?y:y.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!m&&(f=f.replace(n,function(O,v,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?v:O}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),y!=f))return new x(f,b);if(x.DEBUG)throw Error(re+"Not a"+(h?" base "+h:"")+" number: "+y);d.s=null}d.c=d.e=null}}();function _(n,o,l,P){var g,d,y,m,h,b,f,O=n.c,v=Bt;if(O){e:{for(g=1,m=O[0];m>=10;m/=10,g++);if(d=o-g,d<0)d+=N,y=o,h=O[b=0],f=ce(h/v[g-y-1]%10);else if(b=Ot((d+1)/N),b>=O.length)if(P){for(;O.length<=b;O.push(0));h=f=0,g=1,d%=N,y=d-N+1}else break e;else{for(h=m=O[b],g=1;m>=10;m/=10,g++);d%=N,y=d-N+g,f=y<0?0:ce(h/v[g-y-1]%10)}if(P=P||o<0||O[b+1]!=null||(y<0?h:h%v[g-y-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?y>0?h/v[g-y]:0:O[b-1])%10&1||l==(n.s<0?8:7)),o<1||!O[0])return O.length=0,P?(o-=n.e+1,O[0]=v[(N-o%N)%N],n.e=-o||0):O[0]=n.e=0,n;if(d==0?(O.length=b,m=1,b--):(O.length=b+1,m=v[N-d],O[b]=y>0?ce(h/v[g-y]%v[y])*m:0),P)for(;;)if(b==0){for(d=1,y=O[0];y>=10;y/=10,d++);for(y=O[0]+=m,m=1;y>=10;y/=10,m++);d!=m&&(n.e++,O[0]==he&&(O[0]=1));break}else{if(O[b]+=m,O[b]!=he)break;O[b--]=0,m=1}for(d=O.length;O[--d]===0;O.pop());}n.e>B?n.c=n.e=null:n.e<w&&(n.c=[n.e=0])}return n}function X(n){var o,l=n.e;return l===null?n.toString():(o=ue(n.c),o=l<=p||l>=S?tt(o,l):xe(o,l,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new x(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return Te(this,new x(n,o))},r.decimalPlaces=r.dp=function(n,o){var l,P,g,d=this;if(n!=null)return q(n,0,Y),o==null?o=c:q(o,0,8),_(new x(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-pe(this.e/N))*N,g=l[g])for(;g%10==0;g/=10,P--);return P<0&&(P=0),P},r.dividedBy=r.div=function(n,o){return e(this,new x(n,o),a,c)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new x(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var l,P,g,d,y,m,h,b,f,O=this;if(n=new x(n),n.c&&!n.isInteger())throw Error(re+"Exponent not an integer: "+X(n));if(o!=null&&(o=new x(o)),m=n.e>14,!O.c||!O.c[0]||O.c[0]==1&&!O.e&&O.c.length==1||!n.c||!n.c[0])return f=new x(Math.pow(+X(O),m?n.s*(2-et(n)):+X(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new x(NaN);P=!h&&O.isInteger()&&o.isInteger(),P&&(O=O.mod(o))}else{if(n.e>9&&(O.e>0||O.e<-1||(O.e==0?O.c[0]>1||m&&O.c[1]>=24e7:O.c[0]<8e13||m&&O.c[0]<=9999975e7)))return d=O.s<0&&et(n)?-0:0,O.e>-1&&(d=1/d),new x(h?1/d:d);F&&(d=Ot(F/N+2))}for(m?(l=new x(.5),h&&(n.s=1),b=et(n)):(g=Math.abs(+X(n)),b=g%2),f=new x(i);;){if(b){if(f=f.times(O),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(g){if(g=ce(g/2),g===0)break;b=g%2}else if(n=n.times(l),_(n,n.e+1,1),n.e>14)b=et(n);else{if(g=+X(n),g===0)break;b=g%2}O=O.times(O),d?O.c&&O.c.length>d&&(O.c.length=d):P&&(O=O.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?_(f,F,c,y):f)},r.integerValue=function(n){var o=new x(this);return n==null?n=c:q(n,0,8),_(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return Te(this,new x(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return Te(this,new x(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=Te(this,new x(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&pe(this.e/N)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return Te(this,new x(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=Te(this,new x(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 l,P,g,d,y=this,m=y.s;if(n=new x(n,o),o=n.s,!m||!o)return new x(NaN);if(m!=o)return n.s=-o,y.plus(n);var h=y.e/N,b=n.e/N,f=y.c,O=n.c;if(!h||!b){if(!f||!O)return f?(n.s=-o,n):new x(O?y:NaN);if(!f[0]||!O[0])return O[0]?(n.s=-o,n):new x(f[0]?y:c==3?-0:0)}if(h=pe(h),b=pe(b),f=f.slice(),m=h-b){for((d=m<0)?(m=-m,g=f):(b=h,g=O),g.reverse(),o=m;o--;g.push(0));g.reverse()}else for(P=(d=(m=f.length)<(o=O.length))?m:o,m=o=0;o<P;o++)if(f[o]!=O[o]){d=f[o]<O[o];break}if(d&&(g=f,f=O,O=g,n.s=-n.s),o=(P=O.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=he-1;P>m;){if(f[--P]<O[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=he}f[P]-=O[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?Ne(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var l,P,g=this;return n=new x(n,o),!g.c||!n.s||n.c&&!n.c[0]?new x(NaN):!n.c||g.c&&!g.c[0]?new x(g):(k==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,k),n=g.minus(l.times(n)),!n.c[0]&&k==1&&(n.s=g.s),n)},r.multipliedBy=r.times=function(n,o){var l,P,g,d,y,m,h,b,f,O,v,A,L,H,W,R=this,C=R.c,Q=(n=new x(n,o)).c;if(!C||!Q||!C[0]||!Q[0])return!R.s||!n.s||C&&!C[0]&&!Q||Q&&!Q[0]&&!C?n.c=n.e=n.s=null:(n.s*=R.s,!C||!Q?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=pe(R.e/N)+pe(n.e/N),n.s*=R.s,h=C.length,O=Q.length,h<O&&(L=C,C=Q,Q=L,g=h,h=O,O=g),g=h+O,L=[];g--;L.push(0));for(H=he,W=we,g=O;--g>=0;){for(l=0,v=Q[g]%W,A=Q[g]/W|0,y=h,d=g+y;d>g;)b=C[--y]%W,f=C[y]/W|0,m=A*b+f*v,b=v*b+m%W*W+L[d]+l,l=(b/H|0)+(m/W|0)+A*f,L[d--]=b%H;L[d]=l}return l?++P:L.splice(0,1),Ne(n,L,P)},r.negated=function(){var n=new x(this);return n.s=-n.s||null,n},r.plus=function(n,o){var l,P=this,g=P.s;if(n=new x(n,o),o=n.s,!g||!o)return new x(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/N,y=n.e/N,m=P.c,h=n.c;if(!d||!y){if(!m||!h)return new x(g/0);if(!m[0]||!h[0])return h[0]?n:new x(m[0]?P:g*0)}if(d=pe(d),y=pe(y),m=m.slice(),g=d-y){for(g>0?(y=d,l=h):(g=-g,l=m),l.reverse();g--;l.push(0));l.reverse()}for(g=m.length,o=h.length,g-o<0&&(l=h,h=m,m=l,o=g),g=0;o;)g=(m[--o]=m[o]+h[o]+g)/he|0,m[o]=he===m[o]?0:m[o]%he;return g&&(m=[g].concat(m),++y),Ne(n,m,y)},r.precision=r.sd=function(n,o){var l,P,g,d=this;if(n!=null&&n!==!!n)return q(n,1,Y),o==null?o=c:q(o,0,8),_(new x(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*N+1,g=l[g]){for(;g%10==0;g/=10,P--);for(g=l[0];g>=10;g/=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,l,P,g,d=this,y=d.c,m=d.s,h=d.e,b=a+4,f=new x("0.5");if(m!==1||!y||!y[0])return new x(!m||m<0&&(!y||y[0])?NaN:y?d:1/0);if(m=Math.sqrt(+X(d)),m==0||m==1/0?(o=ue(y),(o.length+h)%2==0&&(o+="0"),m=Math.sqrt(+o),h=pe((h+1)/2)-(h<0||h%2),m==1/0?o="5e"+h:(o=m.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new x(o)):l=new x(m+""),l.c[0]){for(h=l.e,m=h+b,m<3&&(m=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ue(g.c).slice(0,m)===(o=ue(l.c)).slice(0,m))if(l.e<h&&--m,o=o.slice(m-3,m+1),o=="9999"||!P&&o=="4999"){if(!P&&(_(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,m+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(_(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return _(l,l.e+a+1,c,n)},r.toExponential=function(n,o){return n!=null&&(q(n,0,Y),n++),ee(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(q(n,0,Y),n=n+this.e+1),ee(this,n,o)},r.toFormat=function(n,o,l){var P,g=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=G;else if(typeof l!="object")throw Error(re+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,y=P.split("."),m=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=y[0],O=y[1],v=g.s<0,A=v?f.slice(1):f,L=A.length;if(h&&(d=m,m=h,h=d,L-=d),m>0&&L>0){for(d=L%m||m,f=A.substr(0,d);d<L;d+=m)f+=b+A.substr(d,m);h>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=O?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?O.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):O):f}return(l.prefix||"")+P+(l.suffix||"")},r.toFraction=function(n){var o,l,P,g,d,y,m,h,b,f,O,v,A=this,L=A.c;if(n!=null&&(m=new x(n),!m.isInteger()&&(m.c||m.s!==1)||m.lt(i)))throw Error(re+"Argument "+(m.isInteger()?"out of range: ":"not an integer: ")+X(m));if(!L)return new x(A);for(o=new x(i),b=l=new x(i),P=h=new x(i),v=ue(L),d=o.e=v.length-A.e-1,o.c[0]=Bt[(y=d%N)<0?N+y:y],n=!n||m.comparedTo(o)>0?d>0?o:b:m,y=B,B=1/0,m=new x(v),h.c[0]=0;f=e(m,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=m.minus(f.times(g=o)),m=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,O=e(b,P,d,c).minus(A).abs().comparedTo(e(h,l,d,c).minus(A).abs())<1?[b,P]:[h,l],B=y,O},r.toNumber=function(){return+X(this)},r.toPrecision=function(n,o){return n!=null&&q(n,1,Y),ee(this,n,o,2)},r.toString=function(n){var o,l=this,P=l.s,g=l.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=p||g>=S?tt(ue(l.c),g):xe(ue(l.c),g,"0"):n===10&&K?(l=_(new x(l),a+g+1,c),o=xe(ue(l.c),l.e,"0")):(q(n,2,D.length,"Base"),o=t(xe(ue(l.c),g,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return X(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,u!=null&&x.set(u),x}function pe(u){var e=u|0;return u>0||u===e?e:e-1}function ue(u){for(var e,t,s=1,r=u.length,i=u[0]+"";s<r;){for(e=u[s++]+"",t=N-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,a=u.s,c=e.s,p=u.e,S=e.e;if(!a||!c)return null;if(t=r&&!r[0],s=i&&!i[0],t||s)return t?s?0:-c:a;if(a!=c)return a;if(t=a<0,s=p==S,!r||!i)return s?0:!r^t?1:-1;if(!s)return p>S^t?1:-1;for(c=(p=r.length)<(S=i.length)?p:S,a=0;a<c;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return p==S?0:p>S^t?1:-1}function q(u,e,t,s){if(u<e||u>t||u!==ce(u))throw Error(re+(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 pe(u.e/N)==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 V=Gt();var qt=12;V.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:qt});var E=I(0),oe=I(1),ms=I("Infinity");function $(u,e){let t=new V(e.toString()),s=new V(10).pow(t);return u.times(s)}function I(u){return new V(u.toString())}var ie=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(ie||{}),_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"),me=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",gs=12,hs=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 hr=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 yr=require("@polkadot/api-base/types/submittable");var Sr=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:a,isSufficient:c,existentialDeposit:p}=t,{symbol:S,decimals:w}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:S,decimals:w,icon:S,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:this.parseLocation("parachain",r),existentialDeposit:p.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:c,isSufficient:p,existentialDeposit:S}=t,{symbol:w,decimals:B}=this.getToken(i.toString(),t,s),T=a.toNumber(),k=new Intl.DateTimeFormat("en-GB"),F=[w,"Bond",k.format(T)].join(" ");return{id:e,name:F,symbol:w+"b",decimals:B,icon:w,type:c.toString(),isSufficient:p.toHuman(),existentialDeposit:S.toString()}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:c,assetType:p,isSufficient:S,existentialDeposit:w}=t,T=i.map(G=>G.toString()).map(G=>{let{symbol:D}=this.getToken(G,t,s);return[G,D]}),k=Object.fromEntries(T),F=Object.values(k);return{id:e,name:F.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:F.join("/"),type:p.toString(),isSufficient:S.toHuman(),existentialDeposit:w.toString(),meta:k}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=this.parseLocation("generalIndex",r),c=s?.find(p=>p.id===a?.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:a}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:a.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,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),c=this.getSupportedAssets(t),p=this.normalizeMetadata(c,a);return c.map(([{args:[S]},w])=>{let B=w.unwrap(),T=s.get(S.toString()),{assetType:k}=B;switch(k.toString()){case"Bond":let F=i.get(S.toString());return this.getBond(S.toString(),B,p,F);case"StableSwap":let G=r.get(S.toString());return this.getShares(S.toString(),B,p,G);case"External":return this.getExternal(S.toString(),B,e,T);default:return this.getToken(S.toString(),B,p,T)}}).filter(S=>this.isValidAsset(S))}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:a,reserved:c,frozen:p},S)=>{let w=this.calculateFreeBalance({free:a,feeFrozen:c,frozen:p}),B=r[S][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((a,c)=>{let p=this.calculateFreeBalance(a),S=r[c][1];s(S,p)})})}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,a=new V(t),c=new V(s||i),p=new V(r||0),S=c.gt(p)?c:p;return a.minus(S)}};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(a=>a.id==s);i>=0&&t(e,s)&&(e.tokens[i].balance=r.toString())}}};var it=class extends be{MAX_FINAL_WEIGHT=$(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,a])=>this.isActivePool(a.unwrap(),s)).map(async([{args:[i]},a])=>{let c=a.unwrap(),p=i.toString(),S=await this.getPoolDelta(p,c,s.toString());return this.poolsData.set(i.toString(),c),{address:p,type:"Lbp",fee:c.fee.toJSON(),...S,...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 a=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(c=>c.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:a,initialWeight:c,finalWeight:p,repayTarget:S,feeCollector:w}=t,B=me.calculateLinearWeights(r.toString(),i.toString(),c.toString(),p.toString(),s),[T,k]=a,F=T.toString(),G=I(B),D=k.toString(),K=this.MAX_FINAL_WEIGHT.minus(I(G)),[x,ee,ae]=await Promise.all([this.isRepayFeeApplied(F,S.toString(),w.toString()),this.getBalance(e,F),this.getBalance(e,D)]);return{repayFeeApply:x,tokens:[{id:F,weight:G,balance:ee.toString()},{id:D,weight:K,balance:ae.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 ge(u){return u[0]/u[1]*100}function ne(u){return u[0]/u[1]}function de(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)]),a=s.map(async([{args:[p]},S])=>{let{hubReserve:w,shares:B,tradable:T}=S.unwrap(),k=await this.getBalance(t,p.toString());return{id:p.toString(),hubReserves:I(w.toString()),shares:I(B.toString()),tradeable:T.bits.toNumber(),balance:k.toString()}}),c=await Promise.all(a);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,a=r.minFee.toNumber()+i.minFee.toNumber(),c=r.maxFee.toNumber()+i.maxFee.toNumber();if(s.isSome){let{assetFee:p,protocolFee:S}=s.unwrap();return{assetFee:de(p.toNumber()),protocolFee:de(S.toNumber()),min:de(a),max:de(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:de(a),max:de(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 a=e.tokens[i];if(r.isNone)return a;let c=r.unwrap();return this.updateTokenState(a,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 de(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return de(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(),[a,c]=r.unwrap(),[p,S]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:p.toString()},{id:c.toString(),balance:S.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 J=require("@galacticcouncil/math-stableswap"),se=class{static getPoolAddress(e){return(0,J.pool_account_name)(e)}static calculateAmplification(e,t,s,r,i){return(0,J.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return(0,J.calculate_in_given_out)(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return(0,J.calculate_add_one_asset)(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return(0,J.calculate_shares_for_amount)(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return(0,J.calculate_out_given_in)(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return(0,J.calculate_liquidity_out_one_asset)(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return(0,J.calculate_shares)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,J.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]},a])=>{let c=a.unwrap(),p=i.toString(),S=this.getPoolAddress(p),[w,B]=await Promise.all([this.getPoolDelta(p,c,s.toString()),this.getPoolTokens(S,p,c)]);return this.stablePools.set(S,c),{address:S,id:p,type:"Stableswap",fee:de(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:a,finalBlock:c}=t,p=se.calculateAmplification(r.toString(),i.toString(),a.toString(),c.toString(),s),S=await this.api.query.tokens.totalIssuance(e);return{amplification:p,totalIssuance:S.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async p=>{let[S,w]=await Promise.all([this.api.query.stableswap.assetTradability(t,p.toString()),this.getBalance(e,p.toString())]);return{id:p.toString(),tradeable:S.bits.toNumber(),balance:w.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:p}=c.unwrap(),S=await this.getBalance($e,t);a.push({id:t,tradeable:p.bits.toNumber(),balance:S.toString()})}return a}getPoolAddress(e){let t=Number(e),s=se.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)}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||this.syncRegistry(),e.length==0){let a=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(c=>c.isSupported()).map(c=>c.getPools()))).flat();return this.withMetadata(a)}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 a=t.get(i.id);return{...i,...a}});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 a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):a=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),ut(i));let c=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):a=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),ut(i));let c=()=>a;return{hex:a.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({}),gt="function",Kt="string",Ge=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===gt)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===gt)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!==gt&&u.length!==void 0&&typeof e!==gt&&e.length!==void 0?ys(u,e):u instanceof Set&&e instanceof Set?Ss(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)},ys=(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()),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 ht=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(ht,s);if(ft(r)){r=es(r.deref()),r!==ht&&(yield r);return}r!==ht&&(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,a=0;for(;s-- >0&&a===0;)a=t(r.value,i.value),r=r.next,i=i.next;return a}}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 ye=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 ye(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 ye}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 ye,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=a=>({first(){return a.value},next(){return a!==r&&a.next?i(a.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 ye,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.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,a=0;for(let p=0;p<t&&(a++,i=i.next,!!i);p++);let c=t;for(;a>0||c>0&&i;){let p;a===0?(p=i,i=i.next,c--):!i||c===0||e(s.value,i.value)<=0?(p=s,s=s.next,a--):(p=i,i=i.next,c--),this._tail?this._tail.next=p:this._head=p,p.prev=this._tail,this._tail=p}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 ye;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 a of s)this.insertBefore(r,a);else for(let a of s)this.push(a);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 ye,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 Be=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Be(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,a,c){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=c}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(p=>[p.id,p])),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 a=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,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 a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let c=this.calculateTradeFee(t,s),p=ge(this.repayFeeApply?s.repayFee:s.exchangeFee),S=t.plus(c),w=this.calculateInGivenOut(e,S),B=e.balanceIn.div(this.maxInRatio);return w.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:w,calculatedIn:w,amountOut:t,feePct:p,errors:i}}else{let c=this.calculateInGivenOut(e,t),p=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(p)&&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 a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let c=this.calculateOutGivenIn(e,t),p=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(p)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),p=this.calculateTradeFee(c,s),S=ge(this.repayFeeApply?s.repayFee:s.exchangeFee),w=c.minus(p),B=e.balanceOut.div(this.maxOutRatio);return w.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:w,feePct:S,errors:i}}}calculateInGivenOut(e,t){let s=me.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=me.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=me.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),$(oe,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=me.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),$(oe,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=me.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(s)}};var M=require("@galacticcouncil/math-omnipool");var z=class{static calculateSpotPrice(e,t,s,r){return(0,M.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,M.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,a,c,p,S){return(0,M.calculate_in_given_out)(e,t,s,r,i,a,c,p,S)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,M.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,a,c,p,S){return(0,M.calculate_out_given_in)(e,t,s,r,i,a,c,p,S)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,M.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,M.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,M.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,a,c,p){return(0,M.calculate_liquidity_out)(e,t,s,r,i,a,c,p)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,c,p){return(0,M.calculate_liquidity_lrna_out)(e,t,s,r,i,a,c,p)}static calculateCapDifference(e,t,s,r){let i=V(t),a=V(e),c=V(r),S=V(s).shiftedBy(-18);if(i.div(c).lt(S)){let B=S.times(c).minus(i).times(a),T=i.times(V(1).minus(S));return B.div(T).toFixed(0)}else return"0"}static verifyAssetCap(e,t,s,r){return(0,M.verify_asset_cap)(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return(0,M.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,M.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,M.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,M.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,M.is_remove_liquidity_allowed)(e)}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(p=>[p.id,p])),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 a=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:a,balanceOut:c,tradeableIn:r.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),c=r===E?E:a.div(r).multipliedBy(100).decimalPlaces(2),p=[],S=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!S||!w)&&p.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&p.push("MaxOutRatioExceeded");let T=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(T)&&p.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:c.toNumber(),errors:p}}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),p=[],S=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!S||!w)&&p.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&p.push("MaxInRatioExceeded");let T=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(T)&&p.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:c.toNumber(),errors:p}}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?ne(s.assetFee).toString():E.toString(),s?ne(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?ne(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?ne(s.assetFee).toString():E.toString(),s?ne(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?ne(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 Ie=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Ie(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,i,a,c,p,S){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=a,this.id=c,this.fee=p,this.totalIssuance=S}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(p=>[p.id,p])),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 a=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,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),a=ge(s.fee),c=[],p=z.isSellAllowed(e.tradeableIn),S=z.isBuyAllowed(e.tradeableOut);return(!p||!S)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=ge(s.fee),c=[],p=z.isSellAllowed(e.tradeableIn),S=z.isBuyAllowed(e.tradeableOut);return(!p||!S)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,s){let r=se.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ne(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateAddOneAsset(e,t,s){let r=se.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?ne(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateSharesForAmount(e,t,s){let r=se.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?ne(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=$(oe,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=se.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ne(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateWithdrawOneAsset(e,t,s){let r=se.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?ne(s.fee).toString():E.toString()),i=I(r);return i.isNegative()?E:i}calculateShares(e,t,s){let r=se.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?ne(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=$(oe,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=se.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"),Se=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(p=>[p.id,p])),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 a=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=ge(s.exchangeFee),c=r.plus(i),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let S=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(S)&&p.push("MaxOutRatioExceeded");let w=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(w)&&p.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:r,amountOut:t,feePct:a,errors:p}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=ge(s.exchangeFee),c=r.minus(i),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let S=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(S)&&p.push("MaxInRatioExceeded");let w=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(w)&&p.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:a,errors:p}}calculateInGivenOut(e,t){let s=Se.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=Se.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=Se.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),$(oe,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=Se.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),$(oe,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=Se.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 ve.fromPool(e);case"Lbp":return Be.fromPool(e);case"Stableswap":return Ie.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),a=this.getPaths(e,null,r,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(a)],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 a=t.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.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 oe.minus(e.div(u)).multipliedBy(100).decimalPlaces(2)}function Dt(u,e){return e.div(u).minus(oe).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,a=r[r.length-1].amountOut;return i.isGreaterThan(a)?-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,a)=>i+a),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[s,r]}}getPoolFeeRange(e){let t=e.min?ge(e.min):void 0,s=e.max?ge(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new De(e,t);let p;if(r)p=await this.toSellSwaps(s,r,a);else{let _=c.map(async n=>await this.toSellSwaps(s,n,a)),X=await Promise.all(_);p=this.findBestSellRoute(X)}let S=p[0],w=p[p.length-1],B=this.isDirectTrade(p),T=p.map(_=>_.spotPrice.shiftedBy(-1*_.assetOutDecimals)).reduce((_,X)=>_.multipliedBy(X)),k=$(T,w.assetOutDecimals),F=B?w.calculatedOut:this.calculateDelta0Y(S.amountIn,p,a),G=w.amountOut,D=B?w.tradeFeePct:Mt(F,G).toNumber(),K=F.minus(G),x=this.getRouteFeeRange(p),ee=S.amountIn.shiftedBy(-1*S.assetInDecimals).multipliedBy(k),ae=ze(F,ee),Ne=_=>this.poolService.buildSellTx(e,t,S.amountIn,_,p.map(X=>X));return{type:"Sell",amountIn:S.amountIn,amountOut:w.amountOut,spotPrice:k,tradeFee:K,tradeFeePct:D,tradeFeeRange:x,priceImpactPct:ae.toNumber(),swaps:p,toTx:Ne,toHuman(){return{type:"Sell",amountIn:j(S.amountIn,S.assetInDecimals),amountOut:j(w.amountOut,w.assetOutDecimals),spotPrice:j(k,w.assetOutDecimals),tradeFee:j(K,w.assetOutDecimals),tradeFeePct:D,tradeFeeRange:x,priceImpactPct:ae.toNumber(),swaps:p.map(_=>_.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let p=c.parsePair(a.assetIn,a.assetOut),S;i>0?S=r[i-1]:S=e;let w=c.calculateOutGivenIn(p,S);r.push(w)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let p=c.parsePair(a.assetIn,a.assetOut),S;i>0?S=r[i-1].amountOut:S=$(I(e),p.decimalsIn).decimalPlaces(0,1);let w=await this.poolService.getPoolFees(p.assetOut,c),{amountOut:B,calculatedOut:T,feePct:k,errors:F}=c.validateAndSell(p,S,w),G=this.getPoolFeeRange(w),D=c.spotPriceOutGivenIn(p),K=S.shiftedBy(-1*p.decimalsIn).multipliedBy(D),x=ze(T,K);r.push({...a,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountIn:S,calculatedOut:T,amountOut:B,spotPrice:D,tradeFeePct:k,tradeFeeRange:G,priceImpactPct:x.toNumber(),errors:F,toHuman(){return{...a,amountIn:j(S,p.decimalsIn),calculatedOut:j(T,p.decimalsOut),amountOut:j(B,p.decimalsOut),spotPrice:j(D,p.decimalsOut),tradeFeePct:k,tradeFeeRange:G,priceImpactPct:x.toNumber(),errors:F}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(x=>x.tokens.find(ee=>ee.id===e)).filter(x=>!!x).sort((x,ee)=>Number(ee.balance)-Number(x.balance)),{balance:c,decimals:p}=a[0],w=I(c).shiftedBy(-1*p).div(100).multipliedBy(.1),B=i.map(async x=>await this.toSellSwaps(w,x,r)),T=await Promise.all(B),k=this.findBestSellRoute(T),F=await this.toSellSwaps("1",k,r),G=F.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,ee)=>x.multipliedBy(ee)),D=F[F.length-1].assetOutDecimals;return{amount:$(G,D),decimals:D}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,a=r[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new De(e,t);let p;if(r)p=await this.toBuySwaps(s,r,a);else{let _=c.map(async n=>await this.toBuySwaps(s,n,a)),X=await Promise.all(_);p=this.findBestBuyRoute(X)}let S=p[p.length-1],w=p[0],B=this.isDirectTrade(p),T=p.map(_=>_.spotPrice.shiftedBy(-1*_.assetInDecimals)).reduce((_,X)=>_.multipliedBy(X)),k=$(T,w.assetInDecimals),F=B?w.calculatedIn:this.calculateDelta0X(S.amountOut,p,a),G=w.amountIn,D=B?w.tradeFeePct:Dt(F,G).toNumber(),K=G.minus(F),x=this.getRouteFeeRange(p),ee=S.amountOut.shiftedBy(-1*S.assetOutDecimals).multipliedBy(k),ae;F.isZero()?ae=-100:ae=ze(ee,F).toNumber();let Ne=_=>this.poolService.buildBuyTx(e,t,S.amountOut,_,p.map(X=>X));return{type:"Buy",amountOut:S.amountOut,amountIn:w.amountIn,spotPrice:k,tradeFee:K,tradeFeePct:D,tradeFeeRange:x,priceImpactPct:ae,swaps:p,toTx:Ne,toHuman(){return{type:"Buy",amountOut:j(S.amountOut,S.assetOutDecimals),amountIn:j(w.amountIn,w.assetInDecimals),spotPrice:j(k,w.assetInDecimals),tradeFee:j(K,w.assetInDecimals),tradeFeePct:D,tradeFeeRange:x,priceImpactPct:ae,swaps:p.map(_=>_.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let p=c.parsePair(a.assetIn,a.assetOut),S;i==t.length-1?S=e:S=r[0];let w=c.calculateInGivenOut(p,S);r.unshift(w)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let p=c.parsePair(a.assetIn,a.assetOut),S;i==t.length-1?S=$(I(e),p.decimalsOut).decimalPlaces(0,1):S=r[0].amountIn;let w=await this.poolService.getPoolFees(p.assetOut,c),{amountIn:B,calculatedIn:T,feePct:k,errors:F}=c.validateAndBuy(p,S,w),G=this.getPoolFeeRange(w),D=c.spotPriceInGivenOut(p),K=S.shiftedBy(-1*p.decimalsOut).multipliedBy(D),x;T.isZero()?x=-100:x=ze(K,T).toNumber(),r.unshift({...a,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountOut:S,calculatedIn:T,amountIn:B,spotPrice:D,tradeFeePct:k,tradeFeeRange:G,priceImpactPct:x,errors:F,toHuman(){return{...a,amountOut:j(S,p.decimalsOut),calculatedIn:j(T,p.decimalsIn),amountIn:j(B,p.decimalsIn),spotPrice:j(D,p.decimalsIn),tradeFeePct:k,tradeFeeRange:G,priceImpactPct:x,errors:F}}})}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});
|
|
1
|
+
"use strict";var wt=Object.defineProperty;var ar=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var ur=Object.prototype.hasOwnProperty;var cr=(m,e)=>{for(var t in e)wt(m,t,{get:e[t],enumerable:!0})},mr=(m,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lr(e))!ur.call(m,s)&&s!==t&&wt(m,s,{get:()=>e[s],enumerable:!(r=ar(e,s))||r.enumerable});return m};var pr=m=>mr(wt({},"__esModule",{value:!0}),m);var Ar={};cr(Ar,{AssetClient:()=>Le,AssetNotFound:()=>_t,BASILISK_PARACHAIN_ID:()=>br,BalanceClient:()=>Me,BigNumber:()=>q,CachingPoolService:()=>bt,DECIMAL_PLACES:()=>zt,DENOMINATOR:()=>st,FarmClient:()=>it,HYDRADX_OMNIPOOL_ADDRESS:()=>$e,HYDRADX_PARACHAIN_ID:()=>Pr,HYDRADX_SS58_PREFIX:()=>ke,INFINITY:()=>dr,LbpMath:()=>pe,LbpPool:()=>Ie,ONE:()=>ae,OmniMath:()=>X,OmniPool:()=>Ae,PoolConfigNotFound:()=>Tt,PoolError:()=>Re,PoolFactory:()=>Ue,PoolNotFound:()=>je,PoolService:()=>Ce,PoolType:()=>ie,ProviderConfigNotFound:()=>kt,RUNTIME_DECIMALS:()=>Ee,RouteNotFound:()=>De,Router:()=>_e,SYSTEM_ASSET_DECIMALS:()=>fr,SYSTEM_ASSET_ID:()=>Oe,StableMath:()=>re,StableSwap:()=>Ne,StorageConfigNotFound:()=>Rt,SubscriptionNotSupported:()=>Et,TRADEABLE_DEFAULT:()=>rt,TradeRouter:()=>Ke,TradeType:()=>It,XykMath:()=>Se,XykPool:()=>Fe,ZERO:()=>_,bnum:()=>I,buildRoute:()=>ct,calculateBuyFee:()=>qt,calculateDiffToAvg:()=>Ir,calculateDiffToRef:()=>ze,calculateSellFee:()=>Gt,findNestedKey:()=>At,findNestedObj:()=>yr,scale:()=>Z});module.exports=pr(Ar);var Ve=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 gr=5,Ye=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new Ve,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>gr)return s;let u=c[c.length-1];(r===null||u[0]===r)&&s.push(c),e.get(u[0])?.forEach(O=>{if(this.isNotVisited(O,c)){let B=[...c];B.push(O),i.enqueue(B)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,a]of t){let c=parseInt(i),u=parseInt(a);r.get(c)?.push([u,s])}return r}};function xt(m){let e={};for(let t of m){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let a=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(a)}}}return e}var We=class{getProposals(e,t,r){let s=xt(r),i=Object.keys(s),a=i.map(O=>s[O]).flat(),c=new Ye,u=c.buildAndPopulateGraph(i,a),y=c.findPaths(u,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let a=r[i],c=r[i+1];if(c==null)break;s.push(this.toEdge(a,c))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var hr=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ot=Math.ceil,ce=Math.floor,se="[BigNumber Error] ",Ht=se+"Number primitive has more than 15 significant digits: ",he=1e14,N=14,Bt=9007199254740991,vt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Be=1e7,J=1e9;function Ut(m){var e,t,r,s=w.prototype={constructor:w,toString:null,valueOf:null},i=new w(1),a=20,c=4,u=-7,y=21,O=-1e7,B=1e7,F=!1,R=1,T=0,C={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},L="0123456789abcdefghijklmnopqrstuvwxyz",W=!0;function w(n,o){var l,P,g,d,S,p,h,b,f=this;if(!(f instanceof w))return new w(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<O?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(!hr.test(b=String(n)))return r(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(H(o,2,L.length,"Base"),o==10&&W)return f=new w(n),E(f,a+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return r(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,w.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Ht+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=L.slice(0,o),d=S=0,h=b.length;S<h;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return r(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(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&w.DEBUG&&h>15&&(n>Bt||n!==ce(n)))throw Error(Ht+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<O)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%N,d<0&&(S+=N),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=N;S<h;)f.c.push(+b.slice(S,S+=N));S=N-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}w.clone=Ut,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],H(l,0,J,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],H(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(H(l[0],-J,0,o),H(l[1],0,J,o),u=l[0],y=l[1]):(H(l,-J,J,o),u=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)H(l[0],-J,-1,o),H(l[1],1,J,o),O=l[0],B=l[1];else if(H(l,-J,J,o),l)O=-(B=l<0?-l:l);else throw Error(se+o+" cannot be zero: "+l);if(n.hasOwnProperty(o="CRYPTO"))if(l=n[o],l===!!l)if(l)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))F=l;else throw F=!l,Error(se+"crypto unavailable");else F=l;else throw Error(se+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],H(l,0,9,o),R=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],H(l,0,J,o),T=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")C=l;else throw Error(se+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))W=l.slice(0,10)=="0123456789",L=l;else throw Error(se+o+" invalid: "+l)}else throw Error(se+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[u,y],RANGE:[O,B],CRYPTO:F,MODULO_MODE:R,POW_PRECISION:T,FORMAT:C,ALPHABET:L}},w.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!w.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-J&&g<=J&&g===ce(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%N,o<1&&(o+=N),String(P[0]).length==o){for(o=0;o<P.length;o++)if(l=P[o],l<0||l>=he||l!==ce(l))break e;if(l!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(se+"Invalid BigNumber: "+n)},w.maximum=w.max=function(){return oe(arguments,-1)},w.minimum=w.min=function(){return oe(arguments,1)},w.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ce(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,S,p,h=0,b=[],f=new w(i);if(l==null?l=a:H(l,0,J),S=Ot(l/N),F)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));h<S;)p=P[h]*131072+(P[h+1]>>>11),p>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(p%1e14),h+=2);h=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);h<S;)p=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],p>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(p%1e14),h+=7);h=S/7}else throw F=!1,Error(se+"crypto unavailable");if(!F)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],l%=N,S&&l&&(p=vt[N-l],b[h]=ce(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=N);for(h=1,p=b[0];p>=10;p/=10,h++);h<N&&(d-=N-h)}return f.e=d,f.c=b,f}}(),w.sum=function(){for(var n=1,o=arguments,l=new w(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var S,p=[0],h,b=0,f=l.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(l.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(l,P,g,d,S){var p,h,b,f,x,v,A,M,U=l.indexOf("."),j=a,k=c;for(U>=0&&(f=T,T=0,l=l.replace(".",""),M=new w(P),v=M.pow(l.length-U),T=f,M.c=o(xe(ue(v.c),v.e,"0"),10,g,n),M.e=M.c.length),A=o(l,P,g,S?(p=L,n):(p=n,L)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(U<0?--b:(v.c=A,v.e=b,v.s=d,v=e(v,M,j,k,g),A=v.c,x=v.r,b=v.e),h=b+j+1,U=A[h],f=g/2,x=x||h<0||A[h+1]!=null,x=k<4?(U!=null||x)&&(k==0||k==(v.s<0?3:2)):U>f||U==f&&(k==4||x||k==6&&A[h-1]&1||k==(v.s<0?8:7)),h<1||!A[0])l=x?xe(p.charAt(1),-j,p.charAt(0)):p.charAt(0);else{if(A.length=h,x)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(U=0,l="";U<=f;l+=p.charAt(A[U++]));l=xe(l,b,p.charAt(0))}return l}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,x=P.length,v=g%Be,A=g/Be|0;for(P=P.slice();x--;)h=P[x]%Be,b=P[x]/Be|0,S=A*h+b*v,p=v*h+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,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function l(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,x,v,A,M,U,j,k,G,ee,Qe,yt,St,fe,Xe,le=P.s==g.s?1:-1,te=P.c,z=g.c;if(!te||!te[0]||!z||!z[0])return new w(!P.s||!g.s||(te?z&&te[0]==z[0]:!z)?NaN:te&&te[0]==0||!z?le*0:le/0);for(U=new w(le),j=U.c=[],b=P.e-g.e,le=d+b+1,p||(p=he,b=me(P.e/N)-me(g.e/N),le=le/N|0),f=0;z[f]==(te[f]||0);f++);if(z[f]>(te[f]||0)&&b--,le<0)j.push(1),x=!0;else{for(yt=te.length,fe=z.length,f=0,le+=2,v=ce(p/(z[0]+1)),v>1&&(z=n(z,v,p),te=n(te,v,p),fe=z.length,yt=te.length),Qe=fe,k=te.slice(0,fe),G=k.length;G<fe;k[G++]=0);Xe=z.slice(),Xe=[0].concat(Xe),St=z[0],z[1]>=p/2&&St++;do{if(v=0,h=o(z,k,fe,G),h<0){if(ee=k[0],fe!=G&&(ee=ee*p+(k[1]||0)),v=ce(ee/St),v>1)for(v>=p&&(v=p-1),A=n(z,v,p),M=A.length,G=k.length;o(A,k,M,G)==1;)v--,l(A,fe<M?Xe:z,M,p),M=A.length,h=1;else v==0&&(h=v=1),A=z.slice(),M=A.length;if(M<G&&(A=[0].concat(A)),l(k,A,G,p),G=k.length,h==-1)for(;o(z,k,fe,G)<1;)v++,l(k,fe<G?Xe:z,G,p),G=k.length}else h===0&&(v++,k=[0]);j[f++]=v,k[0]?k[G++]=te[Qe]||0:(k=[te[Qe]],G=1)}while((Qe++<yt||k[0]!=null)&&le--);x=k[0]!=null,j[0]||j.splice(0,1)}if(p==he){for(f=1,le=j[0];le>=10;le/=10,f++);E(U,d+(U.e=f+b*N-1)+1,S,x)}else U.e=b,U.r=+x;return U}}();function Q(n,o,l,P){var g,d,S,p,h;if(l==null?l=c:H(l,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ue(n.c),h=P==1||P==2&&(S<=u||S>=y)?tt(h,S):xe(h,S,"0");else if(n=E(new w(n),o,l),d=n.e,h=ue(n.c),p=h.length,P==1||P==2&&(o<=d||d<=u)){for(;p<o;h+="0",p++);h=tt(h,d)}else if(o-=S,h=xe(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function oe(n,o){for(var l,P,g=1,d=new w(n[0]);g<n.length;g++)P=new w(n[g]),(!P.s||(l=Te(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function we(n,o,l){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(l=P+l*N-1)>B?n.c=n.e=null:l<O?n.c=[n.e=0]:(n.e=l,n.c=o),n}r=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,h){var b,f=p?S:S.replace(g,"");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,!h||h==b?v:x}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new w(f,b);if(w.DEBUG)throw Error(se+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function E(n,o,l,P){var g,d,S,p,h,b,f,x=n.c,v=vt;if(x){e:{for(g=1,p=x[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=N,S=o,h=x[b=0],f=ce(h/v[g-S-1]%10);else if(b=Ot((d+1)/N),b>=x.length)if(P){for(;x.length<=b;x.push(0));h=f=0,g=1,d%=N,S=d-N+1}else break e;else{for(h=p=x[b],g=1;p>=10;p/=10,g++);d%=N,S=d-N+g,f=S<0?0:ce(h/v[g-S-1]%10)}if(P=P||o<0||x[b+1]!=null||(S<0?h:h%v[g-S-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?S>0?h/v[g-S]:0:x[b-1])%10&1||l==(n.s<0?8:7)),o<1||!x[0])return x.length=0,P?(o-=n.e+1,x[0]=v[(N-o%N)%N],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[N-d],x[b]=S>0?ce(h/v[g-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<O&&(n.c=[n.e=0])}return n}function Y(n){var o,l=n.e;return l===null?n.toString():(o=ue(n.c),o=l<=u||l>=y?tt(o,l):xe(o,l,"0"),n.s<0?"-"+o:o)}return s.absoluteValue=s.abs=function(){var n=new w(this);return n.s<0&&(n.s=1),n},s.comparedTo=function(n,o){return Te(this,new w(n,o))},s.decimalPlaces=s.dp=function(n,o){var l,P,g,d=this;if(n!=null)return H(n,0,J),o==null?o=c:H(o,0,8),E(new w(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-me(this.e/N))*N,g=l[g])for(;g%10==0;g/=10,P--);return P<0&&(P=0),P},s.dividedBy=s.div=function(n,o){return e(this,new w(n,o),a,c)},s.dividedToIntegerBy=s.idiv=function(n,o){return e(this,new w(n,o),0,1)},s.exponentiatedBy=s.pow=function(n,o){var l,P,g,d,S,p,h,b,f,x=this;if(n=new w(n),n.c&&!n.isInteger())throw Error(se+"Exponent not an integer: "+Y(n));if(o!=null&&(o=new w(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 w(Math.pow(+Y(x),p?n.s*(2-et(n)):+Y(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new w(NaN);P=!h&&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 w(h?1/d:d);T&&(d=Ot(T/N+2))}for(p?(l=new w(.5),h&&(n.s=1),b=et(n)):(g=Math.abs(+Y(n)),b=g%2),f=new w(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(g){if(g=ce(g/2),g===0)break;b=g%2}else if(n=n.times(l),E(n,n.e+1,1),n.e>14)b=et(n);else{if(g=+Y(n),g===0)break;b=g%2}x=x.times(x),d?x.c&&x.c.length>d&&(x.c.length=d):P&&(x=x.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?E(f,T,c,S):f)},s.integerValue=function(n){var o=new w(this);return n==null?n=c:H(n,0,8),E(o,o.e+1,n)},s.isEqualTo=s.eq=function(n,o){return Te(this,new w(n,o))===0},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(n,o){return Te(this,new w(n,o))>0},s.isGreaterThanOrEqualTo=s.gte=function(n,o){return(o=Te(this,new w(n,o)))===1||o===0},s.isInteger=function(){return!!this.c&&me(this.e/N)>this.c.length-2},s.isLessThan=s.lt=function(n,o){return Te(this,new w(n,o))<0},s.isLessThanOrEqualTo=s.lte=function(n,o){return(o=Te(this,new w(n,o)))===-1||o===0},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&this.c[0]==0},s.minus=function(n,o){var l,P,g,d,S=this,p=S.s;if(n=new w(n,o),o=n.s,!p||!o)return new w(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/N,b=n.e/N,f=S.c,x=n.c;if(!h||!b){if(!f||!x)return f?(n.s=-o,n):new w(x?S:NaN);if(!f[0]||!x[0])return x[0]?(n.s=-o,n):new w(f[0]?S:c==3?-0:0)}if(h=me(h),b=me(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=x),g.reverse(),o=p;o--;g.push(0));g.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&&(g=f,f=x,x=g,n.s=-n.s),o=(P=x.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=he-1;P>p;){if(f[--P]<x[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=he}f[P]-=x[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?we(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},s.modulo=s.mod=function(n,o){var l,P,g=this;return n=new w(n,o),!g.c||!n.s||n.c&&!n.c[0]?new w(NaN):!n.c||g.c&&!g.c[0]?new w(g):(R==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,R),n=g.minus(l.times(n)),!n.c[0]&&R==1&&(n.s=g.s),n)},s.multipliedBy=s.times=function(n,o){var l,P,g,d,S,p,h,b,f,x,v,A,M,U,j,k=this,G=k.c,ee=(n=new w(n,o)).c;if(!G||!ee||!G[0]||!ee[0])return!k.s||!n.s||G&&!G[0]&&!ee||ee&&!ee[0]&&!G?n.c=n.e=n.s=null:(n.s*=k.s,!G||!ee?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=me(k.e/N)+me(n.e/N),n.s*=k.s,h=G.length,x=ee.length,h<x&&(M=G,G=ee,ee=M,g=h,h=x,x=g),g=h+x,M=[];g--;M.push(0));for(U=he,j=Be,g=x;--g>=0;){for(l=0,v=ee[g]%j,A=ee[g]/j|0,S=h,d=g+S;d>g;)b=G[--S]%j,f=G[S]/j|0,p=A*b+f*v,b=v*b+p%j*j+M[d]+l,l=(b/U|0)+(p/j|0)+A*f,M[d--]=b%U;M[d]=l}return l?++P:M.splice(0,1),we(n,M,P)},s.negated=function(){var n=new w(this);return n.s=-n.s||null,n},s.plus=function(n,o){var l,P=this,g=P.s;if(n=new w(n,o),o=n.s,!g||!o)return new w(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/N,S=n.e/N,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new w(g/0);if(!p[0]||!h[0])return h[0]?n:new w(p[0]?P:g*0)}if(d=me(d),S=me(S),p=p.slice(),g=d-S){for(g>0?(S=d,l=h):(g=-g,l=p),l.reverse();g--;l.push(0));l.reverse()}for(g=p.length,o=h.length,g-o<0&&(l=h,h=p,p=l,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/he|0,p[o]=he===p[o]?0:p[o]%he;return g&&(p=[g].concat(p),++S),we(n,p,S)},s.precision=s.sd=function(n,o){var l,P,g,d=this;if(n!=null&&n!==!!n)return H(n,1,J),o==null?o=c:H(o,0,8),E(new w(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*N+1,g=l[g]){for(;g%10==0;g/=10,P--);for(g=l[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},s.shiftedBy=function(n){return H(n,-Bt,Bt),this.times("1e"+n)},s.squareRoot=s.sqrt=function(){var n,o,l,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new w("0.5");if(p!==1||!S||!S[0])return new w(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+Y(d)),p==0||p==1/0?(o=ue(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=me((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new w(o)):l=new w(p+""),l.c[0]){for(h=l.e,p=h+b,p<3&&(p=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ue(g.c).slice(0,p)===(o=ue(l.c)).slice(0,p))if(l.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(E(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(E(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return E(l,l.e+a+1,c,n)},s.toExponential=function(n,o){return n!=null&&(H(n,0,J),n++),Q(this,n,o,1)},s.toFixed=function(n,o){return n!=null&&(H(n,0,J),n=n+this.e+1),Q(this,n,o)},s.toFormat=function(n,o,l){var P,g=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=C;else if(typeof l!="object")throw Error(se+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],x=S[1],v=g.s<0,A=v?f.slice(1):f,M=A.length;if(h&&(d=p,p=h,h=d,M-=d),p>0&&M>0){for(d=M%p||p,f=A.substr(0,d);d<M;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=x?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?x.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):x):f}return(l.prefix||"")+P+(l.suffix||"")},s.toFraction=function(n){var o,l,P,g,d,S,p,h,b,f,x,v,A=this,M=A.c;if(n!=null&&(p=new w(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(se+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+Y(p));if(!M)return new w(A);for(o=new w(i),b=l=new w(i),P=h=new w(i),v=ue(M),d=o.e=v.length-A.e-1,o.c[0]=vt[(S=d%N)<0?N+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new w(v),h.c[0]=0;f=e(p,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,x=e(b,P,d,c).minus(A).abs().comparedTo(e(h,l,d,c).minus(A).abs())<1?[b,P]:[h,l],B=S,x},s.toNumber=function(){return+Y(this)},s.toPrecision=function(n,o){return n!=null&&H(n,1,J),Q(this,n,o,2)},s.toString=function(n){var o,l=this,P=l.s,g=l.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=u||g>=y?tt(ue(l.c),g):xe(ue(l.c),g,"0"):n===10&&W?(l=E(new w(l),a+g+1,c),o=xe(ue(l.c),l.e,"0")):(H(n,2,L.length,"Base"),o=t(xe(ue(l.c),g,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},s.valueOf=s.toJSON=function(){return Y(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,m!=null&&w.set(m),w}function me(m){var e=m|0;return m>0||m===e?e:e-1}function ue(m){for(var e,t,r=1,s=m.length,i=m[0]+"";r<s;){for(e=m[r++]+"",t=N-e.length;t--;e="0"+e);i+=e}for(s=i.length;i.charCodeAt(--s)===48;);return i.slice(0,s+1||1)}function Te(m,e){var t,r,s=m.c,i=e.c,a=m.s,c=e.s,u=m.e,y=e.e;if(!a||!c)return null;if(t=s&&!s[0],r=i&&!i[0],t||r)return t?r?0:-c:a;if(a!=c)return a;if(t=a<0,r=u==y,!s||!i)return r?0:!s^t?1:-1;if(!r)return u>y^t?1:-1;for(c=(u=s.length)<(y=i.length)?u:y,a=0;a<c;a++)if(s[a]!=i[a])return s[a]>i[a]^t?1:-1;return u==y?0:u>y^t?1:-1}function H(m,e,t,r){if(m<e||m>t||m!==ce(m))throw Error(se+(r||"Argument")+(typeof m=="number"?m<e||m>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(m))}function et(m){var e=m.c.length-1;return me(m.e/N)==e&&m.c[e]%2!=0}function tt(m,e){return(m.length>1?m.charAt(0)+"."+m.slice(1):m)+(e<0?"e":"e+")+e}function xe(m,e,t){var r,s;if(e<0){for(s=t+".";++e;s+=t);m=s+m}else if(r=m.length,++e>r){for(s=t,e-=r;--e;s+=t);m+=s}else e<r&&(m=m.slice(0,e)+"."+m.slice(e));return m}var q=Ut();var zt=12;q.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:zt});var _=I(0),ae=I(1),dr=I("Infinity");function Z(m,e){let t=new q(e.toString()),r=new q(10).pow(t);return m.times(r)}function I(m){return new q(m.toString())}var ie=(s=>(s.XYK="Xyk",s.LBP="Lbp",s.Stable="Stableswap",s.Omni="Omnipool",s))(ie||{}),Re=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(Re||{}),It=(t=>(t.Buy="Buy",t.Sell="Sell",t))(It||{});var Pe=require("@galacticcouncil/math-lbp"),pe=class{static getSpotPrice(e,t,r,s,i){return(0,Pe.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,Pe.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,Pe.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,Pe.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,Pe.calculate_pool_trade_fee)(e,t,r)}};var Xt=require("@polkadot/util-crypto"),Yt=require("@polkadot/util"),Ee=18,rt=15,Oe="0",fr=12,Pr=2034,ke=63,br=2090,st=1e3,$e=(0,Xt.encodeAddress)((0,Yt.stringToU8a)("modlomnipool".padEnd(32,"\0")),ke);function At(m,e){let t;return JSON.stringify(m,(r,s)=>(s&&s[e]&&(t=s),s)),t}function yr(m,e,t){let r;return JSON.stringify(m,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Qr=require("@polkadot/types/lookup");var Vr=require("@polkadot/api-base/types/consts");var es=require("@polkadot/api-base/types/errors");var ts=require("@polkadot/api-base/types/events");var rs=require("@polkadot/api-base/types/storage");var ss=require("@polkadot/api-base/types/submittable");var is=require("@polkadot/rpc-core/types/jsonrpc");var ns=require("@polkadot/api-base/types/calls");var gs=require("@polkadot/types/types/registry");var Ps=require("@polkadot/types/lookup");var bs=require("@polkadot/api-base/types/consts");var ys=require("@polkadot/api-base/types/errors");var Ss=require("@polkadot/api-base/types/events");var ws=require("@polkadot/api-base/types/storage");var xs=require("@polkadot/api-base/types/submittable");var Os=require("@polkadot/rpc-core/types/jsonrpc");var Bs=require("@polkadot/api-base/types/calls");var Rs=require("@polkadot/types/types/registry");var ve=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 ve{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]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.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]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getToken(e,t,r,s){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:a,isSufficient:c,existentialDeposit:u}=t,{symbol:y,decimals:O}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:y,decimals:O,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:this.parseLocation("parachain",s),existentialDeposit:u.toString()}}getBond(e,t,r,s){let[i,a]=s,{assetType:c,isSufficient:u,existentialDeposit:y}=t,{symbol:O,decimals:B}=this.getToken(i.toString(),t,r),F=a.toNumber(),R=new Intl.DateTimeFormat("en-GB"),T=[O,"Bond",R.format(F)].join(" ");return{id:e,name:T,symbol:O+"b",decimals:B,icon:O,type:c.toString(),isSufficient:u.toHuman(),existentialDeposit:y.toString()}}getShares(e,t,r,s){let{assets:i}=s,{name:a,symbol:c,assetType:u,isSufficient:y,existentialDeposit:O}=t,F=i.map(C=>C.toString()).map(C=>{let{symbol:L}=this.getToken(C,t,r);return[C,L]}),R=Object.fromEntries(F),T=Object.values(R);return{id:e,name:T.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:T.join("/"),type:u.toString(),isSufficient:y.toHuman(),existentialDeposit:O.toString(),meta:R}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),a=r?.find(c=>c.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:a}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e){let[t,r,s,i,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),c=this.getSupportedAssets(t),u=this.normalizeMetadata(c,a);return c.map(([{args:[y]},O])=>{let B=O.unwrap(),F=r.get(y.toString()),{assetType:R}=B;switch(R.toString()){case"Bond":let T=i.get(y.toString());return this.getBond(y.toString(),B,u,T);case"StableSwap":let C=s.get(y.toString());return this.getShares(y.toString(),B,u,C);case"External":return this.getExternal(y.toString(),B,e,F);default:return this.getToken(y.toString(),B,u,F)}}).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 r=At(t.toJSON(),e);return r&&r[e]}else return}};var Me=class extends ve{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:r,reserved:s,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:i})}async subscribeBalance(e,t,r){let s=t.filter(i=>i!==Oe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach(({free:a,reserved:c,frozen:u},y)=>{let O=this.calculateFreeBalance({free:a,feeFrozen:c,frozen:u}),B=s[y][1];r(B,O)})})}async subscribeTokenBalance(e,t,r){let s=t.filter(i=>i!==Oe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach((a,c)=>{let u=this.calculateFreeBalance(a),y=s[c][1];r(y,u)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(Oe,this.calculateFreeBalance(r)))}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:i}=e,a=new q(t),c=new q(r||i),u=new q(s||0),y=c.gt(u)?c:u;return a.minus(y)}};var Nt=require("@polkadot/util-crypto"),Ft=require("@galacticcouncil/math-liquidity-mining");var it=class extends ve{constructor(e){super(e)}secondsInYear=new q(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(u)).unwrap(),O=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(u)).unwrap(),O=(await this.api.query.xykWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new q(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),c=a.price.n.toString(),u=a.price.d.toString(),y;return Number(t)<Number(r)?y=(0,Ft.fixed_from_rational)(c,u):y=(0,Ft.fixed_from_rational)(u,c),y}getGlobalRewardPerPeriod(e,t,r,s){let a=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return a.gte(r)?r:a}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,Nt.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,Nt.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:c,globalFarm:u,priceAdjustment:y})=>{let O=new q(u.totalSharesZ.toString()),B=u.plannedYieldingPeriods.toString(),F=new q(u.yieldPerPeriod.toString()),R=new q(u.maxRewardPerPeriod.toString()),T=u.blocksPerPeriod.toString(),C=new q(c.multiplier.toString()).shiftedBy(-18),L=this.secondsInYear.div(new q(r).times(T)),W;if(O.isZero())W=F.times(C).times(L);else{let we=this.getGlobalRewardPerPeriod(O,F,R,y);W=this.getPoolYieldPerPeriod(we,C,O,y).times(L)}let w=new q(u.pendingRewards.toString()).plus(u.accumulatedPaidRewards.toString()),Q=R.times(B);return w.div(Q).gte(.99)?_:W.times(100)}).reduce((c,u)=>c.plus(u),_).toString():void 0}};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 r=>{let s=[await this.subscribePoolChange(r),await this.subscribeTokensPoolBalance(r),await this.subscribeSystemPoolBalance(r)];if(this.hasShareAsset(r)){let i=await this.subscribeSharePoolBalance(r);s.push(i)}return this.subscribeLog(r),s});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,r)=>t.id!==r))}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(r,s){let i=e.tokens.findIndex(a=>a.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=s.toString())}}};var nt=class extends be{MAX_FINAL_WEIGHT=Z(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:r}=t.unwrap(),s=e.filter(([i,a])=>this.isActivePool(a.unwrap(),r)).map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=await this.getPoolDelta(u,c,r.toString());return this.poolsData.set(i.toString(),c),{address:u,type:"Lbp",fee:c.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let a=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(c=>c.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,r){let{start:s,end:i,assets:a,initialWeight:c,finalWeight:u,repayTarget:y,feeCollector:O}=t,B=pe.calculateLinearWeights(s.toString(),i.toString(),c.toString(),u.toString(),r),[F,R]=a,T=F.toString(),C=I(B),L=R.toString(),W=this.MAX_FINAL_WEIGHT.minus(I(C)),[w,Q,oe]=await Promise.all([this.isRepayFeeApplied(T,y.toString(),O.toString()),this.getBalance(e,T),this.getBalance(e,L)]);return{repayFeeApply:w,tokens:[{id:T,weight:C,balance:Q.toString()},{id:L,weight:W,balance:oe.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=I(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}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(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var Wt=require("@polkadot/util-crypto"),$t=require("@polkadot/util");function V(m,e){return m.shiftedBy(-1*e).toString()}function ge(m){return m[0]/m[1]*100}function ne(m){return m[0]/m[1]}function de(m){return[m/st,st]}var ot=class extends be{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=r.map(async([{args:[u]},y])=>{let{hubReserve:O,shares:B,tradable:F}=y.unwrap(),R=await this.getBalance(t,u.toString());return{id:u.toString(),hubReserves:I(O.toString()),shares:I(B.toString()),tradeable:F.bits.toNumber(),balance:R.toString()}}),c=await Promise.all(a);return c.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:c,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=await this.api.query.dynamicFees.assetFee(e),s=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=s.minFee.toNumber()+i.minFee.toNumber(),c=s.maxFee.toNumber()+i.maxFee.toNumber();if(r.isSome){let{assetFee:u,protocolFee:y}=r.unwrap();return{assetFee:de(u.toNumber()),protocolFee:de(y.toNumber()),min:de(a),max:de(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:de(a),max:de(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,i)=>{let a=e.tokens[i];if(s.isNone)return a;let c=s.unwrap();return this.updateTokenState(a,c)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i}=t;return{...e,hubReserves:I(r.toString()),shares:I(s.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return de(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return de(t)}getPoolId(){return(0,Wt.encodeAddress)((0,$t.stringToU8a)("modlomnipool".padEnd(32,"\0")),ke)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var at=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:[r]},s])=>{let i=r.toString(),[a,c]=s.unwrap(),[u,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:u.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(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var ut=require("@polkadot/util-crypto");var K=require("@galacticcouncil/math-stableswap"),re=class{static getPoolAddress(e){return(0,K.pool_account_name)(e)}static calculateAmplification(e,t,r,s,i){return(0,K.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,a){return(0,K.calculate_in_given_out)(e,t,r,s,i,a)}static calculateAddOneAsset(e,t,r,s,i,a){return(0,K.calculate_add_one_asset)(e,t,r,s,i,a)}static calculateSharesForAmount(e,t,r,s,i,a){return(0,K.calculate_shares_for_amount)(e,t,r,s,i,a)}static calculateOutGivenIn(e,t,r,s,i,a){return(0,K.calculate_out_given_in)(e,t,r,s,i,a)}static calculateLiquidityOutOneAsset(e,t,r,s,i,a){return(0,K.calculate_liquidity_out_one_asset)(e,t,r,s,i,a)}static calculateShares(e,t,r,s,i){return(0,K.calculate_shares)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,K.calculate_pool_trade_fee)(e,t,r)}};var lt=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()]),r=t.toNumber(),s=e.map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=this.getPoolAddress(u),[O,B]=await Promise.all([this.getPoolDelta(u,c,r.toString()),this.getPoolTokens(y,u,c)]);return this.stablePools.set(y,c),{address:y,id:u,type:"Stableswap",fee:de(c.fee.toNumber()),tokens:B,...O,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toNumber(),s=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,s,r.toString());Object.assign(e,i)})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:a,finalBlock:c}=t,u=re.calculateAmplification(s.toString(),i.toString(),a.toString(),c.toString(),r),y=await this.api.query.tokens.totalIssuance(e);return{amplification:u,totalIssuance:y.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async u=>{let[y,O]=await Promise.all([this.api.query.stableswap.assetTradability(t,u.toString()),this.getBalance(e,u.toString())]);return{id:u.toString(),tradeable:y.bits.toNumber(),balance:O.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:u}=c.unwrap(),y=await this.getBalance($e,t);a.push({id:t,tradeable:u.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),r=re.getPoolAddress(t);return(0,ut.encodeAddress)((0,ut.blake2AsHex)(r),ke)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function ct(m){return m.map(({assetIn:e,assetOut:t,pool:r,poolId:s})=>r==="Stableswap"?{pool:{Stableswap:s},assetIn:e,assetOut:t}:{pool:r,assetIn:e,assetOut:t})}var je=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Tt=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"}},_t=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Rt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},kt=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 at(this.api),this.omniClient=new ot(this.api),this.lbpClient=new nt(this.api),this.stableClient=new lt(this.api)}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||this.syncRegistry(),e.length==0){let a=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(c=>c.isSupported()).map(c=>c.getPools()))).flat();return this.withMetadata(a)}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 s=(await Promise.all(t)).flat();return this.withMetadata(s)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(r=>[r.id,r]));return e.filter(r=>r.type==="Xyk"?r.tokens.every(s=>t.get(s.id)):!0).map(r=>{let s=r.tokens.map(i=>{let a=t.get(i.id);return{...i,...a}});return{...r,tokens:s}})}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,r,s,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,r.toFixed(),s.toFixed()):a=this.api.tx.router.buy(e,t,r.toFixed(),s.toFixed(),ct(i));let c=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,r,s,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,r.toFixed(),s.toFixed()):a=this.api.tx.router.sell(e,t,r.toFixed(),s.toFixed(),ct(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var Je=(m,e)=>m===e?0:m==null?e==null?0:-1:e==null?m==null?0:1:typeof m.compare=="function"?m.compare(e):typeof e.compare=="function"?-e.compare(m):m<e?-1:m>e?1:0;var mt=(m,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(m(t)+e(t))}};var Sr=mt(()=>"illegal argument(s)"),jt=m=>{throw new Sr(m)};var wr=mt(()=>"index out of bounds"),Lt=m=>{throw new wr(m)},pt=(m,e,t)=>(m<e||m>=t)&&Lt(m);var Jt=23283064365386963e-26,gt=class{float(e=1){return this.int()*Jt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Jt-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var Mt=Math.random,Dt=class extends gt{int(){return Mt()*4294967296>>>0}float(e=1){return Mt()*e}norm(e=1){return(Mt()-.5)*2*e}},Zt=new Dt;var Kt=m=>m!=null&&typeof m!="function"&&m.length!==void 0;var Qt=Object.getPrototypeOf({}),ht="function",Vt="string",Ge=(m,e)=>{let t;if(m===e)return!0;if(m!=null){if(typeof m.equiv===ht)return m.equiv(e)}else return m==e;if(e!=null){if(typeof e.equiv===ht)return e.equiv(m)}else return m==e;return typeof m===Vt||typeof e===Vt?!1:(t=Object.getPrototypeOf(m),(t==null||t===Qt)&&(t=Object.getPrototypeOf(e),t==null||t===Qt)?vr(m,e):typeof m!==ht&&m.length!==void 0&&typeof e!==ht&&e.length!==void 0?xr(m,e):m instanceof Set&&e instanceof Set?Or(m,e):m instanceof Map&&e instanceof Map?Br(m,e):m instanceof Date&&e instanceof Date?m.getTime()===e.getTime():m instanceof RegExp&&e instanceof RegExp?m.toString()===e.toString():m!==m&&e!==e)},xr=(m,e,t=Ge)=>{let r=m.length;if(r===e.length)for(;r-- >0&&t(m[r],e[r]););return r<0},Or=(m,e,t=Ge)=>m.size===e.size&&t([...m.keys()].sort(),[...e.keys()].sort()),Br=(m,e,t=Ge)=>m.size===e.size&&t([...m].sort(),[...e].sort()),vr=(m,e,t=Ge)=>{if(Object.keys(m).length!==Object.keys(e).length)return!1;for(let r in m)if(!e.hasOwnProperty(r)||!t(m[r],e[r]))return!1;return!0};var er=(m,e)=>m!=null&&typeof m[e]=="function";var tr=m=>er(m,"xform")?m.xform():m;var dt=Symbol(),Ct=()=>{};var rr=m=>m!=null&&typeof m[Symbol.iterator]=="function";var ft=class{value;constructor(e){this.value=e}deref(){return this.value}};var Pt=m=>m instanceof ft;var sr=m=>m instanceof ft?m.deref():m;function*ir(m,e){let t=tr(m)([Ct,Ct,(r,s)=>s])[2];for(let r of e){let s=t(dt,r);if(Pt(s)){s=sr(s.deref()),s!==dt&&(yield s);return}s!==dt&&(yield s)}}var nr=(m,e)=>[m[0],m[1],e];function Ze(m,e){return rr(e)?ir(Ze(m),e):t=>{let r=t[2];return nr(t,(s,i)=>r(s,m(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 or("next",this._head)}reverseIterator(){return or("prev",this.tail)}clear(){this.release()}compare(e,t=Je){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,a=0;for(;r-- >0&&a===0;)a=t(s.value,i.value),s=s.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof qe||Kt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!Ge(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.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 r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!Pt(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >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,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&Lt(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}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,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*or(m,e){for(;e;)yield e.value,e=e[m]}var ye=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 ye(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 ye}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}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 r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}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 ye,e)}nth(e,t){let r=this.nthCell(e);return r?r.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 r=this.nthCell(e),s=this.nthCell(t-1),i=a=>({first(){return a.value},next(){return a!==s&&a.next?i(a.next):void 0}});return r?i(r):void 0}shuffle(e,t=Zt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&jt("invalid indices: ${from} / ${to}");let i=new ye,a=this.nthCell(r);for(;a&&++r<=s;)i.push(a.value),a=a.next;return i}sort(e=Je){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,a=0;for(let u=0;u<t&&(a++,i=i.next,!!i);u++);let c=t;for(;a>0||c>0&&i;){let u;a===0?(u=i,i=i.next,c--):!i||c===0||e(r.value,i.value)<=0?(u=r,r=r.next,a--):(u=i,i=i.next,c--),this._tail?this._tail.next=u:this._head=u,u.prev=this._tail,this._tail=u}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),pt(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new ye;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let a of r)this.insertBefore(s,a);else for(let a of r)this.push(a);return i}};var He=class{map;items;opts;_size;constructor(e,t){let r=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=r.map(),this.items=new ye,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ze(e=>[e.k,e],this.items)}keys(){return Ze(e=>e.k,this.items)}values(){return Ze(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 r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e);return this._size+=Math.max(0,r-(s?s.value.s:0)),this.ensureSize()&&this.doSetEntry(s,e,t,r),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let r=this.map.get(e);return r?Promise.resolve(this.resetEntry(r)):t().then(s=>this.set(e,s))}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,r=this.opts.maxlen;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e&&e(s.k,s.v),this._size-=s.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,r,s){e?(e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var bt=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 r=[t.address,e].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let i=await super.getPoolFees(e,t);return this.feeCache.set(r,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
+
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Ie=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Ie(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,i,a,c){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=c}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let c=this.calculateTradeFee(t,r),u=ge(this.repayFeeApply?r.repayFee:r.exchangeFee),y=t.plus(c),O=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return O.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:O,calculatedIn:O,amountOut:t,feePct:u,errors:i}}else{let c=this.calculateInGivenOut(e,t),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let c=this.calculateOutGivenIn(e,t),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),u=this.calculateTradeFee(c,r),y=ge(this.repayFeeApply?r.repayFee:r.exchangeFee),O=c.minus(u),B=e.balanceOut.div(this.maxOutRatio);return O.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:O,feePct:y,errors:i}}}calculateInGivenOut(e,t){let r=pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?_:s}calculateOutGivenIn(e,t){let r=pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?_:s}spotPriceInGivenOut(e){let t=pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),Z(ae,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),Z(ae,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let r=pe.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(r)}};var D=require("@galacticcouncil/math-omnipool");var X=class{static calculateSpotPrice(e,t,r,s){return(0,D.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,D.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,a,c,u,y){return(0,D.calculate_in_given_out)(e,t,r,s,i,a,c,u,y)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,D.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,a,c,u,y){return(0,D.calculate_out_given_in)(e,t,r,s,i,a,c,u,y)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,D.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,D.calculate_pool_trade_fee)(e,t,r)}static calculateShares(e,t,r,s){return(0,D.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,a,c,u){return(0,D.calculate_liquidity_out)(e,t,r,s,i,a,c,u)}static calculateLiquidityLRNAOut(e,t,r,s,i,a,c,u){return(0,D.calculate_liquidity_lrna_out)(e,t,r,s,i,a,c,u)}static calculateCapDifference(e,t,r,s){let i=q(t),a=q(e),c=q(s),y=q(r).shiftedBy(-18);if(i.div(c).lt(y)){let B=y.times(c).minus(i).times(a),F=i.times(q(1).minus(y));return B.div(F).toFixed(0)}else return"0"}static verifyAssetCap(e,t,r,s){return(0,D.verify_asset_cap)(e,t,r,s)}static calculateLimitHubIn(e,t,r,s){return(0,D.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,D.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,D.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,D.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,D.is_remove_liquidity_allowed)(e)}};var Ae=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new Ae(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,i,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,tradeableIn:s.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),c=s===_?_:a.div(s).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),O=X.isBuyAllowed(e.tradeableOut);(!y||!O)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&u.push("MaxOutRatioExceeded");let F=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(F)&&u.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:c.toNumber(),errors:u}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),c=s.minus(i).div(s).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),O=X.isBuyAllowed(e.tradeableOut);(!y||!O)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&u.push("MaxInRatioExceeded");let F=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(F)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:c.toNumber(),errors:u}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=X.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ne(r.assetFee).toString():_.toString(),r?ne(r.protocolFee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateLrnaInGivenOut(e,t,r){let s=X.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ne(r.assetFee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=X.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ne(r.assetFee).toString():_.toString(),r?ne(r.protocolFee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateOutGivenLrnaIn(e,t,r){let s=X.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ne(r.assetFee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=X.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=X.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=X.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=X.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Ee-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,r,s,i,a,c,u,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.amplification=a,this.id=c,this.fee=u,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?rt:s.tradeable,tradeableOut:this.id===t?rt:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=ge(r.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),a=ge(r.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,r){let s=re.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateAddOneAsset(e,t,r){let s=re.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateSharesForAmount(e,t,r){let s=re.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=Z(ae,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,r){let s=re.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateWithdrawOneAsset(e,t,r){let s=re.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateShares(e,t,r){let s=re.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=Z(ae,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 r=re.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(r)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};var $=require("@galacticcouncil/math-xyk"),Se=class{static getSpotPrice(e,t,r){return(0,$.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,$.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,$.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,$.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,$.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,$.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,$.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,$.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,$.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,$.calculate_liquidity_out_asset_b)(e,t,r,s)}};var Fe=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Fe(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),a=ge(r.exchangeFee),c=s.plus(i),u=[];t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&u.push("MaxOutRatioExceeded");let O=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(O)&&u.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:s,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),a=ge(r.exchangeFee),c=s.minus(i),u=[];t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&u.push("MaxInRatioExceeded");let O=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(O)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:c,feePct:a,errors:u}}calculateInGivenOut(e,t){let r=Se.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?_:s}calculateOutGivenIn(e,t){let r=Se.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?_:s}spotPriceInGivenOut(e){let t=Se.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=Z(ae,18-e.decimalsOut);return I(t).div(r)}spotPriceOutGivenIn(e){let t=Se.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=Z(ae,18-e.decimalsIn);return I(t).div(r)}calculateTradeFee(e,t){let r=Se.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(r)}};var Ue=class{static get(e){switch(e.type){case"Xyk":return Fe.fromPool(e);case"Omnipool":return Ae.fromPool(e);case"Lbp":return Ie.fromPool(e);case"Stableswap":return Ne.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var _e=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new We,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:r,poolsMap:s}=await this.validateToken(e,t),a=this.getPaths(e,null,s,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(a)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,origin:s.origin,meta:s.meta}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(c=>this.validPath(c,r)).map(c=>this.toHops(c,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(r);return{assets:s,poolsMap:i}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,Ue.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,i])=>{let a=t.get(r);return{poolAddress:r,poolId:a?.id,pool:a?.type,assetIn:s,assetOut:i}})}toAssets(e,t){return e.map(r=>t.get(r))}};function Ir(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ze(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Gt(m,e){return ae.minus(e.div(m)).multipliedBy(100).decimalPlaces(2)}function qt(m,e){return e.div(m).minus(ae).multipliedBy(100).decimalPlaces(2)}var Ke=class extends _e{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,a=s[s.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[r,s]}}getPoolFeeRange(e){let t=e.min?ge(e.min):void 0,r=e.max?ge(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new De(e,t);let u;if(s)u=await this.toSellSwaps(r,s,a);else{let E=c.map(async n=>await this.toSellSwaps(r,n,a)),Y=await Promise.all(E);u=this.findBestSellRoute(Y)}let y=u[0],O=u[u.length-1],B=this.isDirectTrade(u),F=u.map(E=>E.spotPrice.shiftedBy(-1*E.assetOutDecimals)).reduce((E,Y)=>E.multipliedBy(Y)),R=Z(F,O.assetOutDecimals),T=B?O.calculatedOut:this.calculateDelta0Y(y.amountIn,u,a),C=O.amountOut,L=B?O.tradeFeePct:Gt(T,C).toNumber(),W=T.minus(C),w=this.getRouteFeeRange(u),Q=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(R),oe=ze(T,Q),we=E=>this.poolService.buildSellTx(e,t,y.amountIn,E,u.map(Y=>Y));return{type:"Sell",amountIn:y.amountIn,amountOut:O.amountOut,spotPrice:R,tradeFee:W,tradeFeePct:L,tradeFeeRange:w,priceImpactPct:oe.toNumber(),swaps:u,toTx:we,toHuman(){return{type:"Sell",amountIn:V(y.amountIn,y.assetInDecimals),amountOut:V(O.amountOut,O.assetOutDecimals),spotPrice:V(R,O.assetOutDecimals),tradeFee:V(W,O.assetOutDecimals),tradeFeePct:L,tradeFeeRange:w,priceImpactPct:oe.toNumber(),swaps:u.map(E=>E.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=s[i-1]:y=e;let O=c.calculateOutGivenIn(u,y);s.push(O)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=s[i-1].amountOut:y=Z(I(e),u.decimalsIn).decimalPlaces(0,1);let O=await this.poolService.getPoolFees(u.assetOut,c),{amountOut:B,calculatedOut:F,feePct:R,errors:T}=c.validateAndSell(u,y,O),C=this.getPoolFeeRange(O),L=c.spotPriceOutGivenIn(u),W=y.shiftedBy(-1*u.decimalsIn).multipliedBy(L),w=ze(F,W);s.push({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountIn:y,calculatedOut:F,amountOut:B,spotPrice:L,tradeFeePct:R,tradeFeeRange:C,priceImpactPct:w.toNumber(),errors:T,toHuman(){return{...a,amountIn:V(y,u.decimalsIn),calculatedOut:V(F,u.decimalsOut),amountOut:V(B,u.decimalsOut),spotPrice:V(L,u.decimalsOut),tradeFeePct:R,tradeFeeRange:C,priceImpactPct:w.toNumber(),errors:T}}})}return s}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r),i=super.getPaths(e,t,s,r);if(i.length===0)return Promise.resolve(void 0);let a=r.map(w=>w.tokens.find(Q=>Q.id===e)).filter(w=>!!w).sort((w,Q)=>Number(Q.balance)-Number(w.balance)),{balance:c,decimals:u}=a[0],O=I(c).shiftedBy(-1*u).div(100).multipliedBy(.1),B=i.map(async w=>await this.toSellSwaps(O,w,s)),F=await Promise.all(B),R=this.findBestSellRoute(F),T=await this.toSellSwaps("1",R,s),C=T.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,Q)=>w.multipliedBy(Q)),L=T[T.length-1].assetOutDecimals;return{amount:Z(C,L),decimals:L}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,a=s[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new De(e,t);let u;if(s)u=await this.toBuySwaps(r,s,a);else{let E=c.map(async n=>await this.toBuySwaps(r,n,a)),Y=await Promise.all(E);u=this.findBestBuyRoute(Y)}let y=u[u.length-1],O=u[0],B=this.isDirectTrade(u),F=u.map(E=>E.spotPrice.shiftedBy(-1*E.assetInDecimals)).reduce((E,Y)=>E.multipliedBy(Y)),R=Z(F,O.assetInDecimals),T=B?O.calculatedIn:this.calculateDelta0X(y.amountOut,u,a),C=O.amountIn,L=B?O.tradeFeePct:qt(T,C).toNumber(),W=C.minus(T),w=this.getRouteFeeRange(u),Q=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(R),oe;T.isZero()?oe=-100:oe=ze(Q,T).toNumber();let we=E=>this.poolService.buildBuyTx(e,t,y.amountOut,E,u.map(Y=>Y));return{type:"Buy",amountOut:y.amountOut,amountIn:O.amountIn,spotPrice:R,tradeFee:W,tradeFeePct:L,tradeFeeRange:w,priceImpactPct:oe,swaps:u,toTx:we,toHuman(){return{type:"Buy",amountOut:V(y.amountOut,y.assetOutDecimals),amountIn:V(O.amountIn,O.assetInDecimals),spotPrice:V(R,O.assetInDecimals),tradeFee:V(W,O.assetInDecimals),tradeFeePct:L,tradeFeeRange:w,priceImpactPct:oe,swaps:u.map(E=>E.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=s[0];let O=c.calculateInGivenOut(u,y);s.unshift(O)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=Z(I(e),u.decimalsOut).decimalPlaces(0,1):y=s[0].amountIn;let O=await this.poolService.getPoolFees(u.assetOut,c),{amountIn:B,calculatedIn:F,feePct:R,errors:T}=c.validateAndBuy(u,y,O),C=this.getPoolFeeRange(O),L=c.spotPriceInGivenOut(u),W=y.shiftedBy(-1*u.decimalsOut).multipliedBy(L),w;F.isZero()?w=-100:w=ze(W,F).toNumber(),s.unshift({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountOut:y,calculatedIn:F,amountIn:B,spotPrice:L,tradeFeePct:R,tradeFeeRange:C,priceImpactPct:w,errors:T,toHuman(){return{...a,amountOut:V(y,u.decimalsOut),calculatedIn:V(F,u.decimalsIn),amountIn:V(B,u.decimalsIn),spotPrice:V(L,u.decimalsIn),tradeFeePct:R,tradeFeeRange:C,priceImpactPct:w,errors:T}}})}return s}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,FarmClient,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
|
package/build/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Ye=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var $t=5,Re=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new Ye,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let u=i.dequeue();if(u==null||u.length>$t)return r;let c=u[u.length-1];(s===null||c[0]===s)&&r.push(u),e.get(c[0])?.forEach(w=>{if(this.isNotVisited(w,u)){let B=[...u];B.push(w),i.enqueue(B)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,a]of t){let u=parseInt(i),c=parseInt(a);s.get(u)?.push([c,r])}return s}};function pt(p){let e={};for(let t of p){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 a=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(a)}}}return e}var Ee=class{getProposals(e,t,s){let r=pt(s),i=Object.keys(r),a=i.map(w=>r[w]).flat(),u=new Re,c=u.buildAndPopulateGraph(i,a),S=u.findPaths(c,parseInt(e),t?parseInt(t):null);return this.parsePaths(S)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let a=s[i],u=s[i+1];if(u==null)break;r.push(this.toEdge(a,u))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var Jt=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,mt=Math.ceil,oe=Math.floor,Z="[BigNumber Error] ",wt=Z+"Number primitive has more than 15 significant digits: ",ce=1e14,N=14,gt=9007199254740991,ht=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],be=1e7,W=1e9;function Bt(p){var e,t,s,r=x.prototype={constructor:x,toString:null,valueOf:null},i=new x(1),a=20,u=4,c=-7,S=21,w=-1e7,B=1e7,T=!1,E=1,F=0,C={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},M="0123456789abcdefghijklmnopqrstuvwxyz",J=!0;function x(n,o){var l,P,g,d,y,m,h,b,f=this;if(!(f instanceof x))return new x(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((m=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,y=n;y>=10;y/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!Jt.test(b=String(n)))return s(f,b,m);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(y=b.search(/e/i))>0?(d<0&&(d=y),d+=+b.slice(y+1),b=b.substring(0,y)):d<0&&(d=b.length)}else{if(G(o,2,M.length,"Base"),o==10&&J)return f=new x(n),_(f,a+f.e+1,u);if(b=String(n),m=typeof n=="number"){if(n*0!=0)return s(f,b,m,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(wt+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=M.slice(0,o),d=y=0,h=b.length;y<h;y++)if(l.indexOf(P=b.charAt(y))<0){if(P=="."){if(y>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,y=-1,d=0;continue}return s(f,String(n),m,o)}m=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(y=0;b.charCodeAt(y)===48;y++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(y,++h)){if(h-=y,m&&x.DEBUG&&h>15&&(n>gt||n!==oe(n)))throw Error(wt+f.s*n);if((d=d-y-1)>B)f.c=f.e=null;else if(d<w)f.c=[f.e=0];else{if(f.e=d,f.c=[],y=(d+1)%N,d<0&&(y+=N),y<h){for(y&&f.c.push(+b.slice(0,y)),h-=N;y<h;)f.c.push(+b.slice(y,y+=N));y=N-(b=b.slice(y)).length}else y-=h;for(;y--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}x.clone=Bt,x.ROUND_UP=0,x.ROUND_DOWN=1,x.ROUND_CEIL=2,x.ROUND_FLOOR=3,x.ROUND_HALF_UP=4,x.ROUND_HALF_DOWN=5,x.ROUND_HALF_EVEN=6,x.ROUND_HALF_CEIL=7,x.ROUND_HALF_FLOOR=8,x.EUCLID=9,x.config=x.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],G(l,0,W,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],G(l,0,8,o),u=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(G(l[0],-W,0,o),G(l[1],0,W,o),c=l[0],S=l[1]):(G(l,-W,W,o),c=-(S=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)G(l[0],-W,-1,o),G(l[1],1,W,o),w=l[0],B=l[1];else if(G(l,-W,W,o),l)w=-(B=l<0?-l:l);else throw Error(Z+o+" cannot be zero: "+l);if(n.hasOwnProperty(o="CRYPTO"))if(l=n[o],l===!!l)if(l)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))T=l;else throw T=!l,Error(Z+"crypto unavailable");else T=l;else throw Error(Z+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],G(l,0,9,o),E=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],G(l,0,W,o),F=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")C=l;else throw Error(Z+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))J=l.slice(0,10)=="0123456789",M=l;else throw Error(Z+o+" invalid: "+l)}else throw Error(Z+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:u,EXPONENTIAL_AT:[c,S],RANGE:[w,B],CRYPTO:T,MODULO_MODE:E,POW_PRECISION:F,FORMAT:C,ALPHABET:M}},x.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!x.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-W&&g<=W&&g===oe(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%N,o<1&&(o+=N),String(P[0]).length==o){for(o=0;o<P.length;o++)if(l=P[o],l<0||l>=ce||l!==oe(l))break e;if(l!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(Z+"Invalid BigNumber: "+n)},x.maximum=x.max=function(){return re(arguments,-1)},x.minimum=x.min=function(){return re(arguments,1)},x.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return oe(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,y,m,h=0,b=[],f=new x(i);if(l==null?l=a:G(l,0,W),y=mt(l/N),T)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(y*=2));h<y;)m=P[h]*131072+(P[h+1]>>>11),m>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(m%1e14),h+=2);h=y/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(y*=7);h<y;)m=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],m>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(m%1e14),h+=7);h=y/7}else throw T=!1,Error(Z+"crypto unavailable");if(!T)for(;h<y;)m=o(),m<9e15&&(b[h++]=m%1e14);for(y=b[--h],l%=N,y&&l&&(m=ht[N-l],b[h]=oe(y/m)*m);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=N);for(h=1,m=b[0];m>=10;m/=10,h++);h<N&&(d-=N-h)}return f.e=d,f.c=b,f}}(),x.sum=function(){for(var n=1,o=arguments,l=new x(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var y,m=[0],h,b=0,f=l.length;b<f;){for(h=m.length;h--;m[h]*=P);for(m[0]+=d.indexOf(l.charAt(b++)),y=0;y<m.length;y++)m[y]>g-1&&(m[y+1]==null&&(m[y+1]=0),m[y+1]+=m[y]/g|0,m[y]%=g)}return m.reverse()}return function(l,P,g,d,y){var m,h,b,f,O,v,A,k,q=l.indexOf("."),X=a,R=u;for(q>=0&&(f=F,F=0,l=l.replace(".",""),k=new x(P),v=k.pow(l.length-q),F=f,k.c=o(fe(ne(v.c),v.e,"0"),10,g,n),k.e=k.c.length),A=o(l,P,g,y?(m=M,n):(m=n,M)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return m.charAt(0);if(q<0?--b:(v.c=A,v.e=b,v.s=d,v=e(v,k,X,R,g),A=v.c,O=v.r,b=v.e),h=b+X+1,q=A[h],f=g/2,O=O||h<0||A[h+1]!=null,O=R<4?(q!=null||O)&&(R==0||R==(v.s<0?3:2)):q>f||q==f&&(R==4||O||R==6&&A[h-1]&1||R==(v.s<0?8:7)),h<1||!A[0])l=O?fe(m.charAt(1),-X,m.charAt(0)):m.charAt(0);else{if(A.length=h,O)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(q=0,l="";q<=f;l+=m.charAt(A[q++]));l=fe(l,b,m.charAt(0))}return l}}(),e=function(){function n(P,g,d){var y,m,h,b,f=0,O=P.length,v=g%be,A=g/be|0;for(P=P.slice();O--;)h=P[O]%be,b=P[O]/be|0,y=A*h+b*v,m=v*h+y%be*be+f,f=(m/d|0)+(y/be|0)+A*b,P[O]=m%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,y){var m,h;if(d!=y)h=d>y?1:-1;else for(m=h=0;m<d;m++)if(P[m]!=g[m]){h=P[m]>g[m]?1:-1;break}return h}function l(P,g,d,y){for(var m=0;d--;)P[d]-=m,m=P[d]<g[d]?1:0,P[d]=m*y+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,y,m){var h,b,f,O,v,A,k,q,X,R,D,j,We,ut,ct,ge,_e,ie=P.s==g.s?1:-1,Q=P.c,H=g.c;if(!Q||!Q[0]||!H||!H[0])return new x(!P.s||!g.s||(Q?H&&Q[0]==H[0]:!H)?NaN:Q&&Q[0]==0||!H?ie*0:ie/0);for(q=new x(ie),X=q.c=[],b=P.e-g.e,ie=d+b+1,m||(m=ce,b=ae(P.e/N)-ae(g.e/N),ie=ie/N|0),f=0;H[f]==(Q[f]||0);f++);if(H[f]>(Q[f]||0)&&b--,ie<0)X.push(1),O=!0;else{for(ut=Q.length,ge=H.length,f=0,ie+=2,v=oe(m/(H[0]+1)),v>1&&(H=n(H,v,m),Q=n(Q,v,m),ge=H.length,ut=Q.length),We=ge,R=Q.slice(0,ge),D=R.length;D<ge;R[D++]=0);_e=H.slice(),_e=[0].concat(_e),ct=H[0],H[1]>=m/2&&ct++;do{if(v=0,h=o(H,R,ge,D),h<0){if(j=R[0],ge!=D&&(j=j*m+(R[1]||0)),v=oe(j/ct),v>1)for(v>=m&&(v=m-1),A=n(H,v,m),k=A.length,D=R.length;o(A,R,k,D)==1;)v--,l(A,ge<k?_e:H,k,m),k=A.length,h=1;else v==0&&(h=v=1),A=H.slice(),k=A.length;if(k<D&&(A=[0].concat(A)),l(R,A,D,m),D=R.length,h==-1)for(;o(H,R,ge,D)<1;)v++,l(R,ge<D?_e:H,D,m),D=R.length}else h===0&&(v++,R=[0]);X[f++]=v,R[0]?R[D++]=Q[We]||0:(R=[Q[We]],D=1)}while((We++<ut||R[0]!=null)&&ie--);O=R[0]!=null,X[0]||X.splice(0,1)}if(m==ce){for(f=1,ie=X[0];ie>=10;ie/=10,f++);_(q,d+(q.e=f+b*N-1)+1,y,O)}else q.e=b,q.r=+O;return q}}();function K(n,o,l,P){var g,d,y,m,h;if(l==null?l=u:G(l,0,8),!n.c)return n.toString();if(g=n.c[0],y=n.e,o==null)h=ne(n.c),h=P==1||P==2&&(y<=c||y>=S)?Je(h,y):fe(h,y,"0");else if(n=_(new x(n),o,l),d=n.e,h=ne(n.c),m=h.length,P==1||P==2&&(o<=d||d<=c)){for(;m<o;h+="0",m++);h=Je(h,d)}else if(o-=y,h=fe(h,d,"0"),d+1>m){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-m,o>0)for(d+1==m&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function re(n,o){for(var l,P,g=1,d=new x(n[0]);g<n.length;g++)P=new x(n[g]),(!P.s||(l=xe(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function Se(n,o,l){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(l=P+l*N-1)>B?n.c=n.e=null:l<w?n.c=[n.e=0]:(n.e=l,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,y,m,h){var b,f=m?y:y.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!m&&(f=f.replace(n,function(O,v,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?v:O}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),y!=f))return new x(f,b);if(x.DEBUG)throw Error(Z+"Not a"+(h?" base "+h:"")+" number: "+y);d.s=null}d.c=d.e=null}}();function _(n,o,l,P){var g,d,y,m,h,b,f,O=n.c,v=ht;if(O){e:{for(g=1,m=O[0];m>=10;m/=10,g++);if(d=o-g,d<0)d+=N,y=o,h=O[b=0],f=oe(h/v[g-y-1]%10);else if(b=mt((d+1)/N),b>=O.length)if(P){for(;O.length<=b;O.push(0));h=f=0,g=1,d%=N,y=d-N+1}else break e;else{for(h=m=O[b],g=1;m>=10;m/=10,g++);d%=N,y=d-N+g,f=y<0?0:oe(h/v[g-y-1]%10)}if(P=P||o<0||O[b+1]!=null||(y<0?h:h%v[g-y-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?y>0?h/v[g-y]:0:O[b-1])%10&1||l==(n.s<0?8:7)),o<1||!O[0])return O.length=0,P?(o-=n.e+1,O[0]=v[(N-o%N)%N],n.e=-o||0):O[0]=n.e=0,n;if(d==0?(O.length=b,m=1,b--):(O.length=b+1,m=v[N-d],O[b]=y>0?oe(h/v[g-y]%v[y])*m:0),P)for(;;)if(b==0){for(d=1,y=O[0];y>=10;y/=10,d++);for(y=O[0]+=m,m=1;y>=10;y/=10,m++);d!=m&&(n.e++,O[0]==ce&&(O[0]=1));break}else{if(O[b]+=m,O[b]!=ce)break;O[b--]=0,m=1}for(d=O.length;O[--d]===0;O.pop());}n.e>B?n.c=n.e=null:n.e<w&&(n.c=[n.e=0])}return n}function U(n){var o,l=n.e;return l===null?n.toString():(o=ne(n.c),o=l<=c||l>=S?Je(o,l):fe(o,l,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new x(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return xe(this,new x(n,o))},r.decimalPlaces=r.dp=function(n,o){var l,P,g,d=this;if(n!=null)return G(n,0,W),o==null?o=u:G(o,0,8),_(new x(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-ae(this.e/N))*N,g=l[g])for(;g%10==0;g/=10,P--);return P<0&&(P=0),P},r.dividedBy=r.div=function(n,o){return e(this,new x(n,o),a,u)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new x(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var l,P,g,d,y,m,h,b,f,O=this;if(n=new x(n),n.c&&!n.isInteger())throw Error(Z+"Exponent not an integer: "+U(n));if(o!=null&&(o=new x(o)),m=n.e>14,!O.c||!O.c[0]||O.c[0]==1&&!O.e&&O.c.length==1||!n.c||!n.c[0])return f=new x(Math.pow(+U(O),m?n.s*(2-$e(n)):+U(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new x(NaN);P=!h&&O.isInteger()&&o.isInteger(),P&&(O=O.mod(o))}else{if(n.e>9&&(O.e>0||O.e<-1||(O.e==0?O.c[0]>1||m&&O.c[1]>=24e7:O.c[0]<8e13||m&&O.c[0]<=9999975e7)))return d=O.s<0&&$e(n)?-0:0,O.e>-1&&(d=1/d),new x(h?1/d:d);F&&(d=mt(F/N+2))}for(m?(l=new x(.5),h&&(n.s=1),b=$e(n)):(g=Math.abs(+U(n)),b=g%2),f=new x(i);;){if(b){if(f=f.times(O),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(g){if(g=oe(g/2),g===0)break;b=g%2}else if(n=n.times(l),_(n,n.e+1,1),n.e>14)b=$e(n);else{if(g=+U(n),g===0)break;b=g%2}O=O.times(O),d?O.c&&O.c.length>d&&(O.c.length=d):P&&(O=O.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?_(f,F,u,y):f)},r.integerValue=function(n){var o=new x(this);return n==null?n=u:G(n,0,8),_(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return xe(this,new x(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return xe(this,new x(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=xe(this,new x(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&ae(this.e/N)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return xe(this,new x(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=xe(this,new x(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 l,P,g,d,y=this,m=y.s;if(n=new x(n,o),o=n.s,!m||!o)return new x(NaN);if(m!=o)return n.s=-o,y.plus(n);var h=y.e/N,b=n.e/N,f=y.c,O=n.c;if(!h||!b){if(!f||!O)return f?(n.s=-o,n):new x(O?y:NaN);if(!f[0]||!O[0])return O[0]?(n.s=-o,n):new x(f[0]?y:u==3?-0:0)}if(h=ae(h),b=ae(b),f=f.slice(),m=h-b){for((d=m<0)?(m=-m,g=f):(b=h,g=O),g.reverse(),o=m;o--;g.push(0));g.reverse()}else for(P=(d=(m=f.length)<(o=O.length))?m:o,m=o=0;o<P;o++)if(f[o]!=O[o]){d=f[o]<O[o];break}if(d&&(g=f,f=O,O=g,n.s=-n.s),o=(P=O.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=ce-1;P>m;){if(f[--P]<O[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=ce}f[P]-=O[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?Se(n,f,b):(n.s=u==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var l,P,g=this;return n=new x(n,o),!g.c||!n.s||n.c&&!n.c[0]?new x(NaN):!n.c||g.c&&!g.c[0]?new x(g):(E==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,E),n=g.minus(l.times(n)),!n.c[0]&&E==1&&(n.s=g.s),n)},r.multipliedBy=r.times=function(n,o){var l,P,g,d,y,m,h,b,f,O,v,A,k,q,X,R=this,D=R.c,j=(n=new x(n,o)).c;if(!D||!j||!D[0]||!j[0])return!R.s||!n.s||D&&!D[0]&&!j||j&&!j[0]&&!D?n.c=n.e=n.s=null:(n.s*=R.s,!D||!j?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=ae(R.e/N)+ae(n.e/N),n.s*=R.s,h=D.length,O=j.length,h<O&&(k=D,D=j,j=k,g=h,h=O,O=g),g=h+O,k=[];g--;k.push(0));for(q=ce,X=be,g=O;--g>=0;){for(l=0,v=j[g]%X,A=j[g]/X|0,y=h,d=g+y;d>g;)b=D[--y]%X,f=D[y]/X|0,m=A*b+f*v,b=v*b+m%X*X+k[d]+l,l=(b/q|0)+(m/X|0)+A*f,k[d--]=b%q;k[d]=l}return l?++P:k.splice(0,1),Se(n,k,P)},r.negated=function(){var n=new x(this);return n.s=-n.s||null,n},r.plus=function(n,o){var l,P=this,g=P.s;if(n=new x(n,o),o=n.s,!g||!o)return new x(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/N,y=n.e/N,m=P.c,h=n.c;if(!d||!y){if(!m||!h)return new x(g/0);if(!m[0]||!h[0])return h[0]?n:new x(m[0]?P:g*0)}if(d=ae(d),y=ae(y),m=m.slice(),g=d-y){for(g>0?(y=d,l=h):(g=-g,l=m),l.reverse();g--;l.push(0));l.reverse()}for(g=m.length,o=h.length,g-o<0&&(l=h,h=m,m=l,o=g),g=0;o;)g=(m[--o]=m[o]+h[o]+g)/ce|0,m[o]=ce===m[o]?0:m[o]%ce;return g&&(m=[g].concat(m),++y),Se(n,m,y)},r.precision=r.sd=function(n,o){var l,P,g,d=this;if(n!=null&&n!==!!n)return G(n,1,W),o==null?o=u:G(o,0,8),_(new x(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*N+1,g=l[g]){for(;g%10==0;g/=10,P--);for(g=l[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return G(n,-gt,gt),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,l,P,g,d=this,y=d.c,m=d.s,h=d.e,b=a+4,f=new x("0.5");if(m!==1||!y||!y[0])return new x(!m||m<0&&(!y||y[0])?NaN:y?d:1/0);if(m=Math.sqrt(+U(d)),m==0||m==1/0?(o=ne(y),(o.length+h)%2==0&&(o+="0"),m=Math.sqrt(+o),h=ae((h+1)/2)-(h<0||h%2),m==1/0?o="5e"+h:(o=m.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new x(o)):l=new x(m+""),l.c[0]){for(h=l.e,m=h+b,m<3&&(m=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ne(g.c).slice(0,m)===(o=ne(l.c)).slice(0,m))if(l.e<h&&--m,o=o.slice(m-3,m+1),o=="9999"||!P&&o=="4999"){if(!P&&(_(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,m+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(_(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return _(l,l.e+a+1,u,n)},r.toExponential=function(n,o){return n!=null&&(G(n,0,W),n++),K(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(G(n,0,W),n=n+this.e+1),K(this,n,o)},r.toFormat=function(n,o,l){var P,g=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=C;else if(typeof l!="object")throw Error(Z+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,y=P.split("."),m=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=y[0],O=y[1],v=g.s<0,A=v?f.slice(1):f,k=A.length;if(h&&(d=m,m=h,h=d,k-=d),m>0&&k>0){for(d=k%m||m,f=A.substr(0,d);d<k;d+=m)f+=b+A.substr(d,m);h>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=O?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?O.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):O):f}return(l.prefix||"")+P+(l.suffix||"")},r.toFraction=function(n){var o,l,P,g,d,y,m,h,b,f,O,v,A=this,k=A.c;if(n!=null&&(m=new x(n),!m.isInteger()&&(m.c||m.s!==1)||m.lt(i)))throw Error(Z+"Argument "+(m.isInteger()?"out of range: ":"not an integer: ")+U(m));if(!k)return new x(A);for(o=new x(i),b=l=new x(i),P=h=new x(i),v=ne(k),d=o.e=v.length-A.e-1,o.c[0]=ht[(y=d%N)<0?N+y:y],n=!n||m.comparedTo(o)>0?d>0?o:b:m,y=B,B=1/0,m=new x(v),h.c[0]=0;f=e(m,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=m.minus(f.times(g=o)),m=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,O=e(b,P,d,u).minus(A).abs().comparedTo(e(h,l,d,u).minus(A).abs())<1?[b,P]:[h,l],B=y,O},r.toNumber=function(){return+U(this)},r.toPrecision=function(n,o){return n!=null&&G(n,1,W),K(this,n,o,2)},r.toString=function(n){var o,l=this,P=l.s,g=l.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=c||g>=S?Je(ne(l.c),g):fe(ne(l.c),g,"0"):n===10&&J?(l=_(new x(l),a+g+1,u),o=fe(ne(l.c),l.e,"0")):(G(n,2,M.length,"Base"),o=t(fe(ne(l.c),g,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return U(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,p!=null&&x.set(p),x}function ae(p){var e=p|0;return p>0||p===e?e:e-1}function ne(p){for(var e,t,s=1,r=p.length,i=p[0]+"";s<r;){for(e=p[s++]+"",t=N-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function xe(p,e){var t,s,r=p.c,i=e.c,a=p.s,u=e.s,c=p.e,S=e.e;if(!a||!u)return null;if(t=r&&!r[0],s=i&&!i[0],t||s)return t?s?0:-u:a;if(a!=u)return a;if(t=a<0,s=c==S,!r||!i)return s?0:!r^t?1:-1;if(!s)return c>S^t?1:-1;for(u=(c=r.length)<(S=i.length)?c:S,a=0;a<u;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return c==S?0:c>S^t?1:-1}function G(p,e,t,s){if(p<e||p>t||p!==oe(p))throw Error(Z+(s||"Argument")+(typeof p=="number"?p<e||p>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(p))}function $e(p){var e=p.c.length-1;return ae(p.e/N)==e&&p.c[e]%2!=0}function Je(p,e){return(p.length>1?p.charAt(0)+"."+p.slice(1):p)+(e<0?"e":"e+")+e}function fe(p,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);p=r+p}else if(s=p.length,++e>s){for(r=t,e-=s;--e;r+=t);p+=r}else e<s&&(p=p.slice(0,e)+"."+p.slice(e));return p}var V=Bt();var jt=12;V.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:jt});var L=I(0),le=I(1),cr=I("Infinity");function Y(p,e){let t=new V(e.toString()),s=new V(10).pow(t);return p.times(s)}function I(p){return new V(p.toString())}var se=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(se||{}),ke=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(ke||{}),vt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(vt||{});import{calculate_in_given_out as Kt,calculate_out_given_in as Qt,calculate_linear_weights as Vt,calculate_pool_trade_fee as Zt,get_spot_price as es}from"@galacticcouncil/math-lbp";var pe=class{static getSpotPrice(e,t,s,r,i){return es(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return Kt(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return Qt(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return Vt(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Zt(e,t,s)}};import{encodeAddress as ts}from"@polkadot/util-crypto";import{stringToU8a as ss}from"@polkadot/util";var Le=18,dt=15,ye="0",Pr=12,br=2034,Me=63,yr=2090,ft=1e3,je=ts(ss("modlomnipool".padEnd(32,"\0")),Me);function It(p,e){let t;return JSON.stringify(p,(s,r)=>(r&&r[e]&&(t=r),r)),t}function xr(p,e,t){let s;return JSON.stringify(p,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";var Ie=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var De=class extends Ie{SUPPORTED_TYPES=["StableSwap","Bond","Token","External"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getToken(e,t,s,r){if(e==ye){let B=this.api.consts.balances.existentialDeposit;return{id:ye,name:this.chainToken,symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:B.toString()}}let{name:i,assetType:a,isSufficient:u,existentialDeposit:c}=t,{symbol:S,decimals:w}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:S,decimals:w,icon:S,type:a.toHuman(),isSufficient:u?u.toHuman():!0,origin:this.parseLocation("parachain",r),existentialDeposit:c.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:u,isSufficient:c,existentialDeposit:S}=t,{symbol:w,decimals:B}=this.getToken(i.toString(),t,s),T=a.toNumber(),E=new Intl.DateTimeFormat("en-GB"),F=[w,"Bond",E.format(T)].join(" ");return{id:e,name:F,symbol:w+"b",decimals:B,icon:w,type:u.toString(),isSufficient:c.toHuman(),existentialDeposit:S.toString()}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:u,assetType:c,isSufficient:S,existentialDeposit:w}=t,T=i.map(C=>C.toString()).map(C=>{let{symbol:M}=this.getToken(C,t,s);return[C,M]}),E=Object.fromEntries(T),F=Object.values(E);return{id:e,name:F.join(", "),symbol:u?.isSome?u.toHuman():a.toHuman(),decimals:18,icon:F.join("/"),type:c.toString(),isSufficient:S.toHuman(),existentialDeposit:w.toString(),meta:E}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=this.parseLocation("generalIndex",r),u=s?.find(c=>c.id===a?.toString());return u?{...i,decimals:u.decimals,name:u.name,symbol:u.symbol,icon:u.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:a}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:a.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,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),u=this.getSupportedAssets(t),c=this.normalizeMetadata(u,a);return u.map(([{args:[S]},w])=>{let B=w.unwrap(),T=s.get(S.toString()),{assetType:E}=B;switch(E.toString()){case"Bond":let F=i.get(S.toString());return this.getBond(S.toString(),B,c,F);case"StableSwap":let C=r.get(S.toString());return this.getShares(S.toString(),B,c,C);case"External":return this.getExternal(S.toString(),B,e,T);default:return this.getToken(S.toString(),B,c,T)}}).filter(S=>this.isValidAsset(S))}isValidAsset(e){return!!e.symbol&&!!e.decimals}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let s=It(t.toJSON(),e);return s&&s[e]}else return}};var Ce=class extends Ie{constructor(e){super(e)}async getBalance(e,t){return t===ye?await this.getSystemBalance(e):await this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeBalance(e,t,s){let r=t.filter(i=>i!==ye).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach(({free:a,reserved:u,frozen:c},S)=>{let w=this.calculateFreeBalance({free:a,feeFrozen:u,frozen:c}),B=r[S][1];s(B,w)})})}async subscribeTokenBalance(e,t,s){let r=t.filter(i=>i!==ye).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach((a,u)=>{let c=this.calculateFreeBalance(a),S=r[u][1];s(S,c)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(ye,this.calculateFreeBalance(s)))}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,a=new V(t),u=new V(s||i),c=new V(r||0),S=u.gt(c)?u:c;return a.minus(S)}};var he=class extends Ce{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async s=>{let r=[await this.subscribePoolChange(s),await this.subscribeTokensPoolBalance(s),await this.subscribeSystemPoolBalance(s)];if(this.hasShareAsset(s)){let i=await this.subscribeSharePoolBalance(s);r.push(i)}return this.subscribeLog(s),r});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,s)=>t.id!==s))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance(je,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(s,r){let i=e.tokens.findIndex(a=>a.id==s);i>=0&&t(e,s)&&(e.tokens[i].balance=r.toString())}}};var Ke=class extends he{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,a])=>this.isActivePool(a.unwrap(),s)).map(async([{args:[i]},a])=>{let u=a.unwrap(),c=i.toString(),S=await this.getPoolDelta(c,u,s.toString());return this.poolsData.set(i.toString(),u),{address:c,type:"Lbp",fee:u.fee.toJSON(),...S,...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 a=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(u=>u.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:a,initialWeight:u,finalWeight:c,repayTarget:S,feeCollector:w}=t,B=pe.calculateLinearWeights(r.toString(),i.toString(),u.toString(),c.toString(),s),[T,E]=a,F=T.toString(),C=I(B),M=E.toString(),J=this.MAX_FINAL_WEIGHT.minus(I(C)),[x,K,re]=await Promise.all([this.isRepayFeeApplied(F,S.toString(),w.toString()),this.getBalance(e,F),this.getBalance(e,M)]);return{repayFeeApply:x,tokens:[{id:F,weight:C,balance:K.toString()},{id:M,weight:J,balance:re.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}}};import{encodeAddress as rs}from"@polkadot/util-crypto";import{stringToU8a as is}from"@polkadot/util";function $(p,e){return p.shiftedBy(-1*e).toString()}function ue(p){return p[0]/p[1]*100}function ee(p){return p[0]/p[1]}function me(p){return[p/ft,ft]}var Qe=class extends he{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=s.map(async([{args:[c]},S])=>{let{hubReserve:w,shares:B,tradable:T}=S.unwrap(),E=await this.getBalance(t,c.toString());return{id:c.toString(),hubReserves:I(w.toString()),shares:I(B.toString()),tradeable:T.bits.toNumber(),balance:E.toString()}}),u=await Promise.all(a);return u.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:u,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=await this.api.query.dynamicFees.assetFee(e),r=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=r.minFee.toNumber()+i.minFee.toNumber(),u=r.maxFee.toNumber()+i.maxFee.toNumber();if(s.isSome){let{assetFee:c,protocolFee:S}=s.unwrap();return{assetFee:me(c.toNumber()),protocolFee:me(S.toNumber()),min:me(a),max:me(u)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:me(a),max:me(u)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let a=e.tokens[i];if(r.isNone)return a;let u=r.unwrap();return this.updateTokenState(a,u)})})}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 me(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return me(t)}getPoolId(){return rs(is("modlomnipool".padEnd(32,"\0")),Me)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var Ve=class extends he{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[a,u]=r.unwrap(),[c,S]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,u.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:c.toString()},{id:u.toString(),balance:S.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{blake2AsHex as hs,encodeAddress as ds}from"@polkadot/util-crypto";import{calculate_in_given_out as ns,calculate_out_given_in as os,calculate_amplification as as,calculate_add_one_asset as ls,calculate_liquidity_out_one_asset as us,calculate_pool_trade_fee as cs,calculate_shares as ps,calculate_shares_for_amount as ms,pool_account_name as gs}from"@galacticcouncil/math-stableswap";var te=class{static getPoolAddress(e){return gs(e)}static calculateAmplification(e,t,s,r,i){return as(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return ns(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return ls(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return ms(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return os(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return us(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return ps(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return cs(e,t,s)}};var Ze=class extends he{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},a])=>{let u=a.unwrap(),c=i.toString(),S=this.getPoolAddress(c),[w,B]=await Promise.all([this.getPoolDelta(c,u,s.toString()),this.getPoolTokens(S,c,u)]);return this.stablePools.set(S,u),{address:S,id:c,type:"Stableswap",fee:me(u.fee.toNumber()),tokens:B,...w,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toNumber(),r=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,r,s.toString());Object.assign(e,i)})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:a,finalBlock:u}=t,c=te.calculateAmplification(r.toString(),i.toString(),a.toString(),u.toString(),s),S=await this.api.query.tokens.totalIssuance(e);return{amplification:c,totalIssuance:S.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async c=>{let[S,w]=await Promise.all([this.api.query.stableswap.assetTradability(t,c.toString()),this.getBalance(e,c.toString())]);return{id:c.toString(),tradeable:S.bits.toNumber(),balance:w.toString()}}),a=await Promise.all(i),u=await this.api.query.omnipool.assets(t);if(u.isSome){let{tradable:c}=u.unwrap(),S=await this.getBalance(je,t);a.push({id:t,tradeable:c.bits.toNumber(),balance:S.toString()})}return a}getPoolAddress(e){let t=Number(e),s=te.getPoolAddress(t);return ds(hs(s),Me)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function Pt(p){return p.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var et=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},At=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ge=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Tt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Ft=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},_t=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var qe=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new De(this.api),this.xykClient=new Ve(this.api),this.omniClient=new Qe(this.api),this.lbpClient=new Ke(this.api),this.stableClient=new Ze(this.api)}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||this.syncRegistry(),e.length==0){let a=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(u=>u.isSupported()).map(u=>u.getPools()))).flat();return this.withMetadata(a)}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 a=t.get(i.id);return{...i,...a}});return{...s,tokens:r}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new et(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):a=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),Pt(i));let u=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:u}}buildSellTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):a=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),Pt(i));let u=()=>a;return{hex:a.toHex(),name:"RouterSell",get:u}}};var He=(p,e)=>p===e?0:p==null?e==null?0:-1:e==null?p==null?0:1:typeof p.compare=="function"?p.compare(e):typeof e.compare=="function"?-e.compare(p):p<e?-1:p>e?1:0;var tt=(p,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(p(t)+e(t))}};var fs=tt(()=>"illegal argument(s)"),Rt=p=>{throw new fs(p)};var Ps=tt(()=>"index out of bounds"),bt=p=>{throw new Ps(p)},st=(p,e,t)=>(p<e||p>=t)&&bt(p);var Et=23283064365386963e-26,rt=class{float(e=1){return this.int()*Et*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Et-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var yt=Math.random,St=class extends rt{int(){return yt()*4294967296>>>0}float(e=1){return yt()*e}norm(e=1){return(yt()-.5)*2*e}},kt=new St;var Lt=p=>p!=null&&typeof p!="function"&&p.length!==void 0;var Mt=Object.getPrototypeOf({}),it="function",Dt="string",Ae=(p,e)=>{let t;if(p===e)return!0;if(p!=null){if(typeof p.equiv===it)return p.equiv(e)}else return p==e;if(e!=null){if(typeof e.equiv===it)return e.equiv(p)}else return p==e;return typeof p===Dt||typeof e===Dt?!1:(t=Object.getPrototypeOf(p),(t==null||t===Mt)&&(t=Object.getPrototypeOf(e),t==null||t===Mt)?xs(p,e):typeof p!==it&&p.length!==void 0&&typeof e!==it&&e.length!==void 0?bs(p,e):p instanceof Set&&e instanceof Set?ys(p,e):p instanceof Map&&e instanceof Map?Ss(p,e):p instanceof Date&&e instanceof Date?p.getTime()===e.getTime():p instanceof RegExp&&e instanceof RegExp?p.toString()===e.toString():p!==p&&e!==e)},bs=(p,e,t=Ae)=>{let s=p.length;if(s===e.length)for(;s-- >0&&t(p[s],e[s]););return s<0},ys=(p,e,t=Ae)=>p.size===e.size&&t([...p.keys()].sort(),[...e.keys()].sort()),Ss=(p,e,t=Ae)=>p.size===e.size&&t([...p].sort(),[...e].sort()),xs=(p,e,t=Ae)=>{if(Object.keys(p).length!==Object.keys(e).length)return!1;for(let s in p)if(!e.hasOwnProperty(s)||!t(p[s],e[s]))return!1;return!0};var Ct=(p,e)=>p!=null&&typeof p[e]=="function";var Gt=p=>Ct(p,"xform")?p.xform():p;var nt=Symbol(),xt=()=>{};var qt=p=>p!=null&&typeof p[Symbol.iterator]=="function";var ot=class{value;constructor(e){this.value=e}deref(){return this.value}};var at=p=>p instanceof ot;var Ht=p=>p instanceof ot?p.deref():p;function*Ut(p,e){let t=Gt(p)([xt,xt,(s,r)=>r])[2];for(let s of e){let r=t(nt,s);if(at(r)){r=Ht(r.deref()),r!==nt&&(yield r);return}r!==nt&&(yield r)}}var zt=(p,e)=>[p[0],p[1],e];function Ue(p,e){return qt(e)?Ut(Ue(p),e):t=>{let s=t[2];return zt(t,(r,i)=>s(r,p(i)))}}var Ne=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Xt("next",this._head)}reverseIterator(){return Xt("prev",this.tail)}clear(){this.release()}compare(e,t=He){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,a=0;for(;s-- >0&&a===0;)a=t(r.value,i.value),r=r.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof Ne||Lt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!Ae(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||He;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!at(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&bt(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*Xt(p,e){for(;e;)yield e.value,e=e[p]}var de=class extends Ne{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new de(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 de}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(st(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(st(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new de,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=a=>({first(){return a.value},next(){return a!==r&&a.next?i(a.next):void 0}});return s?i(s):void 0}shuffle(e,t=kt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&Rt("invalid indices: ${from} / ${to}");let i=new de,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=He){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,a=0;for(let c=0;c<t&&(a++,i=i.next,!!i);c++);let u=t;for(;a>0||u>0&&i;){let c;a===0?(c=i,i=i.next,u--):!i||u===0||e(s.value,i.value)<=0?(c=s,s=s.next,a--):(c=i,i=i.next,u--),this._tail?this._tail.next=c:this._head=c,c.prev=this._tail,this._tail=c}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),st(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new de;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 a of s)this.insertBefore(r,a);else for(let a of s)this.push(a);return i}};var Te=class{map;items;opts;_size;constructor(e,t){let s=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=s.map(),this.items=new de,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ue(e=>[e.k,e],this.items)}keys(){return Ue(e=>e.k,this.items)}values(){return Ue(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new Te(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e);return this._size+=Math.max(0,s-(r?r.value.s:0)),this.ensureSize()&&this.doSetEntry(r,e,t,s),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let s=this.map.get(e);return s?Promise.resolve(this.resetEntry(s)):t().then(r=>this.set(e,r))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,s=this.opts.maxlen;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e&&e(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Ot=class extends qe{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Te(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
-
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Oe=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Oe(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,a,u){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),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 a=I(r.balance),u=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:u,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let u=this.calculateTradeFee(t,s),c=ue(this.repayFeeApply?s.repayFee:s.exchangeFee),S=t.plus(u),w=this.calculateInGivenOut(e,S),B=e.balanceIn.div(this.maxInRatio);return w.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:w,calculatedIn:w,amountOut:t,feePct:c,errors:i}}else{let u=this.calculateInGivenOut(e,t),c=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(c)&&i.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let u=this.calculateOutGivenIn(e,t),c=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(c)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:u,amountOut:u,feePct:0,errors:i}}else{let u=this.calculateOutGivenIn(e,t),c=this.calculateTradeFee(u,s),S=ue(this.repayFeeApply?s.repayFee:s.exchangeFee),w=u.minus(c),B=e.balanceOut.div(this.maxOutRatio);return w.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:u,amountOut:w,feePct:S,errors:i}}}calculateInGivenOut(e,t){let s=pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?L:r}calculateOutGivenIn(e,t){let s=pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?L:r}spotPriceInGivenOut(e){let t=pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),Y(le,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),Y(le,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=pe.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(s)}};import{calculate_in_given_out as Os,calculate_lrna_in_given_out as ws,calculate_out_given_in as Bs,calculate_out_given_lrna_in as vs,calculate_pool_trade_fee as Is,calculate_spot_price as As,calculate_lrna_spot_price as Ns,calculate_shares as Ts,calculate_liquidity_out as Fs,calculate_liquidity_lrna_out as _s,verify_asset_cap as Rs,calculate_liquidity_hub_in as Es,is_sell_allowed as ks,is_buy_allowed as Ls,is_add_liquidity_allowed as Ms,is_remove_liquidity_allowed as Ds}from"@galacticcouncil/math-omnipool";var z=class{static calculateSpotPrice(e,t,s,r){return As(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return Ns(e,t)}static calculateInGivenOut(e,t,s,r,i,a,u,c,S){return Os(e,t,s,r,i,a,u,c,S)}static calculateLrnaInGivenOut(e,t,s,r,i){return ws(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,a,u,c,S){return Bs(e,t,s,r,i,a,u,c,S)}static calculateOutGivenLrnaIn(e,t,s,r,i){return vs(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Is(e,t,s)}static calculateShares(e,t,s,r){return Ts(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,a,u,c){return Fs(e,t,s,r,i,a,u,c)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,u,c){return _s(e,t,s,r,i,a,u,c)}static calculateCapDifference(e,t,s,r){let i=V(t),a=V(e),u=V(r),S=V(s).shiftedBy(-18);if(i.div(u).lt(S)){let B=S.times(u).minus(i).times(a),T=i.times(V(1).minus(S));return B.div(T).toFixed(0)}else return"0"}static verifyAssetCap(e,t,s,r){return Rs(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return Es(e,t,s,r)}static isSellAllowed(e){return ks(e)}static isBuyAllowed(e){return Ls(e)}static isAddLiquidityAllowed(e){return Ms(e)}static isRemoveLiquidityAllowed(e){return Ds(e)}};var we=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new we(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),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 a=I(r.balance),u=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:a,balanceOut:u,tradeableIn:r.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),u=r===L?L:a.div(r).multipliedBy(100).decimalPlaces(2),c=[],S=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!S||!w)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&c.push("MaxOutRatioExceeded");let T=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(T)&&c.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:u.toNumber(),errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),u=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),c=[],S=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!S||!w)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&c.push("MaxInRatioExceeded");let T=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(T)&&c.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:u.toNumber(),errors:c}}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?ee(s.assetFee).toString():L.toString(),s?ee(s.protocolFee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateLrnaInGivenOut(e,t,s){let r=z.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():L.toString()),i=I(r);return i.isNegative()?L: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?ee(s.assetFee).toString():L.toString(),s?ee(s.protocolFee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateOutGivenLrnaIn(e,t,s){let r=z.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():L.toString()),i=I(r);return i.isNegative()?L: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*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=z.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Le-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*(Le-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=z.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}};var Be=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Be(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,i,a,u,c,S){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=a,this.id=u,this.fee=c,this.totalIssuance=S}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),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 a=I(r.balance),u=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:u,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?dt:r.tradeable,tradeableOut:this.id===t?dt:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=ue(s.fee),u=[],c=z.isSellAllowed(e.tradeableIn),S=z.isBuyAllowed(e.tradeableOut);return(!c||!S)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=ue(s.fee),u=[],c=z.isSellAllowed(e.tradeableIn),S=z.isBuyAllowed(e.tradeableOut);return(!c||!S)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:u}}calculateIn(e,t,s){let r=te.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ee(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateAddOneAsset(e,t,s){let r=te.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?ee(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateSharesForAmount(e,t,s){let r=te.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?ee(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L: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(le,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=te.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ee(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateWithdrawOneAsset(e,t,s){let r=te.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?ee(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateShares(e,t,s){let r=te.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?ee(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L: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(le,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=te.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])}};import{calculate_in_given_out as Cs,calculate_out_given_in as Gs,calculate_pool_trade_fee as qs,get_spot_price as Hs,calculate_liquidity_in as Us,calculate_shares as zs,calculate_liquidity_out_asset_a as Xs,calculate_liquidity_out_asset_b as Ws}from"@galacticcouncil/math-xyk";var Pe=class{static getSpotPrice(e,t,s){return Hs(e,t,s)}static calculateInGivenOut(e,t,s){return Cs(e,t,s)}static calculateOutGivenIn(e,t,s){return Gs(e,t,s)}static calculatePoolTradeFee(e,t,s){return qs(e,t,s)}static calculateLiquidityIn(e,t,s){return Us(e,t,s)}static calculateShares(e,t,s){return zs(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return Xs(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Ws(e,t,s,r)}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),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 a=I(r.balance),u=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=ue(s.exchangeFee),u=r.plus(i),c=[];t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let S=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(S)&&c.push("MaxOutRatioExceeded");let w=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(w)&&c.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:r,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=ue(s.exchangeFee),u=r.minus(i),c=[];t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let S=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(S)&&c.push("MaxInRatioExceeded");let w=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(w)&&c.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:u,feePct:a,errors:c}}calculateInGivenOut(e,t){let s=Pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?L:r}calculateOutGivenIn(e,t){let s=Pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?L:r}spotPriceInGivenOut(e){let t=Pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),Y(le,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=Pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),Y(le,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=Pe.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(s)}};var ze=class{static get(e){switch(e.type){case"Xyk":return ve.fromPool(e);case"Omnipool":return we.fromPool(e);case"Lbp":return Oe.fromPool(e);case"Stableswap":return Be.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Fe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ee,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),a=this.getPaths(e,null,r,t).map(u=>u[u.length-1].assetOut);return this.toAssets([...new Set(a)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,origin:r.origin,meta:r.meta}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(u=>this.validPath(u,s)).map(u=>this.toHops(u,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,ze.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let a=t.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function bl(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Xe(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Wt(p,e){return le.minus(e.div(p)).multipliedBy(100).decimalPlaces(2)}function Yt(p,e){return e.div(p).minus(le).multipliedBy(100).decimalPlaces(2)}var lt=class extends Fe{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,a=r[r.length-1].amountOut;return i.isGreaterThan(a)?-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,a)=>i+a),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[s,r]}}getPoolFeeRange(e){let t=e.min?ue(e.min):void 0,s=e.max?ue(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),u=super.getPaths(e,t,a,i);if(u.length===0)throw new Ge(e,t);let c;if(r)c=await this.toSellSwaps(s,r,a);else{let _=u.map(async n=>await this.toSellSwaps(s,n,a)),U=await Promise.all(_);c=this.findBestSellRoute(U)}let S=c[0],w=c[c.length-1],B=this.isDirectTrade(c),T=c.map(_=>_.spotPrice.shiftedBy(-1*_.assetOutDecimals)).reduce((_,U)=>_.multipliedBy(U)),E=Y(T,w.assetOutDecimals),F=B?w.calculatedOut:this.calculateDelta0Y(S.amountIn,c,a),C=w.amountOut,M=B?w.tradeFeePct:Wt(F,C).toNumber(),J=F.minus(C),x=this.getRouteFeeRange(c),K=S.amountIn.shiftedBy(-1*S.assetInDecimals).multipliedBy(E),re=Xe(F,K),Se=_=>this.poolService.buildSellTx(e,t,S.amountIn,_,c.map(U=>U));return{type:"Sell",amountIn:S.amountIn,amountOut:w.amountOut,spotPrice:E,tradeFee:J,tradeFeePct:M,tradeFeeRange:x,priceImpactPct:re.toNumber(),swaps:c,toTx:Se,toHuman(){return{type:"Sell",amountIn:$(S.amountIn,S.assetInDecimals),amountOut:$(w.amountOut,w.assetOutDecimals),spotPrice:$(E,w.assetOutDecimals),tradeFee:$(J,w.assetOutDecimals),tradeFeePct:M,tradeFeeRange:x,priceImpactPct:re.toNumber(),swaps:c.map(_=>_.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],u=s.get(a.poolAddress);if(u==null)throw new Error("Pool does not exit");let c=u.parsePair(a.assetIn,a.assetOut),S;i>0?S=r[i-1]:S=e;let w=u.calculateOutGivenIn(c,S);r.push(w)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],u=s.get(a.poolAddress);if(u==null)throw new Error("Pool does not exit");let c=u.parsePair(a.assetIn,a.assetOut),S;i>0?S=r[i-1].amountOut:S=Y(I(e),c.decimalsIn).decimalPlaces(0,1);let w=await this.poolService.getPoolFees(c.assetOut,u),{amountOut:B,calculatedOut:T,feePct:E,errors:F}=u.validateAndSell(c,S,w),C=this.getPoolFeeRange(w),M=u.spotPriceOutGivenIn(c),J=S.shiftedBy(-1*c.decimalsIn).multipliedBy(M),x=Xe(T,J);r.push({...a,assetInDecimals:c.decimalsIn,assetOutDecimals:c.decimalsOut,amountIn:S,calculatedOut:T,amountOut:B,spotPrice:M,tradeFeePct:E,tradeFeeRange:C,priceImpactPct:x.toNumber(),errors:F,toHuman(){return{...a,amountIn:$(S,c.decimalsIn),calculatedOut:$(T,c.decimalsOut),amountOut:$(B,c.decimalsOut),spotPrice:$(M,c.decimalsOut),tradeFeePct:E,tradeFeeRange:C,priceImpactPct:x.toNumber(),errors:F}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(x=>x.tokens.find(K=>K.id===e)).filter(x=>!!x).sort((x,K)=>Number(K.balance)-Number(x.balance)),{balance:u,decimals:c}=a[0],w=I(u).shiftedBy(-1*c).div(100).multipliedBy(.1),B=i.map(async x=>await this.toSellSwaps(w,x,r)),T=await Promise.all(B),E=this.findBestSellRoute(T),F=await this.toSellSwaps("1",E,r),C=F.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,K)=>x.multipliedBy(K)),M=F[F.length-1].assetOutDecimals;return{amount:Y(C,M),decimals:M}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,a=r[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),u=super.getPaths(e,t,a,i);if(u.length===0)throw new Ge(e,t);let c;if(r)c=await this.toBuySwaps(s,r,a);else{let _=u.map(async n=>await this.toBuySwaps(s,n,a)),U=await Promise.all(_);c=this.findBestBuyRoute(U)}let S=c[c.length-1],w=c[0],B=this.isDirectTrade(c),T=c.map(_=>_.spotPrice.shiftedBy(-1*_.assetInDecimals)).reduce((_,U)=>_.multipliedBy(U)),E=Y(T,w.assetInDecimals),F=B?w.calculatedIn:this.calculateDelta0X(S.amountOut,c,a),C=w.amountIn,M=B?w.tradeFeePct:Yt(F,C).toNumber(),J=C.minus(F),x=this.getRouteFeeRange(c),K=S.amountOut.shiftedBy(-1*S.assetOutDecimals).multipliedBy(E),re;F.isZero()?re=-100:re=Xe(K,F).toNumber();let Se=_=>this.poolService.buildBuyTx(e,t,S.amountOut,_,c.map(U=>U));return{type:"Buy",amountOut:S.amountOut,amountIn:w.amountIn,spotPrice:E,tradeFee:J,tradeFeePct:M,tradeFeeRange:x,priceImpactPct:re,swaps:c,toTx:Se,toHuman(){return{type:"Buy",amountOut:$(S.amountOut,S.assetOutDecimals),amountIn:$(w.amountIn,w.assetInDecimals),spotPrice:$(E,w.assetInDecimals),tradeFee:$(J,w.assetInDecimals),tradeFeePct:M,tradeFeeRange:x,priceImpactPct:re,swaps:c.map(_=>_.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],u=s.get(a.poolAddress);if(u==null)throw new Error("Pool does not exit");let c=u.parsePair(a.assetIn,a.assetOut),S;i==t.length-1?S=e:S=r[0];let w=u.calculateInGivenOut(c,S);r.unshift(w)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],u=s.get(a.poolAddress);if(u==null)throw new Error("Pool does not exit");let c=u.parsePair(a.assetIn,a.assetOut),S;i==t.length-1?S=Y(I(e),c.decimalsOut).decimalPlaces(0,1):S=r[0].amountIn;let w=await this.poolService.getPoolFees(c.assetOut,u),{amountIn:B,calculatedIn:T,feePct:E,errors:F}=u.validateAndBuy(c,S,w),C=this.getPoolFeeRange(w),M=u.spotPriceInGivenOut(c),J=S.shiftedBy(-1*c.decimalsOut).multipliedBy(M),x;T.isZero()?x=-100:x=Xe(J,T).toNumber(),r.unshift({...a,assetInDecimals:c.decimalsIn,assetOutDecimals:c.decimalsOut,amountOut:S,calculatedIn:T,amountIn:B,spotPrice:M,tradeFeePct:E,tradeFeeRange:C,priceImpactPct:x,errors:F,toHuman(){return{...a,amountOut:$(S,c.decimalsOut),calculatedIn:$(T,c.decimalsIn),amountIn:$(B,c.decimalsIn),spotPrice:$(M,c.decimalsIn),tradeFeePct:E,tradeFeeRange:C,priceImpactPct:x,errors:F}}})}return r}};export{De as AssetClient,Nt as AssetNotFound,yr as BASILISK_PARACHAIN_ID,Ce as BalanceClient,V as BigNumber,Ot as CachingPoolService,jt as DECIMAL_PLACES,ft as DENOMINATOR,je as HYDRADX_OMNIPOOL_ADDRESS,br as HYDRADX_PARACHAIN_ID,Me as HYDRADX_SS58_PREFIX,cr as INFINITY,pe as LbpMath,Oe as LbpPool,le as ONE,z as OmniMath,we as OmniPool,At as PoolConfigNotFound,ke as PoolError,ze as PoolFactory,et as PoolNotFound,qe as PoolService,se as PoolType,_t as ProviderConfigNotFound,Le as RUNTIME_DECIMALS,Ge as RouteNotFound,Fe as Router,Pr as SYSTEM_ASSET_DECIMALS,ye as SYSTEM_ASSET_ID,te as StableMath,Be as StableSwap,Tt as StorageConfigNotFound,Ft as SubscriptionNotSupported,dt as TRADEABLE_DEFAULT,lt as TradeRouter,vt as TradeType,Pe as XykMath,ve as XykPool,L as ZERO,I as bnum,Pt as buildRoute,Yt as calculateBuyFee,bl as calculateDiffToAvg,Xe as calculateDiffToRef,Wt as calculateSellFee,It as findNestedKey,xr as findNestedObj,Y as scale};
|
|
1
|
+
var We=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 Zt=5,Re=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new We,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>Zt)return s;let u=c[c.length-1];(r===null||u[0]===r)&&s.push(c),e.get(u[0])?.forEach(O=>{if(this.isNotVisited(O,c)){let B=[...c];B.push(O),i.enqueue(B)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,a]of t){let c=parseInt(i),u=parseInt(a);r.get(c)?.push([u,s])}return r}};function mt(m){let e={};for(let t of m){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let a=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(a)}}}return e}var Ee=class{getProposals(e,t,r){let s=mt(r),i=Object.keys(s),a=i.map(O=>s[O]).flat(),c=new Re,u=c.buildAndPopulateGraph(i,a),y=c.findPaths(u,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let a=r[i],c=r[i+1];if(c==null)break;s.push(this.toEdge(a,c))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var Kt=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,pt=Math.ceil,oe=Math.floor,V="[BigNumber Error] ",Bt=V+"Number primitive has more than 15 significant digits: ",ce=1e14,N=14,gt=9007199254740991,ht=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],ye=1e7,$=1e9;function vt(m){var e,t,r,s=w.prototype={constructor:w,toString:null,valueOf:null},i=new w(1),a=20,c=4,u=-7,y=21,O=-1e7,B=1e7,F=!1,_=1,T=0,D={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},L="0123456789abcdefghijklmnopqrstuvwxyz",Y=!0;function w(n,o){var l,P,g,d,S,p,h,b,f=this;if(!(f instanceof w))return new w(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<O?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(!Kt.test(b=String(n)))return r(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,L.length,"Base"),o==10&&Y)return f=new w(n),R(f,a+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return r(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,w.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Bt+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=L.slice(0,o),d=S=0,h=b.length;S<h;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return r(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(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&w.DEBUG&&h>15&&(n>gt||n!==oe(n)))throw Error(Bt+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<O)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%N,d<0&&(S+=N),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=N;S<h;)f.c.push(+b.slice(S,S+=N));S=N-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}w.clone=vt,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],q(l,0,$,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],q(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(q(l[0],-$,0,o),q(l[1],0,$,o),u=l[0],y=l[1]):(q(l,-$,$,o),u=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)q(l[0],-$,-1,o),q(l[1],1,$,o),O=l[0],B=l[1];else if(q(l,-$,$,o),l)O=-(B=l<0?-l:l);else throw Error(V+o+" cannot be zero: "+l);if(n.hasOwnProperty(o="CRYPTO"))if(l=n[o],l===!!l)if(l)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))F=l;else throw F=!l,Error(V+"crypto unavailable");else F=l;else throw Error(V+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],q(l,0,9,o),_=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],q(l,0,$,o),T=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")D=l;else throw Error(V+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))Y=l.slice(0,10)=="0123456789",L=l;else throw Error(V+o+" invalid: "+l)}else throw Error(V+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[u,y],RANGE:[O,B],CRYPTO:F,MODULO_MODE:_,POW_PRECISION:T,FORMAT:D,ALPHABET:L}},w.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!w.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-$&&g<=$&&g===oe(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%N,o<1&&(o+=N),String(P[0]).length==o){for(o=0;o<P.length;o++)if(l=P[o],l<0||l>=ce||l!==oe(l))break e;if(l!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(V+"Invalid BigNumber: "+n)},w.maximum=w.max=function(){return re(arguments,-1)},w.minimum=w.min=function(){return re(arguments,1)},w.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return oe(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,S,p,h=0,b=[],f=new w(i);if(l==null?l=a:q(l,0,$),S=pt(l/N),F)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));h<S;)p=P[h]*131072+(P[h+1]>>>11),p>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(p%1e14),h+=2);h=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);h<S;)p=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],p>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(p%1e14),h+=7);h=S/7}else throw F=!1,Error(V+"crypto unavailable");if(!F)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],l%=N,S&&l&&(p=ht[N-l],b[h]=oe(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=N);for(h=1,p=b[0];p>=10;p/=10,h++);h<N&&(d-=N-h)}return f.e=d,f.c=b,f}}(),w.sum=function(){for(var n=1,o=arguments,l=new w(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var S,p=[0],h,b=0,f=l.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(l.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(l,P,g,d,S){var p,h,b,f,x,v,A,M,H=l.indexOf("."),W=a,k=c;for(H>=0&&(f=T,T=0,l=l.replace(".",""),M=new w(P),v=M.pow(l.length-H),T=f,M.c=o(Pe(ne(v.c),v.e,"0"),10,g,n),M.e=M.c.length),A=o(l,P,g,S?(p=L,n):(p=n,L)),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,M,W,k,g),A=v.c,x=v.r,b=v.e),h=b+W+1,H=A[h],f=g/2,x=x||h<0||A[h+1]!=null,x=k<4?(H!=null||x)&&(k==0||k==(v.s<0?3:2)):H>f||H==f&&(k==4||x||k==6&&A[h-1]&1||k==(v.s<0?8:7)),h<1||!A[0])l=x?Pe(p.charAt(1),-W,p.charAt(0)):p.charAt(0);else{if(A.length=h,x)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(H=0,l="";H<=f;l+=p.charAt(A[H++]));l=Pe(l,b,p.charAt(0))}return l}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,x=P.length,v=g%ye,A=g/ye|0;for(P=P.slice();x--;)h=P[x]%ye,b=P[x]/ye|0,S=A*h+b*v,p=v*h+S%ye*ye+f,f=(p/d|0)+(S/ye|0)+A*b,P[x]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function l(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,x,v,A,M,H,W,k,C,K,Ye,ut,ct,ge,_e,ie=P.s==g.s?1:-1,Q=P.c,U=g.c;if(!Q||!Q[0]||!U||!U[0])return new w(!P.s||!g.s||(Q?U&&Q[0]==U[0]:!U)?NaN:Q&&Q[0]==0||!U?ie*0:ie/0);for(H=new w(ie),W=H.c=[],b=P.e-g.e,ie=d+b+1,p||(p=ce,b=ae(P.e/N)-ae(g.e/N),ie=ie/N|0),f=0;U[f]==(Q[f]||0);f++);if(U[f]>(Q[f]||0)&&b--,ie<0)W.push(1),x=!0;else{for(ut=Q.length,ge=U.length,f=0,ie+=2,v=oe(p/(U[0]+1)),v>1&&(U=n(U,v,p),Q=n(Q,v,p),ge=U.length,ut=Q.length),Ye=ge,k=Q.slice(0,ge),C=k.length;C<ge;k[C++]=0);_e=U.slice(),_e=[0].concat(_e),ct=U[0],U[1]>=p/2&&ct++;do{if(v=0,h=o(U,k,ge,C),h<0){if(K=k[0],ge!=C&&(K=K*p+(k[1]||0)),v=oe(K/ct),v>1)for(v>=p&&(v=p-1),A=n(U,v,p),M=A.length,C=k.length;o(A,k,M,C)==1;)v--,l(A,ge<M?_e:U,M,p),M=A.length,h=1;else v==0&&(h=v=1),A=U.slice(),M=A.length;if(M<C&&(A=[0].concat(A)),l(k,A,C,p),C=k.length,h==-1)for(;o(U,k,ge,C)<1;)v++,l(k,ge<C?_e:U,C,p),C=k.length}else h===0&&(v++,k=[0]);W[f++]=v,k[0]?k[C++]=Q[Ye]||0:(k=[Q[Ye]],C=1)}while((Ye++<ut||k[0]!=null)&&ie--);x=k[0]!=null,W[0]||W.splice(0,1)}if(p==ce){for(f=1,ie=W[0];ie>=10;ie/=10,f++);R(H,d+(H.e=f+b*N-1)+1,S,x)}else H.e=b,H.r=+x;return H}}();function j(n,o,l,P){var g,d,S,p,h;if(l==null?l=c:q(l,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ne(n.c),h=P==1||P==2&&(S<=u||S>=y)?je(h,S):Pe(h,S,"0");else if(n=R(new w(n),o,l),d=n.e,h=ne(n.c),p=h.length,P==1||P==2&&(o<=d||d<=u)){for(;p<o;h+="0",p++);h=je(h,d)}else if(o-=S,h=Pe(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function re(n,o){for(var l,P,g=1,d=new w(n[0]);g<n.length;g++)P=new w(n[g]),(!P.s||(l=xe(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function fe(n,o,l){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(l=P+l*N-1)>B?n.c=n.e=null:l<O?n.c=[n.e=0]:(n.e=l,n.c=o),n}r=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,h){var b,f=p?S:S.replace(g,"");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,!h||h==b?v:x}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new w(f,b);if(w.DEBUG)throw Error(V+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function R(n,o,l,P){var g,d,S,p,h,b,f,x=n.c,v=ht;if(x){e:{for(g=1,p=x[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=N,S=o,h=x[b=0],f=oe(h/v[g-S-1]%10);else if(b=pt((d+1)/N),b>=x.length)if(P){for(;x.length<=b;x.push(0));h=f=0,g=1,d%=N,S=d-N+1}else break e;else{for(h=p=x[b],g=1;p>=10;p/=10,g++);d%=N,S=d-N+g,f=S<0?0:oe(h/v[g-S-1]%10)}if(P=P||o<0||x[b+1]!=null||(S<0?h:h%v[g-S-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?S>0?h/v[g-S]:0:x[b-1])%10&1||l==(n.s<0?8:7)),o<1||!x[0])return x.length=0,P?(o-=n.e+1,x[0]=v[(N-o%N)%N],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[N-d],x[b]=S>0?oe(h/v[g-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]==ce&&(x[0]=1));break}else{if(x[b]+=p,x[b]!=ce)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<O&&(n.c=[n.e=0])}return n}function z(n){var o,l=n.e;return l===null?n.toString():(o=ne(n.c),o=l<=u||l>=y?je(o,l):Pe(o,l,"0"),n.s<0?"-"+o:o)}return s.absoluteValue=s.abs=function(){var n=new w(this);return n.s<0&&(n.s=1),n},s.comparedTo=function(n,o){return xe(this,new w(n,o))},s.decimalPlaces=s.dp=function(n,o){var l,P,g,d=this;if(n!=null)return q(n,0,$),o==null?o=c:q(o,0,8),R(new w(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-ae(this.e/N))*N,g=l[g])for(;g%10==0;g/=10,P--);return P<0&&(P=0),P},s.dividedBy=s.div=function(n,o){return e(this,new w(n,o),a,c)},s.dividedToIntegerBy=s.idiv=function(n,o){return e(this,new w(n,o),0,1)},s.exponentiatedBy=s.pow=function(n,o){var l,P,g,d,S,p,h,b,f,x=this;if(n=new w(n),n.c&&!n.isInteger())throw Error(V+"Exponent not an integer: "+z(n));if(o!=null&&(o=new w(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 w(Math.pow(+z(x),p?n.s*(2-$e(n)):+z(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new w(NaN);P=!h&&x.isInteger()&&o.isInteger(),P&&(x=x.mod(o))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||p&&x.c[1]>=24e7:x.c[0]<8e13||p&&x.c[0]<=9999975e7)))return d=x.s<0&&$e(n)?-0:0,x.e>-1&&(d=1/d),new w(h?1/d:d);T&&(d=pt(T/N+2))}for(p?(l=new w(.5),h&&(n.s=1),b=$e(n)):(g=Math.abs(+z(n)),b=g%2),f=new w(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(g){if(g=oe(g/2),g===0)break;b=g%2}else if(n=n.times(l),R(n,n.e+1,1),n.e>14)b=$e(n);else{if(g=+z(n),g===0)break;b=g%2}x=x.times(x),d?x.c&&x.c.length>d&&(x.c.length=d):P&&(x=x.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?R(f,T,c,S):f)},s.integerValue=function(n){var o=new w(this);return n==null?n=c:q(n,0,8),R(o,o.e+1,n)},s.isEqualTo=s.eq=function(n,o){return xe(this,new w(n,o))===0},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(n,o){return xe(this,new w(n,o))>0},s.isGreaterThanOrEqualTo=s.gte=function(n,o){return(o=xe(this,new w(n,o)))===1||o===0},s.isInteger=function(){return!!this.c&&ae(this.e/N)>this.c.length-2},s.isLessThan=s.lt=function(n,o){return xe(this,new w(n,o))<0},s.isLessThanOrEqualTo=s.lte=function(n,o){return(o=xe(this,new w(n,o)))===-1||o===0},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&this.c[0]==0},s.minus=function(n,o){var l,P,g,d,S=this,p=S.s;if(n=new w(n,o),o=n.s,!p||!o)return new w(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/N,b=n.e/N,f=S.c,x=n.c;if(!h||!b){if(!f||!x)return f?(n.s=-o,n):new w(x?S:NaN);if(!f[0]||!x[0])return x[0]?(n.s=-o,n):new w(f[0]?S:c==3?-0:0)}if(h=ae(h),b=ae(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=x),g.reverse(),o=p;o--;g.push(0));g.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&&(g=f,f=x,x=g,n.s=-n.s),o=(P=x.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=ce-1;P>p;){if(f[--P]<x[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=ce}f[P]-=x[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?fe(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},s.modulo=s.mod=function(n,o){var l,P,g=this;return n=new w(n,o),!g.c||!n.s||n.c&&!n.c[0]?new w(NaN):!n.c||g.c&&!g.c[0]?new w(g):(_==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,_),n=g.minus(l.times(n)),!n.c[0]&&_==1&&(n.s=g.s),n)},s.multipliedBy=s.times=function(n,o){var l,P,g,d,S,p,h,b,f,x,v,A,M,H,W,k=this,C=k.c,K=(n=new w(n,o)).c;if(!C||!K||!C[0]||!K[0])return!k.s||!n.s||C&&!C[0]&&!K||K&&!K[0]&&!C?n.c=n.e=n.s=null:(n.s*=k.s,!C||!K?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=ae(k.e/N)+ae(n.e/N),n.s*=k.s,h=C.length,x=K.length,h<x&&(M=C,C=K,K=M,g=h,h=x,x=g),g=h+x,M=[];g--;M.push(0));for(H=ce,W=ye,g=x;--g>=0;){for(l=0,v=K[g]%W,A=K[g]/W|0,S=h,d=g+S;d>g;)b=C[--S]%W,f=C[S]/W|0,p=A*b+f*v,b=v*b+p%W*W+M[d]+l,l=(b/H|0)+(p/W|0)+A*f,M[d--]=b%H;M[d]=l}return l?++P:M.splice(0,1),fe(n,M,P)},s.negated=function(){var n=new w(this);return n.s=-n.s||null,n},s.plus=function(n,o){var l,P=this,g=P.s;if(n=new w(n,o),o=n.s,!g||!o)return new w(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/N,S=n.e/N,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new w(g/0);if(!p[0]||!h[0])return h[0]?n:new w(p[0]?P:g*0)}if(d=ae(d),S=ae(S),p=p.slice(),g=d-S){for(g>0?(S=d,l=h):(g=-g,l=p),l.reverse();g--;l.push(0));l.reverse()}for(g=p.length,o=h.length,g-o<0&&(l=h,h=p,p=l,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/ce|0,p[o]=ce===p[o]?0:p[o]%ce;return g&&(p=[g].concat(p),++S),fe(n,p,S)},s.precision=s.sd=function(n,o){var l,P,g,d=this;if(n!=null&&n!==!!n)return q(n,1,$),o==null?o=c:q(o,0,8),R(new w(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*N+1,g=l[g]){for(;g%10==0;g/=10,P--);for(g=l[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},s.shiftedBy=function(n){return q(n,-gt,gt),this.times("1e"+n)},s.squareRoot=s.sqrt=function(){var n,o,l,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new w("0.5");if(p!==1||!S||!S[0])return new w(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+z(d)),p==0||p==1/0?(o=ne(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=ae((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new w(o)):l=new w(p+""),l.c[0]){for(h=l.e,p=h+b,p<3&&(p=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ne(g.c).slice(0,p)===(o=ne(l.c)).slice(0,p))if(l.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(R(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(R(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return R(l,l.e+a+1,c,n)},s.toExponential=function(n,o){return n!=null&&(q(n,0,$),n++),j(this,n,o,1)},s.toFixed=function(n,o){return n!=null&&(q(n,0,$),n=n+this.e+1),j(this,n,o)},s.toFormat=function(n,o,l){var P,g=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=D;else if(typeof l!="object")throw Error(V+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],x=S[1],v=g.s<0,A=v?f.slice(1):f,M=A.length;if(h&&(d=p,p=h,h=d,M-=d),p>0&&M>0){for(d=M%p||p,f=A.substr(0,d);d<M;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=x?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?x.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):x):f}return(l.prefix||"")+P+(l.suffix||"")},s.toFraction=function(n){var o,l,P,g,d,S,p,h,b,f,x,v,A=this,M=A.c;if(n!=null&&(p=new w(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(V+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+z(p));if(!M)return new w(A);for(o=new w(i),b=l=new w(i),P=h=new w(i),v=ne(M),d=o.e=v.length-A.e-1,o.c[0]=ht[(S=d%N)<0?N+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new w(v),h.c[0]=0;f=e(p,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,x=e(b,P,d,c).minus(A).abs().comparedTo(e(h,l,d,c).minus(A).abs())<1?[b,P]:[h,l],B=S,x},s.toNumber=function(){return+z(this)},s.toPrecision=function(n,o){return n!=null&&q(n,1,$),j(this,n,o,2)},s.toString=function(n){var o,l=this,P=l.s,g=l.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=u||g>=y?je(ne(l.c),g):Pe(ne(l.c),g,"0"):n===10&&Y?(l=R(new w(l),a+g+1,c),o=Pe(ne(l.c),l.e,"0")):(q(n,2,L.length,"Base"),o=t(Pe(ne(l.c),g,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},s.valueOf=s.toJSON=function(){return z(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,m!=null&&w.set(m),w}function ae(m){var e=m|0;return m>0||m===e?e:e-1}function ne(m){for(var e,t,r=1,s=m.length,i=m[0]+"";r<s;){for(e=m[r++]+"",t=N-e.length;t--;e="0"+e);i+=e}for(s=i.length;i.charCodeAt(--s)===48;);return i.slice(0,s+1||1)}function xe(m,e){var t,r,s=m.c,i=e.c,a=m.s,c=e.s,u=m.e,y=e.e;if(!a||!c)return null;if(t=s&&!s[0],r=i&&!i[0],t||r)return t?r?0:-c:a;if(a!=c)return a;if(t=a<0,r=u==y,!s||!i)return r?0:!s^t?1:-1;if(!r)return u>y^t?1:-1;for(c=(u=s.length)<(y=i.length)?u:y,a=0;a<c;a++)if(s[a]!=i[a])return s[a]>i[a]^t?1:-1;return u==y?0:u>y^t?1:-1}function q(m,e,t,r){if(m<e||m>t||m!==oe(m))throw Error(V+(r||"Argument")+(typeof m=="number"?m<e||m>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(m))}function $e(m){var e=m.c.length-1;return ae(m.e/N)==e&&m.c[e]%2!=0}function je(m,e){return(m.length>1?m.charAt(0)+"."+m.slice(1):m)+(e<0?"e":"e+")+e}function Pe(m,e,t){var r,s;if(e<0){for(s=t+".";++e;s+=t);m=s+m}else if(r=m.length,++e>r){for(s=t,e-=r;--e;s+=t);m+=s}else e<r&&(m=m.slice(0,e)+"."+m.slice(e));return m}var G=vt();var Qt=12;G.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Qt});var E=I(0),le=I(1),ds=I("Infinity");function J(m,e){let t=new G(e.toString()),r=new G(10).pow(t);return m.times(r)}function I(m){return new G(m.toString())}var se=(s=>(s.XYK="Xyk",s.LBP="Lbp",s.Stable="Stableswap",s.Omni="Omnipool",s))(se||{}),ke=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(ke||{}),It=(t=>(t.Buy="Buy",t.Sell="Sell",t))(It||{});import{calculate_in_given_out as Vt,calculate_out_given_in as er,calculate_linear_weights as tr,calculate_pool_trade_fee as rr,get_spot_price as sr}from"@galacticcouncil/math-lbp";var me=class{static getSpotPrice(e,t,r,s,i){return sr(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return Vt(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return er(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return tr(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return rr(e,t,r)}};import{encodeAddress as ir}from"@polkadot/util-crypto";import{stringToU8a as nr}from"@polkadot/util";var Le=18,dt=15,Se="0",xs=12,Os=2034,Me=63,Bs=2090,ft=1e3,Je=ir(nr("modlomnipool".padEnd(32,"\0")),Me);function At(m,e){let t;return JSON.stringify(m,(r,s)=>(s&&s[e]&&(t=s),s)),t}function Is(m,e,t){let r;return JSON.stringify(m,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";var we=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var De=class extends we{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]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.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]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getToken(e,t,r,s){if(e==Se){let B=this.api.consts.balances.existentialDeposit;return{id:Se,name:this.chainToken,symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:B.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:u}=t,{symbol:y,decimals:O}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:y,decimals:O,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:this.parseLocation("parachain",s),existentialDeposit:u.toString()}}getBond(e,t,r,s){let[i,a]=s,{assetType:c,isSufficient:u,existentialDeposit:y}=t,{symbol:O,decimals:B}=this.getToken(i.toString(),t,r),F=a.toNumber(),_=new Intl.DateTimeFormat("en-GB"),T=[O,"Bond",_.format(F)].join(" ");return{id:e,name:T,symbol:O+"b",decimals:B,icon:O,type:c.toString(),isSufficient:u.toHuman(),existentialDeposit:y.toString()}}getShares(e,t,r,s){let{assets:i}=s,{name:a,symbol:c,assetType:u,isSufficient:y,existentialDeposit:O}=t,F=i.map(D=>D.toString()).map(D=>{let{symbol:L}=this.getToken(D,t,r);return[D,L]}),_=Object.fromEntries(F),T=Object.values(_);return{id:e,name:T.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:T.join("/"),type:u.toString(),isSufficient:y.toHuman(),existentialDeposit:O.toString(),meta:_}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),a=r?.find(c=>c.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:a}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e){let[t,r,s,i,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),c=this.getSupportedAssets(t),u=this.normalizeMetadata(c,a);return c.map(([{args:[y]},O])=>{let B=O.unwrap(),F=r.get(y.toString()),{assetType:_}=B;switch(_.toString()){case"Bond":let T=i.get(y.toString());return this.getBond(y.toString(),B,u,T);case"StableSwap":let D=s.get(y.toString());return this.getShares(y.toString(),B,u,D);case"External":return this.getExternal(y.toString(),B,e,F);default:return this.getToken(y.toString(),B,u,F)}}).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 r=At(t.toJSON(),e);return r&&r[e]}else return}};var Ce=class extends we{constructor(e){super(e)}async getBalance(e,t){return t===Se?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:r,reserved:s,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:i})}async subscribeBalance(e,t,r){let s=t.filter(i=>i!==Se).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach(({free:a,reserved:c,frozen:u},y)=>{let O=this.calculateFreeBalance({free:a,feeFrozen:c,frozen:u}),B=s[y][1];r(B,O)})})}async subscribeTokenBalance(e,t,r){let s=t.filter(i=>i!==Se).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach((a,c)=>{let u=this.calculateFreeBalance(a),y=s[c][1];r(y,u)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(Se,this.calculateFreeBalance(r)))}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:i}=e,a=new G(t),c=new G(r||i),u=new G(s||0),y=c.gt(u)?c:u;return a.minus(y)}};import{isAddress as Nt}from"@polkadot/util-crypto";import{fixed_from_rational as Ft}from"@galacticcouncil/math-liquidity-mining";var Pt=class extends we{constructor(e){super(e)}secondsInYear=new G(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(u)).unwrap(),O=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(u)).unwrap(),O=(await this.api.query.xykWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new G(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),c=a.price.n.toString(),u=a.price.d.toString(),y;return Number(t)<Number(r)?y=Ft(c,u):y=Ft(u,c),y}getGlobalRewardPerPeriod(e,t,r,s){let a=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return a.gte(r)?r:a}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!Nt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&Nt(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:c,globalFarm:u,priceAdjustment:y})=>{let O=new G(u.totalSharesZ.toString()),B=u.plannedYieldingPeriods.toString(),F=new G(u.yieldPerPeriod.toString()),_=new G(u.maxRewardPerPeriod.toString()),T=u.blocksPerPeriod.toString(),D=new G(c.multiplier.toString()).shiftedBy(-18),L=this.secondsInYear.div(new G(r).times(T)),Y;if(O.isZero())Y=F.times(D).times(L);else{let fe=this.getGlobalRewardPerPeriod(O,F,_,y);Y=this.getPoolYieldPerPeriod(fe,D,O,y).times(L)}let w=new G(u.pendingRewards.toString()).plus(u.accumulatedPaidRewards.toString()),j=_.times(B);return w.div(j).gte(.99)?E:Y.times(100)}).reduce((c,u)=>c.plus(u),E).toString():void 0}};var he=class extends Ce{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async r=>{let s=[await this.subscribePoolChange(r),await this.subscribeTokensPoolBalance(r),await this.subscribeSystemPoolBalance(r)];if(this.hasShareAsset(r)){let i=await this.subscribeSharePoolBalance(r);s.push(i)}return this.subscribeLog(r),s});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,r)=>t.id!==r))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance(Je,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(r,s){let i=e.tokens.findIndex(a=>a.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=s.toString())}}};var Ze=class extends he{MAX_FINAL_WEIGHT=J(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:r}=t.unwrap(),s=e.filter(([i,a])=>this.isActivePool(a.unwrap(),r)).map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=await this.getPoolDelta(u,c,r.toString());return this.poolsData.set(i.toString(),c),{address:u,type:"Lbp",fee:c.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let a=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(c=>c.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,r){let{start:s,end:i,assets:a,initialWeight:c,finalWeight:u,repayTarget:y,feeCollector:O}=t,B=me.calculateLinearWeights(s.toString(),i.toString(),c.toString(),u.toString(),r),[F,_]=a,T=F.toString(),D=I(B),L=_.toString(),Y=this.MAX_FINAL_WEIGHT.minus(I(D)),[w,j,re]=await Promise.all([this.isRepayFeeApplied(T,y.toString(),O.toString()),this.getBalance(e,T),this.getBalance(e,L)]);return{repayFeeApply:w,tokens:[{id:T,weight:D,balance:j.toString()},{id:L,weight:Y,balance:re.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=I(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}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(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{encodeAddress as or}from"@polkadot/util-crypto";import{stringToU8a as ar}from"@polkadot/util";function Z(m,e){return m.shiftedBy(-1*e).toString()}function ue(m){return m[0]/m[1]*100}function ee(m){return m[0]/m[1]}function pe(m){return[m/ft,ft]}var Ke=class extends he{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=r.map(async([{args:[u]},y])=>{let{hubReserve:O,shares:B,tradable:F}=y.unwrap(),_=await this.getBalance(t,u.toString());return{id:u.toString(),hubReserves:I(O.toString()),shares:I(B.toString()),tradeable:F.bits.toNumber(),balance:_.toString()}}),c=await Promise.all(a);return c.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:c,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=await this.api.query.dynamicFees.assetFee(e),s=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=s.minFee.toNumber()+i.minFee.toNumber(),c=s.maxFee.toNumber()+i.maxFee.toNumber();if(r.isSome){let{assetFee:u,protocolFee:y}=r.unwrap();return{assetFee:pe(u.toNumber()),protocolFee:pe(y.toNumber()),min:pe(a),max:pe(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:pe(a),max:pe(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,i)=>{let a=e.tokens[i];if(s.isNone)return a;let c=s.unwrap();return this.updateTokenState(a,c)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i}=t;return{...e,hubReserves:I(r.toString()),shares:I(s.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return pe(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return pe(t)}getPoolId(){return or(ar("modlomnipool".padEnd(32,"\0")),Me)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var Qe=class extends he{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[a,c]=s.unwrap(),[u,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:u.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(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{blake2AsHex as Pr,encodeAddress as br}from"@polkadot/util-crypto";import{calculate_in_given_out as lr,calculate_out_given_in as ur,calculate_amplification as cr,calculate_add_one_asset as mr,calculate_liquidity_out_one_asset as pr,calculate_pool_trade_fee as gr,calculate_shares as hr,calculate_shares_for_amount as dr,pool_account_name as fr}from"@galacticcouncil/math-stableswap";var te=class{static getPoolAddress(e){return fr(e)}static calculateAmplification(e,t,r,s,i){return cr(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,a){return lr(e,t,r,s,i,a)}static calculateAddOneAsset(e,t,r,s,i,a){return mr(e,t,r,s,i,a)}static calculateSharesForAmount(e,t,r,s,i,a){return dr(e,t,r,s,i,a)}static calculateOutGivenIn(e,t,r,s,i,a){return ur(e,t,r,s,i,a)}static calculateLiquidityOutOneAsset(e,t,r,s,i,a){return pr(e,t,r,s,i,a)}static calculateShares(e,t,r,s,i){return hr(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return gr(e,t,r)}};var Ve=class extends he{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=this.getPoolAddress(u),[O,B]=await Promise.all([this.getPoolDelta(u,c,r.toString()),this.getPoolTokens(y,u,c)]);return this.stablePools.set(y,c),{address:y,id:u,type:"Stableswap",fee:pe(c.fee.toNumber()),tokens:B,...O,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toNumber(),s=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,s,r.toString());Object.assign(e,i)})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:a,finalBlock:c}=t,u=te.calculateAmplification(s.toString(),i.toString(),a.toString(),c.toString(),r),y=await this.api.query.tokens.totalIssuance(e);return{amplification:u,totalIssuance:y.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async u=>{let[y,O]=await Promise.all([this.api.query.stableswap.assetTradability(t,u.toString()),this.getBalance(e,u.toString())]);return{id:u.toString(),tradeable:y.bits.toNumber(),balance:O.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:u}=c.unwrap(),y=await this.getBalance(Je,t);a.push({id:t,tradeable:u.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),r=te.getPoolAddress(t);return br(Pr(r),Me)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function bt(m){return m.map(({assetIn:e,assetOut:t,pool:r,poolId:s})=>r==="Stableswap"?{pool:{Stableswap:s},assetIn:e,assetOut:t}:{pool:r,assetIn:e,assetOut:t})}var et=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Tt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ge=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},_t=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Rt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},kt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var qe=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new De(this.api),this.xykClient=new Qe(this.api),this.omniClient=new Ke(this.api),this.lbpClient=new Ze(this.api),this.stableClient=new Ve(this.api)}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||this.syncRegistry(),e.length==0){let a=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(c=>c.isSupported()).map(c=>c.getPools()))).flat();return this.withMetadata(a)}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 s=(await Promise.all(t)).flat();return this.withMetadata(s)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(r=>[r.id,r]));return e.filter(r=>r.type==="Xyk"?r.tokens.every(s=>t.get(s.id)):!0).map(r=>{let s=r.tokens.map(i=>{let a=t.get(i.id);return{...i,...a}});return{...r,tokens:s}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new et(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,r,s,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,r.toFixed(),s.toFixed()):a=this.api.tx.router.buy(e,t,r.toFixed(),s.toFixed(),bt(i));let c=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,r,s,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,r.toFixed(),s.toFixed()):a=this.api.tx.router.sell(e,t,r.toFixed(),s.toFixed(),bt(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var He=(m,e)=>m===e?0:m==null?e==null?0:-1:e==null?m==null?0:1:typeof m.compare=="function"?m.compare(e):typeof e.compare=="function"?-e.compare(m):m<e?-1:m>e?1:0;var tt=(m,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(m(t)+e(t))}};var yr=tt(()=>"illegal argument(s)"),Lt=m=>{throw new yr(m)};var Sr=tt(()=>"index out of bounds"),yt=m=>{throw new Sr(m)},rt=(m,e,t)=>(m<e||m>=t)&&yt(m);var Mt=23283064365386963e-26,st=class{float(e=1){return this.int()*Mt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Mt-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var St=Math.random,wt=class extends st{int(){return St()*4294967296>>>0}float(e=1){return St()*e}norm(e=1){return(St()-.5)*2*e}},Dt=new wt;var Ct=m=>m!=null&&typeof m!="function"&&m.length!==void 0;var Gt=Object.getPrototypeOf({}),it="function",qt="string",Ae=(m,e)=>{let t;if(m===e)return!0;if(m!=null){if(typeof m.equiv===it)return m.equiv(e)}else return m==e;if(e!=null){if(typeof e.equiv===it)return e.equiv(m)}else return m==e;return typeof m===qt||typeof e===qt?!1:(t=Object.getPrototypeOf(m),(t==null||t===Gt)&&(t=Object.getPrototypeOf(e),t==null||t===Gt)?Br(m,e):typeof m!==it&&m.length!==void 0&&typeof e!==it&&e.length!==void 0?wr(m,e):m instanceof Set&&e instanceof Set?xr(m,e):m instanceof Map&&e instanceof Map?Or(m,e):m instanceof Date&&e instanceof Date?m.getTime()===e.getTime():m instanceof RegExp&&e instanceof RegExp?m.toString()===e.toString():m!==m&&e!==e)},wr=(m,e,t=Ae)=>{let r=m.length;if(r===e.length)for(;r-- >0&&t(m[r],e[r]););return r<0},xr=(m,e,t=Ae)=>m.size===e.size&&t([...m.keys()].sort(),[...e.keys()].sort()),Or=(m,e,t=Ae)=>m.size===e.size&&t([...m].sort(),[...e].sort()),Br=(m,e,t=Ae)=>{if(Object.keys(m).length!==Object.keys(e).length)return!1;for(let r in m)if(!e.hasOwnProperty(r)||!t(m[r],e[r]))return!1;return!0};var Ht=(m,e)=>m!=null&&typeof m[e]=="function";var Ut=m=>Ht(m,"xform")?m.xform():m;var nt=Symbol(),xt=()=>{};var zt=m=>m!=null&&typeof m[Symbol.iterator]=="function";var ot=class{value;constructor(e){this.value=e}deref(){return this.value}};var at=m=>m instanceof ot;var Xt=m=>m instanceof ot?m.deref():m;function*Yt(m,e){let t=Ut(m)([xt,xt,(r,s)=>s])[2];for(let r of e){let s=t(nt,r);if(at(s)){s=Xt(s.deref()),s!==nt&&(yield s);return}s!==nt&&(yield s)}}var Wt=(m,e)=>[m[0],m[1],e];function Ue(m,e){return zt(e)?Yt(Ue(m),e):t=>{let r=t[2];return Wt(t,(s,i)=>r(s,m(i)))}}var Ne=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return $t("next",this._head)}reverseIterator(){return $t("prev",this.tail)}clear(){this.release()}compare(e,t=He){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,a=0;for(;r-- >0&&a===0;)a=t(s.value,i.value),s=s.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof Ne||Ct(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!Ae(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||He;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!at(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >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,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&yt(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}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,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*$t(m,e){for(;e;)yield e.value,e=e[m]}var de=class extends Ne{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new de(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 de}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(rt(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(rt(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new de,e)}nth(e,t){let r=this.nthCell(e);return r?r.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 r=this.nthCell(e),s=this.nthCell(t-1),i=a=>({first(){return a.value},next(){return a!==s&&a.next?i(a.next):void 0}});return r?i(r):void 0}shuffle(e,t=Dt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&Lt("invalid indices: ${from} / ${to}");let i=new de,a=this.nthCell(r);for(;a&&++r<=s;)i.push(a.value),a=a.next;return i}sort(e=He){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,a=0;for(let u=0;u<t&&(a++,i=i.next,!!i);u++);let c=t;for(;a>0||c>0&&i;){let u;a===0?(u=i,i=i.next,c--):!i||c===0||e(r.value,i.value)<=0?(u=r,r=r.next,a--):(u=i,i=i.next,c--),this._tail?this._tail.next=u:this._head=u,u.prev=this._tail,this._tail=u}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),rt(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new de;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let a of r)this.insertBefore(s,a);else for(let a of r)this.push(a);return i}};var Fe=class{map;items;opts;_size;constructor(e,t){let r=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=r.map(),this.items=new de,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ue(e=>[e.k,e],this.items)}keys(){return Ue(e=>e.k,this.items)}values(){return Ue(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new Fe(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 r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e);return this._size+=Math.max(0,r-(s?s.value.s:0)),this.ensureSize()&&this.doSetEntry(s,e,t,r),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let r=this.map.get(e);return r?Promise.resolve(this.resetEntry(r)):t().then(s=>this.set(e,s))}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,r=this.opts.maxlen;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e&&e(s.k,s.v),this._size-=s.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,r,s){e?(e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var Ot=class extends qe{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Fe(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let r=[t.address,e].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let i=await super.getPoolFees(e,t);return this.feeCache.set(r,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
+
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Oe=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Oe(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,i,a,c){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=c}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let c=this.calculateTradeFee(t,r),u=ue(this.repayFeeApply?r.repayFee:r.exchangeFee),y=t.plus(c),O=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return O.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:O,calculatedIn:O,amountOut:t,feePct:u,errors:i}}else{let c=this.calculateInGivenOut(e,t),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let c=this.calculateOutGivenIn(e,t),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),u=this.calculateTradeFee(c,r),y=ue(this.repayFeeApply?r.repayFee:r.exchangeFee),O=c.minus(u),B=e.balanceOut.div(this.maxOutRatio);return O.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:O,feePct:y,errors:i}}}calculateInGivenOut(e,t){let r=me.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?E:s}calculateOutGivenIn(e,t){let r=me.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?E:s}spotPriceInGivenOut(e){let t=me.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),J(le,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=me.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),J(le,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let r=me.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(r)}};import{calculate_in_given_out as vr,calculate_lrna_in_given_out as Ir,calculate_out_given_in as Ar,calculate_out_given_lrna_in as Nr,calculate_pool_trade_fee as Fr,calculate_spot_price as Tr,calculate_lrna_spot_price as _r,calculate_shares as Rr,calculate_liquidity_out as Er,calculate_liquidity_lrna_out as kr,verify_asset_cap as Lr,calculate_liquidity_hub_in as Mr,is_sell_allowed as Dr,is_buy_allowed as Cr,is_add_liquidity_allowed as Gr,is_remove_liquidity_allowed as qr}from"@galacticcouncil/math-omnipool";var X=class{static calculateSpotPrice(e,t,r,s){return Tr(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return _r(e,t)}static calculateInGivenOut(e,t,r,s,i,a,c,u,y){return vr(e,t,r,s,i,a,c,u,y)}static calculateLrnaInGivenOut(e,t,r,s,i){return Ir(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,a,c,u,y){return Ar(e,t,r,s,i,a,c,u,y)}static calculateOutGivenLrnaIn(e,t,r,s,i){return Nr(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return Fr(e,t,r)}static calculateShares(e,t,r,s){return Rr(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,a,c,u){return Er(e,t,r,s,i,a,c,u)}static calculateLiquidityLRNAOut(e,t,r,s,i,a,c,u){return kr(e,t,r,s,i,a,c,u)}static calculateCapDifference(e,t,r,s){let i=G(t),a=G(e),c=G(s),y=G(r).shiftedBy(-18);if(i.div(c).lt(y)){let B=y.times(c).minus(i).times(a),F=i.times(G(1).minus(y));return B.div(F).toFixed(0)}else return"0"}static verifyAssetCap(e,t,r,s){return Lr(e,t,r,s)}static calculateLimitHubIn(e,t,r,s){return Mr(e,t,r,s)}static isSellAllowed(e){return Dr(e)}static isBuyAllowed(e){return Cr(e)}static isAddLiquidityAllowed(e){return Gr(e)}static isRemoveLiquidityAllowed(e){return qr(e)}};var Be=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new Be(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,i,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,tradeableIn:s.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),c=s===E?E:a.div(s).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),O=X.isBuyAllowed(e.tradeableOut);(!y||!O)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&u.push("MaxOutRatioExceeded");let F=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(F)&&u.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:c.toNumber(),errors:u}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),c=s.minus(i).div(s).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),O=X.isBuyAllowed(e.tradeableOut);(!y||!O)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&u.push("MaxInRatioExceeded");let F=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(F)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:c.toNumber(),errors:u}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=X.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ee(r.assetFee).toString():E.toString(),r?ee(r.protocolFee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateLrnaInGivenOut(e,t,r){let s=X.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ee(r.assetFee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=X.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ee(r.assetFee).toString():E.toString(),r?ee(r.protocolFee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateOutGivenLrnaIn(e,t,r){let s=X.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ee(r.assetFee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=X.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=X.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=X.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=X.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,r,s,i,a,c,u,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.amplification=a,this.id=c,this.fee=u,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?dt:s.tradeable,tradeableOut:this.id===t?dt:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=ue(r.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),a=ue(r.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,r){let s=te.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateAddOneAsset(e,t,r){let s=te.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateSharesForAmount(e,t,r){let s=te.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=J(le,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,r){let s=te.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateWithdrawOneAsset(e,t,r){let s=te.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateShares(e,t,r){let s=te.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=J(le,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 r=te.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(r)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{calculate_in_given_out as Hr,calculate_out_given_in as Ur,calculate_pool_trade_fee as zr,get_spot_price as Xr,calculate_liquidity_in as Yr,calculate_shares as Wr,calculate_spot_price as $r,calculate_spot_price_with_fee as jr,calculate_liquidity_out_asset_a as Jr,calculate_liquidity_out_asset_b as Zr}from"@galacticcouncil/math-xyk";var be=class{static getSpotPrice(e,t,r){return Xr(e,t,r)}static calculateInGivenOut(e,t,r){return Hr(e,t,r)}static calculateOutGivenIn(e,t,r){return Ur(e,t,r)}static calculatePoolTradeFee(e,t,r){return zr(e,t,r)}static calculateLiquidityIn(e,t,r){return Yr(e,t,r)}static calculateSpotPrice(e,t){return $r(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return jr(e,t,r,s)}static calculateShares(e,t,r){return Wr(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return Jr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Zr(e,t,r,s)}};var Ie=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Ie(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),a=ue(r.exchangeFee),c=s.plus(i),u=[];t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&u.push("MaxOutRatioExceeded");let O=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(O)&&u.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:s,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),a=ue(r.exchangeFee),c=s.minus(i),u=[];t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&u.push("MaxInRatioExceeded");let O=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(O)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:c,feePct:a,errors:u}}calculateInGivenOut(e,t){let r=be.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?E:s}calculateOutGivenIn(e,t){let r=be.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?E:s}spotPriceInGivenOut(e){let t=be.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=J(le,18-e.decimalsOut);return I(t).div(r)}spotPriceOutGivenIn(e){let t=be.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=J(le,18-e.decimalsIn);return I(t).div(r)}calculateTradeFee(e,t){let r=be.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(r)}};var ze=class{static get(e){switch(e.type){case"Xyk":return Ie.fromPool(e);case"Omnipool":return Be.fromPool(e);case"Lbp":return Oe.fromPool(e);case"Stableswap":return ve.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Te=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ee,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),a=this.getPaths(e,null,s,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(a)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,origin:s.origin,meta:s.meta}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(c=>this.validPath(c,r)).map(c=>this.toHops(c,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(r);return{assets:s,poolsMap:i}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,ze.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,i])=>{let a=t.get(r);return{poolAddress:r,poolId:a?.id,pool:a?.type,assetIn:s,assetOut:i}})}toAssets(e,t){return e.map(r=>t.get(r))}};function Fl(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Xe(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function jt(m,e){return le.minus(e.div(m)).multipliedBy(100).decimalPlaces(2)}function Jt(m,e){return e.div(m).minus(le).multipliedBy(100).decimalPlaces(2)}var lt=class extends Te{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,a=s[s.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[r,s]}}getPoolFeeRange(e){let t=e.min?ue(e.min):void 0,r=e.max?ue(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ge(e,t);let u;if(s)u=await this.toSellSwaps(r,s,a);else{let R=c.map(async n=>await this.toSellSwaps(r,n,a)),z=await Promise.all(R);u=this.findBestSellRoute(z)}let y=u[0],O=u[u.length-1],B=this.isDirectTrade(u),F=u.map(R=>R.spotPrice.shiftedBy(-1*R.assetOutDecimals)).reduce((R,z)=>R.multipliedBy(z)),_=J(F,O.assetOutDecimals),T=B?O.calculatedOut:this.calculateDelta0Y(y.amountIn,u,a),D=O.amountOut,L=B?O.tradeFeePct:jt(T,D).toNumber(),Y=T.minus(D),w=this.getRouteFeeRange(u),j=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(_),re=Xe(T,j),fe=R=>this.poolService.buildSellTx(e,t,y.amountIn,R,u.map(z=>z));return{type:"Sell",amountIn:y.amountIn,amountOut:O.amountOut,spotPrice:_,tradeFee:Y,tradeFeePct:L,tradeFeeRange:w,priceImpactPct:re.toNumber(),swaps:u,toTx:fe,toHuman(){return{type:"Sell",amountIn:Z(y.amountIn,y.assetInDecimals),amountOut:Z(O.amountOut,O.assetOutDecimals),spotPrice:Z(_,O.assetOutDecimals),tradeFee:Z(Y,O.assetOutDecimals),tradeFeePct:L,tradeFeeRange:w,priceImpactPct:re.toNumber(),swaps:u.map(R=>R.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=s[i-1]:y=e;let O=c.calculateOutGivenIn(u,y);s.push(O)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=s[i-1].amountOut:y=J(I(e),u.decimalsIn).decimalPlaces(0,1);let O=await this.poolService.getPoolFees(u.assetOut,c),{amountOut:B,calculatedOut:F,feePct:_,errors:T}=c.validateAndSell(u,y,O),D=this.getPoolFeeRange(O),L=c.spotPriceOutGivenIn(u),Y=y.shiftedBy(-1*u.decimalsIn).multipliedBy(L),w=Xe(F,Y);s.push({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountIn:y,calculatedOut:F,amountOut:B,spotPrice:L,tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w.toNumber(),errors:T,toHuman(){return{...a,amountIn:Z(y,u.decimalsIn),calculatedOut:Z(F,u.decimalsOut),amountOut:Z(B,u.decimalsOut),spotPrice:Z(L,u.decimalsOut),tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w.toNumber(),errors:T}}})}return s}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r),i=super.getPaths(e,t,s,r);if(i.length===0)return Promise.resolve(void 0);let a=r.map(w=>w.tokens.find(j=>j.id===e)).filter(w=>!!w).sort((w,j)=>Number(j.balance)-Number(w.balance)),{balance:c,decimals:u}=a[0],O=I(c).shiftedBy(-1*u).div(100).multipliedBy(.1),B=i.map(async w=>await this.toSellSwaps(O,w,s)),F=await Promise.all(B),_=this.findBestSellRoute(F),T=await this.toSellSwaps("1",_,s),D=T.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,j)=>w.multipliedBy(j)),L=T[T.length-1].assetOutDecimals;return{amount:J(D,L),decimals:L}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,a=s[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ge(e,t);let u;if(s)u=await this.toBuySwaps(r,s,a);else{let R=c.map(async n=>await this.toBuySwaps(r,n,a)),z=await Promise.all(R);u=this.findBestBuyRoute(z)}let y=u[u.length-1],O=u[0],B=this.isDirectTrade(u),F=u.map(R=>R.spotPrice.shiftedBy(-1*R.assetInDecimals)).reduce((R,z)=>R.multipliedBy(z)),_=J(F,O.assetInDecimals),T=B?O.calculatedIn:this.calculateDelta0X(y.amountOut,u,a),D=O.amountIn,L=B?O.tradeFeePct:Jt(T,D).toNumber(),Y=D.minus(T),w=this.getRouteFeeRange(u),j=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(_),re;T.isZero()?re=-100:re=Xe(j,T).toNumber();let fe=R=>this.poolService.buildBuyTx(e,t,y.amountOut,R,u.map(z=>z));return{type:"Buy",amountOut:y.amountOut,amountIn:O.amountIn,spotPrice:_,tradeFee:Y,tradeFeePct:L,tradeFeeRange:w,priceImpactPct:re,swaps:u,toTx:fe,toHuman(){return{type:"Buy",amountOut:Z(y.amountOut,y.assetOutDecimals),amountIn:Z(O.amountIn,O.assetInDecimals),spotPrice:Z(_,O.assetInDecimals),tradeFee:Z(Y,O.assetInDecimals),tradeFeePct:L,tradeFeeRange:w,priceImpactPct:re,swaps:u.map(R=>R.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=s[0];let O=c.calculateInGivenOut(u,y);s.unshift(O)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=J(I(e),u.decimalsOut).decimalPlaces(0,1):y=s[0].amountIn;let O=await this.poolService.getPoolFees(u.assetOut,c),{amountIn:B,calculatedIn:F,feePct:_,errors:T}=c.validateAndBuy(u,y,O),D=this.getPoolFeeRange(O),L=c.spotPriceInGivenOut(u),Y=y.shiftedBy(-1*u.decimalsOut).multipliedBy(L),w;F.isZero()?w=-100:w=Xe(Y,F).toNumber(),s.unshift({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountOut:y,calculatedIn:F,amountIn:B,spotPrice:L,tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w,errors:T,toHuman(){return{...a,amountOut:Z(y,u.decimalsOut),calculatedIn:Z(F,u.decimalsIn),amountIn:Z(B,u.decimalsIn),spotPrice:Z(L,u.decimalsIn),tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w,errors:T}}})}return s}};export{De as AssetClient,_t as AssetNotFound,Bs as BASILISK_PARACHAIN_ID,Ce as BalanceClient,G as BigNumber,Ot as CachingPoolService,Qt as DECIMAL_PLACES,ft as DENOMINATOR,Pt as FarmClient,Je as HYDRADX_OMNIPOOL_ADDRESS,Os as HYDRADX_PARACHAIN_ID,Me as HYDRADX_SS58_PREFIX,ds as INFINITY,me as LbpMath,Oe as LbpPool,le as ONE,X as OmniMath,Be as OmniPool,Tt as PoolConfigNotFound,ke as PoolError,ze as PoolFactory,et as PoolNotFound,qe as PoolService,se as PoolType,kt as ProviderConfigNotFound,Le as RUNTIME_DECIMALS,Ge as RouteNotFound,Te as Router,xs as SYSTEM_ASSET_DECIMALS,Se as SYSTEM_ASSET_ID,te as StableMath,ve as StableSwap,Rt as StorageConfigNotFound,Et as SubscriptionNotSupported,dt as TRADEABLE_DEFAULT,lt as TradeRouter,It as TradeType,be as XykMath,Ie as XykPool,E as ZERO,I as bnum,bt as buildRoute,Jt as calculateBuyFee,Fl as calculateDiffToAvg,Xe as calculateDiffToRef,jt as calculateSellFee,At as findNestedKey,Is as findNestedObj,J as scale};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { ApiPromise } from '@polkadot/api';
|
|
2
|
+
import { PalletLiquidityMiningGlobalFarmData } from '@polkadot/types/lookup';
|
|
3
|
+
import { PolkadotApiClient } from './PolkadotApi';
|
|
4
|
+
export declare class FarmClient extends PolkadotApiClient {
|
|
5
|
+
constructor(api: ApiPromise);
|
|
6
|
+
private secondsInYear;
|
|
7
|
+
private getOmnipoolFarms;
|
|
8
|
+
private getIsolatedPoolFarms;
|
|
9
|
+
getOraclePrice(globalFarm: PalletLiquidityMiningGlobalFarmData): Promise<string | undefined>;
|
|
10
|
+
private getGlobalRewardPerPeriod;
|
|
11
|
+
private getPoolYieldPerPeriod;
|
|
12
|
+
/**
|
|
13
|
+
* Return list of all available assets from substrate based pools
|
|
14
|
+
* @param {string} id - asset id within omnipool or address of isolated pool
|
|
15
|
+
* @param {'omnipool' | 'isolatedpool'} type - type of pool
|
|
16
|
+
* @returns {string} sum of all active farm APRS
|
|
17
|
+
*/
|
|
18
|
+
getFarmApr(id: string, type: 'omnipool' | 'isolatedpool'): Promise<string | undefined>;
|
|
19
|
+
}
|
|
@@ -4,6 +4,8 @@ export declare class XykMath {
|
|
|
4
4
|
static calculateOutGivenIn(balanceIn: string, balanceOut: string, amountIn: string): string;
|
|
5
5
|
static calculatePoolTradeFee(amount: string, feeNumerator: number, feeDenominator: number): string;
|
|
6
6
|
static calculateLiquidityIn(reserveA: string, reserveB: string, amountA: string): string;
|
|
7
|
+
static calculateSpotPrice(balanceA: string, balanceB: string): string;
|
|
8
|
+
static calculateSpotPriceWithFee(balanceA: string, balanceB: string, feeNumerator: string, feeDenominator: string): string;
|
|
7
9
|
static calculateShares(reserveA: string, amountA: string, totalShares: string): string;
|
|
8
10
|
static calculateLiquidityOutAssetA(reserveA: string, reserveB: string, shares: string, totalShares: string): string;
|
|
9
11
|
static calculateLiquidityOutAssetB(reserveA: string, reserveB: string, shares: string, totalShares: string): string;
|
package/build/types/types.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@galacticcouncil/sdk",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "Galactic off-chain routing & optimization of orders across pools for best price execution",
|
|
5
5
|
"author": "GalacticCouncil",
|
|
6
6
|
"repository": {
|
|
@@ -32,10 +32,11 @@
|
|
|
32
32
|
"test": "jest"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@galacticcouncil/math-lbp": "^0.
|
|
36
|
-
"@galacticcouncil/math-
|
|
37
|
-
"@galacticcouncil/math-
|
|
38
|
-
"@galacticcouncil/math-
|
|
35
|
+
"@galacticcouncil/math-lbp": "^1.0.0",
|
|
36
|
+
"@galacticcouncil/math-liquidity-mining": "^1.0.0",
|
|
37
|
+
"@galacticcouncil/math-omnipool": "^1.0.0",
|
|
38
|
+
"@galacticcouncil/math-stableswap": "^1.0.0",
|
|
39
|
+
"@galacticcouncil/math-xyk": "^1.0.0",
|
|
39
40
|
"@thi.ng/cache": "^2.1.35",
|
|
40
41
|
"bignumber.js": "^9.1.0",
|
|
41
42
|
"lodash.clonedeep": "^4.5.0"
|