@galacticcouncil/sdk 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.cjs +2 -2
- package/build/index.mjs +2 -2
- package/build/types/pool/PoolService.d.ts +2 -0
- package/package.json +1 -1
package/build/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var yt=Object.defineProperty;var is=Object.getOwnPropertyDescriptor;var ns=Object.getOwnPropertyNames;var os=Object.prototype.hasOwnProperty;var as=(u,e)=>{for(var t in e)yt(u,t,{get:e[t],enumerable:!0})},ls=(u,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ns(e))!os.call(u,r)&&r!==t&&yt(u,r,{get:()=>e[r],enumerable:!(s=is(e,r))||s.enumerable});return u};var us=u=>ls(yt({},"__esModule",{value:!0}),u);var Bs={};as(Bs,{AssetClient:()=>Le,AssetNotFound:()=>Nt,BASILISK_PARACHAIN_ID:()=>ds,BalanceClient:()=>Me,BigNumber:()=>fe,CachingPoolService:()=>Pt,DECIMAL_PLACES:()=>qt,DENOMINATOR:()=>rt,HYDRADX_OMNIPOOL_ADDRESS:()=>$e,HYDRADX_PARACHAIN_ID:()=>gs,HYDRADX_SS58_PREFIX:()=>Re,INFINITY:()=>ms,LbpMath:()=>pe,LbpPool:()=>Be,ONE:()=>ne,OmniMath:()=>z,OmniPool:()=>ve,PoolConfigNotFound:()=>At,PoolError:()=>_e,PoolFactory:()=>Ue,PoolNotFound:()=>Je,PoolService:()=>Ce,PoolType:()=>re,ProviderConfigNotFound:()=>_t,RUNTIME_DECIMALS:()=>Ee,RouteNotFound:()=>De,Router:()=>Fe,SYSTEM_ASSET_DECIMALS:()=>hs,SYSTEM_ASSET_ID:()=>Oe,StableMath:()=>te,StableSwap:()=>Ie,StorageConfigNotFound:()=>Tt,SubscriptionNotSupported:()=>Ft,TRADEABLE_DEFAULT:()=>st,TradeRouter:()=>Qe,TradeType:()=>vt,XykMath:()=>ye,XykPool:()=>Ae,ZERO:()=>k,bnum:()=>I,buildRoute:()=>ut,calculateBuyFee:()=>Dt,calculateDiffToAvg:()=>ws,calculateDiffToRef:()=>ze,calculateSellFee:()=>Mt,findNestedKey:()=>It,findNestedObj:()=>fs,scale:()=>$});module.exports=us(Bs);var Ze=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var cs=5,We=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new Ze,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>cs)return r;let p=c[c.length-1];(s===null||p[0]===s)&&r.push(c),e.get(p[0])?.forEach(w=>{if(this.isNotVisited(w,c)){let B=[...c];B.push(w),i.enqueue(B)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,a]of t){let c=parseInt(i),p=parseInt(a);s.get(c)?.push([p,r])}return s}};function xt(u){let e={};for(let t of u){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let i=0;i<s;i++){if(r==i)continue;let a=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(a)}}}return e}var Ye=class{getProposals(e,t,s){let r=xt(s),i=Object.keys(r),a=i.map(w=>r[w]).flat(),c=new We,p=c.buildAndPopulateGraph(i,a),y=c.findPaths(p,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let a=s[i],c=s[i+1];if(c==null)break;r.push(this.toEdge(a,c))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ps=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ot=Math.ceil,ue=Math.floor,se="[BigNumber Error] ",Ct=se+"Number primitive has more than 15 significant digits: ",he=1e14,N=14,wt=9007199254740991,Bt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],we=1e7,Y=1e9;function Gt(u){var e,t,s,r=x.prototype={constructor:x,toString:null,valueOf:null},i=new x(1),a=20,c=4,p=-7,y=21,w=-1e7,B=1e7,F=!1,L=1,T=0,G={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},D="0123456789abcdefghijklmnopqrstuvwxyz",K=!0;function x(n,o){var l,P,h,d,S,m,g,b,f=this;if(!(f instanceof x))return new x(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<w?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((m=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!ps.test(b=String(n)))return s(f,b,m);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,D.length,"Base"),o==10&&K)return f=new x(n),_(f,a+f.e+1,c);if(b=String(n),m=typeof n=="number"){if(n*0!=0)return s(f,b,m,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Ct+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=D.slice(0,o),d=S=0,g=b.length;S<g;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=g;continue}}else if(!h&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){h=!0,S=-1,d=0;continue}return s(f,String(n),m,o)}m=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(g=b.length;b.charCodeAt(--g)===48;);if(b=b.slice(S,++g)){if(g-=S,m&&x.DEBUG&&g>15&&(n>wt||n!==ue(n)))throw Error(Ct+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<w)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%N,d<0&&(S+=N),S<g){for(S&&f.c.push(+b.slice(0,S)),g-=N;S<g;)f.c.push(+b.slice(S,S+=N));S=N-(b=b.slice(S)).length}else S-=g;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}x.clone=Gt,x.ROUND_UP=0,x.ROUND_DOWN=1,x.ROUND_CEIL=2,x.ROUND_FLOOR=3,x.ROUND_HALF_UP=4,x.ROUND_HALF_DOWN=5,x.ROUND_HALF_EVEN=6,x.ROUND_HALF_CEIL=7,x.ROUND_HALF_FLOOR=8,x.EUCLID=9,x.config=x.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],q(l,0,Y,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],q(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(q(l[0],-Y,0,o),q(l[1],0,Y,o),p=l[0],y=l[1]):(q(l,-Y,Y,o),p=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)q(l[0],-Y,-1,o),q(l[1],1,Y,o),w=l[0],B=l[1];else if(q(l,-Y,Y,o),l)w=-(B=l<0?-l:l);else throw Error(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],q(l,0,9,o),L=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],q(l,0,Y,o),T=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")G=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))K=l.slice(0,10)=="0123456789",D=l;else throw Error(se+o+" invalid: "+l)}else throw Error(se+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[p,y],RANGE:[w,B],CRYPTO:F,MODULO_MODE:L,POW_PRECISION:T,FORMAT:G,ALPHABET:D}},x.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!x.DEBUG)return!0;var o,l,P=n.c,h=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&h>=-Y&&h<=Y&&h===ue(h)){if(P[0]===0){if(h===0&&P.length===1)return!0;break e}if(o=(h+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!==ue(l))break e;if(l!==0)return!0}}}else if(P===null&&h===null&&(d===null||d===1||d===-1))return!0;throw Error(se+"Invalid BigNumber: "+n)},x.maximum=x.max=function(){return oe(arguments,-1)},x.minimum=x.min=function(){return oe(arguments,1)},x.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ue(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,h,d,S,m,g=0,b=[],f=new x(i);if(l==null?l=a:q(l,0,Y),S=Ot(l/N),F)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));g<S;)m=P[g]*131072+(P[g+1]>>>11),m>=9e15?(h=crypto.getRandomValues(new Uint32Array(2)),P[g]=h[0],P[g+1]=h[1]):(b.push(m%1e14),g+=2);g=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);g<S;)m=(P[g]&31)*281474976710656+P[g+1]*1099511627776+P[g+2]*4294967296+P[g+3]*16777216+(P[g+4]<<16)+(P[g+5]<<8)+P[g+6],m>=9e15?crypto.randomBytes(7).copy(P,g):(b.push(m%1e14),g+=7);g=S/7}else throw F=!1,Error(se+"crypto unavailable");if(!F)for(;g<S;)m=o(),m<9e15&&(b[g++]=m%1e14);for(S=b[--g],l%=N,S&&l&&(m=Bt[N-l],b[g]=ue(S/m)*m);b[g]===0;b.pop(),g--);if(g<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=N);for(g=1,m=b[0];m>=10;m/=10,g++);g<N&&(d-=N-g)}return f.e=d,f.c=b,f}}(),x.sum=function(){for(var n=1,o=arguments,l=new x(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,h,d){for(var S,m=[0],g,b=0,f=l.length;b<f;){for(g=m.length;g--;m[g]*=P);for(m[0]+=d.indexOf(l.charAt(b++)),S=0;S<m.length;S++)m[S]>h-1&&(m[S+1]==null&&(m[S+1]=0),m[S+1]+=m[S]/h|0,m[S]%=h)}return m.reverse()}return function(l,P,h,d,S){var m,g,b,f,O,v,A,M,H=l.indexOf("."),W=a,R=c;for(H>=0&&(f=T,T=0,l=l.replace(".",""),M=new x(P),v=M.pow(l.length-H),T=f,M.c=o(xe(le(v.c),v.e,"0"),10,h,n),M.e=M.c.length),A=o(l,P,h,S?(m=D,n):(m=n,D)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return m.charAt(0);if(H<0?--b:(v.c=A,v.e=b,v.s=d,v=e(v,M,W,R,h),A=v.c,O=v.r,b=v.e),g=b+W+1,H=A[g],f=h/2,O=O||g<0||A[g+1]!=null,O=R<4?(H!=null||O)&&(R==0||R==(v.s<0?3:2)):H>f||H==f&&(R==4||O||R==6&&A[g-1]&1||R==(v.s<0?8:7)),g<1||!A[0])l=O?xe(m.charAt(1),-W,m.charAt(0)):m.charAt(0);else{if(A.length=g,O)for(--h;++A[--g]>h;)A[g]=0,g||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(H=0,l="";H<=f;l+=m.charAt(A[H++]));l=xe(l,b,m.charAt(0))}return l}}(),e=function(){function n(P,h,d){var S,m,g,b,f=0,O=P.length,v=h%we,A=h/we|0;for(P=P.slice();O--;)g=P[O]%we,b=P[O]/we|0,S=A*g+b*v,m=v*g+S%we*we+f,f=(m/d|0)+(S/we|0)+A*b,P[O]=m%d;return f&&(P=[f].concat(P)),P}function o(P,h,d,S){var m,g;if(d!=S)g=d>S?1:-1;else for(m=g=0;m<d;m++)if(P[m]!=h[m]){g=P[m]>h[m]?1:-1;break}return g}function l(P,h,d,S){for(var m=0;d--;)P[d]-=m,m=P[d]<h[d]?1:0,P[d]=m*S+P[d]-h[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,h,d,S,m){var g,b,f,O,v,A,M,H,W,R,C,Q,Ve,bt,St,de,Xe,ae=P.s==h.s?1:-1,ee=P.c,U=h.c;if(!ee||!ee[0]||!U||!U[0])return new x(!P.s||!h.s||(ee?U&&ee[0]==U[0]:!U)?NaN:ee&&ee[0]==0||!U?ae*0:ae/0);for(H=new x(ae),W=H.c=[],b=P.e-h.e,ae=d+b+1,m||(m=he,b=ce(P.e/N)-ce(h.e/N),ae=ae/N|0),f=0;U[f]==(ee[f]||0);f++);if(U[f]>(ee[f]||0)&&b--,ae<0)W.push(1),O=!0;else{for(bt=ee.length,de=U.length,f=0,ae+=2,v=ue(m/(U[0]+1)),v>1&&(U=n(U,v,m),ee=n(ee,v,m),de=U.length,bt=ee.length),Ve=de,R=ee.slice(0,de),C=R.length;C<de;R[C++]=0);Xe=U.slice(),Xe=[0].concat(Xe),St=U[0],U[1]>=m/2&&St++;do{if(v=0,g=o(U,R,de,C),g<0){if(Q=R[0],de!=C&&(Q=Q*m+(R[1]||0)),v=ue(Q/St),v>1)for(v>=m&&(v=m-1),A=n(U,v,m),M=A.length,C=R.length;o(A,R,M,C)==1;)v--,l(A,de<M?Xe:U,M,m),M=A.length,g=1;else v==0&&(g=v=1),A=U.slice(),M=A.length;if(M<C&&(A=[0].concat(A)),l(R,A,C,m),C=R.length,g==-1)for(;o(U,R,de,C)<1;)v++,l(R,de<C?Xe:U,C,m),C=R.length}else g===0&&(v++,R=[0]);W[f++]=v,R[0]?R[C++]=ee[Ve]||0:(R=[ee[Ve]],C=1)}while((Ve++<bt||R[0]!=null)&&ae--);O=R[0]!=null,W[0]||W.splice(0,1)}if(m==he){for(f=1,ae=W[0];ae>=10;ae/=10,f++);_(H,d+(H.e=f+b*N-1)+1,S,O)}else H.e=b,H.r=+O;return H}}();function Z(n,o,l,P){var h,d,S,m,g;if(l==null?l=c:q(l,0,8),!n.c)return n.toString();if(h=n.c[0],S=n.e,o==null)g=le(n.c),g=P==1||P==2&&(S<=p||S>=y)?tt(g,S):xe(g,S,"0");else if(n=_(new x(n),o,l),d=n.e,g=le(n.c),m=g.length,P==1||P==2&&(o<=d||d<=p)){for(;m<o;g+="0",m++);g=tt(g,d)}else if(o-=S,g=xe(g,d,"0"),d+1>m){if(--o>0)for(g+=".";o--;g+="0");}else if(o+=d-m,o>0)for(d+1==m&&(g+=".");o--;g+="0");return n.s<0&&h?"-"+g:g}function oe(n,o){for(var l,P,h=1,d=new x(n[0]);h<n.length;h++)P=new x(n[h]),(!P.s||(l=Te(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function Ne(n,o,l){for(var P=1,h=o.length;!o[--h];o.pop());for(h=o[0];h>=10;h/=10,P++);return(l=P+l*N-1)>B?n.c=n.e=null:l<w?n.c=[n.e=0]:(n.e=l,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,h=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,m,g){var b,f=m?S:S.replace(h,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!m&&(f=f.replace(n,function(O,v,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!g||g==b?v:O}),g&&(b=g,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new x(f,b);if(x.DEBUG)throw Error(se+"Not a"+(g?" base "+g:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function _(n,o,l,P){var h,d,S,m,g,b,f,O=n.c,v=Bt;if(O){e:{for(h=1,m=O[0];m>=10;m/=10,h++);if(d=o-h,d<0)d+=N,S=o,g=O[b=0],f=ue(g/v[h-S-1]%10);else if(b=Ot((d+1)/N),b>=O.length)if(P){for(;O.length<=b;O.push(0));g=f=0,h=1,d%=N,S=d-N+1}else break e;else{for(g=m=O[b],h=1;m>=10;m/=10,h++);d%=N,S=d-N+h,f=S<0?0:ue(g/v[h-S-1]%10)}if(P=P||o<0||O[b+1]!=null||(S<0?g:g%v[h-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?g/v[h-S]:0:O[b-1])%10&1||l==(n.s<0?8:7)),o<1||!O[0])return O.length=0,P?(o-=n.e+1,O[0]=v[(N-o%N)%N],n.e=-o||0):O[0]=n.e=0,n;if(d==0?(O.length=b,m=1,b--):(O.length=b+1,m=v[N-d],O[b]=S>0?ue(g/v[h-S]%v[S])*m:0),P)for(;;)if(b==0){for(d=1,S=O[0];S>=10;S/=10,d++);for(S=O[0]+=m,m=1;S>=10;S/=10,m++);d!=m&&(n.e++,O[0]==he&&(O[0]=1));break}else{if(O[b]+=m,O[b]!=he)break;O[b--]=0,m=1}for(d=O.length;O[--d]===0;O.pop());}n.e>B?n.c=n.e=null:n.e<w&&(n.c=[n.e=0])}return n}function X(n){var o,l=n.e;return l===null?n.toString():(o=le(n.c),o=l<=p||l>=y?tt(o,l):xe(o,l,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new x(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return Te(this,new x(n,o))},r.decimalPlaces=r.dp=function(n,o){var l,P,h,d=this;if(n!=null)return q(n,0,Y),o==null?o=c:q(o,0,8),_(new x(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((h=l.length-1)-ce(this.e/N))*N,h=l[h])for(;h%10==0;h/=10,P--);return P<0&&(P=0),P},r.dividedBy=r.div=function(n,o){return e(this,new x(n,o),a,c)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new x(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var l,P,h,d,S,m,g,b,f,O=this;if(n=new x(n),n.c&&!n.isInteger())throw Error(se+"Exponent not an integer: "+X(n));if(o!=null&&(o=new x(o)),m=n.e>14,!O.c||!O.c[0]||O.c[0]==1&&!O.e&&O.c.length==1||!n.c||!n.c[0])return f=new x(Math.pow(+X(O),m?n.s*(2-et(n)):+X(n))),o?f.mod(o):f;if(g=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new x(NaN);P=!g&&O.isInteger()&&o.isInteger(),P&&(O=O.mod(o))}else{if(n.e>9&&(O.e>0||O.e<-1||(O.e==0?O.c[0]>1||m&&O.c[1]>=24e7:O.c[0]<8e13||m&&O.c[0]<=9999975e7)))return d=O.s<0&&et(n)?-0:0,O.e>-1&&(d=1/d),new x(g?1/d:d);T&&(d=Ot(T/N+2))}for(m?(l=new x(.5),g&&(n.s=1),b=et(n)):(h=Math.abs(+X(n)),b=h%2),f=new x(i);;){if(b){if(f=f.times(O),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(h){if(h=ue(h/2),h===0)break;b=h%2}else if(n=n.times(l),_(n,n.e+1,1),n.e>14)b=et(n);else{if(h=+X(n),h===0)break;b=h%2}O=O.times(O),d?O.c&&O.c.length>d&&(O.c.length=d):P&&(O=O.mod(o))}return P?f:(g&&(f=i.div(f)),o?f.mod(o):d?_(f,T,c,S):f)},r.integerValue=function(n){var o=new x(this);return n==null?n=c:q(n,0,8),_(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return Te(this,new x(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return Te(this,new x(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=Te(this,new x(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&ce(this.e/N)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return Te(this,new x(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=Te(this,new x(n,o)))===-1||o===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(n,o){var l,P,h,d,S=this,m=S.s;if(n=new x(n,o),o=n.s,!m||!o)return new x(NaN);if(m!=o)return n.s=-o,S.plus(n);var g=S.e/N,b=n.e/N,f=S.c,O=n.c;if(!g||!b){if(!f||!O)return f?(n.s=-o,n):new x(O?S:NaN);if(!f[0]||!O[0])return O[0]?(n.s=-o,n):new x(f[0]?S:c==3?-0:0)}if(g=ce(g),b=ce(b),f=f.slice(),m=g-b){for((d=m<0)?(m=-m,h=f):(b=g,h=O),h.reverse(),o=m;o--;h.push(0));h.reverse()}else for(P=(d=(m=f.length)<(o=O.length))?m:o,m=o=0;o<P;o++)if(f[o]!=O[o]){d=f[o]<O[o];break}if(d&&(h=f,f=O,O=h,n.s=-n.s),o=(P=O.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=he-1;P>m;){if(f[--P]<O[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=he}f[P]-=O[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?Ne(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var l,P,h=this;return n=new x(n,o),!h.c||!n.s||n.c&&!n.c[0]?new x(NaN):!n.c||h.c&&!h.c[0]?new x(h):(L==9?(P=n.s,n.s=1,l=e(h,n,0,3),n.s=P,l.s*=P):l=e(h,n,0,L),n=h.minus(l.times(n)),!n.c[0]&&L==1&&(n.s=h.s),n)},r.multipliedBy=r.times=function(n,o){var l,P,h,d,S,m,g,b,f,O,v,A,M,H,W,R=this,C=R.c,Q=(n=new x(n,o)).c;if(!C||!Q||!C[0]||!Q[0])return!R.s||!n.s||C&&!C[0]&&!Q||Q&&!Q[0]&&!C?n.c=n.e=n.s=null:(n.s*=R.s,!C||!Q?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=ce(R.e/N)+ce(n.e/N),n.s*=R.s,g=C.length,O=Q.length,g<O&&(M=C,C=Q,Q=M,h=g,g=O,O=h),h=g+O,M=[];h--;M.push(0));for(H=he,W=we,h=O;--h>=0;){for(l=0,v=Q[h]%W,A=Q[h]/W|0,S=g,d=h+S;d>h;)b=C[--S]%W,f=C[S]/W|0,m=A*b+f*v,b=v*b+m%W*W+M[d]+l,l=(b/H|0)+(m/W|0)+A*f,M[d--]=b%H;M[d]=l}return l?++P:M.splice(0,1),Ne(n,M,P)},r.negated=function(){var n=new x(this);return n.s=-n.s||null,n},r.plus=function(n,o){var l,P=this,h=P.s;if(n=new x(n,o),o=n.s,!h||!o)return new x(NaN);if(h!=o)return n.s=-o,P.minus(n);var d=P.e/N,S=n.e/N,m=P.c,g=n.c;if(!d||!S){if(!m||!g)return new x(h/0);if(!m[0]||!g[0])return g[0]?n:new x(m[0]?P:h*0)}if(d=ce(d),S=ce(S),m=m.slice(),h=d-S){for(h>0?(S=d,l=g):(h=-h,l=m),l.reverse();h--;l.push(0));l.reverse()}for(h=m.length,o=g.length,h-o<0&&(l=g,g=m,m=l,o=h),h=0;o;)h=(m[--o]=m[o]+g[o]+h)/he|0,m[o]=he===m[o]?0:m[o]%he;return h&&(m=[h].concat(m),++S),Ne(n,m,S)},r.precision=r.sd=function(n,o){var l,P,h,d=this;if(n!=null&&n!==!!n)return q(n,1,Y),o==null?o=c:q(o,0,8),_(new x(d),n,o);if(!(l=d.c))return null;if(h=l.length-1,P=h*N+1,h=l[h]){for(;h%10==0;h/=10,P--);for(h=l[0];h>=10;h/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return q(n,-wt,wt),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,l,P,h,d=this,S=d.c,m=d.s,g=d.e,b=a+4,f=new x("0.5");if(m!==1||!S||!S[0])return new x(!m||m<0&&(!S||S[0])?NaN:S?d:1/0);if(m=Math.sqrt(+X(d)),m==0||m==1/0?(o=le(S),(o.length+g)%2==0&&(o+="0"),m=Math.sqrt(+o),g=ce((g+1)/2)-(g<0||g%2),m==1/0?o="5e"+g:(o=m.toExponential(),o=o.slice(0,o.indexOf("e")+1)+g),l=new x(o)):l=new x(m+""),l.c[0]){for(g=l.e,m=g+b,m<3&&(m=0);;)if(h=l,l=f.times(h.plus(e(d,h,b,1))),le(h.c).slice(0,m)===(o=le(l.c)).slice(0,m))if(l.e<g&&--m,o=o.slice(m-3,m+1),o=="9999"||!P&&o=="4999"){if(!P&&(_(h,h.e+a+2,0),h.times(h).eq(d))){l=h;break}b+=4,m+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(_(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return _(l,l.e+a+1,c,n)},r.toExponential=function(n,o){return n!=null&&(q(n,0,Y),n++),Z(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(q(n,0,Y),n=n+this.e+1),Z(this,n,o)},r.toFormat=function(n,o,l){var P,h=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=G;else if(typeof l!="object")throw Error(se+"Argument not an object: "+l);if(P=h.toFixed(n,o),h.c){var d,S=P.split("."),m=+l.groupSize,g=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],O=S[1],v=h.s<0,A=v?f.slice(1):f,M=A.length;if(g&&(d=m,m=g,g=d,M-=d),m>0&&M>0){for(d=M%m||m,f=A.substr(0,d);d<M;d+=m)f+=b+A.substr(d,m);g>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=O?f+(l.decimalSeparator||"")+((g=+l.fractionGroupSize)?O.replace(new RegExp("\\d{"+g+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):O):f}return(l.prefix||"")+P+(l.suffix||"")},r.toFraction=function(n){var o,l,P,h,d,S,m,g,b,f,O,v,A=this,M=A.c;if(n!=null&&(m=new x(n),!m.isInteger()&&(m.c||m.s!==1)||m.lt(i)))throw Error(se+"Argument "+(m.isInteger()?"out of range: ":"not an integer: ")+X(m));if(!M)return new x(A);for(o=new x(i),b=l=new x(i),P=g=new x(i),v=le(M),d=o.e=v.length-A.e-1,o.c[0]=Bt[(S=d%N)<0?N+S:S],n=!n||m.comparedTo(o)>0?d>0?o:b:m,S=B,B=1/0,m=new x(v),g.c[0]=0;f=e(m,o,0,1),h=l.plus(f.times(P)),h.comparedTo(n)!=1;)l=P,P=h,b=g.plus(f.times(h=b)),g=h,o=m.minus(f.times(h=o)),m=h;return h=e(n.minus(l),P,0,1),g=g.plus(h.times(b)),l=l.plus(h.times(P)),g.s=b.s=A.s,d=d*2,O=e(b,P,d,c).minus(A).abs().comparedTo(e(g,l,d,c).minus(A).abs())<1?[b,P]:[g,l],B=S,O},r.toNumber=function(){return+X(this)},r.toPrecision=function(n,o){return n!=null&&q(n,1,Y),Z(this,n,o,2)},r.toString=function(n){var o,l=this,P=l.s,h=l.e;return h===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=h<=p||h>=y?tt(le(l.c),h):xe(le(l.c),h,"0"):n===10&&K?(l=_(new x(l),a+h+1,c),o=xe(le(l.c),l.e,"0")):(q(n,2,D.length,"Base"),o=t(xe(le(l.c),h,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return X(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,u!=null&&x.set(u),x}function ce(u){var e=u|0;return u>0||u===e?e:e-1}function le(u){for(var e,t,s=1,r=u.length,i=u[0]+"";s<r;){for(e=u[s++]+"",t=N-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function Te(u,e){var t,s,r=u.c,i=e.c,a=u.s,c=e.s,p=u.e,y=e.e;if(!a||!c)return null;if(t=r&&!r[0],s=i&&!i[0],t||s)return t?s?0:-c:a;if(a!=c)return a;if(t=a<0,s=p==y,!r||!i)return s?0:!r^t?1:-1;if(!s)return p>y^t?1:-1;for(c=(p=r.length)<(y=i.length)?p:y,a=0;a<c;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return p==y?0:p>y^t?1:-1}function q(u,e,t,s){if(u<e||u>t||u!==ue(u))throw Error(se+(s||"Argument")+(typeof u=="number"?u<e||u>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(u))}function et(u){var e=u.c.length-1;return ce(u.e/N)==e&&u.c[e]%2!=0}function tt(u,e){return(u.length>1?u.charAt(0)+"."+u.slice(1):u)+(e<0?"e":"e+")+e}function xe(u,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);u=r+u}else if(s=u.length,++e>s){for(r=t,e-=s;--e;r+=t);u+=r}else e<s&&(u=u.slice(0,e)+"."+u.slice(e));return u}var fe=Gt();var qt=12;fe.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:qt});var k=I(0),ne=I(1),ms=I("Infinity");function $(u,e){let t=new fe(e.toString()),s=new fe(10).pow(t);return u.times(s)}function I(u){return new fe(u.toString())}var re=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(re||{}),_e=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(_e||{}),vt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(vt||{});var Pe=require("@galacticcouncil/math-lbp"),pe=class{static getSpotPrice(e,t,s,r,i){return(0,Pe.get_spot_price)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return(0,Pe.calculate_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return(0,Pe.calculate_out_given_in)(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return(0,Pe.calculate_linear_weights)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,Pe.calculate_pool_trade_fee)(e,t,s)}};var Ht=require("@polkadot/util-crypto"),Ut=require("@polkadot/util"),Ee=18,st=15,Oe="0",hs=12,gs=2034,Re=63,ds=2090,rt=1e3,$e=(0,Ht.encodeAddress)((0,Ut.stringToU8a)("modlomnipool".padEnd(32,"\0")),Re);function It(u,e){let t;return JSON.stringify(u,(s,r)=>(r&&r[e]&&(t=r),r)),t}function fs(u,e,t){let s;return JSON.stringify(u,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}var js=require("@polkadot/types/lookup");var Ks=require("@polkadot/api-base/types/consts");var Qs=require("@polkadot/api-base/types/errors");var Vs=require("@polkadot/api-base/types/events");var Zs=require("@polkadot/api-base/types/storage");var er=require("@polkadot/api-base/types/submittable");var tr=require("@polkadot/rpc-core/types/jsonrpc");var sr=require("@polkadot/api-base/types/calls");var cr=require("@polkadot/types/types/registry");var gr=require("@polkadot/types/lookup");var dr=require("@polkadot/api-base/types/consts");var fr=require("@polkadot/api-base/types/errors");var Pr=require("@polkadot/api-base/types/events");var br=require("@polkadot/api-base/types/storage");var Sr=require("@polkadot/api-base/types/submittable");var yr=require("@polkadot/rpc-core/types/jsonrpc");var xr=require("@polkadot/api-base/types/calls");var Tr=require("@polkadot/types/types/registry");var ke=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Le=class extends ke{SUPPORTED_TYPES=["StableSwap","Bond","Token","External"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getToken(e,t,s,r){if(e==Oe){let B=this.api.consts.balances.existentialDeposit;return{id:Oe,name:this.chainToken,symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:B.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:p}=t,{symbol:y,decimals:w}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:y,decimals:w,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:this.parseLocation("parachain",r),existentialDeposit:p.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:c,isSufficient:p,existentialDeposit:y}=t,{symbol:w,decimals:B}=this.getToken(i.toString(),t,s),F=a.toNumber(),L=new Intl.DateTimeFormat("en-GB"),T=[w,"Bond",L.format(F)].join(" ");return{id:e,name:T,symbol:w+"b",decimals:B,icon:w,type:c.toString(),isSufficient:p.toHuman(),existentialDeposit:y.toString()}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:c,assetType:p,isSufficient:y,existentialDeposit:w}=t,F=i.map(G=>G.toString()).map(G=>{let{symbol:D}=this.getToken(G,t,s);return[G,D]}),L=Object.fromEntries(F),T=Object.values(L);return{id:e,name:T.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:T.join("/"),type:p.toString(),isSufficient:y.toHuman(),existentialDeposit:w.toString(),meta:L}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=this.parseLocation("generalIndex",r),c=s?.find(p=>p.id===a?.toString());return c?{...i,decimals:c.decimals,name:c.name,symbol:c.symbol,icon:c.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:a}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e){let[t,s,r,i,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),c=this.getSupportedAssets(t),p=this.normalizeMetadata(c,a);return c.map(([{args:[y]},w])=>{let B=w.unwrap(),F=s.get(y.toString()),{assetType:L}=B;switch(L.toString()){case"Bond":let T=i.get(y.toString());return this.getBond(y.toString(),B,p,T);case"StableSwap":let G=r.get(y.toString());return this.getShares(y.toString(),B,p,G);case"External":return this.getExternal(y.toString(),B,e,F);default:return this.getToken(y.toString(),B,p,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 s=It(t.toJSON(),e);return s&&s[e]}else return}};var Me=class extends ke{constructor(e){super(e)}async getBalance(e,t){return t===Oe?await this.getSystemBalance(e):await this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeBalance(e,t,s){let r=t.filter(i=>i!==Oe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach(({free:a,reserved:c,frozen:p},y)=>{let w=this.calculateFreeBalance({free:a,feeFrozen:c,frozen:p}),B=r[y][1];s(B,w)})})}async subscribeTokenBalance(e,t,s){let r=t.filter(i=>i!==Oe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach((a,c)=>{let p=this.calculateFreeBalance(a),y=r[c][1];s(y,p)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(Oe,this.calculateFreeBalance(s)))}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,a=new fe(t),c=new fe(s||i),p=new fe(r||0),y=c.gt(p)?c:p;return a.minus(y)}};var be=class extends Me{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async s=>{let r=[await this.subscribePoolChange(s),await this.subscribeTokensPoolBalance(s),await this.subscribeSystemPoolBalance(s)];if(this.hasShareAsset(s)){let i=await this.subscribeSharePoolBalance(s);r.push(i)}return this.subscribeLog(s),r});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,s)=>t.id!==s))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance($e,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(s,r){let i=e.tokens.findIndex(a=>a.id==s);i>=0&&t(e,s)&&(e.tokens[i].balance=r.toString())}}};var it=class extends be{MAX_FINAL_WEIGHT=$(I(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,a])=>this.isActivePool(a.unwrap(),s)).map(async([{args:[i]},a])=>{let c=a.unwrap(),p=i.toString(),y=await this.getPoolDelta(p,c,s.toString());return this.poolsData.set(i.toString(),c),{address:p,type:"Lbp",fee:c.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let a=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(c=>c.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:a,initialWeight:c,finalWeight:p,repayTarget:y,feeCollector:w}=t,B=pe.calculateLinearWeights(r.toString(),i.toString(),c.toString(),p.toString(),s),[F,L]=a,T=F.toString(),G=I(B),D=L.toString(),K=this.MAX_FINAL_WEIGHT.minus(I(G)),[x,Z,oe]=await Promise.all([this.isRepayFeeApplied(T,y.toString(),w.toString()),this.getBalance(e,T),this.getBalance(e,D)]);return{repayFeeApply:x,tokens:[{id:T,weight:G,balance:Z.toString()},{id:D,weight:K,balance:oe.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=I(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var zt=require("@polkadot/util-crypto"),Xt=require("@polkadot/util");function j(u,e){return u.shiftedBy(-1*e).toString()}function me(u){return u[0]/u[1]*100}function ie(u){return u[0]/u[1]}function ge(u){return[u/rt,rt]}var nt=class extends be{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=s.map(async([{args:[p]},y])=>{let{hubReserve:w,shares:B,tradable:F}=y.unwrap(),L=await this.getBalance(t,p.toString());return{id:p.toString(),hubReserves:I(w.toString()),shares:I(B.toString()),tradeable:F.bits.toNumber(),balance:L.toString()}}),c=await Promise.all(a);return c.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:c,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=await this.api.query.dynamicFees.assetFee(e),r=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=r.minFee.toNumber()+i.minFee.toNumber(),c=r.maxFee.toNumber()+i.maxFee.toNumber();if(s.isSome){let{assetFee:p,protocolFee:y}=s.unwrap();return{assetFee:ge(p.toNumber()),protocolFee:ge(y.toNumber()),min:ge(a),max:ge(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:ge(a),max:ge(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let a=e.tokens[i];if(r.isNone)return a;let c=r.unwrap();return this.updateTokenState(a,c)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i}=t;return{...e,hubReserves:I(s.toString()),shares:I(r.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return ge(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return ge(t)}getPoolId(){return(0,zt.encodeAddress)((0,Xt.stringToU8a)("modlomnipool".padEnd(32,"\0")),Re)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var ot=class extends be{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[a,c]=r.unwrap(),[p,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:p.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var lt=require("@polkadot/util-crypto");var J=require("@galacticcouncil/math-stableswap"),te=class{static getPoolAddress(e){return(0,J.pool_account_name)(e)}static calculateAmplification(e,t,s,r,i){return(0,J.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return(0,J.calculate_in_given_out)(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return(0,J.calculate_add_one_asset)(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return(0,J.calculate_shares_for_amount)(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return(0,J.calculate_out_given_in)(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return(0,J.calculate_liquidity_out_one_asset)(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return(0,J.calculate_shares)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,J.calculate_pool_trade_fee)(e,t,s)}};var at=class extends be{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},a])=>{let c=a.unwrap(),p=i.toString(),y=this.getPoolAddress(p),[w,B]=await Promise.all([this.getPoolDelta(p,c,s.toString()),this.getPoolTokens(y,p,c)]);return this.stablePools.set(y,c),{address:y,id:p,type:"Stableswap",fee:ge(c.fee.toNumber()),tokens:B,...w,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toNumber(),r=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,r,s.toString());Object.assign(e,i)})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:a,finalBlock:c}=t,p=te.calculateAmplification(r.toString(),i.toString(),a.toString(),c.toString(),s),y=await this.api.query.tokens.totalIssuance(e);return{amplification:p,totalIssuance:y.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async p=>{let[y,w]=await Promise.all([this.api.query.stableswap.assetTradability(t,p.toString()),this.getBalance(e,p.toString())]);return{id:p.toString(),tradeable:y.bits.toNumber(),balance:w.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:p}=c.unwrap(),y=await this.getBalance($e,t);a.push({id:t,tradeable:p.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),s=te.getPoolAddress(t);return(0,lt.encodeAddress)((0,lt.blake2AsHex)(s),Re)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function ut(u){return u.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var Je=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},At=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},De=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Tt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Ft=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},_t=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Ce=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new Le(this.api),this.xykClient=new ot(this.api),this.omniClient=new nt(this.api),this.lbpClient=new it(this.api),this.stableClient=new at(this.api)}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||(this.onChainAssets=await this.assetClient.getOnChainAssets(),this.onChainAssetsLoaded=!0),e.length==0){let a=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(c=>c.isSupported()).map(c=>c.getPools()))).flat();return this.withMetadata(a)}let t=[];e.forEach(i=>{switch(i){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break;case"Stableswap":t.push(this.stableClient.getPools());break}});let r=(await Promise.all(t)).flat();return this.withMetadata(r)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(s=>[s.id,s]));return e.filter(s=>s.type==="Xyk"?s.tokens.every(r=>t.get(r.id)):!0).map(s=>{let r=s.tokens.map(i=>{let a=t.get(i.id);return{...i,...a}});return{...s,tokens:r}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new Je(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):a=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),ut(i));let c=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):a=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),ut(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var je=(u,e)=>u===e?0:u==null?e==null?0:-1:e==null?u==null?0:1:typeof u.compare=="function"?u.compare(e):typeof e.compare=="function"?-e.compare(u):u<e?-1:u>e?1:0;var ct=(u,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(u(t)+e(t))}};var Ps=ct(()=>"illegal argument(s)"),Wt=u=>{throw new Ps(u)};var bs=ct(()=>"index out of bounds"),Et=u=>{throw new bs(u)},pt=(u,e,t)=>(u<e||u>=t)&&Et(u);var Yt=23283064365386963e-26,mt=class{float(e=1){return this.int()*Yt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Yt-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var Rt=Math.random,kt=class extends mt{int(){return Rt()*4294967296>>>0}float(e=1){return Rt()*e}norm(e=1){return(Rt()-.5)*2*e}},$t=new kt;var Jt=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var jt=Object.getPrototypeOf({}),ht="function",Kt="string",Ge=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===ht)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===ht)return e.equiv(u)}else return u==e;return typeof u===Kt||typeof e===Kt?!1:(t=Object.getPrototypeOf(u),(t==null||t===jt)&&(t=Object.getPrototypeOf(e),t==null||t===jt)?Os(u,e):typeof u!==ht&&u.length!==void 0&&typeof e!==ht&&e.length!==void 0?Ss(u,e):u instanceof Set&&e instanceof Set?ys(u,e):u instanceof Map&&e instanceof Map?xs(u,e):u instanceof Date&&e instanceof Date?u.getTime()===e.getTime():u instanceof RegExp&&e instanceof RegExp?u.toString()===e.toString():u!==u&&e!==e)},Ss=(u,e,t=Ge)=>{let s=u.length;if(s===e.length)for(;s-- >0&&t(u[s],e[s]););return s<0},ys=(u,e,t=Ge)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),xs=(u,e,t=Ge)=>u.size===e.size&&t([...u].sort(),[...e].sort()),Os=(u,e,t=Ge)=>{if(Object.keys(u).length!==Object.keys(e).length)return!1;for(let s in u)if(!e.hasOwnProperty(s)||!t(u[s],e[s]))return!1;return!0};var Qt=(u,e)=>u!=null&&typeof u[e]=="function";var Vt=u=>Qt(u,"xform")?u.xform():u;var gt=Symbol(),Lt=()=>{};var Zt=u=>u!=null&&typeof u[Symbol.iterator]=="function";var dt=class{value;constructor(e){this.value=e}deref(){return this.value}};var ft=u=>u instanceof dt;var es=u=>u instanceof dt?u.deref():u;function*ts(u,e){let t=Vt(u)([Lt,Lt,(s,r)=>r])[2];for(let s of e){let r=t(gt,s);if(ft(r)){r=es(r.deref()),r!==gt&&(yield r);return}r!==gt&&(yield r)}}var ss=(u,e)=>[u[0],u[1],e];function Ke(u,e){return Zt(e)?ts(Ke(u),e):t=>{let s=t[2];return ss(t,(r,i)=>s(r,u(i)))}}var qe=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return rs("next",this._head)}reverseIterator(){return rs("prev",this.tail)}clear(){this.release()}compare(e,t=je){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,a=0;for(;s-- >0&&a===0;)a=t(r.value,i.value),r=r.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof qe||Jt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!Ge(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||je;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!ft(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&Et(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*rs(u,e){for(;e;)yield e.value,e=e[u]}var Se=class extends qe{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new Se(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new Se}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(pt(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(pt(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new Se,e)}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let s=this.nthCell(e),r=this.nthCell(t-1),i=a=>({first(){return a.value},next(){return a!==r&&a.next?i(a.next):void 0}});return s?i(s):void 0}shuffle(e,t=$t){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&Wt("invalid indices: ${from} / ${to}");let i=new Se,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=je){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,a=0;for(let p=0;p<t&&(a++,i=i.next,!!i);p++);let c=t;for(;a>0||c>0&&i;){let p;a===0?(p=i,i=i.next,c--):!i||c===0||e(s.value,i.value)<=0?(p=s,s=s.next,a--):(p=i,i=i.next,c--),this._tail?this._tail.next=p:this._head=p,p.prev=this._tail,this._tail=p}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),pt(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new Se;if(t>0)for(;r&&t-- >0;)this.remove(r),i.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let a of s)this.insertBefore(r,a);else for(let a of s)this.push(a);return i}};var He=class{map;items;opts;_size;constructor(e,t){let s=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=s.map(),this.items=new Se,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ke(e=>[e.k,e],this.items)}keys(){return Ke(e=>e.k,this.items)}values(){return Ke(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new He(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e);return this._size+=Math.max(0,s-(r?r.value.s:0)),this.ensureSize()&&this.doSetEntry(r,e,t,s),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let s=this.map.get(e);return s?Promise.resolve(this.resetEntry(s)):t().then(r=>this.set(e,r))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,s=this.opts.maxlen;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e&&e(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Pt=class extends Ce{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new He(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
-
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Be=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Be(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,a,c){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=c}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(p=>[p.id,p])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let c=this.calculateTradeFee(t,s),p=me(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(c),w=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return w.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:w,calculatedIn:w,amountOut:t,feePct:p,errors:i}}else{let c=this.calculateInGivenOut(e,t),p=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(p)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let c=this.calculateOutGivenIn(e,t),p=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(p)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),p=this.calculateTradeFee(c,s),y=me(this.repayFeeApply?s.repayFee:s.exchangeFee),w=c.minus(p),B=e.balanceOut.div(this.maxOutRatio);return w.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:w,feePct:y,errors:i}}}calculateInGivenOut(e,t){let s=pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?k:r}calculateOutGivenIn(e,t){let s=pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?k:r}spotPriceInGivenOut(e){let t=pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),$(ne,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),$(ne,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=pe.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(s)}};var E=require("@galacticcouncil/math-omnipool"),z=class{static calculateSpotPrice(e,t,s,r){return(0,E.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,E.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,a,c,p,y){return(0,E.calculate_in_given_out)(e,t,s,r,i,a,c,p,y)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,E.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,a,c,p,y){return(0,E.calculate_out_given_in)(e,t,s,r,i,a,c,p,y)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,E.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,E.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,E.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,a,c,p){return(0,E.calculate_liquidity_out)(e,t,s,r,i,a,c,p)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,c,p){return(0,E.calculate_liquidity_lrna_out)(e,t,s,r,i,a,c,p)}static calculateCapDifference(e,t,s,r){return(0,E.calculate_cap_difference)(e,t,s,r)}static verifyAssetCap(e,t,s,r){return(0,E.verify_asset_cap)(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return(0,E.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,E.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,E.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,E.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,E.is_remove_liquidity_allowed)(e)}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(p=>[p.id,p])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,tradeableIn:r.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),c=r===k?k:a.div(r).multipliedBy(100).decimalPlaces(2),p=[],y=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!y||!w)&&p.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&p.push("MaxOutRatioExceeded");let F=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(F)&&p.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:c.toNumber(),errors:p}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),c=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),p=[],y=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!y||!w)&&p.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&p.push("MaxInRatioExceeded");let F=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(F)&&p.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:c.toNumber(),errors:p}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=z.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ie(s.assetFee).toString():k.toString(),s?ie(s.protocolFee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateLrnaInGivenOut(e,t,s){let r=z.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ie(s.assetFee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=z.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ie(s.assetFee).toString():k.toString(),s?ie(s.protocolFee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateOutGivenLrnaIn(e,t,s){let r=z.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ie(s.assetFee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=z.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=z.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=z.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=z.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Ee-e.decimalsIn)).decimalPlaces(0,1)}};var Ie=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Ie(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,i,a,c,p,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=a,this.id=c,this.fee=p,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(p=>[p.id,p])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?st:r.tradeable,tradeableOut:this.id===t?st:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=me(s.fee),c=[],p=z.isSellAllowed(e.tradeableIn),y=z.isBuyAllowed(e.tradeableOut);return(!p||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=me(s.fee),c=[],p=z.isSellAllowed(e.tradeableIn),y=z.isBuyAllowed(e.tradeableOut);return(!p||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,s){let r=te.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ie(s.fee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateAddOneAsset(e,t,s){let r=te.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?ie(s.fee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateSharesForAmount(e,t,s){let r=te.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?ie(s.fee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=$(ne,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,s){let r=te.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ie(s.fee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateWithdrawOneAsset(e,t,s){let r=te.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?ie(s.fee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateShares(e,t,s){let r=te.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?ie(s.fee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=$(ne,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=te.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var V=require("@galacticcouncil/math-xyk"),ye=class{static getSpotPrice(e,t,s){return(0,V.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,V.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,V.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,V.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,V.calculate_liquidity_in)(e,t,s)}static calculateShares(e,t,s){return(0,V.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,V.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,V.calculate_liquidity_out_asset_b)(e,t,s,r)}};var Ae=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Ae(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(p=>[p.id,p])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=me(s.exchangeFee),c=r.plus(i),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&p.push("MaxOutRatioExceeded");let w=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(w)&&p.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:r,amountOut:t,feePct:a,errors:p}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=me(s.exchangeFee),c=r.minus(i),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&p.push("MaxInRatioExceeded");let w=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(w)&&p.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:a,errors:p}}calculateInGivenOut(e,t){let s=ye.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?k:r}calculateOutGivenIn(e,t){let s=ye.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?k:r}spotPriceInGivenOut(e){let t=ye.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),$(ne,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=ye.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),$(ne,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=ye.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(s)}};var Ue=class{static get(e){switch(e.type){case"Xyk":return Ae.fromPool(e);case"Omnipool":return ve.fromPool(e);case"Lbp":return Be.fromPool(e);case"Stableswap":return Ie.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Fe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ye,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),a=this.getPaths(e,null,r,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(a)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,origin:r.origin,meta:r.meta}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(c=>this.validPath(c,s)).map(c=>this.toHops(c,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,Ue.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let a=t.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function ws(u,e){return u.minus(e).abs().div(u.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ze(u,e){return u.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Mt(u,e){return ne.minus(e.div(u)).multipliedBy(100).decimalPlaces(2)}function Dt(u,e){return e.div(u).minus(ne).multipliedBy(100).decimalPlaces(2)}var Qe=class extends Fe{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,a=r[r.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[s,r]}}getPoolFeeRange(e){let t=e.min?me(e.min):void 0,s=e.max?me(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new De(e,t);let p;if(r)p=await this.toSellSwaps(s,r,a);else{let _=c.map(async n=>await this.toSellSwaps(s,n,a)),X=await Promise.all(_);p=this.findBestSellRoute(X)}let y=p[0],w=p[p.length-1],B=this.isDirectTrade(p),F=p.map(_=>_.spotPrice.shiftedBy(-1*_.assetOutDecimals)).reduce((_,X)=>_.multipliedBy(X)),L=$(F,w.assetOutDecimals),T=B?w.calculatedOut:this.calculateDelta0Y(y.amountIn,p,a),G=w.amountOut,D=B?w.tradeFeePct:Mt(T,G).toNumber(),K=T.minus(G),x=this.getRouteFeeRange(p),Z=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(L),oe=ze(T,Z),Ne=_=>this.poolService.buildSellTx(e,t,y.amountIn,_,p.map(X=>X));return{type:"Sell",amountIn:y.amountIn,amountOut:w.amountOut,spotPrice:L,tradeFee:K,tradeFeePct:D,tradeFeeRange:x,priceImpactPct:oe.toNumber(),swaps:p,toTx:Ne,toHuman(){return{type:"Sell",amountIn:j(y.amountIn,y.assetInDecimals),amountOut:j(w.amountOut,w.assetOutDecimals),spotPrice:j(L,w.assetOutDecimals),tradeFee:j(K,w.assetOutDecimals),tradeFeePct:D,tradeFeeRange:x,priceImpactPct:oe.toNumber(),swaps:p.map(_=>_.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let p=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1]:y=e;let w=c.calculateOutGivenIn(p,y);r.push(w)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let p=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1].amountOut:y=$(I(e),p.decimalsIn).decimalPlaces(0,1);let w=await this.poolService.getPoolFees(p.assetOut,c),{amountOut:B,calculatedOut:F,feePct:L,errors:T}=c.validateAndSell(p,y,w),G=this.getPoolFeeRange(w),D=c.spotPriceOutGivenIn(p),K=y.shiftedBy(-1*p.decimalsIn).multipliedBy(D),x=ze(F,K);r.push({...a,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountIn:y,calculatedOut:F,amountOut:B,spotPrice:D,tradeFeePct:L,tradeFeeRange:G,priceImpactPct:x.toNumber(),errors:T,toHuman(){return{...a,amountIn:j(y,p.decimalsIn),calculatedOut:j(F,p.decimalsOut),amountOut:j(B,p.decimalsOut),spotPrice:j(D,p.decimalsOut),tradeFeePct:L,tradeFeeRange:G,priceImpactPct:x.toNumber(),errors:T}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(x=>x.tokens.find(Z=>Z.id===e)).filter(x=>!!x).sort((x,Z)=>Number(Z.balance)-Number(x.balance)),{balance:c,decimals:p}=a[0],w=I(c).shiftedBy(-1*p).div(100).multipliedBy(.1),B=i.map(async x=>await this.toSellSwaps(w,x,r)),F=await Promise.all(B),L=this.findBestSellRoute(F),T=await this.toSellSwaps("1",L,r),G=T.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,Z)=>x.multipliedBy(Z)),D=T[T.length-1].assetOutDecimals;return{amount:$(G,D),decimals:D}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,a=r[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new De(e,t);let p;if(r)p=await this.toBuySwaps(s,r,a);else{let _=c.map(async n=>await this.toBuySwaps(s,n,a)),X=await Promise.all(_);p=this.findBestBuyRoute(X)}let y=p[p.length-1],w=p[0],B=this.isDirectTrade(p),F=p.map(_=>_.spotPrice.shiftedBy(-1*_.assetInDecimals)).reduce((_,X)=>_.multipliedBy(X)),L=$(F,w.assetInDecimals),T=B?w.calculatedIn:this.calculateDelta0X(y.amountOut,p,a),G=w.amountIn,D=B?w.tradeFeePct:Dt(T,G).toNumber(),K=G.minus(T),x=this.getRouteFeeRange(p),Z=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(L),oe;T.isZero()?oe=-100:oe=ze(Z,T).toNumber();let Ne=_=>this.poolService.buildBuyTx(e,t,y.amountOut,_,p.map(X=>X));return{type:"Buy",amountOut:y.amountOut,amountIn:w.amountIn,spotPrice:L,tradeFee:K,tradeFeePct:D,tradeFeeRange:x,priceImpactPct:oe,swaps:p,toTx:Ne,toHuman(){return{type:"Buy",amountOut:j(y.amountOut,y.assetOutDecimals),amountIn:j(w.amountIn,w.assetInDecimals),spotPrice:j(L,w.assetInDecimals),tradeFee:j(K,w.assetInDecimals),tradeFeePct:D,tradeFeeRange:x,priceImpactPct:oe,swaps:p.map(_=>_.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let p=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=r[0];let w=c.calculateInGivenOut(p,y);r.unshift(w)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let p=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=$(I(e),p.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let w=await this.poolService.getPoolFees(p.assetOut,c),{amountIn:B,calculatedIn:F,feePct:L,errors:T}=c.validateAndBuy(p,y,w),G=this.getPoolFeeRange(w),D=c.spotPriceInGivenOut(p),K=y.shiftedBy(-1*p.decimalsOut).multipliedBy(D),x;F.isZero()?x=-100:x=ze(K,F).toNumber(),r.unshift({...a,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountOut:y,calculatedIn:F,amountIn:B,spotPrice:D,tradeFeePct:L,tradeFeeRange:G,priceImpactPct:x,errors:T,toHuman(){return{...a,amountOut:j(y,p.decimalsOut),calculatedIn:j(F,p.decimalsIn),amountIn:j(B,p.decimalsIn),spotPrice:j(D,p.decimalsIn),tradeFeePct:L,tradeFeeRange:G,priceImpactPct:x,errors:T}}})}return r}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
|
|
1
|
+
"use strict";var St=Object.defineProperty;var is=Object.getOwnPropertyDescriptor;var ns=Object.getOwnPropertyNames;var os=Object.prototype.hasOwnProperty;var as=(u,e)=>{for(var t in e)St(u,t,{get:e[t],enumerable:!0})},ls=(u,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ns(e))!os.call(u,r)&&r!==t&&St(u,r,{get:()=>e[r],enumerable:!(s=is(e,r))||s.enumerable});return u};var us=u=>ls(St({},"__esModule",{value:!0}),u);var Bs={};as(Bs,{AssetClient:()=>Le,AssetNotFound:()=>Nt,BASILISK_PARACHAIN_ID:()=>ds,BalanceClient:()=>Me,BigNumber:()=>fe,CachingPoolService:()=>Pt,DECIMAL_PLACES:()=>qt,DENOMINATOR:()=>rt,HYDRADX_OMNIPOOL_ADDRESS:()=>$e,HYDRADX_PARACHAIN_ID:()=>gs,HYDRADX_SS58_PREFIX:()=>Ee,INFINITY:()=>ms,LbpMath:()=>pe,LbpPool:()=>Be,ONE:()=>ne,OmniMath:()=>z,OmniPool:()=>ve,PoolConfigNotFound:()=>At,PoolError:()=>_e,PoolFactory:()=>Ue,PoolNotFound:()=>Je,PoolService:()=>Ce,PoolType:()=>re,ProviderConfigNotFound:()=>_t,RUNTIME_DECIMALS:()=>Re,RouteNotFound:()=>De,Router:()=>Fe,SYSTEM_ASSET_DECIMALS:()=>hs,SYSTEM_ASSET_ID:()=>Oe,StableMath:()=>te,StableSwap:()=>Ie,StorageConfigNotFound:()=>Tt,SubscriptionNotSupported:()=>Ft,TRADEABLE_DEFAULT:()=>st,TradeRouter:()=>Qe,TradeType:()=>vt,XykMath:()=>Se,XykPool:()=>Ae,ZERO:()=>k,bnum:()=>I,buildRoute:()=>ut,calculateBuyFee:()=>Dt,calculateDiffToAvg:()=>ws,calculateDiffToRef:()=>ze,calculateSellFee:()=>Mt,findNestedKey:()=>It,findNestedObj:()=>fs,scale:()=>$});module.exports=us(Bs);var Ze=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var cs=5,We=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new Ze,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>cs)return r;let p=c[c.length-1];(s===null||p[0]===s)&&r.push(c),e.get(p[0])?.forEach(w=>{if(this.isNotVisited(w,c)){let B=[...c];B.push(w),i.enqueue(B)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,a]of t){let c=parseInt(i),p=parseInt(a);s.get(c)?.push([p,r])}return s}};function xt(u){let e={};for(let t of u){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let i=0;i<s;i++){if(r==i)continue;let a=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(a)}}}return e}var Ye=class{getProposals(e,t,s){let r=xt(s),i=Object.keys(r),a=i.map(w=>r[w]).flat(),c=new We,p=c.buildAndPopulateGraph(i,a),S=c.findPaths(p,parseInt(e),t?parseInt(t):null);return this.parsePaths(S)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let a=s[i],c=s[i+1];if(c==null)break;r.push(this.toEdge(a,c))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ps=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ot=Math.ceil,ue=Math.floor,se="[BigNumber Error] ",Ct=se+"Number primitive has more than 15 significant digits: ",he=1e14,N=14,wt=9007199254740991,Bt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],we=1e7,Y=1e9;function Gt(u){var e,t,s,r=x.prototype={constructor:x,toString:null,valueOf:null},i=new x(1),a=20,c=4,p=-7,S=21,w=-1e7,B=1e7,F=!1,L=1,T=0,G={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},D="0123456789abcdefghijklmnopqrstuvwxyz",K=!0;function x(n,o){var l,P,h,d,y,m,g,b,f=this;if(!(f instanceof x))return new x(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<w?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((m=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,y=n;y>=10;y/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!ps.test(b=String(n)))return s(f,b,m);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(y=b.search(/e/i))>0?(d<0&&(d=y),d+=+b.slice(y+1),b=b.substring(0,y)):d<0&&(d=b.length)}else{if(q(o,2,D.length,"Base"),o==10&&K)return f=new x(n),_(f,a+f.e+1,c);if(b=String(n),m=typeof n=="number"){if(n*0!=0)return s(f,b,m,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Ct+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=D.slice(0,o),d=y=0,g=b.length;y<g;y++)if(l.indexOf(P=b.charAt(y))<0){if(P=="."){if(y>d){d=g;continue}}else if(!h&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){h=!0,y=-1,d=0;continue}return s(f,String(n),m,o)}m=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(y=0;b.charCodeAt(y)===48;y++);for(g=b.length;b.charCodeAt(--g)===48;);if(b=b.slice(y,++g)){if(g-=y,m&&x.DEBUG&&g>15&&(n>wt||n!==ue(n)))throw Error(Ct+f.s*n);if((d=d-y-1)>B)f.c=f.e=null;else if(d<w)f.c=[f.e=0];else{if(f.e=d,f.c=[],y=(d+1)%N,d<0&&(y+=N),y<g){for(y&&f.c.push(+b.slice(0,y)),g-=N;y<g;)f.c.push(+b.slice(y,y+=N));y=N-(b=b.slice(y)).length}else y-=g;for(;y--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}x.clone=Gt,x.ROUND_UP=0,x.ROUND_DOWN=1,x.ROUND_CEIL=2,x.ROUND_FLOOR=3,x.ROUND_HALF_UP=4,x.ROUND_HALF_DOWN=5,x.ROUND_HALF_EVEN=6,x.ROUND_HALF_CEIL=7,x.ROUND_HALF_FLOOR=8,x.EUCLID=9,x.config=x.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],q(l,0,Y,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],q(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(q(l[0],-Y,0,o),q(l[1],0,Y,o),p=l[0],S=l[1]):(q(l,-Y,Y,o),p=-(S=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)q(l[0],-Y,-1,o),q(l[1],1,Y,o),w=l[0],B=l[1];else if(q(l,-Y,Y,o),l)w=-(B=l<0?-l:l);else throw Error(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],q(l,0,9,o),L=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],q(l,0,Y,o),T=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")G=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))K=l.slice(0,10)=="0123456789",D=l;else throw Error(se+o+" invalid: "+l)}else throw Error(se+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[p,S],RANGE:[w,B],CRYPTO:F,MODULO_MODE:L,POW_PRECISION:T,FORMAT:G,ALPHABET:D}},x.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!x.DEBUG)return!0;var o,l,P=n.c,h=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&h>=-Y&&h<=Y&&h===ue(h)){if(P[0]===0){if(h===0&&P.length===1)return!0;break e}if(o=(h+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!==ue(l))break e;if(l!==0)return!0}}}else if(P===null&&h===null&&(d===null||d===1||d===-1))return!0;throw Error(se+"Invalid BigNumber: "+n)},x.maximum=x.max=function(){return oe(arguments,-1)},x.minimum=x.min=function(){return oe(arguments,1)},x.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ue(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,h,d,y,m,g=0,b=[],f=new x(i);if(l==null?l=a:q(l,0,Y),y=Ot(l/N),F)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(y*=2));g<y;)m=P[g]*131072+(P[g+1]>>>11),m>=9e15?(h=crypto.getRandomValues(new Uint32Array(2)),P[g]=h[0],P[g+1]=h[1]):(b.push(m%1e14),g+=2);g=y/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(y*=7);g<y;)m=(P[g]&31)*281474976710656+P[g+1]*1099511627776+P[g+2]*4294967296+P[g+3]*16777216+(P[g+4]<<16)+(P[g+5]<<8)+P[g+6],m>=9e15?crypto.randomBytes(7).copy(P,g):(b.push(m%1e14),g+=7);g=y/7}else throw F=!1,Error(se+"crypto unavailable");if(!F)for(;g<y;)m=o(),m<9e15&&(b[g++]=m%1e14);for(y=b[--g],l%=N,y&&l&&(m=Bt[N-l],b[g]=ue(y/m)*m);b[g]===0;b.pop(),g--);if(g<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=N);for(g=1,m=b[0];m>=10;m/=10,g++);g<N&&(d-=N-g)}return f.e=d,f.c=b,f}}(),x.sum=function(){for(var n=1,o=arguments,l=new x(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,h,d){for(var y,m=[0],g,b=0,f=l.length;b<f;){for(g=m.length;g--;m[g]*=P);for(m[0]+=d.indexOf(l.charAt(b++)),y=0;y<m.length;y++)m[y]>h-1&&(m[y+1]==null&&(m[y+1]=0),m[y+1]+=m[y]/h|0,m[y]%=h)}return m.reverse()}return function(l,P,h,d,y){var m,g,b,f,O,v,A,M,H=l.indexOf("."),W=a,E=c;for(H>=0&&(f=T,T=0,l=l.replace(".",""),M=new x(P),v=M.pow(l.length-H),T=f,M.c=o(xe(le(v.c),v.e,"0"),10,h,n),M.e=M.c.length),A=o(l,P,h,y?(m=D,n):(m=n,D)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return m.charAt(0);if(H<0?--b:(v.c=A,v.e=b,v.s=d,v=e(v,M,W,E,h),A=v.c,O=v.r,b=v.e),g=b+W+1,H=A[g],f=h/2,O=O||g<0||A[g+1]!=null,O=E<4?(H!=null||O)&&(E==0||E==(v.s<0?3:2)):H>f||H==f&&(E==4||O||E==6&&A[g-1]&1||E==(v.s<0?8:7)),g<1||!A[0])l=O?xe(m.charAt(1),-W,m.charAt(0)):m.charAt(0);else{if(A.length=g,O)for(--h;++A[--g]>h;)A[g]=0,g||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(H=0,l="";H<=f;l+=m.charAt(A[H++]));l=xe(l,b,m.charAt(0))}return l}}(),e=function(){function n(P,h,d){var y,m,g,b,f=0,O=P.length,v=h%we,A=h/we|0;for(P=P.slice();O--;)g=P[O]%we,b=P[O]/we|0,y=A*g+b*v,m=v*g+y%we*we+f,f=(m/d|0)+(y/we|0)+A*b,P[O]=m%d;return f&&(P=[f].concat(P)),P}function o(P,h,d,y){var m,g;if(d!=y)g=d>y?1:-1;else for(m=g=0;m<d;m++)if(P[m]!=h[m]){g=P[m]>h[m]?1:-1;break}return g}function l(P,h,d,y){for(var m=0;d--;)P[d]-=m,m=P[d]<h[d]?1:0,P[d]=m*y+P[d]-h[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,h,d,y,m){var g,b,f,O,v,A,M,H,W,E,C,Q,Ve,bt,yt,de,Xe,ae=P.s==h.s?1:-1,ee=P.c,U=h.c;if(!ee||!ee[0]||!U||!U[0])return new x(!P.s||!h.s||(ee?U&&ee[0]==U[0]:!U)?NaN:ee&&ee[0]==0||!U?ae*0:ae/0);for(H=new x(ae),W=H.c=[],b=P.e-h.e,ae=d+b+1,m||(m=he,b=ce(P.e/N)-ce(h.e/N),ae=ae/N|0),f=0;U[f]==(ee[f]||0);f++);if(U[f]>(ee[f]||0)&&b--,ae<0)W.push(1),O=!0;else{for(bt=ee.length,de=U.length,f=0,ae+=2,v=ue(m/(U[0]+1)),v>1&&(U=n(U,v,m),ee=n(ee,v,m),de=U.length,bt=ee.length),Ve=de,E=ee.slice(0,de),C=E.length;C<de;E[C++]=0);Xe=U.slice(),Xe=[0].concat(Xe),yt=U[0],U[1]>=m/2&&yt++;do{if(v=0,g=o(U,E,de,C),g<0){if(Q=E[0],de!=C&&(Q=Q*m+(E[1]||0)),v=ue(Q/yt),v>1)for(v>=m&&(v=m-1),A=n(U,v,m),M=A.length,C=E.length;o(A,E,M,C)==1;)v--,l(A,de<M?Xe:U,M,m),M=A.length,g=1;else v==0&&(g=v=1),A=U.slice(),M=A.length;if(M<C&&(A=[0].concat(A)),l(E,A,C,m),C=E.length,g==-1)for(;o(U,E,de,C)<1;)v++,l(E,de<C?Xe:U,C,m),C=E.length}else g===0&&(v++,E=[0]);W[f++]=v,E[0]?E[C++]=ee[Ve]||0:(E=[ee[Ve]],C=1)}while((Ve++<bt||E[0]!=null)&&ae--);O=E[0]!=null,W[0]||W.splice(0,1)}if(m==he){for(f=1,ae=W[0];ae>=10;ae/=10,f++);_(H,d+(H.e=f+b*N-1)+1,y,O)}else H.e=b,H.r=+O;return H}}();function Z(n,o,l,P){var h,d,y,m,g;if(l==null?l=c:q(l,0,8),!n.c)return n.toString();if(h=n.c[0],y=n.e,o==null)g=le(n.c),g=P==1||P==2&&(y<=p||y>=S)?tt(g,y):xe(g,y,"0");else if(n=_(new x(n),o,l),d=n.e,g=le(n.c),m=g.length,P==1||P==2&&(o<=d||d<=p)){for(;m<o;g+="0",m++);g=tt(g,d)}else if(o-=y,g=xe(g,d,"0"),d+1>m){if(--o>0)for(g+=".";o--;g+="0");}else if(o+=d-m,o>0)for(d+1==m&&(g+=".");o--;g+="0");return n.s<0&&h?"-"+g:g}function oe(n,o){for(var l,P,h=1,d=new x(n[0]);h<n.length;h++)P=new x(n[h]),(!P.s||(l=Te(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function Ne(n,o,l){for(var P=1,h=o.length;!o[--h];o.pop());for(h=o[0];h>=10;h/=10,P++);return(l=P+l*N-1)>B?n.c=n.e=null:l<w?n.c=[n.e=0]:(n.e=l,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,h=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,y,m,g){var b,f=m?y:y.replace(h,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!m&&(f=f.replace(n,function(O,v,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!g||g==b?v:O}),g&&(b=g,f=f.replace(o,"$1").replace(l,"0.$1")),y!=f))return new x(f,b);if(x.DEBUG)throw Error(se+"Not a"+(g?" base "+g:"")+" number: "+y);d.s=null}d.c=d.e=null}}();function _(n,o,l,P){var h,d,y,m,g,b,f,O=n.c,v=Bt;if(O){e:{for(h=1,m=O[0];m>=10;m/=10,h++);if(d=o-h,d<0)d+=N,y=o,g=O[b=0],f=ue(g/v[h-y-1]%10);else if(b=Ot((d+1)/N),b>=O.length)if(P){for(;O.length<=b;O.push(0));g=f=0,h=1,d%=N,y=d-N+1}else break e;else{for(g=m=O[b],h=1;m>=10;m/=10,h++);d%=N,y=d-N+h,f=y<0?0:ue(g/v[h-y-1]%10)}if(P=P||o<0||O[b+1]!=null||(y<0?g:g%v[h-y-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?y>0?g/v[h-y]:0:O[b-1])%10&1||l==(n.s<0?8:7)),o<1||!O[0])return O.length=0,P?(o-=n.e+1,O[0]=v[(N-o%N)%N],n.e=-o||0):O[0]=n.e=0,n;if(d==0?(O.length=b,m=1,b--):(O.length=b+1,m=v[N-d],O[b]=y>0?ue(g/v[h-y]%v[y])*m:0),P)for(;;)if(b==0){for(d=1,y=O[0];y>=10;y/=10,d++);for(y=O[0]+=m,m=1;y>=10;y/=10,m++);d!=m&&(n.e++,O[0]==he&&(O[0]=1));break}else{if(O[b]+=m,O[b]!=he)break;O[b--]=0,m=1}for(d=O.length;O[--d]===0;O.pop());}n.e>B?n.c=n.e=null:n.e<w&&(n.c=[n.e=0])}return n}function X(n){var o,l=n.e;return l===null?n.toString():(o=le(n.c),o=l<=p||l>=S?tt(o,l):xe(o,l,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new x(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return Te(this,new x(n,o))},r.decimalPlaces=r.dp=function(n,o){var l,P,h,d=this;if(n!=null)return q(n,0,Y),o==null?o=c:q(o,0,8),_(new x(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((h=l.length-1)-ce(this.e/N))*N,h=l[h])for(;h%10==0;h/=10,P--);return P<0&&(P=0),P},r.dividedBy=r.div=function(n,o){return e(this,new x(n,o),a,c)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new x(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var l,P,h,d,y,m,g,b,f,O=this;if(n=new x(n),n.c&&!n.isInteger())throw Error(se+"Exponent not an integer: "+X(n));if(o!=null&&(o=new x(o)),m=n.e>14,!O.c||!O.c[0]||O.c[0]==1&&!O.e&&O.c.length==1||!n.c||!n.c[0])return f=new x(Math.pow(+X(O),m?n.s*(2-et(n)):+X(n))),o?f.mod(o):f;if(g=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new x(NaN);P=!g&&O.isInteger()&&o.isInteger(),P&&(O=O.mod(o))}else{if(n.e>9&&(O.e>0||O.e<-1||(O.e==0?O.c[0]>1||m&&O.c[1]>=24e7:O.c[0]<8e13||m&&O.c[0]<=9999975e7)))return d=O.s<0&&et(n)?-0:0,O.e>-1&&(d=1/d),new x(g?1/d:d);T&&(d=Ot(T/N+2))}for(m?(l=new x(.5),g&&(n.s=1),b=et(n)):(h=Math.abs(+X(n)),b=h%2),f=new x(i);;){if(b){if(f=f.times(O),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(h){if(h=ue(h/2),h===0)break;b=h%2}else if(n=n.times(l),_(n,n.e+1,1),n.e>14)b=et(n);else{if(h=+X(n),h===0)break;b=h%2}O=O.times(O),d?O.c&&O.c.length>d&&(O.c.length=d):P&&(O=O.mod(o))}return P?f:(g&&(f=i.div(f)),o?f.mod(o):d?_(f,T,c,y):f)},r.integerValue=function(n){var o=new x(this);return n==null?n=c:q(n,0,8),_(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return Te(this,new x(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return Te(this,new x(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=Te(this,new x(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&ce(this.e/N)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return Te(this,new x(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=Te(this,new x(n,o)))===-1||o===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(n,o){var l,P,h,d,y=this,m=y.s;if(n=new x(n,o),o=n.s,!m||!o)return new x(NaN);if(m!=o)return n.s=-o,y.plus(n);var g=y.e/N,b=n.e/N,f=y.c,O=n.c;if(!g||!b){if(!f||!O)return f?(n.s=-o,n):new x(O?y:NaN);if(!f[0]||!O[0])return O[0]?(n.s=-o,n):new x(f[0]?y:c==3?-0:0)}if(g=ce(g),b=ce(b),f=f.slice(),m=g-b){for((d=m<0)?(m=-m,h=f):(b=g,h=O),h.reverse(),o=m;o--;h.push(0));h.reverse()}else for(P=(d=(m=f.length)<(o=O.length))?m:o,m=o=0;o<P;o++)if(f[o]!=O[o]){d=f[o]<O[o];break}if(d&&(h=f,f=O,O=h,n.s=-n.s),o=(P=O.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=he-1;P>m;){if(f[--P]<O[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=he}f[P]-=O[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?Ne(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var l,P,h=this;return n=new x(n,o),!h.c||!n.s||n.c&&!n.c[0]?new x(NaN):!n.c||h.c&&!h.c[0]?new x(h):(L==9?(P=n.s,n.s=1,l=e(h,n,0,3),n.s=P,l.s*=P):l=e(h,n,0,L),n=h.minus(l.times(n)),!n.c[0]&&L==1&&(n.s=h.s),n)},r.multipliedBy=r.times=function(n,o){var l,P,h,d,y,m,g,b,f,O,v,A,M,H,W,E=this,C=E.c,Q=(n=new x(n,o)).c;if(!C||!Q||!C[0]||!Q[0])return!E.s||!n.s||C&&!C[0]&&!Q||Q&&!Q[0]&&!C?n.c=n.e=n.s=null:(n.s*=E.s,!C||!Q?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=ce(E.e/N)+ce(n.e/N),n.s*=E.s,g=C.length,O=Q.length,g<O&&(M=C,C=Q,Q=M,h=g,g=O,O=h),h=g+O,M=[];h--;M.push(0));for(H=he,W=we,h=O;--h>=0;){for(l=0,v=Q[h]%W,A=Q[h]/W|0,y=g,d=h+y;d>h;)b=C[--y]%W,f=C[y]/W|0,m=A*b+f*v,b=v*b+m%W*W+M[d]+l,l=(b/H|0)+(m/W|0)+A*f,M[d--]=b%H;M[d]=l}return l?++P:M.splice(0,1),Ne(n,M,P)},r.negated=function(){var n=new x(this);return n.s=-n.s||null,n},r.plus=function(n,o){var l,P=this,h=P.s;if(n=new x(n,o),o=n.s,!h||!o)return new x(NaN);if(h!=o)return n.s=-o,P.minus(n);var d=P.e/N,y=n.e/N,m=P.c,g=n.c;if(!d||!y){if(!m||!g)return new x(h/0);if(!m[0]||!g[0])return g[0]?n:new x(m[0]?P:h*0)}if(d=ce(d),y=ce(y),m=m.slice(),h=d-y){for(h>0?(y=d,l=g):(h=-h,l=m),l.reverse();h--;l.push(0));l.reverse()}for(h=m.length,o=g.length,h-o<0&&(l=g,g=m,m=l,o=h),h=0;o;)h=(m[--o]=m[o]+g[o]+h)/he|0,m[o]=he===m[o]?0:m[o]%he;return h&&(m=[h].concat(m),++y),Ne(n,m,y)},r.precision=r.sd=function(n,o){var l,P,h,d=this;if(n!=null&&n!==!!n)return q(n,1,Y),o==null?o=c:q(o,0,8),_(new x(d),n,o);if(!(l=d.c))return null;if(h=l.length-1,P=h*N+1,h=l[h]){for(;h%10==0;h/=10,P--);for(h=l[0];h>=10;h/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return q(n,-wt,wt),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,l,P,h,d=this,y=d.c,m=d.s,g=d.e,b=a+4,f=new x("0.5");if(m!==1||!y||!y[0])return new x(!m||m<0&&(!y||y[0])?NaN:y?d:1/0);if(m=Math.sqrt(+X(d)),m==0||m==1/0?(o=le(y),(o.length+g)%2==0&&(o+="0"),m=Math.sqrt(+o),g=ce((g+1)/2)-(g<0||g%2),m==1/0?o="5e"+g:(o=m.toExponential(),o=o.slice(0,o.indexOf("e")+1)+g),l=new x(o)):l=new x(m+""),l.c[0]){for(g=l.e,m=g+b,m<3&&(m=0);;)if(h=l,l=f.times(h.plus(e(d,h,b,1))),le(h.c).slice(0,m)===(o=le(l.c)).slice(0,m))if(l.e<g&&--m,o=o.slice(m-3,m+1),o=="9999"||!P&&o=="4999"){if(!P&&(_(h,h.e+a+2,0),h.times(h).eq(d))){l=h;break}b+=4,m+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(_(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return _(l,l.e+a+1,c,n)},r.toExponential=function(n,o){return n!=null&&(q(n,0,Y),n++),Z(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(q(n,0,Y),n=n+this.e+1),Z(this,n,o)},r.toFormat=function(n,o,l){var P,h=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=G;else if(typeof l!="object")throw Error(se+"Argument not an object: "+l);if(P=h.toFixed(n,o),h.c){var d,y=P.split("."),m=+l.groupSize,g=+l.secondaryGroupSize,b=l.groupSeparator||"",f=y[0],O=y[1],v=h.s<0,A=v?f.slice(1):f,M=A.length;if(g&&(d=m,m=g,g=d,M-=d),m>0&&M>0){for(d=M%m||m,f=A.substr(0,d);d<M;d+=m)f+=b+A.substr(d,m);g>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=O?f+(l.decimalSeparator||"")+((g=+l.fractionGroupSize)?O.replace(new RegExp("\\d{"+g+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):O):f}return(l.prefix||"")+P+(l.suffix||"")},r.toFraction=function(n){var o,l,P,h,d,y,m,g,b,f,O,v,A=this,M=A.c;if(n!=null&&(m=new x(n),!m.isInteger()&&(m.c||m.s!==1)||m.lt(i)))throw Error(se+"Argument "+(m.isInteger()?"out of range: ":"not an integer: ")+X(m));if(!M)return new x(A);for(o=new x(i),b=l=new x(i),P=g=new x(i),v=le(M),d=o.e=v.length-A.e-1,o.c[0]=Bt[(y=d%N)<0?N+y:y],n=!n||m.comparedTo(o)>0?d>0?o:b:m,y=B,B=1/0,m=new x(v),g.c[0]=0;f=e(m,o,0,1),h=l.plus(f.times(P)),h.comparedTo(n)!=1;)l=P,P=h,b=g.plus(f.times(h=b)),g=h,o=m.minus(f.times(h=o)),m=h;return h=e(n.minus(l),P,0,1),g=g.plus(h.times(b)),l=l.plus(h.times(P)),g.s=b.s=A.s,d=d*2,O=e(b,P,d,c).minus(A).abs().comparedTo(e(g,l,d,c).minus(A).abs())<1?[b,P]:[g,l],B=y,O},r.toNumber=function(){return+X(this)},r.toPrecision=function(n,o){return n!=null&&q(n,1,Y),Z(this,n,o,2)},r.toString=function(n){var o,l=this,P=l.s,h=l.e;return h===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=h<=p||h>=S?tt(le(l.c),h):xe(le(l.c),h,"0"):n===10&&K?(l=_(new x(l),a+h+1,c),o=xe(le(l.c),l.e,"0")):(q(n,2,D.length,"Base"),o=t(xe(le(l.c),h,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return X(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,u!=null&&x.set(u),x}function ce(u){var e=u|0;return u>0||u===e?e:e-1}function le(u){for(var e,t,s=1,r=u.length,i=u[0]+"";s<r;){for(e=u[s++]+"",t=N-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function Te(u,e){var t,s,r=u.c,i=e.c,a=u.s,c=e.s,p=u.e,S=e.e;if(!a||!c)return null;if(t=r&&!r[0],s=i&&!i[0],t||s)return t?s?0:-c:a;if(a!=c)return a;if(t=a<0,s=p==S,!r||!i)return s?0:!r^t?1:-1;if(!s)return p>S^t?1:-1;for(c=(p=r.length)<(S=i.length)?p:S,a=0;a<c;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return p==S?0:p>S^t?1:-1}function q(u,e,t,s){if(u<e||u>t||u!==ue(u))throw Error(se+(s||"Argument")+(typeof u=="number"?u<e||u>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(u))}function et(u){var e=u.c.length-1;return ce(u.e/N)==e&&u.c[e]%2!=0}function tt(u,e){return(u.length>1?u.charAt(0)+"."+u.slice(1):u)+(e<0?"e":"e+")+e}function xe(u,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);u=r+u}else if(s=u.length,++e>s){for(r=t,e-=s;--e;r+=t);u+=r}else e<s&&(u=u.slice(0,e)+"."+u.slice(e));return u}var fe=Gt();var qt=12;fe.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:qt});var k=I(0),ne=I(1),ms=I("Infinity");function $(u,e){let t=new fe(e.toString()),s=new fe(10).pow(t);return u.times(s)}function I(u){return new fe(u.toString())}var re=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(re||{}),_e=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(_e||{}),vt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(vt||{});var Pe=require("@galacticcouncil/math-lbp"),pe=class{static getSpotPrice(e,t,s,r,i){return(0,Pe.get_spot_price)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return(0,Pe.calculate_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return(0,Pe.calculate_out_given_in)(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return(0,Pe.calculate_linear_weights)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,Pe.calculate_pool_trade_fee)(e,t,s)}};var Ht=require("@polkadot/util-crypto"),Ut=require("@polkadot/util"),Re=18,st=15,Oe="0",hs=12,gs=2034,Ee=63,ds=2090,rt=1e3,$e=(0,Ht.encodeAddress)((0,Ut.stringToU8a)("modlomnipool".padEnd(32,"\0")),Ee);function It(u,e){let t;return JSON.stringify(u,(s,r)=>(r&&r[e]&&(t=r),r)),t}function fs(u,e,t){let s;return JSON.stringify(u,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}var js=require("@polkadot/types/lookup");var Ks=require("@polkadot/api-base/types/consts");var Qs=require("@polkadot/api-base/types/errors");var Vs=require("@polkadot/api-base/types/events");var Zs=require("@polkadot/api-base/types/storage");var er=require("@polkadot/api-base/types/submittable");var tr=require("@polkadot/rpc-core/types/jsonrpc");var sr=require("@polkadot/api-base/types/calls");var cr=require("@polkadot/types/types/registry");var gr=require("@polkadot/types/lookup");var dr=require("@polkadot/api-base/types/consts");var fr=require("@polkadot/api-base/types/errors");var Pr=require("@polkadot/api-base/types/events");var br=require("@polkadot/api-base/types/storage");var yr=require("@polkadot/api-base/types/submittable");var Sr=require("@polkadot/rpc-core/types/jsonrpc");var xr=require("@polkadot/api-base/types/calls");var Tr=require("@polkadot/types/types/registry");var ke=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Le=class extends ke{SUPPORTED_TYPES=["StableSwap","Bond","Token","External"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getToken(e,t,s,r){if(e==Oe){let B=this.api.consts.balances.existentialDeposit;return{id:Oe,name:this.chainToken,symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:B.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:p}=t,{symbol:S,decimals:w}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:S,decimals:w,icon:S,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:this.parseLocation("parachain",r),existentialDeposit:p.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:c,isSufficient:p,existentialDeposit:S}=t,{symbol:w,decimals:B}=this.getToken(i.toString(),t,s),F=a.toNumber(),L=new Intl.DateTimeFormat("en-GB"),T=[w,"Bond",L.format(F)].join(" ");return{id:e,name:T,symbol:w+"b",decimals:B,icon:w,type:c.toString(),isSufficient:p.toHuman(),existentialDeposit:S.toString()}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:c,assetType:p,isSufficient:S,existentialDeposit:w}=t,F=i.map(G=>G.toString()).map(G=>{let{symbol:D}=this.getToken(G,t,s);return[G,D]}),L=Object.fromEntries(F),T=Object.values(L);return{id:e,name:T.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:T.join("/"),type:p.toString(),isSufficient:S.toHuman(),existentialDeposit:w.toString(),meta:L}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=this.parseLocation("generalIndex",r),c=s?.find(p=>p.id===a?.toString());return c?{...i,decimals:c.decimals,name:c.name,symbol:c.symbol,icon:c.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:a}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e){let[t,s,r,i,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),c=this.getSupportedAssets(t),p=this.normalizeMetadata(c,a);return c.map(([{args:[S]},w])=>{let B=w.unwrap(),F=s.get(S.toString()),{assetType:L}=B;switch(L.toString()){case"Bond":let T=i.get(S.toString());return this.getBond(S.toString(),B,p,T);case"StableSwap":let G=r.get(S.toString());return this.getShares(S.toString(),B,p,G);case"External":return this.getExternal(S.toString(),B,e,F);default:return this.getToken(S.toString(),B,p,F)}}).filter(S=>this.isValidAsset(S))}isValidAsset(e){return!!e.symbol&&!!e.decimals}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let s=It(t.toJSON(),e);return s&&s[e]}else return}};var Me=class extends ke{constructor(e){super(e)}async getBalance(e,t){return t===Oe?await this.getSystemBalance(e):await this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeBalance(e,t,s){let r=t.filter(i=>i!==Oe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach(({free:a,reserved:c,frozen:p},S)=>{let w=this.calculateFreeBalance({free:a,feeFrozen:c,frozen:p}),B=r[S][1];s(B,w)})})}async subscribeTokenBalance(e,t,s){let r=t.filter(i=>i!==Oe).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach((a,c)=>{let p=this.calculateFreeBalance(a),S=r[c][1];s(S,p)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(Oe,this.calculateFreeBalance(s)))}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,a=new fe(t),c=new fe(s||i),p=new fe(r||0),S=c.gt(p)?c:p;return a.minus(S)}};var be=class extends Me{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async s=>{let r=[await this.subscribePoolChange(s),await this.subscribeTokensPoolBalance(s),await this.subscribeSystemPoolBalance(s)];if(this.hasShareAsset(s)){let i=await this.subscribeSharePoolBalance(s);r.push(i)}return this.subscribeLog(s),r});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,s)=>t.id!==s))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance($e,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(s,r){let i=e.tokens.findIndex(a=>a.id==s);i>=0&&t(e,s)&&(e.tokens[i].balance=r.toString())}}};var it=class extends be{MAX_FINAL_WEIGHT=$(I(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,a])=>this.isActivePool(a.unwrap(),s)).map(async([{args:[i]},a])=>{let c=a.unwrap(),p=i.toString(),S=await this.getPoolDelta(p,c,s.toString());return this.poolsData.set(i.toString(),c),{address:p,type:"Lbp",fee:c.fee.toJSON(),...S,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let a=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(c=>c.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:a,initialWeight:c,finalWeight:p,repayTarget:S,feeCollector:w}=t,B=pe.calculateLinearWeights(r.toString(),i.toString(),c.toString(),p.toString(),s),[F,L]=a,T=F.toString(),G=I(B),D=L.toString(),K=this.MAX_FINAL_WEIGHT.minus(I(G)),[x,Z,oe]=await Promise.all([this.isRepayFeeApplied(T,S.toString(),w.toString()),this.getBalance(e,T),this.getBalance(e,D)]);return{repayFeeApply:x,tokens:[{id:T,weight:G,balance:Z.toString()},{id:D,weight:K,balance:oe.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=I(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var zt=require("@polkadot/util-crypto"),Xt=require("@polkadot/util");function j(u,e){return u.shiftedBy(-1*e).toString()}function me(u){return u[0]/u[1]*100}function ie(u){return u[0]/u[1]}function ge(u){return[u/rt,rt]}var nt=class extends be{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=s.map(async([{args:[p]},S])=>{let{hubReserve:w,shares:B,tradable:F}=S.unwrap(),L=await this.getBalance(t,p.toString());return{id:p.toString(),hubReserves:I(w.toString()),shares:I(B.toString()),tradeable:F.bits.toNumber(),balance:L.toString()}}),c=await Promise.all(a);return c.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:c,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=await this.api.query.dynamicFees.assetFee(e),r=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=r.minFee.toNumber()+i.minFee.toNumber(),c=r.maxFee.toNumber()+i.maxFee.toNumber();if(s.isSome){let{assetFee:p,protocolFee:S}=s.unwrap();return{assetFee:ge(p.toNumber()),protocolFee:ge(S.toNumber()),min:ge(a),max:ge(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:ge(a),max:ge(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let a=e.tokens[i];if(r.isNone)return a;let c=r.unwrap();return this.updateTokenState(a,c)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i}=t;return{...e,hubReserves:I(s.toString()),shares:I(r.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return ge(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return ge(t)}getPoolId(){return(0,zt.encodeAddress)((0,Xt.stringToU8a)("modlomnipool".padEnd(32,"\0")),Ee)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var ot=class extends be{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[a,c]=r.unwrap(),[p,S]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:p.toString()},{id:c.toString(),balance:S.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var lt=require("@polkadot/util-crypto");var J=require("@galacticcouncil/math-stableswap"),te=class{static getPoolAddress(e){return(0,J.pool_account_name)(e)}static calculateAmplification(e,t,s,r,i){return(0,J.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return(0,J.calculate_in_given_out)(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return(0,J.calculate_add_one_asset)(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return(0,J.calculate_shares_for_amount)(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return(0,J.calculate_out_given_in)(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return(0,J.calculate_liquidity_out_one_asset)(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return(0,J.calculate_shares)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,J.calculate_pool_trade_fee)(e,t,s)}};var at=class extends be{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},a])=>{let c=a.unwrap(),p=i.toString(),S=this.getPoolAddress(p),[w,B]=await Promise.all([this.getPoolDelta(p,c,s.toString()),this.getPoolTokens(S,p,c)]);return this.stablePools.set(S,c),{address:S,id:p,type:"Stableswap",fee:ge(c.fee.toNumber()),tokens:B,...w,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toNumber(),r=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,r,s.toString());Object.assign(e,i)})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:a,finalBlock:c}=t,p=te.calculateAmplification(r.toString(),i.toString(),a.toString(),c.toString(),s),S=await this.api.query.tokens.totalIssuance(e);return{amplification:p,totalIssuance:S.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async p=>{let[S,w]=await Promise.all([this.api.query.stableswap.assetTradability(t,p.toString()),this.getBalance(e,p.toString())]);return{id:p.toString(),tradeable:S.bits.toNumber(),balance:w.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:p}=c.unwrap(),S=await this.getBalance($e,t);a.push({id:t,tradeable:p.bits.toNumber(),balance:S.toString()})}return a}getPoolAddress(e){let t=Number(e),s=te.getPoolAddress(t);return(0,lt.encodeAddress)((0,lt.blake2AsHex)(s),Ee)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function ut(u){return u.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var Je=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},At=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},De=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Tt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Ft=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},_t=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Ce=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new Le(this.api),this.xykClient=new ot(this.api),this.omniClient=new nt(this.api),this.lbpClient=new it(this.api),this.stableClient=new at(this.api)}get assets(){return this.assets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||this.syncRegistry(),e.length==0){let a=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(c=>c.isSupported()).map(c=>c.getPools()))).flat();return this.withMetadata(a)}let t=[];e.forEach(i=>{switch(i){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break;case"Stableswap":t.push(this.stableClient.getPools());break}});let r=(await Promise.all(t)).flat();return this.withMetadata(r)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(s=>[s.id,s]));return e.filter(s=>s.type==="Xyk"?s.tokens.every(r=>t.get(r.id)):!0).map(s=>{let r=s.tokens.map(i=>{let a=t.get(i.id);return{...i,...a}});return{...s,tokens:r}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new Je(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):a=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),ut(i));let c=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):a=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),ut(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var je=(u,e)=>u===e?0:u==null?e==null?0:-1:e==null?u==null?0:1:typeof u.compare=="function"?u.compare(e):typeof e.compare=="function"?-e.compare(u):u<e?-1:u>e?1:0;var ct=(u,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(u(t)+e(t))}};var Ps=ct(()=>"illegal argument(s)"),Wt=u=>{throw new Ps(u)};var bs=ct(()=>"index out of bounds"),Rt=u=>{throw new bs(u)},pt=(u,e,t)=>(u<e||u>=t)&&Rt(u);var Yt=23283064365386963e-26,mt=class{float(e=1){return this.int()*Yt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Yt-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var Et=Math.random,kt=class extends mt{int(){return Et()*4294967296>>>0}float(e=1){return Et()*e}norm(e=1){return(Et()-.5)*2*e}},$t=new kt;var Jt=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var jt=Object.getPrototypeOf({}),ht="function",Kt="string",Ge=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===ht)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===ht)return e.equiv(u)}else return u==e;return typeof u===Kt||typeof e===Kt?!1:(t=Object.getPrototypeOf(u),(t==null||t===jt)&&(t=Object.getPrototypeOf(e),t==null||t===jt)?Os(u,e):typeof u!==ht&&u.length!==void 0&&typeof e!==ht&&e.length!==void 0?ys(u,e):u instanceof Set&&e instanceof Set?Ss(u,e):u instanceof Map&&e instanceof Map?xs(u,e):u instanceof Date&&e instanceof Date?u.getTime()===e.getTime():u instanceof RegExp&&e instanceof RegExp?u.toString()===e.toString():u!==u&&e!==e)},ys=(u,e,t=Ge)=>{let s=u.length;if(s===e.length)for(;s-- >0&&t(u[s],e[s]););return s<0},Ss=(u,e,t=Ge)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),xs=(u,e,t=Ge)=>u.size===e.size&&t([...u].sort(),[...e].sort()),Os=(u,e,t=Ge)=>{if(Object.keys(u).length!==Object.keys(e).length)return!1;for(let s in u)if(!e.hasOwnProperty(s)||!t(u[s],e[s]))return!1;return!0};var Qt=(u,e)=>u!=null&&typeof u[e]=="function";var Vt=u=>Qt(u,"xform")?u.xform():u;var gt=Symbol(),Lt=()=>{};var Zt=u=>u!=null&&typeof u[Symbol.iterator]=="function";var dt=class{value;constructor(e){this.value=e}deref(){return this.value}};var ft=u=>u instanceof dt;var es=u=>u instanceof dt?u.deref():u;function*ts(u,e){let t=Vt(u)([Lt,Lt,(s,r)=>r])[2];for(let s of e){let r=t(gt,s);if(ft(r)){r=es(r.deref()),r!==gt&&(yield r);return}r!==gt&&(yield r)}}var ss=(u,e)=>[u[0],u[1],e];function Ke(u,e){return Zt(e)?ts(Ke(u),e):t=>{let s=t[2];return ss(t,(r,i)=>s(r,u(i)))}}var qe=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return rs("next",this._head)}reverseIterator(){return rs("prev",this.tail)}clear(){this.release()}compare(e,t=je){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,a=0;for(;s-- >0&&a===0;)a=t(r.value,i.value),r=r.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof qe||Jt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!Ge(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||je;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!ft(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&Rt(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*rs(u,e){for(;e;)yield e.value,e=e[u]}var ye=class extends qe{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new ye(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new ye}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(pt(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(pt(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new ye,e)}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let s=this.nthCell(e),r=this.nthCell(t-1),i=a=>({first(){return a.value},next(){return a!==r&&a.next?i(a.next):void 0}});return s?i(s):void 0}shuffle(e,t=$t){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&Wt("invalid indices: ${from} / ${to}");let i=new ye,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=je){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,a=0;for(let p=0;p<t&&(a++,i=i.next,!!i);p++);let c=t;for(;a>0||c>0&&i;){let p;a===0?(p=i,i=i.next,c--):!i||c===0||e(s.value,i.value)<=0?(p=s,s=s.next,a--):(p=i,i=i.next,c--),this._tail?this._tail.next=p:this._head=p,p.prev=this._tail,this._tail=p}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),pt(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new ye;if(t>0)for(;r&&t-- >0;)this.remove(r),i.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let a of s)this.insertBefore(r,a);else for(let a of s)this.push(a);return i}};var He=class{map;items;opts;_size;constructor(e,t){let s=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=s.map(),this.items=new ye,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ke(e=>[e.k,e],this.items)}keys(){return Ke(e=>e.k,this.items)}values(){return Ke(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new He(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e);return this._size+=Math.max(0,s-(r?r.value.s:0)),this.ensureSize()&&this.doSetEntry(r,e,t,s),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let s=this.map.get(e);return s?Promise.resolve(this.resetEntry(s)):t().then(r=>this.set(e,r))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,s=this.opts.maxlen;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e&&e(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Pt=class extends Ce{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new He(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
+
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Be=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Be(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,a,c){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=c}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(p=>[p.id,p])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let c=this.calculateTradeFee(t,s),p=me(this.repayFeeApply?s.repayFee:s.exchangeFee),S=t.plus(c),w=this.calculateInGivenOut(e,S),B=e.balanceIn.div(this.maxInRatio);return w.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:w,calculatedIn:w,amountOut:t,feePct:p,errors:i}}else{let c=this.calculateInGivenOut(e,t),p=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(p)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let c=this.calculateOutGivenIn(e,t),p=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(p)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),p=this.calculateTradeFee(c,s),S=me(this.repayFeeApply?s.repayFee:s.exchangeFee),w=c.minus(p),B=e.balanceOut.div(this.maxOutRatio);return w.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:w,feePct:S,errors:i}}}calculateInGivenOut(e,t){let s=pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?k:r}calculateOutGivenIn(e,t){let s=pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?k:r}spotPriceInGivenOut(e){let t=pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),$(ne,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),$(ne,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=pe.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(s)}};var R=require("@galacticcouncil/math-omnipool"),z=class{static calculateSpotPrice(e,t,s,r){return(0,R.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,R.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,a,c,p,S){return(0,R.calculate_in_given_out)(e,t,s,r,i,a,c,p,S)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,R.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,a,c,p,S){return(0,R.calculate_out_given_in)(e,t,s,r,i,a,c,p,S)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,R.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,R.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,R.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,a,c,p){return(0,R.calculate_liquidity_out)(e,t,s,r,i,a,c,p)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,c,p){return(0,R.calculate_liquidity_lrna_out)(e,t,s,r,i,a,c,p)}static calculateCapDifference(e,t,s,r){return(0,R.calculate_cap_difference)(e,t,s,r)}static verifyAssetCap(e,t,s,r){return(0,R.verify_asset_cap)(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return(0,R.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,R.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,R.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,R.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,R.is_remove_liquidity_allowed)(e)}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(p=>[p.id,p])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,tradeableIn:r.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),c=r===k?k:a.div(r).multipliedBy(100).decimalPlaces(2),p=[],S=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!S||!w)&&p.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&p.push("MaxOutRatioExceeded");let F=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(F)&&p.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:c.toNumber(),errors:p}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),c=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),p=[],S=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!S||!w)&&p.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&p.push("MaxInRatioExceeded");let F=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(F)&&p.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:c.toNumber(),errors:p}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=z.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ie(s.assetFee).toString():k.toString(),s?ie(s.protocolFee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateLrnaInGivenOut(e,t,s){let r=z.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ie(s.assetFee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=z.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ie(s.assetFee).toString():k.toString(),s?ie(s.protocolFee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateOutGivenLrnaIn(e,t,s){let r=z.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ie(s.assetFee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=z.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Re-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=z.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Re-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=z.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Re-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=z.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Re-e.decimalsIn)).decimalPlaces(0,1)}};var Ie=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Ie(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,i,a,c,p,S){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=a,this.id=c,this.fee=p,this.totalIssuance=S}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(p=>[p.id,p])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?st:r.tradeable,tradeableOut:this.id===t?st:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=me(s.fee),c=[],p=z.isSellAllowed(e.tradeableIn),S=z.isBuyAllowed(e.tradeableOut);return(!p||!S)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=me(s.fee),c=[],p=z.isSellAllowed(e.tradeableIn),S=z.isBuyAllowed(e.tradeableOut);return(!p||!S)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,s){let r=te.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ie(s.fee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateAddOneAsset(e,t,s){let r=te.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?ie(s.fee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateSharesForAmount(e,t,s){let r=te.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?ie(s.fee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=$(ne,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,s){let r=te.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ie(s.fee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateWithdrawOneAsset(e,t,s){let r=te.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?ie(s.fee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateShares(e,t,s){let r=te.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?ie(s.fee).toString():k.toString()),i=I(r);return i.isNegative()?k:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=$(ne,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=te.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var V=require("@galacticcouncil/math-xyk"),Se=class{static getSpotPrice(e,t,s){return(0,V.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,V.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,V.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,V.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,V.calculate_liquidity_in)(e,t,s)}static calculateShares(e,t,s){return(0,V.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,V.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,V.calculate_liquidity_out_asset_b)(e,t,s,r)}};var Ae=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Ae(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(p=>[p.id,p])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),c=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=me(s.exchangeFee),c=r.plus(i),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let S=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(S)&&p.push("MaxOutRatioExceeded");let w=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(w)&&p.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:r,amountOut:t,feePct:a,errors:p}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=me(s.exchangeFee),c=r.minus(i),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let S=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(S)&&p.push("MaxInRatioExceeded");let w=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(w)&&p.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:a,errors:p}}calculateInGivenOut(e,t){let s=Se.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?k:r}calculateOutGivenIn(e,t){let s=Se.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?k:r}spotPriceInGivenOut(e){let t=Se.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),$(ne,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=Se.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),$(ne,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=Se.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(s)}};var Ue=class{static get(e){switch(e.type){case"Xyk":return Ae.fromPool(e);case"Omnipool":return ve.fromPool(e);case"Lbp":return Be.fromPool(e);case"Stableswap":return Ie.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Fe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ye,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),a=this.getPaths(e,null,r,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(a)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,origin:r.origin,meta:r.meta}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(c=>this.validPath(c,s)).map(c=>this.toHops(c,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,Ue.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let a=t.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function ws(u,e){return u.minus(e).abs().div(u.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ze(u,e){return u.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Mt(u,e){return ne.minus(e.div(u)).multipliedBy(100).decimalPlaces(2)}function Dt(u,e){return e.div(u).minus(ne).multipliedBy(100).decimalPlaces(2)}var Qe=class extends Fe{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,a=r[r.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[s,r]}}getPoolFeeRange(e){let t=e.min?me(e.min):void 0,s=e.max?me(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new De(e,t);let p;if(r)p=await this.toSellSwaps(s,r,a);else{let _=c.map(async n=>await this.toSellSwaps(s,n,a)),X=await Promise.all(_);p=this.findBestSellRoute(X)}let S=p[0],w=p[p.length-1],B=this.isDirectTrade(p),F=p.map(_=>_.spotPrice.shiftedBy(-1*_.assetOutDecimals)).reduce((_,X)=>_.multipliedBy(X)),L=$(F,w.assetOutDecimals),T=B?w.calculatedOut:this.calculateDelta0Y(S.amountIn,p,a),G=w.amountOut,D=B?w.tradeFeePct:Mt(T,G).toNumber(),K=T.minus(G),x=this.getRouteFeeRange(p),Z=S.amountIn.shiftedBy(-1*S.assetInDecimals).multipliedBy(L),oe=ze(T,Z),Ne=_=>this.poolService.buildSellTx(e,t,S.amountIn,_,p.map(X=>X));return{type:"Sell",amountIn:S.amountIn,amountOut:w.amountOut,spotPrice:L,tradeFee:K,tradeFeePct:D,tradeFeeRange:x,priceImpactPct:oe.toNumber(),swaps:p,toTx:Ne,toHuman(){return{type:"Sell",amountIn:j(S.amountIn,S.assetInDecimals),amountOut:j(w.amountOut,w.assetOutDecimals),spotPrice:j(L,w.assetOutDecimals),tradeFee:j(K,w.assetOutDecimals),tradeFeePct:D,tradeFeeRange:x,priceImpactPct:oe.toNumber(),swaps:p.map(_=>_.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let p=c.parsePair(a.assetIn,a.assetOut),S;i>0?S=r[i-1]:S=e;let w=c.calculateOutGivenIn(p,S);r.push(w)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let p=c.parsePair(a.assetIn,a.assetOut),S;i>0?S=r[i-1].amountOut:S=$(I(e),p.decimalsIn).decimalPlaces(0,1);let w=await this.poolService.getPoolFees(p.assetOut,c),{amountOut:B,calculatedOut:F,feePct:L,errors:T}=c.validateAndSell(p,S,w),G=this.getPoolFeeRange(w),D=c.spotPriceOutGivenIn(p),K=S.shiftedBy(-1*p.decimalsIn).multipliedBy(D),x=ze(F,K);r.push({...a,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountIn:S,calculatedOut:F,amountOut:B,spotPrice:D,tradeFeePct:L,tradeFeeRange:G,priceImpactPct:x.toNumber(),errors:T,toHuman(){return{...a,amountIn:j(S,p.decimalsIn),calculatedOut:j(F,p.decimalsOut),amountOut:j(B,p.decimalsOut),spotPrice:j(D,p.decimalsOut),tradeFeePct:L,tradeFeeRange:G,priceImpactPct:x.toNumber(),errors:T}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(x=>x.tokens.find(Z=>Z.id===e)).filter(x=>!!x).sort((x,Z)=>Number(Z.balance)-Number(x.balance)),{balance:c,decimals:p}=a[0],w=I(c).shiftedBy(-1*p).div(100).multipliedBy(.1),B=i.map(async x=>await this.toSellSwaps(w,x,r)),F=await Promise.all(B),L=this.findBestSellRoute(F),T=await this.toSellSwaps("1",L,r),G=T.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,Z)=>x.multipliedBy(Z)),D=T[T.length-1].assetOutDecimals;return{amount:$(G,D),decimals:D}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,a=r[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new De(e,t);let p;if(r)p=await this.toBuySwaps(s,r,a);else{let _=c.map(async n=>await this.toBuySwaps(s,n,a)),X=await Promise.all(_);p=this.findBestBuyRoute(X)}let S=p[p.length-1],w=p[0],B=this.isDirectTrade(p),F=p.map(_=>_.spotPrice.shiftedBy(-1*_.assetInDecimals)).reduce((_,X)=>_.multipliedBy(X)),L=$(F,w.assetInDecimals),T=B?w.calculatedIn:this.calculateDelta0X(S.amountOut,p,a),G=w.amountIn,D=B?w.tradeFeePct:Dt(T,G).toNumber(),K=G.minus(T),x=this.getRouteFeeRange(p),Z=S.amountOut.shiftedBy(-1*S.assetOutDecimals).multipliedBy(L),oe;T.isZero()?oe=-100:oe=ze(Z,T).toNumber();let Ne=_=>this.poolService.buildBuyTx(e,t,S.amountOut,_,p.map(X=>X));return{type:"Buy",amountOut:S.amountOut,amountIn:w.amountIn,spotPrice:L,tradeFee:K,tradeFeePct:D,tradeFeeRange:x,priceImpactPct:oe,swaps:p,toTx:Ne,toHuman(){return{type:"Buy",amountOut:j(S.amountOut,S.assetOutDecimals),amountIn:j(w.amountIn,w.assetInDecimals),spotPrice:j(L,w.assetInDecimals),tradeFee:j(K,w.assetInDecimals),tradeFeePct:D,tradeFeeRange:x,priceImpactPct:oe,swaps:p.map(_=>_.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let p=c.parsePair(a.assetIn,a.assetOut),S;i==t.length-1?S=e:S=r[0];let w=c.calculateInGivenOut(p,S);r.unshift(w)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let p=c.parsePair(a.assetIn,a.assetOut),S;i==t.length-1?S=$(I(e),p.decimalsOut).decimalPlaces(0,1):S=r[0].amountIn;let w=await this.poolService.getPoolFees(p.assetOut,c),{amountIn:B,calculatedIn:F,feePct:L,errors:T}=c.validateAndBuy(p,S,w),G=this.getPoolFeeRange(w),D=c.spotPriceInGivenOut(p),K=S.shiftedBy(-1*p.decimalsOut).multipliedBy(D),x;F.isZero()?x=-100:x=ze(K,F).toNumber(),r.unshift({...a,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountOut:S,calculatedIn:F,amountIn:B,spotPrice:D,tradeFeePct:L,tradeFeeRange:G,priceImpactPct:x,errors:T,toHuman(){return{...a,amountOut:j(S,p.decimalsOut),calculatedIn:j(F,p.decimalsIn),amountIn:j(B,p.decimalsIn),spotPrice:j(D,p.decimalsIn),tradeFeePct:L,tradeFeeRange:G,priceImpactPct:x,errors:T}}})}return r}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
|
package/build/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Ye=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var $t=5,Ee=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new Ye,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let u=i.dequeue();if(u==null||u.length>$t)return r;let c=u[u.length-1];(s===null||c[0]===s)&&r.push(u),e.get(c[0])?.forEach(w=>{if(this.isNotVisited(w,u)){let B=[...u];B.push(w),i.enqueue(B)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,a]of t){let u=parseInt(i),c=parseInt(a);s.get(u)?.push([c,r])}return s}};function pt(p){let e={};for(let t of p){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let i=0;i<s;i++){if(r==i)continue;let a=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(a)}}}return e}var Re=class{getProposals(e,t,s){let r=pt(s),i=Object.keys(r),a=i.map(w=>r[w]).flat(),u=new Ee,c=u.buildAndPopulateGraph(i,a),y=u.findPaths(c,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let a=s[i],u=s[i+1];if(u==null)break;r.push(this.toEdge(a,u))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var Jt=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,mt=Math.ceil,ne=Math.floor,V="[BigNumber Error] ",wt=V+"Number primitive has more than 15 significant digits: ",ue=1e14,N=14,ht=9007199254740991,gt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],be=1e7,W=1e9;function Bt(p){var e,t,s,r=x.prototype={constructor:x,toString:null,valueOf:null},i=new x(1),a=20,u=4,c=-7,y=21,w=-1e7,B=1e7,F=!1,R=1,T=0,C={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},M="0123456789abcdefghijklmnopqrstuvwxyz",J=!0;function x(n,o){var l,P,h,d,S,m,g,b,f=this;if(!(f instanceof x))return new x(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<w?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((m=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,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(!Jt.test(b=String(n)))return s(f,b,m);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(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(G(o,2,M.length,"Base"),o==10&&J)return f=new x(n),_(f,a+f.e+1,u);if(b=String(n),m=typeof n=="number"){if(n*0!=0)return s(f,b,m,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(wt+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=M.slice(0,o),d=S=0,g=b.length;S<g;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=g;continue}}else if(!h&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){h=!0,S=-1,d=0;continue}return s(f,String(n),m,o)}m=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(g=b.length;b.charCodeAt(--g)===48;);if(b=b.slice(S,++g)){if(g-=S,m&&x.DEBUG&&g>15&&(n>ht||n!==ne(n)))throw Error(wt+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<w)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%N,d<0&&(S+=N),S<g){for(S&&f.c.push(+b.slice(0,S)),g-=N;S<g;)f.c.push(+b.slice(S,S+=N));S=N-(b=b.slice(S)).length}else S-=g;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}x.clone=Bt,x.ROUND_UP=0,x.ROUND_DOWN=1,x.ROUND_CEIL=2,x.ROUND_FLOOR=3,x.ROUND_HALF_UP=4,x.ROUND_HALF_DOWN=5,x.ROUND_HALF_EVEN=6,x.ROUND_HALF_CEIL=7,x.ROUND_HALF_FLOOR=8,x.EUCLID=9,x.config=x.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],G(l,0,W,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],G(l,0,8,o),u=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(G(l[0],-W,0,o),G(l[1],0,W,o),c=l[0],y=l[1]):(G(l,-W,W,o),c=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)G(l[0],-W,-1,o),G(l[1],1,W,o),w=l[0],B=l[1];else if(G(l,-W,W,o),l)w=-(B=l<0?-l:l);else throw Error(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],G(l,0,9,o),R=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],G(l,0,W,o),T=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")C=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))J=l.slice(0,10)=="0123456789",M=l;else throw Error(V+o+" invalid: "+l)}else throw Error(V+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:u,EXPONENTIAL_AT:[c,y],RANGE:[w,B],CRYPTO:F,MODULO_MODE:R,POW_PRECISION:T,FORMAT:C,ALPHABET:M}},x.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!x.DEBUG)return!0;var o,l,P=n.c,h=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&h>=-W&&h<=W&&h===ne(h)){if(P[0]===0){if(h===0&&P.length===1)return!0;break e}if(o=(h+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>=ue||l!==ne(l))break e;if(l!==0)return!0}}}else if(P===null&&h===null&&(d===null||d===1||d===-1))return!0;throw Error(V+"Invalid BigNumber: "+n)},x.maximum=x.max=function(){return se(arguments,-1)},x.minimum=x.min=function(){return se(arguments,1)},x.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ne(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,h,d,S,m,g=0,b=[],f=new x(i);if(l==null?l=a:G(l,0,W),S=mt(l/N),F)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));g<S;)m=P[g]*131072+(P[g+1]>>>11),m>=9e15?(h=crypto.getRandomValues(new Uint32Array(2)),P[g]=h[0],P[g+1]=h[1]):(b.push(m%1e14),g+=2);g=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);g<S;)m=(P[g]&31)*281474976710656+P[g+1]*1099511627776+P[g+2]*4294967296+P[g+3]*16777216+(P[g+4]<<16)+(P[g+5]<<8)+P[g+6],m>=9e15?crypto.randomBytes(7).copy(P,g):(b.push(m%1e14),g+=7);g=S/7}else throw F=!1,Error(V+"crypto unavailable");if(!F)for(;g<S;)m=o(),m<9e15&&(b[g++]=m%1e14);for(S=b[--g],l%=N,S&&l&&(m=gt[N-l],b[g]=ne(S/m)*m);b[g]===0;b.pop(),g--);if(g<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=N);for(g=1,m=b[0];m>=10;m/=10,g++);g<N&&(d-=N-g)}return f.e=d,f.c=b,f}}(),x.sum=function(){for(var n=1,o=arguments,l=new x(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,h,d){for(var S,m=[0],g,b=0,f=l.length;b<f;){for(g=m.length;g--;m[g]*=P);for(m[0]+=d.indexOf(l.charAt(b++)),S=0;S<m.length;S++)m[S]>h-1&&(m[S+1]==null&&(m[S+1]=0),m[S+1]+=m[S]/h|0,m[S]%=h)}return m.reverse()}return function(l,P,h,d,S){var m,g,b,f,O,v,A,k,q=l.indexOf("."),X=a,E=u;for(q>=0&&(f=T,T=0,l=l.replace(".",""),k=new x(P),v=k.pow(l.length-q),T=f,k.c=o(de(ie(v.c),v.e,"0"),10,h,n),k.e=k.c.length),A=o(l,P,h,S?(m=M,n):(m=n,M)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return m.charAt(0);if(q<0?--b:(v.c=A,v.e=b,v.s=d,v=e(v,k,X,E,h),A=v.c,O=v.r,b=v.e),g=b+X+1,q=A[g],f=h/2,O=O||g<0||A[g+1]!=null,O=E<4?(q!=null||O)&&(E==0||E==(v.s<0?3:2)):q>f||q==f&&(E==4||O||E==6&&A[g-1]&1||E==(v.s<0?8:7)),g<1||!A[0])l=O?de(m.charAt(1),-X,m.charAt(0)):m.charAt(0);else{if(A.length=g,O)for(--h;++A[--g]>h;)A[g]=0,g||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(q=0,l="";q<=f;l+=m.charAt(A[q++]));l=de(l,b,m.charAt(0))}return l}}(),e=function(){function n(P,h,d){var S,m,g,b,f=0,O=P.length,v=h%be,A=h/be|0;for(P=P.slice();O--;)g=P[O]%be,b=P[O]/be|0,S=A*g+b*v,m=v*g+S%be*be+f,f=(m/d|0)+(S/be|0)+A*b,P[O]=m%d;return f&&(P=[f].concat(P)),P}function o(P,h,d,S){var m,g;if(d!=S)g=d>S?1:-1;else for(m=g=0;m<d;m++)if(P[m]!=h[m]){g=P[m]>h[m]?1:-1;break}return g}function l(P,h,d,S){for(var m=0;d--;)P[d]-=m,m=P[d]<h[d]?1:0,P[d]=m*S+P[d]-h[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,h,d,S,m){var g,b,f,O,v,A,k,q,X,E,D,j,We,ut,ct,me,_e,re=P.s==h.s?1:-1,Q=P.c,H=h.c;if(!Q||!Q[0]||!H||!H[0])return new x(!P.s||!h.s||(Q?H&&Q[0]==H[0]:!H)?NaN:Q&&Q[0]==0||!H?re*0:re/0);for(q=new x(re),X=q.c=[],b=P.e-h.e,re=d+b+1,m||(m=ue,b=oe(P.e/N)-oe(h.e/N),re=re/N|0),f=0;H[f]==(Q[f]||0);f++);if(H[f]>(Q[f]||0)&&b--,re<0)X.push(1),O=!0;else{for(ut=Q.length,me=H.length,f=0,re+=2,v=ne(m/(H[0]+1)),v>1&&(H=n(H,v,m),Q=n(Q,v,m),me=H.length,ut=Q.length),We=me,E=Q.slice(0,me),D=E.length;D<me;E[D++]=0);_e=H.slice(),_e=[0].concat(_e),ct=H[0],H[1]>=m/2&&ct++;do{if(v=0,g=o(H,E,me,D),g<0){if(j=E[0],me!=D&&(j=j*m+(E[1]||0)),v=ne(j/ct),v>1)for(v>=m&&(v=m-1),A=n(H,v,m),k=A.length,D=E.length;o(A,E,k,D)==1;)v--,l(A,me<k?_e:H,k,m),k=A.length,g=1;else v==0&&(g=v=1),A=H.slice(),k=A.length;if(k<D&&(A=[0].concat(A)),l(E,A,D,m),D=E.length,g==-1)for(;o(H,E,me,D)<1;)v++,l(E,me<D?_e:H,D,m),D=E.length}else g===0&&(v++,E=[0]);X[f++]=v,E[0]?E[D++]=Q[We]||0:(E=[Q[We]],D=1)}while((We++<ut||E[0]!=null)&&re--);O=E[0]!=null,X[0]||X.splice(0,1)}if(m==ue){for(f=1,re=X[0];re>=10;re/=10,f++);_(q,d+(q.e=f+b*N-1)+1,S,O)}else q.e=b,q.r=+O;return q}}();function K(n,o,l,P){var h,d,S,m,g;if(l==null?l=u:G(l,0,8),!n.c)return n.toString();if(h=n.c[0],S=n.e,o==null)g=ie(n.c),g=P==1||P==2&&(S<=c||S>=y)?Je(g,S):de(g,S,"0");else if(n=_(new x(n),o,l),d=n.e,g=ie(n.c),m=g.length,P==1||P==2&&(o<=d||d<=c)){for(;m<o;g+="0",m++);g=Je(g,d)}else if(o-=S,g=de(g,d,"0"),d+1>m){if(--o>0)for(g+=".";o--;g+="0");}else if(o+=d-m,o>0)for(d+1==m&&(g+=".");o--;g+="0");return n.s<0&&h?"-"+g:g}function se(n,o){for(var l,P,h=1,d=new x(n[0]);h<n.length;h++)P=new x(n[h]),(!P.s||(l=xe(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function ye(n,o,l){for(var P=1,h=o.length;!o[--h];o.pop());for(h=o[0];h>=10;h/=10,P++);return(l=P+l*N-1)>B?n.c=n.e=null:l<w?n.c=[n.e=0]:(n.e=l,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,h=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,m,g){var b,f=m?S:S.replace(h,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!m&&(f=f.replace(n,function(O,v,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!g||g==b?v:O}),g&&(b=g,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new x(f,b);if(x.DEBUG)throw Error(V+"Not a"+(g?" base "+g:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function _(n,o,l,P){var h,d,S,m,g,b,f,O=n.c,v=gt;if(O){e:{for(h=1,m=O[0];m>=10;m/=10,h++);if(d=o-h,d<0)d+=N,S=o,g=O[b=0],f=ne(g/v[h-S-1]%10);else if(b=mt((d+1)/N),b>=O.length)if(P){for(;O.length<=b;O.push(0));g=f=0,h=1,d%=N,S=d-N+1}else break e;else{for(g=m=O[b],h=1;m>=10;m/=10,h++);d%=N,S=d-N+h,f=S<0?0:ne(g/v[h-S-1]%10)}if(P=P||o<0||O[b+1]!=null||(S<0?g:g%v[h-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?g/v[h-S]:0:O[b-1])%10&1||l==(n.s<0?8:7)),o<1||!O[0])return O.length=0,P?(o-=n.e+1,O[0]=v[(N-o%N)%N],n.e=-o||0):O[0]=n.e=0,n;if(d==0?(O.length=b,m=1,b--):(O.length=b+1,m=v[N-d],O[b]=S>0?ne(g/v[h-S]%v[S])*m:0),P)for(;;)if(b==0){for(d=1,S=O[0];S>=10;S/=10,d++);for(S=O[0]+=m,m=1;S>=10;S/=10,m++);d!=m&&(n.e++,O[0]==ue&&(O[0]=1));break}else{if(O[b]+=m,O[b]!=ue)break;O[b--]=0,m=1}for(d=O.length;O[--d]===0;O.pop());}n.e>B?n.c=n.e=null:n.e<w&&(n.c=[n.e=0])}return n}function U(n){var o,l=n.e;return l===null?n.toString():(o=ie(n.c),o=l<=c||l>=y?Je(o,l):de(o,l,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new x(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return xe(this,new x(n,o))},r.decimalPlaces=r.dp=function(n,o){var l,P,h,d=this;if(n!=null)return G(n,0,W),o==null?o=u:G(o,0,8),_(new x(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((h=l.length-1)-oe(this.e/N))*N,h=l[h])for(;h%10==0;h/=10,P--);return P<0&&(P=0),P},r.dividedBy=r.div=function(n,o){return e(this,new x(n,o),a,u)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new x(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var l,P,h,d,S,m,g,b,f,O=this;if(n=new x(n),n.c&&!n.isInteger())throw Error(V+"Exponent not an integer: "+U(n));if(o!=null&&(o=new x(o)),m=n.e>14,!O.c||!O.c[0]||O.c[0]==1&&!O.e&&O.c.length==1||!n.c||!n.c[0])return f=new x(Math.pow(+U(O),m?n.s*(2-$e(n)):+U(n))),o?f.mod(o):f;if(g=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new x(NaN);P=!g&&O.isInteger()&&o.isInteger(),P&&(O=O.mod(o))}else{if(n.e>9&&(O.e>0||O.e<-1||(O.e==0?O.c[0]>1||m&&O.c[1]>=24e7:O.c[0]<8e13||m&&O.c[0]<=9999975e7)))return d=O.s<0&&$e(n)?-0:0,O.e>-1&&(d=1/d),new x(g?1/d:d);T&&(d=mt(T/N+2))}for(m?(l=new x(.5),g&&(n.s=1),b=$e(n)):(h=Math.abs(+U(n)),b=h%2),f=new x(i);;){if(b){if(f=f.times(O),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(h){if(h=ne(h/2),h===0)break;b=h%2}else if(n=n.times(l),_(n,n.e+1,1),n.e>14)b=$e(n);else{if(h=+U(n),h===0)break;b=h%2}O=O.times(O),d?O.c&&O.c.length>d&&(O.c.length=d):P&&(O=O.mod(o))}return P?f:(g&&(f=i.div(f)),o?f.mod(o):d?_(f,T,u,S):f)},r.integerValue=function(n){var o=new x(this);return n==null?n=u:G(n,0,8),_(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return xe(this,new x(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return xe(this,new x(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=xe(this,new x(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&oe(this.e/N)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return xe(this,new x(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=xe(this,new x(n,o)))===-1||o===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(n,o){var l,P,h,d,S=this,m=S.s;if(n=new x(n,o),o=n.s,!m||!o)return new x(NaN);if(m!=o)return n.s=-o,S.plus(n);var g=S.e/N,b=n.e/N,f=S.c,O=n.c;if(!g||!b){if(!f||!O)return f?(n.s=-o,n):new x(O?S:NaN);if(!f[0]||!O[0])return O[0]?(n.s=-o,n):new x(f[0]?S:u==3?-0:0)}if(g=oe(g),b=oe(b),f=f.slice(),m=g-b){for((d=m<0)?(m=-m,h=f):(b=g,h=O),h.reverse(),o=m;o--;h.push(0));h.reverse()}else for(P=(d=(m=f.length)<(o=O.length))?m:o,m=o=0;o<P;o++)if(f[o]!=O[o]){d=f[o]<O[o];break}if(d&&(h=f,f=O,O=h,n.s=-n.s),o=(P=O.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=ue-1;P>m;){if(f[--P]<O[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=ue}f[P]-=O[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?ye(n,f,b):(n.s=u==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var l,P,h=this;return n=new x(n,o),!h.c||!n.s||n.c&&!n.c[0]?new x(NaN):!n.c||h.c&&!h.c[0]?new x(h):(R==9?(P=n.s,n.s=1,l=e(h,n,0,3),n.s=P,l.s*=P):l=e(h,n,0,R),n=h.minus(l.times(n)),!n.c[0]&&R==1&&(n.s=h.s),n)},r.multipliedBy=r.times=function(n,o){var l,P,h,d,S,m,g,b,f,O,v,A,k,q,X,E=this,D=E.c,j=(n=new x(n,o)).c;if(!D||!j||!D[0]||!j[0])return!E.s||!n.s||D&&!D[0]&&!j||j&&!j[0]&&!D?n.c=n.e=n.s=null:(n.s*=E.s,!D||!j?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=oe(E.e/N)+oe(n.e/N),n.s*=E.s,g=D.length,O=j.length,g<O&&(k=D,D=j,j=k,h=g,g=O,O=h),h=g+O,k=[];h--;k.push(0));for(q=ue,X=be,h=O;--h>=0;){for(l=0,v=j[h]%X,A=j[h]/X|0,S=g,d=h+S;d>h;)b=D[--S]%X,f=D[S]/X|0,m=A*b+f*v,b=v*b+m%X*X+k[d]+l,l=(b/q|0)+(m/X|0)+A*f,k[d--]=b%q;k[d]=l}return l?++P:k.splice(0,1),ye(n,k,P)},r.negated=function(){var n=new x(this);return n.s=-n.s||null,n},r.plus=function(n,o){var l,P=this,h=P.s;if(n=new x(n,o),o=n.s,!h||!o)return new x(NaN);if(h!=o)return n.s=-o,P.minus(n);var d=P.e/N,S=n.e/N,m=P.c,g=n.c;if(!d||!S){if(!m||!g)return new x(h/0);if(!m[0]||!g[0])return g[0]?n:new x(m[0]?P:h*0)}if(d=oe(d),S=oe(S),m=m.slice(),h=d-S){for(h>0?(S=d,l=g):(h=-h,l=m),l.reverse();h--;l.push(0));l.reverse()}for(h=m.length,o=g.length,h-o<0&&(l=g,g=m,m=l,o=h),h=0;o;)h=(m[--o]=m[o]+g[o]+h)/ue|0,m[o]=ue===m[o]?0:m[o]%ue;return h&&(m=[h].concat(m),++S),ye(n,m,S)},r.precision=r.sd=function(n,o){var l,P,h,d=this;if(n!=null&&n!==!!n)return G(n,1,W),o==null?o=u:G(o,0,8),_(new x(d),n,o);if(!(l=d.c))return null;if(h=l.length-1,P=h*N+1,h=l[h]){for(;h%10==0;h/=10,P--);for(h=l[0];h>=10;h/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return G(n,-ht,ht),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,l,P,h,d=this,S=d.c,m=d.s,g=d.e,b=a+4,f=new x("0.5");if(m!==1||!S||!S[0])return new x(!m||m<0&&(!S||S[0])?NaN:S?d:1/0);if(m=Math.sqrt(+U(d)),m==0||m==1/0?(o=ie(S),(o.length+g)%2==0&&(o+="0"),m=Math.sqrt(+o),g=oe((g+1)/2)-(g<0||g%2),m==1/0?o="5e"+g:(o=m.toExponential(),o=o.slice(0,o.indexOf("e")+1)+g),l=new x(o)):l=new x(m+""),l.c[0]){for(g=l.e,m=g+b,m<3&&(m=0);;)if(h=l,l=f.times(h.plus(e(d,h,b,1))),ie(h.c).slice(0,m)===(o=ie(l.c)).slice(0,m))if(l.e<g&&--m,o=o.slice(m-3,m+1),o=="9999"||!P&&o=="4999"){if(!P&&(_(h,h.e+a+2,0),h.times(h).eq(d))){l=h;break}b+=4,m+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(_(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return _(l,l.e+a+1,u,n)},r.toExponential=function(n,o){return n!=null&&(G(n,0,W),n++),K(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(G(n,0,W),n=n+this.e+1),K(this,n,o)},r.toFormat=function(n,o,l){var P,h=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(V+"Argument not an object: "+l);if(P=h.toFixed(n,o),h.c){var d,S=P.split("."),m=+l.groupSize,g=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],O=S[1],v=h.s<0,A=v?f.slice(1):f,k=A.length;if(g&&(d=m,m=g,g=d,k-=d),m>0&&k>0){for(d=k%m||m,f=A.substr(0,d);d<k;d+=m)f+=b+A.substr(d,m);g>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=O?f+(l.decimalSeparator||"")+((g=+l.fractionGroupSize)?O.replace(new RegExp("\\d{"+g+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):O):f}return(l.prefix||"")+P+(l.suffix||"")},r.toFraction=function(n){var o,l,P,h,d,S,m,g,b,f,O,v,A=this,k=A.c;if(n!=null&&(m=new x(n),!m.isInteger()&&(m.c||m.s!==1)||m.lt(i)))throw Error(V+"Argument "+(m.isInteger()?"out of range: ":"not an integer: ")+U(m));if(!k)return new x(A);for(o=new x(i),b=l=new x(i),P=g=new x(i),v=ie(k),d=o.e=v.length-A.e-1,o.c[0]=gt[(S=d%N)<0?N+S:S],n=!n||m.comparedTo(o)>0?d>0?o:b:m,S=B,B=1/0,m=new x(v),g.c[0]=0;f=e(m,o,0,1),h=l.plus(f.times(P)),h.comparedTo(n)!=1;)l=P,P=h,b=g.plus(f.times(h=b)),g=h,o=m.minus(f.times(h=o)),m=h;return h=e(n.minus(l),P,0,1),g=g.plus(h.times(b)),l=l.plus(h.times(P)),g.s=b.s=A.s,d=d*2,O=e(b,P,d,u).minus(A).abs().comparedTo(e(g,l,d,u).minus(A).abs())<1?[b,P]:[g,l],B=S,O},r.toNumber=function(){return+U(this)},r.toPrecision=function(n,o){return n!=null&&G(n,1,W),K(this,n,o,2)},r.toString=function(n){var o,l=this,P=l.s,h=l.e;return h===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=h<=c||h>=y?Je(ie(l.c),h):de(ie(l.c),h,"0"):n===10&&J?(l=_(new x(l),a+h+1,u),o=de(ie(l.c),l.e,"0")):(G(n,2,M.length,"Base"),o=t(de(ie(l.c),h,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return U(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,p!=null&&x.set(p),x}function oe(p){var e=p|0;return p>0||p===e?e:e-1}function ie(p){for(var e,t,s=1,r=p.length,i=p[0]+"";s<r;){for(e=p[s++]+"",t=N-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function xe(p,e){var t,s,r=p.c,i=e.c,a=p.s,u=e.s,c=p.e,y=e.e;if(!a||!u)return null;if(t=r&&!r[0],s=i&&!i[0],t||s)return t?s?0:-u:a;if(a!=u)return a;if(t=a<0,s=c==y,!r||!i)return s?0:!r^t?1:-1;if(!s)return c>y^t?1:-1;for(u=(c=r.length)<(y=i.length)?c:y,a=0;a<u;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return c==y?0:c>y^t?1:-1}function G(p,e,t,s){if(p<e||p>t||p!==ne(p))throw Error(V+(s||"Argument")+(typeof p=="number"?p<e||p>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(p))}function $e(p){var e=p.c.length-1;return oe(p.e/N)==e&&p.c[e]%2!=0}function Je(p,e){return(p.length>1?p.charAt(0)+"."+p.slice(1):p)+(e<0?"e":"e+")+e}function de(p,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);p=r+p}else if(s=p.length,++e>s){for(r=t,e-=s;--e;r+=t);p+=r}else e<s&&(p=p.slice(0,e)+"."+p.slice(e));return p}var fe=Bt();var jt=12;fe.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:jt});var L=I(0),ae=I(1),pr=I("Infinity");function Y(p,e){let t=new fe(e.toString()),s=new fe(10).pow(t);return p.times(s)}function I(p){return new fe(p.toString())}var te=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(te||{}),ke=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(ke||{}),vt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(vt||{});import{calculate_in_given_out as Kt,calculate_out_given_in as Qt,calculate_linear_weights as Vt,calculate_pool_trade_fee as Zt,get_spot_price as es}from"@galacticcouncil/math-lbp";var ce=class{static getSpotPrice(e,t,s,r,i){return es(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return Kt(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return Qt(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return Vt(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Zt(e,t,s)}};import{encodeAddress as ts}from"@polkadot/util-crypto";import{stringToU8a as ss}from"@polkadot/util";var Le=18,dt=15,Se="0",br=12,Sr=2034,Me=63,yr=2090,ft=1e3,je=ts(ss("modlomnipool".padEnd(32,"\0")),Me);function It(p,e){let t;return JSON.stringify(p,(s,r)=>(r&&r[e]&&(t=r),r)),t}function Or(p,e,t){let s;return JSON.stringify(p,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";var Ie=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var De=class extends Ie{SUPPORTED_TYPES=["StableSwap","Bond","Token","External"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getToken(e,t,s,r){if(e==Se){let B=this.api.consts.balances.existentialDeposit;return{id:Se,name:this.chainToken,symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:B.toString()}}let{name:i,assetType:a,isSufficient:u,existentialDeposit:c}=t,{symbol:y,decimals:w}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:y,decimals:w,icon:y,type:a.toHuman(),isSufficient:u?u.toHuman():!0,origin:this.parseLocation("parachain",r),existentialDeposit:c.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:u,isSufficient:c,existentialDeposit:y}=t,{symbol:w,decimals:B}=this.getToken(i.toString(),t,s),F=a.toNumber(),R=new Intl.DateTimeFormat("en-GB"),T=[w,"Bond",R.format(F)].join(" ");return{id:e,name:T,symbol:w+"b",decimals:B,icon:w,type:u.toString(),isSufficient:c.toHuman(),existentialDeposit:y.toString()}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:u,assetType:c,isSufficient:y,existentialDeposit:w}=t,F=i.map(C=>C.toString()).map(C=>{let{symbol:M}=this.getToken(C,t,s);return[C,M]}),R=Object.fromEntries(F),T=Object.values(R);return{id:e,name:T.join(", "),symbol:u?.isSome?u.toHuman():a.toHuman(),decimals:18,icon:T.join("/"),type:c.toString(),isSufficient:y.toHuman(),existentialDeposit:w.toString(),meta:R}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=this.parseLocation("generalIndex",r),u=s?.find(c=>c.id===a?.toString());return u?{...i,decimals:u.decimals,name:u.name,symbol:u.symbol,icon:u.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:a}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e){let[t,s,r,i,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),u=this.getSupportedAssets(t),c=this.normalizeMetadata(u,a);return u.map(([{args:[y]},w])=>{let B=w.unwrap(),F=s.get(y.toString()),{assetType:R}=B;switch(R.toString()){case"Bond":let T=i.get(y.toString());return this.getBond(y.toString(),B,c,T);case"StableSwap":let C=r.get(y.toString());return this.getShares(y.toString(),B,c,C);case"External":return this.getExternal(y.toString(),B,e,F);default:return this.getToken(y.toString(),B,c,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 s=It(t.toJSON(),e);return s&&s[e]}else return}};var Ce=class extends Ie{constructor(e){super(e)}async getBalance(e,t){return t===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:s,reserved:r,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeBalance(e,t,s){let r=t.filter(i=>i!==Se).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach(({free:a,reserved:u,frozen:c},y)=>{let w=this.calculateFreeBalance({free:a,feeFrozen:u,frozen:c}),B=r[y][1];s(B,w)})})}async subscribeTokenBalance(e,t,s){let r=t.filter(i=>i!==Se).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach((a,u)=>{let c=this.calculateFreeBalance(a),y=r[u][1];s(y,c)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(Se,this.calculateFreeBalance(s)))}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,a=new fe(t),u=new fe(s||i),c=new fe(r||0),y=u.gt(c)?u:c;return a.minus(y)}};var he=class extends Ce{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async s=>{let r=[await this.subscribePoolChange(s),await this.subscribeTokensPoolBalance(s),await this.subscribeSystemPoolBalance(s)];if(this.hasShareAsset(s)){let i=await this.subscribeSharePoolBalance(s);r.push(i)}return this.subscribeLog(s),r});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,s)=>t.id!==s))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance(je,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(s,r){let i=e.tokens.findIndex(a=>a.id==s);i>=0&&t(e,s)&&(e.tokens[i].balance=r.toString())}}};var Ke=class extends he{MAX_FINAL_WEIGHT=Y(I(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,a])=>this.isActivePool(a.unwrap(),s)).map(async([{args:[i]},a])=>{let u=a.unwrap(),c=i.toString(),y=await this.getPoolDelta(c,u,s.toString());return this.poolsData.set(i.toString(),u),{address:c,type:"Lbp",fee:u.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let a=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(u=>u.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:a,initialWeight:u,finalWeight:c,repayTarget:y,feeCollector:w}=t,B=ce.calculateLinearWeights(r.toString(),i.toString(),u.toString(),c.toString(),s),[F,R]=a,T=F.toString(),C=I(B),M=R.toString(),J=this.MAX_FINAL_WEIGHT.minus(I(C)),[x,K,se]=await Promise.all([this.isRepayFeeApplied(T,y.toString(),w.toString()),this.getBalance(e,T),this.getBalance(e,M)]);return{repayFeeApply:x,tokens:[{id:T,weight:C,balance:K.toString()},{id:M,weight:J,balance:se.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=I(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{encodeAddress as rs}from"@polkadot/util-crypto";import{stringToU8a as is}from"@polkadot/util";function $(p,e){return p.shiftedBy(-1*e).toString()}function le(p){return p[0]/p[1]*100}function Z(p){return p[0]/p[1]}function pe(p){return[p/ft,ft]}var Qe=class extends he{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=s.map(async([{args:[c]},y])=>{let{hubReserve:w,shares:B,tradable:F}=y.unwrap(),R=await this.getBalance(t,c.toString());return{id:c.toString(),hubReserves:I(w.toString()),shares:I(B.toString()),tradeable:F.bits.toNumber(),balance:R.toString()}}),u=await Promise.all(a);return u.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:u,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=await this.api.query.dynamicFees.assetFee(e),r=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=r.minFee.toNumber()+i.minFee.toNumber(),u=r.maxFee.toNumber()+i.maxFee.toNumber();if(s.isSome){let{assetFee:c,protocolFee:y}=s.unwrap();return{assetFee:pe(c.toNumber()),protocolFee:pe(y.toNumber()),min:pe(a),max:pe(u)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:pe(a),max:pe(u)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let a=e.tokens[i];if(r.isNone)return a;let u=r.unwrap();return this.updateTokenState(a,u)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i}=t;return{...e,hubReserves:I(s.toString()),shares:I(r.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return pe(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return pe(t)}getPoolId(){return rs(is("modlomnipool".padEnd(32,"\0")),Me)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var Ve=class extends he{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[a,u]=r.unwrap(),[c,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,u.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:c.toString()},{id:u.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{blake2AsHex as gs,encodeAddress as ds}from"@polkadot/util-crypto";import{calculate_in_given_out as ns,calculate_out_given_in as os,calculate_amplification as as,calculate_add_one_asset as ls,calculate_liquidity_out_one_asset as us,calculate_pool_trade_fee as cs,calculate_shares as ps,calculate_shares_for_amount as ms,pool_account_name as hs}from"@galacticcouncil/math-stableswap";var ee=class{static getPoolAddress(e){return hs(e)}static calculateAmplification(e,t,s,r,i){return as(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return ns(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return ls(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return ms(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return os(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return us(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return ps(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return cs(e,t,s)}};var Ze=class extends he{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},a])=>{let u=a.unwrap(),c=i.toString(),y=this.getPoolAddress(c),[w,B]=await Promise.all([this.getPoolDelta(c,u,s.toString()),this.getPoolTokens(y,c,u)]);return this.stablePools.set(y,u),{address:y,id:c,type:"Stableswap",fee:pe(u.fee.toNumber()),tokens:B,...w,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toNumber(),r=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,r,s.toString());Object.assign(e,i)})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:a,finalBlock:u}=t,c=ee.calculateAmplification(r.toString(),i.toString(),a.toString(),u.toString(),s),y=await this.api.query.tokens.totalIssuance(e);return{amplification:c,totalIssuance:y.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async c=>{let[y,w]=await Promise.all([this.api.query.stableswap.assetTradability(t,c.toString()),this.getBalance(e,c.toString())]);return{id:c.toString(),tradeable:y.bits.toNumber(),balance:w.toString()}}),a=await Promise.all(i),u=await this.api.query.omnipool.assets(t);if(u.isSome){let{tradable:c}=u.unwrap(),y=await this.getBalance(je,t);a.push({id:t,tradeable:c.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),s=ee.getPoolAddress(t);return ds(gs(s),Me)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function Pt(p){return p.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var et=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},At=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ge=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Tt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Ft=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},_t=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var qe=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new De(this.api),this.xykClient=new Ve(this.api),this.omniClient=new Qe(this.api),this.lbpClient=new Ke(this.api),this.stableClient=new Ze(this.api)}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||(this.onChainAssets=await this.assetClient.getOnChainAssets(),this.onChainAssetsLoaded=!0),e.length==0){let a=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(u=>u.isSupported()).map(u=>u.getPools()))).flat();return this.withMetadata(a)}let t=[];e.forEach(i=>{switch(i){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break;case"Stableswap":t.push(this.stableClient.getPools());break}});let r=(await Promise.all(t)).flat();return this.withMetadata(r)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(s=>[s.id,s]));return e.filter(s=>s.type==="Xyk"?s.tokens.every(r=>t.get(r.id)):!0).map(s=>{let r=s.tokens.map(i=>{let a=t.get(i.id);return{...i,...a}});return{...s,tokens:r}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new et(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):a=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),Pt(i));let u=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:u}}buildSellTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):a=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),Pt(i));let u=()=>a;return{hex:a.toHex(),name:"RouterSell",get:u}}};var He=(p,e)=>p===e?0:p==null?e==null?0:-1:e==null?p==null?0:1:typeof p.compare=="function"?p.compare(e):typeof e.compare=="function"?-e.compare(p):p<e?-1:p>e?1:0;var tt=(p,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(p(t)+e(t))}};var fs=tt(()=>"illegal argument(s)"),Et=p=>{throw new fs(p)};var Ps=tt(()=>"index out of bounds"),bt=p=>{throw new Ps(p)},st=(p,e,t)=>(p<e||p>=t)&&bt(p);var Rt=23283064365386963e-26,rt=class{float(e=1){return this.int()*Rt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Rt-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var St=Math.random,yt=class extends rt{int(){return St()*4294967296>>>0}float(e=1){return St()*e}norm(e=1){return(St()-.5)*2*e}},kt=new yt;var Lt=p=>p!=null&&typeof p!="function"&&p.length!==void 0;var Mt=Object.getPrototypeOf({}),it="function",Dt="string",Ae=(p,e)=>{let t;if(p===e)return!0;if(p!=null){if(typeof p.equiv===it)return p.equiv(e)}else return p==e;if(e!=null){if(typeof e.equiv===it)return e.equiv(p)}else return p==e;return typeof p===Dt||typeof e===Dt?!1:(t=Object.getPrototypeOf(p),(t==null||t===Mt)&&(t=Object.getPrototypeOf(e),t==null||t===Mt)?xs(p,e):typeof p!==it&&p.length!==void 0&&typeof e!==it&&e.length!==void 0?bs(p,e):p instanceof Set&&e instanceof Set?Ss(p,e):p instanceof Map&&e instanceof Map?ys(p,e):p instanceof Date&&e instanceof Date?p.getTime()===e.getTime():p instanceof RegExp&&e instanceof RegExp?p.toString()===e.toString():p!==p&&e!==e)},bs=(p,e,t=Ae)=>{let s=p.length;if(s===e.length)for(;s-- >0&&t(p[s],e[s]););return s<0},Ss=(p,e,t=Ae)=>p.size===e.size&&t([...p.keys()].sort(),[...e.keys()].sort()),ys=(p,e,t=Ae)=>p.size===e.size&&t([...p].sort(),[...e].sort()),xs=(p,e,t=Ae)=>{if(Object.keys(p).length!==Object.keys(e).length)return!1;for(let s in p)if(!e.hasOwnProperty(s)||!t(p[s],e[s]))return!1;return!0};var Ct=(p,e)=>p!=null&&typeof p[e]=="function";var Gt=p=>Ct(p,"xform")?p.xform():p;var nt=Symbol(),xt=()=>{};var qt=p=>p!=null&&typeof p[Symbol.iterator]=="function";var ot=class{value;constructor(e){this.value=e}deref(){return this.value}};var at=p=>p instanceof ot;var Ht=p=>p instanceof ot?p.deref():p;function*Ut(p,e){let t=Gt(p)([xt,xt,(s,r)=>r])[2];for(let s of e){let r=t(nt,s);if(at(r)){r=Ht(r.deref()),r!==nt&&(yield r);return}r!==nt&&(yield r)}}var zt=(p,e)=>[p[0],p[1],e];function Ue(p,e){return qt(e)?Ut(Ue(p),e):t=>{let s=t[2];return zt(t,(r,i)=>s(r,p(i)))}}var Ne=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Xt("next",this._head)}reverseIterator(){return Xt("prev",this.tail)}clear(){this.release()}compare(e,t=He){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,a=0;for(;s-- >0&&a===0;)a=t(r.value,i.value),r=r.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof Ne||Lt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!Ae(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||He;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!at(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&bt(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*Xt(p,e){for(;e;)yield e.value,e=e[p]}var ge=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 ge(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 ge}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(st(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(st(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new ge,e)}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let s=this.nthCell(e),r=this.nthCell(t-1),i=a=>({first(){return a.value},next(){return a!==r&&a.next?i(a.next):void 0}});return s?i(s):void 0}shuffle(e,t=kt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&Et("invalid indices: ${from} / ${to}");let i=new ge,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=He){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,a=0;for(let c=0;c<t&&(a++,i=i.next,!!i);c++);let u=t;for(;a>0||u>0&&i;){let c;a===0?(c=i,i=i.next,u--):!i||u===0||e(s.value,i.value)<=0?(c=s,s=s.next,a--):(c=i,i=i.next,u--),this._tail?this._tail.next=c:this._head=c,c.prev=this._tail,this._tail=c}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),st(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new ge;if(t>0)for(;r&&t-- >0;)this.remove(r),i.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let a of s)this.insertBefore(r,a);else for(let a of s)this.push(a);return i}};var Te=class{map;items;opts;_size;constructor(e,t){let s=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=s.map(),this.items=new ge,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ue(e=>[e.k,e],this.items)}keys(){return Ue(e=>e.k,this.items)}values(){return Ue(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new Te(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e);return this._size+=Math.max(0,s-(r?r.value.s:0)),this.ensureSize()&&this.doSetEntry(r,e,t,s),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let s=this.map.get(e);return s?Promise.resolve(this.resetEntry(s)):t().then(r=>this.set(e,r))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,s=this.opts.maxlen;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e&&e(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Ot=class extends qe{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Te(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
-
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Oe=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Oe(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,a,u){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),u=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:u,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let u=this.calculateTradeFee(t,s),c=le(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(u),w=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return w.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:w,calculatedIn:w,amountOut:t,feePct:c,errors:i}}else{let u=this.calculateInGivenOut(e,t),c=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(c)&&i.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let u=this.calculateOutGivenIn(e,t),c=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(c)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:u,amountOut:u,feePct:0,errors:i}}else{let u=this.calculateOutGivenIn(e,t),c=this.calculateTradeFee(u,s),y=le(this.repayFeeApply?s.repayFee:s.exchangeFee),w=u.minus(c),B=e.balanceOut.div(this.maxOutRatio);return w.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:u,amountOut:w,feePct:y,errors:i}}}calculateInGivenOut(e,t){let s=ce.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?L:r}calculateOutGivenIn(e,t){let s=ce.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?L:r}spotPriceInGivenOut(e){let t=ce.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),Y(ae,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=ce.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),Y(ae,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=ce.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(s)}};import{calculate_in_given_out as Os,calculate_lrna_in_given_out as ws,calculate_out_given_in as Bs,calculate_out_given_lrna_in as vs,calculate_pool_trade_fee as Is,calculate_spot_price as As,calculate_lrna_spot_price as Ns,calculate_shares as Ts,calculate_liquidity_out as Fs,calculate_liquidity_lrna_out as _s,calculate_cap_difference as Es,verify_asset_cap as Rs,calculate_liquidity_hub_in as ks,is_sell_allowed as Ls,is_buy_allowed as Ms,is_add_liquidity_allowed as Ds,is_remove_liquidity_allowed as Cs}from"@galacticcouncil/math-omnipool";var z=class{static calculateSpotPrice(e,t,s,r){return As(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return Ns(e,t)}static calculateInGivenOut(e,t,s,r,i,a,u,c,y){return Os(e,t,s,r,i,a,u,c,y)}static calculateLrnaInGivenOut(e,t,s,r,i){return ws(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,a,u,c,y){return Bs(e,t,s,r,i,a,u,c,y)}static calculateOutGivenLrnaIn(e,t,s,r,i){return vs(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Is(e,t,s)}static calculateShares(e,t,s,r){return Ts(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,a,u,c){return Fs(e,t,s,r,i,a,u,c)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,u,c){return _s(e,t,s,r,i,a,u,c)}static calculateCapDifference(e,t,s,r){return Es(e,t,s,r)}static verifyAssetCap(e,t,s,r){return Rs(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return ks(e,t,s,r)}static isSellAllowed(e){return Ls(e)}static isBuyAllowed(e){return Ms(e)}static isAddLiquidityAllowed(e){return Ds(e)}static isRemoveLiquidityAllowed(e){return Cs(e)}};var we=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new we(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),u=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:u,tradeableIn:r.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),u=r===L?L:a.div(r).multipliedBy(100).decimalPlaces(2),c=[],y=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!y||!w)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&c.push("MaxOutRatioExceeded");let F=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(F)&&c.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:u.toNumber(),errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),u=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),c=[],y=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!y||!w)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&c.push("MaxInRatioExceeded");let F=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(F)&&c.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:u.toNumber(),errors:c}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=z.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?Z(s.assetFee).toString():L.toString(),s?Z(s.protocolFee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateLrnaInGivenOut(e,t,s){let r=z.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?Z(s.assetFee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=z.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?Z(s.assetFee).toString():L.toString(),s?Z(s.protocolFee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateOutGivenLrnaIn(e,t,s){let r=z.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?Z(s.assetFee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=z.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=z.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=z.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=z.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}};var Be=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Be(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,i,a,u,c,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=a,this.id=u,this.fee=c,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),u=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:u,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?dt:r.tradeable,tradeableOut:this.id===t?dt:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=le(s.fee),u=[],c=z.isSellAllowed(e.tradeableIn),y=z.isBuyAllowed(e.tradeableOut);return(!c||!y)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=le(s.fee),u=[],c=z.isSellAllowed(e.tradeableIn),y=z.isBuyAllowed(e.tradeableOut);return(!c||!y)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:u}}calculateIn(e,t,s){let r=ee.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?Z(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateAddOneAsset(e,t,s){let r=ee.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?Z(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateSharesForAmount(e,t,s){let r=ee.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?Z(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=Y(ae,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,s){let r=ee.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?Z(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateWithdrawOneAsset(e,t,s){let r=ee.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?Z(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateShares(e,t,s){let r=ee.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?Z(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=Y(ae,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=ee.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{calculate_in_given_out as Gs,calculate_out_given_in as qs,calculate_pool_trade_fee as Hs,get_spot_price as Us,calculate_liquidity_in as zs,calculate_shares as Xs,calculate_liquidity_out_asset_a as Ws,calculate_liquidity_out_asset_b as Ys}from"@galacticcouncil/math-xyk";var Pe=class{static getSpotPrice(e,t,s){return Us(e,t,s)}static calculateInGivenOut(e,t,s){return Gs(e,t,s)}static calculateOutGivenIn(e,t,s){return qs(e,t,s)}static calculatePoolTradeFee(e,t,s){return Hs(e,t,s)}static calculateLiquidityIn(e,t,s){return zs(e,t,s)}static calculateShares(e,t,s){return Xs(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return Ws(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Ys(e,t,s,r)}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),u=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=le(s.exchangeFee),u=r.plus(i),c=[];t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&c.push("MaxOutRatioExceeded");let w=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(w)&&c.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:r,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=le(s.exchangeFee),u=r.minus(i),c=[];t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&c.push("MaxInRatioExceeded");let w=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(w)&&c.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:u,feePct:a,errors:c}}calculateInGivenOut(e,t){let s=Pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?L:r}calculateOutGivenIn(e,t){let s=Pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?L:r}spotPriceInGivenOut(e){let t=Pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),Y(ae,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=Pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),Y(ae,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=Pe.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(s)}};var ze=class{static get(e){switch(e.type){case"Xyk":return ve.fromPool(e);case"Omnipool":return we.fromPool(e);case"Lbp":return Oe.fromPool(e);case"Stableswap":return Be.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Fe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Re,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),a=this.getPaths(e,null,r,t).map(u=>u[u.length-1].assetOut);return this.toAssets([...new Set(a)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,origin:r.origin,meta:r.meta}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(u=>this.validPath(u,s)).map(u=>this.toHops(u,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,ze.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let a=t.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function bl(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Xe(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Wt(p,e){return ae.minus(e.div(p)).multipliedBy(100).decimalPlaces(2)}function Yt(p,e){return e.div(p).minus(ae).multipliedBy(100).decimalPlaces(2)}var lt=class extends Fe{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,a=r[r.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[s,r]}}getPoolFeeRange(e){let t=e.min?le(e.min):void 0,s=e.max?le(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),u=super.getPaths(e,t,a,i);if(u.length===0)throw new Ge(e,t);let c;if(r)c=await this.toSellSwaps(s,r,a);else{let _=u.map(async n=>await this.toSellSwaps(s,n,a)),U=await Promise.all(_);c=this.findBestSellRoute(U)}let y=c[0],w=c[c.length-1],B=this.isDirectTrade(c),F=c.map(_=>_.spotPrice.shiftedBy(-1*_.assetOutDecimals)).reduce((_,U)=>_.multipliedBy(U)),R=Y(F,w.assetOutDecimals),T=B?w.calculatedOut:this.calculateDelta0Y(y.amountIn,c,a),C=w.amountOut,M=B?w.tradeFeePct:Wt(T,C).toNumber(),J=T.minus(C),x=this.getRouteFeeRange(c),K=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(R),se=Xe(T,K),ye=_=>this.poolService.buildSellTx(e,t,y.amountIn,_,c.map(U=>U));return{type:"Sell",amountIn:y.amountIn,amountOut:w.amountOut,spotPrice:R,tradeFee:J,tradeFeePct:M,tradeFeeRange:x,priceImpactPct:se.toNumber(),swaps:c,toTx:ye,toHuman(){return{type:"Sell",amountIn:$(y.amountIn,y.assetInDecimals),amountOut:$(w.amountOut,w.assetOutDecimals),spotPrice:$(R,w.assetOutDecimals),tradeFee:$(J,w.assetOutDecimals),tradeFeePct:M,tradeFeeRange:x,priceImpactPct:se.toNumber(),swaps:c.map(_=>_.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],u=s.get(a.poolAddress);if(u==null)throw new Error("Pool does not exit");let c=u.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1]:y=e;let w=u.calculateOutGivenIn(c,y);r.push(w)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],u=s.get(a.poolAddress);if(u==null)throw new Error("Pool does not exit");let c=u.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1].amountOut:y=Y(I(e),c.decimalsIn).decimalPlaces(0,1);let w=await this.poolService.getPoolFees(c.assetOut,u),{amountOut:B,calculatedOut:F,feePct:R,errors:T}=u.validateAndSell(c,y,w),C=this.getPoolFeeRange(w),M=u.spotPriceOutGivenIn(c),J=y.shiftedBy(-1*c.decimalsIn).multipliedBy(M),x=Xe(F,J);r.push({...a,assetInDecimals:c.decimalsIn,assetOutDecimals:c.decimalsOut,amountIn:y,calculatedOut:F,amountOut:B,spotPrice:M,tradeFeePct:R,tradeFeeRange:C,priceImpactPct:x.toNumber(),errors:T,toHuman(){return{...a,amountIn:$(y,c.decimalsIn),calculatedOut:$(F,c.decimalsOut),amountOut:$(B,c.decimalsOut),spotPrice:$(M,c.decimalsOut),tradeFeePct:R,tradeFeeRange:C,priceImpactPct:x.toNumber(),errors:T}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(x=>x.tokens.find(K=>K.id===e)).filter(x=>!!x).sort((x,K)=>Number(K.balance)-Number(x.balance)),{balance:u,decimals:c}=a[0],w=I(u).shiftedBy(-1*c).div(100).multipliedBy(.1),B=i.map(async x=>await this.toSellSwaps(w,x,r)),F=await Promise.all(B),R=this.findBestSellRoute(F),T=await this.toSellSwaps("1",R,r),C=T.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,K)=>x.multipliedBy(K)),M=T[T.length-1].assetOutDecimals;return{amount:Y(C,M),decimals:M}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,a=r[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),u=super.getPaths(e,t,a,i);if(u.length===0)throw new Ge(e,t);let c;if(r)c=await this.toBuySwaps(s,r,a);else{let _=u.map(async n=>await this.toBuySwaps(s,n,a)),U=await Promise.all(_);c=this.findBestBuyRoute(U)}let y=c[c.length-1],w=c[0],B=this.isDirectTrade(c),F=c.map(_=>_.spotPrice.shiftedBy(-1*_.assetInDecimals)).reduce((_,U)=>_.multipliedBy(U)),R=Y(F,w.assetInDecimals),T=B?w.calculatedIn:this.calculateDelta0X(y.amountOut,c,a),C=w.amountIn,M=B?w.tradeFeePct:Yt(T,C).toNumber(),J=C.minus(T),x=this.getRouteFeeRange(c),K=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(R),se;T.isZero()?se=-100:se=Xe(K,T).toNumber();let ye=_=>this.poolService.buildBuyTx(e,t,y.amountOut,_,c.map(U=>U));return{type:"Buy",amountOut:y.amountOut,amountIn:w.amountIn,spotPrice:R,tradeFee:J,tradeFeePct:M,tradeFeeRange:x,priceImpactPct:se,swaps:c,toTx:ye,toHuman(){return{type:"Buy",amountOut:$(y.amountOut,y.assetOutDecimals),amountIn:$(w.amountIn,w.assetInDecimals),spotPrice:$(R,w.assetInDecimals),tradeFee:$(J,w.assetInDecimals),tradeFeePct:M,tradeFeeRange:x,priceImpactPct:se,swaps:c.map(_=>_.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],u=s.get(a.poolAddress);if(u==null)throw new Error("Pool does not exit");let c=u.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=r[0];let w=u.calculateInGivenOut(c,y);r.unshift(w)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],u=s.get(a.poolAddress);if(u==null)throw new Error("Pool does not exit");let c=u.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=Y(I(e),c.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let w=await this.poolService.getPoolFees(c.assetOut,u),{amountIn:B,calculatedIn:F,feePct:R,errors:T}=u.validateAndBuy(c,y,w),C=this.getPoolFeeRange(w),M=u.spotPriceInGivenOut(c),J=y.shiftedBy(-1*c.decimalsOut).multipliedBy(M),x;F.isZero()?x=-100:x=Xe(J,F).toNumber(),r.unshift({...a,assetInDecimals:c.decimalsIn,assetOutDecimals:c.decimalsOut,amountOut:y,calculatedIn:F,amountIn:B,spotPrice:M,tradeFeePct:R,tradeFeeRange:C,priceImpactPct:x,errors:T,toHuman(){return{...a,amountOut:$(y,c.decimalsOut),calculatedIn:$(F,c.decimalsIn),amountIn:$(B,c.decimalsIn),spotPrice:$(M,c.decimalsIn),tradeFeePct:R,tradeFeeRange:C,priceImpactPct:x,errors:T}}})}return r}};export{De as AssetClient,Nt as AssetNotFound,yr as BASILISK_PARACHAIN_ID,Ce as BalanceClient,fe as BigNumber,Ot as CachingPoolService,jt as DECIMAL_PLACES,ft as DENOMINATOR,je as HYDRADX_OMNIPOOL_ADDRESS,Sr as HYDRADX_PARACHAIN_ID,Me as HYDRADX_SS58_PREFIX,pr as INFINITY,ce as LbpMath,Oe as LbpPool,ae as ONE,z as OmniMath,we as OmniPool,At as PoolConfigNotFound,ke as PoolError,ze as PoolFactory,et as PoolNotFound,qe as PoolService,te as PoolType,_t as ProviderConfigNotFound,Le as RUNTIME_DECIMALS,Ge as RouteNotFound,Fe as Router,br as SYSTEM_ASSET_DECIMALS,Se as SYSTEM_ASSET_ID,ee as StableMath,Be as StableSwap,Tt as StorageConfigNotFound,Ft as SubscriptionNotSupported,dt as TRADEABLE_DEFAULT,lt as TradeRouter,vt as TradeType,Pe as XykMath,ve as XykPool,L as ZERO,I as bnum,Pt as buildRoute,Yt as calculateBuyFee,bl as calculateDiffToAvg,Xe as calculateDiffToRef,Wt as calculateSellFee,It as findNestedKey,Or as findNestedObj,Y as scale};
|
|
1
|
+
var Ye=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var $t=5,Re=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new Ye,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let u=i.dequeue();if(u==null||u.length>$t)return r;let c=u[u.length-1];(s===null||c[0]===s)&&r.push(u),e.get(c[0])?.forEach(w=>{if(this.isNotVisited(w,u)){let B=[...u];B.push(w),i.enqueue(B)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,a]of t){let u=parseInt(i),c=parseInt(a);s.get(u)?.push([c,r])}return s}};function pt(p){let e={};for(let t of p){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let i=0;i<s;i++){if(r==i)continue;let a=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(a)}}}return e}var Ee=class{getProposals(e,t,s){let r=pt(s),i=Object.keys(r),a=i.map(w=>r[w]).flat(),u=new Re,c=u.buildAndPopulateGraph(i,a),S=u.findPaths(c,parseInt(e),t?parseInt(t):null);return this.parsePaths(S)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let a=s[i],u=s[i+1];if(u==null)break;r.push(this.toEdge(a,u))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var Jt=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,mt=Math.ceil,ne=Math.floor,V="[BigNumber Error] ",wt=V+"Number primitive has more than 15 significant digits: ",ue=1e14,N=14,ht=9007199254740991,gt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],be=1e7,W=1e9;function Bt(p){var e,t,s,r=x.prototype={constructor:x,toString:null,valueOf:null},i=new x(1),a=20,u=4,c=-7,S=21,w=-1e7,B=1e7,F=!1,E=1,T=0,C={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},M="0123456789abcdefghijklmnopqrstuvwxyz",J=!0;function x(n,o){var l,P,h,d,y,m,g,b,f=this;if(!(f instanceof x))return new x(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<w?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((m=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,y=n;y>=10;y/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!Jt.test(b=String(n)))return s(f,b,m);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(y=b.search(/e/i))>0?(d<0&&(d=y),d+=+b.slice(y+1),b=b.substring(0,y)):d<0&&(d=b.length)}else{if(G(o,2,M.length,"Base"),o==10&&J)return f=new x(n),_(f,a+f.e+1,u);if(b=String(n),m=typeof n=="number"){if(n*0!=0)return s(f,b,m,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,x.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(wt+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=M.slice(0,o),d=y=0,g=b.length;y<g;y++)if(l.indexOf(P=b.charAt(y))<0){if(P=="."){if(y>d){d=g;continue}}else if(!h&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){h=!0,y=-1,d=0;continue}return s(f,String(n),m,o)}m=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(y=0;b.charCodeAt(y)===48;y++);for(g=b.length;b.charCodeAt(--g)===48;);if(b=b.slice(y,++g)){if(g-=y,m&&x.DEBUG&&g>15&&(n>ht||n!==ne(n)))throw Error(wt+f.s*n);if((d=d-y-1)>B)f.c=f.e=null;else if(d<w)f.c=[f.e=0];else{if(f.e=d,f.c=[],y=(d+1)%N,d<0&&(y+=N),y<g){for(y&&f.c.push(+b.slice(0,y)),g-=N;y<g;)f.c.push(+b.slice(y,y+=N));y=N-(b=b.slice(y)).length}else y-=g;for(;y--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}x.clone=Bt,x.ROUND_UP=0,x.ROUND_DOWN=1,x.ROUND_CEIL=2,x.ROUND_FLOOR=3,x.ROUND_HALF_UP=4,x.ROUND_HALF_DOWN=5,x.ROUND_HALF_EVEN=6,x.ROUND_HALF_CEIL=7,x.ROUND_HALF_FLOOR=8,x.EUCLID=9,x.config=x.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],G(l,0,W,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],G(l,0,8,o),u=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(G(l[0],-W,0,o),G(l[1],0,W,o),c=l[0],S=l[1]):(G(l,-W,W,o),c=-(S=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)G(l[0],-W,-1,o),G(l[1],1,W,o),w=l[0],B=l[1];else if(G(l,-W,W,o),l)w=-(B=l<0?-l:l);else throw Error(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],G(l,0,9,o),E=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],G(l,0,W,o),T=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")C=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))J=l.slice(0,10)=="0123456789",M=l;else throw Error(V+o+" invalid: "+l)}else throw Error(V+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:u,EXPONENTIAL_AT:[c,S],RANGE:[w,B],CRYPTO:F,MODULO_MODE:E,POW_PRECISION:T,FORMAT:C,ALPHABET:M}},x.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!x.DEBUG)return!0;var o,l,P=n.c,h=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&h>=-W&&h<=W&&h===ne(h)){if(P[0]===0){if(h===0&&P.length===1)return!0;break e}if(o=(h+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>=ue||l!==ne(l))break e;if(l!==0)return!0}}}else if(P===null&&h===null&&(d===null||d===1||d===-1))return!0;throw Error(V+"Invalid BigNumber: "+n)},x.maximum=x.max=function(){return se(arguments,-1)},x.minimum=x.min=function(){return se(arguments,1)},x.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ne(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,h,d,y,m,g=0,b=[],f=new x(i);if(l==null?l=a:G(l,0,W),y=mt(l/N),F)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(y*=2));g<y;)m=P[g]*131072+(P[g+1]>>>11),m>=9e15?(h=crypto.getRandomValues(new Uint32Array(2)),P[g]=h[0],P[g+1]=h[1]):(b.push(m%1e14),g+=2);g=y/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(y*=7);g<y;)m=(P[g]&31)*281474976710656+P[g+1]*1099511627776+P[g+2]*4294967296+P[g+3]*16777216+(P[g+4]<<16)+(P[g+5]<<8)+P[g+6],m>=9e15?crypto.randomBytes(7).copy(P,g):(b.push(m%1e14),g+=7);g=y/7}else throw F=!1,Error(V+"crypto unavailable");if(!F)for(;g<y;)m=o(),m<9e15&&(b[g++]=m%1e14);for(y=b[--g],l%=N,y&&l&&(m=gt[N-l],b[g]=ne(y/m)*m);b[g]===0;b.pop(),g--);if(g<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=N);for(g=1,m=b[0];m>=10;m/=10,g++);g<N&&(d-=N-g)}return f.e=d,f.c=b,f}}(),x.sum=function(){for(var n=1,o=arguments,l=new x(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,h,d){for(var y,m=[0],g,b=0,f=l.length;b<f;){for(g=m.length;g--;m[g]*=P);for(m[0]+=d.indexOf(l.charAt(b++)),y=0;y<m.length;y++)m[y]>h-1&&(m[y+1]==null&&(m[y+1]=0),m[y+1]+=m[y]/h|0,m[y]%=h)}return m.reverse()}return function(l,P,h,d,y){var m,g,b,f,O,v,A,k,q=l.indexOf("."),X=a,R=u;for(q>=0&&(f=T,T=0,l=l.replace(".",""),k=new x(P),v=k.pow(l.length-q),T=f,k.c=o(de(ie(v.c),v.e,"0"),10,h,n),k.e=k.c.length),A=o(l,P,h,y?(m=M,n):(m=n,M)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return m.charAt(0);if(q<0?--b:(v.c=A,v.e=b,v.s=d,v=e(v,k,X,R,h),A=v.c,O=v.r,b=v.e),g=b+X+1,q=A[g],f=h/2,O=O||g<0||A[g+1]!=null,O=R<4?(q!=null||O)&&(R==0||R==(v.s<0?3:2)):q>f||q==f&&(R==4||O||R==6&&A[g-1]&1||R==(v.s<0?8:7)),g<1||!A[0])l=O?de(m.charAt(1),-X,m.charAt(0)):m.charAt(0);else{if(A.length=g,O)for(--h;++A[--g]>h;)A[g]=0,g||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(q=0,l="";q<=f;l+=m.charAt(A[q++]));l=de(l,b,m.charAt(0))}return l}}(),e=function(){function n(P,h,d){var y,m,g,b,f=0,O=P.length,v=h%be,A=h/be|0;for(P=P.slice();O--;)g=P[O]%be,b=P[O]/be|0,y=A*g+b*v,m=v*g+y%be*be+f,f=(m/d|0)+(y/be|0)+A*b,P[O]=m%d;return f&&(P=[f].concat(P)),P}function o(P,h,d,y){var m,g;if(d!=y)g=d>y?1:-1;else for(m=g=0;m<d;m++)if(P[m]!=h[m]){g=P[m]>h[m]?1:-1;break}return g}function l(P,h,d,y){for(var m=0;d--;)P[d]-=m,m=P[d]<h[d]?1:0,P[d]=m*y+P[d]-h[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,h,d,y,m){var g,b,f,O,v,A,k,q,X,R,D,j,We,ut,ct,me,_e,re=P.s==h.s?1:-1,Q=P.c,H=h.c;if(!Q||!Q[0]||!H||!H[0])return new x(!P.s||!h.s||(Q?H&&Q[0]==H[0]:!H)?NaN:Q&&Q[0]==0||!H?re*0:re/0);for(q=new x(re),X=q.c=[],b=P.e-h.e,re=d+b+1,m||(m=ue,b=oe(P.e/N)-oe(h.e/N),re=re/N|0),f=0;H[f]==(Q[f]||0);f++);if(H[f]>(Q[f]||0)&&b--,re<0)X.push(1),O=!0;else{for(ut=Q.length,me=H.length,f=0,re+=2,v=ne(m/(H[0]+1)),v>1&&(H=n(H,v,m),Q=n(Q,v,m),me=H.length,ut=Q.length),We=me,R=Q.slice(0,me),D=R.length;D<me;R[D++]=0);_e=H.slice(),_e=[0].concat(_e),ct=H[0],H[1]>=m/2&&ct++;do{if(v=0,g=o(H,R,me,D),g<0){if(j=R[0],me!=D&&(j=j*m+(R[1]||0)),v=ne(j/ct),v>1)for(v>=m&&(v=m-1),A=n(H,v,m),k=A.length,D=R.length;o(A,R,k,D)==1;)v--,l(A,me<k?_e:H,k,m),k=A.length,g=1;else v==0&&(g=v=1),A=H.slice(),k=A.length;if(k<D&&(A=[0].concat(A)),l(R,A,D,m),D=R.length,g==-1)for(;o(H,R,me,D)<1;)v++,l(R,me<D?_e:H,D,m),D=R.length}else g===0&&(v++,R=[0]);X[f++]=v,R[0]?R[D++]=Q[We]||0:(R=[Q[We]],D=1)}while((We++<ut||R[0]!=null)&&re--);O=R[0]!=null,X[0]||X.splice(0,1)}if(m==ue){for(f=1,re=X[0];re>=10;re/=10,f++);_(q,d+(q.e=f+b*N-1)+1,y,O)}else q.e=b,q.r=+O;return q}}();function K(n,o,l,P){var h,d,y,m,g;if(l==null?l=u:G(l,0,8),!n.c)return n.toString();if(h=n.c[0],y=n.e,o==null)g=ie(n.c),g=P==1||P==2&&(y<=c||y>=S)?Je(g,y):de(g,y,"0");else if(n=_(new x(n),o,l),d=n.e,g=ie(n.c),m=g.length,P==1||P==2&&(o<=d||d<=c)){for(;m<o;g+="0",m++);g=Je(g,d)}else if(o-=y,g=de(g,d,"0"),d+1>m){if(--o>0)for(g+=".";o--;g+="0");}else if(o+=d-m,o>0)for(d+1==m&&(g+=".");o--;g+="0");return n.s<0&&h?"-"+g:g}function se(n,o){for(var l,P,h=1,d=new x(n[0]);h<n.length;h++)P=new x(n[h]),(!P.s||(l=xe(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function Se(n,o,l){for(var P=1,h=o.length;!o[--h];o.pop());for(h=o[0];h>=10;h/=10,P++);return(l=P+l*N-1)>B?n.c=n.e=null:l<w?n.c=[n.e=0]:(n.e=l,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,h=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,y,m,g){var b,f=m?y:y.replace(h,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!m&&(f=f.replace(n,function(O,v,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!g||g==b?v:O}),g&&(b=g,f=f.replace(o,"$1").replace(l,"0.$1")),y!=f))return new x(f,b);if(x.DEBUG)throw Error(V+"Not a"+(g?" base "+g:"")+" number: "+y);d.s=null}d.c=d.e=null}}();function _(n,o,l,P){var h,d,y,m,g,b,f,O=n.c,v=gt;if(O){e:{for(h=1,m=O[0];m>=10;m/=10,h++);if(d=o-h,d<0)d+=N,y=o,g=O[b=0],f=ne(g/v[h-y-1]%10);else if(b=mt((d+1)/N),b>=O.length)if(P){for(;O.length<=b;O.push(0));g=f=0,h=1,d%=N,y=d-N+1}else break e;else{for(g=m=O[b],h=1;m>=10;m/=10,h++);d%=N,y=d-N+h,f=y<0?0:ne(g/v[h-y-1]%10)}if(P=P||o<0||O[b+1]!=null||(y<0?g:g%v[h-y-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?y>0?g/v[h-y]:0:O[b-1])%10&1||l==(n.s<0?8:7)),o<1||!O[0])return O.length=0,P?(o-=n.e+1,O[0]=v[(N-o%N)%N],n.e=-o||0):O[0]=n.e=0,n;if(d==0?(O.length=b,m=1,b--):(O.length=b+1,m=v[N-d],O[b]=y>0?ne(g/v[h-y]%v[y])*m:0),P)for(;;)if(b==0){for(d=1,y=O[0];y>=10;y/=10,d++);for(y=O[0]+=m,m=1;y>=10;y/=10,m++);d!=m&&(n.e++,O[0]==ue&&(O[0]=1));break}else{if(O[b]+=m,O[b]!=ue)break;O[b--]=0,m=1}for(d=O.length;O[--d]===0;O.pop());}n.e>B?n.c=n.e=null:n.e<w&&(n.c=[n.e=0])}return n}function U(n){var o,l=n.e;return l===null?n.toString():(o=ie(n.c),o=l<=c||l>=S?Je(o,l):de(o,l,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new x(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return xe(this,new x(n,o))},r.decimalPlaces=r.dp=function(n,o){var l,P,h,d=this;if(n!=null)return G(n,0,W),o==null?o=u:G(o,0,8),_(new x(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((h=l.length-1)-oe(this.e/N))*N,h=l[h])for(;h%10==0;h/=10,P--);return P<0&&(P=0),P},r.dividedBy=r.div=function(n,o){return e(this,new x(n,o),a,u)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new x(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var l,P,h,d,y,m,g,b,f,O=this;if(n=new x(n),n.c&&!n.isInteger())throw Error(V+"Exponent not an integer: "+U(n));if(o!=null&&(o=new x(o)),m=n.e>14,!O.c||!O.c[0]||O.c[0]==1&&!O.e&&O.c.length==1||!n.c||!n.c[0])return f=new x(Math.pow(+U(O),m?n.s*(2-$e(n)):+U(n))),o?f.mod(o):f;if(g=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new x(NaN);P=!g&&O.isInteger()&&o.isInteger(),P&&(O=O.mod(o))}else{if(n.e>9&&(O.e>0||O.e<-1||(O.e==0?O.c[0]>1||m&&O.c[1]>=24e7:O.c[0]<8e13||m&&O.c[0]<=9999975e7)))return d=O.s<0&&$e(n)?-0:0,O.e>-1&&(d=1/d),new x(g?1/d:d);T&&(d=mt(T/N+2))}for(m?(l=new x(.5),g&&(n.s=1),b=$e(n)):(h=Math.abs(+U(n)),b=h%2),f=new x(i);;){if(b){if(f=f.times(O),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(h){if(h=ne(h/2),h===0)break;b=h%2}else if(n=n.times(l),_(n,n.e+1,1),n.e>14)b=$e(n);else{if(h=+U(n),h===0)break;b=h%2}O=O.times(O),d?O.c&&O.c.length>d&&(O.c.length=d):P&&(O=O.mod(o))}return P?f:(g&&(f=i.div(f)),o?f.mod(o):d?_(f,T,u,y):f)},r.integerValue=function(n){var o=new x(this);return n==null?n=u:G(n,0,8),_(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return xe(this,new x(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return xe(this,new x(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=xe(this,new x(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&oe(this.e/N)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return xe(this,new x(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=xe(this,new x(n,o)))===-1||o===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(n,o){var l,P,h,d,y=this,m=y.s;if(n=new x(n,o),o=n.s,!m||!o)return new x(NaN);if(m!=o)return n.s=-o,y.plus(n);var g=y.e/N,b=n.e/N,f=y.c,O=n.c;if(!g||!b){if(!f||!O)return f?(n.s=-o,n):new x(O?y:NaN);if(!f[0]||!O[0])return O[0]?(n.s=-o,n):new x(f[0]?y:u==3?-0:0)}if(g=oe(g),b=oe(b),f=f.slice(),m=g-b){for((d=m<0)?(m=-m,h=f):(b=g,h=O),h.reverse(),o=m;o--;h.push(0));h.reverse()}else for(P=(d=(m=f.length)<(o=O.length))?m:o,m=o=0;o<P;o++)if(f[o]!=O[o]){d=f[o]<O[o];break}if(d&&(h=f,f=O,O=h,n.s=-n.s),o=(P=O.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=ue-1;P>m;){if(f[--P]<O[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=ue}f[P]-=O[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?Se(n,f,b):(n.s=u==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var l,P,h=this;return n=new x(n,o),!h.c||!n.s||n.c&&!n.c[0]?new x(NaN):!n.c||h.c&&!h.c[0]?new x(h):(E==9?(P=n.s,n.s=1,l=e(h,n,0,3),n.s=P,l.s*=P):l=e(h,n,0,E),n=h.minus(l.times(n)),!n.c[0]&&E==1&&(n.s=h.s),n)},r.multipliedBy=r.times=function(n,o){var l,P,h,d,y,m,g,b,f,O,v,A,k,q,X,R=this,D=R.c,j=(n=new x(n,o)).c;if(!D||!j||!D[0]||!j[0])return!R.s||!n.s||D&&!D[0]&&!j||j&&!j[0]&&!D?n.c=n.e=n.s=null:(n.s*=R.s,!D||!j?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=oe(R.e/N)+oe(n.e/N),n.s*=R.s,g=D.length,O=j.length,g<O&&(k=D,D=j,j=k,h=g,g=O,O=h),h=g+O,k=[];h--;k.push(0));for(q=ue,X=be,h=O;--h>=0;){for(l=0,v=j[h]%X,A=j[h]/X|0,y=g,d=h+y;d>h;)b=D[--y]%X,f=D[y]/X|0,m=A*b+f*v,b=v*b+m%X*X+k[d]+l,l=(b/q|0)+(m/X|0)+A*f,k[d--]=b%q;k[d]=l}return l?++P:k.splice(0,1),Se(n,k,P)},r.negated=function(){var n=new x(this);return n.s=-n.s||null,n},r.plus=function(n,o){var l,P=this,h=P.s;if(n=new x(n,o),o=n.s,!h||!o)return new x(NaN);if(h!=o)return n.s=-o,P.minus(n);var d=P.e/N,y=n.e/N,m=P.c,g=n.c;if(!d||!y){if(!m||!g)return new x(h/0);if(!m[0]||!g[0])return g[0]?n:new x(m[0]?P:h*0)}if(d=oe(d),y=oe(y),m=m.slice(),h=d-y){for(h>0?(y=d,l=g):(h=-h,l=m),l.reverse();h--;l.push(0));l.reverse()}for(h=m.length,o=g.length,h-o<0&&(l=g,g=m,m=l,o=h),h=0;o;)h=(m[--o]=m[o]+g[o]+h)/ue|0,m[o]=ue===m[o]?0:m[o]%ue;return h&&(m=[h].concat(m),++y),Se(n,m,y)},r.precision=r.sd=function(n,o){var l,P,h,d=this;if(n!=null&&n!==!!n)return G(n,1,W),o==null?o=u:G(o,0,8),_(new x(d),n,o);if(!(l=d.c))return null;if(h=l.length-1,P=h*N+1,h=l[h]){for(;h%10==0;h/=10,P--);for(h=l[0];h>=10;h/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return G(n,-ht,ht),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,l,P,h,d=this,y=d.c,m=d.s,g=d.e,b=a+4,f=new x("0.5");if(m!==1||!y||!y[0])return new x(!m||m<0&&(!y||y[0])?NaN:y?d:1/0);if(m=Math.sqrt(+U(d)),m==0||m==1/0?(o=ie(y),(o.length+g)%2==0&&(o+="0"),m=Math.sqrt(+o),g=oe((g+1)/2)-(g<0||g%2),m==1/0?o="5e"+g:(o=m.toExponential(),o=o.slice(0,o.indexOf("e")+1)+g),l=new x(o)):l=new x(m+""),l.c[0]){for(g=l.e,m=g+b,m<3&&(m=0);;)if(h=l,l=f.times(h.plus(e(d,h,b,1))),ie(h.c).slice(0,m)===(o=ie(l.c)).slice(0,m))if(l.e<g&&--m,o=o.slice(m-3,m+1),o=="9999"||!P&&o=="4999"){if(!P&&(_(h,h.e+a+2,0),h.times(h).eq(d))){l=h;break}b+=4,m+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(_(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return _(l,l.e+a+1,u,n)},r.toExponential=function(n,o){return n!=null&&(G(n,0,W),n++),K(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(G(n,0,W),n=n+this.e+1),K(this,n,o)},r.toFormat=function(n,o,l){var P,h=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(V+"Argument not an object: "+l);if(P=h.toFixed(n,o),h.c){var d,y=P.split("."),m=+l.groupSize,g=+l.secondaryGroupSize,b=l.groupSeparator||"",f=y[0],O=y[1],v=h.s<0,A=v?f.slice(1):f,k=A.length;if(g&&(d=m,m=g,g=d,k-=d),m>0&&k>0){for(d=k%m||m,f=A.substr(0,d);d<k;d+=m)f+=b+A.substr(d,m);g>0&&(f+=b+A.slice(d)),v&&(f="-"+f)}P=O?f+(l.decimalSeparator||"")+((g=+l.fractionGroupSize)?O.replace(new RegExp("\\d{"+g+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):O):f}return(l.prefix||"")+P+(l.suffix||"")},r.toFraction=function(n){var o,l,P,h,d,y,m,g,b,f,O,v,A=this,k=A.c;if(n!=null&&(m=new x(n),!m.isInteger()&&(m.c||m.s!==1)||m.lt(i)))throw Error(V+"Argument "+(m.isInteger()?"out of range: ":"not an integer: ")+U(m));if(!k)return new x(A);for(o=new x(i),b=l=new x(i),P=g=new x(i),v=ie(k),d=o.e=v.length-A.e-1,o.c[0]=gt[(y=d%N)<0?N+y:y],n=!n||m.comparedTo(o)>0?d>0?o:b:m,y=B,B=1/0,m=new x(v),g.c[0]=0;f=e(m,o,0,1),h=l.plus(f.times(P)),h.comparedTo(n)!=1;)l=P,P=h,b=g.plus(f.times(h=b)),g=h,o=m.minus(f.times(h=o)),m=h;return h=e(n.minus(l),P,0,1),g=g.plus(h.times(b)),l=l.plus(h.times(P)),g.s=b.s=A.s,d=d*2,O=e(b,P,d,u).minus(A).abs().comparedTo(e(g,l,d,u).minus(A).abs())<1?[b,P]:[g,l],B=y,O},r.toNumber=function(){return+U(this)},r.toPrecision=function(n,o){return n!=null&&G(n,1,W),K(this,n,o,2)},r.toString=function(n){var o,l=this,P=l.s,h=l.e;return h===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=h<=c||h>=S?Je(ie(l.c),h):de(ie(l.c),h,"0"):n===10&&J?(l=_(new x(l),a+h+1,u),o=de(ie(l.c),l.e,"0")):(G(n,2,M.length,"Base"),o=t(de(ie(l.c),h,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return U(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,p!=null&&x.set(p),x}function oe(p){var e=p|0;return p>0||p===e?e:e-1}function ie(p){for(var e,t,s=1,r=p.length,i=p[0]+"";s<r;){for(e=p[s++]+"",t=N-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function xe(p,e){var t,s,r=p.c,i=e.c,a=p.s,u=e.s,c=p.e,S=e.e;if(!a||!u)return null;if(t=r&&!r[0],s=i&&!i[0],t||s)return t?s?0:-u:a;if(a!=u)return a;if(t=a<0,s=c==S,!r||!i)return s?0:!r^t?1:-1;if(!s)return c>S^t?1:-1;for(u=(c=r.length)<(S=i.length)?c:S,a=0;a<u;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return c==S?0:c>S^t?1:-1}function G(p,e,t,s){if(p<e||p>t||p!==ne(p))throw Error(V+(s||"Argument")+(typeof p=="number"?p<e||p>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(p))}function $e(p){var e=p.c.length-1;return oe(p.e/N)==e&&p.c[e]%2!=0}function Je(p,e){return(p.length>1?p.charAt(0)+"."+p.slice(1):p)+(e<0?"e":"e+")+e}function de(p,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);p=r+p}else if(s=p.length,++e>s){for(r=t,e-=s;--e;r+=t);p+=r}else e<s&&(p=p.slice(0,e)+"."+p.slice(e));return p}var fe=Bt();var jt=12;fe.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:jt});var L=I(0),ae=I(1),pr=I("Infinity");function Y(p,e){let t=new fe(e.toString()),s=new fe(10).pow(t);return p.times(s)}function I(p){return new fe(p.toString())}var te=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(te||{}),ke=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(ke||{}),vt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(vt||{});import{calculate_in_given_out as Kt,calculate_out_given_in as Qt,calculate_linear_weights as Vt,calculate_pool_trade_fee as Zt,get_spot_price as es}from"@galacticcouncil/math-lbp";var ce=class{static getSpotPrice(e,t,s,r,i){return es(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return Kt(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return Qt(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return Vt(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Zt(e,t,s)}};import{encodeAddress as ts}from"@polkadot/util-crypto";import{stringToU8a as ss}from"@polkadot/util";var Le=18,dt=15,ye="0",br=12,yr=2034,Me=63,Sr=2090,ft=1e3,je=ts(ss("modlomnipool".padEnd(32,"\0")),Me);function It(p,e){let t;return JSON.stringify(p,(s,r)=>(r&&r[e]&&(t=r),r)),t}function Or(p,e,t){let s;return JSON.stringify(p,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";var Ie=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var De=class extends Ie{SUPPORTED_TYPES=["StableSwap","Bond","Token","External"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getToken(e,t,s,r){if(e==ye){let B=this.api.consts.balances.existentialDeposit;return{id:ye,name:this.chainToken,symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:B.toString()}}let{name:i,assetType:a,isSufficient:u,existentialDeposit:c}=t,{symbol:S,decimals:w}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:S,decimals:w,icon:S,type:a.toHuman(),isSufficient:u?u.toHuman():!0,origin:this.parseLocation("parachain",r),existentialDeposit:c.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:u,isSufficient:c,existentialDeposit:S}=t,{symbol:w,decimals:B}=this.getToken(i.toString(),t,s),F=a.toNumber(),E=new Intl.DateTimeFormat("en-GB"),T=[w,"Bond",E.format(F)].join(" ");return{id:e,name:T,symbol:w+"b",decimals:B,icon:w,type:u.toString(),isSufficient:c.toHuman(),existentialDeposit:S.toString()}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:u,assetType:c,isSufficient:S,existentialDeposit:w}=t,F=i.map(C=>C.toString()).map(C=>{let{symbol:M}=this.getToken(C,t,s);return[C,M]}),E=Object.fromEntries(F),T=Object.values(E);return{id:e,name:T.join(", "),symbol:u?.isSome?u.toHuman():a.toHuman(),decimals:18,icon:T.join("/"),type:c.toString(),isSufficient:S.toHuman(),existentialDeposit:w.toString(),meta:E}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=this.parseLocation("generalIndex",r),u=s?.find(c=>c.id===a?.toString());return u?{...i,decimals:u.decimals,name:u.name,symbol:u.symbol,icon:u.symbol}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:a}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e){let[t,s,r,i,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),u=this.getSupportedAssets(t),c=this.normalizeMetadata(u,a);return u.map(([{args:[S]},w])=>{let B=w.unwrap(),F=s.get(S.toString()),{assetType:E}=B;switch(E.toString()){case"Bond":let T=i.get(S.toString());return this.getBond(S.toString(),B,c,T);case"StableSwap":let C=r.get(S.toString());return this.getShares(S.toString(),B,c,C);case"External":return this.getExternal(S.toString(),B,e,F);default:return this.getToken(S.toString(),B,c,F)}}).filter(S=>this.isValidAsset(S))}isValidAsset(e){return!!e.symbol&&!!e.decimals}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let s=It(t.toJSON(),e);return s&&s[e]}else return}};var Ce=class extends Ie{constructor(e){super(e)}async getBalance(e,t){return t===ye?await this.getSystemBalance(e):await this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeBalance(e,t,s){let r=t.filter(i=>i!==ye).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach(({free:a,reserved:u,frozen:c},S)=>{let w=this.calculateFreeBalance({free:a,feeFrozen:u,frozen:c}),B=r[S][1];s(B,w)})})}async subscribeTokenBalance(e,t,s){let r=t.filter(i=>i!==ye).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(r,i=>{i.forEach((a,u)=>{let c=this.calculateFreeBalance(a),S=r[u][1];s(S,c)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(ye,this.calculateFreeBalance(s)))}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,a=new fe(t),u=new fe(s||i),c=new fe(r||0),S=u.gt(c)?u:c;return a.minus(S)}};var he=class extends Ce{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async s=>{let r=[await this.subscribePoolChange(s),await this.subscribeTokensPoolBalance(s),await this.subscribeSystemPoolBalance(s)];if(this.hasShareAsset(s)){let i=await this.subscribeSharePoolBalance(s);r.push(i)}return this.subscribeLog(s),r});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,s)=>t.id!==s))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance(je,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(s,r){let i=e.tokens.findIndex(a=>a.id==s);i>=0&&t(e,s)&&(e.tokens[i].balance=r.toString())}}};var Ke=class extends he{MAX_FINAL_WEIGHT=Y(I(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,a])=>this.isActivePool(a.unwrap(),s)).map(async([{args:[i]},a])=>{let u=a.unwrap(),c=i.toString(),S=await this.getPoolDelta(c,u,s.toString());return this.poolsData.set(i.toString(),u),{address:c,type:"Lbp",fee:u.fee.toJSON(),...S,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let a=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(u=>u.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:a,initialWeight:u,finalWeight:c,repayTarget:S,feeCollector:w}=t,B=ce.calculateLinearWeights(r.toString(),i.toString(),u.toString(),c.toString(),s),[F,E]=a,T=F.toString(),C=I(B),M=E.toString(),J=this.MAX_FINAL_WEIGHT.minus(I(C)),[x,K,se]=await Promise.all([this.isRepayFeeApplied(T,S.toString(),w.toString()),this.getBalance(e,T),this.getBalance(e,M)]);return{repayFeeApply:x,tokens:[{id:T,weight:C,balance:K.toString()},{id:M,weight:J,balance:se.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=I(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{encodeAddress as rs}from"@polkadot/util-crypto";import{stringToU8a as is}from"@polkadot/util";function $(p,e){return p.shiftedBy(-1*e).toString()}function le(p){return p[0]/p[1]*100}function Z(p){return p[0]/p[1]}function pe(p){return[p/ft,ft]}var Qe=class extends he{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=s.map(async([{args:[c]},S])=>{let{hubReserve:w,shares:B,tradable:F}=S.unwrap(),E=await this.getBalance(t,c.toString());return{id:c.toString(),hubReserves:I(w.toString()),shares:I(B.toString()),tradeable:F.bits.toNumber(),balance:E.toString()}}),u=await Promise.all(a);return u.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:u,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=await this.api.query.dynamicFees.assetFee(e),r=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=r.minFee.toNumber()+i.minFee.toNumber(),u=r.maxFee.toNumber()+i.maxFee.toNumber();if(s.isSome){let{assetFee:c,protocolFee:S}=s.unwrap();return{assetFee:pe(c.toNumber()),protocolFee:pe(S.toNumber()),min:pe(a),max:pe(u)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:pe(a),max:pe(u)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let a=e.tokens[i];if(r.isNone)return a;let u=r.unwrap();return this.updateTokenState(a,u)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i}=t;return{...e,hubReserves:I(s.toString()),shares:I(r.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return pe(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return pe(t)}getPoolId(){return rs(is("modlomnipool".padEnd(32,"\0")),Me)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var Ve=class extends he{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[a,u]=r.unwrap(),[c,S]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,u.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:c.toString()},{id:u.toString(),balance:S.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{blake2AsHex as gs,encodeAddress as ds}from"@polkadot/util-crypto";import{calculate_in_given_out as ns,calculate_out_given_in as os,calculate_amplification as as,calculate_add_one_asset as ls,calculate_liquidity_out_one_asset as us,calculate_pool_trade_fee as cs,calculate_shares as ps,calculate_shares_for_amount as ms,pool_account_name as hs}from"@galacticcouncil/math-stableswap";var ee=class{static getPoolAddress(e){return hs(e)}static calculateAmplification(e,t,s,r,i){return as(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return ns(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return ls(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return ms(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return os(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return us(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return ps(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return cs(e,t,s)}};var Ze=class extends he{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},a])=>{let u=a.unwrap(),c=i.toString(),S=this.getPoolAddress(c),[w,B]=await Promise.all([this.getPoolDelta(c,u,s.toString()),this.getPoolTokens(S,c,u)]);return this.stablePools.set(S,u),{address:S,id:c,type:"Stableswap",fee:pe(u.fee.toNumber()),tokens:B,...w,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toNumber(),r=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,r,s.toString());Object.assign(e,i)})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:a,finalBlock:u}=t,c=ee.calculateAmplification(r.toString(),i.toString(),a.toString(),u.toString(),s),S=await this.api.query.tokens.totalIssuance(e);return{amplification:c,totalIssuance:S.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async c=>{let[S,w]=await Promise.all([this.api.query.stableswap.assetTradability(t,c.toString()),this.getBalance(e,c.toString())]);return{id:c.toString(),tradeable:S.bits.toNumber(),balance:w.toString()}}),a=await Promise.all(i),u=await this.api.query.omnipool.assets(t);if(u.isSome){let{tradable:c}=u.unwrap(),S=await this.getBalance(je,t);a.push({id:t,tradeable:c.bits.toNumber(),balance:S.toString()})}return a}getPoolAddress(e){let t=Number(e),s=ee.getPoolAddress(t);return ds(gs(s),Me)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function Pt(p){return p.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var et=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},At=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ge=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Tt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Ft=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},_t=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var qe=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new De(this.api),this.xykClient=new Ve(this.api),this.omniClient=new Qe(this.api),this.lbpClient=new Ke(this.api),this.stableClient=new Ze(this.api)}get assets(){return this.assets}get isRegistrySynced(){return this.onChainAssetsLoaded}async syncRegistry(e){this.onChainAssets=await this.assetClient.getOnChainAssets(e),this.onChainAssetsLoaded=!0}async getPools(e){if(this.onChainAssetsLoaded||this.syncRegistry(),e.length==0){let a=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(u=>u.isSupported()).map(u=>u.getPools()))).flat();return this.withMetadata(a)}let t=[];e.forEach(i=>{switch(i){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break;case"Stableswap":t.push(this.stableClient.getPools());break}});let r=(await Promise.all(t)).flat();return this.withMetadata(r)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(s=>[s.id,s]));return e.filter(s=>s.type==="Xyk"?s.tokens.every(r=>t.get(r.id)):!0).map(s=>{let r=s.tokens.map(i=>{let a=t.get(i.id);return{...i,...a}});return{...s,tokens:r}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new et(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):a=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),Pt(i));let u=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:u}}buildSellTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):a=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),Pt(i));let u=()=>a;return{hex:a.toHex(),name:"RouterSell",get:u}}};var He=(p,e)=>p===e?0:p==null?e==null?0:-1:e==null?p==null?0:1:typeof p.compare=="function"?p.compare(e):typeof e.compare=="function"?-e.compare(p):p<e?-1:p>e?1:0;var tt=(p,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(p(t)+e(t))}};var fs=tt(()=>"illegal argument(s)"),Rt=p=>{throw new fs(p)};var Ps=tt(()=>"index out of bounds"),bt=p=>{throw new Ps(p)},st=(p,e,t)=>(p<e||p>=t)&&bt(p);var Et=23283064365386963e-26,rt=class{float(e=1){return this.int()*Et*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Et-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var yt=Math.random,St=class extends rt{int(){return yt()*4294967296>>>0}float(e=1){return yt()*e}norm(e=1){return(yt()-.5)*2*e}},kt=new St;var Lt=p=>p!=null&&typeof p!="function"&&p.length!==void 0;var Mt=Object.getPrototypeOf({}),it="function",Dt="string",Ae=(p,e)=>{let t;if(p===e)return!0;if(p!=null){if(typeof p.equiv===it)return p.equiv(e)}else return p==e;if(e!=null){if(typeof e.equiv===it)return e.equiv(p)}else return p==e;return typeof p===Dt||typeof e===Dt?!1:(t=Object.getPrototypeOf(p),(t==null||t===Mt)&&(t=Object.getPrototypeOf(e),t==null||t===Mt)?xs(p,e):typeof p!==it&&p.length!==void 0&&typeof e!==it&&e.length!==void 0?bs(p,e):p instanceof Set&&e instanceof Set?ys(p,e):p instanceof Map&&e instanceof Map?Ss(p,e):p instanceof Date&&e instanceof Date?p.getTime()===e.getTime():p instanceof RegExp&&e instanceof RegExp?p.toString()===e.toString():p!==p&&e!==e)},bs=(p,e,t=Ae)=>{let s=p.length;if(s===e.length)for(;s-- >0&&t(p[s],e[s]););return s<0},ys=(p,e,t=Ae)=>p.size===e.size&&t([...p.keys()].sort(),[...e.keys()].sort()),Ss=(p,e,t=Ae)=>p.size===e.size&&t([...p].sort(),[...e].sort()),xs=(p,e,t=Ae)=>{if(Object.keys(p).length!==Object.keys(e).length)return!1;for(let s in p)if(!e.hasOwnProperty(s)||!t(p[s],e[s]))return!1;return!0};var Ct=(p,e)=>p!=null&&typeof p[e]=="function";var Gt=p=>Ct(p,"xform")?p.xform():p;var nt=Symbol(),xt=()=>{};var qt=p=>p!=null&&typeof p[Symbol.iterator]=="function";var ot=class{value;constructor(e){this.value=e}deref(){return this.value}};var at=p=>p instanceof ot;var Ht=p=>p instanceof ot?p.deref():p;function*Ut(p,e){let t=Gt(p)([xt,xt,(s,r)=>r])[2];for(let s of e){let r=t(nt,s);if(at(r)){r=Ht(r.deref()),r!==nt&&(yield r);return}r!==nt&&(yield r)}}var zt=(p,e)=>[p[0],p[1],e];function Ue(p,e){return qt(e)?Ut(Ue(p),e):t=>{let s=t[2];return zt(t,(r,i)=>s(r,p(i)))}}var Ne=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Xt("next",this._head)}reverseIterator(){return Xt("prev",this.tail)}clear(){this.release()}compare(e,t=He){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,a=0;for(;s-- >0&&a===0;)a=t(r.value,i.value),r=r.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof Ne||Lt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!Ae(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||He;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!at(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&bt(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*Xt(p,e){for(;e;)yield e.value,e=e[p]}var ge=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 ge(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 ge}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(st(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(st(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new ge,e)}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let s=this.nthCell(e),r=this.nthCell(t-1),i=a=>({first(){return a.value},next(){return a!==r&&a.next?i(a.next):void 0}});return s?i(s):void 0}shuffle(e,t=kt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&Rt("invalid indices: ${from} / ${to}");let i=new ge,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=He){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,a=0;for(let c=0;c<t&&(a++,i=i.next,!!i);c++);let u=t;for(;a>0||u>0&&i;){let c;a===0?(c=i,i=i.next,u--):!i||u===0||e(s.value,i.value)<=0?(c=s,s=s.next,a--):(c=i,i=i.next,u--),this._tail?this._tail.next=c:this._head=c,c.prev=this._tail,this._tail=c}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),st(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new ge;if(t>0)for(;r&&t-- >0;)this.remove(r),i.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let a of s)this.insertBefore(r,a);else for(let a of s)this.push(a);return i}};var Te=class{map;items;opts;_size;constructor(e,t){let s=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=s.map(),this.items=new ge,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Ue(e=>[e.k,e],this.items)}keys(){return Ue(e=>e.k,this.items)}values(){return Ue(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new Te(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e);return this._size+=Math.max(0,s-(r?r.value.s:0)),this.ensureSize()&&this.doSetEntry(r,e,t,s),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let s=this.map.get(e);return s?Promise.resolve(this.resetEntry(s)):t().then(r=>this.set(e,r))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,s=this.opts.maxlen;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e&&e(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Ot=class extends qe{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Te(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
+
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Oe=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Oe(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,a,u){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),u=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:u,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let u=this.calculateTradeFee(t,s),c=le(this.repayFeeApply?s.repayFee:s.exchangeFee),S=t.plus(u),w=this.calculateInGivenOut(e,S),B=e.balanceIn.div(this.maxInRatio);return w.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:w,calculatedIn:w,amountOut:t,feePct:c,errors:i}}else{let u=this.calculateInGivenOut(e,t),c=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(c)&&i.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let u=this.calculateOutGivenIn(e,t),c=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(c)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:u,amountOut:u,feePct:0,errors:i}}else{let u=this.calculateOutGivenIn(e,t),c=this.calculateTradeFee(u,s),S=le(this.repayFeeApply?s.repayFee:s.exchangeFee),w=u.minus(c),B=e.balanceOut.div(this.maxOutRatio);return w.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:u,amountOut:w,feePct:S,errors:i}}}calculateInGivenOut(e,t){let s=ce.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?L:r}calculateOutGivenIn(e,t){let s=ce.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?L:r}spotPriceInGivenOut(e){let t=ce.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),Y(ae,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=ce.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),Y(ae,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=ce.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(s)}};import{calculate_in_given_out as Os,calculate_lrna_in_given_out as ws,calculate_out_given_in as Bs,calculate_out_given_lrna_in as vs,calculate_pool_trade_fee as Is,calculate_spot_price as As,calculate_lrna_spot_price as Ns,calculate_shares as Ts,calculate_liquidity_out as Fs,calculate_liquidity_lrna_out as _s,calculate_cap_difference as Rs,verify_asset_cap as Es,calculate_liquidity_hub_in as ks,is_sell_allowed as Ls,is_buy_allowed as Ms,is_add_liquidity_allowed as Ds,is_remove_liquidity_allowed as Cs}from"@galacticcouncil/math-omnipool";var z=class{static calculateSpotPrice(e,t,s,r){return As(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return Ns(e,t)}static calculateInGivenOut(e,t,s,r,i,a,u,c,S){return Os(e,t,s,r,i,a,u,c,S)}static calculateLrnaInGivenOut(e,t,s,r,i){return ws(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,a,u,c,S){return Bs(e,t,s,r,i,a,u,c,S)}static calculateOutGivenLrnaIn(e,t,s,r,i){return vs(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Is(e,t,s)}static calculateShares(e,t,s,r){return Ts(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,a,u,c){return Fs(e,t,s,r,i,a,u,c)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,u,c){return _s(e,t,s,r,i,a,u,c)}static calculateCapDifference(e,t,s,r){return Rs(e,t,s,r)}static verifyAssetCap(e,t,s,r){return Es(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return ks(e,t,s,r)}static isSellAllowed(e){return Ls(e)}static isBuyAllowed(e){return Ms(e)}static isAddLiquidityAllowed(e){return Ds(e)}static isRemoveLiquidityAllowed(e){return Cs(e)}};var we=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new we(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),u=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:u,tradeableIn:r.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),u=r===L?L:a.div(r).multipliedBy(100).decimalPlaces(2),c=[],S=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!S||!w)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&c.push("MaxOutRatioExceeded");let F=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(F)&&c.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:u.toNumber(),errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),u=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),c=[],S=z.isSellAllowed(e.tradeableIn),w=z.isBuyAllowed(e.tradeableOut);(!S||!w)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&c.push("MaxInRatioExceeded");let F=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(F)&&c.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:u.toNumber(),errors:c}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=z.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?Z(s.assetFee).toString():L.toString(),s?Z(s.protocolFee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateLrnaInGivenOut(e,t,s){let r=z.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?Z(s.assetFee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=z.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?Z(s.assetFee).toString():L.toString(),s?Z(s.protocolFee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateOutGivenLrnaIn(e,t,s){let r=z.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?Z(s.assetFee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=z.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=z.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=z.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=z.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Le-e.decimalsIn)).decimalPlaces(0,1)}};var Be=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Be(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,i,a,u,c,S){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=a,this.id=u,this.fee=c,this.totalIssuance=S}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),u=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:u,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?dt:r.tradeable,tradeableOut:this.id===t?dt:i.tradeable}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=le(s.fee),u=[],c=z.isSellAllowed(e.tradeableIn),S=z.isBuyAllowed(e.tradeableOut);return(!c||!S)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=le(s.fee),u=[],c=z.isSellAllowed(e.tradeableIn),S=z.isBuyAllowed(e.tradeableOut);return(!c||!S)&&u.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&u.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:u}}calculateIn(e,t,s){let r=ee.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?Z(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateAddOneAsset(e,t,s){let r=ee.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?Z(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateSharesForAmount(e,t,s){let r=ee.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?Z(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=Y(ae,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,s){let r=ee.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?Z(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateWithdrawOneAsset(e,t,s){let r=ee.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?Z(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateShares(e,t,s){let r=ee.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?Z(s.fee).toString():L.toString()),i=I(r);return i.isNegative()?L:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=Y(ae,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=ee.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{calculate_in_given_out as Gs,calculate_out_given_in as qs,calculate_pool_trade_fee as Hs,get_spot_price as Us,calculate_liquidity_in as zs,calculate_shares as Xs,calculate_liquidity_out_asset_a as Ws,calculate_liquidity_out_asset_b as Ys}from"@galacticcouncil/math-xyk";var Pe=class{static getSpotPrice(e,t,s){return Us(e,t,s)}static calculateInGivenOut(e,t,s){return Gs(e,t,s)}static calculateOutGivenIn(e,t,s){return qs(e,t,s)}static calculatePoolTradeFee(e,t,s){return Hs(e,t,s)}static calculateLiquidityIn(e,t,s){return zs(e,t,s)}static calculateShares(e,t,s){return Xs(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return Ws(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Ys(e,t,s,r)}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=I(r.balance),u=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=le(s.exchangeFee),u=r.plus(i),c=[];t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let S=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(S)&&c.push("MaxOutRatioExceeded");let w=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(w)&&c.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:r,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=le(s.exchangeFee),u=r.minus(i),c=[];t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let S=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(S)&&c.push("MaxInRatioExceeded");let w=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(w)&&c.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:u,feePct:a,errors:c}}calculateInGivenOut(e,t){let s=Pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?L:r}calculateOutGivenIn(e,t){let s=Pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=I(s);return r.isNegative()?L:r}spotPriceInGivenOut(e){let t=Pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),Y(ae,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=Pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),Y(ae,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let s=Pe.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(s)}};var ze=class{static get(e){switch(e.type){case"Xyk":return ve.fromPool(e);case"Omnipool":return we.fromPool(e);case"Lbp":return Oe.fromPool(e);case"Stableswap":return Be.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Fe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ee,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),a=this.getPaths(e,null,r,t).map(u=>u[u.length-1].assetOut);return this.toAssets([...new Set(a)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,origin:r.origin,meta:r.meta}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(u=>this.validPath(u,s)).map(u=>this.toHops(u,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,ze.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let a=t.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function bl(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Xe(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Wt(p,e){return ae.minus(e.div(p)).multipliedBy(100).decimalPlaces(2)}function Yt(p,e){return e.div(p).minus(ae).multipliedBy(100).decimalPlaces(2)}var lt=class extends Fe{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,a=r[r.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[s,r]}}getPoolFeeRange(e){let t=e.min?le(e.min):void 0,s=e.max?le(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),u=super.getPaths(e,t,a,i);if(u.length===0)throw new Ge(e,t);let c;if(r)c=await this.toSellSwaps(s,r,a);else{let _=u.map(async n=>await this.toSellSwaps(s,n,a)),U=await Promise.all(_);c=this.findBestSellRoute(U)}let S=c[0],w=c[c.length-1],B=this.isDirectTrade(c),F=c.map(_=>_.spotPrice.shiftedBy(-1*_.assetOutDecimals)).reduce((_,U)=>_.multipliedBy(U)),E=Y(F,w.assetOutDecimals),T=B?w.calculatedOut:this.calculateDelta0Y(S.amountIn,c,a),C=w.amountOut,M=B?w.tradeFeePct:Wt(T,C).toNumber(),J=T.minus(C),x=this.getRouteFeeRange(c),K=S.amountIn.shiftedBy(-1*S.assetInDecimals).multipliedBy(E),se=Xe(T,K),Se=_=>this.poolService.buildSellTx(e,t,S.amountIn,_,c.map(U=>U));return{type:"Sell",amountIn:S.amountIn,amountOut:w.amountOut,spotPrice:E,tradeFee:J,tradeFeePct:M,tradeFeeRange:x,priceImpactPct:se.toNumber(),swaps:c,toTx:Se,toHuman(){return{type:"Sell",amountIn:$(S.amountIn,S.assetInDecimals),amountOut:$(w.amountOut,w.assetOutDecimals),spotPrice:$(E,w.assetOutDecimals),tradeFee:$(J,w.assetOutDecimals),tradeFeePct:M,tradeFeeRange:x,priceImpactPct:se.toNumber(),swaps:c.map(_=>_.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],u=s.get(a.poolAddress);if(u==null)throw new Error("Pool does not exit");let c=u.parsePair(a.assetIn,a.assetOut),S;i>0?S=r[i-1]:S=e;let w=u.calculateOutGivenIn(c,S);r.push(w)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],u=s.get(a.poolAddress);if(u==null)throw new Error("Pool does not exit");let c=u.parsePair(a.assetIn,a.assetOut),S;i>0?S=r[i-1].amountOut:S=Y(I(e),c.decimalsIn).decimalPlaces(0,1);let w=await this.poolService.getPoolFees(c.assetOut,u),{amountOut:B,calculatedOut:F,feePct:E,errors:T}=u.validateAndSell(c,S,w),C=this.getPoolFeeRange(w),M=u.spotPriceOutGivenIn(c),J=S.shiftedBy(-1*c.decimalsIn).multipliedBy(M),x=Xe(F,J);r.push({...a,assetInDecimals:c.decimalsIn,assetOutDecimals:c.decimalsOut,amountIn:S,calculatedOut:F,amountOut:B,spotPrice:M,tradeFeePct:E,tradeFeeRange:C,priceImpactPct:x.toNumber(),errors:T,toHuman(){return{...a,amountIn:$(S,c.decimalsIn),calculatedOut:$(F,c.decimalsOut),amountOut:$(B,c.decimalsOut),spotPrice:$(M,c.decimalsOut),tradeFeePct:E,tradeFeeRange:C,priceImpactPct:x.toNumber(),errors:T}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(x=>x.tokens.find(K=>K.id===e)).filter(x=>!!x).sort((x,K)=>Number(K.balance)-Number(x.balance)),{balance:u,decimals:c}=a[0],w=I(u).shiftedBy(-1*c).div(100).multipliedBy(.1),B=i.map(async x=>await this.toSellSwaps(w,x,r)),F=await Promise.all(B),E=this.findBestSellRoute(F),T=await this.toSellSwaps("1",E,r),C=T.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,K)=>x.multipliedBy(K)),M=T[T.length-1].assetOutDecimals;return{amount:Y(C,M),decimals:M}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,a=r[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),u=super.getPaths(e,t,a,i);if(u.length===0)throw new Ge(e,t);let c;if(r)c=await this.toBuySwaps(s,r,a);else{let _=u.map(async n=>await this.toBuySwaps(s,n,a)),U=await Promise.all(_);c=this.findBestBuyRoute(U)}let S=c[c.length-1],w=c[0],B=this.isDirectTrade(c),F=c.map(_=>_.spotPrice.shiftedBy(-1*_.assetInDecimals)).reduce((_,U)=>_.multipliedBy(U)),E=Y(F,w.assetInDecimals),T=B?w.calculatedIn:this.calculateDelta0X(S.amountOut,c,a),C=w.amountIn,M=B?w.tradeFeePct:Yt(T,C).toNumber(),J=C.minus(T),x=this.getRouteFeeRange(c),K=S.amountOut.shiftedBy(-1*S.assetOutDecimals).multipliedBy(E),se;T.isZero()?se=-100:se=Xe(K,T).toNumber();let Se=_=>this.poolService.buildBuyTx(e,t,S.amountOut,_,c.map(U=>U));return{type:"Buy",amountOut:S.amountOut,amountIn:w.amountIn,spotPrice:E,tradeFee:J,tradeFeePct:M,tradeFeeRange:x,priceImpactPct:se,swaps:c,toTx:Se,toHuman(){return{type:"Buy",amountOut:$(S.amountOut,S.assetOutDecimals),amountIn:$(w.amountIn,w.assetInDecimals),spotPrice:$(E,w.assetInDecimals),tradeFee:$(J,w.assetInDecimals),tradeFeePct:M,tradeFeeRange:x,priceImpactPct:se,swaps:c.map(_=>_.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],u=s.get(a.poolAddress);if(u==null)throw new Error("Pool does not exit");let c=u.parsePair(a.assetIn,a.assetOut),S;i==t.length-1?S=e:S=r[0];let w=u.calculateInGivenOut(c,S);r.unshift(w)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],u=s.get(a.poolAddress);if(u==null)throw new Error("Pool does not exit");let c=u.parsePair(a.assetIn,a.assetOut),S;i==t.length-1?S=Y(I(e),c.decimalsOut).decimalPlaces(0,1):S=r[0].amountIn;let w=await this.poolService.getPoolFees(c.assetOut,u),{amountIn:B,calculatedIn:F,feePct:E,errors:T}=u.validateAndBuy(c,S,w),C=this.getPoolFeeRange(w),M=u.spotPriceInGivenOut(c),J=S.shiftedBy(-1*c.decimalsOut).multipliedBy(M),x;F.isZero()?x=-100:x=Xe(J,F).toNumber(),r.unshift({...a,assetInDecimals:c.decimalsIn,assetOutDecimals:c.decimalsOut,amountOut:S,calculatedIn:F,amountIn:B,spotPrice:M,tradeFeePct:E,tradeFeeRange:C,priceImpactPct:x,errors:T,toHuman(){return{...a,amountOut:$(S,c.decimalsOut),calculatedIn:$(F,c.decimalsIn),amountIn:$(B,c.decimalsIn),spotPrice:$(M,c.decimalsIn),tradeFeePct:E,tradeFeeRange:C,priceImpactPct:x,errors:T}}})}return r}};export{De as AssetClient,Nt as AssetNotFound,Sr as BASILISK_PARACHAIN_ID,Ce as BalanceClient,fe as BigNumber,Ot as CachingPoolService,jt as DECIMAL_PLACES,ft as DENOMINATOR,je as HYDRADX_OMNIPOOL_ADDRESS,yr as HYDRADX_PARACHAIN_ID,Me as HYDRADX_SS58_PREFIX,pr as INFINITY,ce as LbpMath,Oe as LbpPool,ae as ONE,z as OmniMath,we as OmniPool,At as PoolConfigNotFound,ke as PoolError,ze as PoolFactory,et as PoolNotFound,qe as PoolService,te as PoolType,_t as ProviderConfigNotFound,Le as RUNTIME_DECIMALS,Ge as RouteNotFound,Fe as Router,br as SYSTEM_ASSET_DECIMALS,ye as SYSTEM_ASSET_ID,ee as StableMath,Be as StableSwap,Tt as StorageConfigNotFound,Ft as SubscriptionNotSupported,dt as TRADEABLE_DEFAULT,lt as TradeRouter,vt as TradeType,Pe as XykMath,ve as XykPool,L as ZERO,I as bnum,Pt as buildRoute,Yt as calculateBuyFee,bl as calculateDiffToAvg,Xe as calculateDiffToRef,Wt as calculateSellFee,It as findNestedKey,Or as findNestedObj,Y as scale};
|
|
@@ -16,6 +16,8 @@ export declare class PoolService implements IPoolService {
|
|
|
16
16
|
protected onChainAssets: Asset[];
|
|
17
17
|
protected onChainAssetsLoaded: boolean;
|
|
18
18
|
constructor(api: ApiPromise);
|
|
19
|
+
get assets(): Asset[];
|
|
20
|
+
get isRegistrySynced(): boolean;
|
|
19
21
|
syncRegistry(external?: ExternalAsset[]): Promise<void>;
|
|
20
22
|
getPools(includeOnly: PoolType[]): Promise<PoolBase[]>;
|
|
21
23
|
unsubscribe(): void;
|