@galacticcouncil/sdk 4.3.0 → 4.4.0-pr89-e1182c7

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 xt=Object.defineProperty;var as=Object.getOwnPropertyDescriptor;var ls=Object.getOwnPropertyNames;var us=Object.prototype.hasOwnProperty;var cs=(l,e)=>{for(var t in e)xt(l,t,{get:e[t],enumerable:!0})},ms=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ls(e))!us.call(l,r)&&r!==t&&xt(l,r,{get:()=>e[r],enumerable:!(s=as(e,r))||s.enumerable});return l};var ps=l=>ms(xt({},"__esModule",{value:!0}),l);var As={};cs(As,{AssetClient:()=>Fe,AssetNotFound:()=>_t,BASILISK_PARACHAIN_ID:()=>bs,BalanceClient:()=>_e,BigNumber:()=>q,CachingPoolService:()=>bt,DECIMAL_PLACES:()=>Xt,DENOMINATOR:()=>et,FarmClient:()=>tt,HYDRADX_OMNIPOOL_ADDRESS:()=>ze,HYDRADX_PARACHAIN_ID:()=>Ps,HYDRADX_SS58_PREFIX:()=>Te,INFINITY:()=>ds,LbpMath:()=>pe,LbpPool:()=>Le,ONE:()=>ae,OmniMath:()=>W,OmniPool:()=>De,PoolConfigNotFound:()=>Ft,PoolError:()=>Ae,PoolFactory:()=>Ge,PoolNotFound:()=>We,PoolService:()=>Re,PoolType:()=>ie,ProviderConfigNotFound:()=>kt,RUNTIME_DECIMALS:()=>Ne,RouteNotFound:()=>Ee,Router:()=>Ie,SYSTEM_ASSET_DECIMALS:()=>fs,SYSTEM_ASSET_ID:()=>Oe,StableMath:()=>se,StableSwap:()=>Me,StorageConfigNotFound:()=>Et,SubscriptionNotSupported:()=>Rt,TRADEABLE_DEFAULT:()=>Qe,TradeRouter:()=>je,TradeType:()=>It,XykMath:()=>ye,XykPool:()=>Ce,ZERO:()=>E,bnum:()=>v,buildRoute:()=>at,calculateBuyFee:()=>qt,calculateDiffToAvg:()=>Is,calculateDiffToRef:()=>qe,calculateSellFee:()=>Gt,findNestedKey:()=>At,findNestedObj:()=>ys,scale:()=>K});module.exports=ps(As);var Ke=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var gs=5,Ue=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new Ke,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let m=i.dequeue();if(m==null||m.length>gs)return r;let c=m[m.length-1];(s===null||c[0]===s)&&r.push(m),e.get(c[0])?.forEach(O=>{if(this.isNotVisited(O,m)){let B=[...m];B.push(O),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 m=parseInt(i),c=parseInt(a);s.get(m)?.push([c,r])}return s}};function wt(l){let e={};for(let t of l){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 Xe=class{getProposals(e,t,s){let r=wt(s),i=Object.keys(r),a=i.map(O=>r[O]).flat(),m=new Ue,c=m.buildAndPopulateGraph(i,a),y=m.findPaths(c,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let a=s[i],m=s[i+1];if(m==null)break;r.push(this.toEdge(a,m))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var hs=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ot=Math.ceil,ce=Math.floor,re="[BigNumber Error] ",Ht=re+"Number primitive has more than 15 significant digits: ",he=1e14,T=14,Bt=9007199254740991,vt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],we=1e7,J=1e9;function Ut(l){var e,t,s,r=x.prototype={constructor:x,toString:null,valueOf:null},i=new x(1),a=20,m=4,c=-7,y=21,O=-1e7,B=1e7,N=!1,F=1,_=0,C={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},k="0123456789abcdefghijklmnopqrstuvwxyz",U=!0;function x(n,o){var u,P,g,d,S,p,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<O?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!hs.test(b=String(n)))return s(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(H(o,2,k.length,"Base"),o==10&&U)return f=new x(n),R(f,a+f.e+1,m);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return s(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Ht+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(u=k.slice(0,o),d=S=0,h=b.length;S<h;S++)if(u.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return s(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&x.DEBUG&&h>15&&(n>Bt||n!==ce(n)))throw Error(Ht+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<O)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%T,d<0&&(S+=T),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=T;S<h;)f.c.push(+b.slice(S,S+=T));S=T-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}x.clone=Ut,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,u;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(u=n[o],H(u,0,J,o),a=u),n.hasOwnProperty(o="ROUNDING_MODE")&&(u=n[o],H(u,0,8,o),m=u),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(u=n[o],u&&u.pop?(H(u[0],-J,0,o),H(u[1],0,J,o),c=u[0],y=u[1]):(H(u,-J,J,o),c=-(y=u<0?-u:u))),n.hasOwnProperty(o="RANGE"))if(u=n[o],u&&u.pop)H(u[0],-J,-1,o),H(u[1],1,J,o),O=u[0],B=u[1];else if(H(u,-J,J,o),u)O=-(B=u<0?-u:u);else throw Error(re+o+" cannot be zero: "+u);if(n.hasOwnProperty(o="CRYPTO"))if(u=n[o],u===!!u)if(u)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))N=u;else throw N=!u,Error(re+"crypto unavailable");else N=u;else throw Error(re+o+" not true or false: "+u);if(n.hasOwnProperty(o="MODULO_MODE")&&(u=n[o],H(u,0,9,o),F=u),n.hasOwnProperty(o="POW_PRECISION")&&(u=n[o],H(u,0,J,o),_=u),n.hasOwnProperty(o="FORMAT"))if(u=n[o],typeof u=="object")C=u;else throw Error(re+o+" not an object: "+u);if(n.hasOwnProperty(o="ALPHABET"))if(u=n[o],typeof u=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(u))U=u.slice(0,10)=="0123456789",k=u;else throw Error(re+o+" invalid: "+u)}else throw Error(re+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:m,EXPONENTIAL_AT:[c,y],RANGE:[O,B],CRYPTO:N,MODULO_MODE:F,POW_PRECISION:_,FORMAT:C,ALPHABET:k}},x.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!x.DEBUG)return!0;var o,u,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-J&&g<=J&&g===ce(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%T,o<1&&(o+=T),String(P[0]).length==o){for(o=0;o<P.length;o++)if(u=P[o],u<0||u>=he||u!==ce(u))break e;if(u!==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 oe(arguments,-1)},x.minimum=x.min=function(){return oe(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(u){var P,g,d,S,p,h=0,b=[],f=new x(i);if(u==null?u=a:H(u,0,J),S=Ot(u/T),N)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));h<S;)p=P[h]*131072+(P[h+1]>>>11),p>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(p%1e14),h+=2);h=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);h<S;)p=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],p>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(p%1e14),h+=7);h=S/7}else throw N=!1,Error(re+"crypto unavailable");if(!N)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],u%=T,S&&u&&(p=vt[T-u],b[h]=ce(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=T);for(h=1,p=b[0];p>=10;p/=10,h++);h<T&&(d-=T-h)}return f.e=d,f.c=b,f}}(),x.sum=function(){for(var n=1,o=arguments,u=new x(o[0]);n<o.length;)u=u.plus(o[n++]);return u},t=function(){var n="0123456789";function o(u,P,g,d){for(var S,p=[0],h,b=0,f=u.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(u.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(u,P,g,d,S){var p,h,b,f,w,I,A,D,X=u.indexOf("."),j=a,L=m;for(X>=0&&(f=_,_=0,u=u.replace(".",""),D=new x(P),I=D.pow(u.length-X),_=f,D.c=o(xe(ue(I.c),I.e,"0"),10,g,n),D.e=D.c.length),A=o(u,P,g,S?(p=k,n):(p=n,k)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(X<0?--b:(I.c=A,I.e=b,I.s=d,I=e(I,D,j,L,g),A=I.c,w=I.r,b=I.e),h=b+j+1,X=A[h],f=g/2,w=w||h<0||A[h+1]!=null,w=L<4?(X!=null||w)&&(L==0||L==(I.s<0?3:2)):X>f||X==f&&(L==4||w||L==6&&A[h-1]&1||L==(I.s<0?8:7)),h<1||!A[0])u=w?xe(p.charAt(1),-j,p.charAt(0)):p.charAt(0);else{if(A.length=h,w)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(X=0,u="";X<=f;u+=p.charAt(A[X++]));u=xe(u,b,p.charAt(0))}return u}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,w=P.length,I=g%we,A=g/we|0;for(P=P.slice();w--;)h=P[w]%we,b=P[w]/we|0,S=A*h+b*I,p=I*h+S%we*we+f,f=(p/d|0)+(S/we|0)+A*b,P[w]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function u(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,w,I,A,D,X,j,L,G,ee,Je,yt,St,fe,He,le=P.s==g.s?1:-1,te=P.c,z=g.c;if(!te||!te[0]||!z||!z[0])return new x(!P.s||!g.s||(te?z&&te[0]==z[0]:!z)?NaN:te&&te[0]==0||!z?le*0:le/0);for(X=new x(le),j=X.c=[],b=P.e-g.e,le=d+b+1,p||(p=he,b=me(P.e/T)-me(g.e/T),le=le/T|0),f=0;z[f]==(te[f]||0);f++);if(z[f]>(te[f]||0)&&b--,le<0)j.push(1),w=!0;else{for(yt=te.length,fe=z.length,f=0,le+=2,I=ce(p/(z[0]+1)),I>1&&(z=n(z,I,p),te=n(te,I,p),fe=z.length,yt=te.length),Je=fe,L=te.slice(0,fe),G=L.length;G<fe;L[G++]=0);He=z.slice(),He=[0].concat(He),St=z[0],z[1]>=p/2&&St++;do{if(I=0,h=o(z,L,fe,G),h<0){if(ee=L[0],fe!=G&&(ee=ee*p+(L[1]||0)),I=ce(ee/St),I>1)for(I>=p&&(I=p-1),A=n(z,I,p),D=A.length,G=L.length;o(A,L,D,G)==1;)I--,u(A,fe<D?He:z,D,p),D=A.length,h=1;else I==0&&(h=I=1),A=z.slice(),D=A.length;if(D<G&&(A=[0].concat(A)),u(L,A,G,p),G=L.length,h==-1)for(;o(z,L,fe,G)<1;)I++,u(L,fe<G?He:z,G,p),G=L.length}else h===0&&(I++,L=[0]);j[f++]=I,L[0]?L[G++]=te[Je]||0:(L=[te[Je]],G=1)}while((Je++<yt||L[0]!=null)&&le--);w=L[0]!=null,j[0]||j.splice(0,1)}if(p==he){for(f=1,le=j[0];le>=10;le/=10,f++);R(X,d+(X.e=f+b*T-1)+1,S,w)}else X.e=b,X.r=+w;return X}}();function Z(n,o,u,P){var g,d,S,p,h;if(u==null?u=m:H(u,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ue(n.c),h=P==1||P==2&&(S<=c||S>=y)?Ze(h,S):xe(h,S,"0");else if(n=R(new x(n),o,u),d=n.e,h=ue(n.c),p=h.length,P==1||P==2&&(o<=d||d<=c)){for(;p<o;h+="0",p++);h=Ze(h,d)}else if(o-=S,h=xe(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function oe(n,o){for(var u,P,g=1,d=new x(n[0]);g<n.length;g++)P=new x(n[g]),(!P.s||(u=ve(d,P))===o||u===0&&d.s===o)&&(d=P);return d}function Se(n,o,u){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(u=P+u*T-1)>B?n.c=n.e=null:u<O?n.c=[n.e=0]:(n.e=u,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,u=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,h){var b,f=p?S:S.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(w,I,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?I:w}),h&&(b=h,f=f.replace(o,"$1").replace(u,"0.$1")),S!=f))return new x(f,b);if(x.DEBUG)throw Error(re+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function R(n,o,u,P){var g,d,S,p,h,b,f,w=n.c,I=vt;if(w){e:{for(g=1,p=w[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=T,S=o,h=w[b=0],f=ce(h/I[g-S-1]%10);else if(b=Ot((d+1)/T),b>=w.length)if(P){for(;w.length<=b;w.push(0));h=f=0,g=1,d%=T,S=d-T+1}else break e;else{for(h=p=w[b],g=1;p>=10;p/=10,g++);d%=T,S=d-T+g,f=S<0?0:ce(h/I[g-S-1]%10)}if(P=P||o<0||w[b+1]!=null||(S<0?h:h%I[g-S-1]),P=u<4?(f||P)&&(u==0||u==(n.s<0?3:2)):f>5||f==5&&(u==4||P||u==6&&(d>0?S>0?h/I[g-S]:0:w[b-1])%10&1||u==(n.s<0?8:7)),o<1||!w[0])return w.length=0,P?(o-=n.e+1,w[0]=I[(T-o%T)%T],n.e=-o||0):w[0]=n.e=0,n;if(d==0?(w.length=b,p=1,b--):(w.length=b+1,p=I[T-d],w[b]=S>0?ce(h/I[g-S]%I[S])*p:0),P)for(;;)if(b==0){for(d=1,S=w[0];S>=10;S/=10,d++);for(S=w[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,w[0]==he&&(w[0]=1));break}else{if(w[b]+=p,w[b]!=he)break;w[b--]=0,p=1}for(d=w.length;w[--d]===0;w.pop());}n.e>B?n.c=n.e=null:n.e<O&&(n.c=[n.e=0])}return n}function Y(n){var o,u=n.e;return u===null?n.toString():(o=ue(n.c),o=u<=c||u>=y?Ze(o,u):xe(o,u,"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 ve(this,new x(n,o))},r.decimalPlaces=r.dp=function(n,o){var u,P,g,d=this;if(n!=null)return H(n,0,J),o==null?o=m:H(o,0,8),R(new x(d),n+d.e+1,o);if(!(u=d.c))return null;if(P=((g=u.length-1)-me(this.e/T))*T,g=u[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,m)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new x(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var u,P,g,d,S,p,h,b,f,w=this;if(n=new x(n),n.c&&!n.isInteger())throw Error(re+"Exponent not an integer: "+Y(n));if(o!=null&&(o=new x(o)),p=n.e>14,!w.c||!w.c[0]||w.c[0]==1&&!w.e&&w.c.length==1||!n.c||!n.c[0])return f=new x(Math.pow(+Y(w),p?n.s*(2-Ve(n)):+Y(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&&w.isInteger()&&o.isInteger(),P&&(w=w.mod(o))}else{if(n.e>9&&(w.e>0||w.e<-1||(w.e==0?w.c[0]>1||p&&w.c[1]>=24e7:w.c[0]<8e13||p&&w.c[0]<=9999975e7)))return d=w.s<0&&Ve(n)?-0:0,w.e>-1&&(d=1/d),new x(h?1/d:d);_&&(d=Ot(_/T+2))}for(p?(u=new x(.5),h&&(n.s=1),b=Ve(n)):(g=Math.abs(+Y(n)),b=g%2),f=new x(i);;){if(b){if(f=f.times(w),!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(u),R(n,n.e+1,1),n.e>14)b=Ve(n);else{if(g=+Y(n),g===0)break;b=g%2}w=w.times(w),d?w.c&&w.c.length>d&&(w.c.length=d):P&&(w=w.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?R(f,_,m,S):f)},r.integerValue=function(n){var o=new x(this);return n==null?n=m:H(n,0,8),R(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return ve(this,new x(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return ve(this,new x(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=ve(this,new x(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&me(this.e/T)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return ve(this,new x(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=ve(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 u,P,g,d,S=this,p=S.s;if(n=new x(n,o),o=n.s,!p||!o)return new x(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/T,b=n.e/T,f=S.c,w=n.c;if(!h||!b){if(!f||!w)return f?(n.s=-o,n):new x(w?S:NaN);if(!f[0]||!w[0])return w[0]?(n.s=-o,n):new x(f[0]?S:m==3?-0:0)}if(h=me(h),b=me(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=w),g.reverse(),o=p;o--;g.push(0));g.reverse()}else for(P=(d=(p=f.length)<(o=w.length))?p:o,p=o=0;o<P;o++)if(f[o]!=w[o]){d=f[o]<w[o];break}if(d&&(g=f,f=w,w=g,n.s=-n.s),o=(P=w.length)-(u=f.length),o>0)for(;o--;f[u++]=0);for(o=he-1;P>p;){if(f[--P]<w[P]){for(u=P;u&&!f[--u];f[u]=o);--f[u],f[P]+=he}f[P]-=w[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?Se(n,f,b):(n.s=m==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var u,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):(F==9?(P=n.s,n.s=1,u=e(g,n,0,3),n.s=P,u.s*=P):u=e(g,n,0,F),n=g.minus(u.times(n)),!n.c[0]&&F==1&&(n.s=g.s),n)},r.multipliedBy=r.times=function(n,o){var u,P,g,d,S,p,h,b,f,w,I,A,D,X,j,L=this,G=L.c,ee=(n=new x(n,o)).c;if(!G||!ee||!G[0]||!ee[0])return!L.s||!n.s||G&&!G[0]&&!ee||ee&&!ee[0]&&!G?n.c=n.e=n.s=null:(n.s*=L.s,!G||!ee?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=me(L.e/T)+me(n.e/T),n.s*=L.s,h=G.length,w=ee.length,h<w&&(D=G,G=ee,ee=D,g=h,h=w,w=g),g=h+w,D=[];g--;D.push(0));for(X=he,j=we,g=w;--g>=0;){for(u=0,I=ee[g]%j,A=ee[g]/j|0,S=h,d=g+S;d>g;)b=G[--S]%j,f=G[S]/j|0,p=A*b+f*I,b=I*b+p%j*j+D[d]+u,u=(b/X|0)+(p/j|0)+A*f,D[d--]=b%X;D[d]=u}return u?++P:D.splice(0,1),Se(n,D,P)},r.negated=function(){var n=new x(this);return n.s=-n.s||null,n},r.plus=function(n,o){var u,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/T,S=n.e/T,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new x(g/0);if(!p[0]||!h[0])return h[0]?n:new x(p[0]?P:g*0)}if(d=me(d),S=me(S),p=p.slice(),g=d-S){for(g>0?(S=d,u=h):(g=-g,u=p),u.reverse();g--;u.push(0));u.reverse()}for(g=p.length,o=h.length,g-o<0&&(u=h,h=p,p=u,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/he|0,p[o]=he===p[o]?0:p[o]%he;return g&&(p=[g].concat(p),++S),Se(n,p,S)},r.precision=r.sd=function(n,o){var u,P,g,d=this;if(n!=null&&n!==!!n)return H(n,1,J),o==null?o=m:H(o,0,8),R(new x(d),n,o);if(!(u=d.c))return null;if(g=u.length-1,P=g*T+1,g=u[g]){for(;g%10==0;g/=10,P--);for(g=u[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return H(n,-Bt,Bt),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,u,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new x("0.5");if(p!==1||!S||!S[0])return new x(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+Y(d)),p==0||p==1/0?(o=ue(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=me((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),u=new x(o)):u=new x(p+""),u.c[0]){for(h=u.e,p=h+b,p<3&&(p=0);;)if(g=u,u=f.times(g.plus(e(d,g,b,1))),ue(g.c).slice(0,p)===(o=ue(u.c)).slice(0,p))if(u.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(R(g,g.e+a+2,0),g.times(g).eq(d))){u=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(R(u,u.e+a+2,1),n=!u.times(u).eq(d));break}}return R(u,u.e+a+1,m,n)},r.toExponential=function(n,o){return n!=null&&(H(n,0,J),n++),Z(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(H(n,0,J),n=n+this.e+1),Z(this,n,o)},r.toFormat=function(n,o,u){var P,g=this;if(u==null)n!=null&&o&&typeof o=="object"?(u=o,o=null):n&&typeof n=="object"?(u=n,n=o=null):u=C;else if(typeof u!="object")throw Error(re+"Argument not an object: "+u);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+u.groupSize,h=+u.secondaryGroupSize,b=u.groupSeparator||"",f=S[0],w=S[1],I=g.s<0,A=I?f.slice(1):f,D=A.length;if(h&&(d=p,p=h,h=d,D-=d),p>0&&D>0){for(d=D%p||p,f=A.substr(0,d);d<D;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),I&&(f="-"+f)}P=w?f+(u.decimalSeparator||"")+((h=+u.fractionGroupSize)?w.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(u.fractionGroupSeparator||"")):w):f}return(u.prefix||"")+P+(u.suffix||"")},r.toFraction=function(n){var o,u,P,g,d,S,p,h,b,f,w,I,A=this,D=A.c;if(n!=null&&(p=new x(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(re+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+Y(p));if(!D)return new x(A);for(o=new x(i),b=u=new x(i),P=h=new x(i),I=ue(D),d=o.e=I.length-A.e-1,o.c[0]=vt[(S=d%T)<0?T+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new x(I),h.c[0]=0;f=e(p,o,0,1),g=u.plus(f.times(P)),g.comparedTo(n)!=1;)u=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(u),P,0,1),h=h.plus(g.times(b)),u=u.plus(g.times(P)),h.s=b.s=A.s,d=d*2,w=e(b,P,d,m).minus(A).abs().comparedTo(e(h,u,d,m).minus(A).abs())<1?[b,P]:[h,u],B=S,w},r.toNumber=function(){return+Y(this)},r.toPrecision=function(n,o){return n!=null&&H(n,1,J),Z(this,n,o,2)},r.toString=function(n){var o,u=this,P=u.s,g=u.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=c||g>=y?Ze(ue(u.c),g):xe(ue(u.c),g,"0"):n===10&&U?(u=R(new x(u),a+g+1,m),o=xe(ue(u.c),u.e,"0")):(H(n,2,k.length,"Base"),o=t(xe(ue(u.c),g,"0"),10,n,P,!0)),P<0&&u.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return Y(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,l!=null&&x.set(l),x}function me(l){var e=l|0;return l>0||l===e?e:e-1}function ue(l){for(var e,t,s=1,r=l.length,i=l[0]+"";s<r;){for(e=l[s++]+"",t=T-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function ve(l,e){var t,s,r=l.c,i=e.c,a=l.s,m=e.s,c=l.e,y=e.e;if(!a||!m)return null;if(t=r&&!r[0],s=i&&!i[0],t||s)return t?s?0:-m:a;if(a!=m)return a;if(t=a<0,s=c==y,!r||!i)return s?0:!r^t?1:-1;if(!s)return c>y^t?1:-1;for(m=(c=r.length)<(y=i.length)?c:y,a=0;a<m;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return c==y?0:c>y^t?1:-1}function H(l,e,t,s){if(l<e||l>t||l!==ce(l))throw Error(re+(s||"Argument")+(typeof l=="number"?l<e||l>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(l))}function Ve(l){var e=l.c.length-1;return me(l.e/T)==e&&l.c[e]%2!=0}function Ze(l,e){return(l.length>1?l.charAt(0)+"."+l.slice(1):l)+(e<0?"e":"e+")+e}function xe(l,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);l=r+l}else if(s=l.length,++e>s){for(r=t,e-=s;--e;r+=t);l+=r}else e<s&&(l=l.slice(0,e)+"."+l.slice(e));return l}var q=Ut();var Xt=12;q.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Xt});var E=v(0),ae=v(1),ds=v("Infinity");function K(l,e){let t=new q(e.toString()),s=new q(10).pow(t);return l.times(s)}function v(l){return new q(l.toString())}var ie=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(ie||{}),Ae=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(Ae||{}),It=(t=>(t.Buy="Buy",t.Sell="Sell",t))(It||{});var Pe=require("@galacticcouncil/math-lbp"),pe=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 zt=require("@polkadot/util-crypto"),Wt=require("@polkadot/util"),Ne=18,Qe=15,Oe="0",fs=12,Ps=2034,Te=63,bs=2090,et=1e3,ze=(0,zt.encodeAddress)((0,Wt.stringToU8a)("modlomnipool".padEnd(32,"\0")),Te);function At(l,e){let t=[];return JSON.stringify(l,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function ys(l,e,t){let s;return JSON.stringify(l,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}var Zs=require("@polkadot/types/lookup");var Qs=require("@polkadot/api-base/types/consts");var er=require("@polkadot/api-base/types/errors");var tr=require("@polkadot/api-base/types/events");var sr=require("@polkadot/api-base/types/storage");var rr=require("@polkadot/api-base/types/submittable");var ir=require("@polkadot/rpc-core/types/jsonrpc");var nr=require("@polkadot/api-base/types/calls");var gr=require("@polkadot/types/types/registry");var Pr=require("@polkadot/types/lookup");var br=require("@polkadot/api-base/types/consts");var yr=require("@polkadot/api-base/types/errors");var Sr=require("@polkadot/api-base/types/events");var xr=require("@polkadot/api-base/types/storage");var wr=require("@polkadot/api-base/types/submittable");var Or=require("@polkadot/rpc-core/types/jsonrpc");var Br=require("@polkadot/api-base/types/calls");var Er=require("@polkadot/types/types/registry");var Be=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Fe=class extends Be{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];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([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==Oe){let F=this.api.consts.balances.existentialDeposit;return{id:Oe,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:F.toString()}}let{name:i,assetType:a,isSufficient:m,existentialDeposit:c}=t,{symbol:y,decimals:O}=s.get(e)??{},B=this.parseLocation("parachain",r);return{id:e,name:i.toHuman(),symbol:y,decimals:O,icon:y,type:a.toHuman(),isSufficient:m?m.toHuman():!0,origin:B,externalId:this.parseLocation(2094===B?"generalKey":"generalIndex",r),existentialDeposit:c.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:m,isSufficient:c,existentialDeposit:y}=t,{symbol:O,decimals:B}=this.getToken(i.toString(),t,s),N=a.toNumber(),F=new Intl.DateTimeFormat("en-GB"),_=[O,"Bond",F.format(N)].join(" ");return{id:e,name:_,symbol:O+"b",decimals:B,icon:O,type:m.toString(),isSufficient:c.toHuman(),existentialDeposit:y.toString(),underlyingAssetId:i.toString(),maturity:N}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:m,assetType:c,isSufficient:y,existentialDeposit:O}=t,N=i.map(C=>C.toString()).map(C=>{let{symbol:k}=this.getToken(C,t,s);return[C,k]}),F=Object.fromEntries(N),_=Object.values(F);return{id:e,name:_.join(", "),symbol:m?.isSome?m.toHuman():a.toHuman(),decimals:18,icon:_.join("/"),type:c.toString(),isSufficient:y.toHuman(),existentialDeposit:O.toString(),meta:F}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=s?.find(m=>m.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}: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,t){let[s,r,i,a,m]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),c=this.getSupportedAssets(s),y=this.normalizeMetadata(c,m),O=c.map(([{args:[B]},N])=>{let F=N.unwrap(),_=r.get(B.toString()),{assetType:C}=F;switch(C.toString()){case"Bond":let k=a.get(B.toString());return this.getBond(B.toString(),F,y,k);case"StableSwap":let U=i.get(B.toString());return this.getShares(B.toString(),F,y,U);case"External":return this.getExternal(B.toString(),F,t,_);default:return this.getToken(B.toString(),F,y,_)}});return e?O:O.filter(B=>this.isValidAsset(B))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let s=At(t.toJSON(),e);return s&&s[e]}else return}};var _e=class extends Be{constructor(e){super(e)}async getTokenBalanceData(e,t){let s=this.api.createType("(AssetId, AccountId)",[t,e]),r=await this.api.rpc.state.call("CurrenciesApi_account",s.toHex());return this.api.createType("OrmlTokensAccountData",r)}async getAccountBalanceData(e){let t=this.api.createType("AccountId",e),s=await this.api.rpc.state.call("CurrenciesApi_accounts",t.toHex());return this.api.createType("Vec<(AssetId, OrmlTokensAccountData)>",s)}async getBalance(e,t){let s=this.getTokenBalanceData(e,t);return this.calculateFreeBalance(s)}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:m,frozen:c},y)=>{let O=this.calculateFreeBalance({free:a,feeFrozen:m,frozen:c}),B=r[y][1];s(B,O)})})}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,m)=>{let c=this.calculateFreeBalance(a),y=r[m][1];s(y,c)})})}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 q(t),m=new q(s||i),c=new q(r||0),y=m.gt(c)?m:c;return a.minus(y)}};var Nt=require("@polkadot/util-crypto"),Tt=require("@galacticcouncil/math-liquidity-mining");var tt=class extends Be{constructor(e){super(e)}secondsInYear=new q(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,m=i.unwrap().toString(),c=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(c)).unwrap(),O=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,c,m)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,m=i.unwrap().toString(),c=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(c)).unwrap(),O=(await this.api.query.xykWarehouseLM.yieldFarm(e,c,m)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new q(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),m=a.price.n.toString(),c=a.price.d.toString(),y;return Number(t)<Number(s)?y=(0,Tt.fixed_from_rational)(m,c):y=(0,Tt.fixed_from_rational)(c,m),y}getGlobalRewardPerPeriod(e,t,s,r){let a=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return a.gte(s)?s:a}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,Nt.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,Nt.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:m,globalFarm:c,priceAdjustment:y})=>{let O=new q(c.totalSharesZ.toString()),B=c.plannedYieldingPeriods.toString(),N=new q(c.yieldPerPeriod.toString()),F=new q(c.maxRewardPerPeriod.toString()),_=c.blocksPerPeriod.toString(),C=new q(m.multiplier.toString()).shiftedBy(-18),k=this.secondsInYear.div(new q(s).times(_)),U;if(O.isZero())U=N.times(C).times(k);else{let Se=this.getGlobalRewardPerPeriod(O,N,F,y);U=this.getPoolYieldPerPeriod(Se,C,O,y).times(k)}let x=new q(c.pendingRewards.toString()).plus(c.accumulatedPaidRewards.toString()),Z=F.times(B);return x.div(Z).gte(.99)?E:U.times(100)}).reduce((m,c)=>m.plus(c),E).toString():void 0}};var be=class extends _e{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(ze,[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 st=class extends be{MAX_FINAL_WEIGHT=K(v(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 m=a.unwrap(),c=i.toString(),y=await this.getPoolDelta(c,m,s.toString());return this.poolsData.set(i.toString(),m),{address:c,type:"Lbp",fee:m.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let a=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(m=>m.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:a,initialWeight:m,finalWeight:c,repayTarget:y,feeCollector:O}=t,B=pe.calculateLinearWeights(r.toString(),i.toString(),m.toString(),c.toString(),s),[N,F]=a,_=N.toString(),C=v(B),k=F.toString(),U=this.MAX_FINAL_WEIGHT.minus(v(C)),[x,Z,oe]=await Promise.all([this.isRepayFeeApplied(_,y.toString(),O.toString()),this.getBalance(e,_),this.getBalance(e,k)]);return{repayFeeApply:x,tokens:[{id:_,weight:C,balance:Z.toString()},{id:k,weight:U,balance:oe.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=v(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 Yt=require("@polkadot/util-crypto"),$t=require("@polkadot/util");function Q(l,e){return l.shiftedBy(-1*e).toString()}function ge(l){return l[0]/l[1]*100}function ne(l){return l[0]/l[1]}function de(l){return[l/et,et]}var rt=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:[c]},y])=>{let{hubReserve:O,shares:B,tradable:N}=y.unwrap(),F=await this.getBalance(t,c.toString());return{id:c.toString(),hubReserves:v(O.toString()),shares:v(B.toString()),tradeable:N.bits.toNumber(),balance:F.toString()}}),m=await Promise.all(a);return m.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:m,...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(),m=r.maxFee.toNumber()+i.maxFee.toNumber();if(s.isSome){let{assetFee:c,protocolFee:y}=s.unwrap();return{assetFee:de(c.toNumber()),protocolFee:de(y.toNumber()),min:de(a),max:de(m)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:de(a),max:de(m)}}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 m=r.unwrap();return this.updateTokenState(a,m)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i}=t;return{...e,hubReserves:v(s.toString()),shares:v(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,Yt.encodeAddress)((0,$t.stringToU8a)("modlomnipool".padEnd(32,"\0")),Te)}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 it=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,m]=r.unwrap(),[c,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,m.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:c.toString()},{id:m.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var ot=require("@polkadot/util-crypto");var V=require("@galacticcouncil/math-stableswap"),se=class{static getPoolAddress(e){return(0,V.pool_account_name)(e)}static calculateAmplification(e,t,s,r,i){return(0,V.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return(0,V.calculate_in_given_out)(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return(0,V.calculate_add_one_asset)(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return(0,V.calculate_shares_for_amount)(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return(0,V.calculate_out_given_in)(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return(0,V.calculate_liquidity_out_one_asset)(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return(0,V.calculate_shares)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,V.calculate_pool_trade_fee)(e,t,s)}};var nt=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 m=a.unwrap(),c=i.toString(),y=this.getPoolAddress(c),[O,B]=await Promise.all([this.getPoolDelta(c,m,s.toString()),this.getPoolTokens(y,c,m)]);return this.stablePools.set(y,m),{address:y,id:c,type:"Stableswap",fee:de(m.fee.toNumber()),tokens:B,...O,...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:m}=t,c=se.calculateAmplification(r.toString(),i.toString(),a.toString(),m.toString(),s),y=await this.api.query.tokens.totalIssuance(e);return{amplification:c,totalIssuance:y.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async c=>{let[y,O]=await Promise.all([this.api.query.stableswap.assetTradability(t,c.toString()),this.getBalance(e,c.toString())]);return{id:c.toString(),tradeable:y.bits.toNumber(),balance:O.toString()}}),a=await Promise.all(i),m=await this.api.query.omnipool.assets(t);if(m.isSome){let{tradable:c}=m.unwrap(),y=await this.getBalance(ze,t);a.push({id:t,tradeable:c.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),s=se.getPoolAddress(t);return(0,ot.encodeAddress)((0,ot.blake2AsHex)(s),Te)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function at(l){return l.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 We=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Ft=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ee=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},_t=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Rt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},kt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Re=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new Fe(this.api),this.xykClient=new it(this.api),this.omniClient=new rt(this.api),this.lbpClient=new st(this.api),this.stableClient=new nt(this.api)}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(!1,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(m=>m.isSupported()).map(m=>m.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 We(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(),at(i));let m=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:m}}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(),at(i));let m=()=>a;return{hex:a.toHex(),name:"RouterSell",get:m}}};var Ye=(l,e)=>l===e?0:l==null?e==null?0:-1:e==null?l==null?0:1:typeof l.compare=="function"?l.compare(e):typeof e.compare=="function"?-e.compare(l):l<e?-1:l>e?1:0;var lt=(l,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(l(t)+e(t))}};var Ss=lt(()=>"illegal argument(s)"),jt=l=>{throw new Ss(l)};var xs=lt(()=>"index out of bounds"),Lt=l=>{throw new xs(l)},ut=(l,e,t)=>(l<e||l>=t)&&Lt(l);var Jt=23283064365386963e-26,ct=class{float(e=1){return this.int()*Jt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Jt-.5)*2*e}normMinMax(e,t){let 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 Dt=Math.random,Mt=class extends ct{int(){return Dt()*4294967296>>>0}float(e=1){return Dt()*e}norm(e=1){return(Dt()-.5)*2*e}},Kt=new Mt;var Vt=l=>l!=null&&typeof l!="function"&&l.length!==void 0;var Zt=Object.getPrototypeOf({}),mt="function",Qt="string",ke=(l,e)=>{let t;if(l===e)return!0;if(l!=null){if(typeof l.equiv===mt)return l.equiv(e)}else return l==e;if(e!=null){if(typeof e.equiv===mt)return e.equiv(l)}else return l==e;return typeof l===Qt||typeof e===Qt?!1:(t=Object.getPrototypeOf(l),(t==null||t===Zt)&&(t=Object.getPrototypeOf(e),t==null||t===Zt)?vs(l,e):typeof l!==mt&&l.length!==void 0&&typeof e!==mt&&e.length!==void 0?ws(l,e):l instanceof Set&&e instanceof Set?Os(l,e):l instanceof Map&&e instanceof Map?Bs(l,e):l instanceof Date&&e instanceof Date?l.getTime()===e.getTime():l instanceof RegExp&&e instanceof RegExp?l.toString()===e.toString():l!==l&&e!==e)},ws=(l,e,t=ke)=>{let s=l.length;if(s===e.length)for(;s-- >0&&t(l[s],e[s]););return s<0},Os=(l,e,t=ke)=>l.size===e.size&&t([...l.keys()].sort(),[...e.keys()].sort()),Bs=(l,e,t=ke)=>l.size===e.size&&t([...l].sort(),[...e].sort()),vs=(l,e,t=ke)=>{if(Object.keys(l).length!==Object.keys(e).length)return!1;for(let s in l)if(!e.hasOwnProperty(s)||!t(l[s],e[s]))return!1;return!0};var es=(l,e)=>l!=null&&typeof l[e]=="function";var ts=l=>es(l,"xform")?l.xform():l;var pt=Symbol(),Ct=()=>{};var ss=l=>l!=null&&typeof l[Symbol.iterator]=="function";var gt=class{value;constructor(e){this.value=e}deref(){return this.value}};var ht=l=>l instanceof gt;var rs=l=>l instanceof gt?l.deref():l;function*is(l,e){let t=ts(l)([Ct,Ct,(s,r)=>r])[2];for(let s of e){let r=t(pt,s);if(ht(r)){r=rs(r.deref()),r!==pt&&(yield r);return}r!==pt&&(yield r)}}var ns=(l,e)=>[l[0],l[1],e];function $e(l,e){return ss(e)?is($e(l),e):t=>{let s=t[2];return ns(t,(r,i)=>s(r,l(i)))}}var dt=class l{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return os("next",this._head)}reverseIterator(){return os("prev",this.tail)}clear(){this.release()}compare(e,t=Ye){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 l||Vt(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(!ke(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||Ye;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&&!ht(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&&Lt(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*os(l,e){for(;e;)yield e.value,e=e[l]}var ft=class l extends dt{_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 l(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 l}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):(ut(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):(ut(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new l,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)&&jt("invalid indices: ${from} / ${to}");let i=new l,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=Ye){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 m=t;for(;a>0||m>0&&i;){let c;a===0?(c=i,i=i.next,m--):!i||m===0||e(s.value,i.value)<=0?(c=s,s=s.next,a--):(c=i,i=i.next,m--),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),ut(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new l;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 Pt=class l{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 ft,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 $e(e=>[e.k,e],this.items)}keys(){return $e(e=>e.k,this.items)}values(){return $e(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 l(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 bt=class extends Re{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Pt(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 Le=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,a,m){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=m}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=v(r.balance),m=v(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:m,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 m=this.calculateTradeFee(t,s),c=ge(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(m),O=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return O.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:O,calculatedIn:O,amountOut:t,feePct:c,errors:i}}else{let m=this.calculateInGivenOut(e,t),c=e.balanceIn.div(this.maxInRatio);return m.isGreaterThan(c)&&i.push("MaxInRatioExceeded"),{amountIn:m,calculatedIn:m,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 m=this.calculateOutGivenIn(e,t),c=e.balanceOut.div(this.maxOutRatio);return m.isGreaterThan(c)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:m,amountOut:m,feePct:0,errors:i}}else{let m=this.calculateOutGivenIn(e,t),c=this.calculateTradeFee(m,s),y=ge(this.repayFeeApply?s.repayFee:s.exchangeFee),O=m.minus(c),B=e.balanceOut.div(this.maxOutRatio);return O.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:m,amountOut:O,feePct:y,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=v(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),K(ae,e.decimalsOut).toString());return v(t)}spotPriceOutGivenIn(e){let t=pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),K(ae,e.decimalsIn).toString());return v(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 v(s)}};var M=require("@galacticcouncil/math-omnipool");var W=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,m,c,y){return(0,M.calculate_in_given_out)(e,t,s,r,i,a,m,c,y)}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,m,c,y){return(0,M.calculate_out_given_in)(e,t,s,r,i,a,m,c,y)}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,m,c){return(0,M.calculate_liquidity_out)(e,t,s,r,i,a,m,c)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,m,c){return(0,M.calculate_liquidity_lrna_out)(e,t,s,r,i,a,m,c)}static calculateCapDifference(e,t,s,r){let i=q(t),a=q(e),m=q(r),y=q(s).shiftedBy(-18);if(i.div(m).lt(y)){let B=y.times(m).minus(i).times(a),N=i.times(q(1).minus(y));return B.div(N).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 De=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new l(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(O=>[O.id,O])),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=v(r.balance),m=v(i.balance),c=v(r.existentialDeposit),y=v(i.existentialDeposit);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:m,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:c,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),m=r===E?E:a.div(r).multipliedBy(100).decimalPlaces(2),c=[],y=W.isSellAllowed(e.tradeableIn),O=W.isBuyAllowed(e.tradeableOut);(!y||!O)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&c.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&c.push("MaxOutRatioExceeded");let N=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(N)&&c.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:m.toNumber(),errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),m=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),c=[],y=W.isSellAllowed(e.tradeableIn),O=W.isBuyAllowed(e.tradeableOut);(!y||!O)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&c.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&c.push("MaxInRatioExceeded");let N=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(N)&&c.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:m.toNumber(),errors:c}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=W.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=v(r);return i.isNegative()?E:i}calculateLrnaInGivenOut(e,t,s){let r=W.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ne(s.assetFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=W.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=v(r);return i.isNegative()?E:i}calculateOutGivenLrnaIn(e,t,s){let r=W.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ne(s.assetFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=W.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=W.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=W.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=W.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsIn)).decimalPlaces(0,1)}};var Me=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new l(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,m,c,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=a,this.id=m,this.fee=c,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(O=>[O.id,O])),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=v(r.balance),m=v(i.balance),c=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:m,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?Qe:r.tradeable,tradeableOut:this.id===t?Qe:i.tradeable,assetInED:c,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=ge(s.fee),m=[],c=W.isSellAllowed(e.tradeableIn),y=W.isBuyAllowed(e.tradeableOut);return(!c||!y)&&m.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&m.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a,errors:m}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=ge(s.fee),m=[],c=W.isSellAllowed(e.tradeableIn),y=W.isBuyAllowed(e.tradeableOut);return(!c||!y)&&m.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&m.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:m}}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=v(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=v(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=v(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=K(ae,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,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=v(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=v(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=v(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=K(ae,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=se.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return v(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 $=require("@galacticcouncil/math-xyk"),ye=class{static getSpotPrice(e,t,s){return(0,$.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,$.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,$.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,$.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,$.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,$.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,$.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,$.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,$.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,$.calculate_liquidity_out_asset_b)(e,t,s,r)}};var Ce=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(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(O=>[O.id,O])),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=v(r.balance),m=v(i.balance),c=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:m,assetInED:c,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=ge(s.exchangeFee),m=r.plus(i),c=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&c.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&c.push("MaxOutRatioExceeded");let O=e.balanceIn.div(this.maxInRatio);return m.isGreaterThan(O)&&c.push("MaxInRatioExceeded"),{amountIn:m,calculatedIn:r,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=ge(s.exchangeFee),m=r.minus(i),c=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&c.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&c.push("MaxInRatioExceeded");let O=e.balanceOut.div(this.maxOutRatio);return m.isGreaterThan(O)&&c.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:m,feePct:a,errors:c}}calculateInGivenOut(e,t){let s=ye.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=ye.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=ye.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=K(ae,18-e.decimalsOut);return v(t).div(s)}spotPriceOutGivenIn(e){let t=ye.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=K(ae,18-e.decimalsIn);return v(t).div(s)}calculateTradeFee(e,t){let s=ye.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return v(s)}};var Ge=class{static get(e){switch(e.type){case"Xyk":return Ce.fromPool(e);case"Omnipool":return De.fromPool(e);case"Lbp":return Le.fromPool(e);case"Stableswap":return Me.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Ie=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Xe,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(m=>m[m.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,externalId:r.externalId,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(m=>this.validPath(m,s)).map(m=>this.toHops(m,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,Ge.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 Is(l,e){return l.minus(e).abs().div(l.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function qe(l,e){return l.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Gt(l,e){return ae.minus(e.div(l)).multipliedBy(100).decimalPlaces(2)}function qt(l,e){return e.div(l).minus(ae).multipliedBy(100).decimalPlaces(2)}var je=class extends Ie{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),m=super.getPaths(e,t,a,i);if(m.length===0)throw new Ee(e,t);let c;if(r)c=await this.toSellSwaps(s,r,a);else{let R=m.map(async n=>await this.toSellSwaps(s,n,a)),Y=await Promise.all(R);c=this.findBestSellRoute(Y)}let y=c[0],O=c[c.length-1],B=this.isDirectTrade(c),N=c.map(R=>R.spotPrice.shiftedBy(-1*R.assetOutDecimals)).reduce((R,Y)=>R.multipliedBy(Y)),F=K(N,O.assetOutDecimals),_=B?O.calculatedOut:this.calculateDelta0Y(y.amountIn,c,a),C=O.amountOut,k=B?O.tradeFeePct:Gt(_,C).toNumber(),U=_.minus(C),x=this.getRouteFeeRange(c),Z=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(F),oe=qe(_,Z),Se=R=>this.poolService.buildSellTx(e,t,y.amountIn,R,c.map(Y=>Y));return{type:"Sell",amountIn:y.amountIn,amountOut:O.amountOut,spotPrice:F,tradeFee:U,tradeFeePct:k,tradeFeeRange:x,priceImpactPct:oe.toNumber(),swaps:c,toTx:Se,toHuman(){return{type:"Sell",amountIn:Q(y.amountIn,y.assetInDecimals),amountOut:Q(O.amountOut,O.assetOutDecimals),spotPrice:Q(F,O.assetOutDecimals),tradeFee:Q(U,O.assetOutDecimals),tradeFeePct:k,tradeFeeRange:x,priceImpactPct:oe.toNumber(),swaps:c.map(R=>R.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],m=s.get(a.poolAddress);if(m==null)throw new Error("Pool does not exit");let c=m.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1]:y=e;let O=m.calculateOutGivenIn(c,y);r.push(O)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],m=s.get(a.poolAddress);if(m==null)throw new Error("Pool does not exit");let c=m.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1].amountOut:y=K(v(e),c.decimalsIn).decimalPlaces(0,1);let O=await this.poolService.getPoolFees(c.assetOut,m),{amountOut:B,calculatedOut:N,feePct:F,errors:_}=m.validateAndSell(c,y,O),C=this.getPoolFeeRange(O),k=m.spotPriceOutGivenIn(c),U=y.shiftedBy(-1*c.decimalsIn).multipliedBy(k),x=qe(N,U);r.push({...a,assetInDecimals:c.decimalsIn,assetOutDecimals:c.decimalsOut,amountIn:y,calculatedOut:N,amountOut:B,spotPrice:k,tradeFeePct:F,tradeFeeRange:C,priceImpactPct:x.toNumber(),errors:_,toHuman(){return{...a,amountIn:Q(y,c.decimalsIn),calculatedOut:Q(N,c.decimalsOut),amountOut:Q(B,c.decimalsOut),spotPrice:Q(k,c.decimalsOut),tradeFeePct:F,tradeFeeRange:C,priceImpactPct:x.toNumber(),errors:_}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(x=>x.tokens.find(Z=>Z.id===e)).filter(x=>!!x).sort((x,Z)=>Number(Z.balance)-Number(x.balance)),{balance:m,decimals:c}=a[0],O=v(m).shiftedBy(-1*c).div(100).multipliedBy(.1),B=i.map(async x=>await this.toSellSwaps(O,x,r)),N=await Promise.all(B),F=this.findBestSellRoute(N),_=await this.toSellSwaps("1",F,r),C=_.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,Z)=>x.multipliedBy(Z)),k=_[_.length-1].assetOutDecimals;return{amount:K(C,k),decimals:k}}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),m=super.getPaths(e,t,a,i);if(m.length===0)throw new Ee(e,t);let c;if(r)c=await this.toBuySwaps(s,r,a);else{let R=m.map(async n=>await this.toBuySwaps(s,n,a)),Y=await Promise.all(R);c=this.findBestBuyRoute(Y)}let y=c[c.length-1],O=c[0],B=this.isDirectTrade(c),N=c.map(R=>R.spotPrice.shiftedBy(-1*R.assetInDecimals)).reduce((R,Y)=>R.multipliedBy(Y)),F=K(N,O.assetInDecimals),_=B?O.calculatedIn:this.calculateDelta0X(y.amountOut,c,a),C=O.amountIn,k=B?O.tradeFeePct:qt(_,C).toNumber(),U=C.minus(_),x=this.getRouteFeeRange(c),Z=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(F),oe;_.isZero()?oe=-100:oe=qe(Z,_).toNumber();let Se=R=>this.poolService.buildBuyTx(e,t,y.amountOut,R,c.map(Y=>Y));return{type:"Buy",amountOut:y.amountOut,amountIn:O.amountIn,spotPrice:F,tradeFee:U,tradeFeePct:k,tradeFeeRange:x,priceImpactPct:oe,swaps:c,toTx:Se,toHuman(){return{type:"Buy",amountOut:Q(y.amountOut,y.assetOutDecimals),amountIn:Q(O.amountIn,O.assetInDecimals),spotPrice:Q(F,O.assetInDecimals),tradeFee:Q(U,O.assetInDecimals),tradeFeePct:k,tradeFeeRange:x,priceImpactPct:oe,swaps:c.map(R=>R.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],m=s.get(a.poolAddress);if(m==null)throw new Error("Pool does not exit");let c=m.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=r[0];let O=m.calculateInGivenOut(c,y);r.unshift(O)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],m=s.get(a.poolAddress);if(m==null)throw new Error("Pool does not exit");let c=m.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=K(v(e),c.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let O=await this.poolService.getPoolFees(c.assetOut,m),{amountIn:B,calculatedIn:N,feePct:F,errors:_}=m.validateAndBuy(c,y,O),C=this.getPoolFeeRange(O),k=m.spotPriceInGivenOut(c),U=y.shiftedBy(-1*c.decimalsOut).multipliedBy(k),x;N.isZero()?x=-100:x=qe(U,N).toNumber(),r.unshift({...a,assetInDecimals:c.decimalsIn,assetOutDecimals:c.decimalsOut,amountOut:y,calculatedIn:N,amountIn:B,spotPrice:k,tradeFeePct:F,tradeFeeRange:C,priceImpactPct:x,errors:_,toHuman(){return{...a,amountOut:Q(y,c.decimalsOut),calculatedIn:Q(N,c.decimalsIn),amountIn:Q(B,c.decimalsIn),spotPrice:Q(k,c.decimalsIn),tradeFeePct:F,tradeFeeRange:C,priceImpactPct:x,errors:_}}})}return r}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,FarmClient,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
1
+ "use strict";var wt=Object.defineProperty;var as=Object.getOwnPropertyDescriptor;var ls=Object.getOwnPropertyNames;var us=Object.prototype.hasOwnProperty;var cs=(l,e)=>{for(var t in e)wt(l,t,{get:e[t],enumerable:!0})},ms=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ls(e))!us.call(l,r)&&r!==t&&wt(l,r,{get:()=>e[r],enumerable:!(s=as(e,r))||s.enumerable});return l};var ps=l=>ms(wt({},"__esModule",{value:!0}),l);var As={};cs(As,{AssetClient:()=>Fe,AssetNotFound:()=>_t,BASILISK_PARACHAIN_ID:()=>bs,BalanceClient:()=>_e,BigNumber:()=>q,CachingPoolService:()=>bt,DECIMAL_PLACES:()=>Xt,DENOMINATOR:()=>et,FarmClient:()=>tt,HYDRADX_OMNIPOOL_ADDRESS:()=>ze,HYDRADX_PARACHAIN_ID:()=>Ps,HYDRADX_SS58_PREFIX:()=>Te,INFINITY:()=>ds,LbpMath:()=>pe,LbpPool:()=>Le,ONE:()=>ae,OmniMath:()=>W,OmniPool:()=>De,PoolConfigNotFound:()=>Ft,PoolError:()=>Ae,PoolFactory:()=>Ge,PoolNotFound:()=>We,PoolService:()=>Re,PoolType:()=>ie,ProviderConfigNotFound:()=>kt,RUNTIME_DECIMALS:()=>Ne,RouteNotFound:()=>Ee,Router:()=>Ie,SYSTEM_ASSET_DECIMALS:()=>fs,SYSTEM_ASSET_ID:()=>ve,StableMath:()=>se,StableSwap:()=>Me,StorageConfigNotFound:()=>Et,SubscriptionNotSupported:()=>Rt,TRADEABLE_DEFAULT:()=>Qe,TradeRouter:()=>je,TradeType:()=>It,XykMath:()=>ye,XykPool:()=>Ce,ZERO:()=>E,bnum:()=>v,buildRoute:()=>at,calculateBuyFee:()=>qt,calculateDiffToAvg:()=>Is,calculateDiffToRef:()=>qe,calculateSellFee:()=>Gt,findNestedKey:()=>At,findNestedObj:()=>ys,scale:()=>K});module.exports=ps(As);var Ke=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var gs=5,Ue=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new Ke,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>gs)return r;let m=c[c.length-1];(s===null||m[0]===s)&&r.push(c),e.get(m[0])?.forEach(O=>{if(this.isNotVisited(O,c)){let B=[...c];B.push(O),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),m=parseInt(a);s.get(c)?.push([m,r])}return s}};function xt(l){let e={};for(let t of l){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 Xe=class{getProposals(e,t,s){let r=xt(s),i=Object.keys(r),a=i.map(O=>r[O]).flat(),c=new Ue,m=c.buildAndPopulateGraph(i,a),y=c.findPaths(m,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let 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 hs=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ot=Math.ceil,ce=Math.floor,re="[BigNumber Error] ",Ht=re+"Number primitive has more than 15 significant digits: ",he=1e14,T=14,Bt=9007199254740991,vt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],xe=1e7,J=1e9;function Ut(l){var e,t,s,r=w.prototype={constructor:w,toString:null,valueOf:null},i=new w(1),a=20,c=4,m=-7,y=21,O=-1e7,B=1e7,N=!1,F=1,_=0,C={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},k="0123456789abcdefghijklmnopqrstuvwxyz",U=!0;function w(n,o){var u,P,g,d,S,p,h,b,f=this;if(!(f instanceof w))return new w(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<O?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!hs.test(b=String(n)))return s(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(H(o,2,k.length,"Base"),o==10&&U)return f=new w(n),R(f,a+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return s(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,w.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Ht+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(u=k.slice(0,o),d=S=0,h=b.length;S<h;S++)if(u.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return s(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&w.DEBUG&&h>15&&(n>Bt||n!==ce(n)))throw Error(Ht+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<O)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%T,d<0&&(S+=T),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=T;S<h;)f.c.push(+b.slice(S,S+=T));S=T-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}w.clone=Ut,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(n){var o,u;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(u=n[o],H(u,0,J,o),a=u),n.hasOwnProperty(o="ROUNDING_MODE")&&(u=n[o],H(u,0,8,o),c=u),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(u=n[o],u&&u.pop?(H(u[0],-J,0,o),H(u[1],0,J,o),m=u[0],y=u[1]):(H(u,-J,J,o),m=-(y=u<0?-u:u))),n.hasOwnProperty(o="RANGE"))if(u=n[o],u&&u.pop)H(u[0],-J,-1,o),H(u[1],1,J,o),O=u[0],B=u[1];else if(H(u,-J,J,o),u)O=-(B=u<0?-u:u);else throw Error(re+o+" cannot be zero: "+u);if(n.hasOwnProperty(o="CRYPTO"))if(u=n[o],u===!!u)if(u)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))N=u;else throw N=!u,Error(re+"crypto unavailable");else N=u;else throw Error(re+o+" not true or false: "+u);if(n.hasOwnProperty(o="MODULO_MODE")&&(u=n[o],H(u,0,9,o),F=u),n.hasOwnProperty(o="POW_PRECISION")&&(u=n[o],H(u,0,J,o),_=u),n.hasOwnProperty(o="FORMAT"))if(u=n[o],typeof u=="object")C=u;else throw Error(re+o+" not an object: "+u);if(n.hasOwnProperty(o="ALPHABET"))if(u=n[o],typeof u=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(u))U=u.slice(0,10)=="0123456789",k=u;else throw Error(re+o+" invalid: "+u)}else throw Error(re+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[m,y],RANGE:[O,B],CRYPTO:N,MODULO_MODE:F,POW_PRECISION:_,FORMAT:C,ALPHABET:k}},w.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!w.DEBUG)return!0;var o,u,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-J&&g<=J&&g===ce(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%T,o<1&&(o+=T),String(P[0]).length==o){for(o=0;o<P.length;o++)if(u=P[o],u<0||u>=he||u!==ce(u))break e;if(u!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(re+"Invalid BigNumber: "+n)},w.maximum=w.max=function(){return oe(arguments,-1)},w.minimum=w.min=function(){return oe(arguments,1)},w.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ce(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(u){var P,g,d,S,p,h=0,b=[],f=new w(i);if(u==null?u=a:H(u,0,J),S=Ot(u/T),N)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));h<S;)p=P[h]*131072+(P[h+1]>>>11),p>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(p%1e14),h+=2);h=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);h<S;)p=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],p>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(p%1e14),h+=7);h=S/7}else throw N=!1,Error(re+"crypto unavailable");if(!N)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],u%=T,S&&u&&(p=vt[T-u],b[h]=ce(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=T);for(h=1,p=b[0];p>=10;p/=10,h++);h<T&&(d-=T-h)}return f.e=d,f.c=b,f}}(),w.sum=function(){for(var n=1,o=arguments,u=new w(o[0]);n<o.length;)u=u.plus(o[n++]);return u},t=function(){var n="0123456789";function o(u,P,g,d){for(var S,p=[0],h,b=0,f=u.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(u.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(u,P,g,d,S){var p,h,b,f,x,I,A,D,X=u.indexOf("."),j=a,L=c;for(X>=0&&(f=_,_=0,u=u.replace(".",""),D=new w(P),I=D.pow(u.length-X),_=f,D.c=o(we(ue(I.c),I.e,"0"),10,g,n),D.e=D.c.length),A=o(u,P,g,S?(p=k,n):(p=n,k)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(X<0?--b:(I.c=A,I.e=b,I.s=d,I=e(I,D,j,L,g),A=I.c,x=I.r,b=I.e),h=b+j+1,X=A[h],f=g/2,x=x||h<0||A[h+1]!=null,x=L<4?(X!=null||x)&&(L==0||L==(I.s<0?3:2)):X>f||X==f&&(L==4||x||L==6&&A[h-1]&1||L==(I.s<0?8:7)),h<1||!A[0])u=x?we(p.charAt(1),-j,p.charAt(0)):p.charAt(0);else{if(A.length=h,x)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(X=0,u="";X<=f;u+=p.charAt(A[X++]));u=we(u,b,p.charAt(0))}return u}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,x=P.length,I=g%xe,A=g/xe|0;for(P=P.slice();x--;)h=P[x]%xe,b=P[x]/xe|0,S=A*h+b*I,p=I*h+S%xe*xe+f,f=(p/d|0)+(S/xe|0)+A*b,P[x]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function u(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,x,I,A,D,X,j,L,G,ee,Je,yt,St,fe,He,le=P.s==g.s?1:-1,te=P.c,z=g.c;if(!te||!te[0]||!z||!z[0])return new w(!P.s||!g.s||(te?z&&te[0]==z[0]:!z)?NaN:te&&te[0]==0||!z?le*0:le/0);for(X=new w(le),j=X.c=[],b=P.e-g.e,le=d+b+1,p||(p=he,b=me(P.e/T)-me(g.e/T),le=le/T|0),f=0;z[f]==(te[f]||0);f++);if(z[f]>(te[f]||0)&&b--,le<0)j.push(1),x=!0;else{for(yt=te.length,fe=z.length,f=0,le+=2,I=ce(p/(z[0]+1)),I>1&&(z=n(z,I,p),te=n(te,I,p),fe=z.length,yt=te.length),Je=fe,L=te.slice(0,fe),G=L.length;G<fe;L[G++]=0);He=z.slice(),He=[0].concat(He),St=z[0],z[1]>=p/2&&St++;do{if(I=0,h=o(z,L,fe,G),h<0){if(ee=L[0],fe!=G&&(ee=ee*p+(L[1]||0)),I=ce(ee/St),I>1)for(I>=p&&(I=p-1),A=n(z,I,p),D=A.length,G=L.length;o(A,L,D,G)==1;)I--,u(A,fe<D?He:z,D,p),D=A.length,h=1;else I==0&&(h=I=1),A=z.slice(),D=A.length;if(D<G&&(A=[0].concat(A)),u(L,A,G,p),G=L.length,h==-1)for(;o(z,L,fe,G)<1;)I++,u(L,fe<G?He:z,G,p),G=L.length}else h===0&&(I++,L=[0]);j[f++]=I,L[0]?L[G++]=te[Je]||0:(L=[te[Je]],G=1)}while((Je++<yt||L[0]!=null)&&le--);x=L[0]!=null,j[0]||j.splice(0,1)}if(p==he){for(f=1,le=j[0];le>=10;le/=10,f++);R(X,d+(X.e=f+b*T-1)+1,S,x)}else X.e=b,X.r=+x;return X}}();function Z(n,o,u,P){var g,d,S,p,h;if(u==null?u=c:H(u,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ue(n.c),h=P==1||P==2&&(S<=m||S>=y)?Ze(h,S):we(h,S,"0");else if(n=R(new w(n),o,u),d=n.e,h=ue(n.c),p=h.length,P==1||P==2&&(o<=d||d<=m)){for(;p<o;h+="0",p++);h=Ze(h,d)}else if(o-=S,h=we(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function oe(n,o){for(var u,P,g=1,d=new w(n[0]);g<n.length;g++)P=new w(n[g]),(!P.s||(u=Be(d,P))===o||u===0&&d.s===o)&&(d=P);return d}function Se(n,o,u){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(u=P+u*T-1)>B?n.c=n.e=null:u<O?n.c=[n.e=0]:(n.e=u,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,u=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,h){var b,f=p?S:S.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(x,I,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?I:x}),h&&(b=h,f=f.replace(o,"$1").replace(u,"0.$1")),S!=f))return new w(f,b);if(w.DEBUG)throw Error(re+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function R(n,o,u,P){var g,d,S,p,h,b,f,x=n.c,I=vt;if(x){e:{for(g=1,p=x[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=T,S=o,h=x[b=0],f=ce(h/I[g-S-1]%10);else if(b=Ot((d+1)/T),b>=x.length)if(P){for(;x.length<=b;x.push(0));h=f=0,g=1,d%=T,S=d-T+1}else break e;else{for(h=p=x[b],g=1;p>=10;p/=10,g++);d%=T,S=d-T+g,f=S<0?0:ce(h/I[g-S-1]%10)}if(P=P||o<0||x[b+1]!=null||(S<0?h:h%I[g-S-1]),P=u<4?(f||P)&&(u==0||u==(n.s<0?3:2)):f>5||f==5&&(u==4||P||u==6&&(d>0?S>0?h/I[g-S]:0:x[b-1])%10&1||u==(n.s<0?8:7)),o<1||!x[0])return x.length=0,P?(o-=n.e+1,x[0]=I[(T-o%T)%T],n.e=-o||0):x[0]=n.e=0,n;if(d==0?(x.length=b,p=1,b--):(x.length=b+1,p=I[T-d],x[b]=S>0?ce(h/I[g-S]%I[S])*p:0),P)for(;;)if(b==0){for(d=1,S=x[0];S>=10;S/=10,d++);for(S=x[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,x[0]==he&&(x[0]=1));break}else{if(x[b]+=p,x[b]!=he)break;x[b--]=0,p=1}for(d=x.length;x[--d]===0;x.pop());}n.e>B?n.c=n.e=null:n.e<O&&(n.c=[n.e=0])}return n}function Y(n){var o,u=n.e;return u===null?n.toString():(o=ue(n.c),o=u<=m||u>=y?Ze(o,u):we(o,u,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new w(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return Be(this,new w(n,o))},r.decimalPlaces=r.dp=function(n,o){var u,P,g,d=this;if(n!=null)return H(n,0,J),o==null?o=c:H(o,0,8),R(new w(d),n+d.e+1,o);if(!(u=d.c))return null;if(P=((g=u.length-1)-me(this.e/T))*T,g=u[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 w(n,o),a,c)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new w(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var u,P,g,d,S,p,h,b,f,x=this;if(n=new w(n),n.c&&!n.isInteger())throw Error(re+"Exponent not an integer: "+Y(n));if(o!=null&&(o=new w(o)),p=n.e>14,!x.c||!x.c[0]||x.c[0]==1&&!x.e&&x.c.length==1||!n.c||!n.c[0])return f=new w(Math.pow(+Y(x),p?n.s*(2-Ve(n)):+Y(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new w(NaN);P=!h&&x.isInteger()&&o.isInteger(),P&&(x=x.mod(o))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||p&&x.c[1]>=24e7:x.c[0]<8e13||p&&x.c[0]<=9999975e7)))return d=x.s<0&&Ve(n)?-0:0,x.e>-1&&(d=1/d),new w(h?1/d:d);_&&(d=Ot(_/T+2))}for(p?(u=new w(.5),h&&(n.s=1),b=Ve(n)):(g=Math.abs(+Y(n)),b=g%2),f=new w(i);;){if(b){if(f=f.times(x),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(g){if(g=ce(g/2),g===0)break;b=g%2}else if(n=n.times(u),R(n,n.e+1,1),n.e>14)b=Ve(n);else{if(g=+Y(n),g===0)break;b=g%2}x=x.times(x),d?x.c&&x.c.length>d&&(x.c.length=d):P&&(x=x.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?R(f,_,c,S):f)},r.integerValue=function(n){var o=new w(this);return n==null?n=c:H(n,0,8),R(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return Be(this,new w(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return Be(this,new w(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=Be(this,new w(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&me(this.e/T)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return Be(this,new w(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=Be(this,new w(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 u,P,g,d,S=this,p=S.s;if(n=new w(n,o),o=n.s,!p||!o)return new w(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/T,b=n.e/T,f=S.c,x=n.c;if(!h||!b){if(!f||!x)return f?(n.s=-o,n):new w(x?S:NaN);if(!f[0]||!x[0])return x[0]?(n.s=-o,n):new w(f[0]?S:c==3?-0:0)}if(h=me(h),b=me(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=x),g.reverse(),o=p;o--;g.push(0));g.reverse()}else for(P=(d=(p=f.length)<(o=x.length))?p:o,p=o=0;o<P;o++)if(f[o]!=x[o]){d=f[o]<x[o];break}if(d&&(g=f,f=x,x=g,n.s=-n.s),o=(P=x.length)-(u=f.length),o>0)for(;o--;f[u++]=0);for(o=he-1;P>p;){if(f[--P]<x[P]){for(u=P;u&&!f[--u];f[u]=o);--f[u],f[P]+=he}f[P]-=x[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?Se(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var u,P,g=this;return n=new w(n,o),!g.c||!n.s||n.c&&!n.c[0]?new w(NaN):!n.c||g.c&&!g.c[0]?new w(g):(F==9?(P=n.s,n.s=1,u=e(g,n,0,3),n.s=P,u.s*=P):u=e(g,n,0,F),n=g.minus(u.times(n)),!n.c[0]&&F==1&&(n.s=g.s),n)},r.multipliedBy=r.times=function(n,o){var u,P,g,d,S,p,h,b,f,x,I,A,D,X,j,L=this,G=L.c,ee=(n=new w(n,o)).c;if(!G||!ee||!G[0]||!ee[0])return!L.s||!n.s||G&&!G[0]&&!ee||ee&&!ee[0]&&!G?n.c=n.e=n.s=null:(n.s*=L.s,!G||!ee?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=me(L.e/T)+me(n.e/T),n.s*=L.s,h=G.length,x=ee.length,h<x&&(D=G,G=ee,ee=D,g=h,h=x,x=g),g=h+x,D=[];g--;D.push(0));for(X=he,j=xe,g=x;--g>=0;){for(u=0,I=ee[g]%j,A=ee[g]/j|0,S=h,d=g+S;d>g;)b=G[--S]%j,f=G[S]/j|0,p=A*b+f*I,b=I*b+p%j*j+D[d]+u,u=(b/X|0)+(p/j|0)+A*f,D[d--]=b%X;D[d]=u}return u?++P:D.splice(0,1),Se(n,D,P)},r.negated=function(){var n=new w(this);return n.s=-n.s||null,n},r.plus=function(n,o){var u,P=this,g=P.s;if(n=new w(n,o),o=n.s,!g||!o)return new w(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/T,S=n.e/T,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new w(g/0);if(!p[0]||!h[0])return h[0]?n:new w(p[0]?P:g*0)}if(d=me(d),S=me(S),p=p.slice(),g=d-S){for(g>0?(S=d,u=h):(g=-g,u=p),u.reverse();g--;u.push(0));u.reverse()}for(g=p.length,o=h.length,g-o<0&&(u=h,h=p,p=u,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/he|0,p[o]=he===p[o]?0:p[o]%he;return g&&(p=[g].concat(p),++S),Se(n,p,S)},r.precision=r.sd=function(n,o){var u,P,g,d=this;if(n!=null&&n!==!!n)return H(n,1,J),o==null?o=c:H(o,0,8),R(new w(d),n,o);if(!(u=d.c))return null;if(g=u.length-1,P=g*T+1,g=u[g]){for(;g%10==0;g/=10,P--);for(g=u[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return H(n,-Bt,Bt),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,u,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new w("0.5");if(p!==1||!S||!S[0])return new w(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+Y(d)),p==0||p==1/0?(o=ue(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=me((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),u=new w(o)):u=new w(p+""),u.c[0]){for(h=u.e,p=h+b,p<3&&(p=0);;)if(g=u,u=f.times(g.plus(e(d,g,b,1))),ue(g.c).slice(0,p)===(o=ue(u.c)).slice(0,p))if(u.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(R(g,g.e+a+2,0),g.times(g).eq(d))){u=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(R(u,u.e+a+2,1),n=!u.times(u).eq(d));break}}return R(u,u.e+a+1,c,n)},r.toExponential=function(n,o){return n!=null&&(H(n,0,J),n++),Z(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(H(n,0,J),n=n+this.e+1),Z(this,n,o)},r.toFormat=function(n,o,u){var P,g=this;if(u==null)n!=null&&o&&typeof o=="object"?(u=o,o=null):n&&typeof n=="object"?(u=n,n=o=null):u=C;else if(typeof u!="object")throw Error(re+"Argument not an object: "+u);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+u.groupSize,h=+u.secondaryGroupSize,b=u.groupSeparator||"",f=S[0],x=S[1],I=g.s<0,A=I?f.slice(1):f,D=A.length;if(h&&(d=p,p=h,h=d,D-=d),p>0&&D>0){for(d=D%p||p,f=A.substr(0,d);d<D;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),I&&(f="-"+f)}P=x?f+(u.decimalSeparator||"")+((h=+u.fractionGroupSize)?x.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(u.fractionGroupSeparator||"")):x):f}return(u.prefix||"")+P+(u.suffix||"")},r.toFraction=function(n){var o,u,P,g,d,S,p,h,b,f,x,I,A=this,D=A.c;if(n!=null&&(p=new w(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(re+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+Y(p));if(!D)return new w(A);for(o=new w(i),b=u=new w(i),P=h=new w(i),I=ue(D),d=o.e=I.length-A.e-1,o.c[0]=vt[(S=d%T)<0?T+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new w(I),h.c[0]=0;f=e(p,o,0,1),g=u.plus(f.times(P)),g.comparedTo(n)!=1;)u=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(u),P,0,1),h=h.plus(g.times(b)),u=u.plus(g.times(P)),h.s=b.s=A.s,d=d*2,x=e(b,P,d,c).minus(A).abs().comparedTo(e(h,u,d,c).minus(A).abs())<1?[b,P]:[h,u],B=S,x},r.toNumber=function(){return+Y(this)},r.toPrecision=function(n,o){return n!=null&&H(n,1,J),Z(this,n,o,2)},r.toString=function(n){var o,u=this,P=u.s,g=u.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=m||g>=y?Ze(ue(u.c),g):we(ue(u.c),g,"0"):n===10&&U?(u=R(new w(u),a+g+1,c),o=we(ue(u.c),u.e,"0")):(H(n,2,k.length,"Base"),o=t(we(ue(u.c),g,"0"),10,n,P,!0)),P<0&&u.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return Y(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,l!=null&&w.set(l),w}function me(l){var e=l|0;return l>0||l===e?e:e-1}function ue(l){for(var e,t,s=1,r=l.length,i=l[0]+"";s<r;){for(e=l[s++]+"",t=T-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function Be(l,e){var t,s,r=l.c,i=e.c,a=l.s,c=e.s,m=l.e,y=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=m==y,!r||!i)return s?0:!r^t?1:-1;if(!s)return m>y^t?1:-1;for(c=(m=r.length)<(y=i.length)?m:y,a=0;a<c;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return m==y?0:m>y^t?1:-1}function H(l,e,t,s){if(l<e||l>t||l!==ce(l))throw Error(re+(s||"Argument")+(typeof l=="number"?l<e||l>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(l))}function Ve(l){var e=l.c.length-1;return me(l.e/T)==e&&l.c[e]%2!=0}function Ze(l,e){return(l.length>1?l.charAt(0)+"."+l.slice(1):l)+(e<0?"e":"e+")+e}function we(l,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);l=r+l}else if(s=l.length,++e>s){for(r=t,e-=s;--e;r+=t);l+=r}else e<s&&(l=l.slice(0,e)+"."+l.slice(e));return l}var q=Ut();var Xt=12;q.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Xt});var E=v(0),ae=v(1),ds=v("Infinity");function K(l,e){let t=new q(e.toString()),s=new q(10).pow(t);return l.times(s)}function v(l){return new q(l.toString())}var ie=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(ie||{}),Ae=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(Ae||{}),It=(t=>(t.Buy="Buy",t.Sell="Sell",t))(It||{});var Pe=require("@galacticcouncil/math-lbp"),pe=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 zt=require("@polkadot/util-crypto"),Wt=require("@polkadot/util"),Ne=18,Qe=15,ve="0",fs=12,Ps=2034,Te=63,bs=2090,et=1e3,ze=(0,zt.encodeAddress)((0,Wt.stringToU8a)("modlomnipool".padEnd(32,"\0")),Te);function At(l,e){let t=[];return JSON.stringify(l,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function ys(l,e,t){let s;return JSON.stringify(l,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}var Zs=require("@polkadot/types/lookup");var Qs=require("@polkadot/api-base/types/consts");var er=require("@polkadot/api-base/types/errors");var tr=require("@polkadot/api-base/types/events");var sr=require("@polkadot/api-base/types/storage");var rr=require("@polkadot/api-base/types/submittable");var ir=require("@polkadot/rpc-core/types/jsonrpc");var nr=require("@polkadot/api-base/types/calls");var gr=require("@polkadot/types/types/registry");var Pr=require("@polkadot/types/lookup");var br=require("@polkadot/api-base/types/consts");var yr=require("@polkadot/api-base/types/errors");var Sr=require("@polkadot/api-base/types/events");var wr=require("@polkadot/api-base/types/storage");var xr=require("@polkadot/api-base/types/submittable");var Or=require("@polkadot/rpc-core/types/jsonrpc");var Br=require("@polkadot/api-base/types/calls");var Er=require("@polkadot/types/types/registry");var Oe=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Fe=class extends Oe{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];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([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==ve){let F=this.api.consts.balances.existentialDeposit;return{id:ve,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:F.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:m}=t,{symbol:y,decimals:O}=s.get(e)??{},B=this.parseLocation("parachain",r);return{id:e,name:i.toHuman(),symbol:y,decimals:O,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:B,externalId:this.parseLocation(2094===B?"generalKey":"generalIndex",r),existentialDeposit:m.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:c,isSufficient:m,existentialDeposit:y}=t,{symbol:O,decimals:B}=this.getToken(i.toString(),t,s),N=a.toNumber(),F=new Intl.DateTimeFormat("en-GB"),_=[O,"Bond",F.format(N)].join(" ");return{id:e,name:_,symbol:O+"b",decimals:B,icon:O,type:c.toString(),isSufficient:m.toHuman(),existentialDeposit:y.toString(),underlyingAssetId:i.toString(),maturity:N}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:c,assetType:m,isSufficient:y,existentialDeposit:O}=t,N=i.map(C=>C.toString()).map(C=>{let{symbol:k}=this.getToken(C,t,s);return[C,k]}),F=Object.fromEntries(N),_=Object.values(F);return{id:e,name:_.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:_.join("/"),type:m.toString(),isSufficient:y.toHuman(),existentialDeposit:O.toString(),meta:F}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=s?.find(c=>c.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}: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,t){let[s,r,i,a,c]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),m=this.getSupportedAssets(s),y=this.normalizeMetadata(m,c),O=m.map(([{args:[B]},N])=>{let F=N.unwrap(),_=r.get(B.toString()),{assetType:C}=F;switch(C.toString()){case"Bond":let k=a.get(B.toString());return this.getBond(B.toString(),F,y,k);case"StableSwap":let U=i.get(B.toString());return this.getShares(B.toString(),F,y,U);case"External":return this.getExternal(B.toString(),F,t,_);default:return this.getToken(B.toString(),F,y,_)}});return e?O:O.filter(B=>this.isValidAsset(B))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let s=At(t.toJSON(),e);return s&&s[e]}else return}};var _e=class extends Oe{constructor(e){super(e)}async getTokenBalanceData(e,t){let s=this.api.createType("(AssetId, AccountId)",[t,e]),r=await this.api.rpc.state.call("CurrenciesApi_account",s.toHex());return this.api.createType("OrmlTokensAccountData",r)}async getAccountBalanceData(e){let t=this.api.createType("AccountId",e),s=await this.api.rpc.state.call("CurrenciesApi_accounts",t.toHex());return this.api.createType("Vec<(AssetId, OrmlTokensAccountData)>",s)}async getBalance(e,t){let s=this.getTokenBalanceData(e,t);return this.calculateFreeBalance(s)}async subscribeBalances(e,t){let s=async()=>{let r=[];(await this.getAccountBalanceData(e)).forEach(([a,c])=>{r.push([a.toString(),this.calculateFreeBalance(c)])}),t(r)};return await s(),this.api.rpc.chain.subscribeNewHeads(async()=>{s()})}async subscribeBalance(e,t,s){let r=async()=>{let i=await this.getTokenBalanceData(e,t);s(t.toString(),this.calculateFreeBalance(i))};return await r(),this.api.rpc.chain.subscribeNewHeads(async()=>{r()})}async subscribeTokenBalance(e,t,s){let r=t.filter(i=>i!==ve).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach(({free:a,reserved:c,frozen:m},y)=>{let O=this.calculateFreeBalance({free:a,feeFrozen:c,frozen:m}),B=r[y][1];s(B,O)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(ve,this.calculateFreeBalance(s)))}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,a=new q(t),c=new q(s||i),m=new q(r||0),y=c.gt(m)?c:m;return a.minus(y)}};var Nt=require("@polkadot/util-crypto"),Tt=require("@galacticcouncil/math-liquidity-mining");var tt=class extends Oe{constructor(e){super(e)}secondsInYear=new q(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,c=i.unwrap().toString(),m=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(m)).unwrap(),O=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,m,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,c=i.unwrap().toString(),m=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(m)).unwrap(),O=(await this.api.query.xykWarehouseLM.yieldFarm(e,m,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new q(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),c=a.price.n.toString(),m=a.price.d.toString(),y;return Number(t)<Number(s)?y=(0,Tt.fixed_from_rational)(c,m):y=(0,Tt.fixed_from_rational)(m,c),y}getGlobalRewardPerPeriod(e,t,s,r){let a=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return a.gte(s)?s:a}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,Nt.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,Nt.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:c,globalFarm:m,priceAdjustment:y})=>{let O=new q(m.totalSharesZ.toString()),B=m.plannedYieldingPeriods.toString(),N=new q(m.yieldPerPeriod.toString()),F=new q(m.maxRewardPerPeriod.toString()),_=m.blocksPerPeriod.toString(),C=new q(c.multiplier.toString()).shiftedBy(-18),k=this.secondsInYear.div(new q(s).times(_)),U;if(O.isZero())U=N.times(C).times(k);else{let Se=this.getGlobalRewardPerPeriod(O,N,F,y);U=this.getPoolYieldPerPeriod(Se,C,O,y).times(k)}let w=new q(m.pendingRewards.toString()).plus(m.accumulatedPaidRewards.toString()),Z=F.times(B);return w.div(Z).gte(.99)?E:U.times(100)}).reduce((c,m)=>c.plus(m),E).toString():void 0}};var be=class extends _e{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)];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.subscribeBalances(e.address,this.updateBalancesCallback(e))}subscribeSharePoolBalance(e){return this.subscribeBalance(ze,e.id,this.updateBalanceCallback(e))}updateBalancesCallback(e){return function(t){t.forEach(([s,r])=>{let i=e.tokens.findIndex(a=>a.id==s);i>=0&&(e.tokens[i].balance=r.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(i=>i.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var st=class extends be{MAX_FINAL_WEIGHT=K(v(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(),m=i.toString(),y=await this.getPoolDelta(m,c,s.toString());return this.poolsData.set(i.toString(),c),{address:m,type:"Lbp",fee:c.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let 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:m,repayTarget:y,feeCollector:O}=t,B=pe.calculateLinearWeights(r.toString(),i.toString(),c.toString(),m.toString(),s),[N,F]=a,_=N.toString(),C=v(B),k=F.toString(),U=this.MAX_FINAL_WEIGHT.minus(v(C)),[w,Z,oe]=await Promise.all([this.isRepayFeeApplied(_,y.toString(),O.toString()),this.getBalance(e,_),this.getBalance(e,k)]);return{repayFeeApply:w,tokens:[{id:_,weight:C,balance:Z.toString()},{id:k,weight:U,balance:oe.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=v(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 Yt=require("@polkadot/util-crypto"),$t=require("@polkadot/util");function Q(l,e){return l.shiftedBy(-1*e).toString()}function ge(l){return l[0]/l[1]*100}function ne(l){return l[0]/l[1]}function de(l){return[l/et,et]}var rt=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:[m]},y])=>{let{hubReserve:O,shares:B,tradable:N}=y.unwrap(),F=await this.getBalance(t,m.toString());return{id:m.toString(),hubReserves:v(O.toString()),shares:v(B.toString()),tradeable:N.bits.toNumber(),balance:F.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:m,protocolFee:y}=s.unwrap();return{assetFee:de(m.toNumber()),protocolFee:de(y.toNumber()),min:de(a),max:de(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:de(a),max:de(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(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:v(s.toString()),shares:v(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,Yt.encodeAddress)((0,$t.stringToU8a)("modlomnipool".padEnd(32,"\0")),Te)}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 it=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(),[m,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:m.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var ot=require("@polkadot/util-crypto");var V=require("@galacticcouncil/math-stableswap"),se=class{static getPoolAddress(e){return(0,V.pool_account_name)(e)}static calculateAmplification(e,t,s,r,i){return(0,V.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return(0,V.calculate_in_given_out)(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return(0,V.calculate_add_one_asset)(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return(0,V.calculate_shares_for_amount)(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return(0,V.calculate_out_given_in)(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return(0,V.calculate_liquidity_out_one_asset)(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return(0,V.calculate_shares)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,V.calculate_pool_trade_fee)(e,t,s)}};var nt=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(),m=i.toString(),y=this.getPoolAddress(m),[O,B]=await Promise.all([this.getPoolDelta(m,c,s.toString()),this.getPoolTokens(y,m,c)]);return this.stablePools.set(y,c),{address:y,id:m,type:"Stableswap",fee:de(c.fee.toNumber()),tokens:B,...O,...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,m=se.calculateAmplification(r.toString(),i.toString(),a.toString(),c.toString(),s),y=await this.api.query.tokens.totalIssuance(e);return{amplification:m,totalIssuance:y.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async m=>{let[y,O]=await Promise.all([this.api.query.stableswap.assetTradability(t,m.toString()),this.getBalance(e,m.toString())]);return{id:m.toString(),tradeable:y.bits.toNumber(),balance:O.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:m}=c.unwrap(),y=await this.getBalance(ze,t);a.push({id:t,tradeable:m.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),s=se.getPoolAddress(t);return(0,ot.encodeAddress)((0,ot.blake2AsHex)(s),Te)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function at(l){return l.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 We=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Ft=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ee=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},_t=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Rt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},kt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Re=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new Fe(this.api),this.xykClient=new it(this.api),this.omniClient=new rt(this.api),this.lbpClient=new st(this.api),this.stableClient=new nt(this.api)}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(!1,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 We(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(),at(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(),at(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var Ye=(l,e)=>l===e?0:l==null?e==null?0:-1:e==null?l==null?0:1:typeof l.compare=="function"?l.compare(e):typeof e.compare=="function"?-e.compare(l):l<e?-1:l>e?1:0;var lt=(l,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(l(t)+e(t))}};var Ss=lt(()=>"illegal argument(s)"),jt=l=>{throw new Ss(l)};var ws=lt(()=>"index out of bounds"),Lt=l=>{throw new ws(l)},ut=(l,e,t)=>(l<e||l>=t)&&Lt(l);var Jt=23283064365386963e-26,ct=class{float(e=1){return this.int()*Jt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Jt-.5)*2*e}normMinMax(e,t){let 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 Dt=Math.random,Mt=class extends ct{int(){return Dt()*4294967296>>>0}float(e=1){return Dt()*e}norm(e=1){return(Dt()-.5)*2*e}},Kt=new Mt;var Vt=l=>l!=null&&typeof l!="function"&&l.length!==void 0;var Zt=Object.getPrototypeOf({}),mt="function",Qt="string",ke=(l,e)=>{let t;if(l===e)return!0;if(l!=null){if(typeof l.equiv===mt)return l.equiv(e)}else return l==e;if(e!=null){if(typeof e.equiv===mt)return e.equiv(l)}else return l==e;return typeof l===Qt||typeof e===Qt?!1:(t=Object.getPrototypeOf(l),(t==null||t===Zt)&&(t=Object.getPrototypeOf(e),t==null||t===Zt)?vs(l,e):typeof l!==mt&&l.length!==void 0&&typeof e!==mt&&e.length!==void 0?xs(l,e):l instanceof Set&&e instanceof Set?Os(l,e):l instanceof Map&&e instanceof Map?Bs(l,e):l instanceof Date&&e instanceof Date?l.getTime()===e.getTime():l instanceof RegExp&&e instanceof RegExp?l.toString()===e.toString():l!==l&&e!==e)},xs=(l,e,t=ke)=>{let s=l.length;if(s===e.length)for(;s-- >0&&t(l[s],e[s]););return s<0},Os=(l,e,t=ke)=>l.size===e.size&&t([...l.keys()].sort(),[...e.keys()].sort()),Bs=(l,e,t=ke)=>l.size===e.size&&t([...l].sort(),[...e].sort()),vs=(l,e,t=ke)=>{if(Object.keys(l).length!==Object.keys(e).length)return!1;for(let s in l)if(!e.hasOwnProperty(s)||!t(l[s],e[s]))return!1;return!0};var es=(l,e)=>l!=null&&typeof l[e]=="function";var ts=l=>es(l,"xform")?l.xform():l;var pt=Symbol(),Ct=()=>{};var ss=l=>l!=null&&typeof l[Symbol.iterator]=="function";var gt=class{value;constructor(e){this.value=e}deref(){return this.value}};var ht=l=>l instanceof gt;var rs=l=>l instanceof gt?l.deref():l;function*is(l,e){let t=ts(l)([Ct,Ct,(s,r)=>r])[2];for(let s of e){let r=t(pt,s);if(ht(r)){r=rs(r.deref()),r!==pt&&(yield r);return}r!==pt&&(yield r)}}var ns=(l,e)=>[l[0],l[1],e];function $e(l,e){return ss(e)?is($e(l),e):t=>{let s=t[2];return ns(t,(r,i)=>s(r,l(i)))}}var dt=class l{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return os("next",this._head)}reverseIterator(){return os("prev",this.tail)}clear(){this.release()}compare(e,t=Ye){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 l||Vt(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(!ke(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||Ye;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&&!ht(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&&Lt(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*os(l,e){for(;e;)yield e.value,e=e[l]}var ft=class l extends dt{_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 l(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 l}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):(ut(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):(ut(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new l,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)&&jt("invalid indices: ${from} / ${to}");let i=new l,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=Ye){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 m=0;m<t&&(a++,i=i.next,!!i);m++);let c=t;for(;a>0||c>0&&i;){let m;a===0?(m=i,i=i.next,c--):!i||c===0||e(s.value,i.value)<=0?(m=s,s=s.next,a--):(m=i,i=i.next,c--),this._tail?this._tail.next=m:this._head=m,m.prev=this._tail,this._tail=m}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),ut(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new l;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 Pt=class l{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 ft,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 $e(e=>[e.k,e],this.items)}keys(){return $e(e=>e.k,this.items)}values(){return $e(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 l(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 bt=class extends Re{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Pt(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 Le=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new l(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(m=>[m.id,m])),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=v(r.balance),c=v(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),m=ge(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(c),O=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return O.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:O,calculatedIn:O,amountOut:t,feePct:m,errors:i}}else{let c=this.calculateInGivenOut(e,t),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&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),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),m=this.calculateTradeFee(c,s),y=ge(this.repayFeeApply?s.repayFee:s.exchangeFee),O=c.minus(m),B=e.balanceOut.div(this.maxOutRatio);return O.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:O,feePct:y,errors:i}}}calculateInGivenOut(e,t){let s=pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),K(ae,e.decimalsOut).toString());return v(t)}spotPriceOutGivenIn(e){let t=pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),K(ae,e.decimalsIn).toString());return v(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 v(s)}};var M=require("@galacticcouncil/math-omnipool");var W=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,m,y){return(0,M.calculate_in_given_out)(e,t,s,r,i,a,c,m,y)}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,m,y){return(0,M.calculate_out_given_in)(e,t,s,r,i,a,c,m,y)}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,m){return(0,M.calculate_liquidity_out)(e,t,s,r,i,a,c,m)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,c,m){return(0,M.calculate_liquidity_lrna_out)(e,t,s,r,i,a,c,m)}static calculateCapDifference(e,t,s,r){let i=q(t),a=q(e),c=q(r),y=q(s).shiftedBy(-18);if(i.div(c).lt(y)){let B=y.times(c).minus(i).times(a),N=i.times(q(1).minus(y));return B.div(N).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 De=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new l(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(O=>[O.id,O])),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=v(r.balance),c=v(i.balance),m=v(r.existentialDeposit),y=v(i.existentialDeposit);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,assetInED:m,assetOutED:y}}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),m=[],y=W.isSellAllowed(e.tradeableIn),O=W.isBuyAllowed(e.tradeableOut);(!y||!O)&&m.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&m.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&m.push("MaxOutRatioExceeded");let N=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(N)&&m.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:c.toNumber(),errors:m}}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),m=[],y=W.isSellAllowed(e.tradeableIn),O=W.isBuyAllowed(e.tradeableOut);(!y||!O)&&m.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&m.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&m.push("MaxInRatioExceeded");let N=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(N)&&m.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:c.toNumber(),errors:m}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=W.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=v(r);return i.isNegative()?E:i}calculateLrnaInGivenOut(e,t,s){let r=W.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ne(s.assetFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=W.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=v(r);return i.isNegative()?E:i}calculateOutGivenLrnaIn(e,t,s){let r=W.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ne(s.assetFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=W.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=W.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=W.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=W.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsIn)).decimalPlaces(0,1)}};var Me=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new l(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,m,y){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=m,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(O=>[O.id,O])),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=v(r.balance),c=v(i.balance),m=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?Qe:r.tradeable,tradeableOut:this.id===t?Qe:i.tradeable,assetInED:m,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=ge(s.fee),c=[],m=W.isSellAllowed(e.tradeableIn),y=W.isBuyAllowed(e.tradeableOut);return(!m||!y)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&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=[],m=W.isSellAllowed(e.tradeableIn),y=W.isBuyAllowed(e.tradeableOut);return(!m||!y)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&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=v(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=v(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=v(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=K(ae,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,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=v(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=v(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=v(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=K(ae,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=se.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return v(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 $=require("@galacticcouncil/math-xyk"),ye=class{static getSpotPrice(e,t,s){return(0,$.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,$.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,$.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,$.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,$.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,$.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,$.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,$.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,$.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,$.calculate_liquidity_out_asset_b)(e,t,s,r)}};var Ce=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(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(O=>[O.id,O])),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=v(r.balance),c=v(i.balance),m=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,assetInED:m,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=ge(s.exchangeFee),c=r.plus(i),m=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&m.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&m.push("MaxOutRatioExceeded");let O=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(O)&&m.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:r,amountOut:t,feePct:a,errors:m}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=ge(s.exchangeFee),c=r.minus(i),m=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&m.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&m.push("MaxInRatioExceeded");let O=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(O)&&m.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:a,errors:m}}calculateInGivenOut(e,t){let s=ye.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=ye.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=ye.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=K(ae,18-e.decimalsOut);return v(t).div(s)}spotPriceOutGivenIn(e){let t=ye.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=K(ae,18-e.decimalsIn);return v(t).div(s)}calculateTradeFee(e,t){let s=ye.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return v(s)}};var Ge=class{static get(e){switch(e.type){case"Xyk":return Ce.fromPool(e);case"Omnipool":return De.fromPool(e);case"Lbp":return Le.fromPool(e);case"Stableswap":return Me.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Ie=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Xe,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,externalId:r.externalId,isWhiteListed:r.isWhiteListed}))).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,Ge.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 Is(l,e){return l.minus(e).abs().div(l.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function qe(l,e){return l.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Gt(l,e){return ae.minus(e.div(l)).multipliedBy(100).decimalPlaces(2)}function qt(l,e){return e.div(l).minus(ae).multipliedBy(100).decimalPlaces(2)}var je=class extends Ie{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 Ee(e,t);let m;if(r)m=await this.toSellSwaps(s,r,a);else{let R=c.map(async n=>await this.toSellSwaps(s,n,a)),Y=await Promise.all(R);m=this.findBestSellRoute(Y)}let y=m[0],O=m[m.length-1],B=this.isDirectTrade(m),N=m.map(R=>R.spotPrice.shiftedBy(-1*R.assetOutDecimals)).reduce((R,Y)=>R.multipliedBy(Y)),F=K(N,O.assetOutDecimals),_=B?O.calculatedOut:this.calculateDelta0Y(y.amountIn,m,a),C=O.amountOut,k=B?O.tradeFeePct:Gt(_,C).toNumber(),U=_.minus(C),w=this.getRouteFeeRange(m),Z=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(F),oe=qe(_,Z),Se=R=>this.poolService.buildSellTx(e,t,y.amountIn,R,m.map(Y=>Y));return{type:"Sell",amountIn:y.amountIn,amountOut:O.amountOut,spotPrice:F,tradeFee:U,tradeFeePct:k,tradeFeeRange:w,priceImpactPct:oe.toNumber(),swaps:m,toTx:Se,toHuman(){return{type:"Sell",amountIn:Q(y.amountIn,y.assetInDecimals),amountOut:Q(O.amountOut,O.assetOutDecimals),spotPrice:Q(F,O.assetOutDecimals),tradeFee:Q(U,O.assetOutDecimals),tradeFeePct:k,tradeFeeRange:w,priceImpactPct:oe.toNumber(),swaps:m.map(R=>R.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 m=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1]:y=e;let O=c.calculateOutGivenIn(m,y);r.push(O)}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 m=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1].amountOut:y=K(v(e),m.decimalsIn).decimalPlaces(0,1);let O=await this.poolService.getPoolFees(m.assetOut,c),{amountOut:B,calculatedOut:N,feePct:F,errors:_}=c.validateAndSell(m,y,O),C=this.getPoolFeeRange(O),k=c.spotPriceOutGivenIn(m),U=y.shiftedBy(-1*m.decimalsIn).multipliedBy(k),w=qe(N,U);r.push({...a,assetInDecimals:m.decimalsIn,assetOutDecimals:m.decimalsOut,amountIn:y,calculatedOut:N,amountOut:B,spotPrice:k,tradeFeePct:F,tradeFeeRange:C,priceImpactPct:w.toNumber(),errors:_,toHuman(){return{...a,amountIn:Q(y,m.decimalsIn),calculatedOut:Q(N,m.decimalsOut),amountOut:Q(B,m.decimalsOut),spotPrice:Q(k,m.decimalsOut),tradeFeePct:F,tradeFeeRange:C,priceImpactPct:w.toNumber(),errors:_}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(w=>w.tokens.find(Z=>Z.id===e)).filter(w=>!!w).sort((w,Z)=>Number(Z.balance)-Number(w.balance)),{balance:c,decimals:m}=a[0],O=v(c).shiftedBy(-1*m).div(100).multipliedBy(.1),B=i.map(async w=>await this.toSellSwaps(O,w,r)),N=await Promise.all(B),F=this.findBestSellRoute(N),_=await this.toSellSwaps("1",F,r),C=_.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,Z)=>w.multipliedBy(Z)),k=_[_.length-1].assetOutDecimals;return{amount:K(C,k),decimals:k}}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 Ee(e,t);let m;if(r)m=await this.toBuySwaps(s,r,a);else{let R=c.map(async n=>await this.toBuySwaps(s,n,a)),Y=await Promise.all(R);m=this.findBestBuyRoute(Y)}let y=m[m.length-1],O=m[0],B=this.isDirectTrade(m),N=m.map(R=>R.spotPrice.shiftedBy(-1*R.assetInDecimals)).reduce((R,Y)=>R.multipliedBy(Y)),F=K(N,O.assetInDecimals),_=B?O.calculatedIn:this.calculateDelta0X(y.amountOut,m,a),C=O.amountIn,k=B?O.tradeFeePct:qt(_,C).toNumber(),U=C.minus(_),w=this.getRouteFeeRange(m),Z=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(F),oe;_.isZero()?oe=-100:oe=qe(Z,_).toNumber();let Se=R=>this.poolService.buildBuyTx(e,t,y.amountOut,R,m.map(Y=>Y));return{type:"Buy",amountOut:y.amountOut,amountIn:O.amountIn,spotPrice:F,tradeFee:U,tradeFeePct:k,tradeFeeRange:w,priceImpactPct:oe,swaps:m,toTx:Se,toHuman(){return{type:"Buy",amountOut:Q(y.amountOut,y.assetOutDecimals),amountIn:Q(O.amountIn,O.assetInDecimals),spotPrice:Q(F,O.assetInDecimals),tradeFee:Q(U,O.assetInDecimals),tradeFeePct:k,tradeFeeRange:w,priceImpactPct:oe,swaps:m.map(R=>R.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 m=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=r[0];let O=c.calculateInGivenOut(m,y);r.unshift(O)}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 m=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=K(v(e),m.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let O=await this.poolService.getPoolFees(m.assetOut,c),{amountIn:B,calculatedIn:N,feePct:F,errors:_}=c.validateAndBuy(m,y,O),C=this.getPoolFeeRange(O),k=c.spotPriceInGivenOut(m),U=y.shiftedBy(-1*m.decimalsOut).multipliedBy(k),w;N.isZero()?w=-100:w=qe(U,N).toNumber(),r.unshift({...a,assetInDecimals:m.decimalsIn,assetOutDecimals:m.decimalsOut,amountOut:y,calculatedIn:N,amountIn:B,spotPrice:k,tradeFeePct:F,tradeFeeRange:C,priceImpactPct:w,errors:_,toHuman(){return{...a,amountOut:Q(y,m.decimalsOut),calculatedIn:Q(N,m.decimalsIn),amountIn:Q(B,m.decimalsIn),spotPrice:Q(k,m.decimalsIn),tradeFeePct:F,tradeFeeRange:C,priceImpactPct:w,errors:_}}})}return r}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,FarmClient,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
package/build/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var Xe=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 Kt=5,ve=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 Xe,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let m=i.dequeue();if(m==null||m.length>Kt)return r;let c=m[m.length-1];(s===null||c[0]===s)&&r.push(m),e.get(c[0])?.forEach(O=>{if(this.isNotVisited(O,m)){let B=[...m];B.push(O),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 m=parseInt(i),c=parseInt(a);s.get(m)?.push([c,r])}return s}};function mt(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 Ie=class{getProposals(e,t,s){let r=mt(s),i=Object.keys(r),a=i.map(O=>r[O]).flat(),m=new ve,c=m.buildAndPopulateGraph(i,a),y=m.findPaths(c,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let a=s[i],m=s[i+1];if(m==null)break;r.push(this.toEdge(a,m))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var Vt=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,pt=Math.ceil,oe=Math.floor,Q="[BigNumber Error] ",Bt=Q+"Number primitive has more than 15 significant digits: ",ce=1e14,T=14,gt=9007199254740991,ht=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],be=1e7,$=1e9;function vt(u){var e,t,s,r=x.prototype={constructor:x,toString:null,valueOf:null},i=new x(1),a=20,m=4,c=-7,y=21,O=-1e7,B=1e7,N=!1,F=1,_=0,M={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},k="0123456789abcdefghijklmnopqrstuvwxyz",H=!0;function x(n,o){var l,P,g,d,S,p,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<O?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!Vt.test(b=String(n)))return s(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(q(o,2,k.length,"Base"),o==10&&H)return f=new x(n),E(f,a+f.e+1,m);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return s(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Bt+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=k.slice(0,o),d=S=0,h=b.length;S<h;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return s(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&x.DEBUG&&h>15&&(n>gt||n!==oe(n)))throw Error(Bt+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<O)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%T,d<0&&(S+=T),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=T;S<h;)f.c.push(+b.slice(S,S+=T));S=T-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}x.clone=vt,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),m=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(q(l[0],-$,0,o),q(l[1],0,$,o),c=l[0],y=l[1]):(q(l,-$,$,o),c=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)q(l[0],-$,-1,o),q(l[1],1,$,o),O=l[0],B=l[1];else if(q(l,-$,$,o),l)O=-(B=l<0?-l:l);else throw Error(Q+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))N=l;else throw N=!l,Error(Q+"crypto unavailable");else N=l;else throw Error(Q+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],q(l,0,9,o),F=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],q(l,0,$,o),_=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")M=l;else throw Error(Q+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))H=l.slice(0,10)=="0123456789",k=l;else throw Error(Q+o+" invalid: "+l)}else throw Error(Q+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:m,EXPONENTIAL_AT:[c,y],RANGE:[O,B],CRYPTO:N,MODULO_MODE:F,POW_PRECISION:_,FORMAT:M,ALPHABET:k}},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===oe(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%T,o<1&&(o+=T),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(Q+"Invalid BigNumber: "+n)},x.maximum=x.max=function(){return se(arguments,-1)},x.minimum=x.min=function(){return se(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,S,p,h=0,b=[],f=new x(i);if(l==null?l=a:q(l,0,$),S=pt(l/T),N)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));h<S;)p=P[h]*131072+(P[h+1]>>>11),p>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(p%1e14),h+=2);h=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);h<S;)p=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],p>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(p%1e14),h+=7);h=S/7}else throw N=!1,Error(Q+"crypto unavailable");if(!N)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],l%=T,S&&l&&(p=ht[T-l],b[h]=oe(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=T);for(h=1,p=b[0];p>=10;p/=10,h++);h<T&&(d-=T-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 S,p=[0],h,b=0,f=l.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(l.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(l,P,g,d,S){var p,h,b,f,w,I,A,D,U=l.indexOf("."),Y=a,L=m;for(U>=0&&(f=_,_=0,l=l.replace(".",""),D=new x(P),I=D.pow(l.length-U),_=f,D.c=o(fe(ne(I.c),I.e,"0"),10,g,n),D.e=D.c.length),A=o(l,P,g,S?(p=k,n):(p=n,k)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(U<0?--b:(I.c=A,I.e=b,I.s=d,I=e(I,D,Y,L,g),A=I.c,w=I.r,b=I.e),h=b+Y+1,U=A[h],f=g/2,w=w||h<0||A[h+1]!=null,w=L<4?(U!=null||w)&&(L==0||L==(I.s<0?3:2)):U>f||U==f&&(L==4||w||L==6&&A[h-1]&1||L==(I.s<0?8:7)),h<1||!A[0])l=w?fe(p.charAt(1),-Y,p.charAt(0)):p.charAt(0);else{if(A.length=h,w)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(U=0,l="";U<=f;l+=p.charAt(A[U++]));l=fe(l,b,p.charAt(0))}return l}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,w=P.length,I=g%be,A=g/be|0;for(P=P.slice();w--;)h=P[w]%be,b=P[w]/be|0,S=A*h+b*I,p=I*h+S%be*be+f,f=(p/d|0)+(S/be|0)+A*b,P[w]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function l(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,w,I,A,D,U,Y,L,C,V,Ue,ut,ct,ge,Be,ie=P.s==g.s?1:-1,Z=P.c,X=g.c;if(!Z||!Z[0]||!X||!X[0])return new x(!P.s||!g.s||(Z?X&&Z[0]==X[0]:!X)?NaN:Z&&Z[0]==0||!X?ie*0:ie/0);for(U=new x(ie),Y=U.c=[],b=P.e-g.e,ie=d+b+1,p||(p=ce,b=ae(P.e/T)-ae(g.e/T),ie=ie/T|0),f=0;X[f]==(Z[f]||0);f++);if(X[f]>(Z[f]||0)&&b--,ie<0)Y.push(1),w=!0;else{for(ut=Z.length,ge=X.length,f=0,ie+=2,I=oe(p/(X[0]+1)),I>1&&(X=n(X,I,p),Z=n(Z,I,p),ge=X.length,ut=Z.length),Ue=ge,L=Z.slice(0,ge),C=L.length;C<ge;L[C++]=0);Be=X.slice(),Be=[0].concat(Be),ct=X[0],X[1]>=p/2&&ct++;do{if(I=0,h=o(X,L,ge,C),h<0){if(V=L[0],ge!=C&&(V=V*p+(L[1]||0)),I=oe(V/ct),I>1)for(I>=p&&(I=p-1),A=n(X,I,p),D=A.length,C=L.length;o(A,L,D,C)==1;)I--,l(A,ge<D?Be:X,D,p),D=A.length,h=1;else I==0&&(h=I=1),A=X.slice(),D=A.length;if(D<C&&(A=[0].concat(A)),l(L,A,C,p),C=L.length,h==-1)for(;o(X,L,ge,C)<1;)I++,l(L,ge<C?Be:X,C,p),C=L.length}else h===0&&(I++,L=[0]);Y[f++]=I,L[0]?L[C++]=Z[Ue]||0:(L=[Z[Ue]],C=1)}while((Ue++<ut||L[0]!=null)&&ie--);w=L[0]!=null,Y[0]||Y.splice(0,1)}if(p==ce){for(f=1,ie=Y[0];ie>=10;ie/=10,f++);E(U,d+(U.e=f+b*T-1)+1,S,w)}else U.e=b,U.r=+w;return U}}();function j(n,o,l,P){var g,d,S,p,h;if(l==null?l=m:q(l,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ne(n.c),h=P==1||P==2&&(S<=c||S>=y)?We(h,S):fe(h,S,"0");else if(n=E(new x(n),o,l),d=n.e,h=ne(n.c),p=h.length,P==1||P==2&&(o<=d||d<=c)){for(;p<o;h+="0",p++);h=We(h,d)}else if(o-=S,h=fe(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function se(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=Se(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function de(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*T-1)>B?n.c=n.e=null:l<O?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,S,p,h){var b,f=p?S:S.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(w,I,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?I:w}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new x(f,b);if(x.DEBUG)throw Error(Q+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function E(n,o,l,P){var g,d,S,p,h,b,f,w=n.c,I=ht;if(w){e:{for(g=1,p=w[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=T,S=o,h=w[b=0],f=oe(h/I[g-S-1]%10);else if(b=pt((d+1)/T),b>=w.length)if(P){for(;w.length<=b;w.push(0));h=f=0,g=1,d%=T,S=d-T+1}else break e;else{for(h=p=w[b],g=1;p>=10;p/=10,g++);d%=T,S=d-T+g,f=S<0?0:oe(h/I[g-S-1]%10)}if(P=P||o<0||w[b+1]!=null||(S<0?h:h%I[g-S-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?S>0?h/I[g-S]:0:w[b-1])%10&1||l==(n.s<0?8:7)),o<1||!w[0])return w.length=0,P?(o-=n.e+1,w[0]=I[(T-o%T)%T],n.e=-o||0):w[0]=n.e=0,n;if(d==0?(w.length=b,p=1,b--):(w.length=b+1,p=I[T-d],w[b]=S>0?oe(h/I[g-S]%I[S])*p:0),P)for(;;)if(b==0){for(d=1,S=w[0];S>=10;S/=10,d++);for(S=w[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,w[0]==ce&&(w[0]=1));break}else{if(w[b]+=p,w[b]!=ce)break;w[b--]=0,p=1}for(d=w.length;w[--d]===0;w.pop());}n.e>B?n.c=n.e=null:n.e<O&&(n.c=[n.e=0])}return n}function z(n){var o,l=n.e;return l===null?n.toString():(o=ne(n.c),o=l<=c||l>=y?We(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 Se(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=m:q(o,0,8),E(new x(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-ae(this.e/T))*T,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,m)},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,S,p,h,b,f,w=this;if(n=new x(n),n.c&&!n.isInteger())throw Error(Q+"Exponent not an integer: "+z(n));if(o!=null&&(o=new x(o)),p=n.e>14,!w.c||!w.c[0]||w.c[0]==1&&!w.e&&w.c.length==1||!n.c||!n.c[0])return f=new x(Math.pow(+z(w),p?n.s*(2-ze(n)):+z(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&&w.isInteger()&&o.isInteger(),P&&(w=w.mod(o))}else{if(n.e>9&&(w.e>0||w.e<-1||(w.e==0?w.c[0]>1||p&&w.c[1]>=24e7:w.c[0]<8e13||p&&w.c[0]<=9999975e7)))return d=w.s<0&&ze(n)?-0:0,w.e>-1&&(d=1/d),new x(h?1/d:d);_&&(d=pt(_/T+2))}for(p?(l=new x(.5),h&&(n.s=1),b=ze(n)):(g=Math.abs(+z(n)),b=g%2),f=new x(i);;){if(b){if(f=f.times(w),!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),E(n,n.e+1,1),n.e>14)b=ze(n);else{if(g=+z(n),g===0)break;b=g%2}w=w.times(w),d?w.c&&w.c.length>d&&(w.c.length=d):P&&(w=w.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?E(f,_,m,S):f)},r.integerValue=function(n){var o=new x(this);return n==null?n=m:q(n,0,8),E(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return Se(this,new x(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return Se(this,new x(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=Se(this,new x(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&ae(this.e/T)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return Se(this,new x(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=Se(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,S=this,p=S.s;if(n=new x(n,o),o=n.s,!p||!o)return new x(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/T,b=n.e/T,f=S.c,w=n.c;if(!h||!b){if(!f||!w)return f?(n.s=-o,n):new x(w?S:NaN);if(!f[0]||!w[0])return w[0]?(n.s=-o,n):new x(f[0]?S:m==3?-0:0)}if(h=ae(h),b=ae(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=w),g.reverse(),o=p;o--;g.push(0));g.reverse()}else for(P=(d=(p=f.length)<(o=w.length))?p:o,p=o=0;o<P;o++)if(f[o]!=w[o]){d=f[o]<w[o];break}if(d&&(g=f,f=w,w=g,n.s=-n.s),o=(P=w.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=ce-1;P>p;){if(f[--P]<w[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=ce}f[P]-=w[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?de(n,f,b):(n.s=m==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):(F==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,F),n=g.minus(l.times(n)),!n.c[0]&&F==1&&(n.s=g.s),n)},r.multipliedBy=r.times=function(n,o){var l,P,g,d,S,p,h,b,f,w,I,A,D,U,Y,L=this,C=L.c,V=(n=new x(n,o)).c;if(!C||!V||!C[0]||!V[0])return!L.s||!n.s||C&&!C[0]&&!V||V&&!V[0]&&!C?n.c=n.e=n.s=null:(n.s*=L.s,!C||!V?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=ae(L.e/T)+ae(n.e/T),n.s*=L.s,h=C.length,w=V.length,h<w&&(D=C,C=V,V=D,g=h,h=w,w=g),g=h+w,D=[];g--;D.push(0));for(U=ce,Y=be,g=w;--g>=0;){for(l=0,I=V[g]%Y,A=V[g]/Y|0,S=h,d=g+S;d>g;)b=C[--S]%Y,f=C[S]/Y|0,p=A*b+f*I,b=I*b+p%Y*Y+D[d]+l,l=(b/U|0)+(p/Y|0)+A*f,D[d--]=b%U;D[d]=l}return l?++P:D.splice(0,1),de(n,D,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/T,S=n.e/T,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new x(g/0);if(!p[0]||!h[0])return h[0]?n:new x(p[0]?P:g*0)}if(d=ae(d),S=ae(S),p=p.slice(),g=d-S){for(g>0?(S=d,l=h):(g=-g,l=p),l.reverse();g--;l.push(0));l.reverse()}for(g=p.length,o=h.length,g-o<0&&(l=h,h=p,p=l,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/ce|0,p[o]=ce===p[o]?0:p[o]%ce;return g&&(p=[g].concat(p),++S),de(n,p,S)},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=m:q(o,0,8),E(new x(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*T+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,-gt,gt),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,l,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new x("0.5");if(p!==1||!S||!S[0])return new x(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+z(d)),p==0||p==1/0?(o=ne(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=ae((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new x(o)):l=new x(p+""),l.c[0]){for(h=l.e,p=h+b,p<3&&(p=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ne(g.c).slice(0,p)===(o=ne(l.c)).slice(0,p))if(l.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(E(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(E(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return E(l,l.e+a+1,m,n)},r.toExponential=function(n,o){return n!=null&&(q(n,0,$),n++),j(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(q(n,0,$),n=n+this.e+1),j(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=M;else if(typeof l!="object")throw Error(Q+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],w=S[1],I=g.s<0,A=I?f.slice(1):f,D=A.length;if(h&&(d=p,p=h,h=d,D-=d),p>0&&D>0){for(d=D%p||p,f=A.substr(0,d);d<D;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),I&&(f="-"+f)}P=w?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?w.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):w):f}return(l.prefix||"")+P+(l.suffix||"")},r.toFraction=function(n){var o,l,P,g,d,S,p,h,b,f,w,I,A=this,D=A.c;if(n!=null&&(p=new x(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(Q+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+z(p));if(!D)return new x(A);for(o=new x(i),b=l=new x(i),P=h=new x(i),I=ne(D),d=o.e=I.length-A.e-1,o.c[0]=ht[(S=d%T)<0?T+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new x(I),h.c[0]=0;f=e(p,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,w=e(b,P,d,m).minus(A).abs().comparedTo(e(h,l,d,m).minus(A).abs())<1?[b,P]:[h,l],B=S,w},r.toNumber=function(){return+z(this)},r.toPrecision=function(n,o){return n!=null&&q(n,1,$),j(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>=y?We(ne(l.c),g):fe(ne(l.c),g,"0"):n===10&&H?(l=E(new x(l),a+g+1,m),o=fe(ne(l.c),l.e,"0")):(q(n,2,k.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 z(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,u!=null&&x.set(u),x}function ae(u){var e=u|0;return u>0||u===e?e:e-1}function ne(u){for(var e,t,s=1,r=u.length,i=u[0]+"";s<r;){for(e=u[s++]+"",t=T-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function Se(u,e){var t,s,r=u.c,i=e.c,a=u.s,m=e.s,c=u.e,y=e.e;if(!a||!m)return null;if(t=r&&!r[0],s=i&&!i[0],t||s)return t?s?0:-m:a;if(a!=m)return a;if(t=a<0,s=c==y,!r||!i)return s?0:!r^t?1:-1;if(!s)return c>y^t?1:-1;for(m=(c=r.length)<(y=i.length)?c:y,a=0;a<m;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return c==y?0:c>y^t?1:-1}function q(u,e,t,s){if(u<e||u>t||u!==oe(u))throw Error(Q+(s||"Argument")+(typeof u=="number"?u<e||u>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(u))}function ze(u){var e=u.c.length-1;return ae(u.e/T)==e&&u.c[e]%2!=0}function We(u,e){return(u.length>1?u.charAt(0)+"."+u.slice(1):u)+(e<0?"e":"e+")+e}function fe(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 G=vt();var Zt=12;G.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Zt});var R=v(0),le=v(1),dr=v("Infinity");function J(u,e){let t=new G(e.toString()),s=new G(10).pow(t);return u.times(s)}function v(u){return new G(u.toString())}var re=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(re||{}),Ae=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(Ae||{}),It=(t=>(t.Buy="Buy",t.Sell="Sell",t))(It||{});import{calculate_in_given_out as Qt,calculate_out_given_in as es,calculate_linear_weights as ts,calculate_pool_trade_fee as ss,get_spot_price as rs}from"@galacticcouncil/math-lbp";var me=class{static getSpotPrice(e,t,s,r,i){return rs(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return Qt(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return es(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return ts(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return ss(e,t,s)}};import{encodeAddress as is}from"@polkadot/util-crypto";import{stringToU8a as ns}from"@polkadot/util";var Ne=18,dt=15,xe="0",wr=12,Or=2034,Te=63,Br=2090,ft=1e3,Ye=is(ns("modlomnipool".padEnd(32,"\0")),Te);function At(u,e){let t=[];return JSON.stringify(u,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function Ir(u,e,t){let s;return JSON.stringify(u,(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 ye=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Fe=class extends ye{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];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([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==xe){let F=this.api.consts.balances.existentialDeposit;return{id:xe,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:F.toString()}}let{name:i,assetType:a,isSufficient:m,existentialDeposit:c}=t,{symbol:y,decimals:O}=s.get(e)??{},B=this.parseLocation("parachain",r);return{id:e,name:i.toHuman(),symbol:y,decimals:O,icon:y,type:a.toHuman(),isSufficient:m?m.toHuman():!0,origin:B,externalId:this.parseLocation(2094===B?"generalKey":"generalIndex",r),existentialDeposit:c.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:m,isSufficient:c,existentialDeposit:y}=t,{symbol:O,decimals:B}=this.getToken(i.toString(),t,s),N=a.toNumber(),F=new Intl.DateTimeFormat("en-GB"),_=[O,"Bond",F.format(N)].join(" ");return{id:e,name:_,symbol:O+"b",decimals:B,icon:O,type:m.toString(),isSufficient:c.toHuman(),existentialDeposit:y.toString(),underlyingAssetId:i.toString(),maturity:N}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:m,assetType:c,isSufficient:y,existentialDeposit:O}=t,N=i.map(M=>M.toString()).map(M=>{let{symbol:k}=this.getToken(M,t,s);return[M,k]}),F=Object.fromEntries(N),_=Object.values(F);return{id:e,name:_.join(", "),symbol:m?.isSome?m.toHuman():a.toHuman(),decimals:18,icon:_.join("/"),type:c.toString(),isSufficient:y.toHuman(),existentialDeposit:O.toString(),meta:F}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=s?.find(m=>m.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}: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,t){let[s,r,i,a,m]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),c=this.getSupportedAssets(s),y=this.normalizeMetadata(c,m),O=c.map(([{args:[B]},N])=>{let F=N.unwrap(),_=r.get(B.toString()),{assetType:M}=F;switch(M.toString()){case"Bond":let k=a.get(B.toString());return this.getBond(B.toString(),F,y,k);case"StableSwap":let H=i.get(B.toString());return this.getShares(B.toString(),F,y,H);case"External":return this.getExternal(B.toString(),F,t,_);default:return this.getToken(B.toString(),F,y,_)}});return e?O:O.filter(B=>this.isValidAsset(B))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let s=At(t.toJSON(),e);return s&&s[e]}else return}};var _e=class extends ye{constructor(e){super(e)}async getTokenBalanceData(e,t){let s=this.api.createType("(AssetId, AccountId)",[t,e]),r=await this.api.rpc.state.call("CurrenciesApi_account",s.toHex());return this.api.createType("OrmlTokensAccountData",r)}async getAccountBalanceData(e){let t=this.api.createType("AccountId",e),s=await this.api.rpc.state.call("CurrenciesApi_accounts",t.toHex());return this.api.createType("Vec<(AssetId, OrmlTokensAccountData)>",s)}async getBalance(e,t){let s=this.getTokenBalanceData(e,t);return this.calculateFreeBalance(s)}async subscribeBalance(e,t,s){let r=t.filter(i=>i!==xe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach(({free:a,reserved:m,frozen:c},y)=>{let O=this.calculateFreeBalance({free:a,feeFrozen:m,frozen:c}),B=r[y][1];s(B,O)})})}async subscribeTokenBalance(e,t,s){let r=t.filter(i=>i!==xe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach((a,m)=>{let c=this.calculateFreeBalance(a),y=r[m][1];s(y,c)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(xe,this.calculateFreeBalance(s)))}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,a=new G(t),m=new G(s||i),c=new G(r||0),y=m.gt(c)?m:c;return a.minus(y)}};import{isAddress as Nt}from"@polkadot/util-crypto";import{fixed_from_rational as Tt}from"@galacticcouncil/math-liquidity-mining";var Pt=class extends ye{constructor(e){super(e)}secondsInYear=new G(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,m=i.unwrap().toString(),c=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(c)).unwrap(),O=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,c,m)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,m=i.unwrap().toString(),c=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(c)).unwrap(),O=(await this.api.query.xykWarehouseLM.yieldFarm(e,c,m)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new G(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),m=a.price.n.toString(),c=a.price.d.toString(),y;return Number(t)<Number(s)?y=Tt(m,c):y=Tt(c,m),y}getGlobalRewardPerPeriod(e,t,s,r){let a=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return a.gte(s)?s:a}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!Nt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&Nt(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:m,globalFarm:c,priceAdjustment:y})=>{let O=new G(c.totalSharesZ.toString()),B=c.plannedYieldingPeriods.toString(),N=new G(c.yieldPerPeriod.toString()),F=new G(c.maxRewardPerPeriod.toString()),_=c.blocksPerPeriod.toString(),M=new G(m.multiplier.toString()).shiftedBy(-18),k=this.secondsInYear.div(new G(s).times(_)),H;if(O.isZero())H=N.times(M).times(k);else{let de=this.getGlobalRewardPerPeriod(O,N,F,y);H=this.getPoolYieldPerPeriod(de,M,O,y).times(k)}let x=new G(c.pendingRewards.toString()).plus(c.accumulatedPaidRewards.toString()),j=F.times(B);return x.div(j).gte(.99)?R:H.times(100)}).reduce((m,c)=>m.plus(c),R).toString():void 0}};var he=class extends _e{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(Ye,[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 $e=class extends he{MAX_FINAL_WEIGHT=J(v(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 m=a.unwrap(),c=i.toString(),y=await this.getPoolDelta(c,m,s.toString());return this.poolsData.set(i.toString(),m),{address:c,type:"Lbp",fee:m.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let a=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(m=>m.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:a,initialWeight:m,finalWeight:c,repayTarget:y,feeCollector:O}=t,B=me.calculateLinearWeights(r.toString(),i.toString(),m.toString(),c.toString(),s),[N,F]=a,_=N.toString(),M=v(B),k=F.toString(),H=this.MAX_FINAL_WEIGHT.minus(v(M)),[x,j,se]=await Promise.all([this.isRepayFeeApplied(_,y.toString(),O.toString()),this.getBalance(e,_),this.getBalance(e,k)]);return{repayFeeApply:x,tokens:[{id:_,weight:M,balance:j.toString()},{id:k,weight:H,balance:se.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=v(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 os}from"@polkadot/util-crypto";import{stringToU8a as as}from"@polkadot/util";function K(u,e){return u.shiftedBy(-1*e).toString()}function ue(u){return u[0]/u[1]*100}function ee(u){return u[0]/u[1]}function pe(u){return[u/ft,ft]}var je=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]},y])=>{let{hubReserve:O,shares:B,tradable:N}=y.unwrap(),F=await this.getBalance(t,c.toString());return{id:c.toString(),hubReserves:v(O.toString()),shares:v(B.toString()),tradeable:N.bits.toNumber(),balance:F.toString()}}),m=await Promise.all(a);return m.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:m,...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(),m=r.maxFee.toNumber()+i.maxFee.toNumber();if(s.isSome){let{assetFee:c,protocolFee:y}=s.unwrap();return{assetFee:pe(c.toNumber()),protocolFee:pe(y.toNumber()),min:pe(a),max:pe(m)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:pe(a),max:pe(m)}}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 m=r.unwrap();return this.updateTokenState(a,m)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i}=t;return{...e,hubReserves:v(s.toString()),shares:v(r.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return pe(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return pe(t)}getPoolId(){return os(as("modlomnipool".padEnd(32,"\0")),Te)}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 Je=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,m]=r.unwrap(),[c,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,m.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:c.toString()},{id:m.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{blake2AsHex as Ps,encodeAddress as bs}from"@polkadot/util-crypto";import{calculate_in_given_out as ls,calculate_out_given_in as us,calculate_amplification as cs,calculate_add_one_asset as ms,calculate_liquidity_out_one_asset as ps,calculate_pool_trade_fee as gs,calculate_shares as hs,calculate_shares_for_amount as ds,pool_account_name as fs}from"@galacticcouncil/math-stableswap";var te=class{static getPoolAddress(e){return fs(e)}static calculateAmplification(e,t,s,r,i){return cs(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return ls(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return ms(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return ds(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return us(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return ps(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return hs(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return gs(e,t,s)}};var Ke=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 m=a.unwrap(),c=i.toString(),y=this.getPoolAddress(c),[O,B]=await Promise.all([this.getPoolDelta(c,m,s.toString()),this.getPoolTokens(y,c,m)]);return this.stablePools.set(y,m),{address:y,id:c,type:"Stableswap",fee:pe(m.fee.toNumber()),tokens:B,...O,...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:m}=t,c=te.calculateAmplification(r.toString(),i.toString(),a.toString(),m.toString(),s),y=await this.api.query.tokens.totalIssuance(e);return{amplification:c,totalIssuance:y.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async c=>{let[y,O]=await Promise.all([this.api.query.stableswap.assetTradability(t,c.toString()),this.getBalance(e,c.toString())]);return{id:c.toString(),tradeable:y.bits.toNumber(),balance:O.toString()}}),a=await Promise.all(i),m=await this.api.query.omnipool.assets(t);if(m.isSome){let{tradable:c}=m.unwrap(),y=await this.getBalance(Ye,t);a.push({id:t,tradeable:c.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),s=te.getPoolAddress(t);return bs(Ps(s),Te)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function bt(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 Ve=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Ft=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ee=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},_t=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Rt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},kt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Re=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new Fe(this.api),this.xykClient=new Je(this.api),this.omniClient=new je(this.api),this.lbpClient=new $e(this.api),this.stableClient=new Ke(this.api)}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(!1,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(m=>m.isSupported()).map(m=>m.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 Ve(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(),bt(i));let m=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:m}}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(),bt(i));let m=()=>a;return{hex:a.toHex(),name:"RouterSell",get:m}}};var ke=(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 Ze=(u,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(u(t)+e(t))}};var ys=Ze(()=>"illegal argument(s)"),Lt=u=>{throw new ys(u)};var Ss=Ze(()=>"index out of bounds"),yt=u=>{throw new Ss(u)},Qe=(u,e,t)=>(u<e||u>=t)&&yt(u);var Dt=23283064365386963e-26,et=class{float(e=1){return this.int()*Dt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Dt-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var St=Math.random,xt=class extends et{int(){return St()*4294967296>>>0}float(e=1){return St()*e}norm(e=1){return(St()-.5)*2*e}},Mt=new xt;var Ct=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var Gt=Object.getPrototypeOf({}),tt="function",qt="string",we=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===tt)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===tt)return e.equiv(u)}else return u==e;return typeof u===qt||typeof e===qt?!1:(t=Object.getPrototypeOf(u),(t==null||t===Gt)&&(t=Object.getPrototypeOf(e),t==null||t===Gt)?Bs(u,e):typeof u!==tt&&u.length!==void 0&&typeof e!==tt&&e.length!==void 0?xs(u,e):u instanceof Set&&e instanceof Set?ws(u,e):u instanceof Map&&e instanceof Map?Os(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)},xs=(u,e,t=we)=>{let s=u.length;if(s===e.length)for(;s-- >0&&t(u[s],e[s]););return s<0},ws=(u,e,t=we)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),Os=(u,e,t=we)=>u.size===e.size&&t([...u].sort(),[...e].sort()),Bs=(u,e,t=we)=>{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 Ht=(u,e)=>u!=null&&typeof u[e]=="function";var Ut=u=>Ht(u,"xform")?u.xform():u;var st=Symbol(),wt=()=>{};var Xt=u=>u!=null&&typeof u[Symbol.iterator]=="function";var rt=class{value;constructor(e){this.value=e}deref(){return this.value}};var it=u=>u instanceof rt;var zt=u=>u instanceof rt?u.deref():u;function*Wt(u,e){let t=Ut(u)([wt,wt,(s,r)=>r])[2];for(let s of e){let r=t(st,s);if(it(r)){r=zt(r.deref()),r!==st&&(yield r);return}r!==st&&(yield r)}}var Yt=(u,e)=>[u[0],u[1],e];function Le(u,e){return Xt(e)?Wt(Le(u),e):t=>{let s=t[2];return Yt(t,(r,i)=>s(r,u(i)))}}var nt=class u{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return $t("next",this._head)}reverseIterator(){return $t("prev",this.tail)}clear(){this.release()}compare(e,t=ke){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 u||Ct(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(!we(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||ke;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&&!it(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&&yt(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*$t(u,e){for(;e;)yield e.value,e=e[u]}var ot=class u extends nt{_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 u(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 u}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):(Qe(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):(Qe(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new u,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=Mt){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)&&Lt("invalid indices: ${from} / ${to}");let i=new u,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=ke){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 m=t;for(;a>0||m>0&&i;){let c;a===0?(c=i,i=i.next,m--):!i||m===0||e(s.value,i.value)<=0?(c=s,s=s.next,a--):(c=i,i=i.next,m--),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),Qe(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new u;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 at=class u{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 ot,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 Le(e=>[e.k,e],this.items)}keys(){return Le(e=>e.k,this.items)}values(){return Le(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 u(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 Re{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new at(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 De=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,a,m){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=m}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=v(r.balance),m=v(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:m,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 m=this.calculateTradeFee(t,s),c=ue(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(m),O=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return O.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:O,calculatedIn:O,amountOut:t,feePct:c,errors:i}}else{let m=this.calculateInGivenOut(e,t),c=e.balanceIn.div(this.maxInRatio);return m.isGreaterThan(c)&&i.push("MaxInRatioExceeded"),{amountIn:m,calculatedIn:m,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 m=this.calculateOutGivenIn(e,t),c=e.balanceOut.div(this.maxOutRatio);return m.isGreaterThan(c)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:m,amountOut:m,feePct:0,errors:i}}else{let m=this.calculateOutGivenIn(e,t),c=this.calculateTradeFee(m,s),y=ue(this.repayFeeApply?s.repayFee:s.exchangeFee),O=m.minus(c),B=e.balanceOut.div(this.maxOutRatio);return O.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:m,amountOut:O,feePct:y,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=v(s);return r.isNegative()?R:r}calculateOutGivenIn(e,t){let s=me.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?R:r}spotPriceInGivenOut(e){let t=me.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),J(le,e.decimalsOut).toString());return v(t)}spotPriceOutGivenIn(e){let t=me.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),J(le,e.decimalsIn).toString());return v(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 v(s)}};import{calculate_in_given_out as vs,calculate_lrna_in_given_out as Is,calculate_out_given_in as As,calculate_out_given_lrna_in as Ns,calculate_pool_trade_fee as Ts,calculate_spot_price as Fs,calculate_lrna_spot_price as _s,calculate_shares as Es,calculate_liquidity_out as Rs,calculate_liquidity_lrna_out as ks,verify_asset_cap as Ls,calculate_liquidity_hub_in as Ds,is_sell_allowed as Ms,is_buy_allowed as Cs,is_add_liquidity_allowed as Gs,is_remove_liquidity_allowed as qs}from"@galacticcouncil/math-omnipool";var W=class{static calculateSpotPrice(e,t,s,r){return Fs(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return _s(e,t)}static calculateInGivenOut(e,t,s,r,i,a,m,c,y){return vs(e,t,s,r,i,a,m,c,y)}static calculateLrnaInGivenOut(e,t,s,r,i){return Is(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,a,m,c,y){return As(e,t,s,r,i,a,m,c,y)}static calculateOutGivenLrnaIn(e,t,s,r,i){return Ns(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Ts(e,t,s)}static calculateShares(e,t,s,r){return Es(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,a,m,c){return Rs(e,t,s,r,i,a,m,c)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,m,c){return ks(e,t,s,r,i,a,m,c)}static calculateCapDifference(e,t,s,r){let i=G(t),a=G(e),m=G(r),y=G(s).shiftedBy(-18);if(i.div(m).lt(y)){let B=y.times(m).minus(i).times(a),N=i.times(G(1).minus(y));return B.div(N).toFixed(0)}else return"0"}static verifyAssetCap(e,t,s,r){return Ls(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return Ds(e,t,s,r)}static isSellAllowed(e){return Ms(e)}static isBuyAllowed(e){return Cs(e)}static isAddLiquidityAllowed(e){return Gs(e)}static isRemoveLiquidityAllowed(e){return qs(e)}};var Me=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new u(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(O=>[O.id,O])),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=v(r.balance),m=v(i.balance),c=v(r.existentialDeposit),y=v(i.existentialDeposit);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:m,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:c,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),m=r===R?R:a.div(r).multipliedBy(100).decimalPlaces(2),c=[],y=W.isSellAllowed(e.tradeableIn),O=W.isBuyAllowed(e.tradeableOut);(!y||!O)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&c.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&c.push("MaxOutRatioExceeded");let N=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(N)&&c.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:m.toNumber(),errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),m=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),c=[],y=W.isSellAllowed(e.tradeableIn),O=W.isBuyAllowed(e.tradeableOut);(!y||!O)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&c.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&c.push("MaxInRatioExceeded");let N=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(N)&&c.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:m.toNumber(),errors:c}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=W.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():R.toString(),s?ee(s.protocolFee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateLrnaInGivenOut(e,t,s){let r=W.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=W.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():R.toString(),s?ee(s.protocolFee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateOutGivenLrnaIn(e,t,s){let r=W.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=W.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=W.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=W.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=W.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsIn)).decimalPlaces(0,1)}};var Ce=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new u(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,m,c,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=a,this.id=m,this.fee=c,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(O=>[O.id,O])),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=v(r.balance),m=v(i.balance),c=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:m,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?dt:r.tradeable,tradeableOut:this.id===t?dt:i.tradeable,assetInED:c,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=ue(s.fee),m=[],c=W.isSellAllowed(e.tradeableIn),y=W.isBuyAllowed(e.tradeableOut);return(!c||!y)&&m.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&m.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a,errors:m}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=ue(s.fee),m=[],c=W.isSellAllowed(e.tradeableIn),y=W.isBuyAllowed(e.tradeableOut);return(!c||!y)&&m.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&m.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:m}}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():R.toString()),i=v(r);return i.isNegative()?R: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():R.toString()),i=v(r);return i.isNegative()?R: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():R.toString()),i=v(r);return i.isNegative()?R: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(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():R.toString()),i=v(r);return i.isNegative()?R: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():R.toString()),i=v(r);return i.isNegative()?R: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():R.toString()),i=v(r);return i.isNegative()?R: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(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 v(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 Hs,calculate_out_given_in as Us,calculate_pool_trade_fee as Xs,get_spot_price as zs,calculate_liquidity_in as Ws,calculate_shares as Ys,calculate_spot_price as $s,calculate_spot_price_with_fee as js,calculate_liquidity_out_asset_a as Js,calculate_liquidity_out_asset_b as Ks}from"@galacticcouncil/math-xyk";var Pe=class{static getSpotPrice(e,t,s){return zs(e,t,s)}static calculateInGivenOut(e,t,s){return Hs(e,t,s)}static calculateOutGivenIn(e,t,s){return Us(e,t,s)}static calculatePoolTradeFee(e,t,s){return Xs(e,t,s)}static calculateLiquidityIn(e,t,s){return Ws(e,t,s)}static calculateSpotPrice(e,t){return $s(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return js(e,t,s,r)}static calculateShares(e,t,s){return Ys(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return Js(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Ks(e,t,s,r)}};var Ge=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(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(O=>[O.id,O])),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=v(r.balance),m=v(i.balance),c=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:m,assetInED:c,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=ue(s.exchangeFee),m=r.plus(i),c=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&c.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&c.push("MaxOutRatioExceeded");let O=e.balanceIn.div(this.maxInRatio);return m.isGreaterThan(O)&&c.push("MaxInRatioExceeded"),{amountIn:m,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),m=r.minus(i),c=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&c.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&c.push("MaxInRatioExceeded");let O=e.balanceOut.div(this.maxOutRatio);return m.isGreaterThan(O)&&c.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:m,feePct:a,errors:c}}calculateInGivenOut(e,t){let s=Pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?R:r}calculateOutGivenIn(e,t){let s=Pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?R:r}spotPriceInGivenOut(e){let t=Pe.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=J(le,18-e.decimalsOut);return v(t).div(s)}spotPriceOutGivenIn(e){let t=Pe.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=J(le,18-e.decimalsIn);return v(t).div(s)}calculateTradeFee(e,t){let s=Pe.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return v(s)}};var qe=class{static get(e){switch(e.type){case"Xyk":return Ge.fromPool(e);case"Omnipool":return Me.fromPool(e);case"Lbp":return De.fromPool(e);case"Stableswap":return Ce.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Oe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ie,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(m=>m[m.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,externalId:r.externalId,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(m=>this.validPath(m,s)).map(m=>this.toHops(m,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,qe.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 Tl(u,e){return u.minus(e).abs().div(u.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function He(u,e){return u.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function jt(u,e){return le.minus(e.div(u)).multipliedBy(100).decimalPlaces(2)}function Jt(u,e){return e.div(u).minus(le).multipliedBy(100).decimalPlaces(2)}var lt=class extends Oe{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),m=super.getPaths(e,t,a,i);if(m.length===0)throw new Ee(e,t);let c;if(r)c=await this.toSellSwaps(s,r,a);else{let E=m.map(async n=>await this.toSellSwaps(s,n,a)),z=await Promise.all(E);c=this.findBestSellRoute(z)}let y=c[0],O=c[c.length-1],B=this.isDirectTrade(c),N=c.map(E=>E.spotPrice.shiftedBy(-1*E.assetOutDecimals)).reduce((E,z)=>E.multipliedBy(z)),F=J(N,O.assetOutDecimals),_=B?O.calculatedOut:this.calculateDelta0Y(y.amountIn,c,a),M=O.amountOut,k=B?O.tradeFeePct:jt(_,M).toNumber(),H=_.minus(M),x=this.getRouteFeeRange(c),j=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(F),se=He(_,j),de=E=>this.poolService.buildSellTx(e,t,y.amountIn,E,c.map(z=>z));return{type:"Sell",amountIn:y.amountIn,amountOut:O.amountOut,spotPrice:F,tradeFee:H,tradeFeePct:k,tradeFeeRange:x,priceImpactPct:se.toNumber(),swaps:c,toTx:de,toHuman(){return{type:"Sell",amountIn:K(y.amountIn,y.assetInDecimals),amountOut:K(O.amountOut,O.assetOutDecimals),spotPrice:K(F,O.assetOutDecimals),tradeFee:K(H,O.assetOutDecimals),tradeFeePct:k,tradeFeeRange:x,priceImpactPct:se.toNumber(),swaps:c.map(E=>E.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],m=s.get(a.poolAddress);if(m==null)throw new Error("Pool does not exit");let c=m.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1]:y=e;let O=m.calculateOutGivenIn(c,y);r.push(O)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],m=s.get(a.poolAddress);if(m==null)throw new Error("Pool does not exit");let c=m.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1].amountOut:y=J(v(e),c.decimalsIn).decimalPlaces(0,1);let O=await this.poolService.getPoolFees(c.assetOut,m),{amountOut:B,calculatedOut:N,feePct:F,errors:_}=m.validateAndSell(c,y,O),M=this.getPoolFeeRange(O),k=m.spotPriceOutGivenIn(c),H=y.shiftedBy(-1*c.decimalsIn).multipliedBy(k),x=He(N,H);r.push({...a,assetInDecimals:c.decimalsIn,assetOutDecimals:c.decimalsOut,amountIn:y,calculatedOut:N,amountOut:B,spotPrice:k,tradeFeePct:F,tradeFeeRange:M,priceImpactPct:x.toNumber(),errors:_,toHuman(){return{...a,amountIn:K(y,c.decimalsIn),calculatedOut:K(N,c.decimalsOut),amountOut:K(B,c.decimalsOut),spotPrice:K(k,c.decimalsOut),tradeFeePct:F,tradeFeeRange:M,priceImpactPct:x.toNumber(),errors:_}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(x=>x.tokens.find(j=>j.id===e)).filter(x=>!!x).sort((x,j)=>Number(j.balance)-Number(x.balance)),{balance:m,decimals:c}=a[0],O=v(m).shiftedBy(-1*c).div(100).multipliedBy(.1),B=i.map(async x=>await this.toSellSwaps(O,x,r)),N=await Promise.all(B),F=this.findBestSellRoute(N),_=await this.toSellSwaps("1",F,r),M=_.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,j)=>x.multipliedBy(j)),k=_[_.length-1].assetOutDecimals;return{amount:J(M,k),decimals:k}}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),m=super.getPaths(e,t,a,i);if(m.length===0)throw new Ee(e,t);let c;if(r)c=await this.toBuySwaps(s,r,a);else{let E=m.map(async n=>await this.toBuySwaps(s,n,a)),z=await Promise.all(E);c=this.findBestBuyRoute(z)}let y=c[c.length-1],O=c[0],B=this.isDirectTrade(c),N=c.map(E=>E.spotPrice.shiftedBy(-1*E.assetInDecimals)).reduce((E,z)=>E.multipliedBy(z)),F=J(N,O.assetInDecimals),_=B?O.calculatedIn:this.calculateDelta0X(y.amountOut,c,a),M=O.amountIn,k=B?O.tradeFeePct:Jt(_,M).toNumber(),H=M.minus(_),x=this.getRouteFeeRange(c),j=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(F),se;_.isZero()?se=-100:se=He(j,_).toNumber();let de=E=>this.poolService.buildBuyTx(e,t,y.amountOut,E,c.map(z=>z));return{type:"Buy",amountOut:y.amountOut,amountIn:O.amountIn,spotPrice:F,tradeFee:H,tradeFeePct:k,tradeFeeRange:x,priceImpactPct:se,swaps:c,toTx:de,toHuman(){return{type:"Buy",amountOut:K(y.amountOut,y.assetOutDecimals),amountIn:K(O.amountIn,O.assetInDecimals),spotPrice:K(F,O.assetInDecimals),tradeFee:K(H,O.assetInDecimals),tradeFeePct:k,tradeFeeRange:x,priceImpactPct:se,swaps:c.map(E=>E.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],m=s.get(a.poolAddress);if(m==null)throw new Error("Pool does not exit");let c=m.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=r[0];let O=m.calculateInGivenOut(c,y);r.unshift(O)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],m=s.get(a.poolAddress);if(m==null)throw new Error("Pool does not exit");let c=m.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=J(v(e),c.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let O=await this.poolService.getPoolFees(c.assetOut,m),{amountIn:B,calculatedIn:N,feePct:F,errors:_}=m.validateAndBuy(c,y,O),M=this.getPoolFeeRange(O),k=m.spotPriceInGivenOut(c),H=y.shiftedBy(-1*c.decimalsOut).multipliedBy(k),x;N.isZero()?x=-100:x=He(H,N).toNumber(),r.unshift({...a,assetInDecimals:c.decimalsIn,assetOutDecimals:c.decimalsOut,amountOut:y,calculatedIn:N,amountIn:B,spotPrice:k,tradeFeePct:F,tradeFeeRange:M,priceImpactPct:x,errors:_,toHuman(){return{...a,amountOut:K(y,c.decimalsOut),calculatedIn:K(N,c.decimalsIn),amountIn:K(B,c.decimalsIn),spotPrice:K(k,c.decimalsIn),tradeFeePct:F,tradeFeeRange:M,priceImpactPct:x,errors:_}}})}return r}};export{Fe as AssetClient,_t as AssetNotFound,Br as BASILISK_PARACHAIN_ID,_e as BalanceClient,G as BigNumber,Ot as CachingPoolService,Zt as DECIMAL_PLACES,ft as DENOMINATOR,Pt as FarmClient,Ye as HYDRADX_OMNIPOOL_ADDRESS,Or as HYDRADX_PARACHAIN_ID,Te as HYDRADX_SS58_PREFIX,dr as INFINITY,me as LbpMath,De as LbpPool,le as ONE,W as OmniMath,Me as OmniPool,Ft as PoolConfigNotFound,Ae as PoolError,qe as PoolFactory,Ve as PoolNotFound,Re as PoolService,re as PoolType,kt as ProviderConfigNotFound,Ne as RUNTIME_DECIMALS,Ee as RouteNotFound,Oe as Router,wr as SYSTEM_ASSET_DECIMALS,xe as SYSTEM_ASSET_ID,te as StableMath,Ce as StableSwap,Et as StorageConfigNotFound,Rt as SubscriptionNotSupported,dt as TRADEABLE_DEFAULT,lt as TradeRouter,It as TradeType,Pe as XykMath,Ge as XykPool,R as ZERO,v as bnum,bt as buildRoute,Jt as calculateBuyFee,Tl as calculateDiffToAvg,He as calculateDiffToRef,jt as calculateSellFee,At as findNestedKey,Ir as findNestedObj,J as scale};
1
+ var Xe=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 Kt=5,ve=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 Xe,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>Kt)return r;let m=c[c.length-1];(s===null||m[0]===s)&&r.push(c),e.get(m[0])?.forEach(O=>{if(this.isNotVisited(O,c)){let B=[...c];B.push(O),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),m=parseInt(a);s.get(c)?.push([m,r])}return s}};function mt(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 Ie=class{getProposals(e,t,s){let r=mt(s),i=Object.keys(r),a=i.map(O=>r[O]).flat(),c=new ve,m=c.buildAndPopulateGraph(i,a),y=c.findPaths(m,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let 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 Vt=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,pt=Math.ceil,oe=Math.floor,Q="[BigNumber Error] ",Bt=Q+"Number primitive has more than 15 significant digits: ",ce=1e14,T=14,gt=9007199254740991,ht=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],be=1e7,$=1e9;function vt(u){var e,t,s,r=w.prototype={constructor:w,toString:null,valueOf:null},i=new w(1),a=20,c=4,m=-7,y=21,O=-1e7,B=1e7,N=!1,F=1,_=0,M={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},k="0123456789abcdefghijklmnopqrstuvwxyz",H=!0;function w(n,o){var l,P,g,d,S,p,h,b,f=this;if(!(f instanceof w))return new w(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<O?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!Vt.test(b=String(n)))return s(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(q(o,2,k.length,"Base"),o==10&&H)return f=new w(n),E(f,a+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return s(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,w.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Bt+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=k.slice(0,o),d=S=0,h=b.length;S<h;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return s(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&w.DEBUG&&h>15&&(n>gt||n!==oe(n)))throw Error(Bt+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<O)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%T,d<0&&(S+=T),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=T;S<h;)f.c.push(+b.slice(S,S+=T));S=T-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}w.clone=vt,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],q(l,0,$,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],q(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(q(l[0],-$,0,o),q(l[1],0,$,o),m=l[0],y=l[1]):(q(l,-$,$,o),m=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)q(l[0],-$,-1,o),q(l[1],1,$,o),O=l[0],B=l[1];else if(q(l,-$,$,o),l)O=-(B=l<0?-l:l);else throw Error(Q+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))N=l;else throw N=!l,Error(Q+"crypto unavailable");else N=l;else throw Error(Q+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],q(l,0,9,o),F=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],q(l,0,$,o),_=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")M=l;else throw Error(Q+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))H=l.slice(0,10)=="0123456789",k=l;else throw Error(Q+o+" invalid: "+l)}else throw Error(Q+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[m,y],RANGE:[O,B],CRYPTO:N,MODULO_MODE:F,POW_PRECISION:_,FORMAT:M,ALPHABET:k}},w.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!w.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-$&&g<=$&&g===oe(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%T,o<1&&(o+=T),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(Q+"Invalid BigNumber: "+n)},w.maximum=w.max=function(){return se(arguments,-1)},w.minimum=w.min=function(){return se(arguments,1)},w.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return oe(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,S,p,h=0,b=[],f=new w(i);if(l==null?l=a:q(l,0,$),S=pt(l/T),N)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));h<S;)p=P[h]*131072+(P[h+1]>>>11),p>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(p%1e14),h+=2);h=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);h<S;)p=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],p>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(p%1e14),h+=7);h=S/7}else throw N=!1,Error(Q+"crypto unavailable");if(!N)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],l%=T,S&&l&&(p=ht[T-l],b[h]=oe(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=T);for(h=1,p=b[0];p>=10;p/=10,h++);h<T&&(d-=T-h)}return f.e=d,f.c=b,f}}(),w.sum=function(){for(var n=1,o=arguments,l=new w(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var S,p=[0],h,b=0,f=l.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(l.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(l,P,g,d,S){var p,h,b,f,x,I,A,D,U=l.indexOf("."),Y=a,L=c;for(U>=0&&(f=_,_=0,l=l.replace(".",""),D=new w(P),I=D.pow(l.length-U),_=f,D.c=o(fe(ne(I.c),I.e,"0"),10,g,n),D.e=D.c.length),A=o(l,P,g,S?(p=k,n):(p=n,k)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(U<0?--b:(I.c=A,I.e=b,I.s=d,I=e(I,D,Y,L,g),A=I.c,x=I.r,b=I.e),h=b+Y+1,U=A[h],f=g/2,x=x||h<0||A[h+1]!=null,x=L<4?(U!=null||x)&&(L==0||L==(I.s<0?3:2)):U>f||U==f&&(L==4||x||L==6&&A[h-1]&1||L==(I.s<0?8:7)),h<1||!A[0])l=x?fe(p.charAt(1),-Y,p.charAt(0)):p.charAt(0);else{if(A.length=h,x)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(U=0,l="";U<=f;l+=p.charAt(A[U++]));l=fe(l,b,p.charAt(0))}return l}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,x=P.length,I=g%be,A=g/be|0;for(P=P.slice();x--;)h=P[x]%be,b=P[x]/be|0,S=A*h+b*I,p=I*h+S%be*be+f,f=(p/d|0)+(S/be|0)+A*b,P[x]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function l(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,x,I,A,D,U,Y,L,C,V,Ue,ut,ct,ge,Be,ie=P.s==g.s?1:-1,Z=P.c,X=g.c;if(!Z||!Z[0]||!X||!X[0])return new w(!P.s||!g.s||(Z?X&&Z[0]==X[0]:!X)?NaN:Z&&Z[0]==0||!X?ie*0:ie/0);for(U=new w(ie),Y=U.c=[],b=P.e-g.e,ie=d+b+1,p||(p=ce,b=ae(P.e/T)-ae(g.e/T),ie=ie/T|0),f=0;X[f]==(Z[f]||0);f++);if(X[f]>(Z[f]||0)&&b--,ie<0)Y.push(1),x=!0;else{for(ut=Z.length,ge=X.length,f=0,ie+=2,I=oe(p/(X[0]+1)),I>1&&(X=n(X,I,p),Z=n(Z,I,p),ge=X.length,ut=Z.length),Ue=ge,L=Z.slice(0,ge),C=L.length;C<ge;L[C++]=0);Be=X.slice(),Be=[0].concat(Be),ct=X[0],X[1]>=p/2&&ct++;do{if(I=0,h=o(X,L,ge,C),h<0){if(V=L[0],ge!=C&&(V=V*p+(L[1]||0)),I=oe(V/ct),I>1)for(I>=p&&(I=p-1),A=n(X,I,p),D=A.length,C=L.length;o(A,L,D,C)==1;)I--,l(A,ge<D?Be:X,D,p),D=A.length,h=1;else I==0&&(h=I=1),A=X.slice(),D=A.length;if(D<C&&(A=[0].concat(A)),l(L,A,C,p),C=L.length,h==-1)for(;o(X,L,ge,C)<1;)I++,l(L,ge<C?Be:X,C,p),C=L.length}else h===0&&(I++,L=[0]);Y[f++]=I,L[0]?L[C++]=Z[Ue]||0:(L=[Z[Ue]],C=1)}while((Ue++<ut||L[0]!=null)&&ie--);x=L[0]!=null,Y[0]||Y.splice(0,1)}if(p==ce){for(f=1,ie=Y[0];ie>=10;ie/=10,f++);E(U,d+(U.e=f+b*T-1)+1,S,x)}else U.e=b,U.r=+x;return U}}();function j(n,o,l,P){var g,d,S,p,h;if(l==null?l=c:q(l,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ne(n.c),h=P==1||P==2&&(S<=m||S>=y)?We(h,S):fe(h,S,"0");else if(n=E(new w(n),o,l),d=n.e,h=ne(n.c),p=h.length,P==1||P==2&&(o<=d||d<=m)){for(;p<o;h+="0",p++);h=We(h,d)}else if(o-=S,h=fe(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function se(n,o){for(var l,P,g=1,d=new w(n[0]);g<n.length;g++)P=new w(n[g]),(!P.s||(l=Se(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function de(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*T-1)>B?n.c=n.e=null:l<O?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,S,p,h){var b,f=p?S:S.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(x,I,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?I:x}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new w(f,b);if(w.DEBUG)throw Error(Q+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function E(n,o,l,P){var g,d,S,p,h,b,f,x=n.c,I=ht;if(x){e:{for(g=1,p=x[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=T,S=o,h=x[b=0],f=oe(h/I[g-S-1]%10);else if(b=pt((d+1)/T),b>=x.length)if(P){for(;x.length<=b;x.push(0));h=f=0,g=1,d%=T,S=d-T+1}else break e;else{for(h=p=x[b],g=1;p>=10;p/=10,g++);d%=T,S=d-T+g,f=S<0?0:oe(h/I[g-S-1]%10)}if(P=P||o<0||x[b+1]!=null||(S<0?h:h%I[g-S-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?S>0?h/I[g-S]:0:x[b-1])%10&1||l==(n.s<0?8:7)),o<1||!x[0])return x.length=0,P?(o-=n.e+1,x[0]=I[(T-o%T)%T],n.e=-o||0):x[0]=n.e=0,n;if(d==0?(x.length=b,p=1,b--):(x.length=b+1,p=I[T-d],x[b]=S>0?oe(h/I[g-S]%I[S])*p:0),P)for(;;)if(b==0){for(d=1,S=x[0];S>=10;S/=10,d++);for(S=x[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,x[0]==ce&&(x[0]=1));break}else{if(x[b]+=p,x[b]!=ce)break;x[b--]=0,p=1}for(d=x.length;x[--d]===0;x.pop());}n.e>B?n.c=n.e=null:n.e<O&&(n.c=[n.e=0])}return n}function z(n){var o,l=n.e;return l===null?n.toString():(o=ne(n.c),o=l<=m||l>=y?We(o,l):fe(o,l,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new w(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return Se(this,new w(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),E(new w(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-ae(this.e/T))*T,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 w(n,o),a,c)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new w(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var l,P,g,d,S,p,h,b,f,x=this;if(n=new w(n),n.c&&!n.isInteger())throw Error(Q+"Exponent not an integer: "+z(n));if(o!=null&&(o=new w(o)),p=n.e>14,!x.c||!x.c[0]||x.c[0]==1&&!x.e&&x.c.length==1||!n.c||!n.c[0])return f=new w(Math.pow(+z(x),p?n.s*(2-ze(n)):+z(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new w(NaN);P=!h&&x.isInteger()&&o.isInteger(),P&&(x=x.mod(o))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||p&&x.c[1]>=24e7:x.c[0]<8e13||p&&x.c[0]<=9999975e7)))return d=x.s<0&&ze(n)?-0:0,x.e>-1&&(d=1/d),new w(h?1/d:d);_&&(d=pt(_/T+2))}for(p?(l=new w(.5),h&&(n.s=1),b=ze(n)):(g=Math.abs(+z(n)),b=g%2),f=new w(i);;){if(b){if(f=f.times(x),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(g){if(g=oe(g/2),g===0)break;b=g%2}else if(n=n.times(l),E(n,n.e+1,1),n.e>14)b=ze(n);else{if(g=+z(n),g===0)break;b=g%2}x=x.times(x),d?x.c&&x.c.length>d&&(x.c.length=d):P&&(x=x.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?E(f,_,c,S):f)},r.integerValue=function(n){var o=new w(this);return n==null?n=c:q(n,0,8),E(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return Se(this,new w(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return Se(this,new w(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=Se(this,new w(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&ae(this.e/T)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return Se(this,new w(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=Se(this,new w(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,S=this,p=S.s;if(n=new w(n,o),o=n.s,!p||!o)return new w(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/T,b=n.e/T,f=S.c,x=n.c;if(!h||!b){if(!f||!x)return f?(n.s=-o,n):new w(x?S:NaN);if(!f[0]||!x[0])return x[0]?(n.s=-o,n):new w(f[0]?S:c==3?-0:0)}if(h=ae(h),b=ae(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=x),g.reverse(),o=p;o--;g.push(0));g.reverse()}else for(P=(d=(p=f.length)<(o=x.length))?p:o,p=o=0;o<P;o++)if(f[o]!=x[o]){d=f[o]<x[o];break}if(d&&(g=f,f=x,x=g,n.s=-n.s),o=(P=x.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=ce-1;P>p;){if(f[--P]<x[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=ce}f[P]-=x[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?de(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 w(n,o),!g.c||!n.s||n.c&&!n.c[0]?new w(NaN):!n.c||g.c&&!g.c[0]?new w(g):(F==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,F),n=g.minus(l.times(n)),!n.c[0]&&F==1&&(n.s=g.s),n)},r.multipliedBy=r.times=function(n,o){var l,P,g,d,S,p,h,b,f,x,I,A,D,U,Y,L=this,C=L.c,V=(n=new w(n,o)).c;if(!C||!V||!C[0]||!V[0])return!L.s||!n.s||C&&!C[0]&&!V||V&&!V[0]&&!C?n.c=n.e=n.s=null:(n.s*=L.s,!C||!V?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=ae(L.e/T)+ae(n.e/T),n.s*=L.s,h=C.length,x=V.length,h<x&&(D=C,C=V,V=D,g=h,h=x,x=g),g=h+x,D=[];g--;D.push(0));for(U=ce,Y=be,g=x;--g>=0;){for(l=0,I=V[g]%Y,A=V[g]/Y|0,S=h,d=g+S;d>g;)b=C[--S]%Y,f=C[S]/Y|0,p=A*b+f*I,b=I*b+p%Y*Y+D[d]+l,l=(b/U|0)+(p/Y|0)+A*f,D[d--]=b%U;D[d]=l}return l?++P:D.splice(0,1),de(n,D,P)},r.negated=function(){var n=new w(this);return n.s=-n.s||null,n},r.plus=function(n,o){var l,P=this,g=P.s;if(n=new w(n,o),o=n.s,!g||!o)return new w(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/T,S=n.e/T,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new w(g/0);if(!p[0]||!h[0])return h[0]?n:new w(p[0]?P:g*0)}if(d=ae(d),S=ae(S),p=p.slice(),g=d-S){for(g>0?(S=d,l=h):(g=-g,l=p),l.reverse();g--;l.push(0));l.reverse()}for(g=p.length,o=h.length,g-o<0&&(l=h,h=p,p=l,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/ce|0,p[o]=ce===p[o]?0:p[o]%ce;return g&&(p=[g].concat(p),++S),de(n,p,S)},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),E(new w(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*T+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,-gt,gt),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,l,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new w("0.5");if(p!==1||!S||!S[0])return new w(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+z(d)),p==0||p==1/0?(o=ne(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=ae((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new w(o)):l=new w(p+""),l.c[0]){for(h=l.e,p=h+b,p<3&&(p=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ne(g.c).slice(0,p)===(o=ne(l.c)).slice(0,p))if(l.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(E(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(E(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return E(l,l.e+a+1,c,n)},r.toExponential=function(n,o){return n!=null&&(q(n,0,$),n++),j(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(q(n,0,$),n=n+this.e+1),j(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=M;else if(typeof l!="object")throw Error(Q+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],x=S[1],I=g.s<0,A=I?f.slice(1):f,D=A.length;if(h&&(d=p,p=h,h=d,D-=d),p>0&&D>0){for(d=D%p||p,f=A.substr(0,d);d<D;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),I&&(f="-"+f)}P=x?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?x.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):x):f}return(l.prefix||"")+P+(l.suffix||"")},r.toFraction=function(n){var o,l,P,g,d,S,p,h,b,f,x,I,A=this,D=A.c;if(n!=null&&(p=new w(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(Q+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+z(p));if(!D)return new w(A);for(o=new w(i),b=l=new w(i),P=h=new w(i),I=ne(D),d=o.e=I.length-A.e-1,o.c[0]=ht[(S=d%T)<0?T+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new w(I),h.c[0]=0;f=e(p,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,x=e(b,P,d,c).minus(A).abs().comparedTo(e(h,l,d,c).minus(A).abs())<1?[b,P]:[h,l],B=S,x},r.toNumber=function(){return+z(this)},r.toPrecision=function(n,o){return n!=null&&q(n,1,$),j(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<=m||g>=y?We(ne(l.c),g):fe(ne(l.c),g,"0"):n===10&&H?(l=E(new w(l),a+g+1,c),o=fe(ne(l.c),l.e,"0")):(q(n,2,k.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 z(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,u!=null&&w.set(u),w}function ae(u){var e=u|0;return u>0||u===e?e:e-1}function ne(u){for(var e,t,s=1,r=u.length,i=u[0]+"";s<r;){for(e=u[s++]+"",t=T-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function Se(u,e){var t,s,r=u.c,i=e.c,a=u.s,c=e.s,m=u.e,y=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=m==y,!r||!i)return s?0:!r^t?1:-1;if(!s)return m>y^t?1:-1;for(c=(m=r.length)<(y=i.length)?m:y,a=0;a<c;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return m==y?0:m>y^t?1:-1}function q(u,e,t,s){if(u<e||u>t||u!==oe(u))throw Error(Q+(s||"Argument")+(typeof u=="number"?u<e||u>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(u))}function ze(u){var e=u.c.length-1;return ae(u.e/T)==e&&u.c[e]%2!=0}function We(u,e){return(u.length>1?u.charAt(0)+"."+u.slice(1):u)+(e<0?"e":"e+")+e}function fe(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 G=vt();var Zt=12;G.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Zt});var R=v(0),le=v(1),dr=v("Infinity");function J(u,e){let t=new G(e.toString()),s=new G(10).pow(t);return u.times(s)}function v(u){return new G(u.toString())}var re=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(re||{}),Ae=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(Ae||{}),It=(t=>(t.Buy="Buy",t.Sell="Sell",t))(It||{});import{calculate_in_given_out as Qt,calculate_out_given_in as es,calculate_linear_weights as ts,calculate_pool_trade_fee as ss,get_spot_price as rs}from"@galacticcouncil/math-lbp";var me=class{static getSpotPrice(e,t,s,r,i){return rs(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return Qt(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return es(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return ts(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return ss(e,t,s)}};import{encodeAddress as is}from"@polkadot/util-crypto";import{stringToU8a as ns}from"@polkadot/util";var Ne=18,dt=15,we="0",xr=12,Or=2034,Te=63,Br=2090,ft=1e3,Ye=is(ns("modlomnipool".padEnd(32,"\0")),Te);function At(u,e){let t=[];return JSON.stringify(u,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function Ir(u,e,t){let s;return JSON.stringify(u,(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 ye=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Fe=class extends ye{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];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([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==we){let F=this.api.consts.balances.existentialDeposit;return{id:we,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:F.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:m}=t,{symbol:y,decimals:O}=s.get(e)??{},B=this.parseLocation("parachain",r);return{id:e,name:i.toHuman(),symbol:y,decimals:O,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:B,externalId:this.parseLocation(2094===B?"generalKey":"generalIndex",r),existentialDeposit:m.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:c,isSufficient:m,existentialDeposit:y}=t,{symbol:O,decimals:B}=this.getToken(i.toString(),t,s),N=a.toNumber(),F=new Intl.DateTimeFormat("en-GB"),_=[O,"Bond",F.format(N)].join(" ");return{id:e,name:_,symbol:O+"b",decimals:B,icon:O,type:c.toString(),isSufficient:m.toHuman(),existentialDeposit:y.toString(),underlyingAssetId:i.toString(),maturity:N}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:c,assetType:m,isSufficient:y,existentialDeposit:O}=t,N=i.map(M=>M.toString()).map(M=>{let{symbol:k}=this.getToken(M,t,s);return[M,k]}),F=Object.fromEntries(N),_=Object.values(F);return{id:e,name:_.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:_.join("/"),type:m.toString(),isSufficient:y.toHuman(),existentialDeposit:O.toString(),meta:F}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=s?.find(c=>c.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}: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,t){let[s,r,i,a,c]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),m=this.getSupportedAssets(s),y=this.normalizeMetadata(m,c),O=m.map(([{args:[B]},N])=>{let F=N.unwrap(),_=r.get(B.toString()),{assetType:M}=F;switch(M.toString()){case"Bond":let k=a.get(B.toString());return this.getBond(B.toString(),F,y,k);case"StableSwap":let H=i.get(B.toString());return this.getShares(B.toString(),F,y,H);case"External":return this.getExternal(B.toString(),F,t,_);default:return this.getToken(B.toString(),F,y,_)}});return e?O:O.filter(B=>this.isValidAsset(B))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let s=At(t.toJSON(),e);return s&&s[e]}else return}};var _e=class extends ye{constructor(e){super(e)}async getTokenBalanceData(e,t){let s=this.api.createType("(AssetId, AccountId)",[t,e]),r=await this.api.rpc.state.call("CurrenciesApi_account",s.toHex());return this.api.createType("OrmlTokensAccountData",r)}async getAccountBalanceData(e){let t=this.api.createType("AccountId",e),s=await this.api.rpc.state.call("CurrenciesApi_accounts",t.toHex());return this.api.createType("Vec<(AssetId, OrmlTokensAccountData)>",s)}async getBalance(e,t){let s=this.getTokenBalanceData(e,t);return this.calculateFreeBalance(s)}async subscribeBalances(e,t){let s=async()=>{let r=[];(await this.getAccountBalanceData(e)).forEach(([a,c])=>{r.push([a.toString(),this.calculateFreeBalance(c)])}),t(r)};return await s(),this.api.rpc.chain.subscribeNewHeads(async()=>{s()})}async subscribeBalance(e,t,s){let r=async()=>{let i=await this.getTokenBalanceData(e,t);s(t.toString(),this.calculateFreeBalance(i))};return await r(),this.api.rpc.chain.subscribeNewHeads(async()=>{r()})}async subscribeTokenBalance(e,t,s){let r=t.filter(i=>i!==we).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach(({free:a,reserved:c,frozen:m},y)=>{let O=this.calculateFreeBalance({free:a,feeFrozen:c,frozen:m}),B=r[y][1];s(B,O)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(we,this.calculateFreeBalance(s)))}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,a=new G(t),c=new G(s||i),m=new G(r||0),y=c.gt(m)?c:m;return a.minus(y)}};import{isAddress as Nt}from"@polkadot/util-crypto";import{fixed_from_rational as Tt}from"@galacticcouncil/math-liquidity-mining";var Pt=class extends ye{constructor(e){super(e)}secondsInYear=new G(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,c=i.unwrap().toString(),m=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(m)).unwrap(),O=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,m,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,c=i.unwrap().toString(),m=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(m)).unwrap(),O=(await this.api.query.xykWarehouseLM.yieldFarm(e,m,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new G(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),c=a.price.n.toString(),m=a.price.d.toString(),y;return Number(t)<Number(s)?y=Tt(c,m):y=Tt(m,c),y}getGlobalRewardPerPeriod(e,t,s,r){let a=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return a.gte(s)?s:a}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!Nt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&Nt(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:c,globalFarm:m,priceAdjustment:y})=>{let O=new G(m.totalSharesZ.toString()),B=m.plannedYieldingPeriods.toString(),N=new G(m.yieldPerPeriod.toString()),F=new G(m.maxRewardPerPeriod.toString()),_=m.blocksPerPeriod.toString(),M=new G(c.multiplier.toString()).shiftedBy(-18),k=this.secondsInYear.div(new G(s).times(_)),H;if(O.isZero())H=N.times(M).times(k);else{let de=this.getGlobalRewardPerPeriod(O,N,F,y);H=this.getPoolYieldPerPeriod(de,M,O,y).times(k)}let w=new G(m.pendingRewards.toString()).plus(m.accumulatedPaidRewards.toString()),j=F.times(B);return w.div(j).gte(.99)?R:H.times(100)}).reduce((c,m)=>c.plus(m),R).toString():void 0}};var he=class extends _e{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)];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.subscribeBalances(e.address,this.updateBalancesCallback(e))}subscribeSharePoolBalance(e){return this.subscribeBalance(Ye,e.id,this.updateBalanceCallback(e))}updateBalancesCallback(e){return function(t){t.forEach(([s,r])=>{let i=e.tokens.findIndex(a=>a.id==s);i>=0&&(e.tokens[i].balance=r.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(i=>i.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var $e=class extends he{MAX_FINAL_WEIGHT=J(v(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(),m=i.toString(),y=await this.getPoolDelta(m,c,s.toString());return this.poolsData.set(i.toString(),c),{address:m,type:"Lbp",fee:c.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let 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:m,repayTarget:y,feeCollector:O}=t,B=me.calculateLinearWeights(r.toString(),i.toString(),c.toString(),m.toString(),s),[N,F]=a,_=N.toString(),M=v(B),k=F.toString(),H=this.MAX_FINAL_WEIGHT.minus(v(M)),[w,j,se]=await Promise.all([this.isRepayFeeApplied(_,y.toString(),O.toString()),this.getBalance(e,_),this.getBalance(e,k)]);return{repayFeeApply:w,tokens:[{id:_,weight:M,balance:j.toString()},{id:k,weight:H,balance:se.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=v(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 os}from"@polkadot/util-crypto";import{stringToU8a as as}from"@polkadot/util";function K(u,e){return u.shiftedBy(-1*e).toString()}function ue(u){return u[0]/u[1]*100}function ee(u){return u[0]/u[1]}function pe(u){return[u/ft,ft]}var je=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:[m]},y])=>{let{hubReserve:O,shares:B,tradable:N}=y.unwrap(),F=await this.getBalance(t,m.toString());return{id:m.toString(),hubReserves:v(O.toString()),shares:v(B.toString()),tradeable:N.bits.toNumber(),balance:F.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:m,protocolFee:y}=s.unwrap();return{assetFee:pe(m.toNumber()),protocolFee:pe(y.toNumber()),min:pe(a),max:pe(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:pe(a),max:pe(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(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:v(s.toString()),shares:v(r.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return pe(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return pe(t)}getPoolId(){return os(as("modlomnipool".padEnd(32,"\0")),Te)}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 Je=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,c]=r.unwrap(),[m,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:m.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{blake2AsHex as Ps,encodeAddress as bs}from"@polkadot/util-crypto";import{calculate_in_given_out as ls,calculate_out_given_in as us,calculate_amplification as cs,calculate_add_one_asset as ms,calculate_liquidity_out_one_asset as ps,calculate_pool_trade_fee as gs,calculate_shares as hs,calculate_shares_for_amount as ds,pool_account_name as fs}from"@galacticcouncil/math-stableswap";var te=class{static getPoolAddress(e){return fs(e)}static calculateAmplification(e,t,s,r,i){return cs(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return ls(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return ms(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return ds(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return us(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return ps(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return hs(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return gs(e,t,s)}};var Ke=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 c=a.unwrap(),m=i.toString(),y=this.getPoolAddress(m),[O,B]=await Promise.all([this.getPoolDelta(m,c,s.toString()),this.getPoolTokens(y,m,c)]);return this.stablePools.set(y,c),{address:y,id:m,type:"Stableswap",fee:pe(c.fee.toNumber()),tokens:B,...O,...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,m=te.calculateAmplification(r.toString(),i.toString(),a.toString(),c.toString(),s),y=await this.api.query.tokens.totalIssuance(e);return{amplification:m,totalIssuance:y.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async m=>{let[y,O]=await Promise.all([this.api.query.stableswap.assetTradability(t,m.toString()),this.getBalance(e,m.toString())]);return{id:m.toString(),tradeable:y.bits.toNumber(),balance:O.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:m}=c.unwrap(),y=await this.getBalance(Ye,t);a.push({id:t,tradeable:m.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),s=te.getPoolAddress(t);return bs(Ps(s),Te)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function bt(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 Ve=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Ft=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ee=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},_t=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Rt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},kt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Re=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new Fe(this.api),this.xykClient=new Je(this.api),this.omniClient=new je(this.api),this.lbpClient=new $e(this.api),this.stableClient=new Ke(this.api)}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(!1,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 Ve(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(),bt(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(),bt(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var ke=(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 Ze=(u,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(u(t)+e(t))}};var ys=Ze(()=>"illegal argument(s)"),Lt=u=>{throw new ys(u)};var Ss=Ze(()=>"index out of bounds"),yt=u=>{throw new Ss(u)},Qe=(u,e,t)=>(u<e||u>=t)&&yt(u);var Dt=23283064365386963e-26,et=class{float(e=1){return this.int()*Dt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Dt-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var St=Math.random,wt=class extends et{int(){return St()*4294967296>>>0}float(e=1){return St()*e}norm(e=1){return(St()-.5)*2*e}},Mt=new wt;var Ct=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var Gt=Object.getPrototypeOf({}),tt="function",qt="string",xe=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===tt)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===tt)return e.equiv(u)}else return u==e;return typeof u===qt||typeof e===qt?!1:(t=Object.getPrototypeOf(u),(t==null||t===Gt)&&(t=Object.getPrototypeOf(e),t==null||t===Gt)?Bs(u,e):typeof u!==tt&&u.length!==void 0&&typeof e!==tt&&e.length!==void 0?ws(u,e):u instanceof Set&&e instanceof Set?xs(u,e):u instanceof Map&&e instanceof Map?Os(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)},ws=(u,e,t=xe)=>{let s=u.length;if(s===e.length)for(;s-- >0&&t(u[s],e[s]););return s<0},xs=(u,e,t=xe)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),Os=(u,e,t=xe)=>u.size===e.size&&t([...u].sort(),[...e].sort()),Bs=(u,e,t=xe)=>{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 Ht=(u,e)=>u!=null&&typeof u[e]=="function";var Ut=u=>Ht(u,"xform")?u.xform():u;var st=Symbol(),xt=()=>{};var Xt=u=>u!=null&&typeof u[Symbol.iterator]=="function";var rt=class{value;constructor(e){this.value=e}deref(){return this.value}};var it=u=>u instanceof rt;var zt=u=>u instanceof rt?u.deref():u;function*Wt(u,e){let t=Ut(u)([xt,xt,(s,r)=>r])[2];for(let s of e){let r=t(st,s);if(it(r)){r=zt(r.deref()),r!==st&&(yield r);return}r!==st&&(yield r)}}var Yt=(u,e)=>[u[0],u[1],e];function Le(u,e){return Xt(e)?Wt(Le(u),e):t=>{let s=t[2];return Yt(t,(r,i)=>s(r,u(i)))}}var nt=class u{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return $t("next",this._head)}reverseIterator(){return $t("prev",this.tail)}clear(){this.release()}compare(e,t=ke){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 u||Ct(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(!xe(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||ke;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&&!it(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&&yt(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*$t(u,e){for(;e;)yield e.value,e=e[u]}var ot=class u extends nt{_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 u(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 u}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):(Qe(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):(Qe(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new u,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=Mt){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)&&Lt("invalid indices: ${from} / ${to}");let i=new u,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=ke){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 m=0;m<t&&(a++,i=i.next,!!i);m++);let c=t;for(;a>0||c>0&&i;){let m;a===0?(m=i,i=i.next,c--):!i||c===0||e(s.value,i.value)<=0?(m=s,s=s.next,a--):(m=i,i=i.next,c--),this._tail?this._tail.next=m:this._head=m,m.prev=this._tail,this._tail=m}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),Qe(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new u;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 at=class u{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 ot,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 Le(e=>[e.k,e],this.items)}keys(){return Le(e=>e.k,this.items)}values(){return Le(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 u(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 Re{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new at(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 De=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new u(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(m=>[m.id,m])),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=v(r.balance),c=v(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),m=ue(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(c),O=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return O.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:O,calculatedIn:O,amountOut:t,feePct:m,errors:i}}else{let c=this.calculateInGivenOut(e,t),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&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),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),m=this.calculateTradeFee(c,s),y=ue(this.repayFeeApply?s.repayFee:s.exchangeFee),O=c.minus(m),B=e.balanceOut.div(this.maxOutRatio);return O.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:O,feePct:y,errors:i}}}calculateInGivenOut(e,t){let s=me.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?R:r}calculateOutGivenIn(e,t){let s=me.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?R:r}spotPriceInGivenOut(e){let t=me.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),J(le,e.decimalsOut).toString());return v(t)}spotPriceOutGivenIn(e){let t=me.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),J(le,e.decimalsIn).toString());return v(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 v(s)}};import{calculate_in_given_out as vs,calculate_lrna_in_given_out as Is,calculate_out_given_in as As,calculate_out_given_lrna_in as Ns,calculate_pool_trade_fee as Ts,calculate_spot_price as Fs,calculate_lrna_spot_price as _s,calculate_shares as Es,calculate_liquidity_out as Rs,calculate_liquidity_lrna_out as ks,verify_asset_cap as Ls,calculate_liquidity_hub_in as Ds,is_sell_allowed as Ms,is_buy_allowed as Cs,is_add_liquidity_allowed as Gs,is_remove_liquidity_allowed as qs}from"@galacticcouncil/math-omnipool";var W=class{static calculateSpotPrice(e,t,s,r){return Fs(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return _s(e,t)}static calculateInGivenOut(e,t,s,r,i,a,c,m,y){return vs(e,t,s,r,i,a,c,m,y)}static calculateLrnaInGivenOut(e,t,s,r,i){return Is(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,a,c,m,y){return As(e,t,s,r,i,a,c,m,y)}static calculateOutGivenLrnaIn(e,t,s,r,i){return Ns(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Ts(e,t,s)}static calculateShares(e,t,s,r){return Es(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,a,c,m){return Rs(e,t,s,r,i,a,c,m)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,c,m){return ks(e,t,s,r,i,a,c,m)}static calculateCapDifference(e,t,s,r){let i=G(t),a=G(e),c=G(r),y=G(s).shiftedBy(-18);if(i.div(c).lt(y)){let B=y.times(c).minus(i).times(a),N=i.times(G(1).minus(y));return B.div(N).toFixed(0)}else return"0"}static verifyAssetCap(e,t,s,r){return Ls(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return Ds(e,t,s,r)}static isSellAllowed(e){return Ms(e)}static isBuyAllowed(e){return Cs(e)}static isAddLiquidityAllowed(e){return Gs(e)}static isRemoveLiquidityAllowed(e){return qs(e)}};var Me=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new u(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(O=>[O.id,O])),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=v(r.balance),c=v(i.balance),m=v(r.existentialDeposit),y=v(i.existentialDeposit);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,assetInED:m,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),c=r===R?R:a.div(r).multipliedBy(100).decimalPlaces(2),m=[],y=W.isSellAllowed(e.tradeableIn),O=W.isBuyAllowed(e.tradeableOut);(!y||!O)&&m.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&m.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&m.push("MaxOutRatioExceeded");let N=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(N)&&m.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:c.toNumber(),errors:m}}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),m=[],y=W.isSellAllowed(e.tradeableIn),O=W.isBuyAllowed(e.tradeableOut);(!y||!O)&&m.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&m.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&m.push("MaxInRatioExceeded");let N=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(N)&&m.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:c.toNumber(),errors:m}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=W.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():R.toString(),s?ee(s.protocolFee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateLrnaInGivenOut(e,t,s){let r=W.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=W.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():R.toString(),s?ee(s.protocolFee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateOutGivenLrnaIn(e,t,s){let r=W.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=W.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=W.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=W.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=W.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsIn)).decimalPlaces(0,1)}};var Ce=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new u(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,m,y){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=m,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(O=>[O.id,O])),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=v(r.balance),c=v(i.balance),m=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?dt:r.tradeable,tradeableOut:this.id===t?dt:i.tradeable,assetInED:m,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=ue(s.fee),c=[],m=W.isSellAllowed(e.tradeableIn),y=W.isBuyAllowed(e.tradeableOut);return(!m||!y)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&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=ue(s.fee),c=[],m=W.isSellAllowed(e.tradeableIn),y=W.isBuyAllowed(e.tradeableOut);return(!m||!y)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:c}}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():R.toString()),i=v(r);return i.isNegative()?R: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():R.toString()),i=v(r);return i.isNegative()?R: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():R.toString()),i=v(r);return i.isNegative()?R: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(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():R.toString()),i=v(r);return i.isNegative()?R: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():R.toString()),i=v(r);return i.isNegative()?R: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():R.toString()),i=v(r);return i.isNegative()?R: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(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 v(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 Hs,calculate_out_given_in as Us,calculate_pool_trade_fee as Xs,get_spot_price as zs,calculate_liquidity_in as Ws,calculate_shares as Ys,calculate_spot_price as $s,calculate_spot_price_with_fee as js,calculate_liquidity_out_asset_a as Js,calculate_liquidity_out_asset_b as Ks}from"@galacticcouncil/math-xyk";var Pe=class{static getSpotPrice(e,t,s){return zs(e,t,s)}static calculateInGivenOut(e,t,s){return Hs(e,t,s)}static calculateOutGivenIn(e,t,s){return Us(e,t,s)}static calculatePoolTradeFee(e,t,s){return Xs(e,t,s)}static calculateLiquidityIn(e,t,s){return Ws(e,t,s)}static calculateSpotPrice(e,t){return $s(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return js(e,t,s,r)}static calculateShares(e,t,s){return Ys(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return Js(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Ks(e,t,s,r)}};var Ge=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(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(O=>[O.id,O])),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=v(r.balance),c=v(i.balance),m=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,assetInED:m,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=ue(s.exchangeFee),c=r.plus(i),m=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&m.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&m.push("MaxOutRatioExceeded");let O=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(O)&&m.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:r,amountOut:t,feePct:a,errors:m}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=ue(s.exchangeFee),c=r.minus(i),m=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&m.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&m.push("MaxInRatioExceeded");let O=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(O)&&m.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:a,errors:m}}calculateInGivenOut(e,t){let s=Pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?R:r}calculateOutGivenIn(e,t){let s=Pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?R:r}spotPriceInGivenOut(e){let t=Pe.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=J(le,18-e.decimalsOut);return v(t).div(s)}spotPriceOutGivenIn(e){let t=Pe.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=J(le,18-e.decimalsIn);return v(t).div(s)}calculateTradeFee(e,t){let s=Pe.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return v(s)}};var qe=class{static get(e){switch(e.type){case"Xyk":return Ge.fromPool(e);case"Omnipool":return Me.fromPool(e);case"Lbp":return De.fromPool(e);case"Stableswap":return Ce.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Oe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ie,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,externalId:r.externalId,isWhiteListed:r.isWhiteListed}))).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,qe.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 Tl(u,e){return u.minus(e).abs().div(u.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function He(u,e){return u.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function jt(u,e){return le.minus(e.div(u)).multipliedBy(100).decimalPlaces(2)}function Jt(u,e){return e.div(u).minus(le).multipliedBy(100).decimalPlaces(2)}var lt=class extends Oe{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),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ee(e,t);let m;if(r)m=await this.toSellSwaps(s,r,a);else{let E=c.map(async n=>await this.toSellSwaps(s,n,a)),z=await Promise.all(E);m=this.findBestSellRoute(z)}let y=m[0],O=m[m.length-1],B=this.isDirectTrade(m),N=m.map(E=>E.spotPrice.shiftedBy(-1*E.assetOutDecimals)).reduce((E,z)=>E.multipliedBy(z)),F=J(N,O.assetOutDecimals),_=B?O.calculatedOut:this.calculateDelta0Y(y.amountIn,m,a),M=O.amountOut,k=B?O.tradeFeePct:jt(_,M).toNumber(),H=_.minus(M),w=this.getRouteFeeRange(m),j=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(F),se=He(_,j),de=E=>this.poolService.buildSellTx(e,t,y.amountIn,E,m.map(z=>z));return{type:"Sell",amountIn:y.amountIn,amountOut:O.amountOut,spotPrice:F,tradeFee:H,tradeFeePct:k,tradeFeeRange:w,priceImpactPct:se.toNumber(),swaps:m,toTx:de,toHuman(){return{type:"Sell",amountIn:K(y.amountIn,y.assetInDecimals),amountOut:K(O.amountOut,O.assetOutDecimals),spotPrice:K(F,O.assetOutDecimals),tradeFee:K(H,O.assetOutDecimals),tradeFeePct:k,tradeFeeRange:w,priceImpactPct:se.toNumber(),swaps:m.map(E=>E.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 m=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1]:y=e;let O=c.calculateOutGivenIn(m,y);r.push(O)}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 m=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1].amountOut:y=J(v(e),m.decimalsIn).decimalPlaces(0,1);let O=await this.poolService.getPoolFees(m.assetOut,c),{amountOut:B,calculatedOut:N,feePct:F,errors:_}=c.validateAndSell(m,y,O),M=this.getPoolFeeRange(O),k=c.spotPriceOutGivenIn(m),H=y.shiftedBy(-1*m.decimalsIn).multipliedBy(k),w=He(N,H);r.push({...a,assetInDecimals:m.decimalsIn,assetOutDecimals:m.decimalsOut,amountIn:y,calculatedOut:N,amountOut:B,spotPrice:k,tradeFeePct:F,tradeFeeRange:M,priceImpactPct:w.toNumber(),errors:_,toHuman(){return{...a,amountIn:K(y,m.decimalsIn),calculatedOut:K(N,m.decimalsOut),amountOut:K(B,m.decimalsOut),spotPrice:K(k,m.decimalsOut),tradeFeePct:F,tradeFeeRange:M,priceImpactPct:w.toNumber(),errors:_}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(w=>w.tokens.find(j=>j.id===e)).filter(w=>!!w).sort((w,j)=>Number(j.balance)-Number(w.balance)),{balance:c,decimals:m}=a[0],O=v(c).shiftedBy(-1*m).div(100).multipliedBy(.1),B=i.map(async w=>await this.toSellSwaps(O,w,r)),N=await Promise.all(B),F=this.findBestSellRoute(N),_=await this.toSellSwaps("1",F,r),M=_.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,j)=>w.multipliedBy(j)),k=_[_.length-1].assetOutDecimals;return{amount:J(M,k),decimals:k}}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 Ee(e,t);let m;if(r)m=await this.toBuySwaps(s,r,a);else{let E=c.map(async n=>await this.toBuySwaps(s,n,a)),z=await Promise.all(E);m=this.findBestBuyRoute(z)}let y=m[m.length-1],O=m[0],B=this.isDirectTrade(m),N=m.map(E=>E.spotPrice.shiftedBy(-1*E.assetInDecimals)).reduce((E,z)=>E.multipliedBy(z)),F=J(N,O.assetInDecimals),_=B?O.calculatedIn:this.calculateDelta0X(y.amountOut,m,a),M=O.amountIn,k=B?O.tradeFeePct:Jt(_,M).toNumber(),H=M.minus(_),w=this.getRouteFeeRange(m),j=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(F),se;_.isZero()?se=-100:se=He(j,_).toNumber();let de=E=>this.poolService.buildBuyTx(e,t,y.amountOut,E,m.map(z=>z));return{type:"Buy",amountOut:y.amountOut,amountIn:O.amountIn,spotPrice:F,tradeFee:H,tradeFeePct:k,tradeFeeRange:w,priceImpactPct:se,swaps:m,toTx:de,toHuman(){return{type:"Buy",amountOut:K(y.amountOut,y.assetOutDecimals),amountIn:K(O.amountIn,O.assetInDecimals),spotPrice:K(F,O.assetInDecimals),tradeFee:K(H,O.assetInDecimals),tradeFeePct:k,tradeFeeRange:w,priceImpactPct:se,swaps:m.map(E=>E.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 m=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=r[0];let O=c.calculateInGivenOut(m,y);r.unshift(O)}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 m=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=J(v(e),m.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let O=await this.poolService.getPoolFees(m.assetOut,c),{amountIn:B,calculatedIn:N,feePct:F,errors:_}=c.validateAndBuy(m,y,O),M=this.getPoolFeeRange(O),k=c.spotPriceInGivenOut(m),H=y.shiftedBy(-1*m.decimalsOut).multipliedBy(k),w;N.isZero()?w=-100:w=He(H,N).toNumber(),r.unshift({...a,assetInDecimals:m.decimalsIn,assetOutDecimals:m.decimalsOut,amountOut:y,calculatedIn:N,amountIn:B,spotPrice:k,tradeFeePct:F,tradeFeeRange:M,priceImpactPct:w,errors:_,toHuman(){return{...a,amountOut:K(y,m.decimalsOut),calculatedIn:K(N,m.decimalsIn),amountIn:K(B,m.decimalsIn),spotPrice:K(k,m.decimalsIn),tradeFeePct:F,tradeFeeRange:M,priceImpactPct:w,errors:_}}})}return r}};export{Fe as AssetClient,_t as AssetNotFound,Br as BASILISK_PARACHAIN_ID,_e as BalanceClient,G as BigNumber,Ot as CachingPoolService,Zt as DECIMAL_PLACES,ft as DENOMINATOR,Pt as FarmClient,Ye as HYDRADX_OMNIPOOL_ADDRESS,Or as HYDRADX_PARACHAIN_ID,Te as HYDRADX_SS58_PREFIX,dr as INFINITY,me as LbpMath,De as LbpPool,le as ONE,W as OmniMath,Me as OmniPool,Ft as PoolConfigNotFound,Ae as PoolError,qe as PoolFactory,Ve as PoolNotFound,Re as PoolService,re as PoolType,kt as ProviderConfigNotFound,Ne as RUNTIME_DECIMALS,Ee as RouteNotFound,Oe as Router,xr as SYSTEM_ASSET_DECIMALS,we as SYSTEM_ASSET_ID,te as StableMath,Ce as StableSwap,Et as StorageConfigNotFound,Rt as SubscriptionNotSupported,dt as TRADEABLE_DEFAULT,lt as TradeRouter,It as TradeType,Pe as XykMath,Ge as XykPool,R as ZERO,v as bnum,bt as buildRoute,Jt as calculateBuyFee,Tl as calculateDiffToAvg,He as calculateDiffToRef,jt as calculateSellFee,At as findNestedKey,Ir as findNestedObj,J as scale};
@@ -10,7 +10,8 @@ export declare class BalanceClient extends PolkadotApiClient {
10
10
  getTokenBalanceData(accountId: string, tokenKey: string): Promise<OrmlTokensAccountData>;
11
11
  getAccountBalanceData(accountId: string): Promise<Vec<ITuple<[u32, OrmlTokensAccountData]>>>;
12
12
  getBalance(accountId: string, tokenKey: string): Promise<BigNumber>;
13
- subscribeBalance(address: string, tokens: string[], onChange: (token: string, balance: BigNumber) => void): UnsubscribePromise;
13
+ subscribeBalances(address: string, onChange: (balances: [string, BigNumber][]) => void): UnsubscribePromise;
14
+ subscribeBalance(address: string, token: string, onChange: (token: string, balance: BigNumber) => void): UnsubscribePromise;
14
15
  subscribeTokenBalance(address: string, tokens: string[], onChange: (token: string, balance: BigNumber) => void): UnsubscribePromise;
15
16
  subscribeSystemBalance(address: string, onChange: (token: string, balance: BigNumber) => void): UnsubscribePromise;
16
17
  private calculateFreeBalance;
@@ -0,0 +1,24 @@
1
+ import { ApiPromise } from '@polkadot/api';
2
+ import { UnsubscribePromise, VoidFn } from '@polkadot/api-base/types';
3
+ import { PoolBase, PoolFees, PoolType } from '../types';
4
+ import { BalanceClient } from '../client';
5
+ export declare abstract class PoolClient extends BalanceClient {
6
+ protected pools: PoolBase[];
7
+ protected subs: VoidFn[];
8
+ private poolsLoaded;
9
+ constructor(api: ApiPromise);
10
+ abstract isSupported(): boolean;
11
+ protected abstract loadPools(): Promise<PoolBase[]>;
12
+ abstract getPoolType(): PoolType;
13
+ abstract getPoolFees(feeAsset: string, address: string): Promise<PoolFees>;
14
+ protected abstract subscribePoolChange(pool: PoolBase): UnsubscribePromise;
15
+ getPools(): Promise<PoolBase[]>;
16
+ subscribe(): Promise<VoidFn[]>;
17
+ private subscribeLog;
18
+ unsubscribe(): void;
19
+ private hasShareAsset;
20
+ private subscribeTokensPoolBalance;
21
+ private subscribeSharePoolBalance;
22
+ private updateBalancesCallback;
23
+ private updateBalanceCallback;
24
+ }
@@ -1,6 +1,6 @@
1
1
  import { UnsubscribePromise } from '@polkadot/api-base/types';
2
2
  import { PoolBase, PoolFees, PoolType } from '../../types';
3
- import { PoolClient } from '../PoolClient';
3
+ import { PoolClient } from '../PoolClientV2';
4
4
  export declare class LbpPoolClient extends PoolClient {
5
5
  private readonly MAX_FINAL_WEIGHT;
6
6
  private poolsData;
@@ -1,6 +1,6 @@
1
1
  import { UnsubscribePromise } from '@polkadot/api-base/types';
2
2
  import { PoolBase, PoolType, PoolFees } from '../../types';
3
- import { PoolClient } from '../PoolClient';
3
+ import { PoolClient } from '../PoolClientV2';
4
4
  export declare class OmniPoolClient extends PoolClient {
5
5
  isSupported(): boolean;
6
6
  loadPools(): Promise<PoolBase[]>;
@@ -1,6 +1,6 @@
1
1
  import { UnsubscribePromise } from '@polkadot/api-base/types';
2
2
  import { PoolBase, PoolType, PoolFees } from '../../types';
3
- import { PoolClient } from '../PoolClient';
3
+ import { PoolClient } from '../PoolClientV2';
4
4
  export declare class StableSwapClient extends PoolClient {
5
5
  private stablePools;
6
6
  isSupported(): boolean;
@@ -1,6 +1,6 @@
1
1
  import { UnsubscribePromise } from '@polkadot/api-base/types';
2
2
  import { PoolBase, PoolType, PoolFees } from '../../types';
3
- import { PoolClient } from '../PoolClient';
3
+ import { PoolClient } from '../PoolClientV2';
4
4
  export declare class XykPoolClient extends PoolClient {
5
5
  isSupported(): boolean;
6
6
  loadPools(): Promise<PoolBase[]>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk",
3
- "version": "4.3.0",
3
+ "version": "4.4.0-pr89-e1182c7",
4
4
  "description": "Galactic off-chain routing & optimization of orders across pools for best price execution",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {