@galacticcouncil/sdk 3.1.0 → 3.1.1

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 wt=Object.defineProperty;var ar=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var ur=Object.prototype.hasOwnProperty;var cr=(m,e)=>{for(var t in e)wt(m,t,{get:e[t],enumerable:!0})},mr=(m,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lr(e))!ur.call(m,s)&&s!==t&&wt(m,s,{get:()=>e[s],enumerable:!(r=ar(e,s))||r.enumerable});return m};var pr=m=>mr(wt({},"__esModule",{value:!0}),m);var Ar={};cr(Ar,{AssetClient:()=>Le,AssetNotFound:()=>_t,BASILISK_PARACHAIN_ID:()=>br,BalanceClient:()=>Me,BigNumber:()=>q,CachingPoolService:()=>bt,DECIMAL_PLACES:()=>zt,DENOMINATOR:()=>st,FarmClient:()=>it,HYDRADX_OMNIPOOL_ADDRESS:()=>$e,HYDRADX_PARACHAIN_ID:()=>Pr,HYDRADX_SS58_PREFIX:()=>ke,INFINITY:()=>dr,LbpMath:()=>pe,LbpPool:()=>Ie,ONE:()=>ae,OmniMath:()=>X,OmniPool:()=>Ae,PoolConfigNotFound:()=>Tt,PoolError:()=>Re,PoolFactory:()=>Ue,PoolNotFound:()=>je,PoolService:()=>Ce,PoolType:()=>ie,ProviderConfigNotFound:()=>kt,RUNTIME_DECIMALS:()=>Ee,RouteNotFound:()=>De,Router:()=>_e,SYSTEM_ASSET_DECIMALS:()=>fr,SYSTEM_ASSET_ID:()=>Oe,StableMath:()=>re,StableSwap:()=>Ne,StorageConfigNotFound:()=>Rt,SubscriptionNotSupported:()=>Et,TRADEABLE_DEFAULT:()=>rt,TradeRouter:()=>Ke,TradeType:()=>It,XykMath:()=>Se,XykPool:()=>Fe,ZERO:()=>_,bnum:()=>I,buildRoute:()=>ct,calculateBuyFee:()=>qt,calculateDiffToAvg:()=>Ir,calculateDiffToRef:()=>ze,calculateSellFee:()=>Gt,findNestedKey:()=>At,findNestedObj:()=>yr,scale:()=>Z});module.exports=pr(Ar);var Ve=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var gr=5,Ye=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new Ve,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>gr)return s;let u=c[c.length-1];(r===null||u[0]===r)&&s.push(c),e.get(u[0])?.forEach(O=>{if(this.isNotVisited(O,c)){let B=[...c];B.push(O),i.enqueue(B)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,a]of t){let c=parseInt(i),u=parseInt(a);r.get(c)?.push([u,s])}return r}};function xt(m){let e={};for(let t of m){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let a=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(a)}}}return e}var We=class{getProposals(e,t,r){let s=xt(r),i=Object.keys(s),a=i.map(O=>s[O]).flat(),c=new Ye,u=c.buildAndPopulateGraph(i,a),y=c.findPaths(u,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let a=r[i],c=r[i+1];if(c==null)break;s.push(this.toEdge(a,c))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var hr=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ot=Math.ceil,ce=Math.floor,se="[BigNumber Error] ",Ht=se+"Number primitive has more than 15 significant digits: ",he=1e14,N=14,Bt=9007199254740991,vt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Be=1e7,J=1e9;function Ut(m){var e,t,r,s=w.prototype={constructor:w,toString:null,valueOf:null},i=new w(1),a=20,c=4,u=-7,y=21,O=-1e7,B=1e7,F=!1,R=1,T=0,C={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},L="0123456789abcdefghijklmnopqrstuvwxyz",W=!0;function w(n,o){var l,P,g,d,S,p,h,b,f=this;if(!(f instanceof w))return new w(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<O?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!hr.test(b=String(n)))return r(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(H(o,2,L.length,"Base"),o==10&&W)return f=new w(n),E(f,a+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return r(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,w.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Ht+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=L.slice(0,o),d=S=0,h=b.length;S<h;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return r(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&w.DEBUG&&h>15&&(n>Bt||n!==ce(n)))throw Error(Ht+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<O)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%N,d<0&&(S+=N),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=N;S<h;)f.c.push(+b.slice(S,S+=N));S=N-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}w.clone=Ut,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],H(l,0,J,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],H(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(H(l[0],-J,0,o),H(l[1],0,J,o),u=l[0],y=l[1]):(H(l,-J,J,o),u=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)H(l[0],-J,-1,o),H(l[1],1,J,o),O=l[0],B=l[1];else if(H(l,-J,J,o),l)O=-(B=l<0?-l:l);else throw Error(se+o+" cannot be zero: "+l);if(n.hasOwnProperty(o="CRYPTO"))if(l=n[o],l===!!l)if(l)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))F=l;else throw F=!l,Error(se+"crypto unavailable");else F=l;else throw Error(se+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],H(l,0,9,o),R=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],H(l,0,J,o),T=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")C=l;else throw Error(se+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))W=l.slice(0,10)=="0123456789",L=l;else throw Error(se+o+" invalid: "+l)}else throw Error(se+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[u,y],RANGE:[O,B],CRYPTO:F,MODULO_MODE:R,POW_PRECISION:T,FORMAT:C,ALPHABET:L}},w.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!w.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-J&&g<=J&&g===ce(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%N,o<1&&(o+=N),String(P[0]).length==o){for(o=0;o<P.length;o++)if(l=P[o],l<0||l>=he||l!==ce(l))break e;if(l!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(se+"Invalid BigNumber: "+n)},w.maximum=w.max=function(){return oe(arguments,-1)},w.minimum=w.min=function(){return oe(arguments,1)},w.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ce(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,S,p,h=0,b=[],f=new w(i);if(l==null?l=a:H(l,0,J),S=Ot(l/N),F)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));h<S;)p=P[h]*131072+(P[h+1]>>>11),p>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(p%1e14),h+=2);h=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);h<S;)p=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],p>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(p%1e14),h+=7);h=S/7}else throw F=!1,Error(se+"crypto unavailable");if(!F)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],l%=N,S&&l&&(p=vt[N-l],b[h]=ce(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=N);for(h=1,p=b[0];p>=10;p/=10,h++);h<N&&(d-=N-h)}return f.e=d,f.c=b,f}}(),w.sum=function(){for(var n=1,o=arguments,l=new w(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var S,p=[0],h,b=0,f=l.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(l.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(l,P,g,d,S){var p,h,b,f,x,v,A,M,U=l.indexOf("."),j=a,k=c;for(U>=0&&(f=T,T=0,l=l.replace(".",""),M=new w(P),v=M.pow(l.length-U),T=f,M.c=o(xe(ue(v.c),v.e,"0"),10,g,n),M.e=M.c.length),A=o(l,P,g,S?(p=L,n):(p=n,L)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(U<0?--b:(v.c=A,v.e=b,v.s=d,v=e(v,M,j,k,g),A=v.c,x=v.r,b=v.e),h=b+j+1,U=A[h],f=g/2,x=x||h<0||A[h+1]!=null,x=k<4?(U!=null||x)&&(k==0||k==(v.s<0?3:2)):U>f||U==f&&(k==4||x||k==6&&A[h-1]&1||k==(v.s<0?8:7)),h<1||!A[0])l=x?xe(p.charAt(1),-j,p.charAt(0)):p.charAt(0);else{if(A.length=h,x)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(U=0,l="";U<=f;l+=p.charAt(A[U++]));l=xe(l,b,p.charAt(0))}return l}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,x=P.length,v=g%Be,A=g/Be|0;for(P=P.slice();x--;)h=P[x]%Be,b=P[x]/Be|0,S=A*h+b*v,p=v*h+S%Be*Be+f,f=(p/d|0)+(S/Be|0)+A*b,P[x]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function l(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,x,v,A,M,U,j,k,G,ee,Qe,yt,St,fe,Xe,le=P.s==g.s?1:-1,te=P.c,z=g.c;if(!te||!te[0]||!z||!z[0])return new w(!P.s||!g.s||(te?z&&te[0]==z[0]:!z)?NaN:te&&te[0]==0||!z?le*0:le/0);for(U=new w(le),j=U.c=[],b=P.e-g.e,le=d+b+1,p||(p=he,b=me(P.e/N)-me(g.e/N),le=le/N|0),f=0;z[f]==(te[f]||0);f++);if(z[f]>(te[f]||0)&&b--,le<0)j.push(1),x=!0;else{for(yt=te.length,fe=z.length,f=0,le+=2,v=ce(p/(z[0]+1)),v>1&&(z=n(z,v,p),te=n(te,v,p),fe=z.length,yt=te.length),Qe=fe,k=te.slice(0,fe),G=k.length;G<fe;k[G++]=0);Xe=z.slice(),Xe=[0].concat(Xe),St=z[0],z[1]>=p/2&&St++;do{if(v=0,h=o(z,k,fe,G),h<0){if(ee=k[0],fe!=G&&(ee=ee*p+(k[1]||0)),v=ce(ee/St),v>1)for(v>=p&&(v=p-1),A=n(z,v,p),M=A.length,G=k.length;o(A,k,M,G)==1;)v--,l(A,fe<M?Xe:z,M,p),M=A.length,h=1;else v==0&&(h=v=1),A=z.slice(),M=A.length;if(M<G&&(A=[0].concat(A)),l(k,A,G,p),G=k.length,h==-1)for(;o(z,k,fe,G)<1;)v++,l(k,fe<G?Xe:z,G,p),G=k.length}else h===0&&(v++,k=[0]);j[f++]=v,k[0]?k[G++]=te[Qe]||0:(k=[te[Qe]],G=1)}while((Qe++<yt||k[0]!=null)&&le--);x=k[0]!=null,j[0]||j.splice(0,1)}if(p==he){for(f=1,le=j[0];le>=10;le/=10,f++);E(U,d+(U.e=f+b*N-1)+1,S,x)}else U.e=b,U.r=+x;return U}}();function Q(n,o,l,P){var g,d,S,p,h;if(l==null?l=c:H(l,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ue(n.c),h=P==1||P==2&&(S<=u||S>=y)?tt(h,S):xe(h,S,"0");else if(n=E(new w(n),o,l),d=n.e,h=ue(n.c),p=h.length,P==1||P==2&&(o<=d||d<=u)){for(;p<o;h+="0",p++);h=tt(h,d)}else if(o-=S,h=xe(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function oe(n,o){for(var l,P,g=1,d=new w(n[0]);g<n.length;g++)P=new w(n[g]),(!P.s||(l=Te(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function we(n,o,l){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(l=P+l*N-1)>B?n.c=n.e=null:l<O?n.c=[n.e=0]:(n.e=l,n.c=o),n}r=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,h){var b,f=p?S:S.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(x,v,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?v:x}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new w(f,b);if(w.DEBUG)throw Error(se+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function E(n,o,l,P){var g,d,S,p,h,b,f,x=n.c,v=vt;if(x){e:{for(g=1,p=x[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=N,S=o,h=x[b=0],f=ce(h/v[g-S-1]%10);else if(b=Ot((d+1)/N),b>=x.length)if(P){for(;x.length<=b;x.push(0));h=f=0,g=1,d%=N,S=d-N+1}else break e;else{for(h=p=x[b],g=1;p>=10;p/=10,g++);d%=N,S=d-N+g,f=S<0?0:ce(h/v[g-S-1]%10)}if(P=P||o<0||x[b+1]!=null||(S<0?h:h%v[g-S-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?S>0?h/v[g-S]:0:x[b-1])%10&1||l==(n.s<0?8:7)),o<1||!x[0])return x.length=0,P?(o-=n.e+1,x[0]=v[(N-o%N)%N],n.e=-o||0):x[0]=n.e=0,n;if(d==0?(x.length=b,p=1,b--):(x.length=b+1,p=v[N-d],x[b]=S>0?ce(h/v[g-S]%v[S])*p:0),P)for(;;)if(b==0){for(d=1,S=x[0];S>=10;S/=10,d++);for(S=x[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,x[0]==he&&(x[0]=1));break}else{if(x[b]+=p,x[b]!=he)break;x[b--]=0,p=1}for(d=x.length;x[--d]===0;x.pop());}n.e>B?n.c=n.e=null:n.e<O&&(n.c=[n.e=0])}return n}function Y(n){var o,l=n.e;return l===null?n.toString():(o=ue(n.c),o=l<=u||l>=y?tt(o,l):xe(o,l,"0"),n.s<0?"-"+o:o)}return s.absoluteValue=s.abs=function(){var n=new w(this);return n.s<0&&(n.s=1),n},s.comparedTo=function(n,o){return Te(this,new w(n,o))},s.decimalPlaces=s.dp=function(n,o){var l,P,g,d=this;if(n!=null)return H(n,0,J),o==null?o=c:H(o,0,8),E(new w(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-me(this.e/N))*N,g=l[g])for(;g%10==0;g/=10,P--);return P<0&&(P=0),P},s.dividedBy=s.div=function(n,o){return e(this,new w(n,o),a,c)},s.dividedToIntegerBy=s.idiv=function(n,o){return e(this,new w(n,o),0,1)},s.exponentiatedBy=s.pow=function(n,o){var l,P,g,d,S,p,h,b,f,x=this;if(n=new w(n),n.c&&!n.isInteger())throw Error(se+"Exponent not an integer: "+Y(n));if(o!=null&&(o=new w(o)),p=n.e>14,!x.c||!x.c[0]||x.c[0]==1&&!x.e&&x.c.length==1||!n.c||!n.c[0])return f=new w(Math.pow(+Y(x),p?n.s*(2-et(n)):+Y(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new w(NaN);P=!h&&x.isInteger()&&o.isInteger(),P&&(x=x.mod(o))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||p&&x.c[1]>=24e7:x.c[0]<8e13||p&&x.c[0]<=9999975e7)))return d=x.s<0&&et(n)?-0:0,x.e>-1&&(d=1/d),new w(h?1/d:d);T&&(d=Ot(T/N+2))}for(p?(l=new w(.5),h&&(n.s=1),b=et(n)):(g=Math.abs(+Y(n)),b=g%2),f=new w(i);;){if(b){if(f=f.times(x),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(g){if(g=ce(g/2),g===0)break;b=g%2}else if(n=n.times(l),E(n,n.e+1,1),n.e>14)b=et(n);else{if(g=+Y(n),g===0)break;b=g%2}x=x.times(x),d?x.c&&x.c.length>d&&(x.c.length=d):P&&(x=x.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?E(f,T,c,S):f)},s.integerValue=function(n){var o=new w(this);return n==null?n=c:H(n,0,8),E(o,o.e+1,n)},s.isEqualTo=s.eq=function(n,o){return Te(this,new w(n,o))===0},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(n,o){return Te(this,new w(n,o))>0},s.isGreaterThanOrEqualTo=s.gte=function(n,o){return(o=Te(this,new w(n,o)))===1||o===0},s.isInteger=function(){return!!this.c&&me(this.e/N)>this.c.length-2},s.isLessThan=s.lt=function(n,o){return Te(this,new w(n,o))<0},s.isLessThanOrEqualTo=s.lte=function(n,o){return(o=Te(this,new w(n,o)))===-1||o===0},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&this.c[0]==0},s.minus=function(n,o){var l,P,g,d,S=this,p=S.s;if(n=new w(n,o),o=n.s,!p||!o)return new w(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/N,b=n.e/N,f=S.c,x=n.c;if(!h||!b){if(!f||!x)return f?(n.s=-o,n):new w(x?S:NaN);if(!f[0]||!x[0])return x[0]?(n.s=-o,n):new w(f[0]?S:c==3?-0:0)}if(h=me(h),b=me(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=x),g.reverse(),o=p;o--;g.push(0));g.reverse()}else for(P=(d=(p=f.length)<(o=x.length))?p:o,p=o=0;o<P;o++)if(f[o]!=x[o]){d=f[o]<x[o];break}if(d&&(g=f,f=x,x=g,n.s=-n.s),o=(P=x.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=he-1;P>p;){if(f[--P]<x[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=he}f[P]-=x[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?we(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},s.modulo=s.mod=function(n,o){var l,P,g=this;return n=new w(n,o),!g.c||!n.s||n.c&&!n.c[0]?new w(NaN):!n.c||g.c&&!g.c[0]?new w(g):(R==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,R),n=g.minus(l.times(n)),!n.c[0]&&R==1&&(n.s=g.s),n)},s.multipliedBy=s.times=function(n,o){var l,P,g,d,S,p,h,b,f,x,v,A,M,U,j,k=this,G=k.c,ee=(n=new w(n,o)).c;if(!G||!ee||!G[0]||!ee[0])return!k.s||!n.s||G&&!G[0]&&!ee||ee&&!ee[0]&&!G?n.c=n.e=n.s=null:(n.s*=k.s,!G||!ee?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=me(k.e/N)+me(n.e/N),n.s*=k.s,h=G.length,x=ee.length,h<x&&(M=G,G=ee,ee=M,g=h,h=x,x=g),g=h+x,M=[];g--;M.push(0));for(U=he,j=Be,g=x;--g>=0;){for(l=0,v=ee[g]%j,A=ee[g]/j|0,S=h,d=g+S;d>g;)b=G[--S]%j,f=G[S]/j|0,p=A*b+f*v,b=v*b+p%j*j+M[d]+l,l=(b/U|0)+(p/j|0)+A*f,M[d--]=b%U;M[d]=l}return l?++P:M.splice(0,1),we(n,M,P)},s.negated=function(){var n=new w(this);return n.s=-n.s||null,n},s.plus=function(n,o){var l,P=this,g=P.s;if(n=new w(n,o),o=n.s,!g||!o)return new w(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/N,S=n.e/N,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new w(g/0);if(!p[0]||!h[0])return h[0]?n:new w(p[0]?P:g*0)}if(d=me(d),S=me(S),p=p.slice(),g=d-S){for(g>0?(S=d,l=h):(g=-g,l=p),l.reverse();g--;l.push(0));l.reverse()}for(g=p.length,o=h.length,g-o<0&&(l=h,h=p,p=l,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/he|0,p[o]=he===p[o]?0:p[o]%he;return g&&(p=[g].concat(p),++S),we(n,p,S)},s.precision=s.sd=function(n,o){var l,P,g,d=this;if(n!=null&&n!==!!n)return H(n,1,J),o==null?o=c:H(o,0,8),E(new w(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*N+1,g=l[g]){for(;g%10==0;g/=10,P--);for(g=l[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},s.shiftedBy=function(n){return H(n,-Bt,Bt),this.times("1e"+n)},s.squareRoot=s.sqrt=function(){var n,o,l,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new w("0.5");if(p!==1||!S||!S[0])return new w(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+Y(d)),p==0||p==1/0?(o=ue(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=me((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new w(o)):l=new w(p+""),l.c[0]){for(h=l.e,p=h+b,p<3&&(p=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ue(g.c).slice(0,p)===(o=ue(l.c)).slice(0,p))if(l.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(E(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(E(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return E(l,l.e+a+1,c,n)},s.toExponential=function(n,o){return n!=null&&(H(n,0,J),n++),Q(this,n,o,1)},s.toFixed=function(n,o){return n!=null&&(H(n,0,J),n=n+this.e+1),Q(this,n,o)},s.toFormat=function(n,o,l){var P,g=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=C;else if(typeof l!="object")throw Error(se+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],x=S[1],v=g.s<0,A=v?f.slice(1):f,M=A.length;if(h&&(d=p,p=h,h=d,M-=d),p>0&&M>0){for(d=M%p||p,f=A.substr(0,d);d<M;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=x?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?x.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):x):f}return(l.prefix||"")+P+(l.suffix||"")},s.toFraction=function(n){var o,l,P,g,d,S,p,h,b,f,x,v,A=this,M=A.c;if(n!=null&&(p=new w(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(se+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+Y(p));if(!M)return new w(A);for(o=new w(i),b=l=new w(i),P=h=new w(i),v=ue(M),d=o.e=v.length-A.e-1,o.c[0]=vt[(S=d%N)<0?N+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new w(v),h.c[0]=0;f=e(p,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,x=e(b,P,d,c).minus(A).abs().comparedTo(e(h,l,d,c).minus(A).abs())<1?[b,P]:[h,l],B=S,x},s.toNumber=function(){return+Y(this)},s.toPrecision=function(n,o){return n!=null&&H(n,1,J),Q(this,n,o,2)},s.toString=function(n){var o,l=this,P=l.s,g=l.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=u||g>=y?tt(ue(l.c),g):xe(ue(l.c),g,"0"):n===10&&W?(l=E(new w(l),a+g+1,c),o=xe(ue(l.c),l.e,"0")):(H(n,2,L.length,"Base"),o=t(xe(ue(l.c),g,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},s.valueOf=s.toJSON=function(){return Y(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,m!=null&&w.set(m),w}function me(m){var e=m|0;return m>0||m===e?e:e-1}function ue(m){for(var e,t,r=1,s=m.length,i=m[0]+"";r<s;){for(e=m[r++]+"",t=N-e.length;t--;e="0"+e);i+=e}for(s=i.length;i.charCodeAt(--s)===48;);return i.slice(0,s+1||1)}function Te(m,e){var t,r,s=m.c,i=e.c,a=m.s,c=e.s,u=m.e,y=e.e;if(!a||!c)return null;if(t=s&&!s[0],r=i&&!i[0],t||r)return t?r?0:-c:a;if(a!=c)return a;if(t=a<0,r=u==y,!s||!i)return r?0:!s^t?1:-1;if(!r)return u>y^t?1:-1;for(c=(u=s.length)<(y=i.length)?u:y,a=0;a<c;a++)if(s[a]!=i[a])return s[a]>i[a]^t?1:-1;return u==y?0:u>y^t?1:-1}function H(m,e,t,r){if(m<e||m>t||m!==ce(m))throw Error(se+(r||"Argument")+(typeof m=="number"?m<e||m>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(m))}function et(m){var e=m.c.length-1;return me(m.e/N)==e&&m.c[e]%2!=0}function tt(m,e){return(m.length>1?m.charAt(0)+"."+m.slice(1):m)+(e<0?"e":"e+")+e}function xe(m,e,t){var r,s;if(e<0){for(s=t+".";++e;s+=t);m=s+m}else if(r=m.length,++e>r){for(s=t,e-=r;--e;s+=t);m+=s}else e<r&&(m=m.slice(0,e)+"."+m.slice(e));return m}var q=Ut();var zt=12;q.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:zt});var _=I(0),ae=I(1),dr=I("Infinity");function Z(m,e){let t=new q(e.toString()),r=new q(10).pow(t);return m.times(r)}function I(m){return new q(m.toString())}var ie=(s=>(s.XYK="Xyk",s.LBP="Lbp",s.Stable="Stableswap",s.Omni="Omnipool",s))(ie||{}),Re=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(Re||{}),It=(t=>(t.Buy="Buy",t.Sell="Sell",t))(It||{});var Pe=require("@galacticcouncil/math-lbp"),pe=class{static getSpotPrice(e,t,r,s,i){return(0,Pe.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,Pe.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,Pe.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,Pe.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,Pe.calculate_pool_trade_fee)(e,t,r)}};var Xt=require("@polkadot/util-crypto"),Yt=require("@polkadot/util"),Ee=18,rt=15,Oe="0",fr=12,Pr=2034,ke=63,br=2090,st=1e3,$e=(0,Xt.encodeAddress)((0,Yt.stringToU8a)("modlomnipool".padEnd(32,"\0")),ke);function At(m,e){let t;return JSON.stringify(m,(r,s)=>(s&&s[e]&&(t=s),s)),t}function yr(m,e,t){let r;return JSON.stringify(m,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Qr=require("@polkadot/types/lookup");var Vr=require("@polkadot/api-base/types/consts");var es=require("@polkadot/api-base/types/errors");var ts=require("@polkadot/api-base/types/events");var rs=require("@polkadot/api-base/types/storage");var ss=require("@polkadot/api-base/types/submittable");var is=require("@polkadot/rpc-core/types/jsonrpc");var ns=require("@polkadot/api-base/types/calls");var gs=require("@polkadot/types/types/registry");var Ps=require("@polkadot/types/lookup");var bs=require("@polkadot/api-base/types/consts");var ys=require("@polkadot/api-base/types/errors");var Ss=require("@polkadot/api-base/types/events");var ws=require("@polkadot/api-base/types/storage");var xs=require("@polkadot/api-base/types/submittable");var Os=require("@polkadot/rpc-core/types/jsonrpc");var Bs=require("@polkadot/api-base/types/calls");var Rs=require("@polkadot/types/types/registry");var ve=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Le=class extends ve{SUPPORTED_TYPES=["StableSwap","Bond","Token","External"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==Oe){let B=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:B.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:u}=t,{symbol:y,decimals:O}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:y,decimals:O,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:this.parseLocation("parachain",s),existentialDeposit:u.toString()}}getBond(e,t,r,s){let[i,a]=s,{assetType:c,isSufficient:u,existentialDeposit:y}=t,{symbol:O,decimals:B}=this.getToken(i.toString(),t,r),F=a.toNumber(),R=new Intl.DateTimeFormat("en-GB"),T=[O,"Bond",R.format(F)].join(" ");return{id:e,name:T,symbol:O+"b",decimals:B,icon:O,type:c.toString(),isSufficient:u.toHuman(),existentialDeposit:y.toString()}}getShares(e,t,r,s){let{assets:i}=s,{name:a,symbol:c,assetType:u,isSufficient:y,existentialDeposit:O}=t,F=i.map(C=>C.toString()).map(C=>{let{symbol:L}=this.getToken(C,t,r);return[C,L]}),R=Object.fromEntries(F),T=Object.values(R);return{id:e,name:T.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:T.join("/"),type:u.toString(),isSufficient:y.toHuman(),existentialDeposit:O.toString(),meta:R}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),a=r?.find(c=>c.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:a}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e){let[t,r,s,i,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),c=this.getSupportedAssets(t),u=this.normalizeMetadata(c,a);return c.map(([{args:[y]},O])=>{let B=O.unwrap(),F=r.get(y.toString()),{assetType:R}=B;switch(R.toString()){case"Bond":let T=i.get(y.toString());return this.getBond(y.toString(),B,u,T);case"StableSwap":let C=s.get(y.toString());return this.getShares(y.toString(),B,u,C);case"External":return this.getExternal(y.toString(),B,e,F);default:return this.getToken(y.toString(),B,u,F)}}).filter(y=>this.isValidAsset(y))}isValidAsset(e){return!!e.symbol&&!!e.decimals}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let r=At(t.toJSON(),e);return r&&r[e]}else return}};var Me=class extends ve{constructor(e){super(e)}async getBalance(e,t){return t===Oe?await this.getSystemBalance(e):await this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:i})}async subscribeBalance(e,t,r){let s=t.filter(i=>i!==Oe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach(({free:a,reserved:c,frozen:u},y)=>{let O=this.calculateFreeBalance({free:a,feeFrozen:c,frozen:u}),B=s[y][1];r(B,O)})})}async subscribeTokenBalance(e,t,r){let s=t.filter(i=>i!==Oe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach((a,c)=>{let u=this.calculateFreeBalance(a),y=s[c][1];r(y,u)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(Oe,this.calculateFreeBalance(r)))}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:i}=e,a=new q(t),c=new q(r||i),u=new q(s||0),y=c.gt(u)?c:u;return a.minus(y)}};var Nt=require("@polkadot/util-crypto"),Ft=require("@galacticcouncil/math-liquidity-mining");var it=class extends ve{constructor(e){super(e)}secondsInYear=new q(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(u)).unwrap(),O=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(u)).unwrap(),O=(await this.api.query.xykWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new q(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),c=a.price.n.toString(),u=a.price.d.toString(),y;return Number(t)<Number(r)?y=(0,Ft.fixed_from_rational)(c,u):y=(0,Ft.fixed_from_rational)(u,c),y}getGlobalRewardPerPeriod(e,t,r,s){let a=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return a.gte(r)?r:a}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,Nt.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,Nt.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:c,globalFarm:u,priceAdjustment:y})=>{let O=new q(u.totalSharesZ.toString()),B=u.plannedYieldingPeriods.toString(),F=new q(u.yieldPerPeriod.toString()),R=new q(u.maxRewardPerPeriod.toString()),T=u.blocksPerPeriod.toString(),C=new q(c.multiplier.toString()).shiftedBy(-18),L=this.secondsInYear.div(new q(r).times(T)),W;if(O.isZero())W=F.times(C).times(L);else{let we=this.getGlobalRewardPerPeriod(O,F,R,y);W=this.getPoolYieldPerPeriod(we,C,O,y).times(L)}let w=new q(u.pendingRewards.toString()).plus(u.accumulatedPaidRewards.toString()),Q=R.times(B);return w.div(Q).gte(.99)?_:W.times(100)}).reduce((c,u)=>c.plus(u),_).toString():void 0}};var be=class extends Me{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async r=>{let s=[await this.subscribePoolChange(r),await this.subscribeTokensPoolBalance(r),await this.subscribeSystemPoolBalance(r)];if(this.hasShareAsset(r)){let i=await this.subscribeSharePoolBalance(r);s.push(i)}return this.subscribeLog(r),s});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,r)=>t.id!==r))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance($e,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(r,s){let i=e.tokens.findIndex(a=>a.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=s.toString())}}};var nt=class extends be{MAX_FINAL_WEIGHT=Z(I(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,a])=>this.isActivePool(a.unwrap(),r)).map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=await this.getPoolDelta(u,c,r.toString());return this.poolsData.set(i.toString(),c),{address:u,type:"Lbp",fee:c.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let a=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(c=>c.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,r){let{start:s,end:i,assets:a,initialWeight:c,finalWeight:u,repayTarget:y,feeCollector:O}=t,B=pe.calculateLinearWeights(s.toString(),i.toString(),c.toString(),u.toString(),r),[F,R]=a,T=F.toString(),C=I(B),L=R.toString(),W=this.MAX_FINAL_WEIGHT.minus(I(C)),[w,Q,oe]=await Promise.all([this.isRepayFeeApplied(T,y.toString(),O.toString()),this.getBalance(e,T),this.getBalance(e,L)]);return{repayFeeApply:w,tokens:[{id:T,weight:C,balance:Q.toString()},{id:L,weight:W,balance:oe.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=I(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var Wt=require("@polkadot/util-crypto"),$t=require("@polkadot/util");function V(m,e){return m.shiftedBy(-1*e).toString()}function ge(m){return m[0]/m[1]*100}function ne(m){return m[0]/m[1]}function de(m){return[m/st,st]}var ot=class extends be{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=r.map(async([{args:[u]},y])=>{let{hubReserve:O,shares:B,tradable:F}=y.unwrap(),R=await this.getBalance(t,u.toString());return{id:u.toString(),hubReserves:I(O.toString()),shares:I(B.toString()),tradeable:F.bits.toNumber(),balance:R.toString()}}),c=await Promise.all(a);return c.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:c,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=await this.api.query.dynamicFees.assetFee(e),s=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=s.minFee.toNumber()+i.minFee.toNumber(),c=s.maxFee.toNumber()+i.maxFee.toNumber();if(r.isSome){let{assetFee:u,protocolFee:y}=r.unwrap();return{assetFee:de(u.toNumber()),protocolFee:de(y.toNumber()),min:de(a),max:de(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:de(a),max:de(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,i)=>{let a=e.tokens[i];if(s.isNone)return a;let c=s.unwrap();return this.updateTokenState(a,c)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i}=t;return{...e,hubReserves:I(r.toString()),shares:I(s.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return de(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return de(t)}getPoolId(){return(0,Wt.encodeAddress)((0,$t.stringToU8a)("modlomnipool".padEnd(32,"\0")),ke)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var at=class extends be{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[a,c]=s.unwrap(),[u,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:u.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var ut=require("@polkadot/util-crypto");var K=require("@galacticcouncil/math-stableswap"),re=class{static getPoolAddress(e){return(0,K.pool_account_name)(e)}static calculateAmplification(e,t,r,s,i){return(0,K.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,a){return(0,K.calculate_in_given_out)(e,t,r,s,i,a)}static calculateAddOneAsset(e,t,r,s,i,a){return(0,K.calculate_add_one_asset)(e,t,r,s,i,a)}static calculateSharesForAmount(e,t,r,s,i,a){return(0,K.calculate_shares_for_amount)(e,t,r,s,i,a)}static calculateOutGivenIn(e,t,r,s,i,a){return(0,K.calculate_out_given_in)(e,t,r,s,i,a)}static calculateLiquidityOutOneAsset(e,t,r,s,i,a){return(0,K.calculate_liquidity_out_one_asset)(e,t,r,s,i,a)}static calculateShares(e,t,r,s,i){return(0,K.calculate_shares)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,K.calculate_pool_trade_fee)(e,t,r)}};var lt=class extends be{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=this.getPoolAddress(u),[O,B]=await Promise.all([this.getPoolDelta(u,c,r.toString()),this.getPoolTokens(y,u,c)]);return this.stablePools.set(y,c),{address:y,id:u,type:"Stableswap",fee:de(c.fee.toNumber()),tokens:B,...O,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toNumber(),s=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,s,r.toString());Object.assign(e,i)})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:a,finalBlock:c}=t,u=re.calculateAmplification(s.toString(),i.toString(),a.toString(),c.toString(),r),y=await this.api.query.tokens.totalIssuance(e);return{amplification:u,totalIssuance:y.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async u=>{let[y,O]=await Promise.all([this.api.query.stableswap.assetTradability(t,u.toString()),this.getBalance(e,u.toString())]);return{id:u.toString(),tradeable:y.bits.toNumber(),balance:O.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:u}=c.unwrap(),y=await this.getBalance($e,t);a.push({id:t,tradeable:u.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),r=re.getPoolAddress(t);return(0,ut.encodeAddress)((0,ut.blake2AsHex)(r),ke)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function ct(m){return m.map(({assetIn:e,assetOut:t,pool:r,poolId:s})=>r==="Stableswap"?{pool:{Stableswap:s},assetIn:e,assetOut:t}:{pool:r,assetIn:e,assetOut:t})}var je=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Tt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},De=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},_t=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Rt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},kt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Ce=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new Le(this.api),this.xykClient=new at(this.api),this.omniClient=new ot(this.api),this.lbpClient=new nt(this.api),this.stableClient=new lt(this.api)}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||this.syncRegistry(),e.length==0){let a=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(c=>c.isSupported()).map(c=>c.getPools()))).flat();return this.withMetadata(a)}let t=[];e.forEach(i=>{switch(i){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break;case"Stableswap":t.push(this.stableClient.getPools());break}});let s=(await Promise.all(t)).flat();return this.withMetadata(s)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(r=>[r.id,r]));return e.filter(r=>r.type==="Xyk"?r.tokens.every(s=>t.get(s.id)):!0).map(r=>{let s=r.tokens.map(i=>{let a=t.get(i.id);return{...i,...a}});return{...r,tokens:s}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new je(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,r,s,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,r.toFixed(),s.toFixed()):a=this.api.tx.router.buy(e,t,r.toFixed(),s.toFixed(),ct(i));let c=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,r,s,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,r.toFixed(),s.toFixed()):a=this.api.tx.router.sell(e,t,r.toFixed(),s.toFixed(),ct(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var Je=(m,e)=>m===e?0:m==null?e==null?0:-1:e==null?m==null?0:1:typeof m.compare=="function"?m.compare(e):typeof e.compare=="function"?-e.compare(m):m<e?-1:m>e?1:0;var mt=(m,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(m(t)+e(t))}};var Sr=mt(()=>"illegal argument(s)"),jt=m=>{throw new Sr(m)};var wr=mt(()=>"index out of bounds"),Lt=m=>{throw new wr(m)},pt=(m,e,t)=>(m<e||m>=t)&&Lt(m);var Jt=23283064365386963e-26,gt=class{float(e=1){return this.int()*Jt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Jt-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var Mt=Math.random,Dt=class extends gt{int(){return Mt()*4294967296>>>0}float(e=1){return Mt()*e}norm(e=1){return(Mt()-.5)*2*e}},Zt=new Dt;var Kt=m=>m!=null&&typeof m!="function"&&m.length!==void 0;var Qt=Object.getPrototypeOf({}),ht="function",Vt="string",Ge=(m,e)=>{let t;if(m===e)return!0;if(m!=null){if(typeof m.equiv===ht)return m.equiv(e)}else return m==e;if(e!=null){if(typeof e.equiv===ht)return e.equiv(m)}else return m==e;return typeof m===Vt||typeof e===Vt?!1:(t=Object.getPrototypeOf(m),(t==null||t===Qt)&&(t=Object.getPrototypeOf(e),t==null||t===Qt)?vr(m,e):typeof m!==ht&&m.length!==void 0&&typeof e!==ht&&e.length!==void 0?xr(m,e):m instanceof Set&&e instanceof Set?Or(m,e):m instanceof Map&&e instanceof Map?Br(m,e):m instanceof Date&&e instanceof Date?m.getTime()===e.getTime():m instanceof RegExp&&e instanceof RegExp?m.toString()===e.toString():m!==m&&e!==e)},xr=(m,e,t=Ge)=>{let r=m.length;if(r===e.length)for(;r-- >0&&t(m[r],e[r]););return r<0},Or=(m,e,t=Ge)=>m.size===e.size&&t([...m.keys()].sort(),[...e.keys()].sort()),Br=(m,e,t=Ge)=>m.size===e.size&&t([...m].sort(),[...e].sort()),vr=(m,e,t=Ge)=>{if(Object.keys(m).length!==Object.keys(e).length)return!1;for(let r in m)if(!e.hasOwnProperty(r)||!t(m[r],e[r]))return!1;return!0};var er=(m,e)=>m!=null&&typeof m[e]=="function";var tr=m=>er(m,"xform")?m.xform():m;var dt=Symbol(),Ct=()=>{};var rr=m=>m!=null&&typeof m[Symbol.iterator]=="function";var ft=class{value;constructor(e){this.value=e}deref(){return this.value}};var Pt=m=>m instanceof ft;var sr=m=>m instanceof ft?m.deref():m;function*ir(m,e){let t=tr(m)([Ct,Ct,(r,s)=>s])[2];for(let r of e){let s=t(dt,r);if(Pt(s)){s=sr(s.deref()),s!==dt&&(yield s);return}s!==dt&&(yield s)}}var nr=(m,e)=>[m[0],m[1],e];function Ze(m,e){return rr(e)?ir(Ze(m),e):t=>{let r=t[2];return nr(t,(s,i)=>r(s,m(i)))}}var qe=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return or("next",this._head)}reverseIterator(){return or("prev",this.tail)}clear(){this.release()}compare(e,t=Je){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,a=0;for(;r-- >0&&a===0;)a=t(s.value,i.value),s=s.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof qe||Kt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!Ge(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||Je;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!Pt(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&Lt(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*or(m,e){for(;e;)yield e.value,e=e[m]}var ye=class extends qe{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new ye(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new ye}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(pt(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(pt(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new ye,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=a=>({first(){return a.value},next(){return a!==s&&a.next?i(a.next):void 0}});return r?i(r):void 0}shuffle(e,t=Zt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&jt("invalid indices: ${from} / ${to}");let i=new ye,a=this.nthCell(r);for(;a&&++r<=s;)i.push(a.value),a=a.next;return i}sort(e=Je){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,a=0;for(let u=0;u<t&&(a++,i=i.next,!!i);u++);let c=t;for(;a>0||c>0&&i;){let u;a===0?(u=i,i=i.next,c--):!i||c===0||e(r.value,i.value)<=0?(u=r,r=r.next,a--):(u=i,i=i.next,c--),this._tail?this._tail.next=u:this._head=u,u.prev=this._tail,this._tail=u}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),pt(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new ye;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let a of r)this.insertBefore(s,a);else for(let a of r)this.push(a);return i}};var He=class{map;items;opts;_size;constructor(e,t){let r=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=r.map(),this.items=new ye,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ze(e=>[e.k,e],this.items)}keys(){return Ze(e=>e.k,this.items)}values(){return Ze(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new He(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e);return this._size+=Math.max(0,r-(s?s.value.s:0)),this.ensureSize()&&this.doSetEntry(s,e,t,r),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let r=this.map.get(e);return r?Promise.resolve(this.resetEntry(r)):t().then(s=>this.set(e,s))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,r=this.opts.maxlen;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e&&e(s.k,s.v),this._size-=s.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,r,s){e?(e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var bt=class extends Ce{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new He(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let r=[t.address,e].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let i=await super.getPoolFees(e,t);return this.feeCache.set(r,i),i}}async destroy(){console.log(`Destroying pool cache!
2
- Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Ie=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Ie(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,i,a,c){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=c}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let c=this.calculateTradeFee(t,r),u=ge(this.repayFeeApply?r.repayFee:r.exchangeFee),y=t.plus(c),O=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return O.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:O,calculatedIn:O,amountOut:t,feePct:u,errors:i}}else{let c=this.calculateInGivenOut(e,t),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let c=this.calculateOutGivenIn(e,t),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),u=this.calculateTradeFee(c,r),y=ge(this.repayFeeApply?r.repayFee:r.exchangeFee),O=c.minus(u),B=e.balanceOut.div(this.maxOutRatio);return O.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:O,feePct:y,errors:i}}}calculateInGivenOut(e,t){let r=pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?_:s}calculateOutGivenIn(e,t){let r=pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?_:s}spotPriceInGivenOut(e){let t=pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),Z(ae,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),Z(ae,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let r=pe.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(r)}};var D=require("@galacticcouncil/math-omnipool");var X=class{static calculateSpotPrice(e,t,r,s){return(0,D.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,D.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,a,c,u,y){return(0,D.calculate_in_given_out)(e,t,r,s,i,a,c,u,y)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,D.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,a,c,u,y){return(0,D.calculate_out_given_in)(e,t,r,s,i,a,c,u,y)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,D.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,D.calculate_pool_trade_fee)(e,t,r)}static calculateShares(e,t,r,s){return(0,D.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,a,c,u){return(0,D.calculate_liquidity_out)(e,t,r,s,i,a,c,u)}static calculateLiquidityLRNAOut(e,t,r,s,i,a,c,u){return(0,D.calculate_liquidity_lrna_out)(e,t,r,s,i,a,c,u)}static calculateCapDifference(e,t,r,s){let i=q(t),a=q(e),c=q(s),y=q(r).shiftedBy(-18);if(i.div(c).lt(y)){let B=y.times(c).minus(i).times(a),F=i.times(q(1).minus(y));return B.div(F).toFixed(0)}else return"0"}static verifyAssetCap(e,t,r,s){return(0,D.verify_asset_cap)(e,t,r,s)}static calculateLimitHubIn(e,t,r,s){return(0,D.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,D.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,D.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,D.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,D.is_remove_liquidity_allowed)(e)}};var Ae=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new Ae(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,i,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,tradeableIn:s.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),c=s===_?_:a.div(s).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),O=X.isBuyAllowed(e.tradeableOut);(!y||!O)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&u.push("MaxOutRatioExceeded");let F=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(F)&&u.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:c.toNumber(),errors:u}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),c=s.minus(i).div(s).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),O=X.isBuyAllowed(e.tradeableOut);(!y||!O)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&u.push("MaxInRatioExceeded");let F=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(F)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:c.toNumber(),errors:u}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=X.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ne(r.assetFee).toString():_.toString(),r?ne(r.protocolFee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateLrnaInGivenOut(e,t,r){let s=X.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ne(r.assetFee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=X.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ne(r.assetFee).toString():_.toString(),r?ne(r.protocolFee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateOutGivenLrnaIn(e,t,r){let s=X.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ne(r.assetFee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=X.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=X.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=X.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=X.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsIn)).decimalPlaces(0,1)}};var Ne=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Ne(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,r,s,i,a,c,u,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.amplification=a,this.id=c,this.fee=u,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?rt:s.tradeable,tradeableOut:this.id===t?rt:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=ge(r.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),a=ge(r.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,r){let s=re.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateAddOneAsset(e,t,r){let s=re.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateSharesForAmount(e,t,r){let s=re.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=Z(ae,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,r){let s=re.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateWithdrawOneAsset(e,t,r){let s=re.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateShares(e,t,r){let s=re.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=Z(ae,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let r=re.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(r)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};var $=require("@galacticcouncil/math-xyk"),Se=class{static getSpotPrice(e,t,r){return(0,$.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,$.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,$.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,$.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,$.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,$.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,$.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,$.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,$.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,$.calculate_liquidity_out_asset_b)(e,t,r,s)}};var Fe=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Fe(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),a=ge(r.exchangeFee),c=s.plus(i),u=[];t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&u.push("MaxOutRatioExceeded");let O=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(O)&&u.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:s,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),a=ge(r.exchangeFee),c=s.minus(i),u=[];t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&u.push("MaxInRatioExceeded");let O=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(O)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:c,feePct:a,errors:u}}calculateInGivenOut(e,t){let r=Se.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?_:s}calculateOutGivenIn(e,t){let r=Se.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?_:s}spotPriceInGivenOut(e){let t=Se.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=Z(ae,18-e.decimalsOut);return I(t).div(r)}spotPriceOutGivenIn(e){let t=Se.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=Z(ae,18-e.decimalsIn);return I(t).div(r)}calculateTradeFee(e,t){let r=Se.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(r)}};var Ue=class{static get(e){switch(e.type){case"Xyk":return Fe.fromPool(e);case"Omnipool":return Ae.fromPool(e);case"Lbp":return Ie.fromPool(e);case"Stableswap":return Ne.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var _e=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new We,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),a=this.getPaths(e,null,s,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(a)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,origin:s.origin,meta:s.meta}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(c=>this.validPath(c,r)).map(c=>this.toHops(c,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(r);return{assets:s,poolsMap:i}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,Ue.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,i])=>{let a=t.get(r);return{poolAddress:r,poolId:a?.id,pool:a?.type,assetIn:s,assetOut:i}})}toAssets(e,t){return e.map(r=>t.get(r))}};function Ir(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ze(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Gt(m,e){return ae.minus(e.div(m)).multipliedBy(100).decimalPlaces(2)}function qt(m,e){return e.div(m).minus(ae).multipliedBy(100).decimalPlaces(2)}var Ke=class extends _e{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,a=s[s.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[r,s]}}getPoolFeeRange(e){let t=e.min?ge(e.min):void 0,r=e.max?ge(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new De(e,t);let u;if(s)u=await this.toSellSwaps(r,s,a);else{let E=c.map(async n=>await this.toSellSwaps(r,n,a)),Y=await Promise.all(E);u=this.findBestSellRoute(Y)}let y=u[0],O=u[u.length-1],B=this.isDirectTrade(u),F=u.map(E=>E.spotPrice.shiftedBy(-1*E.assetOutDecimals)).reduce((E,Y)=>E.multipliedBy(Y)),R=Z(F,O.assetOutDecimals),T=B?O.calculatedOut:this.calculateDelta0Y(y.amountIn,u,a),C=O.amountOut,L=B?O.tradeFeePct:Gt(T,C).toNumber(),W=T.minus(C),w=this.getRouteFeeRange(u),Q=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(R),oe=ze(T,Q),we=E=>this.poolService.buildSellTx(e,t,y.amountIn,E,u.map(Y=>Y));return{type:"Sell",amountIn:y.amountIn,amountOut:O.amountOut,spotPrice:R,tradeFee:W,tradeFeePct:L,tradeFeeRange:w,priceImpactPct:oe.toNumber(),swaps:u,toTx:we,toHuman(){return{type:"Sell",amountIn:V(y.amountIn,y.assetInDecimals),amountOut:V(O.amountOut,O.assetOutDecimals),spotPrice:V(R,O.assetOutDecimals),tradeFee:V(W,O.assetOutDecimals),tradeFeePct:L,tradeFeeRange:w,priceImpactPct:oe.toNumber(),swaps:u.map(E=>E.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=s[i-1]:y=e;let O=c.calculateOutGivenIn(u,y);s.push(O)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=s[i-1].amountOut:y=Z(I(e),u.decimalsIn).decimalPlaces(0,1);let O=await this.poolService.getPoolFees(u.assetOut,c),{amountOut:B,calculatedOut:F,feePct:R,errors:T}=c.validateAndSell(u,y,O),C=this.getPoolFeeRange(O),L=c.spotPriceOutGivenIn(u),W=y.shiftedBy(-1*u.decimalsIn).multipliedBy(L),w=ze(F,W);s.push({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountIn:y,calculatedOut:F,amountOut:B,spotPrice:L,tradeFeePct:R,tradeFeeRange:C,priceImpactPct:w.toNumber(),errors:T,toHuman(){return{...a,amountIn:V(y,u.decimalsIn),calculatedOut:V(F,u.decimalsOut),amountOut:V(B,u.decimalsOut),spotPrice:V(L,u.decimalsOut),tradeFeePct:R,tradeFeeRange:C,priceImpactPct:w.toNumber(),errors:T}}})}return s}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r),i=super.getPaths(e,t,s,r);if(i.length===0)return Promise.resolve(void 0);let a=r.map(w=>w.tokens.find(Q=>Q.id===e)).filter(w=>!!w).sort((w,Q)=>Number(Q.balance)-Number(w.balance)),{balance:c,decimals:u}=a[0],O=I(c).shiftedBy(-1*u).div(100).multipliedBy(.1),B=i.map(async w=>await this.toSellSwaps(O,w,s)),F=await Promise.all(B),R=this.findBestSellRoute(F),T=await this.toSellSwaps("1",R,s),C=T.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,Q)=>w.multipliedBy(Q)),L=T[T.length-1].assetOutDecimals;return{amount:Z(C,L),decimals:L}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,a=s[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new De(e,t);let u;if(s)u=await this.toBuySwaps(r,s,a);else{let E=c.map(async n=>await this.toBuySwaps(r,n,a)),Y=await Promise.all(E);u=this.findBestBuyRoute(Y)}let y=u[u.length-1],O=u[0],B=this.isDirectTrade(u),F=u.map(E=>E.spotPrice.shiftedBy(-1*E.assetInDecimals)).reduce((E,Y)=>E.multipliedBy(Y)),R=Z(F,O.assetInDecimals),T=B?O.calculatedIn:this.calculateDelta0X(y.amountOut,u,a),C=O.amountIn,L=B?O.tradeFeePct:qt(T,C).toNumber(),W=C.minus(T),w=this.getRouteFeeRange(u),Q=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(R),oe;T.isZero()?oe=-100:oe=ze(Q,T).toNumber();let we=E=>this.poolService.buildBuyTx(e,t,y.amountOut,E,u.map(Y=>Y));return{type:"Buy",amountOut:y.amountOut,amountIn:O.amountIn,spotPrice:R,tradeFee:W,tradeFeePct:L,tradeFeeRange:w,priceImpactPct:oe,swaps:u,toTx:we,toHuman(){return{type:"Buy",amountOut:V(y.amountOut,y.assetOutDecimals),amountIn:V(O.amountIn,O.assetInDecimals),spotPrice:V(R,O.assetInDecimals),tradeFee:V(W,O.assetInDecimals),tradeFeePct:L,tradeFeeRange:w,priceImpactPct:oe,swaps:u.map(E=>E.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=s[0];let O=c.calculateInGivenOut(u,y);s.unshift(O)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=Z(I(e),u.decimalsOut).decimalPlaces(0,1):y=s[0].amountIn;let O=await this.poolService.getPoolFees(u.assetOut,c),{amountIn:B,calculatedIn:F,feePct:R,errors:T}=c.validateAndBuy(u,y,O),C=this.getPoolFeeRange(O),L=c.spotPriceInGivenOut(u),W=y.shiftedBy(-1*u.decimalsOut).multipliedBy(L),w;F.isZero()?w=-100:w=ze(W,F).toNumber(),s.unshift({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountOut:y,calculatedIn:F,amountIn:B,spotPrice:L,tradeFeePct:R,tradeFeeRange:C,priceImpactPct:w,errors:T,toHuman(){return{...a,amountOut:V(y,u.decimalsOut),calculatedIn:V(F,u.decimalsIn),amountIn:V(B,u.decimalsIn),spotPrice:V(L,u.decimalsIn),tradeFeePct:R,tradeFeeRange:C,priceImpactPct:w,errors:T}}})}return s}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,FarmClient,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
1
+ "use strict";var wt=Object.defineProperty;var ar=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var ur=Object.prototype.hasOwnProperty;var cr=(m,e)=>{for(var t in e)wt(m,t,{get:e[t],enumerable:!0})},mr=(m,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lr(e))!ur.call(m,s)&&s!==t&&wt(m,s,{get:()=>e[s],enumerable:!(r=ar(e,s))||r.enumerable});return m};var pr=m=>mr(wt({},"__esModule",{value:!0}),m);var Ar={};cr(Ar,{AssetClient:()=>Le,AssetNotFound:()=>_t,BASILISK_PARACHAIN_ID:()=>br,BalanceClient:()=>Me,BigNumber:()=>q,CachingPoolService:()=>bt,DECIMAL_PLACES:()=>zt,DENOMINATOR:()=>st,FarmClient:()=>it,HYDRADX_OMNIPOOL_ADDRESS:()=>$e,HYDRADX_PARACHAIN_ID:()=>Pr,HYDRADX_SS58_PREFIX:()=>ke,INFINITY:()=>dr,LbpMath:()=>pe,LbpPool:()=>Ie,ONE:()=>ae,OmniMath:()=>X,OmniPool:()=>Ae,PoolConfigNotFound:()=>Tt,PoolError:()=>Re,PoolFactory:()=>Ue,PoolNotFound:()=>je,PoolService:()=>Ce,PoolType:()=>ie,ProviderConfigNotFound:()=>kt,RUNTIME_DECIMALS:()=>Ee,RouteNotFound:()=>De,Router:()=>_e,SYSTEM_ASSET_DECIMALS:()=>fr,SYSTEM_ASSET_ID:()=>Oe,StableMath:()=>re,StableSwap:()=>Ne,StorageConfigNotFound:()=>Rt,SubscriptionNotSupported:()=>Et,TRADEABLE_DEFAULT:()=>rt,TradeRouter:()=>Ke,TradeType:()=>It,XykMath:()=>Se,XykPool:()=>Fe,ZERO:()=>_,bnum:()=>I,buildRoute:()=>ct,calculateBuyFee:()=>qt,calculateDiffToAvg:()=>Ir,calculateDiffToRef:()=>ze,calculateSellFee:()=>Gt,findNestedKey:()=>At,findNestedObj:()=>yr,scale:()=>Z});module.exports=pr(Ar);var Ve=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var gr=5,Ye=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new Ve,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>gr)return s;let u=c[c.length-1];(r===null||u[0]===r)&&s.push(c),e.get(u[0])?.forEach(O=>{if(this.isNotVisited(O,c)){let B=[...c];B.push(O),i.enqueue(B)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,a]of t){let c=parseInt(i),u=parseInt(a);r.get(c)?.push([u,s])}return r}};function xt(m){let e={};for(let t of m){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let a=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(a)}}}return e}var We=class{getProposals(e,t,r){let s=xt(r),i=Object.keys(s),a=i.map(O=>s[O]).flat(),c=new Ye,u=c.buildAndPopulateGraph(i,a),y=c.findPaths(u,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let a=r[i],c=r[i+1];if(c==null)break;s.push(this.toEdge(a,c))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var hr=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ot=Math.ceil,ce=Math.floor,se="[BigNumber Error] ",Ht=se+"Number primitive has more than 15 significant digits: ",he=1e14,F=14,Bt=9007199254740991,vt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Be=1e7,J=1e9;function Ut(m){var e,t,r,s=w.prototype={constructor:w,toString:null,valueOf:null},i=new w(1),a=20,c=4,u=-7,y=21,O=-1e7,B=1e7,N=!1,R=1,T=0,C={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},L="0123456789abcdefghijklmnopqrstuvwxyz",W=!0;function w(n,o){var l,P,g,d,S,p,h,b,f=this;if(!(f instanceof w))return new w(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<O?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!hr.test(b=String(n)))return r(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(H(o,2,L.length,"Base"),o==10&&W)return f=new w(n),E(f,a+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return r(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,w.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Ht+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=L.slice(0,o),d=S=0,h=b.length;S<h;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return r(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&w.DEBUG&&h>15&&(n>Bt||n!==ce(n)))throw Error(Ht+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<O)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%F,d<0&&(S+=F),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=F;S<h;)f.c.push(+b.slice(S,S+=F));S=F-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}w.clone=Ut,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],H(l,0,J,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],H(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(H(l[0],-J,0,o),H(l[1],0,J,o),u=l[0],y=l[1]):(H(l,-J,J,o),u=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)H(l[0],-J,-1,o),H(l[1],1,J,o),O=l[0],B=l[1];else if(H(l,-J,J,o),l)O=-(B=l<0?-l:l);else throw Error(se+o+" cannot be zero: "+l);if(n.hasOwnProperty(o="CRYPTO"))if(l=n[o],l===!!l)if(l)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))N=l;else throw N=!l,Error(se+"crypto unavailable");else N=l;else throw Error(se+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],H(l,0,9,o),R=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],H(l,0,J,o),T=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")C=l;else throw Error(se+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))W=l.slice(0,10)=="0123456789",L=l;else throw Error(se+o+" invalid: "+l)}else throw Error(se+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[u,y],RANGE:[O,B],CRYPTO:N,MODULO_MODE:R,POW_PRECISION:T,FORMAT:C,ALPHABET:L}},w.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!w.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-J&&g<=J&&g===ce(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%F,o<1&&(o+=F),String(P[0]).length==o){for(o=0;o<P.length;o++)if(l=P[o],l<0||l>=he||l!==ce(l))break e;if(l!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(se+"Invalid BigNumber: "+n)},w.maximum=w.max=function(){return oe(arguments,-1)},w.minimum=w.min=function(){return oe(arguments,1)},w.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ce(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,S,p,h=0,b=[],f=new w(i);if(l==null?l=a:H(l,0,J),S=Ot(l/F),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(se+"crypto unavailable");if(!N)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],l%=F,S&&l&&(p=vt[F-l],b[h]=ce(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=F);for(h=1,p=b[0];p>=10;p/=10,h++);h<F&&(d-=F-h)}return f.e=d,f.c=b,f}}(),w.sum=function(){for(var n=1,o=arguments,l=new w(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var S,p=[0],h,b=0,f=l.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(l.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(l,P,g,d,S){var p,h,b,f,x,v,A,M,U=l.indexOf("."),j=a,k=c;for(U>=0&&(f=T,T=0,l=l.replace(".",""),M=new w(P),v=M.pow(l.length-U),T=f,M.c=o(xe(ue(v.c),v.e,"0"),10,g,n),M.e=M.c.length),A=o(l,P,g,S?(p=L,n):(p=n,L)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(U<0?--b:(v.c=A,v.e=b,v.s=d,v=e(v,M,j,k,g),A=v.c,x=v.r,b=v.e),h=b+j+1,U=A[h],f=g/2,x=x||h<0||A[h+1]!=null,x=k<4?(U!=null||x)&&(k==0||k==(v.s<0?3:2)):U>f||U==f&&(k==4||x||k==6&&A[h-1]&1||k==(v.s<0?8:7)),h<1||!A[0])l=x?xe(p.charAt(1),-j,p.charAt(0)):p.charAt(0);else{if(A.length=h,x)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(U=0,l="";U<=f;l+=p.charAt(A[U++]));l=xe(l,b,p.charAt(0))}return l}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,x=P.length,v=g%Be,A=g/Be|0;for(P=P.slice();x--;)h=P[x]%Be,b=P[x]/Be|0,S=A*h+b*v,p=v*h+S%Be*Be+f,f=(p/d|0)+(S/Be|0)+A*b,P[x]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function l(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,x,v,A,M,U,j,k,G,ee,Qe,yt,St,fe,Xe,le=P.s==g.s?1:-1,te=P.c,z=g.c;if(!te||!te[0]||!z||!z[0])return new w(!P.s||!g.s||(te?z&&te[0]==z[0]:!z)?NaN:te&&te[0]==0||!z?le*0:le/0);for(U=new w(le),j=U.c=[],b=P.e-g.e,le=d+b+1,p||(p=he,b=me(P.e/F)-me(g.e/F),le=le/F|0),f=0;z[f]==(te[f]||0);f++);if(z[f]>(te[f]||0)&&b--,le<0)j.push(1),x=!0;else{for(yt=te.length,fe=z.length,f=0,le+=2,v=ce(p/(z[0]+1)),v>1&&(z=n(z,v,p),te=n(te,v,p),fe=z.length,yt=te.length),Qe=fe,k=te.slice(0,fe),G=k.length;G<fe;k[G++]=0);Xe=z.slice(),Xe=[0].concat(Xe),St=z[0],z[1]>=p/2&&St++;do{if(v=0,h=o(z,k,fe,G),h<0){if(ee=k[0],fe!=G&&(ee=ee*p+(k[1]||0)),v=ce(ee/St),v>1)for(v>=p&&(v=p-1),A=n(z,v,p),M=A.length,G=k.length;o(A,k,M,G)==1;)v--,l(A,fe<M?Xe:z,M,p),M=A.length,h=1;else v==0&&(h=v=1),A=z.slice(),M=A.length;if(M<G&&(A=[0].concat(A)),l(k,A,G,p),G=k.length,h==-1)for(;o(z,k,fe,G)<1;)v++,l(k,fe<G?Xe:z,G,p),G=k.length}else h===0&&(v++,k=[0]);j[f++]=v,k[0]?k[G++]=te[Qe]||0:(k=[te[Qe]],G=1)}while((Qe++<yt||k[0]!=null)&&le--);x=k[0]!=null,j[0]||j.splice(0,1)}if(p==he){for(f=1,le=j[0];le>=10;le/=10,f++);E(U,d+(U.e=f+b*F-1)+1,S,x)}else U.e=b,U.r=+x;return U}}();function Q(n,o,l,P){var g,d,S,p,h;if(l==null?l=c:H(l,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ue(n.c),h=P==1||P==2&&(S<=u||S>=y)?tt(h,S):xe(h,S,"0");else if(n=E(new w(n),o,l),d=n.e,h=ue(n.c),p=h.length,P==1||P==2&&(o<=d||d<=u)){for(;p<o;h+="0",p++);h=tt(h,d)}else if(o-=S,h=xe(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function oe(n,o){for(var l,P,g=1,d=new w(n[0]);g<n.length;g++)P=new w(n[g]),(!P.s||(l=Te(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function we(n,o,l){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(l=P+l*F-1)>B?n.c=n.e=null:l<O?n.c=[n.e=0]:(n.e=l,n.c=o),n}r=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,h){var b,f=p?S:S.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(x,v,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?v:x}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new w(f,b);if(w.DEBUG)throw Error(se+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function E(n,o,l,P){var g,d,S,p,h,b,f,x=n.c,v=vt;if(x){e:{for(g=1,p=x[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=F,S=o,h=x[b=0],f=ce(h/v[g-S-1]%10);else if(b=Ot((d+1)/F),b>=x.length)if(P){for(;x.length<=b;x.push(0));h=f=0,g=1,d%=F,S=d-F+1}else break e;else{for(h=p=x[b],g=1;p>=10;p/=10,g++);d%=F,S=d-F+g,f=S<0?0:ce(h/v[g-S-1]%10)}if(P=P||o<0||x[b+1]!=null||(S<0?h:h%v[g-S-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?S>0?h/v[g-S]:0:x[b-1])%10&1||l==(n.s<0?8:7)),o<1||!x[0])return x.length=0,P?(o-=n.e+1,x[0]=v[(F-o%F)%F],n.e=-o||0):x[0]=n.e=0,n;if(d==0?(x.length=b,p=1,b--):(x.length=b+1,p=v[F-d],x[b]=S>0?ce(h/v[g-S]%v[S])*p:0),P)for(;;)if(b==0){for(d=1,S=x[0];S>=10;S/=10,d++);for(S=x[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,x[0]==he&&(x[0]=1));break}else{if(x[b]+=p,x[b]!=he)break;x[b--]=0,p=1}for(d=x.length;x[--d]===0;x.pop());}n.e>B?n.c=n.e=null:n.e<O&&(n.c=[n.e=0])}return n}function Y(n){var o,l=n.e;return l===null?n.toString():(o=ue(n.c),o=l<=u||l>=y?tt(o,l):xe(o,l,"0"),n.s<0?"-"+o:o)}return s.absoluteValue=s.abs=function(){var n=new w(this);return n.s<0&&(n.s=1),n},s.comparedTo=function(n,o){return Te(this,new w(n,o))},s.decimalPlaces=s.dp=function(n,o){var l,P,g,d=this;if(n!=null)return H(n,0,J),o==null?o=c:H(o,0,8),E(new w(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-me(this.e/F))*F,g=l[g])for(;g%10==0;g/=10,P--);return P<0&&(P=0),P},s.dividedBy=s.div=function(n,o){return e(this,new w(n,o),a,c)},s.dividedToIntegerBy=s.idiv=function(n,o){return e(this,new w(n,o),0,1)},s.exponentiatedBy=s.pow=function(n,o){var l,P,g,d,S,p,h,b,f,x=this;if(n=new w(n),n.c&&!n.isInteger())throw Error(se+"Exponent not an integer: "+Y(n));if(o!=null&&(o=new w(o)),p=n.e>14,!x.c||!x.c[0]||x.c[0]==1&&!x.e&&x.c.length==1||!n.c||!n.c[0])return f=new w(Math.pow(+Y(x),p?n.s*(2-et(n)):+Y(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new w(NaN);P=!h&&x.isInteger()&&o.isInteger(),P&&(x=x.mod(o))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||p&&x.c[1]>=24e7:x.c[0]<8e13||p&&x.c[0]<=9999975e7)))return d=x.s<0&&et(n)?-0:0,x.e>-1&&(d=1/d),new w(h?1/d:d);T&&(d=Ot(T/F+2))}for(p?(l=new w(.5),h&&(n.s=1),b=et(n)):(g=Math.abs(+Y(n)),b=g%2),f=new w(i);;){if(b){if(f=f.times(x),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(g){if(g=ce(g/2),g===0)break;b=g%2}else if(n=n.times(l),E(n,n.e+1,1),n.e>14)b=et(n);else{if(g=+Y(n),g===0)break;b=g%2}x=x.times(x),d?x.c&&x.c.length>d&&(x.c.length=d):P&&(x=x.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?E(f,T,c,S):f)},s.integerValue=function(n){var o=new w(this);return n==null?n=c:H(n,0,8),E(o,o.e+1,n)},s.isEqualTo=s.eq=function(n,o){return Te(this,new w(n,o))===0},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(n,o){return Te(this,new w(n,o))>0},s.isGreaterThanOrEqualTo=s.gte=function(n,o){return(o=Te(this,new w(n,o)))===1||o===0},s.isInteger=function(){return!!this.c&&me(this.e/F)>this.c.length-2},s.isLessThan=s.lt=function(n,o){return Te(this,new w(n,o))<0},s.isLessThanOrEqualTo=s.lte=function(n,o){return(o=Te(this,new w(n,o)))===-1||o===0},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&this.c[0]==0},s.minus=function(n,o){var l,P,g,d,S=this,p=S.s;if(n=new w(n,o),o=n.s,!p||!o)return new w(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/F,b=n.e/F,f=S.c,x=n.c;if(!h||!b){if(!f||!x)return f?(n.s=-o,n):new w(x?S:NaN);if(!f[0]||!x[0])return x[0]?(n.s=-o,n):new w(f[0]?S:c==3?-0:0)}if(h=me(h),b=me(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=x),g.reverse(),o=p;o--;g.push(0));g.reverse()}else for(P=(d=(p=f.length)<(o=x.length))?p:o,p=o=0;o<P;o++)if(f[o]!=x[o]){d=f[o]<x[o];break}if(d&&(g=f,f=x,x=g,n.s=-n.s),o=(P=x.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=he-1;P>p;){if(f[--P]<x[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=he}f[P]-=x[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?we(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},s.modulo=s.mod=function(n,o){var l,P,g=this;return n=new w(n,o),!g.c||!n.s||n.c&&!n.c[0]?new w(NaN):!n.c||g.c&&!g.c[0]?new w(g):(R==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,R),n=g.minus(l.times(n)),!n.c[0]&&R==1&&(n.s=g.s),n)},s.multipliedBy=s.times=function(n,o){var l,P,g,d,S,p,h,b,f,x,v,A,M,U,j,k=this,G=k.c,ee=(n=new w(n,o)).c;if(!G||!ee||!G[0]||!ee[0])return!k.s||!n.s||G&&!G[0]&&!ee||ee&&!ee[0]&&!G?n.c=n.e=n.s=null:(n.s*=k.s,!G||!ee?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=me(k.e/F)+me(n.e/F),n.s*=k.s,h=G.length,x=ee.length,h<x&&(M=G,G=ee,ee=M,g=h,h=x,x=g),g=h+x,M=[];g--;M.push(0));for(U=he,j=Be,g=x;--g>=0;){for(l=0,v=ee[g]%j,A=ee[g]/j|0,S=h,d=g+S;d>g;)b=G[--S]%j,f=G[S]/j|0,p=A*b+f*v,b=v*b+p%j*j+M[d]+l,l=(b/U|0)+(p/j|0)+A*f,M[d--]=b%U;M[d]=l}return l?++P:M.splice(0,1),we(n,M,P)},s.negated=function(){var n=new w(this);return n.s=-n.s||null,n},s.plus=function(n,o){var l,P=this,g=P.s;if(n=new w(n,o),o=n.s,!g||!o)return new w(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/F,S=n.e/F,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new w(g/0);if(!p[0]||!h[0])return h[0]?n:new w(p[0]?P:g*0)}if(d=me(d),S=me(S),p=p.slice(),g=d-S){for(g>0?(S=d,l=h):(g=-g,l=p),l.reverse();g--;l.push(0));l.reverse()}for(g=p.length,o=h.length,g-o<0&&(l=h,h=p,p=l,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/he|0,p[o]=he===p[o]?0:p[o]%he;return g&&(p=[g].concat(p),++S),we(n,p,S)},s.precision=s.sd=function(n,o){var l,P,g,d=this;if(n!=null&&n!==!!n)return H(n,1,J),o==null?o=c:H(o,0,8),E(new w(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*F+1,g=l[g]){for(;g%10==0;g/=10,P--);for(g=l[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},s.shiftedBy=function(n){return H(n,-Bt,Bt),this.times("1e"+n)},s.squareRoot=s.sqrt=function(){var n,o,l,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new w("0.5");if(p!==1||!S||!S[0])return new w(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+Y(d)),p==0||p==1/0?(o=ue(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=me((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new w(o)):l=new w(p+""),l.c[0]){for(h=l.e,p=h+b,p<3&&(p=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ue(g.c).slice(0,p)===(o=ue(l.c)).slice(0,p))if(l.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(E(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(E(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return E(l,l.e+a+1,c,n)},s.toExponential=function(n,o){return n!=null&&(H(n,0,J),n++),Q(this,n,o,1)},s.toFixed=function(n,o){return n!=null&&(H(n,0,J),n=n+this.e+1),Q(this,n,o)},s.toFormat=function(n,o,l){var P,g=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=C;else if(typeof l!="object")throw Error(se+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],x=S[1],v=g.s<0,A=v?f.slice(1):f,M=A.length;if(h&&(d=p,p=h,h=d,M-=d),p>0&&M>0){for(d=M%p||p,f=A.substr(0,d);d<M;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=x?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?x.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):x):f}return(l.prefix||"")+P+(l.suffix||"")},s.toFraction=function(n){var o,l,P,g,d,S,p,h,b,f,x,v,A=this,M=A.c;if(n!=null&&(p=new w(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(se+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+Y(p));if(!M)return new w(A);for(o=new w(i),b=l=new w(i),P=h=new w(i),v=ue(M),d=o.e=v.length-A.e-1,o.c[0]=vt[(S=d%F)<0?F+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new w(v),h.c[0]=0;f=e(p,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,x=e(b,P,d,c).minus(A).abs().comparedTo(e(h,l,d,c).minus(A).abs())<1?[b,P]:[h,l],B=S,x},s.toNumber=function(){return+Y(this)},s.toPrecision=function(n,o){return n!=null&&H(n,1,J),Q(this,n,o,2)},s.toString=function(n){var o,l=this,P=l.s,g=l.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=u||g>=y?tt(ue(l.c),g):xe(ue(l.c),g,"0"):n===10&&W?(l=E(new w(l),a+g+1,c),o=xe(ue(l.c),l.e,"0")):(H(n,2,L.length,"Base"),o=t(xe(ue(l.c),g,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},s.valueOf=s.toJSON=function(){return Y(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,m!=null&&w.set(m),w}function me(m){var e=m|0;return m>0||m===e?e:e-1}function ue(m){for(var e,t,r=1,s=m.length,i=m[0]+"";r<s;){for(e=m[r++]+"",t=F-e.length;t--;e="0"+e);i+=e}for(s=i.length;i.charCodeAt(--s)===48;);return i.slice(0,s+1||1)}function Te(m,e){var t,r,s=m.c,i=e.c,a=m.s,c=e.s,u=m.e,y=e.e;if(!a||!c)return null;if(t=s&&!s[0],r=i&&!i[0],t||r)return t?r?0:-c:a;if(a!=c)return a;if(t=a<0,r=u==y,!s||!i)return r?0:!s^t?1:-1;if(!r)return u>y^t?1:-1;for(c=(u=s.length)<(y=i.length)?u:y,a=0;a<c;a++)if(s[a]!=i[a])return s[a]>i[a]^t?1:-1;return u==y?0:u>y^t?1:-1}function H(m,e,t,r){if(m<e||m>t||m!==ce(m))throw Error(se+(r||"Argument")+(typeof m=="number"?m<e||m>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(m))}function et(m){var e=m.c.length-1;return me(m.e/F)==e&&m.c[e]%2!=0}function tt(m,e){return(m.length>1?m.charAt(0)+"."+m.slice(1):m)+(e<0?"e":"e+")+e}function xe(m,e,t){var r,s;if(e<0){for(s=t+".";++e;s+=t);m=s+m}else if(r=m.length,++e>r){for(s=t,e-=r;--e;s+=t);m+=s}else e<r&&(m=m.slice(0,e)+"."+m.slice(e));return m}var q=Ut();var zt=12;q.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:zt});var _=I(0),ae=I(1),dr=I("Infinity");function Z(m,e){let t=new q(e.toString()),r=new q(10).pow(t);return m.times(r)}function I(m){return new q(m.toString())}var ie=(s=>(s.XYK="Xyk",s.LBP="Lbp",s.Stable="Stableswap",s.Omni="Omnipool",s))(ie||{}),Re=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(Re||{}),It=(t=>(t.Buy="Buy",t.Sell="Sell",t))(It||{});var Pe=require("@galacticcouncil/math-lbp"),pe=class{static getSpotPrice(e,t,r,s,i){return(0,Pe.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,Pe.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,Pe.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,Pe.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,Pe.calculate_pool_trade_fee)(e,t,r)}};var Xt=require("@polkadot/util-crypto"),Yt=require("@polkadot/util"),Ee=18,rt=15,Oe="0",fr=12,Pr=2034,ke=63,br=2090,st=1e3,$e=(0,Xt.encodeAddress)((0,Yt.stringToU8a)("modlomnipool".padEnd(32,"\0")),ke);function At(m,e){let t;return JSON.stringify(m,(r,s)=>(s&&s[e]&&(t=s),s)),t}function yr(m,e,t){let r;return JSON.stringify(m,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Qr=require("@polkadot/types/lookup");var Vr=require("@polkadot/api-base/types/consts");var es=require("@polkadot/api-base/types/errors");var ts=require("@polkadot/api-base/types/events");var rs=require("@polkadot/api-base/types/storage");var ss=require("@polkadot/api-base/types/submittable");var is=require("@polkadot/rpc-core/types/jsonrpc");var ns=require("@polkadot/api-base/types/calls");var gs=require("@polkadot/types/types/registry");var Ps=require("@polkadot/types/lookup");var bs=require("@polkadot/api-base/types/consts");var ys=require("@polkadot/api-base/types/errors");var Ss=require("@polkadot/api-base/types/events");var ws=require("@polkadot/api-base/types/storage");var xs=require("@polkadot/api-base/types/submittable");var Os=require("@polkadot/rpc-core/types/jsonrpc");var Bs=require("@polkadot/api-base/types/calls");var Rs=require("@polkadot/types/types/registry");var ve=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Le=class extends ve{SUPPORTED_TYPES=["StableSwap","Bond","Token","External"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==Oe){let B=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:B.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:u}=t,{symbol:y,decimals:O}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:y,decimals:O,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:this.parseLocation("parachain",s),existentialDeposit:u.toString()}}getBond(e,t,r,s){let[i,a]=s,{assetType:c,isSufficient:u,existentialDeposit:y}=t,{symbol:O,decimals:B}=this.getToken(i.toString(),t,r),N=a.toNumber(),R=new Intl.DateTimeFormat("en-GB"),T=[O,"Bond",R.format(N)].join(" ");return{id:e,name:T,symbol:O+"b",decimals:B,icon:O,type:c.toString(),isSufficient:u.toHuman(),existentialDeposit:y.toString(),underlyingAssetId:i.toString(),maturity:N}}getShares(e,t,r,s){let{assets:i}=s,{name:a,symbol:c,assetType:u,isSufficient:y,existentialDeposit:O}=t,N=i.map(C=>C.toString()).map(C=>{let{symbol:L}=this.getToken(C,t,r);return[C,L]}),R=Object.fromEntries(N),T=Object.values(R);return{id:e,name:T.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:T.join("/"),type:u.toString(),isSufficient:y.toHuman(),existentialDeposit:O.toString(),meta:R}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),a=r?.find(c=>c.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:a}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e){let[t,r,s,i,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),c=this.getSupportedAssets(t),u=this.normalizeMetadata(c,a);return c.map(([{args:[y]},O])=>{let B=O.unwrap(),N=r.get(y.toString()),{assetType:R}=B;switch(R.toString()){case"Bond":let T=i.get(y.toString());return this.getBond(y.toString(),B,u,T);case"StableSwap":let C=s.get(y.toString());return this.getShares(y.toString(),B,u,C);case"External":return this.getExternal(y.toString(),B,e,N);default:return this.getToken(y.toString(),B,u,N)}}).filter(y=>this.isValidAsset(y))}isValidAsset(e){return!!e.symbol&&!!e.decimals}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let r=At(t.toJSON(),e);return r&&r[e]}else return}};var Me=class extends ve{constructor(e){super(e)}async getBalance(e,t){return t===Oe?await this.getSystemBalance(e):await this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:i})}async subscribeBalance(e,t,r){let s=t.filter(i=>i!==Oe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach(({free:a,reserved:c,frozen:u},y)=>{let O=this.calculateFreeBalance({free:a,feeFrozen:c,frozen:u}),B=s[y][1];r(B,O)})})}async subscribeTokenBalance(e,t,r){let s=t.filter(i=>i!==Oe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach((a,c)=>{let u=this.calculateFreeBalance(a),y=s[c][1];r(y,u)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(Oe,this.calculateFreeBalance(r)))}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:i}=e,a=new q(t),c=new q(r||i),u=new q(s||0),y=c.gt(u)?c:u;return a.minus(y)}};var Nt=require("@polkadot/util-crypto"),Ft=require("@galacticcouncil/math-liquidity-mining");var it=class extends ve{constructor(e){super(e)}secondsInYear=new q(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(u)).unwrap(),O=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(u)).unwrap(),O=(await this.api.query.xykWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new q(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),c=a.price.n.toString(),u=a.price.d.toString(),y;return Number(t)<Number(r)?y=(0,Ft.fixed_from_rational)(c,u):y=(0,Ft.fixed_from_rational)(u,c),y}getGlobalRewardPerPeriod(e,t,r,s){let a=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return a.gte(r)?r:a}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,Nt.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,Nt.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:c,globalFarm:u,priceAdjustment:y})=>{let O=new q(u.totalSharesZ.toString()),B=u.plannedYieldingPeriods.toString(),N=new q(u.yieldPerPeriod.toString()),R=new q(u.maxRewardPerPeriod.toString()),T=u.blocksPerPeriod.toString(),C=new q(c.multiplier.toString()).shiftedBy(-18),L=this.secondsInYear.div(new q(r).times(T)),W;if(O.isZero())W=N.times(C).times(L);else{let we=this.getGlobalRewardPerPeriod(O,N,R,y);W=this.getPoolYieldPerPeriod(we,C,O,y).times(L)}let w=new q(u.pendingRewards.toString()).plus(u.accumulatedPaidRewards.toString()),Q=R.times(B);return w.div(Q).gte(.99)?_:W.times(100)}).reduce((c,u)=>c.plus(u),_).toString():void 0}};var be=class extends Me{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async r=>{let s=[await this.subscribePoolChange(r),await this.subscribeTokensPoolBalance(r),await this.subscribeSystemPoolBalance(r)];if(this.hasShareAsset(r)){let i=await this.subscribeSharePoolBalance(r);s.push(i)}return this.subscribeLog(r),s});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,r)=>t.id!==r))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance($e,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(r,s){let i=e.tokens.findIndex(a=>a.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=s.toString())}}};var nt=class extends be{MAX_FINAL_WEIGHT=Z(I(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,a])=>this.isActivePool(a.unwrap(),r)).map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=await this.getPoolDelta(u,c,r.toString());return this.poolsData.set(i.toString(),c),{address:u,type:"Lbp",fee:c.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let a=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(c=>c.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,r){let{start:s,end:i,assets:a,initialWeight:c,finalWeight:u,repayTarget:y,feeCollector:O}=t,B=pe.calculateLinearWeights(s.toString(),i.toString(),c.toString(),u.toString(),r),[N,R]=a,T=N.toString(),C=I(B),L=R.toString(),W=this.MAX_FINAL_WEIGHT.minus(I(C)),[w,Q,oe]=await Promise.all([this.isRepayFeeApplied(T,y.toString(),O.toString()),this.getBalance(e,T),this.getBalance(e,L)]);return{repayFeeApply:w,tokens:[{id:T,weight:C,balance:Q.toString()},{id:L,weight:W,balance:oe.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=I(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var Wt=require("@polkadot/util-crypto"),$t=require("@polkadot/util");function V(m,e){return m.shiftedBy(-1*e).toString()}function ge(m){return m[0]/m[1]*100}function ne(m){return m[0]/m[1]}function de(m){return[m/st,st]}var ot=class extends be{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=r.map(async([{args:[u]},y])=>{let{hubReserve:O,shares:B,tradable:N}=y.unwrap(),R=await this.getBalance(t,u.toString());return{id:u.toString(),hubReserves:I(O.toString()),shares:I(B.toString()),tradeable:N.bits.toNumber(),balance:R.toString()}}),c=await Promise.all(a);return c.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:c,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=await this.api.query.dynamicFees.assetFee(e),s=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=s.minFee.toNumber()+i.minFee.toNumber(),c=s.maxFee.toNumber()+i.maxFee.toNumber();if(r.isSome){let{assetFee:u,protocolFee:y}=r.unwrap();return{assetFee:de(u.toNumber()),protocolFee:de(y.toNumber()),min:de(a),max:de(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:de(a),max:de(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,i)=>{let a=e.tokens[i];if(s.isNone)return a;let c=s.unwrap();return this.updateTokenState(a,c)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i}=t;return{...e,hubReserves:I(r.toString()),shares:I(s.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return de(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return de(t)}getPoolId(){return(0,Wt.encodeAddress)((0,$t.stringToU8a)("modlomnipool".padEnd(32,"\0")),ke)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var at=class extends be{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[a,c]=s.unwrap(),[u,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:u.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var ut=require("@polkadot/util-crypto");var K=require("@galacticcouncil/math-stableswap"),re=class{static getPoolAddress(e){return(0,K.pool_account_name)(e)}static calculateAmplification(e,t,r,s,i){return(0,K.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,a){return(0,K.calculate_in_given_out)(e,t,r,s,i,a)}static calculateAddOneAsset(e,t,r,s,i,a){return(0,K.calculate_add_one_asset)(e,t,r,s,i,a)}static calculateSharesForAmount(e,t,r,s,i,a){return(0,K.calculate_shares_for_amount)(e,t,r,s,i,a)}static calculateOutGivenIn(e,t,r,s,i,a){return(0,K.calculate_out_given_in)(e,t,r,s,i,a)}static calculateLiquidityOutOneAsset(e,t,r,s,i,a){return(0,K.calculate_liquidity_out_one_asset)(e,t,r,s,i,a)}static calculateShares(e,t,r,s,i){return(0,K.calculate_shares)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,K.calculate_pool_trade_fee)(e,t,r)}};var lt=class extends be{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=this.getPoolAddress(u),[O,B]=await Promise.all([this.getPoolDelta(u,c,r.toString()),this.getPoolTokens(y,u,c)]);return this.stablePools.set(y,c),{address:y,id:u,type:"Stableswap",fee:de(c.fee.toNumber()),tokens:B,...O,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toNumber(),s=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,s,r.toString());Object.assign(e,i)})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:a,finalBlock:c}=t,u=re.calculateAmplification(s.toString(),i.toString(),a.toString(),c.toString(),r),y=await this.api.query.tokens.totalIssuance(e);return{amplification:u,totalIssuance:y.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async u=>{let[y,O]=await Promise.all([this.api.query.stableswap.assetTradability(t,u.toString()),this.getBalance(e,u.toString())]);return{id:u.toString(),tradeable:y.bits.toNumber(),balance:O.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:u}=c.unwrap(),y=await this.getBalance($e,t);a.push({id:t,tradeable:u.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),r=re.getPoolAddress(t);return(0,ut.encodeAddress)((0,ut.blake2AsHex)(r),ke)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function ct(m){return m.map(({assetIn:e,assetOut:t,pool:r,poolId:s})=>r==="Stableswap"?{pool:{Stableswap:s},assetIn:e,assetOut:t}:{pool:r,assetIn:e,assetOut:t})}var je=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Tt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},De=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},_t=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Rt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},kt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Ce=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new Le(this.api),this.xykClient=new at(this.api),this.omniClient=new ot(this.api),this.lbpClient=new nt(this.api),this.stableClient=new lt(this.api)}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||this.syncRegistry(),e.length==0){let a=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(c=>c.isSupported()).map(c=>c.getPools()))).flat();return this.withMetadata(a)}let t=[];e.forEach(i=>{switch(i){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break;case"Stableswap":t.push(this.stableClient.getPools());break}});let s=(await Promise.all(t)).flat();return this.withMetadata(s)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(r=>[r.id,r]));return e.filter(r=>r.type==="Xyk"?r.tokens.every(s=>t.get(s.id)):!0).map(r=>{let s=r.tokens.map(i=>{let a=t.get(i.id);return{...i,...a}});return{...r,tokens:s}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new je(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,r,s,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,r.toFixed(),s.toFixed()):a=this.api.tx.router.buy(e,t,r.toFixed(),s.toFixed(),ct(i));let c=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,r,s,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,r.toFixed(),s.toFixed()):a=this.api.tx.router.sell(e,t,r.toFixed(),s.toFixed(),ct(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var Je=(m,e)=>m===e?0:m==null?e==null?0:-1:e==null?m==null?0:1:typeof m.compare=="function"?m.compare(e):typeof e.compare=="function"?-e.compare(m):m<e?-1:m>e?1:0;var mt=(m,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(m(t)+e(t))}};var Sr=mt(()=>"illegal argument(s)"),jt=m=>{throw new Sr(m)};var wr=mt(()=>"index out of bounds"),Lt=m=>{throw new wr(m)},pt=(m,e,t)=>(m<e||m>=t)&&Lt(m);var Jt=23283064365386963e-26,gt=class{float(e=1){return this.int()*Jt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Jt-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var Mt=Math.random,Dt=class extends gt{int(){return Mt()*4294967296>>>0}float(e=1){return Mt()*e}norm(e=1){return(Mt()-.5)*2*e}},Zt=new Dt;var Kt=m=>m!=null&&typeof m!="function"&&m.length!==void 0;var Qt=Object.getPrototypeOf({}),ht="function",Vt="string",Ge=(m,e)=>{let t;if(m===e)return!0;if(m!=null){if(typeof m.equiv===ht)return m.equiv(e)}else return m==e;if(e!=null){if(typeof e.equiv===ht)return e.equiv(m)}else return m==e;return typeof m===Vt||typeof e===Vt?!1:(t=Object.getPrototypeOf(m),(t==null||t===Qt)&&(t=Object.getPrototypeOf(e),t==null||t===Qt)?vr(m,e):typeof m!==ht&&m.length!==void 0&&typeof e!==ht&&e.length!==void 0?xr(m,e):m instanceof Set&&e instanceof Set?Or(m,e):m instanceof Map&&e instanceof Map?Br(m,e):m instanceof Date&&e instanceof Date?m.getTime()===e.getTime():m instanceof RegExp&&e instanceof RegExp?m.toString()===e.toString():m!==m&&e!==e)},xr=(m,e,t=Ge)=>{let r=m.length;if(r===e.length)for(;r-- >0&&t(m[r],e[r]););return r<0},Or=(m,e,t=Ge)=>m.size===e.size&&t([...m.keys()].sort(),[...e.keys()].sort()),Br=(m,e,t=Ge)=>m.size===e.size&&t([...m].sort(),[...e].sort()),vr=(m,e,t=Ge)=>{if(Object.keys(m).length!==Object.keys(e).length)return!1;for(let r in m)if(!e.hasOwnProperty(r)||!t(m[r],e[r]))return!1;return!0};var er=(m,e)=>m!=null&&typeof m[e]=="function";var tr=m=>er(m,"xform")?m.xform():m;var dt=Symbol(),Ct=()=>{};var rr=m=>m!=null&&typeof m[Symbol.iterator]=="function";var ft=class{value;constructor(e){this.value=e}deref(){return this.value}};var Pt=m=>m instanceof ft;var sr=m=>m instanceof ft?m.deref():m;function*ir(m,e){let t=tr(m)([Ct,Ct,(r,s)=>s])[2];for(let r of e){let s=t(dt,r);if(Pt(s)){s=sr(s.deref()),s!==dt&&(yield s);return}s!==dt&&(yield s)}}var nr=(m,e)=>[m[0],m[1],e];function Ze(m,e){return rr(e)?ir(Ze(m),e):t=>{let r=t[2];return nr(t,(s,i)=>r(s,m(i)))}}var qe=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return or("next",this._head)}reverseIterator(){return or("prev",this.tail)}clear(){this.release()}compare(e,t=Je){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,a=0;for(;r-- >0&&a===0;)a=t(s.value,i.value),s=s.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof qe||Kt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!Ge(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||Je;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!Pt(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&Lt(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*or(m,e){for(;e;)yield e.value,e=e[m]}var ye=class extends qe{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new ye(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new ye}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(pt(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(pt(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new ye,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=a=>({first(){return a.value},next(){return a!==s&&a.next?i(a.next):void 0}});return r?i(r):void 0}shuffle(e,t=Zt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&jt("invalid indices: ${from} / ${to}");let i=new ye,a=this.nthCell(r);for(;a&&++r<=s;)i.push(a.value),a=a.next;return i}sort(e=Je){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,a=0;for(let u=0;u<t&&(a++,i=i.next,!!i);u++);let c=t;for(;a>0||c>0&&i;){let u;a===0?(u=i,i=i.next,c--):!i||c===0||e(r.value,i.value)<=0?(u=r,r=r.next,a--):(u=i,i=i.next,c--),this._tail?this._tail.next=u:this._head=u,u.prev=this._tail,this._tail=u}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),pt(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new ye;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let a of r)this.insertBefore(s,a);else for(let a of r)this.push(a);return i}};var He=class{map;items;opts;_size;constructor(e,t){let r=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=r.map(),this.items=new ye,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ze(e=>[e.k,e],this.items)}keys(){return Ze(e=>e.k,this.items)}values(){return Ze(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new He(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e);return this._size+=Math.max(0,r-(s?s.value.s:0)),this.ensureSize()&&this.doSetEntry(s,e,t,r),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let r=this.map.get(e);return r?Promise.resolve(this.resetEntry(r)):t().then(s=>this.set(e,s))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,r=this.opts.maxlen;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e&&e(s.k,s.v),this._size-=s.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,r,s){e?(e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var bt=class extends Ce{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new He(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let r=[t.address,e].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let i=await super.getPoolFees(e,t);return this.feeCache.set(r,i),i}}async destroy(){console.log(`Destroying pool cache!
2
+ Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Ie=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Ie(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,i,a,c){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=c}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let c=this.calculateTradeFee(t,r),u=ge(this.repayFeeApply?r.repayFee:r.exchangeFee),y=t.plus(c),O=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return O.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:O,calculatedIn:O,amountOut:t,feePct:u,errors:i}}else{let c=this.calculateInGivenOut(e,t),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let c=this.calculateOutGivenIn(e,t),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),u=this.calculateTradeFee(c,r),y=ge(this.repayFeeApply?r.repayFee:r.exchangeFee),O=c.minus(u),B=e.balanceOut.div(this.maxOutRatio);return O.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:O,feePct:y,errors:i}}}calculateInGivenOut(e,t){let r=pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?_:s}calculateOutGivenIn(e,t){let r=pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?_:s}spotPriceInGivenOut(e){let t=pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),Z(ae,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),Z(ae,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let r=pe.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(r)}};var D=require("@galacticcouncil/math-omnipool");var X=class{static calculateSpotPrice(e,t,r,s){return(0,D.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,D.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,a,c,u,y){return(0,D.calculate_in_given_out)(e,t,r,s,i,a,c,u,y)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,D.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,a,c,u,y){return(0,D.calculate_out_given_in)(e,t,r,s,i,a,c,u,y)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,D.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,D.calculate_pool_trade_fee)(e,t,r)}static calculateShares(e,t,r,s){return(0,D.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,a,c,u){return(0,D.calculate_liquidity_out)(e,t,r,s,i,a,c,u)}static calculateLiquidityLRNAOut(e,t,r,s,i,a,c,u){return(0,D.calculate_liquidity_lrna_out)(e,t,r,s,i,a,c,u)}static calculateCapDifference(e,t,r,s){let i=q(t),a=q(e),c=q(s),y=q(r).shiftedBy(-18);if(i.div(c).lt(y)){let B=y.times(c).minus(i).times(a),N=i.times(q(1).minus(y));return B.div(N).toFixed(0)}else return"0"}static verifyAssetCap(e,t,r,s){return(0,D.verify_asset_cap)(e,t,r,s)}static calculateLimitHubIn(e,t,r,s){return(0,D.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,D.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,D.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,D.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,D.is_remove_liquidity_allowed)(e)}};var Ae=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new Ae(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,i,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,tradeableIn:s.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),c=s===_?_:a.div(s).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),O=X.isBuyAllowed(e.tradeableOut);(!y||!O)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&u.push("MaxOutRatioExceeded");let N=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(N)&&u.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:c.toNumber(),errors:u}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),c=s.minus(i).div(s).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),O=X.isBuyAllowed(e.tradeableOut);(!y||!O)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&u.push("MaxInRatioExceeded");let N=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(N)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:c.toNumber(),errors:u}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=X.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ne(r.assetFee).toString():_.toString(),r?ne(r.protocolFee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateLrnaInGivenOut(e,t,r){let s=X.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ne(r.assetFee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=X.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ne(r.assetFee).toString():_.toString(),r?ne(r.protocolFee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateOutGivenLrnaIn(e,t,r){let s=X.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ne(r.assetFee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=X.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=X.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=X.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=X.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsIn)).decimalPlaces(0,1)}};var Ne=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Ne(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,r,s,i,a,c,u,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.amplification=a,this.id=c,this.fee=u,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?rt:s.tradeable,tradeableOut:this.id===t?rt:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=ge(r.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),a=ge(r.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,r){let s=re.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateAddOneAsset(e,t,r){let s=re.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateSharesForAmount(e,t,r){let s=re.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=Z(ae,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,r){let s=re.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateWithdrawOneAsset(e,t,r){let s=re.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateShares(e,t,r){let s=re.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?ne(r.fee).toString():_.toString()),i=I(s);return i.isNegative()?_:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=Z(ae,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let r=re.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(r)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};var $=require("@galacticcouncil/math-xyk"),Se=class{static getSpotPrice(e,t,r){return(0,$.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,$.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,$.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,$.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,$.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,$.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,$.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,$.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,$.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,$.calculate_liquidity_out_asset_b)(e,t,r,s)}};var Fe=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Fe(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),a=ge(r.exchangeFee),c=s.plus(i),u=[];t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&u.push("MaxOutRatioExceeded");let O=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(O)&&u.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:s,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),a=ge(r.exchangeFee),c=s.minus(i),u=[];t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&u.push("MaxInRatioExceeded");let O=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(O)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:c,feePct:a,errors:u}}calculateInGivenOut(e,t){let r=Se.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?_:s}calculateOutGivenIn(e,t){let r=Se.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?_:s}spotPriceInGivenOut(e){let t=Se.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=Z(ae,18-e.decimalsOut);return I(t).div(r)}spotPriceOutGivenIn(e){let t=Se.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=Z(ae,18-e.decimalsIn);return I(t).div(r)}calculateTradeFee(e,t){let r=Se.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(r)}};var Ue=class{static get(e){switch(e.type){case"Xyk":return Fe.fromPool(e);case"Omnipool":return Ae.fromPool(e);case"Lbp":return Ie.fromPool(e);case"Stableswap":return Ne.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var _e=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new We,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),a=this.getPaths(e,null,s,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(a)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,origin:s.origin,meta:s.meta}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(c=>this.validPath(c,r)).map(c=>this.toHops(c,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(r);return{assets:s,poolsMap:i}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,Ue.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,i])=>{let a=t.get(r);return{poolAddress:r,poolId:a?.id,pool:a?.type,assetIn:s,assetOut:i}})}toAssets(e,t){return e.map(r=>t.get(r))}};function Ir(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ze(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Gt(m,e){return ae.minus(e.div(m)).multipliedBy(100).decimalPlaces(2)}function qt(m,e){return e.div(m).minus(ae).multipliedBy(100).decimalPlaces(2)}var Ke=class extends _e{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,a=s[s.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[r,s]}}getPoolFeeRange(e){let t=e.min?ge(e.min):void 0,r=e.max?ge(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new De(e,t);let u;if(s)u=await this.toSellSwaps(r,s,a);else{let E=c.map(async n=>await this.toSellSwaps(r,n,a)),Y=await Promise.all(E);u=this.findBestSellRoute(Y)}let y=u[0],O=u[u.length-1],B=this.isDirectTrade(u),N=u.map(E=>E.spotPrice.shiftedBy(-1*E.assetOutDecimals)).reduce((E,Y)=>E.multipliedBy(Y)),R=Z(N,O.assetOutDecimals),T=B?O.calculatedOut:this.calculateDelta0Y(y.amountIn,u,a),C=O.amountOut,L=B?O.tradeFeePct:Gt(T,C).toNumber(),W=T.minus(C),w=this.getRouteFeeRange(u),Q=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(R),oe=ze(T,Q),we=E=>this.poolService.buildSellTx(e,t,y.amountIn,E,u.map(Y=>Y));return{type:"Sell",amountIn:y.amountIn,amountOut:O.amountOut,spotPrice:R,tradeFee:W,tradeFeePct:L,tradeFeeRange:w,priceImpactPct:oe.toNumber(),swaps:u,toTx:we,toHuman(){return{type:"Sell",amountIn:V(y.amountIn,y.assetInDecimals),amountOut:V(O.amountOut,O.assetOutDecimals),spotPrice:V(R,O.assetOutDecimals),tradeFee:V(W,O.assetOutDecimals),tradeFeePct:L,tradeFeeRange:w,priceImpactPct:oe.toNumber(),swaps:u.map(E=>E.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=s[i-1]:y=e;let O=c.calculateOutGivenIn(u,y);s.push(O)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=s[i-1].amountOut:y=Z(I(e),u.decimalsIn).decimalPlaces(0,1);let O=await this.poolService.getPoolFees(u.assetOut,c),{amountOut:B,calculatedOut:N,feePct:R,errors:T}=c.validateAndSell(u,y,O),C=this.getPoolFeeRange(O),L=c.spotPriceOutGivenIn(u),W=y.shiftedBy(-1*u.decimalsIn).multipliedBy(L),w=ze(N,W);s.push({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountIn:y,calculatedOut:N,amountOut:B,spotPrice:L,tradeFeePct:R,tradeFeeRange:C,priceImpactPct:w.toNumber(),errors:T,toHuman(){return{...a,amountIn:V(y,u.decimalsIn),calculatedOut:V(N,u.decimalsOut),amountOut:V(B,u.decimalsOut),spotPrice:V(L,u.decimalsOut),tradeFeePct:R,tradeFeeRange:C,priceImpactPct:w.toNumber(),errors:T}}})}return s}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r),i=super.getPaths(e,t,s,r);if(i.length===0)return Promise.resolve(void 0);let a=r.map(w=>w.tokens.find(Q=>Q.id===e)).filter(w=>!!w).sort((w,Q)=>Number(Q.balance)-Number(w.balance)),{balance:c,decimals:u}=a[0],O=I(c).shiftedBy(-1*u).div(100).multipliedBy(.1),B=i.map(async w=>await this.toSellSwaps(O,w,s)),N=await Promise.all(B),R=this.findBestSellRoute(N),T=await this.toSellSwaps("1",R,s),C=T.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,Q)=>w.multipliedBy(Q)),L=T[T.length-1].assetOutDecimals;return{amount:Z(C,L),decimals:L}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,a=s[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new De(e,t);let u;if(s)u=await this.toBuySwaps(r,s,a);else{let E=c.map(async n=>await this.toBuySwaps(r,n,a)),Y=await Promise.all(E);u=this.findBestBuyRoute(Y)}let y=u[u.length-1],O=u[0],B=this.isDirectTrade(u),N=u.map(E=>E.spotPrice.shiftedBy(-1*E.assetInDecimals)).reduce((E,Y)=>E.multipliedBy(Y)),R=Z(N,O.assetInDecimals),T=B?O.calculatedIn:this.calculateDelta0X(y.amountOut,u,a),C=O.amountIn,L=B?O.tradeFeePct:qt(T,C).toNumber(),W=C.minus(T),w=this.getRouteFeeRange(u),Q=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(R),oe;T.isZero()?oe=-100:oe=ze(Q,T).toNumber();let we=E=>this.poolService.buildBuyTx(e,t,y.amountOut,E,u.map(Y=>Y));return{type:"Buy",amountOut:y.amountOut,amountIn:O.amountIn,spotPrice:R,tradeFee:W,tradeFeePct:L,tradeFeeRange:w,priceImpactPct:oe,swaps:u,toTx:we,toHuman(){return{type:"Buy",amountOut:V(y.amountOut,y.assetOutDecimals),amountIn:V(O.amountIn,O.assetInDecimals),spotPrice:V(R,O.assetInDecimals),tradeFee:V(W,O.assetInDecimals),tradeFeePct:L,tradeFeeRange:w,priceImpactPct:oe,swaps:u.map(E=>E.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=s[0];let O=c.calculateInGivenOut(u,y);s.unshift(O)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=Z(I(e),u.decimalsOut).decimalPlaces(0,1):y=s[0].amountIn;let O=await this.poolService.getPoolFees(u.assetOut,c),{amountIn:B,calculatedIn:N,feePct:R,errors:T}=c.validateAndBuy(u,y,O),C=this.getPoolFeeRange(O),L=c.spotPriceInGivenOut(u),W=y.shiftedBy(-1*u.decimalsOut).multipliedBy(L),w;N.isZero()?w=-100:w=ze(W,N).toNumber(),s.unshift({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountOut:y,calculatedIn:N,amountIn:B,spotPrice:L,tradeFeePct:R,tradeFeeRange:C,priceImpactPct:w,errors:T,toHuman(){return{...a,amountOut:V(y,u.decimalsOut),calculatedIn:V(N,u.decimalsIn),amountIn:V(B,u.decimalsIn),spotPrice:V(L,u.decimalsIn),tradeFeePct:R,tradeFeeRange:C,priceImpactPct:w,errors:T}}})}return s}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,FarmClient,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
package/build/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var We=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Zt=5,Re=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new We,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>Zt)return s;let u=c[c.length-1];(r===null||u[0]===r)&&s.push(c),e.get(u[0])?.forEach(O=>{if(this.isNotVisited(O,c)){let B=[...c];B.push(O),i.enqueue(B)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,a]of t){let c=parseInt(i),u=parseInt(a);r.get(c)?.push([u,s])}return r}};function mt(m){let e={};for(let t of m){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let a=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(a)}}}return e}var Ee=class{getProposals(e,t,r){let s=mt(r),i=Object.keys(s),a=i.map(O=>s[O]).flat(),c=new Re,u=c.buildAndPopulateGraph(i,a),y=c.findPaths(u,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let a=r[i],c=r[i+1];if(c==null)break;s.push(this.toEdge(a,c))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var Kt=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,pt=Math.ceil,oe=Math.floor,V="[BigNumber Error] ",Bt=V+"Number primitive has more than 15 significant digits: ",ce=1e14,N=14,gt=9007199254740991,ht=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],ye=1e7,$=1e9;function vt(m){var e,t,r,s=w.prototype={constructor:w,toString:null,valueOf:null},i=new w(1),a=20,c=4,u=-7,y=21,O=-1e7,B=1e7,F=!1,_=1,T=0,D={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},L="0123456789abcdefghijklmnopqrstuvwxyz",Y=!0;function w(n,o){var l,P,g,d,S,p,h,b,f=this;if(!(f instanceof w))return new w(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<O?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!Kt.test(b=String(n)))return r(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(q(o,2,L.length,"Base"),o==10&&Y)return f=new w(n),R(f,a+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return r(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,w.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Bt+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=L.slice(0,o),d=S=0,h=b.length;S<h;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return r(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&w.DEBUG&&h>15&&(n>gt||n!==oe(n)))throw Error(Bt+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<O)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%N,d<0&&(S+=N),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=N;S<h;)f.c.push(+b.slice(S,S+=N));S=N-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}w.clone=vt,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],q(l,0,$,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],q(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(q(l[0],-$,0,o),q(l[1],0,$,o),u=l[0],y=l[1]):(q(l,-$,$,o),u=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)q(l[0],-$,-1,o),q(l[1],1,$,o),O=l[0],B=l[1];else if(q(l,-$,$,o),l)O=-(B=l<0?-l:l);else throw Error(V+o+" cannot be zero: "+l);if(n.hasOwnProperty(o="CRYPTO"))if(l=n[o],l===!!l)if(l)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))F=l;else throw F=!l,Error(V+"crypto unavailable");else F=l;else throw Error(V+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],q(l,0,9,o),_=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],q(l,0,$,o),T=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")D=l;else throw Error(V+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))Y=l.slice(0,10)=="0123456789",L=l;else throw Error(V+o+" invalid: "+l)}else throw Error(V+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[u,y],RANGE:[O,B],CRYPTO:F,MODULO_MODE:_,POW_PRECISION:T,FORMAT:D,ALPHABET:L}},w.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!w.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-$&&g<=$&&g===oe(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%N,o<1&&(o+=N),String(P[0]).length==o){for(o=0;o<P.length;o++)if(l=P[o],l<0||l>=ce||l!==oe(l))break e;if(l!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(V+"Invalid BigNumber: "+n)},w.maximum=w.max=function(){return re(arguments,-1)},w.minimum=w.min=function(){return re(arguments,1)},w.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return oe(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,S,p,h=0,b=[],f=new w(i);if(l==null?l=a:q(l,0,$),S=pt(l/N),F)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));h<S;)p=P[h]*131072+(P[h+1]>>>11),p>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(p%1e14),h+=2);h=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);h<S;)p=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],p>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(p%1e14),h+=7);h=S/7}else throw F=!1,Error(V+"crypto unavailable");if(!F)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],l%=N,S&&l&&(p=ht[N-l],b[h]=oe(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=N);for(h=1,p=b[0];p>=10;p/=10,h++);h<N&&(d-=N-h)}return f.e=d,f.c=b,f}}(),w.sum=function(){for(var n=1,o=arguments,l=new w(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var S,p=[0],h,b=0,f=l.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(l.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(l,P,g,d,S){var p,h,b,f,x,v,A,M,H=l.indexOf("."),W=a,k=c;for(H>=0&&(f=T,T=0,l=l.replace(".",""),M=new w(P),v=M.pow(l.length-H),T=f,M.c=o(Pe(ne(v.c),v.e,"0"),10,g,n),M.e=M.c.length),A=o(l,P,g,S?(p=L,n):(p=n,L)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(H<0?--b:(v.c=A,v.e=b,v.s=d,v=e(v,M,W,k,g),A=v.c,x=v.r,b=v.e),h=b+W+1,H=A[h],f=g/2,x=x||h<0||A[h+1]!=null,x=k<4?(H!=null||x)&&(k==0||k==(v.s<0?3:2)):H>f||H==f&&(k==4||x||k==6&&A[h-1]&1||k==(v.s<0?8:7)),h<1||!A[0])l=x?Pe(p.charAt(1),-W,p.charAt(0)):p.charAt(0);else{if(A.length=h,x)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(H=0,l="";H<=f;l+=p.charAt(A[H++]));l=Pe(l,b,p.charAt(0))}return l}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,x=P.length,v=g%ye,A=g/ye|0;for(P=P.slice();x--;)h=P[x]%ye,b=P[x]/ye|0,S=A*h+b*v,p=v*h+S%ye*ye+f,f=(p/d|0)+(S/ye|0)+A*b,P[x]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function l(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,x,v,A,M,H,W,k,C,K,Ye,ut,ct,ge,_e,ie=P.s==g.s?1:-1,Q=P.c,U=g.c;if(!Q||!Q[0]||!U||!U[0])return new w(!P.s||!g.s||(Q?U&&Q[0]==U[0]:!U)?NaN:Q&&Q[0]==0||!U?ie*0:ie/0);for(H=new w(ie),W=H.c=[],b=P.e-g.e,ie=d+b+1,p||(p=ce,b=ae(P.e/N)-ae(g.e/N),ie=ie/N|0),f=0;U[f]==(Q[f]||0);f++);if(U[f]>(Q[f]||0)&&b--,ie<0)W.push(1),x=!0;else{for(ut=Q.length,ge=U.length,f=0,ie+=2,v=oe(p/(U[0]+1)),v>1&&(U=n(U,v,p),Q=n(Q,v,p),ge=U.length,ut=Q.length),Ye=ge,k=Q.slice(0,ge),C=k.length;C<ge;k[C++]=0);_e=U.slice(),_e=[0].concat(_e),ct=U[0],U[1]>=p/2&&ct++;do{if(v=0,h=o(U,k,ge,C),h<0){if(K=k[0],ge!=C&&(K=K*p+(k[1]||0)),v=oe(K/ct),v>1)for(v>=p&&(v=p-1),A=n(U,v,p),M=A.length,C=k.length;o(A,k,M,C)==1;)v--,l(A,ge<M?_e:U,M,p),M=A.length,h=1;else v==0&&(h=v=1),A=U.slice(),M=A.length;if(M<C&&(A=[0].concat(A)),l(k,A,C,p),C=k.length,h==-1)for(;o(U,k,ge,C)<1;)v++,l(k,ge<C?_e:U,C,p),C=k.length}else h===0&&(v++,k=[0]);W[f++]=v,k[0]?k[C++]=Q[Ye]||0:(k=[Q[Ye]],C=1)}while((Ye++<ut||k[0]!=null)&&ie--);x=k[0]!=null,W[0]||W.splice(0,1)}if(p==ce){for(f=1,ie=W[0];ie>=10;ie/=10,f++);R(H,d+(H.e=f+b*N-1)+1,S,x)}else H.e=b,H.r=+x;return H}}();function j(n,o,l,P){var g,d,S,p,h;if(l==null?l=c:q(l,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ne(n.c),h=P==1||P==2&&(S<=u||S>=y)?je(h,S):Pe(h,S,"0");else if(n=R(new w(n),o,l),d=n.e,h=ne(n.c),p=h.length,P==1||P==2&&(o<=d||d<=u)){for(;p<o;h+="0",p++);h=je(h,d)}else if(o-=S,h=Pe(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function re(n,o){for(var l,P,g=1,d=new w(n[0]);g<n.length;g++)P=new w(n[g]),(!P.s||(l=xe(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function fe(n,o,l){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(l=P+l*N-1)>B?n.c=n.e=null:l<O?n.c=[n.e=0]:(n.e=l,n.c=o),n}r=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,h){var b,f=p?S:S.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(x,v,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?v:x}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new w(f,b);if(w.DEBUG)throw Error(V+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function R(n,o,l,P){var g,d,S,p,h,b,f,x=n.c,v=ht;if(x){e:{for(g=1,p=x[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=N,S=o,h=x[b=0],f=oe(h/v[g-S-1]%10);else if(b=pt((d+1)/N),b>=x.length)if(P){for(;x.length<=b;x.push(0));h=f=0,g=1,d%=N,S=d-N+1}else break e;else{for(h=p=x[b],g=1;p>=10;p/=10,g++);d%=N,S=d-N+g,f=S<0?0:oe(h/v[g-S-1]%10)}if(P=P||o<0||x[b+1]!=null||(S<0?h:h%v[g-S-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?S>0?h/v[g-S]:0:x[b-1])%10&1||l==(n.s<0?8:7)),o<1||!x[0])return x.length=0,P?(o-=n.e+1,x[0]=v[(N-o%N)%N],n.e=-o||0):x[0]=n.e=0,n;if(d==0?(x.length=b,p=1,b--):(x.length=b+1,p=v[N-d],x[b]=S>0?oe(h/v[g-S]%v[S])*p:0),P)for(;;)if(b==0){for(d=1,S=x[0];S>=10;S/=10,d++);for(S=x[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,x[0]==ce&&(x[0]=1));break}else{if(x[b]+=p,x[b]!=ce)break;x[b--]=0,p=1}for(d=x.length;x[--d]===0;x.pop());}n.e>B?n.c=n.e=null:n.e<O&&(n.c=[n.e=0])}return n}function z(n){var o,l=n.e;return l===null?n.toString():(o=ne(n.c),o=l<=u||l>=y?je(o,l):Pe(o,l,"0"),n.s<0?"-"+o:o)}return s.absoluteValue=s.abs=function(){var n=new w(this);return n.s<0&&(n.s=1),n},s.comparedTo=function(n,o){return xe(this,new w(n,o))},s.decimalPlaces=s.dp=function(n,o){var l,P,g,d=this;if(n!=null)return q(n,0,$),o==null?o=c:q(o,0,8),R(new w(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-ae(this.e/N))*N,g=l[g])for(;g%10==0;g/=10,P--);return P<0&&(P=0),P},s.dividedBy=s.div=function(n,o){return e(this,new w(n,o),a,c)},s.dividedToIntegerBy=s.idiv=function(n,o){return e(this,new w(n,o),0,1)},s.exponentiatedBy=s.pow=function(n,o){var l,P,g,d,S,p,h,b,f,x=this;if(n=new w(n),n.c&&!n.isInteger())throw Error(V+"Exponent not an integer: "+z(n));if(o!=null&&(o=new w(o)),p=n.e>14,!x.c||!x.c[0]||x.c[0]==1&&!x.e&&x.c.length==1||!n.c||!n.c[0])return f=new w(Math.pow(+z(x),p?n.s*(2-$e(n)):+z(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new w(NaN);P=!h&&x.isInteger()&&o.isInteger(),P&&(x=x.mod(o))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||p&&x.c[1]>=24e7:x.c[0]<8e13||p&&x.c[0]<=9999975e7)))return d=x.s<0&&$e(n)?-0:0,x.e>-1&&(d=1/d),new w(h?1/d:d);T&&(d=pt(T/N+2))}for(p?(l=new w(.5),h&&(n.s=1),b=$e(n)):(g=Math.abs(+z(n)),b=g%2),f=new w(i);;){if(b){if(f=f.times(x),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(g){if(g=oe(g/2),g===0)break;b=g%2}else if(n=n.times(l),R(n,n.e+1,1),n.e>14)b=$e(n);else{if(g=+z(n),g===0)break;b=g%2}x=x.times(x),d?x.c&&x.c.length>d&&(x.c.length=d):P&&(x=x.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?R(f,T,c,S):f)},s.integerValue=function(n){var o=new w(this);return n==null?n=c:q(n,0,8),R(o,o.e+1,n)},s.isEqualTo=s.eq=function(n,o){return xe(this,new w(n,o))===0},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(n,o){return xe(this,new w(n,o))>0},s.isGreaterThanOrEqualTo=s.gte=function(n,o){return(o=xe(this,new w(n,o)))===1||o===0},s.isInteger=function(){return!!this.c&&ae(this.e/N)>this.c.length-2},s.isLessThan=s.lt=function(n,o){return xe(this,new w(n,o))<0},s.isLessThanOrEqualTo=s.lte=function(n,o){return(o=xe(this,new w(n,o)))===-1||o===0},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&this.c[0]==0},s.minus=function(n,o){var l,P,g,d,S=this,p=S.s;if(n=new w(n,o),o=n.s,!p||!o)return new w(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/N,b=n.e/N,f=S.c,x=n.c;if(!h||!b){if(!f||!x)return f?(n.s=-o,n):new w(x?S:NaN);if(!f[0]||!x[0])return x[0]?(n.s=-o,n):new w(f[0]?S:c==3?-0:0)}if(h=ae(h),b=ae(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=x),g.reverse(),o=p;o--;g.push(0));g.reverse()}else for(P=(d=(p=f.length)<(o=x.length))?p:o,p=o=0;o<P;o++)if(f[o]!=x[o]){d=f[o]<x[o];break}if(d&&(g=f,f=x,x=g,n.s=-n.s),o=(P=x.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=ce-1;P>p;){if(f[--P]<x[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=ce}f[P]-=x[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?fe(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},s.modulo=s.mod=function(n,o){var l,P,g=this;return n=new w(n,o),!g.c||!n.s||n.c&&!n.c[0]?new w(NaN):!n.c||g.c&&!g.c[0]?new w(g):(_==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,_),n=g.minus(l.times(n)),!n.c[0]&&_==1&&(n.s=g.s),n)},s.multipliedBy=s.times=function(n,o){var l,P,g,d,S,p,h,b,f,x,v,A,M,H,W,k=this,C=k.c,K=(n=new w(n,o)).c;if(!C||!K||!C[0]||!K[0])return!k.s||!n.s||C&&!C[0]&&!K||K&&!K[0]&&!C?n.c=n.e=n.s=null:(n.s*=k.s,!C||!K?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=ae(k.e/N)+ae(n.e/N),n.s*=k.s,h=C.length,x=K.length,h<x&&(M=C,C=K,K=M,g=h,h=x,x=g),g=h+x,M=[];g--;M.push(0));for(H=ce,W=ye,g=x;--g>=0;){for(l=0,v=K[g]%W,A=K[g]/W|0,S=h,d=g+S;d>g;)b=C[--S]%W,f=C[S]/W|0,p=A*b+f*v,b=v*b+p%W*W+M[d]+l,l=(b/H|0)+(p/W|0)+A*f,M[d--]=b%H;M[d]=l}return l?++P:M.splice(0,1),fe(n,M,P)},s.negated=function(){var n=new w(this);return n.s=-n.s||null,n},s.plus=function(n,o){var l,P=this,g=P.s;if(n=new w(n,o),o=n.s,!g||!o)return new w(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/N,S=n.e/N,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new w(g/0);if(!p[0]||!h[0])return h[0]?n:new w(p[0]?P:g*0)}if(d=ae(d),S=ae(S),p=p.slice(),g=d-S){for(g>0?(S=d,l=h):(g=-g,l=p),l.reverse();g--;l.push(0));l.reverse()}for(g=p.length,o=h.length,g-o<0&&(l=h,h=p,p=l,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/ce|0,p[o]=ce===p[o]?0:p[o]%ce;return g&&(p=[g].concat(p),++S),fe(n,p,S)},s.precision=s.sd=function(n,o){var l,P,g,d=this;if(n!=null&&n!==!!n)return q(n,1,$),o==null?o=c:q(o,0,8),R(new w(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*N+1,g=l[g]){for(;g%10==0;g/=10,P--);for(g=l[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},s.shiftedBy=function(n){return q(n,-gt,gt),this.times("1e"+n)},s.squareRoot=s.sqrt=function(){var n,o,l,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new w("0.5");if(p!==1||!S||!S[0])return new w(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+z(d)),p==0||p==1/0?(o=ne(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=ae((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new w(o)):l=new w(p+""),l.c[0]){for(h=l.e,p=h+b,p<3&&(p=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ne(g.c).slice(0,p)===(o=ne(l.c)).slice(0,p))if(l.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(R(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(R(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return R(l,l.e+a+1,c,n)},s.toExponential=function(n,o){return n!=null&&(q(n,0,$),n++),j(this,n,o,1)},s.toFixed=function(n,o){return n!=null&&(q(n,0,$),n=n+this.e+1),j(this,n,o)},s.toFormat=function(n,o,l){var P,g=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=D;else if(typeof l!="object")throw Error(V+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],x=S[1],v=g.s<0,A=v?f.slice(1):f,M=A.length;if(h&&(d=p,p=h,h=d,M-=d),p>0&&M>0){for(d=M%p||p,f=A.substr(0,d);d<M;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=x?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?x.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):x):f}return(l.prefix||"")+P+(l.suffix||"")},s.toFraction=function(n){var o,l,P,g,d,S,p,h,b,f,x,v,A=this,M=A.c;if(n!=null&&(p=new w(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(V+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+z(p));if(!M)return new w(A);for(o=new w(i),b=l=new w(i),P=h=new w(i),v=ne(M),d=o.e=v.length-A.e-1,o.c[0]=ht[(S=d%N)<0?N+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new w(v),h.c[0]=0;f=e(p,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,x=e(b,P,d,c).minus(A).abs().comparedTo(e(h,l,d,c).minus(A).abs())<1?[b,P]:[h,l],B=S,x},s.toNumber=function(){return+z(this)},s.toPrecision=function(n,o){return n!=null&&q(n,1,$),j(this,n,o,2)},s.toString=function(n){var o,l=this,P=l.s,g=l.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=u||g>=y?je(ne(l.c),g):Pe(ne(l.c),g,"0"):n===10&&Y?(l=R(new w(l),a+g+1,c),o=Pe(ne(l.c),l.e,"0")):(q(n,2,L.length,"Base"),o=t(Pe(ne(l.c),g,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},s.valueOf=s.toJSON=function(){return z(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,m!=null&&w.set(m),w}function ae(m){var e=m|0;return m>0||m===e?e:e-1}function ne(m){for(var e,t,r=1,s=m.length,i=m[0]+"";r<s;){for(e=m[r++]+"",t=N-e.length;t--;e="0"+e);i+=e}for(s=i.length;i.charCodeAt(--s)===48;);return i.slice(0,s+1||1)}function xe(m,e){var t,r,s=m.c,i=e.c,a=m.s,c=e.s,u=m.e,y=e.e;if(!a||!c)return null;if(t=s&&!s[0],r=i&&!i[0],t||r)return t?r?0:-c:a;if(a!=c)return a;if(t=a<0,r=u==y,!s||!i)return r?0:!s^t?1:-1;if(!r)return u>y^t?1:-1;for(c=(u=s.length)<(y=i.length)?u:y,a=0;a<c;a++)if(s[a]!=i[a])return s[a]>i[a]^t?1:-1;return u==y?0:u>y^t?1:-1}function q(m,e,t,r){if(m<e||m>t||m!==oe(m))throw Error(V+(r||"Argument")+(typeof m=="number"?m<e||m>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(m))}function $e(m){var e=m.c.length-1;return ae(m.e/N)==e&&m.c[e]%2!=0}function je(m,e){return(m.length>1?m.charAt(0)+"."+m.slice(1):m)+(e<0?"e":"e+")+e}function Pe(m,e,t){var r,s;if(e<0){for(s=t+".";++e;s+=t);m=s+m}else if(r=m.length,++e>r){for(s=t,e-=r;--e;s+=t);m+=s}else e<r&&(m=m.slice(0,e)+"."+m.slice(e));return m}var G=vt();var Qt=12;G.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Qt});var E=I(0),le=I(1),ds=I("Infinity");function J(m,e){let t=new G(e.toString()),r=new G(10).pow(t);return m.times(r)}function I(m){return new G(m.toString())}var se=(s=>(s.XYK="Xyk",s.LBP="Lbp",s.Stable="Stableswap",s.Omni="Omnipool",s))(se||{}),ke=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(ke||{}),It=(t=>(t.Buy="Buy",t.Sell="Sell",t))(It||{});import{calculate_in_given_out as Vt,calculate_out_given_in as er,calculate_linear_weights as tr,calculate_pool_trade_fee as rr,get_spot_price as sr}from"@galacticcouncil/math-lbp";var me=class{static getSpotPrice(e,t,r,s,i){return sr(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return Vt(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return er(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return tr(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return rr(e,t,r)}};import{encodeAddress as ir}from"@polkadot/util-crypto";import{stringToU8a as nr}from"@polkadot/util";var Le=18,dt=15,Se="0",xs=12,Os=2034,Me=63,Bs=2090,ft=1e3,Je=ir(nr("modlomnipool".padEnd(32,"\0")),Me);function At(m,e){let t;return JSON.stringify(m,(r,s)=>(s&&s[e]&&(t=s),s)),t}function Is(m,e,t){let r;return JSON.stringify(m,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";var we=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var De=class extends we{SUPPORTED_TYPES=["StableSwap","Bond","Token","External"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==Se){let B=this.api.consts.balances.existentialDeposit;return{id:Se,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:B.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:u}=t,{symbol:y,decimals:O}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:y,decimals:O,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:this.parseLocation("parachain",s),existentialDeposit:u.toString()}}getBond(e,t,r,s){let[i,a]=s,{assetType:c,isSufficient:u,existentialDeposit:y}=t,{symbol:O,decimals:B}=this.getToken(i.toString(),t,r),F=a.toNumber(),_=new Intl.DateTimeFormat("en-GB"),T=[O,"Bond",_.format(F)].join(" ");return{id:e,name:T,symbol:O+"b",decimals:B,icon:O,type:c.toString(),isSufficient:u.toHuman(),existentialDeposit:y.toString()}}getShares(e,t,r,s){let{assets:i}=s,{name:a,symbol:c,assetType:u,isSufficient:y,existentialDeposit:O}=t,F=i.map(D=>D.toString()).map(D=>{let{symbol:L}=this.getToken(D,t,r);return[D,L]}),_=Object.fromEntries(F),T=Object.values(_);return{id:e,name:T.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:T.join("/"),type:u.toString(),isSufficient:y.toHuman(),existentialDeposit:O.toString(),meta:_}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),a=r?.find(c=>c.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:a}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e){let[t,r,s,i,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),c=this.getSupportedAssets(t),u=this.normalizeMetadata(c,a);return c.map(([{args:[y]},O])=>{let B=O.unwrap(),F=r.get(y.toString()),{assetType:_}=B;switch(_.toString()){case"Bond":let T=i.get(y.toString());return this.getBond(y.toString(),B,u,T);case"StableSwap":let D=s.get(y.toString());return this.getShares(y.toString(),B,u,D);case"External":return this.getExternal(y.toString(),B,e,F);default:return this.getToken(y.toString(),B,u,F)}}).filter(y=>this.isValidAsset(y))}isValidAsset(e){return!!e.symbol&&!!e.decimals}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let r=At(t.toJSON(),e);return r&&r[e]}else return}};var Ce=class extends we{constructor(e){super(e)}async getBalance(e,t){return t===Se?await this.getSystemBalance(e):await this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:i})}async subscribeBalance(e,t,r){let s=t.filter(i=>i!==Se).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach(({free:a,reserved:c,frozen:u},y)=>{let O=this.calculateFreeBalance({free:a,feeFrozen:c,frozen:u}),B=s[y][1];r(B,O)})})}async subscribeTokenBalance(e,t,r){let s=t.filter(i=>i!==Se).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach((a,c)=>{let u=this.calculateFreeBalance(a),y=s[c][1];r(y,u)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(Se,this.calculateFreeBalance(r)))}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:i}=e,a=new G(t),c=new G(r||i),u=new G(s||0),y=c.gt(u)?c:u;return a.minus(y)}};import{isAddress as Nt}from"@polkadot/util-crypto";import{fixed_from_rational as Ft}from"@galacticcouncil/math-liquidity-mining";var Pt=class extends we{constructor(e){super(e)}secondsInYear=new G(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(u)).unwrap(),O=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(u)).unwrap(),O=(await this.api.query.xykWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new G(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),c=a.price.n.toString(),u=a.price.d.toString(),y;return Number(t)<Number(r)?y=Ft(c,u):y=Ft(u,c),y}getGlobalRewardPerPeriod(e,t,r,s){let a=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return a.gte(r)?r:a}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!Nt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&Nt(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:c,globalFarm:u,priceAdjustment:y})=>{let O=new G(u.totalSharesZ.toString()),B=u.plannedYieldingPeriods.toString(),F=new G(u.yieldPerPeriod.toString()),_=new G(u.maxRewardPerPeriod.toString()),T=u.blocksPerPeriod.toString(),D=new G(c.multiplier.toString()).shiftedBy(-18),L=this.secondsInYear.div(new G(r).times(T)),Y;if(O.isZero())Y=F.times(D).times(L);else{let fe=this.getGlobalRewardPerPeriod(O,F,_,y);Y=this.getPoolYieldPerPeriod(fe,D,O,y).times(L)}let w=new G(u.pendingRewards.toString()).plus(u.accumulatedPaidRewards.toString()),j=_.times(B);return w.div(j).gte(.99)?E:Y.times(100)}).reduce((c,u)=>c.plus(u),E).toString():void 0}};var he=class extends Ce{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async r=>{let s=[await this.subscribePoolChange(r),await this.subscribeTokensPoolBalance(r),await this.subscribeSystemPoolBalance(r)];if(this.hasShareAsset(r)){let i=await this.subscribeSharePoolBalance(r);s.push(i)}return this.subscribeLog(r),s});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,r)=>t.id!==r))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance(Je,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(r,s){let i=e.tokens.findIndex(a=>a.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=s.toString())}}};var Ze=class extends he{MAX_FINAL_WEIGHT=J(I(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,a])=>this.isActivePool(a.unwrap(),r)).map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=await this.getPoolDelta(u,c,r.toString());return this.poolsData.set(i.toString(),c),{address:u,type:"Lbp",fee:c.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let a=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(c=>c.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,r){let{start:s,end:i,assets:a,initialWeight:c,finalWeight:u,repayTarget:y,feeCollector:O}=t,B=me.calculateLinearWeights(s.toString(),i.toString(),c.toString(),u.toString(),r),[F,_]=a,T=F.toString(),D=I(B),L=_.toString(),Y=this.MAX_FINAL_WEIGHT.minus(I(D)),[w,j,re]=await Promise.all([this.isRepayFeeApplied(T,y.toString(),O.toString()),this.getBalance(e,T),this.getBalance(e,L)]);return{repayFeeApply:w,tokens:[{id:T,weight:D,balance:j.toString()},{id:L,weight:Y,balance:re.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=I(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{encodeAddress as or}from"@polkadot/util-crypto";import{stringToU8a as ar}from"@polkadot/util";function Z(m,e){return m.shiftedBy(-1*e).toString()}function ue(m){return m[0]/m[1]*100}function ee(m){return m[0]/m[1]}function pe(m){return[m/ft,ft]}var Ke=class extends he{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=r.map(async([{args:[u]},y])=>{let{hubReserve:O,shares:B,tradable:F}=y.unwrap(),_=await this.getBalance(t,u.toString());return{id:u.toString(),hubReserves:I(O.toString()),shares:I(B.toString()),tradeable:F.bits.toNumber(),balance:_.toString()}}),c=await Promise.all(a);return c.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:c,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=await this.api.query.dynamicFees.assetFee(e),s=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=s.minFee.toNumber()+i.minFee.toNumber(),c=s.maxFee.toNumber()+i.maxFee.toNumber();if(r.isSome){let{assetFee:u,protocolFee:y}=r.unwrap();return{assetFee:pe(u.toNumber()),protocolFee:pe(y.toNumber()),min:pe(a),max:pe(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:pe(a),max:pe(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,i)=>{let a=e.tokens[i];if(s.isNone)return a;let c=s.unwrap();return this.updateTokenState(a,c)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i}=t;return{...e,hubReserves:I(r.toString()),shares:I(s.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return pe(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return pe(t)}getPoolId(){return or(ar("modlomnipool".padEnd(32,"\0")),Me)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var Qe=class extends he{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[a,c]=s.unwrap(),[u,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:u.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{blake2AsHex as Pr,encodeAddress as br}from"@polkadot/util-crypto";import{calculate_in_given_out as lr,calculate_out_given_in as ur,calculate_amplification as cr,calculate_add_one_asset as mr,calculate_liquidity_out_one_asset as pr,calculate_pool_trade_fee as gr,calculate_shares as hr,calculate_shares_for_amount as dr,pool_account_name as fr}from"@galacticcouncil/math-stableswap";var te=class{static getPoolAddress(e){return fr(e)}static calculateAmplification(e,t,r,s,i){return cr(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,a){return lr(e,t,r,s,i,a)}static calculateAddOneAsset(e,t,r,s,i,a){return mr(e,t,r,s,i,a)}static calculateSharesForAmount(e,t,r,s,i,a){return dr(e,t,r,s,i,a)}static calculateOutGivenIn(e,t,r,s,i,a){return ur(e,t,r,s,i,a)}static calculateLiquidityOutOneAsset(e,t,r,s,i,a){return pr(e,t,r,s,i,a)}static calculateShares(e,t,r,s,i){return hr(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return gr(e,t,r)}};var Ve=class extends he{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=this.getPoolAddress(u),[O,B]=await Promise.all([this.getPoolDelta(u,c,r.toString()),this.getPoolTokens(y,u,c)]);return this.stablePools.set(y,c),{address:y,id:u,type:"Stableswap",fee:pe(c.fee.toNumber()),tokens:B,...O,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toNumber(),s=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,s,r.toString());Object.assign(e,i)})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:a,finalBlock:c}=t,u=te.calculateAmplification(s.toString(),i.toString(),a.toString(),c.toString(),r),y=await this.api.query.tokens.totalIssuance(e);return{amplification:u,totalIssuance:y.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async u=>{let[y,O]=await Promise.all([this.api.query.stableswap.assetTradability(t,u.toString()),this.getBalance(e,u.toString())]);return{id:u.toString(),tradeable:y.bits.toNumber(),balance:O.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:u}=c.unwrap(),y=await this.getBalance(Je,t);a.push({id:t,tradeable:u.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),r=te.getPoolAddress(t);return br(Pr(r),Me)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function bt(m){return m.map(({assetIn:e,assetOut:t,pool:r,poolId:s})=>r==="Stableswap"?{pool:{Stableswap:s},assetIn:e,assetOut:t}:{pool:r,assetIn:e,assetOut:t})}var et=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Tt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ge=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},_t=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Rt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},kt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var qe=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new De(this.api),this.xykClient=new Qe(this.api),this.omniClient=new Ke(this.api),this.lbpClient=new Ze(this.api),this.stableClient=new Ve(this.api)}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||this.syncRegistry(),e.length==0){let a=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(c=>c.isSupported()).map(c=>c.getPools()))).flat();return this.withMetadata(a)}let t=[];e.forEach(i=>{switch(i){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break;case"Stableswap":t.push(this.stableClient.getPools());break}});let s=(await Promise.all(t)).flat();return this.withMetadata(s)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(r=>[r.id,r]));return e.filter(r=>r.type==="Xyk"?r.tokens.every(s=>t.get(s.id)):!0).map(r=>{let s=r.tokens.map(i=>{let a=t.get(i.id);return{...i,...a}});return{...r,tokens:s}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new et(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,r,s,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,r.toFixed(),s.toFixed()):a=this.api.tx.router.buy(e,t,r.toFixed(),s.toFixed(),bt(i));let c=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,r,s,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,r.toFixed(),s.toFixed()):a=this.api.tx.router.sell(e,t,r.toFixed(),s.toFixed(),bt(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var He=(m,e)=>m===e?0:m==null?e==null?0:-1:e==null?m==null?0:1:typeof m.compare=="function"?m.compare(e):typeof e.compare=="function"?-e.compare(m):m<e?-1:m>e?1:0;var tt=(m,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(m(t)+e(t))}};var yr=tt(()=>"illegal argument(s)"),Lt=m=>{throw new yr(m)};var Sr=tt(()=>"index out of bounds"),yt=m=>{throw new Sr(m)},rt=(m,e,t)=>(m<e||m>=t)&&yt(m);var Mt=23283064365386963e-26,st=class{float(e=1){return this.int()*Mt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Mt-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var St=Math.random,wt=class extends st{int(){return St()*4294967296>>>0}float(e=1){return St()*e}norm(e=1){return(St()-.5)*2*e}},Dt=new wt;var Ct=m=>m!=null&&typeof m!="function"&&m.length!==void 0;var Gt=Object.getPrototypeOf({}),it="function",qt="string",Ae=(m,e)=>{let t;if(m===e)return!0;if(m!=null){if(typeof m.equiv===it)return m.equiv(e)}else return m==e;if(e!=null){if(typeof e.equiv===it)return e.equiv(m)}else return m==e;return typeof m===qt||typeof e===qt?!1:(t=Object.getPrototypeOf(m),(t==null||t===Gt)&&(t=Object.getPrototypeOf(e),t==null||t===Gt)?Br(m,e):typeof m!==it&&m.length!==void 0&&typeof e!==it&&e.length!==void 0?wr(m,e):m instanceof Set&&e instanceof Set?xr(m,e):m instanceof Map&&e instanceof Map?Or(m,e):m instanceof Date&&e instanceof Date?m.getTime()===e.getTime():m instanceof RegExp&&e instanceof RegExp?m.toString()===e.toString():m!==m&&e!==e)},wr=(m,e,t=Ae)=>{let r=m.length;if(r===e.length)for(;r-- >0&&t(m[r],e[r]););return r<0},xr=(m,e,t=Ae)=>m.size===e.size&&t([...m.keys()].sort(),[...e.keys()].sort()),Or=(m,e,t=Ae)=>m.size===e.size&&t([...m].sort(),[...e].sort()),Br=(m,e,t=Ae)=>{if(Object.keys(m).length!==Object.keys(e).length)return!1;for(let r in m)if(!e.hasOwnProperty(r)||!t(m[r],e[r]))return!1;return!0};var Ht=(m,e)=>m!=null&&typeof m[e]=="function";var Ut=m=>Ht(m,"xform")?m.xform():m;var nt=Symbol(),xt=()=>{};var zt=m=>m!=null&&typeof m[Symbol.iterator]=="function";var ot=class{value;constructor(e){this.value=e}deref(){return this.value}};var at=m=>m instanceof ot;var Xt=m=>m instanceof ot?m.deref():m;function*Yt(m,e){let t=Ut(m)([xt,xt,(r,s)=>s])[2];for(let r of e){let s=t(nt,r);if(at(s)){s=Xt(s.deref()),s!==nt&&(yield s);return}s!==nt&&(yield s)}}var Wt=(m,e)=>[m[0],m[1],e];function Ue(m,e){return zt(e)?Yt(Ue(m),e):t=>{let r=t[2];return Wt(t,(s,i)=>r(s,m(i)))}}var Ne=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return $t("next",this._head)}reverseIterator(){return $t("prev",this.tail)}clear(){this.release()}compare(e,t=He){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,a=0;for(;r-- >0&&a===0;)a=t(s.value,i.value),s=s.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof Ne||Ct(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!Ae(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||He;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!at(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&yt(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*$t(m,e){for(;e;)yield e.value,e=e[m]}var de=class extends Ne{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new de(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new de}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(rt(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(rt(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new de,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=a=>({first(){return a.value},next(){return a!==s&&a.next?i(a.next):void 0}});return r?i(r):void 0}shuffle(e,t=Dt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&Lt("invalid indices: ${from} / ${to}");let i=new de,a=this.nthCell(r);for(;a&&++r<=s;)i.push(a.value),a=a.next;return i}sort(e=He){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,a=0;for(let u=0;u<t&&(a++,i=i.next,!!i);u++);let c=t;for(;a>0||c>0&&i;){let u;a===0?(u=i,i=i.next,c--):!i||c===0||e(r.value,i.value)<=0?(u=r,r=r.next,a--):(u=i,i=i.next,c--),this._tail?this._tail.next=u:this._head=u,u.prev=this._tail,this._tail=u}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),rt(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new de;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let a of r)this.insertBefore(s,a);else for(let a of r)this.push(a);return i}};var Fe=class{map;items;opts;_size;constructor(e,t){let r=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=r.map(),this.items=new de,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ue(e=>[e.k,e],this.items)}keys(){return Ue(e=>e.k,this.items)}values(){return Ue(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new Fe(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e);return this._size+=Math.max(0,r-(s?s.value.s:0)),this.ensureSize()&&this.doSetEntry(s,e,t,r),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let r=this.map.get(e);return r?Promise.resolve(this.resetEntry(r)):t().then(s=>this.set(e,s))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,r=this.opts.maxlen;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e&&e(s.k,s.v),this._size-=s.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,r,s){e?(e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var Ot=class extends qe{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Fe(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let r=[t.address,e].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let i=await super.getPoolFees(e,t);return this.feeCache.set(r,i),i}}async destroy(){console.log(`Destroying pool cache!
2
- Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Oe=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Oe(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,i,a,c){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=c}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let c=this.calculateTradeFee(t,r),u=ue(this.repayFeeApply?r.repayFee:r.exchangeFee),y=t.plus(c),O=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return O.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:O,calculatedIn:O,amountOut:t,feePct:u,errors:i}}else{let c=this.calculateInGivenOut(e,t),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let c=this.calculateOutGivenIn(e,t),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),u=this.calculateTradeFee(c,r),y=ue(this.repayFeeApply?r.repayFee:r.exchangeFee),O=c.minus(u),B=e.balanceOut.div(this.maxOutRatio);return O.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:O,feePct:y,errors:i}}}calculateInGivenOut(e,t){let r=me.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?E:s}calculateOutGivenIn(e,t){let r=me.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?E:s}spotPriceInGivenOut(e){let t=me.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),J(le,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=me.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),J(le,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let r=me.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(r)}};import{calculate_in_given_out as vr,calculate_lrna_in_given_out as Ir,calculate_out_given_in as Ar,calculate_out_given_lrna_in as Nr,calculate_pool_trade_fee as Fr,calculate_spot_price as Tr,calculate_lrna_spot_price as _r,calculate_shares as Rr,calculate_liquidity_out as Er,calculate_liquidity_lrna_out as kr,verify_asset_cap as Lr,calculate_liquidity_hub_in as Mr,is_sell_allowed as Dr,is_buy_allowed as Cr,is_add_liquidity_allowed as Gr,is_remove_liquidity_allowed as qr}from"@galacticcouncil/math-omnipool";var X=class{static calculateSpotPrice(e,t,r,s){return Tr(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return _r(e,t)}static calculateInGivenOut(e,t,r,s,i,a,c,u,y){return vr(e,t,r,s,i,a,c,u,y)}static calculateLrnaInGivenOut(e,t,r,s,i){return Ir(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,a,c,u,y){return Ar(e,t,r,s,i,a,c,u,y)}static calculateOutGivenLrnaIn(e,t,r,s,i){return Nr(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return Fr(e,t,r)}static calculateShares(e,t,r,s){return Rr(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,a,c,u){return Er(e,t,r,s,i,a,c,u)}static calculateLiquidityLRNAOut(e,t,r,s,i,a,c,u){return kr(e,t,r,s,i,a,c,u)}static calculateCapDifference(e,t,r,s){let i=G(t),a=G(e),c=G(s),y=G(r).shiftedBy(-18);if(i.div(c).lt(y)){let B=y.times(c).minus(i).times(a),F=i.times(G(1).minus(y));return B.div(F).toFixed(0)}else return"0"}static verifyAssetCap(e,t,r,s){return Lr(e,t,r,s)}static calculateLimitHubIn(e,t,r,s){return Mr(e,t,r,s)}static isSellAllowed(e){return Dr(e)}static isBuyAllowed(e){return Cr(e)}static isAddLiquidityAllowed(e){return Gr(e)}static isRemoveLiquidityAllowed(e){return qr(e)}};var Be=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new Be(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,i,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,tradeableIn:s.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),c=s===E?E:a.div(s).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),O=X.isBuyAllowed(e.tradeableOut);(!y||!O)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&u.push("MaxOutRatioExceeded");let F=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(F)&&u.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:c.toNumber(),errors:u}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),c=s.minus(i).div(s).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),O=X.isBuyAllowed(e.tradeableOut);(!y||!O)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&u.push("MaxInRatioExceeded");let F=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(F)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:c.toNumber(),errors:u}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=X.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ee(r.assetFee).toString():E.toString(),r?ee(r.protocolFee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateLrnaInGivenOut(e,t,r){let s=X.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ee(r.assetFee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=X.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ee(r.assetFee).toString():E.toString(),r?ee(r.protocolFee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateOutGivenLrnaIn(e,t,r){let s=X.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ee(r.assetFee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=X.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=X.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=X.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=X.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,r,s,i,a,c,u,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.amplification=a,this.id=c,this.fee=u,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?dt:s.tradeable,tradeableOut:this.id===t?dt:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=ue(r.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),a=ue(r.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,r){let s=te.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateAddOneAsset(e,t,r){let s=te.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateSharesForAmount(e,t,r){let s=te.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=J(le,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,r){let s=te.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateWithdrawOneAsset(e,t,r){let s=te.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateShares(e,t,r){let s=te.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=J(le,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let r=te.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(r)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{calculate_in_given_out as Hr,calculate_out_given_in as Ur,calculate_pool_trade_fee as zr,get_spot_price as Xr,calculate_liquidity_in as Yr,calculate_shares as Wr,calculate_spot_price as $r,calculate_spot_price_with_fee as jr,calculate_liquidity_out_asset_a as Jr,calculate_liquidity_out_asset_b as Zr}from"@galacticcouncil/math-xyk";var be=class{static getSpotPrice(e,t,r){return Xr(e,t,r)}static calculateInGivenOut(e,t,r){return Hr(e,t,r)}static calculateOutGivenIn(e,t,r){return Ur(e,t,r)}static calculatePoolTradeFee(e,t,r){return zr(e,t,r)}static calculateLiquidityIn(e,t,r){return Yr(e,t,r)}static calculateSpotPrice(e,t){return $r(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return jr(e,t,r,s)}static calculateShares(e,t,r){return Wr(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return Jr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Zr(e,t,r,s)}};var Ie=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Ie(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),a=ue(r.exchangeFee),c=s.plus(i),u=[];t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&u.push("MaxOutRatioExceeded");let O=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(O)&&u.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:s,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),a=ue(r.exchangeFee),c=s.minus(i),u=[];t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&u.push("MaxInRatioExceeded");let O=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(O)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:c,feePct:a,errors:u}}calculateInGivenOut(e,t){let r=be.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?E:s}calculateOutGivenIn(e,t){let r=be.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?E:s}spotPriceInGivenOut(e){let t=be.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=J(le,18-e.decimalsOut);return I(t).div(r)}spotPriceOutGivenIn(e){let t=be.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=J(le,18-e.decimalsIn);return I(t).div(r)}calculateTradeFee(e,t){let r=be.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(r)}};var ze=class{static get(e){switch(e.type){case"Xyk":return Ie.fromPool(e);case"Omnipool":return Be.fromPool(e);case"Lbp":return Oe.fromPool(e);case"Stableswap":return ve.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Te=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ee,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),a=this.getPaths(e,null,s,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(a)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,origin:s.origin,meta:s.meta}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(c=>this.validPath(c,r)).map(c=>this.toHops(c,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(r);return{assets:s,poolsMap:i}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,ze.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,i])=>{let a=t.get(r);return{poolAddress:r,poolId:a?.id,pool:a?.type,assetIn:s,assetOut:i}})}toAssets(e,t){return e.map(r=>t.get(r))}};function Fl(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Xe(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function jt(m,e){return le.minus(e.div(m)).multipliedBy(100).decimalPlaces(2)}function Jt(m,e){return e.div(m).minus(le).multipliedBy(100).decimalPlaces(2)}var lt=class extends Te{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,a=s[s.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[r,s]}}getPoolFeeRange(e){let t=e.min?ue(e.min):void 0,r=e.max?ue(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ge(e,t);let u;if(s)u=await this.toSellSwaps(r,s,a);else{let R=c.map(async n=>await this.toSellSwaps(r,n,a)),z=await Promise.all(R);u=this.findBestSellRoute(z)}let y=u[0],O=u[u.length-1],B=this.isDirectTrade(u),F=u.map(R=>R.spotPrice.shiftedBy(-1*R.assetOutDecimals)).reduce((R,z)=>R.multipliedBy(z)),_=J(F,O.assetOutDecimals),T=B?O.calculatedOut:this.calculateDelta0Y(y.amountIn,u,a),D=O.amountOut,L=B?O.tradeFeePct:jt(T,D).toNumber(),Y=T.minus(D),w=this.getRouteFeeRange(u),j=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(_),re=Xe(T,j),fe=R=>this.poolService.buildSellTx(e,t,y.amountIn,R,u.map(z=>z));return{type:"Sell",amountIn:y.amountIn,amountOut:O.amountOut,spotPrice:_,tradeFee:Y,tradeFeePct:L,tradeFeeRange:w,priceImpactPct:re.toNumber(),swaps:u,toTx:fe,toHuman(){return{type:"Sell",amountIn:Z(y.amountIn,y.assetInDecimals),amountOut:Z(O.amountOut,O.assetOutDecimals),spotPrice:Z(_,O.assetOutDecimals),tradeFee:Z(Y,O.assetOutDecimals),tradeFeePct:L,tradeFeeRange:w,priceImpactPct:re.toNumber(),swaps:u.map(R=>R.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=s[i-1]:y=e;let O=c.calculateOutGivenIn(u,y);s.push(O)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=s[i-1].amountOut:y=J(I(e),u.decimalsIn).decimalPlaces(0,1);let O=await this.poolService.getPoolFees(u.assetOut,c),{amountOut:B,calculatedOut:F,feePct:_,errors:T}=c.validateAndSell(u,y,O),D=this.getPoolFeeRange(O),L=c.spotPriceOutGivenIn(u),Y=y.shiftedBy(-1*u.decimalsIn).multipliedBy(L),w=Xe(F,Y);s.push({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountIn:y,calculatedOut:F,amountOut:B,spotPrice:L,tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w.toNumber(),errors:T,toHuman(){return{...a,amountIn:Z(y,u.decimalsIn),calculatedOut:Z(F,u.decimalsOut),amountOut:Z(B,u.decimalsOut),spotPrice:Z(L,u.decimalsOut),tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w.toNumber(),errors:T}}})}return s}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r),i=super.getPaths(e,t,s,r);if(i.length===0)return Promise.resolve(void 0);let a=r.map(w=>w.tokens.find(j=>j.id===e)).filter(w=>!!w).sort((w,j)=>Number(j.balance)-Number(w.balance)),{balance:c,decimals:u}=a[0],O=I(c).shiftedBy(-1*u).div(100).multipliedBy(.1),B=i.map(async w=>await this.toSellSwaps(O,w,s)),F=await Promise.all(B),_=this.findBestSellRoute(F),T=await this.toSellSwaps("1",_,s),D=T.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,j)=>w.multipliedBy(j)),L=T[T.length-1].assetOutDecimals;return{amount:J(D,L),decimals:L}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,a=s[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ge(e,t);let u;if(s)u=await this.toBuySwaps(r,s,a);else{let R=c.map(async n=>await this.toBuySwaps(r,n,a)),z=await Promise.all(R);u=this.findBestBuyRoute(z)}let y=u[u.length-1],O=u[0],B=this.isDirectTrade(u),F=u.map(R=>R.spotPrice.shiftedBy(-1*R.assetInDecimals)).reduce((R,z)=>R.multipliedBy(z)),_=J(F,O.assetInDecimals),T=B?O.calculatedIn:this.calculateDelta0X(y.amountOut,u,a),D=O.amountIn,L=B?O.tradeFeePct:Jt(T,D).toNumber(),Y=D.minus(T),w=this.getRouteFeeRange(u),j=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(_),re;T.isZero()?re=-100:re=Xe(j,T).toNumber();let fe=R=>this.poolService.buildBuyTx(e,t,y.amountOut,R,u.map(z=>z));return{type:"Buy",amountOut:y.amountOut,amountIn:O.amountIn,spotPrice:_,tradeFee:Y,tradeFeePct:L,tradeFeeRange:w,priceImpactPct:re,swaps:u,toTx:fe,toHuman(){return{type:"Buy",amountOut:Z(y.amountOut,y.assetOutDecimals),amountIn:Z(O.amountIn,O.assetInDecimals),spotPrice:Z(_,O.assetInDecimals),tradeFee:Z(Y,O.assetInDecimals),tradeFeePct:L,tradeFeeRange:w,priceImpactPct:re,swaps:u.map(R=>R.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=s[0];let O=c.calculateInGivenOut(u,y);s.unshift(O)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=J(I(e),u.decimalsOut).decimalPlaces(0,1):y=s[0].amountIn;let O=await this.poolService.getPoolFees(u.assetOut,c),{amountIn:B,calculatedIn:F,feePct:_,errors:T}=c.validateAndBuy(u,y,O),D=this.getPoolFeeRange(O),L=c.spotPriceInGivenOut(u),Y=y.shiftedBy(-1*u.decimalsOut).multipliedBy(L),w;F.isZero()?w=-100:w=Xe(Y,F).toNumber(),s.unshift({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountOut:y,calculatedIn:F,amountIn:B,spotPrice:L,tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w,errors:T,toHuman(){return{...a,amountOut:Z(y,u.decimalsOut),calculatedIn:Z(F,u.decimalsIn),amountIn:Z(B,u.decimalsIn),spotPrice:Z(L,u.decimalsIn),tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w,errors:T}}})}return s}};export{De as AssetClient,_t as AssetNotFound,Bs as BASILISK_PARACHAIN_ID,Ce as BalanceClient,G as BigNumber,Ot as CachingPoolService,Qt as DECIMAL_PLACES,ft as DENOMINATOR,Pt as FarmClient,Je as HYDRADX_OMNIPOOL_ADDRESS,Os as HYDRADX_PARACHAIN_ID,Me as HYDRADX_SS58_PREFIX,ds as INFINITY,me as LbpMath,Oe as LbpPool,le as ONE,X as OmniMath,Be as OmniPool,Tt as PoolConfigNotFound,ke as PoolError,ze as PoolFactory,et as PoolNotFound,qe as PoolService,se as PoolType,kt as ProviderConfigNotFound,Le as RUNTIME_DECIMALS,Ge as RouteNotFound,Te as Router,xs as SYSTEM_ASSET_DECIMALS,Se as SYSTEM_ASSET_ID,te as StableMath,ve as StableSwap,Rt as StorageConfigNotFound,Et as SubscriptionNotSupported,dt as TRADEABLE_DEFAULT,lt as TradeRouter,It as TradeType,be as XykMath,Ie as XykPool,E as ZERO,I as bnum,bt as buildRoute,Jt as calculateBuyFee,Fl as calculateDiffToAvg,Xe as calculateDiffToRef,jt as calculateSellFee,At as findNestedKey,Is as findNestedObj,J as scale};
1
+ var We=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Zt=5,Re=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new We,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>Zt)return s;let u=c[c.length-1];(r===null||u[0]===r)&&s.push(c),e.get(u[0])?.forEach(O=>{if(this.isNotVisited(O,c)){let B=[...c];B.push(O),i.enqueue(B)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,a]of t){let c=parseInt(i),u=parseInt(a);r.get(c)?.push([u,s])}return r}};function mt(m){let e={};for(let t of m){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let a=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(a)}}}return e}var Ee=class{getProposals(e,t,r){let s=mt(r),i=Object.keys(s),a=i.map(O=>s[O]).flat(),c=new Re,u=c.buildAndPopulateGraph(i,a),y=c.findPaths(u,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let a=r[i],c=r[i+1];if(c==null)break;s.push(this.toEdge(a,c))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var Kt=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,pt=Math.ceil,oe=Math.floor,V="[BigNumber Error] ",Bt=V+"Number primitive has more than 15 significant digits: ",ce=1e14,F=14,gt=9007199254740991,ht=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],ye=1e7,$=1e9;function vt(m){var e,t,r,s=w.prototype={constructor:w,toString:null,valueOf:null},i=new w(1),a=20,c=4,u=-7,y=21,O=-1e7,B=1e7,N=!1,_=1,T=0,D={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},L="0123456789abcdefghijklmnopqrstuvwxyz",Y=!0;function w(n,o){var l,P,g,d,S,p,h,b,f=this;if(!(f instanceof w))return new w(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<O?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!Kt.test(b=String(n)))return r(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(q(o,2,L.length,"Base"),o==10&&Y)return f=new w(n),R(f,a+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return r(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,w.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Bt+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=L.slice(0,o),d=S=0,h=b.length;S<h;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return r(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&w.DEBUG&&h>15&&(n>gt||n!==oe(n)))throw Error(Bt+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<O)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%F,d<0&&(S+=F),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=F;S<h;)f.c.push(+b.slice(S,S+=F));S=F-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}w.clone=vt,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],q(l,0,$,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],q(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(q(l[0],-$,0,o),q(l[1],0,$,o),u=l[0],y=l[1]):(q(l,-$,$,o),u=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)q(l[0],-$,-1,o),q(l[1],1,$,o),O=l[0],B=l[1];else if(q(l,-$,$,o),l)O=-(B=l<0?-l:l);else throw Error(V+o+" cannot be zero: "+l);if(n.hasOwnProperty(o="CRYPTO"))if(l=n[o],l===!!l)if(l)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))N=l;else throw N=!l,Error(V+"crypto unavailable");else N=l;else throw Error(V+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],q(l,0,9,o),_=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],q(l,0,$,o),T=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")D=l;else throw Error(V+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))Y=l.slice(0,10)=="0123456789",L=l;else throw Error(V+o+" invalid: "+l)}else throw Error(V+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[u,y],RANGE:[O,B],CRYPTO:N,MODULO_MODE:_,POW_PRECISION:T,FORMAT:D,ALPHABET:L}},w.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!w.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-$&&g<=$&&g===oe(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%F,o<1&&(o+=F),String(P[0]).length==o){for(o=0;o<P.length;o++)if(l=P[o],l<0||l>=ce||l!==oe(l))break e;if(l!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(V+"Invalid BigNumber: "+n)},w.maximum=w.max=function(){return re(arguments,-1)},w.minimum=w.min=function(){return re(arguments,1)},w.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return oe(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,S,p,h=0,b=[],f=new w(i);if(l==null?l=a:q(l,0,$),S=pt(l/F),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(V+"crypto unavailable");if(!N)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],l%=F,S&&l&&(p=ht[F-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-=F);for(h=1,p=b[0];p>=10;p/=10,h++);h<F&&(d-=F-h)}return f.e=d,f.c=b,f}}(),w.sum=function(){for(var n=1,o=arguments,l=new w(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var S,p=[0],h,b=0,f=l.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(l.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(l,P,g,d,S){var p,h,b,f,x,v,A,M,H=l.indexOf("."),W=a,k=c;for(H>=0&&(f=T,T=0,l=l.replace(".",""),M=new w(P),v=M.pow(l.length-H),T=f,M.c=o(Pe(ne(v.c),v.e,"0"),10,g,n),M.e=M.c.length),A=o(l,P,g,S?(p=L,n):(p=n,L)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(H<0?--b:(v.c=A,v.e=b,v.s=d,v=e(v,M,W,k,g),A=v.c,x=v.r,b=v.e),h=b+W+1,H=A[h],f=g/2,x=x||h<0||A[h+1]!=null,x=k<4?(H!=null||x)&&(k==0||k==(v.s<0?3:2)):H>f||H==f&&(k==4||x||k==6&&A[h-1]&1||k==(v.s<0?8:7)),h<1||!A[0])l=x?Pe(p.charAt(1),-W,p.charAt(0)):p.charAt(0);else{if(A.length=h,x)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(H=0,l="";H<=f;l+=p.charAt(A[H++]));l=Pe(l,b,p.charAt(0))}return l}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,x=P.length,v=g%ye,A=g/ye|0;for(P=P.slice();x--;)h=P[x]%ye,b=P[x]/ye|0,S=A*h+b*v,p=v*h+S%ye*ye+f,f=(p/d|0)+(S/ye|0)+A*b,P[x]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function l(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,x,v,A,M,H,W,k,C,K,Ye,ut,ct,ge,_e,ie=P.s==g.s?1:-1,Q=P.c,U=g.c;if(!Q||!Q[0]||!U||!U[0])return new w(!P.s||!g.s||(Q?U&&Q[0]==U[0]:!U)?NaN:Q&&Q[0]==0||!U?ie*0:ie/0);for(H=new w(ie),W=H.c=[],b=P.e-g.e,ie=d+b+1,p||(p=ce,b=ae(P.e/F)-ae(g.e/F),ie=ie/F|0),f=0;U[f]==(Q[f]||0);f++);if(U[f]>(Q[f]||0)&&b--,ie<0)W.push(1),x=!0;else{for(ut=Q.length,ge=U.length,f=0,ie+=2,v=oe(p/(U[0]+1)),v>1&&(U=n(U,v,p),Q=n(Q,v,p),ge=U.length,ut=Q.length),Ye=ge,k=Q.slice(0,ge),C=k.length;C<ge;k[C++]=0);_e=U.slice(),_e=[0].concat(_e),ct=U[0],U[1]>=p/2&&ct++;do{if(v=0,h=o(U,k,ge,C),h<0){if(K=k[0],ge!=C&&(K=K*p+(k[1]||0)),v=oe(K/ct),v>1)for(v>=p&&(v=p-1),A=n(U,v,p),M=A.length,C=k.length;o(A,k,M,C)==1;)v--,l(A,ge<M?_e:U,M,p),M=A.length,h=1;else v==0&&(h=v=1),A=U.slice(),M=A.length;if(M<C&&(A=[0].concat(A)),l(k,A,C,p),C=k.length,h==-1)for(;o(U,k,ge,C)<1;)v++,l(k,ge<C?_e:U,C,p),C=k.length}else h===0&&(v++,k=[0]);W[f++]=v,k[0]?k[C++]=Q[Ye]||0:(k=[Q[Ye]],C=1)}while((Ye++<ut||k[0]!=null)&&ie--);x=k[0]!=null,W[0]||W.splice(0,1)}if(p==ce){for(f=1,ie=W[0];ie>=10;ie/=10,f++);R(H,d+(H.e=f+b*F-1)+1,S,x)}else H.e=b,H.r=+x;return H}}();function j(n,o,l,P){var g,d,S,p,h;if(l==null?l=c:q(l,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ne(n.c),h=P==1||P==2&&(S<=u||S>=y)?je(h,S):Pe(h,S,"0");else if(n=R(new w(n),o,l),d=n.e,h=ne(n.c),p=h.length,P==1||P==2&&(o<=d||d<=u)){for(;p<o;h+="0",p++);h=je(h,d)}else if(o-=S,h=Pe(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function re(n,o){for(var l,P,g=1,d=new w(n[0]);g<n.length;g++)P=new w(n[g]),(!P.s||(l=xe(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function fe(n,o,l){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(l=P+l*F-1)>B?n.c=n.e=null:l<O?n.c=[n.e=0]:(n.e=l,n.c=o),n}r=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,h){var b,f=p?S:S.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(x,v,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?v:x}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new w(f,b);if(w.DEBUG)throw Error(V+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function R(n,o,l,P){var g,d,S,p,h,b,f,x=n.c,v=ht;if(x){e:{for(g=1,p=x[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=F,S=o,h=x[b=0],f=oe(h/v[g-S-1]%10);else if(b=pt((d+1)/F),b>=x.length)if(P){for(;x.length<=b;x.push(0));h=f=0,g=1,d%=F,S=d-F+1}else break e;else{for(h=p=x[b],g=1;p>=10;p/=10,g++);d%=F,S=d-F+g,f=S<0?0:oe(h/v[g-S-1]%10)}if(P=P||o<0||x[b+1]!=null||(S<0?h:h%v[g-S-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?S>0?h/v[g-S]:0:x[b-1])%10&1||l==(n.s<0?8:7)),o<1||!x[0])return x.length=0,P?(o-=n.e+1,x[0]=v[(F-o%F)%F],n.e=-o||0):x[0]=n.e=0,n;if(d==0?(x.length=b,p=1,b--):(x.length=b+1,p=v[F-d],x[b]=S>0?oe(h/v[g-S]%v[S])*p:0),P)for(;;)if(b==0){for(d=1,S=x[0];S>=10;S/=10,d++);for(S=x[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,x[0]==ce&&(x[0]=1));break}else{if(x[b]+=p,x[b]!=ce)break;x[b--]=0,p=1}for(d=x.length;x[--d]===0;x.pop());}n.e>B?n.c=n.e=null:n.e<O&&(n.c=[n.e=0])}return n}function z(n){var o,l=n.e;return l===null?n.toString():(o=ne(n.c),o=l<=u||l>=y?je(o,l):Pe(o,l,"0"),n.s<0?"-"+o:o)}return s.absoluteValue=s.abs=function(){var n=new w(this);return n.s<0&&(n.s=1),n},s.comparedTo=function(n,o){return xe(this,new w(n,o))},s.decimalPlaces=s.dp=function(n,o){var l,P,g,d=this;if(n!=null)return q(n,0,$),o==null?o=c:q(o,0,8),R(new w(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-ae(this.e/F))*F,g=l[g])for(;g%10==0;g/=10,P--);return P<0&&(P=0),P},s.dividedBy=s.div=function(n,o){return e(this,new w(n,o),a,c)},s.dividedToIntegerBy=s.idiv=function(n,o){return e(this,new w(n,o),0,1)},s.exponentiatedBy=s.pow=function(n,o){var l,P,g,d,S,p,h,b,f,x=this;if(n=new w(n),n.c&&!n.isInteger())throw Error(V+"Exponent not an integer: "+z(n));if(o!=null&&(o=new w(o)),p=n.e>14,!x.c||!x.c[0]||x.c[0]==1&&!x.e&&x.c.length==1||!n.c||!n.c[0])return f=new w(Math.pow(+z(x),p?n.s*(2-$e(n)):+z(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new w(NaN);P=!h&&x.isInteger()&&o.isInteger(),P&&(x=x.mod(o))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||p&&x.c[1]>=24e7:x.c[0]<8e13||p&&x.c[0]<=9999975e7)))return d=x.s<0&&$e(n)?-0:0,x.e>-1&&(d=1/d),new w(h?1/d:d);T&&(d=pt(T/F+2))}for(p?(l=new w(.5),h&&(n.s=1),b=$e(n)):(g=Math.abs(+z(n)),b=g%2),f=new w(i);;){if(b){if(f=f.times(x),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(g){if(g=oe(g/2),g===0)break;b=g%2}else if(n=n.times(l),R(n,n.e+1,1),n.e>14)b=$e(n);else{if(g=+z(n),g===0)break;b=g%2}x=x.times(x),d?x.c&&x.c.length>d&&(x.c.length=d):P&&(x=x.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?R(f,T,c,S):f)},s.integerValue=function(n){var o=new w(this);return n==null?n=c:q(n,0,8),R(o,o.e+1,n)},s.isEqualTo=s.eq=function(n,o){return xe(this,new w(n,o))===0},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(n,o){return xe(this,new w(n,o))>0},s.isGreaterThanOrEqualTo=s.gte=function(n,o){return(o=xe(this,new w(n,o)))===1||o===0},s.isInteger=function(){return!!this.c&&ae(this.e/F)>this.c.length-2},s.isLessThan=s.lt=function(n,o){return xe(this,new w(n,o))<0},s.isLessThanOrEqualTo=s.lte=function(n,o){return(o=xe(this,new w(n,o)))===-1||o===0},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&this.c[0]==0},s.minus=function(n,o){var l,P,g,d,S=this,p=S.s;if(n=new w(n,o),o=n.s,!p||!o)return new w(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/F,b=n.e/F,f=S.c,x=n.c;if(!h||!b){if(!f||!x)return f?(n.s=-o,n):new w(x?S:NaN);if(!f[0]||!x[0])return x[0]?(n.s=-o,n):new w(f[0]?S:c==3?-0:0)}if(h=ae(h),b=ae(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=x),g.reverse(),o=p;o--;g.push(0));g.reverse()}else for(P=(d=(p=f.length)<(o=x.length))?p:o,p=o=0;o<P;o++)if(f[o]!=x[o]){d=f[o]<x[o];break}if(d&&(g=f,f=x,x=g,n.s=-n.s),o=(P=x.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=ce-1;P>p;){if(f[--P]<x[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=ce}f[P]-=x[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?fe(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},s.modulo=s.mod=function(n,o){var l,P,g=this;return n=new w(n,o),!g.c||!n.s||n.c&&!n.c[0]?new w(NaN):!n.c||g.c&&!g.c[0]?new w(g):(_==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,_),n=g.minus(l.times(n)),!n.c[0]&&_==1&&(n.s=g.s),n)},s.multipliedBy=s.times=function(n,o){var l,P,g,d,S,p,h,b,f,x,v,A,M,H,W,k=this,C=k.c,K=(n=new w(n,o)).c;if(!C||!K||!C[0]||!K[0])return!k.s||!n.s||C&&!C[0]&&!K||K&&!K[0]&&!C?n.c=n.e=n.s=null:(n.s*=k.s,!C||!K?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=ae(k.e/F)+ae(n.e/F),n.s*=k.s,h=C.length,x=K.length,h<x&&(M=C,C=K,K=M,g=h,h=x,x=g),g=h+x,M=[];g--;M.push(0));for(H=ce,W=ye,g=x;--g>=0;){for(l=0,v=K[g]%W,A=K[g]/W|0,S=h,d=g+S;d>g;)b=C[--S]%W,f=C[S]/W|0,p=A*b+f*v,b=v*b+p%W*W+M[d]+l,l=(b/H|0)+(p/W|0)+A*f,M[d--]=b%H;M[d]=l}return l?++P:M.splice(0,1),fe(n,M,P)},s.negated=function(){var n=new w(this);return n.s=-n.s||null,n},s.plus=function(n,o){var l,P=this,g=P.s;if(n=new w(n,o),o=n.s,!g||!o)return new w(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/F,S=n.e/F,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new w(g/0);if(!p[0]||!h[0])return h[0]?n:new w(p[0]?P:g*0)}if(d=ae(d),S=ae(S),p=p.slice(),g=d-S){for(g>0?(S=d,l=h):(g=-g,l=p),l.reverse();g--;l.push(0));l.reverse()}for(g=p.length,o=h.length,g-o<0&&(l=h,h=p,p=l,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/ce|0,p[o]=ce===p[o]?0:p[o]%ce;return g&&(p=[g].concat(p),++S),fe(n,p,S)},s.precision=s.sd=function(n,o){var l,P,g,d=this;if(n!=null&&n!==!!n)return q(n,1,$),o==null?o=c:q(o,0,8),R(new w(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*F+1,g=l[g]){for(;g%10==0;g/=10,P--);for(g=l[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},s.shiftedBy=function(n){return q(n,-gt,gt),this.times("1e"+n)},s.squareRoot=s.sqrt=function(){var n,o,l,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new w("0.5");if(p!==1||!S||!S[0])return new w(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+z(d)),p==0||p==1/0?(o=ne(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=ae((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new w(o)):l=new w(p+""),l.c[0]){for(h=l.e,p=h+b,p<3&&(p=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ne(g.c).slice(0,p)===(o=ne(l.c)).slice(0,p))if(l.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(R(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(R(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return R(l,l.e+a+1,c,n)},s.toExponential=function(n,o){return n!=null&&(q(n,0,$),n++),j(this,n,o,1)},s.toFixed=function(n,o){return n!=null&&(q(n,0,$),n=n+this.e+1),j(this,n,o)},s.toFormat=function(n,o,l){var P,g=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=D;else if(typeof l!="object")throw Error(V+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],x=S[1],v=g.s<0,A=v?f.slice(1):f,M=A.length;if(h&&(d=p,p=h,h=d,M-=d),p>0&&M>0){for(d=M%p||p,f=A.substr(0,d);d<M;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=x?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?x.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):x):f}return(l.prefix||"")+P+(l.suffix||"")},s.toFraction=function(n){var o,l,P,g,d,S,p,h,b,f,x,v,A=this,M=A.c;if(n!=null&&(p=new w(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(V+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+z(p));if(!M)return new w(A);for(o=new w(i),b=l=new w(i),P=h=new w(i),v=ne(M),d=o.e=v.length-A.e-1,o.c[0]=ht[(S=d%F)<0?F+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new w(v),h.c[0]=0;f=e(p,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,x=e(b,P,d,c).minus(A).abs().comparedTo(e(h,l,d,c).minus(A).abs())<1?[b,P]:[h,l],B=S,x},s.toNumber=function(){return+z(this)},s.toPrecision=function(n,o){return n!=null&&q(n,1,$),j(this,n,o,2)},s.toString=function(n){var o,l=this,P=l.s,g=l.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=u||g>=y?je(ne(l.c),g):Pe(ne(l.c),g,"0"):n===10&&Y?(l=R(new w(l),a+g+1,c),o=Pe(ne(l.c),l.e,"0")):(q(n,2,L.length,"Base"),o=t(Pe(ne(l.c),g,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},s.valueOf=s.toJSON=function(){return z(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,m!=null&&w.set(m),w}function ae(m){var e=m|0;return m>0||m===e?e:e-1}function ne(m){for(var e,t,r=1,s=m.length,i=m[0]+"";r<s;){for(e=m[r++]+"",t=F-e.length;t--;e="0"+e);i+=e}for(s=i.length;i.charCodeAt(--s)===48;);return i.slice(0,s+1||1)}function xe(m,e){var t,r,s=m.c,i=e.c,a=m.s,c=e.s,u=m.e,y=e.e;if(!a||!c)return null;if(t=s&&!s[0],r=i&&!i[0],t||r)return t?r?0:-c:a;if(a!=c)return a;if(t=a<0,r=u==y,!s||!i)return r?0:!s^t?1:-1;if(!r)return u>y^t?1:-1;for(c=(u=s.length)<(y=i.length)?u:y,a=0;a<c;a++)if(s[a]!=i[a])return s[a]>i[a]^t?1:-1;return u==y?0:u>y^t?1:-1}function q(m,e,t,r){if(m<e||m>t||m!==oe(m))throw Error(V+(r||"Argument")+(typeof m=="number"?m<e||m>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(m))}function $e(m){var e=m.c.length-1;return ae(m.e/F)==e&&m.c[e]%2!=0}function je(m,e){return(m.length>1?m.charAt(0)+"."+m.slice(1):m)+(e<0?"e":"e+")+e}function Pe(m,e,t){var r,s;if(e<0){for(s=t+".";++e;s+=t);m=s+m}else if(r=m.length,++e>r){for(s=t,e-=r;--e;s+=t);m+=s}else e<r&&(m=m.slice(0,e)+"."+m.slice(e));return m}var G=vt();var Qt=12;G.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Qt});var E=I(0),le=I(1),ds=I("Infinity");function J(m,e){let t=new G(e.toString()),r=new G(10).pow(t);return m.times(r)}function I(m){return new G(m.toString())}var se=(s=>(s.XYK="Xyk",s.LBP="Lbp",s.Stable="Stableswap",s.Omni="Omnipool",s))(se||{}),ke=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(ke||{}),It=(t=>(t.Buy="Buy",t.Sell="Sell",t))(It||{});import{calculate_in_given_out as Vt,calculate_out_given_in as er,calculate_linear_weights as tr,calculate_pool_trade_fee as rr,get_spot_price as sr}from"@galacticcouncil/math-lbp";var me=class{static getSpotPrice(e,t,r,s,i){return sr(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return Vt(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return er(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return tr(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return rr(e,t,r)}};import{encodeAddress as ir}from"@polkadot/util-crypto";import{stringToU8a as nr}from"@polkadot/util";var Le=18,dt=15,Se="0",xs=12,Os=2034,Me=63,Bs=2090,ft=1e3,Je=ir(nr("modlomnipool".padEnd(32,"\0")),Me);function At(m,e){let t;return JSON.stringify(m,(r,s)=>(s&&s[e]&&(t=s),s)),t}function Is(m,e,t){let r;return JSON.stringify(m,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";var we=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var De=class extends we{SUPPORTED_TYPES=["StableSwap","Bond","Token","External"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==Se){let B=this.api.consts.balances.existentialDeposit;return{id:Se,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:B.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:u}=t,{symbol:y,decimals:O}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:y,decimals:O,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:this.parseLocation("parachain",s),existentialDeposit:u.toString()}}getBond(e,t,r,s){let[i,a]=s,{assetType:c,isSufficient:u,existentialDeposit:y}=t,{symbol:O,decimals:B}=this.getToken(i.toString(),t,r),N=a.toNumber(),_=new Intl.DateTimeFormat("en-GB"),T=[O,"Bond",_.format(N)].join(" ");return{id:e,name:T,symbol:O+"b",decimals:B,icon:O,type:c.toString(),isSufficient:u.toHuman(),existentialDeposit:y.toString(),underlyingAssetId:i.toString(),maturity:N}}getShares(e,t,r,s){let{assets:i}=s,{name:a,symbol:c,assetType:u,isSufficient:y,existentialDeposit:O}=t,N=i.map(D=>D.toString()).map(D=>{let{symbol:L}=this.getToken(D,t,r);return[D,L]}),_=Object.fromEntries(N),T=Object.values(_);return{id:e,name:T.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:T.join("/"),type:u.toString(),isSufficient:y.toHuman(),existentialDeposit:O.toString(),meta:_}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),a=r?.find(c=>c.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:a}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e){let[t,r,s,i,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),c=this.getSupportedAssets(t),u=this.normalizeMetadata(c,a);return c.map(([{args:[y]},O])=>{let B=O.unwrap(),N=r.get(y.toString()),{assetType:_}=B;switch(_.toString()){case"Bond":let T=i.get(y.toString());return this.getBond(y.toString(),B,u,T);case"StableSwap":let D=s.get(y.toString());return this.getShares(y.toString(),B,u,D);case"External":return this.getExternal(y.toString(),B,e,N);default:return this.getToken(y.toString(),B,u,N)}}).filter(y=>this.isValidAsset(y))}isValidAsset(e){return!!e.symbol&&!!e.decimals}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let r=At(t.toJSON(),e);return r&&r[e]}else return}};var Ce=class extends we{constructor(e){super(e)}async getBalance(e,t){return t===Se?await this.getSystemBalance(e):await this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:i})}async subscribeBalance(e,t,r){let s=t.filter(i=>i!==Se).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach(({free:a,reserved:c,frozen:u},y)=>{let O=this.calculateFreeBalance({free:a,feeFrozen:c,frozen:u}),B=s[y][1];r(B,O)})})}async subscribeTokenBalance(e,t,r){let s=t.filter(i=>i!==Se).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach((a,c)=>{let u=this.calculateFreeBalance(a),y=s[c][1];r(y,u)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(Se,this.calculateFreeBalance(r)))}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:i}=e,a=new G(t),c=new G(r||i),u=new G(s||0),y=c.gt(u)?c:u;return a.minus(y)}};import{isAddress as Nt}from"@polkadot/util-crypto";import{fixed_from_rational as Ft}from"@galacticcouncil/math-liquidity-mining";var Pt=class extends we{constructor(e){super(e)}secondsInYear=new G(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(u)).unwrap(),O=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(u)).unwrap(),O=(await this.api.query.xykWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:O,priceAdjustment:B}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new G(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),c=a.price.n.toString(),u=a.price.d.toString(),y;return Number(t)<Number(r)?y=Ft(c,u):y=Ft(u,c),y}getGlobalRewardPerPeriod(e,t,r,s){let a=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return a.gte(r)?r:a}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!Nt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&Nt(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:c,globalFarm:u,priceAdjustment:y})=>{let O=new G(u.totalSharesZ.toString()),B=u.plannedYieldingPeriods.toString(),N=new G(u.yieldPerPeriod.toString()),_=new G(u.maxRewardPerPeriod.toString()),T=u.blocksPerPeriod.toString(),D=new G(c.multiplier.toString()).shiftedBy(-18),L=this.secondsInYear.div(new G(r).times(T)),Y;if(O.isZero())Y=N.times(D).times(L);else{let fe=this.getGlobalRewardPerPeriod(O,N,_,y);Y=this.getPoolYieldPerPeriod(fe,D,O,y).times(L)}let w=new G(u.pendingRewards.toString()).plus(u.accumulatedPaidRewards.toString()),j=_.times(B);return w.div(j).gte(.99)?E:Y.times(100)}).reduce((c,u)=>c.plus(u),E).toString():void 0}};var he=class extends Ce{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async r=>{let s=[await this.subscribePoolChange(r),await this.subscribeTokensPoolBalance(r),await this.subscribeSystemPoolBalance(r)];if(this.hasShareAsset(r)){let i=await this.subscribeSharePoolBalance(r);s.push(i)}return this.subscribeLog(r),s});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,r)=>t.id!==r))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance(Je,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(r,s){let i=e.tokens.findIndex(a=>a.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=s.toString())}}};var Ze=class extends he{MAX_FINAL_WEIGHT=J(I(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,a])=>this.isActivePool(a.unwrap(),r)).map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=await this.getPoolDelta(u,c,r.toString());return this.poolsData.set(i.toString(),c),{address:u,type:"Lbp",fee:c.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let a=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(c=>c.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,r){let{start:s,end:i,assets:a,initialWeight:c,finalWeight:u,repayTarget:y,feeCollector:O}=t,B=me.calculateLinearWeights(s.toString(),i.toString(),c.toString(),u.toString(),r),[N,_]=a,T=N.toString(),D=I(B),L=_.toString(),Y=this.MAX_FINAL_WEIGHT.minus(I(D)),[w,j,re]=await Promise.all([this.isRepayFeeApplied(T,y.toString(),O.toString()),this.getBalance(e,T),this.getBalance(e,L)]);return{repayFeeApply:w,tokens:[{id:T,weight:D,balance:j.toString()},{id:L,weight:Y,balance:re.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=I(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{encodeAddress as or}from"@polkadot/util-crypto";import{stringToU8a as ar}from"@polkadot/util";function Z(m,e){return m.shiftedBy(-1*e).toString()}function ue(m){return m[0]/m[1]*100}function ee(m){return m[0]/m[1]}function pe(m){return[m/ft,ft]}var Ke=class extends he{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=r.map(async([{args:[u]},y])=>{let{hubReserve:O,shares:B,tradable:N}=y.unwrap(),_=await this.getBalance(t,u.toString());return{id:u.toString(),hubReserves:I(O.toString()),shares:I(B.toString()),tradeable:N.bits.toNumber(),balance:_.toString()}}),c=await Promise.all(a);return c.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:c,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=await this.api.query.dynamicFees.assetFee(e),s=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=s.minFee.toNumber()+i.minFee.toNumber(),c=s.maxFee.toNumber()+i.maxFee.toNumber();if(r.isSome){let{assetFee:u,protocolFee:y}=r.unwrap();return{assetFee:pe(u.toNumber()),protocolFee:pe(y.toNumber()),min:pe(a),max:pe(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:pe(a),max:pe(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,i)=>{let a=e.tokens[i];if(s.isNone)return a;let c=s.unwrap();return this.updateTokenState(a,c)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i}=t;return{...e,hubReserves:I(r.toString()),shares:I(s.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return pe(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return pe(t)}getPoolId(){return or(ar("modlomnipool".padEnd(32,"\0")),Me)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var Qe=class extends he{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[a,c]=s.unwrap(),[u,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:u.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{blake2AsHex as Pr,encodeAddress as br}from"@polkadot/util-crypto";import{calculate_in_given_out as lr,calculate_out_given_in as ur,calculate_amplification as cr,calculate_add_one_asset as mr,calculate_liquidity_out_one_asset as pr,calculate_pool_trade_fee as gr,calculate_shares as hr,calculate_shares_for_amount as dr,pool_account_name as fr}from"@galacticcouncil/math-stableswap";var te=class{static getPoolAddress(e){return fr(e)}static calculateAmplification(e,t,r,s,i){return cr(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,a){return lr(e,t,r,s,i,a)}static calculateAddOneAsset(e,t,r,s,i,a){return mr(e,t,r,s,i,a)}static calculateSharesForAmount(e,t,r,s,i,a){return dr(e,t,r,s,i,a)}static calculateOutGivenIn(e,t,r,s,i,a){return ur(e,t,r,s,i,a)}static calculateLiquidityOutOneAsset(e,t,r,s,i,a){return pr(e,t,r,s,i,a)}static calculateShares(e,t,r,s,i){return hr(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return gr(e,t,r)}};var Ve=class extends he{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=this.getPoolAddress(u),[O,B]=await Promise.all([this.getPoolDelta(u,c,r.toString()),this.getPoolTokens(y,u,c)]);return this.stablePools.set(y,c),{address:y,id:u,type:"Stableswap",fee:pe(c.fee.toNumber()),tokens:B,...O,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toNumber(),s=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,s,r.toString());Object.assign(e,i)})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:a,finalBlock:c}=t,u=te.calculateAmplification(s.toString(),i.toString(),a.toString(),c.toString(),r),y=await this.api.query.tokens.totalIssuance(e);return{amplification:u,totalIssuance:y.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async u=>{let[y,O]=await Promise.all([this.api.query.stableswap.assetTradability(t,u.toString()),this.getBalance(e,u.toString())]);return{id:u.toString(),tradeable:y.bits.toNumber(),balance:O.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:u}=c.unwrap(),y=await this.getBalance(Je,t);a.push({id:t,tradeable:u.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),r=te.getPoolAddress(t);return br(Pr(r),Me)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function bt(m){return m.map(({assetIn:e,assetOut:t,pool:r,poolId:s})=>r==="Stableswap"?{pool:{Stableswap:s},assetIn:e,assetOut:t}:{pool:r,assetIn:e,assetOut:t})}var et=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Tt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ge=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},_t=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Rt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},kt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var qe=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new De(this.api),this.xykClient=new Qe(this.api),this.omniClient=new Ke(this.api),this.lbpClient=new Ze(this.api),this.stableClient=new Ve(this.api)}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||this.syncRegistry(),e.length==0){let a=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(c=>c.isSupported()).map(c=>c.getPools()))).flat();return this.withMetadata(a)}let t=[];e.forEach(i=>{switch(i){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break;case"Stableswap":t.push(this.stableClient.getPools());break}});let s=(await Promise.all(t)).flat();return this.withMetadata(s)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(r=>[r.id,r]));return e.filter(r=>r.type==="Xyk"?r.tokens.every(s=>t.get(s.id)):!0).map(r=>{let s=r.tokens.map(i=>{let a=t.get(i.id);return{...i,...a}});return{...r,tokens:s}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new et(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,r,s,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,r.toFixed(),s.toFixed()):a=this.api.tx.router.buy(e,t,r.toFixed(),s.toFixed(),bt(i));let c=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,r,s,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,r.toFixed(),s.toFixed()):a=this.api.tx.router.sell(e,t,r.toFixed(),s.toFixed(),bt(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var He=(m,e)=>m===e?0:m==null?e==null?0:-1:e==null?m==null?0:1:typeof m.compare=="function"?m.compare(e):typeof e.compare=="function"?-e.compare(m):m<e?-1:m>e?1:0;var tt=(m,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(m(t)+e(t))}};var yr=tt(()=>"illegal argument(s)"),Lt=m=>{throw new yr(m)};var Sr=tt(()=>"index out of bounds"),yt=m=>{throw new Sr(m)},rt=(m,e,t)=>(m<e||m>=t)&&yt(m);var Mt=23283064365386963e-26,st=class{float(e=1){return this.int()*Mt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Mt-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var St=Math.random,wt=class extends st{int(){return St()*4294967296>>>0}float(e=1){return St()*e}norm(e=1){return(St()-.5)*2*e}},Dt=new wt;var Ct=m=>m!=null&&typeof m!="function"&&m.length!==void 0;var Gt=Object.getPrototypeOf({}),it="function",qt="string",Ae=(m,e)=>{let t;if(m===e)return!0;if(m!=null){if(typeof m.equiv===it)return m.equiv(e)}else return m==e;if(e!=null){if(typeof e.equiv===it)return e.equiv(m)}else return m==e;return typeof m===qt||typeof e===qt?!1:(t=Object.getPrototypeOf(m),(t==null||t===Gt)&&(t=Object.getPrototypeOf(e),t==null||t===Gt)?Br(m,e):typeof m!==it&&m.length!==void 0&&typeof e!==it&&e.length!==void 0?wr(m,e):m instanceof Set&&e instanceof Set?xr(m,e):m instanceof Map&&e instanceof Map?Or(m,e):m instanceof Date&&e instanceof Date?m.getTime()===e.getTime():m instanceof RegExp&&e instanceof RegExp?m.toString()===e.toString():m!==m&&e!==e)},wr=(m,e,t=Ae)=>{let r=m.length;if(r===e.length)for(;r-- >0&&t(m[r],e[r]););return r<0},xr=(m,e,t=Ae)=>m.size===e.size&&t([...m.keys()].sort(),[...e.keys()].sort()),Or=(m,e,t=Ae)=>m.size===e.size&&t([...m].sort(),[...e].sort()),Br=(m,e,t=Ae)=>{if(Object.keys(m).length!==Object.keys(e).length)return!1;for(let r in m)if(!e.hasOwnProperty(r)||!t(m[r],e[r]))return!1;return!0};var Ht=(m,e)=>m!=null&&typeof m[e]=="function";var Ut=m=>Ht(m,"xform")?m.xform():m;var nt=Symbol(),xt=()=>{};var zt=m=>m!=null&&typeof m[Symbol.iterator]=="function";var ot=class{value;constructor(e){this.value=e}deref(){return this.value}};var at=m=>m instanceof ot;var Xt=m=>m instanceof ot?m.deref():m;function*Yt(m,e){let t=Ut(m)([xt,xt,(r,s)=>s])[2];for(let r of e){let s=t(nt,r);if(at(s)){s=Xt(s.deref()),s!==nt&&(yield s);return}s!==nt&&(yield s)}}var Wt=(m,e)=>[m[0],m[1],e];function Ue(m,e){return zt(e)?Yt(Ue(m),e):t=>{let r=t[2];return Wt(t,(s,i)=>r(s,m(i)))}}var Ne=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return $t("next",this._head)}reverseIterator(){return $t("prev",this.tail)}clear(){this.release()}compare(e,t=He){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,a=0;for(;r-- >0&&a===0;)a=t(s.value,i.value),s=s.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof Ne||Ct(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!Ae(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||He;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!at(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&yt(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*$t(m,e){for(;e;)yield e.value,e=e[m]}var de=class extends Ne{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new de(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new de}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(rt(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(rt(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new de,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=a=>({first(){return a.value},next(){return a!==s&&a.next?i(a.next):void 0}});return r?i(r):void 0}shuffle(e,t=Dt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&Lt("invalid indices: ${from} / ${to}");let i=new de,a=this.nthCell(r);for(;a&&++r<=s;)i.push(a.value),a=a.next;return i}sort(e=He){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,a=0;for(let u=0;u<t&&(a++,i=i.next,!!i);u++);let c=t;for(;a>0||c>0&&i;){let u;a===0?(u=i,i=i.next,c--):!i||c===0||e(r.value,i.value)<=0?(u=r,r=r.next,a--):(u=i,i=i.next,c--),this._tail?this._tail.next=u:this._head=u,u.prev=this._tail,this._tail=u}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),rt(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new de;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let a of r)this.insertBefore(s,a);else for(let a of r)this.push(a);return i}};var Fe=class{map;items;opts;_size;constructor(e,t){let r=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=r.map(),this.items=new de,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ue(e=>[e.k,e],this.items)}keys(){return Ue(e=>e.k,this.items)}values(){return Ue(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new Fe(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e);return this._size+=Math.max(0,r-(s?s.value.s:0)),this.ensureSize()&&this.doSetEntry(s,e,t,r),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let r=this.map.get(e);return r?Promise.resolve(this.resetEntry(r)):t().then(s=>this.set(e,s))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,r=this.opts.maxlen;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e&&e(s.k,s.v),this._size-=s.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,r,s){e?(e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var Ot=class extends qe{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Fe(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let r=[t.address,e].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let i=await super.getPoolFees(e,t);return this.feeCache.set(r,i),i}}async destroy(){console.log(`Destroying pool cache!
2
+ Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Oe=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Oe(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,i,a,c){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=c}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let c=this.calculateTradeFee(t,r),u=ue(this.repayFeeApply?r.repayFee:r.exchangeFee),y=t.plus(c),O=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return O.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:O,calculatedIn:O,amountOut:t,feePct:u,errors:i}}else{let c=this.calculateInGivenOut(e,t),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let c=this.calculateOutGivenIn(e,t),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),u=this.calculateTradeFee(c,r),y=ue(this.repayFeeApply?r.repayFee:r.exchangeFee),O=c.minus(u),B=e.balanceOut.div(this.maxOutRatio);return O.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:O,feePct:y,errors:i}}}calculateInGivenOut(e,t){let r=me.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?E:s}calculateOutGivenIn(e,t){let r=me.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?E:s}spotPriceInGivenOut(e){let t=me.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),J(le,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=me.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),J(le,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let r=me.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(r)}};import{calculate_in_given_out as vr,calculate_lrna_in_given_out as Ir,calculate_out_given_in as Ar,calculate_out_given_lrna_in as Nr,calculate_pool_trade_fee as Fr,calculate_spot_price as Tr,calculate_lrna_spot_price as _r,calculate_shares as Rr,calculate_liquidity_out as Er,calculate_liquidity_lrna_out as kr,verify_asset_cap as Lr,calculate_liquidity_hub_in as Mr,is_sell_allowed as Dr,is_buy_allowed as Cr,is_add_liquidity_allowed as Gr,is_remove_liquidity_allowed as qr}from"@galacticcouncil/math-omnipool";var X=class{static calculateSpotPrice(e,t,r,s){return Tr(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return _r(e,t)}static calculateInGivenOut(e,t,r,s,i,a,c,u,y){return vr(e,t,r,s,i,a,c,u,y)}static calculateLrnaInGivenOut(e,t,r,s,i){return Ir(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,a,c,u,y){return Ar(e,t,r,s,i,a,c,u,y)}static calculateOutGivenLrnaIn(e,t,r,s,i){return Nr(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return Fr(e,t,r)}static calculateShares(e,t,r,s){return Rr(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,a,c,u){return Er(e,t,r,s,i,a,c,u)}static calculateLiquidityLRNAOut(e,t,r,s,i,a,c,u){return kr(e,t,r,s,i,a,c,u)}static calculateCapDifference(e,t,r,s){let i=G(t),a=G(e),c=G(s),y=G(r).shiftedBy(-18);if(i.div(c).lt(y)){let B=y.times(c).minus(i).times(a),N=i.times(G(1).minus(y));return B.div(N).toFixed(0)}else return"0"}static verifyAssetCap(e,t,r,s){return Lr(e,t,r,s)}static calculateLimitHubIn(e,t,r,s){return Mr(e,t,r,s)}static isSellAllowed(e){return Dr(e)}static isBuyAllowed(e){return Cr(e)}static isAddLiquidityAllowed(e){return Gr(e)}static isRemoveLiquidityAllowed(e){return qr(e)}};var Be=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new Be(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,i,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,tradeableIn:s.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),c=s===E?E:a.div(s).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),O=X.isBuyAllowed(e.tradeableOut);(!y||!O)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&u.push("MaxOutRatioExceeded");let N=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(N)&&u.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:c.toNumber(),errors:u}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),c=s.minus(i).div(s).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),O=X.isBuyAllowed(e.tradeableOut);(!y||!O)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&u.push("MaxInRatioExceeded");let N=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(N)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:c.toNumber(),errors:u}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=X.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ee(r.assetFee).toString():E.toString(),r?ee(r.protocolFee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateLrnaInGivenOut(e,t,r){let s=X.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ee(r.assetFee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=X.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ee(r.assetFee).toString():E.toString(),r?ee(r.protocolFee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateOutGivenLrnaIn(e,t,r){let s=X.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?ee(r.assetFee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=X.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=X.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=X.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=X.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,r,s,i,a,c,u,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.amplification=a,this.id=c,this.fee=u,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?dt:s.tradeable,tradeableOut:this.id===t?dt:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=ue(r.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),a=ue(r.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,r){let s=te.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateAddOneAsset(e,t,r){let s=te.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateSharesForAmount(e,t,r){let s=te.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=J(le,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,r){let s=te.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateWithdrawOneAsset(e,t,r){let s=te.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateShares(e,t,r){let s=te.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?ee(r.fee).toString():E.toString()),i=I(s);return i.isNegative()?E:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=J(le,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let r=te.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(r)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{calculate_in_given_out as Hr,calculate_out_given_in as Ur,calculate_pool_trade_fee as zr,get_spot_price as Xr,calculate_liquidity_in as Yr,calculate_shares as Wr,calculate_spot_price as $r,calculate_spot_price_with_fee as jr,calculate_liquidity_out_asset_a as Jr,calculate_liquidity_out_asset_b as Zr}from"@galacticcouncil/math-xyk";var be=class{static getSpotPrice(e,t,r){return Xr(e,t,r)}static calculateInGivenOut(e,t,r){return Hr(e,t,r)}static calculateOutGivenIn(e,t,r){return Ur(e,t,r)}static calculatePoolTradeFee(e,t,r){return zr(e,t,r)}static calculateLiquidityIn(e,t,r){return Yr(e,t,r)}static calculateSpotPrice(e,t){return $r(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return jr(e,t,r,s)}static calculateShares(e,t,r){return Wr(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return Jr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Zr(e,t,r,s)}};var Ie=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Ie(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),a=ue(r.exchangeFee),c=s.plus(i),u=[];t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&u.push("MaxOutRatioExceeded");let O=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(O)&&u.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:s,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),a=ue(r.exchangeFee),c=s.minus(i),u=[];t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&u.push("MaxInRatioExceeded");let O=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(O)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:c,feePct:a,errors:u}}calculateInGivenOut(e,t){let r=be.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?E:s}calculateOutGivenIn(e,t){let r=be.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?E:s}spotPriceInGivenOut(e){let t=be.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=J(le,18-e.decimalsOut);return I(t).div(r)}spotPriceOutGivenIn(e){let t=be.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=J(le,18-e.decimalsIn);return I(t).div(r)}calculateTradeFee(e,t){let r=be.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(r)}};var ze=class{static get(e){switch(e.type){case"Xyk":return Ie.fromPool(e);case"Omnipool":return Be.fromPool(e);case"Lbp":return Oe.fromPool(e);case"Stableswap":return ve.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Te=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ee,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),a=this.getPaths(e,null,s,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(a)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,origin:s.origin,meta:s.meta}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(c=>this.validPath(c,r)).map(c=>this.toHops(c,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(r);return{assets:s,poolsMap:i}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,ze.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,i])=>{let a=t.get(r);return{poolAddress:r,poolId:a?.id,pool:a?.type,assetIn:s,assetOut:i}})}toAssets(e,t){return e.map(r=>t.get(r))}};function Fl(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Xe(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function jt(m,e){return le.minus(e.div(m)).multipliedBy(100).decimalPlaces(2)}function Jt(m,e){return e.div(m).minus(le).multipliedBy(100).decimalPlaces(2)}var lt=class extends Te{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,a=s[s.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[r,s]}}getPoolFeeRange(e){let t=e.min?ue(e.min):void 0,r=e.max?ue(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ge(e,t);let u;if(s)u=await this.toSellSwaps(r,s,a);else{let R=c.map(async n=>await this.toSellSwaps(r,n,a)),z=await Promise.all(R);u=this.findBestSellRoute(z)}let y=u[0],O=u[u.length-1],B=this.isDirectTrade(u),N=u.map(R=>R.spotPrice.shiftedBy(-1*R.assetOutDecimals)).reduce((R,z)=>R.multipliedBy(z)),_=J(N,O.assetOutDecimals),T=B?O.calculatedOut:this.calculateDelta0Y(y.amountIn,u,a),D=O.amountOut,L=B?O.tradeFeePct:jt(T,D).toNumber(),Y=T.minus(D),w=this.getRouteFeeRange(u),j=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(_),re=Xe(T,j),fe=R=>this.poolService.buildSellTx(e,t,y.amountIn,R,u.map(z=>z));return{type:"Sell",amountIn:y.amountIn,amountOut:O.amountOut,spotPrice:_,tradeFee:Y,tradeFeePct:L,tradeFeeRange:w,priceImpactPct:re.toNumber(),swaps:u,toTx:fe,toHuman(){return{type:"Sell",amountIn:Z(y.amountIn,y.assetInDecimals),amountOut:Z(O.amountOut,O.assetOutDecimals),spotPrice:Z(_,O.assetOutDecimals),tradeFee:Z(Y,O.assetOutDecimals),tradeFeePct:L,tradeFeeRange:w,priceImpactPct:re.toNumber(),swaps:u.map(R=>R.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=s[i-1]:y=e;let O=c.calculateOutGivenIn(u,y);s.push(O)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=s[i-1].amountOut:y=J(I(e),u.decimalsIn).decimalPlaces(0,1);let O=await this.poolService.getPoolFees(u.assetOut,c),{amountOut:B,calculatedOut:N,feePct:_,errors:T}=c.validateAndSell(u,y,O),D=this.getPoolFeeRange(O),L=c.spotPriceOutGivenIn(u),Y=y.shiftedBy(-1*u.decimalsIn).multipliedBy(L),w=Xe(N,Y);s.push({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountIn:y,calculatedOut:N,amountOut:B,spotPrice:L,tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w.toNumber(),errors:T,toHuman(){return{...a,amountIn:Z(y,u.decimalsIn),calculatedOut:Z(N,u.decimalsOut),amountOut:Z(B,u.decimalsOut),spotPrice:Z(L,u.decimalsOut),tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w.toNumber(),errors:T}}})}return s}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r),i=super.getPaths(e,t,s,r);if(i.length===0)return Promise.resolve(void 0);let a=r.map(w=>w.tokens.find(j=>j.id===e)).filter(w=>!!w).sort((w,j)=>Number(j.balance)-Number(w.balance)),{balance:c,decimals:u}=a[0],O=I(c).shiftedBy(-1*u).div(100).multipliedBy(.1),B=i.map(async w=>await this.toSellSwaps(O,w,s)),N=await Promise.all(B),_=this.findBestSellRoute(N),T=await this.toSellSwaps("1",_,s),D=T.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,j)=>w.multipliedBy(j)),L=T[T.length-1].assetOutDecimals;return{amount:J(D,L),decimals:L}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,a=s[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ge(e,t);let u;if(s)u=await this.toBuySwaps(r,s,a);else{let R=c.map(async n=>await this.toBuySwaps(r,n,a)),z=await Promise.all(R);u=this.findBestBuyRoute(z)}let y=u[u.length-1],O=u[0],B=this.isDirectTrade(u),N=u.map(R=>R.spotPrice.shiftedBy(-1*R.assetInDecimals)).reduce((R,z)=>R.multipliedBy(z)),_=J(N,O.assetInDecimals),T=B?O.calculatedIn:this.calculateDelta0X(y.amountOut,u,a),D=O.amountIn,L=B?O.tradeFeePct:Jt(T,D).toNumber(),Y=D.minus(T),w=this.getRouteFeeRange(u),j=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(_),re;T.isZero()?re=-100:re=Xe(j,T).toNumber();let fe=R=>this.poolService.buildBuyTx(e,t,y.amountOut,R,u.map(z=>z));return{type:"Buy",amountOut:y.amountOut,amountIn:O.amountIn,spotPrice:_,tradeFee:Y,tradeFeePct:L,tradeFeeRange:w,priceImpactPct:re,swaps:u,toTx:fe,toHuman(){return{type:"Buy",amountOut:Z(y.amountOut,y.assetOutDecimals),amountIn:Z(O.amountIn,O.assetInDecimals),spotPrice:Z(_,O.assetInDecimals),tradeFee:Z(Y,O.assetInDecimals),tradeFeePct:L,tradeFeeRange:w,priceImpactPct:re,swaps:u.map(R=>R.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=s[0];let O=c.calculateInGivenOut(u,y);s.unshift(O)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=r.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=J(I(e),u.decimalsOut).decimalPlaces(0,1):y=s[0].amountIn;let O=await this.poolService.getPoolFees(u.assetOut,c),{amountIn:B,calculatedIn:N,feePct:_,errors:T}=c.validateAndBuy(u,y,O),D=this.getPoolFeeRange(O),L=c.spotPriceInGivenOut(u),Y=y.shiftedBy(-1*u.decimalsOut).multipliedBy(L),w;N.isZero()?w=-100:w=Xe(Y,N).toNumber(),s.unshift({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountOut:y,calculatedIn:N,amountIn:B,spotPrice:L,tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w,errors:T,toHuman(){return{...a,amountOut:Z(y,u.decimalsOut),calculatedIn:Z(N,u.decimalsIn),amountIn:Z(B,u.decimalsIn),spotPrice:Z(L,u.decimalsIn),tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w,errors:T}}})}return s}};export{De as AssetClient,_t as AssetNotFound,Bs as BASILISK_PARACHAIN_ID,Ce as BalanceClient,G as BigNumber,Ot as CachingPoolService,Qt as DECIMAL_PLACES,ft as DENOMINATOR,Pt as FarmClient,Je as HYDRADX_OMNIPOOL_ADDRESS,Os as HYDRADX_PARACHAIN_ID,Me as HYDRADX_SS58_PREFIX,ds as INFINITY,me as LbpMath,Oe as LbpPool,le as ONE,X as OmniMath,Be as OmniPool,Tt as PoolConfigNotFound,ke as PoolError,ze as PoolFactory,et as PoolNotFound,qe as PoolService,se as PoolType,kt as ProviderConfigNotFound,Le as RUNTIME_DECIMALS,Ge as RouteNotFound,Te as Router,xs as SYSTEM_ASSET_DECIMALS,Se as SYSTEM_ASSET_ID,te as StableMath,ve as StableSwap,Rt as StorageConfigNotFound,Et as SubscriptionNotSupported,dt as TRADEABLE_DEFAULT,lt as TradeRouter,It as TradeType,be as XykMath,Ie as XykPool,E as ZERO,I as bnum,bt as buildRoute,Jt as calculateBuyFee,Fl as calculateDiffToAvg,Xe as calculateDiffToRef,jt as calculateSellFee,At as findNestedKey,Is as findNestedObj,J as scale};
@@ -137,3 +137,7 @@ export interface AssetMetadata {
137
137
  decimals: number;
138
138
  symbol: string;
139
139
  }
140
+ export interface Bond extends Asset {
141
+ underlyingAssetId: string;
142
+ maturity: number;
143
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk",
3
- "version": "3.1.0",
3
+ "version": "3.1.1",
4
4
  "description": "Galactic off-chain routing & optimization of orders across pools for best price execution",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {