@galacticcouncil/sdk 2.2.3 → 2.3.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 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:()=>Z,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:()=>J});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,$=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",Q=!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&&Q)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,$,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),p=l[0],S=l[1]):(q(l,-$,$,o),p=-(S=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),w=l[0],B=l[1];else if(q(l,-$,$,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,$,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))Q=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>=-$&&g<=$&&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=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("."),Y=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,Y,R,g),A=v.c,O=v.r,b=v.e),h=b+Y+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),-Y,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,Y,R,C,V,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),Y=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)Y.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(V=R[0],fe!=C&&(V=V*m+(R[1]||0)),v=ce(V/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]);Y[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,Y[0]||Y.splice(0,1)}if(m==he){for(f=1,le=Y[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,$),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,Y,R=this,C=R.c,V=(n=new x(n,o)).c;if(!C||!V||!C[0]||!V[0])return!R.s||!n.s||C&&!C[0]&&!V||V&&!V[0]&&!C?n.c=n.e=n.s=null:(n.s*=R.s,!C||!V?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=V.length,h<O&&(L=C,C=V,V=L,g=h,h=O,O=g),g=h+O,L=[];g--;L.push(0));for(H=he,Y=we,g=O;--g>=0;){for(l=0,v=V[g]%Y,A=V[g]/Y|0,y=h,d=g+y;d>g;)b=C[--y]%Y,f=C[y]/Y|0,m=A*b+f*v,b=v*b+m%Y*Y+L[d]+l,l=(b/H|0)+(m/Y|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,$),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,$),n++),ee(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(q(n,0,$),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,$),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&&Q?(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 Z=Gt();var qt=12;Z.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:qt});var E=I(0),oe=I(1),ms=I("Infinity");function J(u,e){let t=new Z(e.toString()),s=new Z(10).pow(t);return u.times(s)}function I(u){return new Z(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 Z(t),c=new Z(s||i),p=new Z(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=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: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(),Q=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:Q,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 K(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(),J(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(),J(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=Z(t),a=Z(e),c=Z(r),S=Z(s).shiftedBy(-18);if(i.div(c).lt(S)){let B=S.times(c).minus(i).times(a),T=i.times(Z(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=J(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=J(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 W=require("@galacticcouncil/math-xyk"),Se=class{static getSpotPrice(e,t,s){return(0,W.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,W.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,W.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,W.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,W.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,W.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,W.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,W.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,W.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,W.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.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=J(oe,18-e.decimalsOut);return I(t).div(s)}spotPriceOutGivenIn(e){let t=Se.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=J(oe,18-e.decimalsIn);return I(t).div(s)}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=J(T,w.assetOutDecimals),F=B?w.calculatedOut:this.calculateDelta0Y(S.amountIn,p,a),G=w.amountOut,D=B?w.tradeFeePct:Mt(F,G).toNumber(),Q=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:Q,tradeFeePct:D,tradeFeeRange:x,priceImpactPct:ae.toNumber(),swaps:p,toTx:Ne,toHuman(){return{type:"Sell",amountIn:K(S.amountIn,S.assetInDecimals),amountOut:K(w.amountOut,w.assetOutDecimals),spotPrice:K(k,w.assetOutDecimals),tradeFee:K(Q,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=J(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),Q=S.shiftedBy(-1*p.decimalsIn).multipliedBy(D),x=ze(T,Q);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:K(S,p.decimalsIn),calculatedOut:K(T,p.decimalsOut),amountOut:K(B,p.decimalsOut),spotPrice:K(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:J(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=J(T,w.assetInDecimals),F=B?w.calculatedIn:this.calculateDelta0X(S.amountOut,p,a),G=w.amountIn,D=B?w.tradeFeePct:Dt(F,G).toNumber(),Q=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:Q,tradeFeePct:D,tradeFeeRange:x,priceImpactPct:ae,swaps:p,toTx:Ne,toHuman(){return{type:"Buy",amountOut:K(S.amountOut,S.assetOutDecimals),amountIn:K(w.amountIn,w.assetInDecimals),spotPrice:K(k,w.assetInDecimals),tradeFee:K(Q,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=J(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),Q=S.shiftedBy(-1*p.decimalsOut).multipliedBy(D),x;T.isZero()?x=-100:x=ze(Q,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:K(S,p.decimalsOut),calculatedIn:K(T,p.decimalsIn),amountIn:K(B,p.decimalsIn),spotPrice:K(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});
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 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),mr=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",yr=12,Sr=2034,Me=63,xr=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 wr(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_spot_price as Xs,calculate_spot_price_with_fee as Ws,calculate_liquidity_out_asset_a as Ys,calculate_liquidity_out_asset_b as $s}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 calculateSpotPrice(e,t){return Xs(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return Ws(e,t,s,r)}static calculateShares(e,t,s){return zs(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return Ys(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return $s(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.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=Y(le,18-e.decimalsOut);return I(t).div(s)}spotPriceOutGivenIn(e){let t=Pe.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=Y(le,18-e.decimalsIn);return I(t).div(s)}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 Sl(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,xr 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,Sr as HYDRADX_PARACHAIN_ID,Me as HYDRADX_SS58_PREFIX,mr 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,yr 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,Sl as calculateDiffToAvg,Xe as calculateDiffToRef,Wt as calculateSellFee,It as findNestedKey,wr as findNestedObj,Y as scale};
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk",
3
- "version": "2.2.3",
3
+ "version": "2.3.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,10 @@
32
32
  "test": "jest"
33
33
  },
34
34
  "dependencies": {
35
- "@galacticcouncil/math-lbp": "^0.2.1",
36
- "@galacticcouncil/math-omnipool": "^0.2.0",
37
- "@galacticcouncil/math-stableswap": "^0.2.2",
38
- "@galacticcouncil/math-xyk": "^0.2.0",
35
+ "@galacticcouncil/math-lbp": "^1.0.0",
36
+ "@galacticcouncil/math-omnipool": "^1.0.0",
37
+ "@galacticcouncil/math-stableswap": "^1.0.0",
38
+ "@galacticcouncil/math-xyk": "^1.0.0",
39
39
  "@thi.ng/cache": "^2.1.35",
40
40
  "bignumber.js": "^9.1.0",
41
41
  "lodash.clonedeep": "^4.5.0"