@galacticcouncil/sdk 4.6.1 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.cjs +2 -2
- package/build/index.mjs +2 -2
- package/build/types/api/WalletCtx.d.ts +20 -0
- package/build/types/api/index.d.ts +1 -0
- package/build/types/client/AssetClient.d.ts +0 -1
- package/build/types/pool/PoolClient.d.ts +1 -1
- package/build/types/types.d.ts +1 -2
- package/package.json +1 -1
package/build/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var yt=Object.defineProperty;var Qt=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var es=Object.prototype.hasOwnProperty;var ts=(m,e)=>{for(var t in e)yt(m,t,{get:e[t],enumerable:!0})},ss=(m,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Vt(e))!es.call(m,r)&&r!==t&&yt(m,r,{get:()=>e[r],enumerable:!(s=Qt(e,r))||s.enumerable});return m};var rs=m=>ss(yt({},"__esModule",{value:!0}),m);var bs={};ts(bs,{AssetClient:()=>Fe,AssetNotFound:()=>Tt,BASILISK_PARACHAIN_ID:()=>us,BalanceClient:()=>_e,BigNumber:()=>q,CachingPoolService:()=>ft,DECIMAL_PLACES:()=>Gt,DENOMINATOR:()=>et,FarmClient:()=>tt,HYDRADX_OMNIPOOL_ADDRESS:()=>Xe,HYDRADX_PARACHAIN_ID:()=>ls,HYDRADX_SS58_PREFIX:()=>Te,INFINITY:()=>os,LbpMath:()=>pe,LbpPool:()=>Le,ONE:()=>ae,OmniMath:()=>W,OmniPool:()=>Me,PoolConfigNotFound:()=>Nt,PoolError:()=>Ae,PoolFactory:()=>Ge,PoolNotFound:()=>We,PoolService:()=>Re,PoolType:()=>ie,ProviderConfigNotFound:()=>Et,RUNTIME_DECIMALS:()=>Ne,RouteNotFound:()=>Ee,Router:()=>Ie,SYSTEM_ASSET_DECIMALS:()=>as,SYSTEM_ASSET_ID:()=>xe,StableMath:()=>se,StableSwap:()=>De,StorageConfigNotFound:()=>Ft,SubscriptionNotSupported:()=>_t,TRADEABLE_DEFAULT:()=>Ve,TradeRouter:()=>$e,TradeType:()=>Bt,XykMath:()=>ye,XykPool:()=>Ce,ZERO:()=>E,bnum:()=>v,buildRoute:()=>at,calculateBuyFee:()=>Mt,calculateDiffToAvg:()=>Ps,calculateDiffToRef:()=>qe,calculateSellFee:()=>Lt,findNestedKey:()=>vt,findNestedObj:()=>cs,scale:()=>K});module.exports=rs(bs);var je=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 is=5,Ue=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new je,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>is)return r;let u=c[c.length-1];(s===null||u[0]===s)&&r.push(c),e.get(u[0])?.forEach(x=>{if(this.isNotVisited(x,c)){let B=[...c];B.push(x),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),u=parseInt(a);s.get(c)?.push([u,r])}return s}};function St(m){let e={};for(let t of m){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 ze=class{getProposals(e,t,s){let r=St(s),i=Object.keys(r),a=i.map(x=>r[x]).flat(),c=new Ue,u=c.buildAndPopulateGraph(i,a),y=c.findPaths(u,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let 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 Ke=(m,e=new Map)=>t=>{let s;return e.has(t)?e.get(t):(e.set(t,s=m(t)),s)};var ns=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,wt=Math.ceil,ce=Math.floor,re="[BigNumber Error] ",Dt=re+"Number primitive has more than 15 significant digits: ",he=1e14,T=14,Ot=9007199254740991,xt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Oe=1e7,j=1e9;function Ct(m){var e,t,s,r=w.prototype={constructor:w,toString:null,valueOf:null},i=new w(1),a=20,c=4,u=-7,y=21,x=-1e7,B=1e7,N=!1,F=1,_=0,C={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},k="0123456789abcdefghijklmnopqrstuvwxyz",U=!0;function w(n,o){var l,P,g,d,S,p,h,b,f=this;if(!(f instanceof w))return new w(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<x?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!ns.test(b=String(n)))return s(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(H(o,2,k.length,"Base"),o==10&&U)return f=new w(n),R(f,a+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return s(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,w.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Dt+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=k.slice(0,o),d=S=0,h=b.length;S<h;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return s(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&w.DEBUG&&h>15&&(n>Ot||n!==ce(n)))throw Error(Dt+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<x)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%T,d<0&&(S+=T),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=T;S<h;)f.c.push(+b.slice(S,S+=T));S=T-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}w.clone=Ct,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],H(l,0,j,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],H(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(H(l[0],-j,0,o),H(l[1],0,j,o),u=l[0],y=l[1]):(H(l,-j,j,o),u=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)H(l[0],-j,-1,o),H(l[1],1,j,o),x=l[0],B=l[1];else if(H(l,-j,j,o),l)x=-(B=l<0?-l:l);else throw Error(re+o+" cannot be zero: "+l);if(n.hasOwnProperty(o="CRYPTO"))if(l=n[o],l===!!l)if(l)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))N=l;else throw N=!l,Error(re+"crypto unavailable");else N=l;else throw Error(re+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],H(l,0,9,o),F=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],H(l,0,j,o),_=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")C=l;else throw Error(re+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))U=l.slice(0,10)=="0123456789",k=l;else throw Error(re+o+" invalid: "+l)}else throw Error(re+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[u,y],RANGE:[x,B],CRYPTO:N,MODULO_MODE:F,POW_PRECISION:_,FORMAT:C,ALPHABET:k}},w.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!w.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-j&&g<=j&&g===ce(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%T,o<1&&(o+=T),String(P[0]).length==o){for(o=0;o<P.length;o++)if(l=P[o],l<0||l>=he||l!==ce(l))break e;if(l!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(re+"Invalid BigNumber: "+n)},w.maximum=w.max=function(){return oe(arguments,-1)},w.minimum=w.min=function(){return oe(arguments,1)},w.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ce(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,S,p,h=0,b=[],f=new w(i);if(l==null?l=a:H(l,0,j),S=wt(l/T),N)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));h<S;)p=P[h]*131072+(P[h+1]>>>11),p>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(p%1e14),h+=2);h=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);h<S;)p=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],p>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(p%1e14),h+=7);h=S/7}else throw N=!1,Error(re+"crypto unavailable");if(!N)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],l%=T,S&&l&&(p=xt[T-l],b[h]=ce(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=T);for(h=1,p=b[0];p>=10;p/=10,h++);h<T&&(d-=T-h)}return f.e=d,f.c=b,f}}(),w.sum=function(){for(var n=1,o=arguments,l=new w(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var S,p=[0],h,b=0,f=l.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(l.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(l,P,g,d,S){var p,h,b,f,O,I,A,M,z=l.indexOf("."),J=a,L=c;for(z>=0&&(f=_,_=0,l=l.replace(".",""),M=new w(P),I=M.pow(l.length-z),_=f,M.c=o(we(ue(I.c),I.e,"0"),10,g,n),M.e=M.c.length),A=o(l,P,g,S?(p=k,n):(p=n,k)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(z<0?--b:(I.c=A,I.e=b,I.s=d,I=e(I,M,J,L,g),A=I.c,O=I.r,b=I.e),h=b+J+1,z=A[h],f=g/2,O=O||h<0||A[h+1]!=null,O=L<4?(z!=null||O)&&(L==0||L==(I.s<0?3:2)):z>f||z==f&&(L==4||O||L==6&&A[h-1]&1||L==(I.s<0?8:7)),h<1||!A[0])l=O?we(p.charAt(1),-J,p.charAt(0)):p.charAt(0);else{if(A.length=h,O)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(z=0,l="";z<=f;l+=p.charAt(A[z++]));l=we(l,b,p.charAt(0))}return l}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,O=P.length,I=g%Oe,A=g/Oe|0;for(P=P.slice();O--;)h=P[O]%Oe,b=P[O]/Oe|0,S=A*h+b*I,p=I*h+S%Oe*Oe+f,f=(p/d|0)+(S/Oe|0)+A*b,P[O]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function l(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,O,I,A,M,z,J,L,G,ee,Je,Pt,bt,fe,He,le=P.s==g.s?1:-1,te=P.c,X=g.c;if(!te||!te[0]||!X||!X[0])return new w(!P.s||!g.s||(te?X&&te[0]==X[0]:!X)?NaN:te&&te[0]==0||!X?le*0:le/0);for(z=new w(le),J=z.c=[],b=P.e-g.e,le=d+b+1,p||(p=he,b=me(P.e/T)-me(g.e/T),le=le/T|0),f=0;X[f]==(te[f]||0);f++);if(X[f]>(te[f]||0)&&b--,le<0)J.push(1),O=!0;else{for(Pt=te.length,fe=X.length,f=0,le+=2,I=ce(p/(X[0]+1)),I>1&&(X=n(X,I,p),te=n(te,I,p),fe=X.length,Pt=te.length),Je=fe,L=te.slice(0,fe),G=L.length;G<fe;L[G++]=0);He=X.slice(),He=[0].concat(He),bt=X[0],X[1]>=p/2&&bt++;do{if(I=0,h=o(X,L,fe,G),h<0){if(ee=L[0],fe!=G&&(ee=ee*p+(L[1]||0)),I=ce(ee/bt),I>1)for(I>=p&&(I=p-1),A=n(X,I,p),M=A.length,G=L.length;o(A,L,M,G)==1;)I--,l(A,fe<M?He:X,M,p),M=A.length,h=1;else I==0&&(h=I=1),A=X.slice(),M=A.length;if(M<G&&(A=[0].concat(A)),l(L,A,G,p),G=L.length,h==-1)for(;o(X,L,fe,G)<1;)I++,l(L,fe<G?He:X,G,p),G=L.length}else h===0&&(I++,L=[0]);J[f++]=I,L[0]?L[G++]=te[Je]||0:(L=[te[Je]],G=1)}while((Je++<Pt||L[0]!=null)&&le--);O=L[0]!=null,J[0]||J.splice(0,1)}if(p==he){for(f=1,le=J[0];le>=10;le/=10,f++);R(z,d+(z.e=f+b*T-1)+1,S,O)}else z.e=b,z.r=+O;return z}}();function Q(n,o,l,P){var g,d,S,p,h;if(l==null?l=c:H(l,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ue(n.c),h=P==1||P==2&&(S<=u||S>=y)?Qe(h,S):we(h,S,"0");else if(n=R(new w(n),o,l),d=n.e,h=ue(n.c),p=h.length,P==1||P==2&&(o<=d||d<=u)){for(;p<o;h+="0",p++);h=Qe(h,d)}else if(o-=S,h=we(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function oe(n,o){for(var l,P,g=1,d=new w(n[0]);g<n.length;g++)P=new w(n[g]),(!P.s||(l=ve(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function Se(n,o,l){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(l=P+l*T-1)>B?n.c=n.e=null:l<x?n.c=[n.e=0]:(n.e=l,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,h){var b,f=p?S:S.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(O,I,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?I:O}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new w(f,b);if(w.DEBUG)throw Error(re+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function R(n,o,l,P){var g,d,S,p,h,b,f,O=n.c,I=xt;if(O){e:{for(g=1,p=O[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=T,S=o,h=O[b=0],f=ce(h/I[g-S-1]%10);else if(b=wt((d+1)/T),b>=O.length)if(P){for(;O.length<=b;O.push(0));h=f=0,g=1,d%=T,S=d-T+1}else break e;else{for(h=p=O[b],g=1;p>=10;p/=10,g++);d%=T,S=d-T+g,f=S<0?0:ce(h/I[g-S-1]%10)}if(P=P||o<0||O[b+1]!=null||(S<0?h:h%I[g-S-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?S>0?h/I[g-S]:0: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]=I[(T-o%T)%T],n.e=-o||0):O[0]=n.e=0,n;if(d==0?(O.length=b,p=1,b--):(O.length=b+1,p=I[T-d],O[b]=S>0?ce(h/I[g-S]%I[S])*p:0),P)for(;;)if(b==0){for(d=1,S=O[0];S>=10;S/=10,d++);for(S=O[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,O[0]==he&&(O[0]=1));break}else{if(O[b]+=p,O[b]!=he)break;O[b--]=0,p=1}for(d=O.length;O[--d]===0;O.pop());}n.e>B?n.c=n.e=null:n.e<x&&(n.c=[n.e=0])}return n}function Y(n){var o,l=n.e;return l===null?n.toString():(o=ue(n.c),o=l<=u||l>=y?Qe(o,l):we(o,l,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new w(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return ve(this,new w(n,o))},r.decimalPlaces=r.dp=function(n,o){var l,P,g,d=this;if(n!=null)return H(n,0,j),o==null?o=c:H(o,0,8),R(new w(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-me(this.e/T))*T,g=l[g])for(;g%10==0;g/=10,P--);return P<0&&(P=0),P},r.dividedBy=r.div=function(n,o){return e(this,new w(n,o),a,c)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new w(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var l,P,g,d,S,p,h,b,f,O=this;if(n=new w(n),n.c&&!n.isInteger())throw Error(re+"Exponent not an integer: "+Y(n));if(o!=null&&(o=new w(o)),p=n.e>14,!O.c||!O.c[0]||O.c[0]==1&&!O.e&&O.c.length==1||!n.c||!n.c[0])return f=new w(Math.pow(+Y(O),p?n.s*(2-Ze(n)):+Y(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new w(NaN);P=!h&&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||p&&O.c[1]>=24e7:O.c[0]<8e13||p&&O.c[0]<=9999975e7)))return d=O.s<0&&Ze(n)?-0:0,O.e>-1&&(d=1/d),new w(h?1/d:d);_&&(d=wt(_/T+2))}for(p?(l=new w(.5),h&&(n.s=1),b=Ze(n)):(g=Math.abs(+Y(n)),b=g%2),f=new w(i);;){if(b){if(f=f.times(O),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(g){if(g=ce(g/2),g===0)break;b=g%2}else if(n=n.times(l),R(n,n.e+1,1),n.e>14)b=Ze(n);else{if(g=+Y(n),g===0)break;b=g%2}O=O.times(O),d?O.c&&O.c.length>d&&(O.c.length=d):P&&(O=O.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?R(f,_,c,S):f)},r.integerValue=function(n){var o=new w(this);return n==null?n=c:H(n,0,8),R(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return ve(this,new w(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return ve(this,new w(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=ve(this,new w(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&me(this.e/T)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return ve(this,new w(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=ve(this,new w(n,o)))===-1||o===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(n,o){var l,P,g,d,S=this,p=S.s;if(n=new w(n,o),o=n.s,!p||!o)return new w(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/T,b=n.e/T,f=S.c,O=n.c;if(!h||!b){if(!f||!O)return f?(n.s=-o,n):new w(O?S:NaN);if(!f[0]||!O[0])return O[0]?(n.s=-o,n):new w(f[0]?S:c==3?-0:0)}if(h=me(h),b=me(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=O),g.reverse(),o=p;o--;g.push(0));g.reverse()}else for(P=(d=(p=f.length)<(o=O.length))?p:o,p=o=0;o<P;o++)if(f[o]!=O[o]){d=f[o]<O[o];break}if(d&&(g=f,f=O,O=g,n.s=-n.s),o=(P=O.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=he-1;P>p;){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]?Se(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var l,P,g=this;return n=new w(n,o),!g.c||!n.s||n.c&&!n.c[0]?new w(NaN):!n.c||g.c&&!g.c[0]?new w(g):(F==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,F),n=g.minus(l.times(n)),!n.c[0]&&F==1&&(n.s=g.s),n)},r.multipliedBy=r.times=function(n,o){var l,P,g,d,S,p,h,b,f,O,I,A,M,z,J,L=this,G=L.c,ee=(n=new w(n,o)).c;if(!G||!ee||!G[0]||!ee[0])return!L.s||!n.s||G&&!G[0]&&!ee||ee&&!ee[0]&&!G?n.c=n.e=n.s=null:(n.s*=L.s,!G||!ee?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=me(L.e/T)+me(n.e/T),n.s*=L.s,h=G.length,O=ee.length,h<O&&(M=G,G=ee,ee=M,g=h,h=O,O=g),g=h+O,M=[];g--;M.push(0));for(z=he,J=Oe,g=O;--g>=0;){for(l=0,I=ee[g]%J,A=ee[g]/J|0,S=h,d=g+S;d>g;)b=G[--S]%J,f=G[S]/J|0,p=A*b+f*I,b=I*b+p%J*J+M[d]+l,l=(b/z|0)+(p/J|0)+A*f,M[d--]=b%z;M[d]=l}return l?++P:M.splice(0,1),Se(n,M,P)},r.negated=function(){var n=new w(this);return n.s=-n.s||null,n},r.plus=function(n,o){var l,P=this,g=P.s;if(n=new w(n,o),o=n.s,!g||!o)return new w(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/T,S=n.e/T,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new w(g/0);if(!p[0]||!h[0])return h[0]?n:new w(p[0]?P:g*0)}if(d=me(d),S=me(S),p=p.slice(),g=d-S){for(g>0?(S=d,l=h):(g=-g,l=p),l.reverse();g--;l.push(0));l.reverse()}for(g=p.length,o=h.length,g-o<0&&(l=h,h=p,p=l,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/he|0,p[o]=he===p[o]?0:p[o]%he;return g&&(p=[g].concat(p),++S),Se(n,p,S)},r.precision=r.sd=function(n,o){var l,P,g,d=this;if(n!=null&&n!==!!n)return H(n,1,j),o==null?o=c:H(o,0,8),R(new w(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*T+1,g=l[g]){for(;g%10==0;g/=10,P--);for(g=l[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return H(n,-Ot,Ot),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,l,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new w("0.5");if(p!==1||!S||!S[0])return new w(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+Y(d)),p==0||p==1/0?(o=ue(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=me((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new w(o)):l=new w(p+""),l.c[0]){for(h=l.e,p=h+b,p<3&&(p=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ue(g.c).slice(0,p)===(o=ue(l.c)).slice(0,p))if(l.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(R(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(R(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return R(l,l.e+a+1,c,n)},r.toExponential=function(n,o){return n!=null&&(H(n,0,j),n++),Q(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(H(n,0,j),n=n+this.e+1),Q(this,n,o)},r.toFormat=function(n,o,l){var P,g=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=C;else if(typeof l!="object")throw Error(re+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],O=S[1],I=g.s<0,A=I?f.slice(1):f,M=A.length;if(h&&(d=p,p=h,h=d,M-=d),p>0&&M>0){for(d=M%p||p,f=A.substr(0,d);d<M;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),I&&(f="-"+f)}P=O?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?O.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):O):f}return(l.prefix||"")+P+(l.suffix||"")},r.toFraction=function(n){var o,l,P,g,d,S,p,h,b,f,O,I,A=this,M=A.c;if(n!=null&&(p=new w(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(re+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+Y(p));if(!M)return new w(A);for(o=new w(i),b=l=new w(i),P=h=new w(i),I=ue(M),d=o.e=I.length-A.e-1,o.c[0]=xt[(S=d%T)<0?T+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new w(I),h.c[0]=0;f=e(p,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,O=e(b,P,d,c).minus(A).abs().comparedTo(e(h,l,d,c).minus(A).abs())<1?[b,P]:[h,l],B=S,O},r.toNumber=function(){return+Y(this)},r.toPrecision=function(n,o){return n!=null&&H(n,1,j),Q(this,n,o,2)},r.toString=function(n){var o,l=this,P=l.s,g=l.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=u||g>=y?Qe(ue(l.c),g):we(ue(l.c),g,"0"):n===10&&U?(l=R(new w(l),a+g+1,c),o=we(ue(l.c),l.e,"0")):(H(n,2,k.length,"Base"),o=t(we(ue(l.c),g,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return Y(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,m!=null&&w.set(m),w}function me(m){var e=m|0;return m>0||m===e?e:e-1}function ue(m){for(var e,t,s=1,r=m.length,i=m[0]+"";s<r;){for(e=m[s++]+"",t=T-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function ve(m,e){var t,s,r=m.c,i=e.c,a=m.s,c=e.s,u=m.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=u==y,!r||!i)return s?0:!r^t?1:-1;if(!s)return u>y^t?1:-1;for(c=(u=r.length)<(y=i.length)?u:y,a=0;a<c;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return u==y?0:u>y^t?1:-1}function H(m,e,t,s){if(m<e||m>t||m!==ce(m))throw Error(re+(s||"Argument")+(typeof m=="number"?m<e||m>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(m))}function Ze(m){var e=m.c.length-1;return me(m.e/T)==e&&m.c[e]%2!=0}function Qe(m,e){return(m.length>1?m.charAt(0)+"."+m.slice(1):m)+(e<0?"e":"e+")+e}function we(m,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);m=r+m}else if(s=m.length,++e>s){for(r=t,e-=s;--e;r+=t);m+=r}else e<s&&(m=m.slice(0,e)+"."+m.slice(e));return m}var q=Ct();var Gt=12;q.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Gt});var E=v(0),ae=v(1),os=v("Infinity");function K(m,e){let t=new q(e.toString()),s=new q(10).pow(t);return m.times(s)}function v(m){return new q(m.toString())}var ie=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(ie||{}),Ae=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(Ae||{}),Bt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Bt||{});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 qt=require("@polkadot/util-crypto"),Ht=require("@polkadot/util"),Ne=18,Ve=15,xe="0",as=12,ls=2034,Te=63,us=2090,et=1e3,Xe=(0,qt.encodeAddress)((0,Ht.stringToU8a)("modlomnipool".padEnd(32,"\0")),Te);function vt(m,e){let t=[];return JSON.stringify(m,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function cs(m,e,t){let s;return JSON.stringify(m,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}var Xs=require("@polkadot/types/lookup");var Ws=require("@polkadot/api-base/types/consts");var Ys=require("@polkadot/api-base/types/errors");var $s=require("@polkadot/api-base/types/events");var Js=require("@polkadot/api-base/types/storage");var js=require("@polkadot/api-base/types/submittable");var Ks=require("@polkadot/rpc-core/types/jsonrpc");var Zs=require("@polkadot/api-base/types/calls");var nr=require("@polkadot/types/types/registry");var ur=require("@polkadot/types/lookup");var cr=require("@polkadot/api-base/types/consts");var mr=require("@polkadot/api-base/types/errors");var pr=require("@polkadot/api-base/types/events");var gr=require("@polkadot/api-base/types/storage");var hr=require("@polkadot/api-base/types/submittable");var dr=require("@polkadot/rpc-core/types/jsonrpc");var fr=require("@polkadot/api-base/types/calls");var Br=require("@polkadot/types/types/registry");var Be=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Fe=class extends Be{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==xe){let F=this.api.consts.balances.existentialDeposit;return{id:xe,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:F.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:u}=t,{symbol:y,decimals:x}=s.get(e)??{},B=this.parseLocation("parachain",r);return{id:e,name:i.toHuman(),symbol:y,decimals:x,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:B,externalId:this.parseLocation(2094===B?"generalKey":"generalIndex",r),existentialDeposit:u.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:c,isSufficient:u,existentialDeposit:y}=t,{symbol:x,decimals:B}=this.getToken(i.toString(),t,s),N=a.toNumber(),F=new Intl.DateTimeFormat("en-GB"),_=[x,"Bond",F.format(N)].join(" ");return{id:e,name:_,symbol:x+"b",decimals:B,icon:x,type:c.toString(),isSufficient:u.toHuman(),existentialDeposit:y.toString(),underlyingAssetId:i.toString(),maturity:N}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:c,assetType:u,isSufficient:y,existentialDeposit:x}=t,N=i.map(C=>C.toString()).map(C=>{let{symbol:k}=this.getToken(C,t,s);return[C,k]}),F=Object.fromEntries(N),_=Object.values(F);return{id:e,name:_.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:_.join("/"),type:u.toString(),isSufficient:y.toHuman(),existentialDeposit:x.toString(),meta:F}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=s?.find(c=>c.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:a}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,i,a,c]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),u=this.getSupportedAssets(s),y=this.normalizeMetadata(u,c),x=u.map(([{args:[B]},N])=>{let F=N.unwrap(),_=r.get(B.toString()),{assetType:C}=F;switch(C.toString()){case"Bond":let k=a.get(B.toString());return this.getBond(B.toString(),F,y,k);case"StableSwap":let U=i.get(B.toString());return this.getShares(B.toString(),F,y,U);case"External":return this.getExternal(B.toString(),F,t,_);default:return this.getToken(B.toString(),F,y,_)}});return e?x:x.filter(B=>this.isValidAsset(B))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let s=vt(t.toJSON(),e);return s&&s[e]}else return}};var _e=class extends Be{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===xe?this.getSystemBalance(e):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 getErc20Balance(e,t){let{free:s,reserved:r,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(xe,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let i=t.filter(a=>a.type!=="Erc20").filter(a=>a.id!==xe).map(a=>[e,a.id]);return this.api.query.tokens.accounts.multi(i,a=>{let c=[];a.forEach((u,y)=>{let x=this.calculateFreeBalance(u),B=i[y][1];c.push([B,x])}),s(c)})}async subscribeErc20Balance(e,t,s){let r=t.filter(a=>a.type==="Erc20"),i=async()=>{let a=[];(await Promise.all(r.map(async u=>[u.id,await this.getErc20Balance(e,u.id)]))).forEach(([u,y])=>{a.push([u,y])}),s(a)};return await i(),this.api.rpc.chain.subscribeNewHeads(async()=>{i()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,a=new q(t),c=new q(s||i),u=new q(r||0n),y=c.gt(u)?c:u;return a.minus(y)}};var It=require("@polkadot/util-crypto"),At=require("@galacticcouncil/math-liquidity-mining");var tt=class extends Be{constructor(e){super(e)}secondsInYear=new q(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(u)).unwrap(),x=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:x,priceAdjustment:B}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(u)).unwrap(),x=(await this.api.query.xykWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:x,priceAdjustment:B}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new q(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),c=a.price.n.toString(),u=a.price.d.toString(),y;return Number(t)<Number(s)?y=(0,At.fixed_from_rational)(c,u):y=(0,At.fixed_from_rational)(u,c),y}getGlobalRewardPerPeriod(e,t,s,r){let a=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return a.gte(s)?s:a}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,It.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,It.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:c,globalFarm:u,priceAdjustment:y})=>{let x=new q(u.totalSharesZ.toString()),B=u.plannedYieldingPeriods.toString(),N=new q(u.yieldPerPeriod.toString()),F=new q(u.maxRewardPerPeriod.toString()),_=u.blocksPerPeriod.toString(),C=new q(c.multiplier.toString()).shiftedBy(-18),k=this.secondsInYear.div(new q(s).times(_)),U;if(x.isZero())U=N.times(C).times(k);else{let Se=this.getGlobalRewardPerPeriod(x,N,F,y);U=this.getPoolYieldPerPeriod(Se,C,x,y).times(k)}let w=new q(u.pendingRewards.toString()).plus(u.accumulatedPaidRewards.toString()),Q=F.times(B);return w.div(Q).gte(.99)?E:U.times(100)}).reduce((c,u)=>c.plus(u),E).toString():void 0}};var be=class extends _e{pools=[];subs=[];assets=new Map([]);mem=0;memPools=Ke(e=>(console.log(this.getPoolType(),"mem pools",e,"\u2705"),this.getPools()));constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getMemPools(){return this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=await this.subscribe();let e=this.getPoolType();return console.log(e,`pools(${this.augmentedPools.length})`,"\u2705"),console.log(e,`subs(${this.subs.length})`,"\u2705"),this.augmentedPools}async subscribe(){let e=this.augmentedPools.map(async s=>{let r=[await this.subscribeTokensPoolBalance(s)];try{let i=await this.subscribePoolChange(s);r.push(i)}catch{}if(this.hasSystemAsset(s)){let i=await this.subscribeSystemPoolBalance(s);r.push(i)}if(this.hasErc20Asset(s)){let i=await this.subscribeErc20PoolBalance(s);r.push(i)}if(this.hasShareAsset(s)){let i=await this.subscribeSharePoolBalance(s);r.push(i)}return this.subscribeLog(s),r});return(await Promise.all(e)).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasShareAsset(e){return e.type==="Stableswap"&&e.id}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e()})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}subscribeSharePoolBalance(e){let t=this.assets.get(e.id);return this.subscribeTokenBalance(Xe,[t],this.updateBalancesCallback(e,()=>!0))}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,i])=>{let a=e.tokens.findIndex(c=>c.id==r);a>=0&&t(e,r)&&(e.tokens[a].balance=i.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(i=>i.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var st=class extends be{MAX_FINAL_WEIGHT=K(v(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,a])=>this.isActivePool(a.unwrap(),s)).map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=await this.getPoolDelta(u,c,s.toString());return this.poolsData.set(i.toString(),c),{address:u,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:u,repayTarget:y,feeCollector:x}=t,B=pe.calculateLinearWeights(r.toString(),i.toString(),c.toString(),u.toString(),s),[N,F]=a,_=N.toString(),C=v(B),k=F.toString(),U=this.MAX_FINAL_WEIGHT.minus(v(C)),[w,Q,oe]=await Promise.all([this.isRepayFeeApplied(_,y.toString(),x.toString()),this.getBalance(e,_),this.getBalance(e,k)]);return{repayFeeApply:w,tokens:[{id:_,weight:C,balance:Q.toString()},{id:k,weight:U,balance:oe.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=v(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var Ut=require("@polkadot/util-crypto"),zt=require("@polkadot/util");function V(m,e){return m.shiftedBy(-1*e).toString()}function ge(m){return m[0]/m[1]*100}function ne(m){return m[0]/m[1]}function de(m){return[m/et,et]}var rt=class extends be{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=s.map(async([{args:[u]},y])=>{let{hubReserve:x,shares:B,tradable:N}=y.unwrap(),F=await this.getBalance(t,u.toString());return{id:u.toString(),hubReserves:v(x.toString()),shares:v(B.toString()),tradeable:N.bits.toNumber(),balance:F.toString()}}),c=await Promise.all(a);return c.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:c,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=await this.api.query.dynamicFees.assetFee(e),r=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=r.minFee.toNumber()+i.minFee.toNumber(),c=r.maxFee.toNumber()+i.maxFee.toNumber();if(s.isSome){let{assetFee:u,protocolFee:y}=s.unwrap();return{assetFee:de(u.toNumber()),protocolFee:de(y.toNumber()),min:de(a),max:de(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:de(a),max:de(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let a=e.tokens[i];if(r.isNone)return a;let c=r.unwrap();return this.updateTokenState(a,c)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i}=t;return{...e,hubReserves:v(s.toString()),shares:v(r.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return de(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return de(t)}getPoolId(){return(0,Ut.encodeAddress)((0,zt.stringToU8a)("modlomnipool".padEnd(32,"\0")),Te)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var it=class extends be{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[a,c]=r.unwrap(),[u,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:u.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var ot=require("@polkadot/util-crypto");var Z=require("@galacticcouncil/math-stableswap"),se=class{static getPoolAddress(e){return(0,Z.pool_account_name)(e)}static calculateAmplification(e,t,s,r,i){return(0,Z.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return(0,Z.calculate_in_given_out)(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return(0,Z.calculate_add_one_asset)(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return(0,Z.calculate_shares_for_amount)(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return(0,Z.calculate_out_given_in)(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return(0,Z.calculate_liquidity_out_one_asset)(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return(0,Z.calculate_shares)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,Z.calculate_pool_trade_fee)(e,t,s)}};var nt=class extends be{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=this.getPoolAddress(u),[x,B]=await Promise.all([this.getPoolDelta(u,c,s.toString()),this.getPoolTokens(y,u,c)]);return this.stablePools.set(y,c),{address:y,id:u,type:"Stableswap",fee:de(c.fee.toNumber()),tokens:B,...x,...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,u=se.calculateAmplification(r.toString(),i.toString(),a.toString(),c.toString(),s),y=await this.api.query.tokens.totalIssuance(e);return{amplification:u,totalIssuance:y.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async u=>{let[y,x]=await Promise.all([this.api.query.stableswap.assetTradability(t,u.toString()),this.getBalance(e,u.toString())]);return{id:u.toString(),tradeable:y.bits.toNumber(),balance:x.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:u}=c.unwrap(),y=await this.getBalance(Xe,t);a.push({id:t,tradeable:u.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),s=se.getPoolAddress(t);return(0,ot.encodeAddress)((0,ot.blake2AsHex)(s),Te)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function at(m){return m.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var We=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Nt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ee=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Tt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Ft=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},_t=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Et=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Re=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=Ke(e=>(console.log("Registry mem sync",e,"\u2705"),this.syncRegistry()));constructor(e){this.api=e,this.assetClient=new Fe(this.api),this.xykClient=new it(this.api),this.omniClient=new rt(this.api),this.lbpClient=new st(this.api),this.stableClient=new nt(this.api),this.clients=[this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getMemPools()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getMemPools()))).flat()}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new We(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):a=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),at(i));let c=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):a=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),at(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var Ye=(m,e)=>m===e?0:m==null?e==null?0:-1:e==null?m==null?0:1:typeof m.compare=="function"?m.compare(e):typeof e.compare=="function"?-e.compare(m):m<e?-1:m>e?1:0;var lt=(m,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(m(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var ms=lt(()=>"illegal argument(s)"),Xt=m=>{throw new ms(m)};var ps=lt(()=>"index out of bounds"),Rt=m=>{throw new ps(m)},ut=(m,e,t)=>(m<e||m>=t)&&Rt(m);var Wt=23283064365386963e-26,ct=class{float(e=1){return this.int()*Wt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Wt-.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 mt=class extends ct{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var Yt=new mt(Math.random);var $t=m=>m!=null&&typeof m!="function"&&m.length!==void 0;var Jt=Object.getPrototypeOf({}),pt="function",jt="string",ke=(m,e)=>{let t;if(m===e)return!0;if(m!=null){if(typeof m.equiv===pt)return m.equiv(e)}else return m==e;if(e!=null){if(typeof e.equiv===pt)return e.equiv(m)}else return m==e;return typeof m===jt||typeof e===jt?!1:(t=Object.getPrototypeOf(m),(t==null||t===Jt)&&(t=Object.getPrototypeOf(e),t==null||t===Jt)?fs(m,e):typeof m!==pt&&m.length!==void 0&&typeof e!==pt&&e.length!==void 0?gs(m,e):m instanceof Set&&e instanceof Set?hs(m,e):m instanceof Map&&e instanceof Map?ds(m,e):m instanceof Date&&e instanceof Date?m.getTime()===e.getTime():m instanceof RegExp&&e instanceof RegExp?m.toString()===e.toString():m!==m&&e!==e)},gs=(m,e,t=ke)=>{let s=m.length;if(s===e.length)for(;s-- >0&&t(m[s],e[s]););return s<0},hs=(m,e,t=ke)=>m.size===e.size&&t([...m.keys()].sort(),[...e.keys()].sort()),ds=(m,e,t=ke)=>m.size===e.size&&t([...m].sort(),[...e].sort()),fs=(m,e,t=ke)=>{if(Object.keys(m).length!==Object.keys(e).length)return!1;for(let s in m)if(!e.hasOwnProperty(s)||!t(m[s],e[s]))return!1;return!0};var kt=class{value;constructor(e){this.value=e}deref(){return this.value}};var Kt=m=>m instanceof kt;var gt=class m{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Zt("next",this._head)}reverseIterator(){return Zt("prev",this.tail)}clear(){this.release()}compare(e,t=Ye){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,a=0;for(;s-- >0&&a===0;)a=t(r.value,i.value),r=r.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof m||$t(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!ke(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||Ye;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!Kt(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*Zt(m,e){for(;e;)yield e.value,e=e[m]}var ht=class m extends gt{_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 m(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 m}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(ut(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(ut(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new m,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=Yt){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)&&Xt("invalid indices: ${from} / ${to}");let i=new m,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=Ye){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,a=0;for(let u=0;u<t&&(a++,i=i.next,!!i);u++);let c=t;for(;a>0||c>0&&i;){let u;a===0?(u=i,i=i.next,c--):!i||c===0||e(s.value,i.value)<=0?(u=s,s=s.next,a--):(u=i,i=i.next,c--),this._tail?this._tail.next=u:this._head=u,u.prev=this._tail,this._tail=u}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),ut(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new m;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 dt=class m{map;items;opts;_size;constructor(e,t){let s={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=s.map(),this.items=new ht,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(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}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 m(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),i=Math.max(0,s-(r?r.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(r,e,t,s):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let s=this.map.get(e);return s?this.resetEntry(s):this.set(e,await t())}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{release:e,maxsize:t,maxlen:s}=this.opts;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),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?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(this.opts.update?.(t,e.value.v,s),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 ft=class extends Re{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new dt(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
-
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Le=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new m(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(u=>[u.id,u])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let c=this.calculateTradeFee(t,s),u=ge(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(c),x=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return x.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:x,calculatedIn:x,amountOut:t,feePct:u,errors:i}}else{let c=this.calculateInGivenOut(e,t),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,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),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),u=this.calculateTradeFee(c,s),y=ge(this.repayFeeApply?s.repayFee:s.exchangeFee),x=c.minus(u),B=e.balanceOut.div(this.maxOutRatio);return x.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:x,feePct:y,errors:i}}}calculateInGivenOut(e,t){let s=pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),K(ae,e.decimalsOut).toString());return v(t)}spotPriceOutGivenIn(e){let t=pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),K(ae,e.decimalsIn).toString());return v(t)}calculateTradeFee(e,t){let s=pe.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return v(s)}};var D=require("@galacticcouncil/math-omnipool");var W=class{static calculateSpotPrice(e,t,s,r){return(0,D.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,D.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,a,c,u,y){return(0,D.calculate_in_given_out)(e,t,s,r,i,a,c,u,y)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,D.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,a,c,u,y){return(0,D.calculate_out_given_in)(e,t,s,r,i,a,c,u,y)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,D.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,D.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,D.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,a,c,u){return(0,D.calculate_liquidity_out)(e,t,s,r,i,a,c,u)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,c,u){return(0,D.calculate_liquidity_lrna_out)(e,t,s,r,i,a,c,u)}static calculateCapDifference(e,t,s,r){let i=q(t),a=q(e),c=q(r),y=q(s).shiftedBy(-18);if(i.div(c).lt(y)){let B=y.times(c).minus(i).times(a),N=i.times(q(1).minus(y));return B.div(N).toFixed(0)}else return"0"}static verifyAssetCap(e,t,s,r){return(0,D.verify_asset_cap)(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return(0,D.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,D.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,D.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,D.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,D.is_remove_liquidity_allowed)(e)}};var Me=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new m(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(x=>[x.id,x])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance),u=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:u,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),c=r===E?E:a.div(r).multipliedBy(100).decimalPlaces(2),u=[],y=W.isSellAllowed(e.tradeableIn),x=W.isBuyAllowed(e.tradeableOut);(!y||!x)&&u.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&u.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&u.push("MaxOutRatioExceeded");let N=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(N)&&u.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:c.toNumber(),errors:u}}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),u=[],y=W.isSellAllowed(e.tradeableIn),x=W.isBuyAllowed(e.tradeableOut);(!y||!x)&&u.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&u.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&u.push("MaxInRatioExceeded");let N=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(N)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:c.toNumber(),errors:u}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=W.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ne(s.assetFee).toString():E.toString(),s?ne(s.protocolFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateLrnaInGivenOut(e,t,s){let r=W.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ne(s.assetFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=W.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ne(s.assetFee).toString():E.toString(),s?ne(s.protocolFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateOutGivenLrnaIn(e,t,s){let r=W.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ne(s.assetFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=W.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=W.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=W.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=W.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsIn)).decimalPlaces(0,1)}};var De=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new m(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,u,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=u,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(x=>[x.id,x])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance),u=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?Ve:r.tradeable,tradeableOut:this.id===t?Ve:i.tradeable,assetInED:u,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=ge(s.fee),c=[],u=W.isSellAllowed(e.tradeableIn),y=W.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=ge(s.fee),c=[],u=W.isSellAllowed(e.tradeableIn),y=W.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,s){let r=se.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ne(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateAddOneAsset(e,t,s){let r=se.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?ne(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateSharesForAmount(e,t,s){let r=se.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?ne(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=K(ae,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,s){let r=se.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ne(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateWithdrawOneAsset(e,t,s){let r=se.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?ne(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateShares(e,t,s){let r=se.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?ne(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=K(ae,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=se.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return v(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var $=require("@galacticcouncil/math-xyk"),ye=class{static getSpotPrice(e,t,s){return(0,$.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,$.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,$.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,$.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,$.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,$.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,$.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,$.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,$.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,$.calculate_liquidity_out_asset_b)(e,t,s,r)}};var Ce=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new m(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(x=>[x.id,x])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance),u=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,assetInED:u,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=ge(s.exchangeFee),c=r.plus(i),u=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&u.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&u.push("MaxOutRatioExceeded");let x=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(x)&&u.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:r,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=ge(s.exchangeFee),c=r.minus(i),u=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&u.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&u.push("MaxInRatioExceeded");let x=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(x)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:a,errors:u}}calculateInGivenOut(e,t){let s=ye.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=ye.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=ye.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=K(ae,18-e.decimalsOut);return v(t).div(s)}spotPriceOutGivenIn(e){let t=ye.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=K(ae,18-e.decimalsIn);return v(t).div(s)}calculateTradeFee(e,t){let s=ye.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return v(s)}};var Ge=class{static get(e){switch(e.type){case"Xyk":return Ce.fromPool(e);case"Omnipool":return Me.fromPool(e);case"Lbp":return Le.fromPool(e);case"Stableswap":return De.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Ie=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new ze,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),a=this.getPaths(e,null,r,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(a)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,origin:r.origin,meta:r.meta,externalId:r.externalId,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(c=>this.validPath(c,s)).map(c=>this.toHops(c,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,Ge.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let a=t.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function Ps(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function qe(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Lt(m,e){return ae.minus(e.div(m)).multipliedBy(100).decimalPlaces(2)}function Mt(m,e){return e.div(m).minus(ae).multipliedBy(100).decimalPlaces(2)}var $e=class extends Ie{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,a=r[r.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[s,r]}}getPoolFeeRange(e){let t=e.min?ge(e.min):void 0,s=e.max?ge(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ee(e,t);let u;if(r)u=await this.toSellSwaps(s,r,a);else{let R=c.map(async n=>await this.toSellSwaps(s,n,a)),Y=await Promise.all(R);u=this.findBestSellRoute(Y)}let y=u[0],x=u[u.length-1],B=this.isDirectTrade(u),N=u.map(R=>R.spotPrice.shiftedBy(-1*R.assetOutDecimals)).reduce((R,Y)=>R.multipliedBy(Y)),F=K(N,x.assetOutDecimals),_=B?x.calculatedOut:this.calculateDelta0Y(y.amountIn,u,a),C=x.amountOut,k=B?x.tradeFeePct:Lt(_,C).toNumber(),U=_.minus(C),w=this.getRouteFeeRange(u),Q=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(F),oe=qe(_,Q),Se=R=>this.poolService.buildSellTx(e,t,y.amountIn,R,u.map(Y=>Y));return{type:"Sell",amountIn:y.amountIn,amountOut:x.amountOut,spotPrice:F,tradeFee:U,tradeFeePct:k,tradeFeeRange:w,priceImpactPct:oe.toNumber(),swaps:u,toTx:Se,toHuman(){return{type:"Sell",amountIn:V(y.amountIn,y.assetInDecimals),amountOut:V(x.amountOut,x.assetOutDecimals),spotPrice:V(F,x.assetOutDecimals),tradeFee:V(U,x.assetOutDecimals),tradeFeePct:k,tradeFeeRange:w,priceImpactPct:oe.toNumber(),swaps:u.map(R=>R.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1]:y=e;let x=c.calculateOutGivenIn(u,y);r.push(x)}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 u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1].amountOut:y=K(v(e),u.decimalsIn).decimalPlaces(0,1);let x=await this.poolService.getPoolFees(u.assetOut,c),{amountOut:B,calculatedOut:N,feePct:F,errors:_}=c.validateAndSell(u,y,x),C=this.getPoolFeeRange(x),k=c.spotPriceOutGivenIn(u),U=y.shiftedBy(-1*u.decimalsIn).multipliedBy(k),w=qe(N,U);r.push({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountIn:y,calculatedOut:N,amountOut:B,spotPrice:k,tradeFeePct:F,tradeFeeRange:C,priceImpactPct:w.toNumber(),errors:_,toHuman(){return{...a,amountIn:V(y,u.decimalsIn),calculatedOut:V(N,u.decimalsOut),amountOut:V(B,u.decimalsOut),spotPrice:V(k,u.decimalsOut),tradeFeePct:F,tradeFeeRange:C,priceImpactPct:w.toNumber(),errors:_}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(w=>w.tokens.find(Q=>Q.id===e)).filter(w=>!!w).sort((w,Q)=>Number(Q.balance)-Number(w.balance)),{balance:c,decimals:u}=a[0],x=v(c).shiftedBy(-1*u).div(100).multipliedBy(.1),B=i.map(async w=>await this.toSellSwaps(x,w,r)),N=await Promise.all(B),F=this.findBestSellRoute(N),_=await this.toSellSwaps("1",F,r),C=_.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,Q)=>w.multipliedBy(Q)),k=_[_.length-1].assetOutDecimals;return{amount:K(C,k),decimals:k}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,a=r[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ee(e,t);let u;if(r)u=await this.toBuySwaps(s,r,a);else{let R=c.map(async n=>await this.toBuySwaps(s,n,a)),Y=await Promise.all(R);u=this.findBestBuyRoute(Y)}let y=u[u.length-1],x=u[0],B=this.isDirectTrade(u),N=u.map(R=>R.spotPrice.shiftedBy(-1*R.assetInDecimals)).reduce((R,Y)=>R.multipliedBy(Y)),F=K(N,x.assetInDecimals),_=B?x.calculatedIn:this.calculateDelta0X(y.amountOut,u,a),C=x.amountIn,k=B?x.tradeFeePct:Mt(_,C).toNumber(),U=C.minus(_),w=this.getRouteFeeRange(u),Q=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(F),oe;_.isZero()?oe=-100:oe=qe(Q,_).toNumber();let Se=R=>this.poolService.buildBuyTx(e,t,y.amountOut,R,u.map(Y=>Y));return{type:"Buy",amountOut:y.amountOut,amountIn:x.amountIn,spotPrice:F,tradeFee:U,tradeFeePct:k,tradeFeeRange:w,priceImpactPct:oe,swaps:u,toTx:Se,toHuman(){return{type:"Buy",amountOut:V(y.amountOut,y.assetOutDecimals),amountIn:V(x.amountIn,x.assetInDecimals),spotPrice:V(F,x.assetInDecimals),tradeFee:V(U,x.assetInDecimals),tradeFeePct:k,tradeFeeRange:w,priceImpactPct:oe,swaps:u.map(R=>R.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=r[0];let x=c.calculateInGivenOut(u,y);r.unshift(x)}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 u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=K(v(e),u.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let x=await this.poolService.getPoolFees(u.assetOut,c),{amountIn:B,calculatedIn:N,feePct:F,errors:_}=c.validateAndBuy(u,y,x),C=this.getPoolFeeRange(x),k=c.spotPriceInGivenOut(u),U=y.shiftedBy(-1*u.decimalsOut).multipliedBy(k),w;N.isZero()?w=-100:w=qe(U,N).toNumber(),r.unshift({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountOut:y,calculatedIn:N,amountIn:B,spotPrice:k,tradeFeePct:F,tradeFeeRange:C,priceImpactPct:w,errors:_,toHuman(){return{...a,amountOut:V(y,u.decimalsOut),calculatedIn:V(N,u.decimalsIn),amountIn:V(B,u.decimalsIn),spotPrice:V(k,u.decimalsIn),tradeFeePct:F,tradeFeeRange:C,priceImpactPct:w,errors:_}}})}return r}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,FarmClient,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
|
|
1
|
+
"use strict";var yt=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var Kt=Object.getOwnPropertyNames;var Qt=Object.prototype.hasOwnProperty;var es=(m,e)=>{for(var t in e)yt(m,t,{get:e[t],enumerable:!0})},ts=(m,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Kt(e))!Qt.call(m,r)&&r!==t&&yt(m,r,{get:()=>e[r],enumerable:!(s=Zt(e,r))||s.enumerable});return m};var ss=m=>ts(yt({},"__esModule",{value:!0}),m);var bs={};es(bs,{AssetClient:()=>Ie,AssetNotFound:()=>Nt,BASILISK_PARACHAIN_ID:()=>ls,BalanceClient:()=>Ae,BigNumber:()=>q,CachingPoolService:()=>ft,DECIMAL_PLACES:()=>Ct,DENOMINATOR:()=>et,FarmClient:()=>tt,HYDRADX_OMNIPOOL_ADDRESS:()=>We,HYDRADX_PARACHAIN_ID:()=>as,HYDRADX_SS58_PREFIX:()=>_e,INFINITY:()=>ns,LbpMath:()=>pe,LbpPool:()=>Le,ONE:()=>ae,OmniMath:()=>X,OmniPool:()=>Me,PoolConfigNotFound:()=>At,PoolError:()=>Te,PoolFactory:()=>Ge,PoolNotFound:()=>Xe,PoolService:()=>Re,PoolType:()=>ie,ProviderConfigNotFound:()=>_t,RUNTIME_DECIMALS:()=>Fe,RouteNotFound:()=>Ee,Router:()=>Ne,SYSTEM_ASSET_DECIMALS:()=>os,SYSTEM_ASSET_ID:()=>xe,StableMath:()=>se,StableSwap:()=>De,StorageConfigNotFound:()=>Tt,SubscriptionNotSupported:()=>Ft,TRADEABLE_DEFAULT:()=>Qe,TradeRouter:()=>$e,TradeType:()=>Ot,XykMath:()=>ye,XykPool:()=>Ce,ZERO:()=>E,bnum:()=>v,buildRoute:()=>at,calculateBuyFee:()=>Lt,calculateDiffToAvg:()=>ds,calculateDiffToRef:()=>qe,calculateSellFee:()=>kt,findNestedKey:()=>fs,findNestedObj:()=>Ps,scale:()=>V});module.exports=ss(bs);var je=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 rs=5,Ue=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new je,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>rs)return r;let u=c[c.length-1];(s===null||u[0]===s)&&r.push(c),e.get(u[0])?.forEach(x=>{if(this.isNotVisited(x,c)){let O=[...c];O.push(x),i.enqueue(O)}})}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),u=parseInt(a);s.get(c)?.push([u,r])}return s}};function St(m){let e={};for(let t of m){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 ze=class{getProposals(e,t,s){let r=St(s),i=Object.keys(r),a=i.map(x=>r[x]).flat(),c=new Ue,u=c.buildAndPopulateGraph(i,a),y=c.findPaths(u,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let 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 Ve=(m,e=new Map)=>t=>{let s;return e.has(t)?e.get(t):(e.set(t,s=m(t)),s)};var is=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,wt=Math.ceil,ce=Math.floor,re="[BigNumber Error] ",Mt=re+"Number primitive has more than 15 significant digits: ",he=1e14,N=14,Bt=9007199254740991,xt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Be=1e7,j=1e9;function Dt(m){var e,t,s,r=w.prototype={constructor:w,toString:null,valueOf:null},i=new w(1),a=20,c=4,u=-7,y=21,x=-1e7,O=1e7,T=!1,_=1,F=0,C={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},k="0123456789abcdefghijklmnopqrstuvwxyz",U=!0;function w(n,o){var l,P,g,d,S,p,h,b,f=this;if(!(f instanceof w))return new w(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>O?f.c=f.e=null:n.e<x?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>O?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!is.test(b=String(n)))return s(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(H(o,2,k.length,"Base"),o==10&&U)return f=new w(n),R(f,a+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return s(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,w.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(Mt+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=k.slice(0,o),d=S=0,h=b.length;S<h;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return s(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&w.DEBUG&&h>15&&(n>Bt||n!==ce(n)))throw Error(Mt+f.s*n);if((d=d-S-1)>O)f.c=f.e=null;else if(d<x)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%N,d<0&&(S+=N),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=N;S<h;)f.c.push(+b.slice(S,S+=N));S=N-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}w.clone=Dt,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],H(l,0,j,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],H(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(H(l[0],-j,0,o),H(l[1],0,j,o),u=l[0],y=l[1]):(H(l,-j,j,o),u=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)H(l[0],-j,-1,o),H(l[1],1,j,o),x=l[0],O=l[1];else if(H(l,-j,j,o),l)x=-(O=l<0?-l:l);else throw Error(re+o+" cannot be zero: "+l);if(n.hasOwnProperty(o="CRYPTO"))if(l=n[o],l===!!l)if(l)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))T=l;else throw T=!l,Error(re+"crypto unavailable");else T=l;else throw Error(re+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],H(l,0,9,o),_=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],H(l,0,j,o),F=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")C=l;else throw Error(re+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))U=l.slice(0,10)=="0123456789",k=l;else throw Error(re+o+" invalid: "+l)}else throw Error(re+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[u,y],RANGE:[x,O],CRYPTO:T,MODULO_MODE:_,POW_PRECISION:F,FORMAT:C,ALPHABET:k}},w.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!w.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-j&&g<=j&&g===ce(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%N,o<1&&(o+=N),String(P[0]).length==o){for(o=0;o<P.length;o++)if(l=P[o],l<0||l>=he||l!==ce(l))break e;if(l!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(re+"Invalid BigNumber: "+n)},w.maximum=w.max=function(){return oe(arguments,-1)},w.minimum=w.min=function(){return oe(arguments,1)},w.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ce(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,S,p,h=0,b=[],f=new w(i);if(l==null?l=a:H(l,0,j),S=wt(l/N),T)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));h<S;)p=P[h]*131072+(P[h+1]>>>11),p>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(p%1e14),h+=2);h=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);h<S;)p=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],p>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(p%1e14),h+=7);h=S/7}else throw T=!1,Error(re+"crypto unavailable");if(!T)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],l%=N,S&&l&&(p=xt[N-l],b[h]=ce(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=N);for(h=1,p=b[0];p>=10;p/=10,h++);h<N&&(d-=N-h)}return f.e=d,f.c=b,f}}(),w.sum=function(){for(var n=1,o=arguments,l=new w(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var S,p=[0],h,b=0,f=l.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(l.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(l,P,g,d,S){var p,h,b,f,B,I,A,M,z=l.indexOf("."),J=a,L=c;for(z>=0&&(f=F,F=0,l=l.replace(".",""),M=new w(P),I=M.pow(l.length-z),F=f,M.c=o(we(ue(I.c),I.e,"0"),10,g,n),M.e=M.c.length),A=o(l,P,g,S?(p=k,n):(p=n,k)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(z<0?--b:(I.c=A,I.e=b,I.s=d,I=e(I,M,J,L,g),A=I.c,B=I.r,b=I.e),h=b+J+1,z=A[h],f=g/2,B=B||h<0||A[h+1]!=null,B=L<4?(z!=null||B)&&(L==0||L==(I.s<0?3:2)):z>f||z==f&&(L==4||B||L==6&&A[h-1]&1||L==(I.s<0?8:7)),h<1||!A[0])l=B?we(p.charAt(1),-J,p.charAt(0)):p.charAt(0);else{if(A.length=h,B)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(z=0,l="";z<=f;l+=p.charAt(A[z++]));l=we(l,b,p.charAt(0))}return l}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,B=P.length,I=g%Be,A=g/Be|0;for(P=P.slice();B--;)h=P[B]%Be,b=P[B]/Be|0,S=A*h+b*I,p=I*h+S%Be*Be+f,f=(p/d|0)+(S/Be|0)+A*b,P[B]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function l(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,B,I,A,M,z,J,L,G,ee,Je,Pt,bt,fe,He,le=P.s==g.s?1:-1,te=P.c,W=g.c;if(!te||!te[0]||!W||!W[0])return new w(!P.s||!g.s||(te?W&&te[0]==W[0]:!W)?NaN:te&&te[0]==0||!W?le*0:le/0);for(z=new w(le),J=z.c=[],b=P.e-g.e,le=d+b+1,p||(p=he,b=me(P.e/N)-me(g.e/N),le=le/N|0),f=0;W[f]==(te[f]||0);f++);if(W[f]>(te[f]||0)&&b--,le<0)J.push(1),B=!0;else{for(Pt=te.length,fe=W.length,f=0,le+=2,I=ce(p/(W[0]+1)),I>1&&(W=n(W,I,p),te=n(te,I,p),fe=W.length,Pt=te.length),Je=fe,L=te.slice(0,fe),G=L.length;G<fe;L[G++]=0);He=W.slice(),He=[0].concat(He),bt=W[0],W[1]>=p/2&&bt++;do{if(I=0,h=o(W,L,fe,G),h<0){if(ee=L[0],fe!=G&&(ee=ee*p+(L[1]||0)),I=ce(ee/bt),I>1)for(I>=p&&(I=p-1),A=n(W,I,p),M=A.length,G=L.length;o(A,L,M,G)==1;)I--,l(A,fe<M?He:W,M,p),M=A.length,h=1;else I==0&&(h=I=1),A=W.slice(),M=A.length;if(M<G&&(A=[0].concat(A)),l(L,A,G,p),G=L.length,h==-1)for(;o(W,L,fe,G)<1;)I++,l(L,fe<G?He:W,G,p),G=L.length}else h===0&&(I++,L=[0]);J[f++]=I,L[0]?L[G++]=te[Je]||0:(L=[te[Je]],G=1)}while((Je++<Pt||L[0]!=null)&&le--);B=L[0]!=null,J[0]||J.splice(0,1)}if(p==he){for(f=1,le=J[0];le>=10;le/=10,f++);R(z,d+(z.e=f+b*N-1)+1,S,B)}else z.e=b,z.r=+B;return z}}();function K(n,o,l,P){var g,d,S,p,h;if(l==null?l=c:H(l,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ue(n.c),h=P==1||P==2&&(S<=u||S>=y)?Ke(h,S):we(h,S,"0");else if(n=R(new w(n),o,l),d=n.e,h=ue(n.c),p=h.length,P==1||P==2&&(o<=d||d<=u)){for(;p<o;h+="0",p++);h=Ke(h,d)}else if(o-=S,h=we(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function oe(n,o){for(var l,P,g=1,d=new w(n[0]);g<n.length;g++)P=new w(n[g]),(!P.s||(l=ve(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function Se(n,o,l){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(l=P+l*N-1)>O?n.c=n.e=null:l<x?n.c=[n.e=0]:(n.e=l,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,h){var b,f=p?S:S.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(B,I,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?I:B}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new w(f,b);if(w.DEBUG)throw Error(re+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function R(n,o,l,P){var g,d,S,p,h,b,f,B=n.c,I=xt;if(B){e:{for(g=1,p=B[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=N,S=o,h=B[b=0],f=ce(h/I[g-S-1]%10);else if(b=wt((d+1)/N),b>=B.length)if(P){for(;B.length<=b;B.push(0));h=f=0,g=1,d%=N,S=d-N+1}else break e;else{for(h=p=B[b],g=1;p>=10;p/=10,g++);d%=N,S=d-N+g,f=S<0?0:ce(h/I[g-S-1]%10)}if(P=P||o<0||B[b+1]!=null||(S<0?h:h%I[g-S-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?S>0?h/I[g-S]:0:B[b-1])%10&1||l==(n.s<0?8:7)),o<1||!B[0])return B.length=0,P?(o-=n.e+1,B[0]=I[(N-o%N)%N],n.e=-o||0):B[0]=n.e=0,n;if(d==0?(B.length=b,p=1,b--):(B.length=b+1,p=I[N-d],B[b]=S>0?ce(h/I[g-S]%I[S])*p:0),P)for(;;)if(b==0){for(d=1,S=B[0];S>=10;S/=10,d++);for(S=B[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,B[0]==he&&(B[0]=1));break}else{if(B[b]+=p,B[b]!=he)break;B[b--]=0,p=1}for(d=B.length;B[--d]===0;B.pop());}n.e>O?n.c=n.e=null:n.e<x&&(n.c=[n.e=0])}return n}function Y(n){var o,l=n.e;return l===null?n.toString():(o=ue(n.c),o=l<=u||l>=y?Ke(o,l):we(o,l,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new w(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return ve(this,new w(n,o))},r.decimalPlaces=r.dp=function(n,o){var l,P,g,d=this;if(n!=null)return H(n,0,j),o==null?o=c:H(o,0,8),R(new w(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-me(this.e/N))*N,g=l[g])for(;g%10==0;g/=10,P--);return P<0&&(P=0),P},r.dividedBy=r.div=function(n,o){return e(this,new w(n,o),a,c)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new w(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var l,P,g,d,S,p,h,b,f,B=this;if(n=new w(n),n.c&&!n.isInteger())throw Error(re+"Exponent not an integer: "+Y(n));if(o!=null&&(o=new w(o)),p=n.e>14,!B.c||!B.c[0]||B.c[0]==1&&!B.e&&B.c.length==1||!n.c||!n.c[0])return f=new w(Math.pow(+Y(B),p?n.s*(2-Ze(n)):+Y(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new w(NaN);P=!h&&B.isInteger()&&o.isInteger(),P&&(B=B.mod(o))}else{if(n.e>9&&(B.e>0||B.e<-1||(B.e==0?B.c[0]>1||p&&B.c[1]>=24e7:B.c[0]<8e13||p&&B.c[0]<=9999975e7)))return d=B.s<0&&Ze(n)?-0:0,B.e>-1&&(d=1/d),new w(h?1/d:d);F&&(d=wt(F/N+2))}for(p?(l=new w(.5),h&&(n.s=1),b=Ze(n)):(g=Math.abs(+Y(n)),b=g%2),f=new w(i);;){if(b){if(f=f.times(B),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(g){if(g=ce(g/2),g===0)break;b=g%2}else if(n=n.times(l),R(n,n.e+1,1),n.e>14)b=Ze(n);else{if(g=+Y(n),g===0)break;b=g%2}B=B.times(B),d?B.c&&B.c.length>d&&(B.c.length=d):P&&(B=B.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?R(f,F,c,S):f)},r.integerValue=function(n){var o=new w(this);return n==null?n=c:H(n,0,8),R(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return ve(this,new w(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return ve(this,new w(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=ve(this,new w(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&me(this.e/N)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return ve(this,new w(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=ve(this,new w(n,o)))===-1||o===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(n,o){var l,P,g,d,S=this,p=S.s;if(n=new w(n,o),o=n.s,!p||!o)return new w(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/N,b=n.e/N,f=S.c,B=n.c;if(!h||!b){if(!f||!B)return f?(n.s=-o,n):new w(B?S:NaN);if(!f[0]||!B[0])return B[0]?(n.s=-o,n):new w(f[0]?S:c==3?-0:0)}if(h=me(h),b=me(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=B),g.reverse(),o=p;o--;g.push(0));g.reverse()}else for(P=(d=(p=f.length)<(o=B.length))?p:o,p=o=0;o<P;o++)if(f[o]!=B[o]){d=f[o]<B[o];break}if(d&&(g=f,f=B,B=g,n.s=-n.s),o=(P=B.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=he-1;P>p;){if(f[--P]<B[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=he}f[P]-=B[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?Se(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var l,P,g=this;return n=new w(n,o),!g.c||!n.s||n.c&&!n.c[0]?new w(NaN):!n.c||g.c&&!g.c[0]?new w(g):(_==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,_),n=g.minus(l.times(n)),!n.c[0]&&_==1&&(n.s=g.s),n)},r.multipliedBy=r.times=function(n,o){var l,P,g,d,S,p,h,b,f,B,I,A,M,z,J,L=this,G=L.c,ee=(n=new w(n,o)).c;if(!G||!ee||!G[0]||!ee[0])return!L.s||!n.s||G&&!G[0]&&!ee||ee&&!ee[0]&&!G?n.c=n.e=n.s=null:(n.s*=L.s,!G||!ee?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=me(L.e/N)+me(n.e/N),n.s*=L.s,h=G.length,B=ee.length,h<B&&(M=G,G=ee,ee=M,g=h,h=B,B=g),g=h+B,M=[];g--;M.push(0));for(z=he,J=Be,g=B;--g>=0;){for(l=0,I=ee[g]%J,A=ee[g]/J|0,S=h,d=g+S;d>g;)b=G[--S]%J,f=G[S]/J|0,p=A*b+f*I,b=I*b+p%J*J+M[d]+l,l=(b/z|0)+(p/J|0)+A*f,M[d--]=b%z;M[d]=l}return l?++P:M.splice(0,1),Se(n,M,P)},r.negated=function(){var n=new w(this);return n.s=-n.s||null,n},r.plus=function(n,o){var l,P=this,g=P.s;if(n=new w(n,o),o=n.s,!g||!o)return new w(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/N,S=n.e/N,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new w(g/0);if(!p[0]||!h[0])return h[0]?n:new w(p[0]?P:g*0)}if(d=me(d),S=me(S),p=p.slice(),g=d-S){for(g>0?(S=d,l=h):(g=-g,l=p),l.reverse();g--;l.push(0));l.reverse()}for(g=p.length,o=h.length,g-o<0&&(l=h,h=p,p=l,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/he|0,p[o]=he===p[o]?0:p[o]%he;return g&&(p=[g].concat(p),++S),Se(n,p,S)},r.precision=r.sd=function(n,o){var l,P,g,d=this;if(n!=null&&n!==!!n)return H(n,1,j),o==null?o=c:H(o,0,8),R(new w(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*N+1,g=l[g]){for(;g%10==0;g/=10,P--);for(g=l[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return H(n,-Bt,Bt),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,l,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new w("0.5");if(p!==1||!S||!S[0])return new w(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+Y(d)),p==0||p==1/0?(o=ue(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=me((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new w(o)):l=new w(p+""),l.c[0]){for(h=l.e,p=h+b,p<3&&(p=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ue(g.c).slice(0,p)===(o=ue(l.c)).slice(0,p))if(l.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(R(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(R(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return R(l,l.e+a+1,c,n)},r.toExponential=function(n,o){return n!=null&&(H(n,0,j),n++),K(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(H(n,0,j),n=n+this.e+1),K(this,n,o)},r.toFormat=function(n,o,l){var P,g=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=C;else if(typeof l!="object")throw Error(re+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],B=S[1],I=g.s<0,A=I?f.slice(1):f,M=A.length;if(h&&(d=p,p=h,h=d,M-=d),p>0&&M>0){for(d=M%p||p,f=A.substr(0,d);d<M;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),I&&(f="-"+f)}P=B?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?B.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):B):f}return(l.prefix||"")+P+(l.suffix||"")},r.toFraction=function(n){var o,l,P,g,d,S,p,h,b,f,B,I,A=this,M=A.c;if(n!=null&&(p=new w(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(re+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+Y(p));if(!M)return new w(A);for(o=new w(i),b=l=new w(i),P=h=new w(i),I=ue(M),d=o.e=I.length-A.e-1,o.c[0]=xt[(S=d%N)<0?N+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=O,O=1/0,p=new w(I),h.c[0]=0;f=e(p,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,B=e(b,P,d,c).minus(A).abs().comparedTo(e(h,l,d,c).minus(A).abs())<1?[b,P]:[h,l],O=S,B},r.toNumber=function(){return+Y(this)},r.toPrecision=function(n,o){return n!=null&&H(n,1,j),K(this,n,o,2)},r.toString=function(n){var o,l=this,P=l.s,g=l.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=u||g>=y?Ke(ue(l.c),g):we(ue(l.c),g,"0"):n===10&&U?(l=R(new w(l),a+g+1,c),o=we(ue(l.c),l.e,"0")):(H(n,2,k.length,"Base"),o=t(we(ue(l.c),g,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return Y(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,m!=null&&w.set(m),w}function me(m){var e=m|0;return m>0||m===e?e:e-1}function ue(m){for(var e,t,s=1,r=m.length,i=m[0]+"";s<r;){for(e=m[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 ve(m,e){var t,s,r=m.c,i=e.c,a=m.s,c=e.s,u=m.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=u==y,!r||!i)return s?0:!r^t?1:-1;if(!s)return u>y^t?1:-1;for(c=(u=r.length)<(y=i.length)?u:y,a=0;a<c;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return u==y?0:u>y^t?1:-1}function H(m,e,t,s){if(m<e||m>t||m!==ce(m))throw Error(re+(s||"Argument")+(typeof m=="number"?m<e||m>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(m))}function Ze(m){var e=m.c.length-1;return me(m.e/N)==e&&m.c[e]%2!=0}function Ke(m,e){return(m.length>1?m.charAt(0)+"."+m.slice(1):m)+(e<0?"e":"e+")+e}function we(m,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);m=r+m}else if(s=m.length,++e>s){for(r=t,e-=s;--e;r+=t);m+=r}else e<s&&(m=m.slice(0,e)+"."+m.slice(e));return m}var q=Dt();var Ct=12;q.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Ct});var E=v(0),ae=v(1),ns=v("Infinity");function V(m,e){let t=new q(e.toString()),s=new q(10).pow(t);return m.times(s)}function v(m){return new q(m.toString())}var ie=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(ie||{}),Te=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(Te||{}),Ot=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Ot||{});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 Gt=require("@polkadot/util-crypto"),qt=require("@polkadot/util"),Fe=18,Qe=15,xe="0",os=12,as=2034,_e=63,ls=2090,et=1e3,We=(0,Gt.encodeAddress)((0,qt.stringToU8a)("modlomnipool".padEnd(32,"\0")),_e);var zs=require("@polkadot/types/lookup");var Ws=require("@polkadot/api-base/types/consts");var Xs=require("@polkadot/api-base/types/errors");var Ys=require("@polkadot/api-base/types/events");var $s=require("@polkadot/api-base/types/storage");var Js=require("@polkadot/api-base/types/submittable");var js=require("@polkadot/rpc-core/types/jsonrpc");var Vs=require("@polkadot/api-base/types/calls");var ir=require("@polkadot/types/types/registry");var lr=require("@polkadot/types/lookup");var ur=require("@polkadot/api-base/types/consts");var cr=require("@polkadot/api-base/types/errors");var mr=require("@polkadot/api-base/types/events");var pr=require("@polkadot/api-base/types/storage");var gr=require("@polkadot/api-base/types/submittable");var hr=require("@polkadot/rpc-core/types/jsonrpc");var dr=require("@polkadot/api-base/types/calls");var xr=require("@polkadot/types/types/registry");var Oe=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Ie=class extends Oe{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==xe){let O=this.api.consts.balances.existentialDeposit;return{id:xe,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:O.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:u}=t,{symbol:y,decimals:x}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:y,decimals:x,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,location:r?.toJSON(),existentialDeposit:u.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:c,isSufficient:u,existentialDeposit:y}=t,{symbol:x,decimals:O}=this.getToken(i.toString(),t,s),T=a.toNumber(),_=new Intl.DateTimeFormat("en-GB"),F=[x,"Bond",_.format(T)].join(" ");return{id:e,name:F,symbol:x+"b",decimals:O,icon:x,type:c.toString(),isSufficient:u.toHuman(),existentialDeposit:y.toString(),underlyingAssetId:i.toString(),maturity:T}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:c,assetType:u,isSufficient:y,existentialDeposit:x}=t,T=i.map(C=>C.toString()).map(C=>{let{symbol:k}=this.getToken(C,t,s);return[C,k]}),_=Object.fromEntries(T),F=Object.values(_);return{id:e,name:F.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:F.join("/"),type:u.toString(),isSufficient:y.toHuman(),existentialDeposit:x.toString(),meta:_}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=s?.find(c=>c.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:a}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,i,a,c]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),u=this.getSupportedAssets(s),y=this.normalizeMetadata(u,c),x=u.map(([{args:[O]},T])=>{let _=T.unwrap(),F=r.get(O.toString()),{assetType:C}=_;switch(C.toString()){case"Bond":let k=a.get(O.toString());return this.getBond(O.toString(),_,y,k);case"StableSwap":let U=i.get(O.toString());return this.getShares(O.toString(),_,y,U);case"External":return this.getExternal(O.toString(),_,t,F);default:return this.getToken(O.toString(),_,y,F)}});return e?x:x.filter(O=>this.isValidAsset(O))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var Ae=class extends Oe{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===xe?this.getSystemBalance(e):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 getErc20Balance(e,t){let{free:s,reserved:r,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(xe,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let i=t.filter(a=>a.type!=="Erc20").filter(a=>a.id!==xe).map(a=>[e,a.id]);return this.api.query.tokens.accounts.multi(i,a=>{let c=[];a.forEach((u,y)=>{let x=this.calculateFreeBalance(u),O=i[y][1];c.push([O,x])}),s(c)})}async subscribeErc20Balance(e,t,s){let r=t.filter(a=>a.type==="Erc20"),i=async()=>{let a=[];(await Promise.all(r.map(async u=>[u.id,await this.getErc20Balance(e,u.id)]))).forEach(([u,y])=>{a.push([u,y])}),s(a)};return await i(),this.api.rpc.chain.subscribeNewHeads(async()=>{i()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,a=new q(t),c=new q(s||i),u=new q(r||0n),y=c.gt(u)?c:u;return a.minus(y)}};var vt=require("@polkadot/util-crypto"),It=require("@galacticcouncil/math-liquidity-mining");var tt=class extends Oe{constructor(e){super(e)}secondsInYear=new q(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(u)).unwrap(),x=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,u,c)).unwrap(),O=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:x,priceAdjustment:O}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(u)).unwrap(),x=(await this.api.query.xykWarehouseLM.yieldFarm(e,u,c)).unwrap(),O=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:x,priceAdjustment:O}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new q(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),c=a.price.n.toString(),u=a.price.d.toString(),y;return Number(t)<Number(s)?y=(0,It.fixed_from_rational)(c,u):y=(0,It.fixed_from_rational)(u,c),y}getGlobalRewardPerPeriod(e,t,s,r){let a=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return a.gte(s)?s:a}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,vt.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,vt.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:c,globalFarm:u,priceAdjustment:y})=>{let x=new q(u.totalSharesZ.toString()),O=u.plannedYieldingPeriods.toString(),T=new q(u.yieldPerPeriod.toString()),_=new q(u.maxRewardPerPeriod.toString()),F=u.blocksPerPeriod.toString(),C=new q(c.multiplier.toString()).shiftedBy(-18),k=this.secondsInYear.div(new q(s).times(F)),U;if(x.isZero())U=T.times(C).times(k);else{let Se=this.getGlobalRewardPerPeriod(x,T,_,y);U=this.getPoolYieldPerPeriod(Se,C,x,y).times(k)}let w=new q(u.pendingRewards.toString()).plus(u.accumulatedPaidRewards.toString()),K=_.times(O);return w.div(K).gte(.99)?E:U.times(100)}).reduce((c,u)=>c.plus(u),E).toString():void 0}};var be=class extends Ae{pools=[];subs=[];assets=new Map([]);mem=0;memPools=Ve(e=>(console.log(this.getPoolType(),"mem pools",e,"\u2705"),this.getPools()));constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=await this.subscribe();let e=this.getPoolType();return console.log(e,`pools(${this.augmentedPools.length})`,"\u2705"),console.log(e,`subs(${this.subs.length})`,"\u2705"),this.augmentedPools}async subscribe(){let e=this.augmentedPools.map(async s=>{let r=[await this.subscribeTokensPoolBalance(s)];try{let i=await this.subscribePoolChange(s);r.push(i)}catch{}if(this.hasSystemAsset(s)){let i=await this.subscribeSystemPoolBalance(s);r.push(i)}if(this.hasErc20Asset(s)){let i=await this.subscribeErc20PoolBalance(s);r.push(i)}if(this.hasShareAsset(s)){let i=await this.subscribeSharePoolBalance(s);r.push(i)}return this.subscribeLog(s),r});return(await Promise.all(e)).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasShareAsset(e){return e.type==="Stableswap"&&e.id}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e()})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}subscribeSharePoolBalance(e){let t=this.assets.get(e.id);return this.subscribeTokenBalance(We,[t],this.updateBalancesCallback(e,()=>!0))}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,i])=>{let a=e.tokens.findIndex(c=>c.id==r);a>=0&&t(e,r)&&(e.tokens[a].balance=i.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(i=>i.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var st=class extends be{MAX_FINAL_WEIGHT=V(v(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,a])=>this.isActivePool(a.unwrap(),s)).map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=await this.getPoolDelta(u,c,s.toString());return this.poolsData.set(i.toString(),c),{address:u,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:u,repayTarget:y,feeCollector:x}=t,O=pe.calculateLinearWeights(r.toString(),i.toString(),c.toString(),u.toString(),s),[T,_]=a,F=T.toString(),C=v(O),k=_.toString(),U=this.MAX_FINAL_WEIGHT.minus(v(C)),[w,K,oe]=await Promise.all([this.isRepayFeeApplied(F,y.toString(),x.toString()),this.getBalance(e,F),this.getBalance(e,k)]);return{repayFeeApply:w,tokens:[{id:F,weight:C,balance:K.toString()},{id:k,weight:U,balance:oe.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=v(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var Ht=require("@polkadot/util-crypto"),Ut=require("@polkadot/util");function Q(m,e){return m.shiftedBy(-1*e).toString()}function ge(m){return m[0]/m[1]*100}function ne(m){return m[0]/m[1]}function de(m){return[m/et,et]}var rt=class extends be{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=s.map(async([{args:[u]},y])=>{let{hubReserve:x,shares:O,tradable:T}=y.unwrap(),_=await this.getBalance(t,u.toString());return{id:u.toString(),hubReserves:v(x.toString()),shares:v(O.toString()),tradeable:T.bits.toNumber(),balance:_.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:u,protocolFee:y}=s.unwrap();return{assetFee:de(u.toNumber()),protocolFee:de(y.toNumber()),min:de(a),max:de(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:de(a),max:de(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let a=e.tokens[i];if(r.isNone)return a;let c=r.unwrap();return this.updateTokenState(a,c)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i}=t;return{...e,hubReserves:v(s.toString()),shares:v(r.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return de(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return de(t)}getPoolId(){return(0,Ht.encodeAddress)((0,Ut.stringToU8a)("modlomnipool".padEnd(32,"\0")),_e)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var it=class extends be{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[a,c]=r.unwrap(),[u,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:u.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var ot=require("@polkadot/util-crypto");var Z=require("@galacticcouncil/math-stableswap"),se=class{static getPoolAddress(e){return(0,Z.pool_account_name)(e)}static calculateAmplification(e,t,s,r,i){return(0,Z.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return(0,Z.calculate_in_given_out)(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return(0,Z.calculate_add_one_asset)(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return(0,Z.calculate_shares_for_amount)(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return(0,Z.calculate_out_given_in)(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return(0,Z.calculate_liquidity_out_one_asset)(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return(0,Z.calculate_shares)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,Z.calculate_pool_trade_fee)(e,t,s)}};var nt=class extends be{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=this.getPoolAddress(u),[x,O]=await Promise.all([this.getPoolDelta(u,c,s.toString()),this.getPoolTokens(y,u,c)]);return this.stablePools.set(y,c),{address:y,id:u,type:"Stableswap",fee:de(c.fee.toNumber()),tokens:O,...x,...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,u=se.calculateAmplification(r.toString(),i.toString(),a.toString(),c.toString(),s),y=await this.api.query.tokens.totalIssuance(e);return{amplification:u,totalIssuance:y.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async u=>{let[y,x]=await Promise.all([this.api.query.stableswap.assetTradability(t,u.toString()),this.getBalance(e,u.toString())]);return{id:u.toString(),tradeable:y.bits.toNumber(),balance:x.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:u}=c.unwrap(),y=await this.getBalance(We,t);a.push({id:t,tradeable:u.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),s=se.getPoolAddress(t);return(0,ot.encodeAddress)((0,ot.blake2AsHex)(s),_e)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function at(m){return m.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 Xe=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"}},Ee=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 Re=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=Ve(e=>(console.log("Registry mem sync",e,"\u2705"),this.syncRegistry()));constructor(e){this.api=e,this.assetClient=new Ie(this.api),this.xykClient=new it(this.api),this.omniClient=new rt(this.api),this.lbpClient=new st(this.api),this.stableClient=new nt(this.api),this.clients=[this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}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 Xe(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):a=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),at(i));let c=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,s,r,i){let a;this.isDirectOmnipoolTrade(i)?a=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):a=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),at(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var Ye=(m,e)=>m===e?0:m==null?e==null?0:-1:e==null?m==null?0:1:typeof m.compare=="function"?m.compare(e):typeof e.compare=="function"?-e.compare(m):m<e?-1:m>e?1:0;var lt=(m,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(m(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var us=lt(()=>"illegal argument(s)"),zt=m=>{throw new us(m)};var cs=lt(()=>"index out of bounds"),Et=m=>{throw new cs(m)},ut=(m,e,t)=>(m<e||m>=t)&&Et(m);var Wt=23283064365386963e-26,ct=class{float(e=1){return this.int()*Wt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Wt-.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 mt=class extends ct{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var Xt=new mt(Math.random);var Yt=m=>m!=null&&typeof m!="function"&&m.length!==void 0;var $t=Object.getPrototypeOf({}),pt="function",Jt="string",ke=(m,e)=>{let t;if(m===e)return!0;if(m!=null){if(typeof m.equiv===pt)return m.equiv(e)}else return m==e;if(e!=null){if(typeof e.equiv===pt)return e.equiv(m)}else return m==e;return typeof m===Jt||typeof e===Jt?!1:(t=Object.getPrototypeOf(m),(t==null||t===$t)&&(t=Object.getPrototypeOf(e),t==null||t===$t)?hs(m,e):typeof m!==pt&&m.length!==void 0&&typeof e!==pt&&e.length!==void 0?ms(m,e):m instanceof Set&&e instanceof Set?ps(m,e):m instanceof Map&&e instanceof Map?gs(m,e):m instanceof Date&&e instanceof Date?m.getTime()===e.getTime():m instanceof RegExp&&e instanceof RegExp?m.toString()===e.toString():m!==m&&e!==e)},ms=(m,e,t=ke)=>{let s=m.length;if(s===e.length)for(;s-- >0&&t(m[s],e[s]););return s<0},ps=(m,e,t=ke)=>m.size===e.size&&t([...m.keys()].sort(),[...e.keys()].sort()),gs=(m,e,t=ke)=>m.size===e.size&&t([...m].sort(),[...e].sort()),hs=(m,e,t=ke)=>{if(Object.keys(m).length!==Object.keys(e).length)return!1;for(let s in m)if(!e.hasOwnProperty(s)||!t(m[s],e[s]))return!1;return!0};var Rt=class{value;constructor(e){this.value=e}deref(){return this.value}};var jt=m=>m instanceof Rt;var gt=class m{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Vt("next",this._head)}reverseIterator(){return Vt("prev",this.tail)}clear(){this.release()}compare(e,t=Ye){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,a=0;for(;s-- >0&&a===0;)a=t(r.value,i.value),r=r.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof m||Yt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!ke(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||Ye;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!jt(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*Vt(m,e){for(;e;)yield e.value,e=e[m]}var ht=class m extends gt{_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 m(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 m}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(ut(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(ut(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new m,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=Xt){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)&&zt("invalid indices: ${from} / ${to}");let i=new m,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=Ye){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,a=0;for(let u=0;u<t&&(a++,i=i.next,!!i);u++);let c=t;for(;a>0||c>0&&i;){let u;a===0?(u=i,i=i.next,c--):!i||c===0||e(s.value,i.value)<=0?(u=s,s=s.next,a--):(u=i,i=i.next,c--),this._tail?this._tail.next=u:this._head=u,u.prev=this._tail,this._tail=u}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),ut(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new m;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 dt=class m{map;items;opts;_size;constructor(e,t){let s={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=s.map(),this.items=new ht,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(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}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 m(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),i=Math.max(0,s-(r?r.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(r,e,t,s):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let s=this.map.get(e);return s?this.resetEntry(s):this.set(e,await t())}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{release:e,maxsize:t,maxlen:s}=this.opts;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),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?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(this.opts.update?.(t,e.value.v,s),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 ft=class extends Re{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new dt(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
+
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Le=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new m(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(u=>[u.id,u])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let c=this.calculateTradeFee(t,s),u=ge(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(c),x=this.calculateInGivenOut(e,y),O=e.balanceIn.div(this.maxInRatio);return x.isGreaterThan(O)&&i.push("MaxInRatioExceeded"),{amountIn:x,calculatedIn:x,amountOut:t,feePct:u,errors:i}}else{let c=this.calculateInGivenOut(e,t),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,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),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),u=this.calculateTradeFee(c,s),y=ge(this.repayFeeApply?s.repayFee:s.exchangeFee),x=c.minus(u),O=e.balanceOut.div(this.maxOutRatio);return x.isGreaterThan(O)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:x,feePct:y,errors:i}}}calculateInGivenOut(e,t){let s=pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=pe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),V(ae,e.decimalsOut).toString());return v(t)}spotPriceOutGivenIn(e){let t=pe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),V(ae,e.decimalsIn).toString());return v(t)}calculateTradeFee(e,t){let s=pe.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return v(s)}};var D=require("@galacticcouncil/math-omnipool");var X=class{static calculateSpotPrice(e,t,s,r){return(0,D.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,D.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,a,c,u,y){return(0,D.calculate_in_given_out)(e,t,s,r,i,a,c,u,y)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,D.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,a,c,u,y){return(0,D.calculate_out_given_in)(e,t,s,r,i,a,c,u,y)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,D.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,D.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,D.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,a,c,u){return(0,D.calculate_liquidity_out)(e,t,s,r,i,a,c,u)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,c,u){return(0,D.calculate_liquidity_lrna_out)(e,t,s,r,i,a,c,u)}static calculateCapDifference(e,t,s,r){let i=q(t),a=q(e),c=q(r),y=q(s).shiftedBy(-18);if(i.div(c).lt(y)){let O=y.times(c).minus(i).times(a),T=i.times(q(1).minus(y));return O.div(T).toFixed(0)}else return"0"}static verifyAssetCap(e,t,s,r){return(0,D.verify_asset_cap)(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return(0,D.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,D.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,D.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,D.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,D.is_remove_liquidity_allowed)(e)}};var Me=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new m(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(x=>[x.id,x])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance),u=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:u,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),c=r===E?E:a.div(r).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),x=X.isBuyAllowed(e.tradeableOut);(!y||!x)&&u.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&u.push("InsufficientTradingAmount");let O=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(O)&&u.push("MaxOutRatioExceeded");let T=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(T)&&u.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:c.toNumber(),errors:u}}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),u=[],y=X.isSellAllowed(e.tradeableIn),x=X.isBuyAllowed(e.tradeableOut);(!y||!x)&&u.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&u.push("InsufficientTradingAmount");let O=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(O)&&u.push("MaxInRatioExceeded");let T=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(T)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:c.toNumber(),errors:u}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=X.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ne(s.assetFee).toString():E.toString(),s?ne(s.protocolFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateLrnaInGivenOut(e,t,s){let r=X.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ne(s.assetFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=X.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ne(s.assetFee).toString():E.toString(),s?ne(s.protocolFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateOutGivenLrnaIn(e,t,s){let r=X.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ne(s.assetFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=X.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return v(t).shiftedBy(-1*(Fe-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=X.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return v(t).shiftedBy(-1*(Fe-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=X.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Fe-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=X.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Fe-e.decimalsIn)).decimalPlaces(0,1)}};var De=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new m(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,u,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=u,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(x=>[x.id,x])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance),u=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?Qe:r.tradeable,tradeableOut:this.id===t?Qe:i.tradeable,assetInED:u,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=ge(s.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=ge(s.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,s){let r=se.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ne(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateAddOneAsset(e,t,s){let r=se.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?ne(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateSharesForAmount(e,t,s){let r=se.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?ne(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=V(ae,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,s){let r=se.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ne(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateWithdrawOneAsset(e,t,s){let r=se.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?ne(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateShares(e,t,s){let r=se.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?ne(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=V(ae,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=se.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return v(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var $=require("@galacticcouncil/math-xyk"),ye=class{static getSpotPrice(e,t,s){return(0,$.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,$.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,$.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,$.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,$.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,$.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,$.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,$.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,$.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,$.calculate_liquidity_out_asset_b)(e,t,s,r)}};var Ce=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new m(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(x=>[x.id,x])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance),u=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,assetInED:u,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=ge(s.exchangeFee),c=r.plus(i),u=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&u.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&u.push("MaxOutRatioExceeded");let x=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(x)&&u.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:r,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=ge(s.exchangeFee),c=r.minus(i),u=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&u.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&u.push("MaxInRatioExceeded");let x=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(x)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:a,errors:u}}calculateInGivenOut(e,t){let s=ye.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=ye.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=ye.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=V(ae,18-e.decimalsOut);return v(t).div(s)}spotPriceOutGivenIn(e){let t=ye.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=V(ae,18-e.decimalsIn);return v(t).div(s)}calculateTradeFee(e,t){let s=ye.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return v(s)}};var Ge=class{static get(e){switch(e.type){case"Xyk":return Ce.fromPool(e);case"Omnipool":return Me.fromPool(e);case"Lbp":return Le.fromPool(e);case"Stableswap":return De.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Ne=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new ze,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,meta:r.meta,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(c=>this.validPath(c,s)).map(c=>this.toHops(c,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,Ge.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let a=t.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function ds(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function qe(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function kt(m,e){return ae.minus(e.div(m)).multipliedBy(100).decimalPlaces(2)}function Lt(m,e){return e.div(m).minus(ae).multipliedBy(100).decimalPlaces(2)}var $e=class extends Ne{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,a=r[r.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[s,r]}}getPoolFeeRange(e){let t=e.min?ge(e.min):void 0,s=e.max?ge(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ee(e,t);let u;if(r)u=await this.toSellSwaps(s,r,a);else{let R=c.map(async n=>await this.toSellSwaps(s,n,a)),Y=await Promise.all(R);u=this.findBestSellRoute(Y)}let y=u[0],x=u[u.length-1],O=this.isDirectTrade(u),T=u.map(R=>R.spotPrice.shiftedBy(-1*R.assetOutDecimals)).reduce((R,Y)=>R.multipliedBy(Y)),_=V(T,x.assetOutDecimals),F=O?x.calculatedOut:this.calculateDelta0Y(y.amountIn,u,a),C=x.amountOut,k=O?x.tradeFeePct:kt(F,C).toNumber(),U=F.minus(C),w=this.getRouteFeeRange(u),K=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(_),oe=qe(F,K),Se=R=>this.poolService.buildSellTx(e,t,y.amountIn,R,u.map(Y=>Y));return{type:"Sell",amountIn:y.amountIn,amountOut:x.amountOut,spotPrice:_,tradeFee:U,tradeFeePct:k,tradeFeeRange:w,priceImpactPct:oe.toNumber(),swaps:u,toTx:Se,toHuman(){return{type:"Sell",amountIn:Q(y.amountIn,y.assetInDecimals),amountOut:Q(x.amountOut,x.assetOutDecimals),spotPrice:Q(_,x.assetOutDecimals),tradeFee:Q(U,x.assetOutDecimals),tradeFeePct:k,tradeFeeRange:w,priceImpactPct:oe.toNumber(),swaps:u.map(R=>R.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1]:y=e;let x=c.calculateOutGivenIn(u,y);r.push(x)}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 u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1].amountOut:y=V(v(e),u.decimalsIn).decimalPlaces(0,1);let x=await this.poolService.getPoolFees(u.assetOut,c),{amountOut:O,calculatedOut:T,feePct:_,errors:F}=c.validateAndSell(u,y,x),C=this.getPoolFeeRange(x),k=c.spotPriceOutGivenIn(u),U=y.shiftedBy(-1*u.decimalsIn).multipliedBy(k),w=qe(T,U);r.push({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountIn:y,calculatedOut:T,amountOut:O,spotPrice:k,tradeFeePct:_,tradeFeeRange:C,priceImpactPct:w.toNumber(),errors:F,toHuman(){return{...a,amountIn:Q(y,u.decimalsIn),calculatedOut:Q(T,u.decimalsOut),amountOut:Q(O,u.decimalsOut),spotPrice:Q(k,u.decimalsOut),tradeFeePct:_,tradeFeeRange:C,priceImpactPct:w.toNumber(),errors:F}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(w=>w.tokens.find(K=>K.id===e)).filter(w=>!!w).sort((w,K)=>Number(K.balance)-Number(w.balance)),{balance:c,decimals:u}=a[0],x=v(c).shiftedBy(-1*u).div(100).multipliedBy(.1),O=i.map(async w=>await this.toSellSwaps(x,w,r)),T=await Promise.all(O),_=this.findBestSellRoute(T),F=await this.toSellSwaps("1",_,r),C=F.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,K)=>w.multipliedBy(K)),k=F[F.length-1].assetOutDecimals;return{amount:V(C,k),decimals:k}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,a=r[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ee(e,t);let u;if(r)u=await this.toBuySwaps(s,r,a);else{let R=c.map(async n=>await this.toBuySwaps(s,n,a)),Y=await Promise.all(R);u=this.findBestBuyRoute(Y)}let y=u[u.length-1],x=u[0],O=this.isDirectTrade(u),T=u.map(R=>R.spotPrice.shiftedBy(-1*R.assetInDecimals)).reduce((R,Y)=>R.multipliedBy(Y)),_=V(T,x.assetInDecimals),F=O?x.calculatedIn:this.calculateDelta0X(y.amountOut,u,a),C=x.amountIn,k=O?x.tradeFeePct:Lt(F,C).toNumber(),U=C.minus(F),w=this.getRouteFeeRange(u),K=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(_),oe;F.isZero()?oe=-100:oe=qe(K,F).toNumber();let Se=R=>this.poolService.buildBuyTx(e,t,y.amountOut,R,u.map(Y=>Y));return{type:"Buy",amountOut:y.amountOut,amountIn:x.amountIn,spotPrice:_,tradeFee:U,tradeFeePct:k,tradeFeeRange:w,priceImpactPct:oe,swaps:u,toTx:Se,toHuman(){return{type:"Buy",amountOut:Q(y.amountOut,y.assetOutDecimals),amountIn:Q(x.amountIn,x.assetInDecimals),spotPrice:Q(_,x.assetInDecimals),tradeFee:Q(U,x.assetInDecimals),tradeFeePct:k,tradeFeeRange:w,priceImpactPct:oe,swaps:u.map(R=>R.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=r[0];let x=c.calculateInGivenOut(u,y);r.unshift(x)}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 u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=V(v(e),u.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let x=await this.poolService.getPoolFees(u.assetOut,c),{amountIn:O,calculatedIn:T,feePct:_,errors:F}=c.validateAndBuy(u,y,x),C=this.getPoolFeeRange(x),k=c.spotPriceInGivenOut(u),U=y.shiftedBy(-1*u.decimalsOut).multipliedBy(k),w;T.isZero()?w=-100:w=qe(U,T).toNumber(),r.unshift({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountOut:y,calculatedIn:T,amountIn:O,spotPrice:k,tradeFeePct:_,tradeFeeRange:C,priceImpactPct:w,errors:F,toHuman(){return{...a,amountOut:Q(y,u.decimalsOut),calculatedIn:Q(T,u.decimalsIn),amountIn:Q(O,u.decimalsIn),spotPrice:Q(k,u.decimalsIn),tradeFeePct:_,tradeFeeRange:C,priceImpactPct:w,errors:F}}})}return r}};function fs(m,e){let t=[];return JSON.stringify(m,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function Ps(m,e,t){let s;return JSON.stringify(m,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,FarmClient,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
|
package/build/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Ue=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 Ht=5,ve=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new Ue,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>Ht)return r;let u=c[c.length-1];(s===null||u[0]===s)&&r.push(c),e.get(u[0])?.forEach(x=>{if(this.isNotVisited(x,c)){let B=[...c];B.push(x),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),u=parseInt(a);s.get(c)?.push([u,r])}return s}};function ut(m){let e={};for(let t of m){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let i=0;i<s;i++){if(r==i)continue;let a=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(a)}}}return e}var Ie=class{getProposals(e,t,s){let r=ut(s),i=Object.keys(r),a=i.map(x=>r[x]).flat(),c=new ve,u=c.buildAndPopulateGraph(i,a),y=c.findPaths(u,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let 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 ze=(m,e=new Map)=>t=>{let s;return e.has(t)?e.get(t):(e.set(t,s=m(t)),s)};var Ut=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,ct=Math.ceil,oe=Math.floor,V="[BigNumber Error] ",St=V+"Number primitive has more than 15 significant digits: ",ce=1e14,T=14,mt=9007199254740991,pt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],be=1e7,$=1e9;function wt(m){var e,t,s,r=w.prototype={constructor:w,toString:null,valueOf:null},i=new w(1),a=20,c=4,u=-7,y=21,x=-1e7,B=1e7,N=!1,F=1,_=0,D={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},k="0123456789abcdefghijklmnopqrstuvwxyz",H=!0;function w(n,o){var l,P,g,d,S,p,h,b,f=this;if(!(f instanceof w))return new w(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<x?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>B?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!Ut.test(b=String(n)))return s(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(q(o,2,k.length,"Base"),o==10&&H)return f=new w(n),E(f,a+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return s(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,w.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(St+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=k.slice(0,o),d=S=0,h=b.length;S<h;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return s(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&w.DEBUG&&h>15&&(n>mt||n!==oe(n)))throw Error(St+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<x)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%T,d<0&&(S+=T),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=T;S<h;)f.c.push(+b.slice(S,S+=T));S=T-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}w.clone=wt,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],q(l,0,$,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],q(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(q(l[0],-$,0,o),q(l[1],0,$,o),u=l[0],y=l[1]):(q(l,-$,$,o),u=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)q(l[0],-$,-1,o),q(l[1],1,$,o),x=l[0],B=l[1];else if(q(l,-$,$,o),l)x=-(B=l<0?-l:l);else throw Error(V+o+" cannot be zero: "+l);if(n.hasOwnProperty(o="CRYPTO"))if(l=n[o],l===!!l)if(l)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))N=l;else throw N=!l,Error(V+"crypto unavailable");else N=l;else throw Error(V+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],q(l,0,9,o),F=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],q(l,0,$,o),_=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")D=l;else throw Error(V+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))H=l.slice(0,10)=="0123456789",k=l;else throw Error(V+o+" invalid: "+l)}else throw Error(V+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[u,y],RANGE:[x,B],CRYPTO:N,MODULO_MODE:F,POW_PRECISION:_,FORMAT:D,ALPHABET:k}},w.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!w.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-$&&g<=$&&g===oe(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%T,o<1&&(o+=T),String(P[0]).length==o){for(o=0;o<P.length;o++)if(l=P[o],l<0||l>=ce||l!==oe(l))break e;if(l!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(V+"Invalid BigNumber: "+n)},w.maximum=w.max=function(){return se(arguments,-1)},w.minimum=w.min=function(){return se(arguments,1)},w.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return oe(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,S,p,h=0,b=[],f=new w(i);if(l==null?l=a:q(l,0,$),S=ct(l/T),N)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));h<S;)p=P[h]*131072+(P[h+1]>>>11),p>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(p%1e14),h+=2);h=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);h<S;)p=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],p>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(p%1e14),h+=7);h=S/7}else throw N=!1,Error(V+"crypto unavailable");if(!N)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],l%=T,S&&l&&(p=pt[T-l],b[h]=oe(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=T);for(h=1,p=b[0];p>=10;p/=10,h++);h<T&&(d-=T-h)}return f.e=d,f.c=b,f}}(),w.sum=function(){for(var n=1,o=arguments,l=new w(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var S,p=[0],h,b=0,f=l.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(l.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(l,P,g,d,S){var p,h,b,f,O,I,A,M,U=l.indexOf("."),Y=a,L=c;for(U>=0&&(f=_,_=0,l=l.replace(".",""),M=new w(P),I=M.pow(l.length-U),_=f,M.c=o(fe(ne(I.c),I.e,"0"),10,g,n),M.e=M.c.length),A=o(l,P,g,S?(p=k,n):(p=n,k)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(U<0?--b:(I.c=A,I.e=b,I.s=d,I=e(I,M,Y,L,g),A=I.c,O=I.r,b=I.e),h=b+Y+1,U=A[h],f=g/2,O=O||h<0||A[h+1]!=null,O=L<4?(U!=null||O)&&(L==0||L==(I.s<0?3:2)):U>f||U==f&&(L==4||O||L==6&&A[h-1]&1||L==(I.s<0?8:7)),h<1||!A[0])l=O?fe(p.charAt(1),-Y,p.charAt(0)):p.charAt(0);else{if(A.length=h,O)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(U=0,l="";U<=f;l+=p.charAt(A[U++]));l=fe(l,b,p.charAt(0))}return l}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,O=P.length,I=g%be,A=g/be|0;for(P=P.slice();O--;)h=P[O]%be,b=P[O]/be|0,S=A*h+b*I,p=I*h+S%be*be+f,f=(p/d|0)+(S/be|0)+A*b,P[O]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function l(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,O,I,A,M,U,Y,L,C,Z,He,at,lt,ge,Be,ie=P.s==g.s?1:-1,Q=P.c,z=g.c;if(!Q||!Q[0]||!z||!z[0])return new w(!P.s||!g.s||(Q?z&&Q[0]==z[0]:!z)?NaN:Q&&Q[0]==0||!z?ie*0:ie/0);for(U=new w(ie),Y=U.c=[],b=P.e-g.e,ie=d+b+1,p||(p=ce,b=ae(P.e/T)-ae(g.e/T),ie=ie/T|0),f=0;z[f]==(Q[f]||0);f++);if(z[f]>(Q[f]||0)&&b--,ie<0)Y.push(1),O=!0;else{for(at=Q.length,ge=z.length,f=0,ie+=2,I=oe(p/(z[0]+1)),I>1&&(z=n(z,I,p),Q=n(Q,I,p),ge=z.length,at=Q.length),He=ge,L=Q.slice(0,ge),C=L.length;C<ge;L[C++]=0);Be=z.slice(),Be=[0].concat(Be),lt=z[0],z[1]>=p/2&<++;do{if(I=0,h=o(z,L,ge,C),h<0){if(Z=L[0],ge!=C&&(Z=Z*p+(L[1]||0)),I=oe(Z/lt),I>1)for(I>=p&&(I=p-1),A=n(z,I,p),M=A.length,C=L.length;o(A,L,M,C)==1;)I--,l(A,ge<M?Be:z,M,p),M=A.length,h=1;else I==0&&(h=I=1),A=z.slice(),M=A.length;if(M<C&&(A=[0].concat(A)),l(L,A,C,p),C=L.length,h==-1)for(;o(z,L,ge,C)<1;)I++,l(L,ge<C?Be:z,C,p),C=L.length}else h===0&&(I++,L=[0]);Y[f++]=I,L[0]?L[C++]=Q[He]||0:(L=[Q[He]],C=1)}while((He++<at||L[0]!=null)&&ie--);O=L[0]!=null,Y[0]||Y.splice(0,1)}if(p==ce){for(f=1,ie=Y[0];ie>=10;ie/=10,f++);E(U,d+(U.e=f+b*T-1)+1,S,O)}else U.e=b,U.r=+O;return U}}();function J(n,o,l,P){var g,d,S,p,h;if(l==null?l=c:q(l,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ne(n.c),h=P==1||P==2&&(S<=u||S>=y)?We(h,S):fe(h,S,"0");else if(n=E(new w(n),o,l),d=n.e,h=ne(n.c),p=h.length,P==1||P==2&&(o<=d||d<=u)){for(;p<o;h+="0",p++);h=We(h,d)}else if(o-=S,h=fe(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function se(n,o){for(var l,P,g=1,d=new w(n[0]);g<n.length;g++)P=new w(n[g]),(!P.s||(l=Se(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function de(n,o,l){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(l=P+l*T-1)>B?n.c=n.e=null:l<x?n.c=[n.e=0]:(n.e=l,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,h){var b,f=p?S:S.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(O,I,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?I:O}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new w(f,b);if(w.DEBUG)throw Error(V+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function E(n,o,l,P){var g,d,S,p,h,b,f,O=n.c,I=pt;if(O){e:{for(g=1,p=O[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=T,S=o,h=O[b=0],f=oe(h/I[g-S-1]%10);else if(b=ct((d+1)/T),b>=O.length)if(P){for(;O.length<=b;O.push(0));h=f=0,g=1,d%=T,S=d-T+1}else break e;else{for(h=p=O[b],g=1;p>=10;p/=10,g++);d%=T,S=d-T+g,f=S<0?0:oe(h/I[g-S-1]%10)}if(P=P||o<0||O[b+1]!=null||(S<0?h:h%I[g-S-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?S>0?h/I[g-S]:0: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]=I[(T-o%T)%T],n.e=-o||0):O[0]=n.e=0,n;if(d==0?(O.length=b,p=1,b--):(O.length=b+1,p=I[T-d],O[b]=S>0?oe(h/I[g-S]%I[S])*p:0),P)for(;;)if(b==0){for(d=1,S=O[0];S>=10;S/=10,d++);for(S=O[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,O[0]==ce&&(O[0]=1));break}else{if(O[b]+=p,O[b]!=ce)break;O[b--]=0,p=1}for(d=O.length;O[--d]===0;O.pop());}n.e>B?n.c=n.e=null:n.e<x&&(n.c=[n.e=0])}return n}function X(n){var o,l=n.e;return l===null?n.toString():(o=ne(n.c),o=l<=u||l>=y?We(o,l):fe(o,l,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new w(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return Se(this,new w(n,o))},r.decimalPlaces=r.dp=function(n,o){var l,P,g,d=this;if(n!=null)return q(n,0,$),o==null?o=c:q(o,0,8),E(new w(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-ae(this.e/T))*T,g=l[g])for(;g%10==0;g/=10,P--);return P<0&&(P=0),P},r.dividedBy=r.div=function(n,o){return e(this,new w(n,o),a,c)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new w(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var l,P,g,d,S,p,h,b,f,O=this;if(n=new w(n),n.c&&!n.isInteger())throw Error(V+"Exponent not an integer: "+X(n));if(o!=null&&(o=new w(o)),p=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 w(Math.pow(+X(O),p?n.s*(2-Xe(n)):+X(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new w(NaN);P=!h&&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||p&&O.c[1]>=24e7:O.c[0]<8e13||p&&O.c[0]<=9999975e7)))return d=O.s<0&&Xe(n)?-0:0,O.e>-1&&(d=1/d),new w(h?1/d:d);_&&(d=ct(_/T+2))}for(p?(l=new w(.5),h&&(n.s=1),b=Xe(n)):(g=Math.abs(+X(n)),b=g%2),f=new w(i);;){if(b){if(f=f.times(O),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(g){if(g=oe(g/2),g===0)break;b=g%2}else if(n=n.times(l),E(n,n.e+1,1),n.e>14)b=Xe(n);else{if(g=+X(n),g===0)break;b=g%2}O=O.times(O),d?O.c&&O.c.length>d&&(O.c.length=d):P&&(O=O.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?E(f,_,c,S):f)},r.integerValue=function(n){var o=new w(this);return n==null?n=c:q(n,0,8),E(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return Se(this,new w(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return Se(this,new w(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=Se(this,new w(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&ae(this.e/T)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return Se(this,new w(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=Se(this,new w(n,o)))===-1||o===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(n,o){var l,P,g,d,S=this,p=S.s;if(n=new w(n,o),o=n.s,!p||!o)return new w(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/T,b=n.e/T,f=S.c,O=n.c;if(!h||!b){if(!f||!O)return f?(n.s=-o,n):new w(O?S:NaN);if(!f[0]||!O[0])return O[0]?(n.s=-o,n):new w(f[0]?S:c==3?-0:0)}if(h=ae(h),b=ae(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=O),g.reverse(),o=p;o--;g.push(0));g.reverse()}else for(P=(d=(p=f.length)<(o=O.length))?p:o,p=o=0;o<P;o++)if(f[o]!=O[o]){d=f[o]<O[o];break}if(d&&(g=f,f=O,O=g,n.s=-n.s),o=(P=O.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=ce-1;P>p;){if(f[--P]<O[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=ce}f[P]-=O[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?de(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var l,P,g=this;return n=new w(n,o),!g.c||!n.s||n.c&&!n.c[0]?new w(NaN):!n.c||g.c&&!g.c[0]?new w(g):(F==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,F),n=g.minus(l.times(n)),!n.c[0]&&F==1&&(n.s=g.s),n)},r.multipliedBy=r.times=function(n,o){var l,P,g,d,S,p,h,b,f,O,I,A,M,U,Y,L=this,C=L.c,Z=(n=new w(n,o)).c;if(!C||!Z||!C[0]||!Z[0])return!L.s||!n.s||C&&!C[0]&&!Z||Z&&!Z[0]&&!C?n.c=n.e=n.s=null:(n.s*=L.s,!C||!Z?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=ae(L.e/T)+ae(n.e/T),n.s*=L.s,h=C.length,O=Z.length,h<O&&(M=C,C=Z,Z=M,g=h,h=O,O=g),g=h+O,M=[];g--;M.push(0));for(U=ce,Y=be,g=O;--g>=0;){for(l=0,I=Z[g]%Y,A=Z[g]/Y|0,S=h,d=g+S;d>g;)b=C[--S]%Y,f=C[S]/Y|0,p=A*b+f*I,b=I*b+p%Y*Y+M[d]+l,l=(b/U|0)+(p/Y|0)+A*f,M[d--]=b%U;M[d]=l}return l?++P:M.splice(0,1),de(n,M,P)},r.negated=function(){var n=new w(this);return n.s=-n.s||null,n},r.plus=function(n,o){var l,P=this,g=P.s;if(n=new w(n,o),o=n.s,!g||!o)return new w(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/T,S=n.e/T,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new w(g/0);if(!p[0]||!h[0])return h[0]?n:new w(p[0]?P:g*0)}if(d=ae(d),S=ae(S),p=p.slice(),g=d-S){for(g>0?(S=d,l=h):(g=-g,l=p),l.reverse();g--;l.push(0));l.reverse()}for(g=p.length,o=h.length,g-o<0&&(l=h,h=p,p=l,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/ce|0,p[o]=ce===p[o]?0:p[o]%ce;return g&&(p=[g].concat(p),++S),de(n,p,S)},r.precision=r.sd=function(n,o){var l,P,g,d=this;if(n!=null&&n!==!!n)return q(n,1,$),o==null?o=c:q(o,0,8),E(new w(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*T+1,g=l[g]){for(;g%10==0;g/=10,P--);for(g=l[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return q(n,-mt,mt),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,l,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new w("0.5");if(p!==1||!S||!S[0])return new w(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+X(d)),p==0||p==1/0?(o=ne(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=ae((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new w(o)):l=new w(p+""),l.c[0]){for(h=l.e,p=h+b,p<3&&(p=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ne(g.c).slice(0,p)===(o=ne(l.c)).slice(0,p))if(l.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(E(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(E(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return E(l,l.e+a+1,c,n)},r.toExponential=function(n,o){return n!=null&&(q(n,0,$),n++),J(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(q(n,0,$),n=n+this.e+1),J(this,n,o)},r.toFormat=function(n,o,l){var P,g=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=D;else if(typeof l!="object")throw Error(V+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],O=S[1],I=g.s<0,A=I?f.slice(1):f,M=A.length;if(h&&(d=p,p=h,h=d,M-=d),p>0&&M>0){for(d=M%p||p,f=A.substr(0,d);d<M;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),I&&(f="-"+f)}P=O?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?O.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):O):f}return(l.prefix||"")+P+(l.suffix||"")},r.toFraction=function(n){var o,l,P,g,d,S,p,h,b,f,O,I,A=this,M=A.c;if(n!=null&&(p=new w(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(V+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+X(p));if(!M)return new w(A);for(o=new w(i),b=l=new w(i),P=h=new w(i),I=ne(M),d=o.e=I.length-A.e-1,o.c[0]=pt[(S=d%T)<0?T+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new w(I),h.c[0]=0;f=e(p,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,O=e(b,P,d,c).minus(A).abs().comparedTo(e(h,l,d,c).minus(A).abs())<1?[b,P]:[h,l],B=S,O},r.toNumber=function(){return+X(this)},r.toPrecision=function(n,o){return n!=null&&q(n,1,$),J(this,n,o,2)},r.toString=function(n){var o,l=this,P=l.s,g=l.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=u||g>=y?We(ne(l.c),g):fe(ne(l.c),g,"0"):n===10&&H?(l=E(new w(l),a+g+1,c),o=fe(ne(l.c),l.e,"0")):(q(n,2,k.length,"Base"),o=t(fe(ne(l.c),g,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return X(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,m!=null&&w.set(m),w}function ae(m){var e=m|0;return m>0||m===e?e:e-1}function ne(m){for(var e,t,s=1,r=m.length,i=m[0]+"";s<r;){for(e=m[s++]+"",t=T-e.length;t--;e="0"+e);i+=e}for(r=i.length;i.charCodeAt(--r)===48;);return i.slice(0,r+1||1)}function Se(m,e){var t,s,r=m.c,i=e.c,a=m.s,c=e.s,u=m.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=u==y,!r||!i)return s?0:!r^t?1:-1;if(!s)return u>y^t?1:-1;for(c=(u=r.length)<(y=i.length)?u:y,a=0;a<c;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return u==y?0:u>y^t?1:-1}function q(m,e,t,s){if(m<e||m>t||m!==oe(m))throw Error(V+(s||"Argument")+(typeof m=="number"?m<e||m>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(m))}function Xe(m){var e=m.c.length-1;return ae(m.e/T)==e&&m.c[e]%2!=0}function We(m,e){return(m.length>1?m.charAt(0)+"."+m.slice(1):m)+(e<0?"e":"e+")+e}function fe(m,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);m=r+m}else if(s=m.length,++e>s){for(r=t,e-=s;--e;r+=t);m+=r}else e<s&&(m=m.slice(0,e)+"."+m.slice(e));return m}var G=wt();var zt=12;G.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:zt});var R=v(0),le=v(1),ar=v("Infinity");function j(m,e){let t=new G(e.toString()),s=new G(10).pow(t);return m.times(s)}function v(m){return new G(m.toString())}var re=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(re||{}),Ae=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(Ae||{}),Ot=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Ot||{});import{calculate_in_given_out as Xt,calculate_out_given_in as Wt,calculate_linear_weights as Yt,calculate_pool_trade_fee as $t,get_spot_price as Jt}from"@galacticcouncil/math-lbp";var me=class{static getSpotPrice(e,t,s,r,i){return Jt(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return Xt(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return Wt(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return Yt(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return $t(e,t,s)}};import{encodeAddress as jt}from"@polkadot/util-crypto";import{stringToU8a as Kt}from"@polkadot/util";var Ne=18,gt=15,we="0",hr=12,dr=2034,Te=63,fr=2090,ht=1e3,Ye=jt(Kt("modlomnipool".padEnd(32,"\0")),Te);function xt(m,e){let t=[];return JSON.stringify(m,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function br(m,e,t){let s;return JSON.stringify(m,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";var ye=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Fe=class extends ye{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==we){let F=this.api.consts.balances.existentialDeposit;return{id:we,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:F.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:u}=t,{symbol:y,decimals:x}=s.get(e)??{},B=this.parseLocation("parachain",r);return{id:e,name:i.toHuman(),symbol:y,decimals:x,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,origin:B,externalId:this.parseLocation(2094===B?"generalKey":"generalIndex",r),existentialDeposit:u.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:c,isSufficient:u,existentialDeposit:y}=t,{symbol:x,decimals:B}=this.getToken(i.toString(),t,s),N=a.toNumber(),F=new Intl.DateTimeFormat("en-GB"),_=[x,"Bond",F.format(N)].join(" ");return{id:e,name:_,symbol:x+"b",decimals:B,icon:x,type:c.toString(),isSufficient:u.toHuman(),existentialDeposit:y.toString(),underlyingAssetId:i.toString(),maturity:N}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:c,assetType:u,isSufficient:y,existentialDeposit:x}=t,N=i.map(D=>D.toString()).map(D=>{let{symbol:k}=this.getToken(D,t,s);return[D,k]}),F=Object.fromEntries(N),_=Object.values(F);return{id:e,name:_.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:_.join("/"),type:u.toString(),isSufficient:y.toHuman(),existentialDeposit:x.toString(),meta:F}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=s?.find(c=>c.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:a}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,i,a,c]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),u=this.getSupportedAssets(s),y=this.normalizeMetadata(u,c),x=u.map(([{args:[B]},N])=>{let F=N.unwrap(),_=r.get(B.toString()),{assetType:D}=F;switch(D.toString()){case"Bond":let k=a.get(B.toString());return this.getBond(B.toString(),F,y,k);case"StableSwap":let H=i.get(B.toString());return this.getShares(B.toString(),F,y,H);case"External":return this.getExternal(B.toString(),F,t,_);default:return this.getToken(B.toString(),F,y,_)}});return e?x:x.filter(B=>this.isValidAsset(B))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}parseLocation(e,t){if(t){let s=xt(t.toJSON(),e);return s&&s[e]}else return}};var _e=class extends ye{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===we?this.getSystemBalance(e):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 getErc20Balance(e,t){let{free:s,reserved:r,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(we,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let i=t.filter(a=>a.type!=="Erc20").filter(a=>a.id!==we).map(a=>[e,a.id]);return this.api.query.tokens.accounts.multi(i,a=>{let c=[];a.forEach((u,y)=>{let x=this.calculateFreeBalance(u),B=i[y][1];c.push([B,x])}),s(c)})}async subscribeErc20Balance(e,t,s){let r=t.filter(a=>a.type==="Erc20"),i=async()=>{let a=[];(await Promise.all(r.map(async u=>[u.id,await this.getErc20Balance(e,u.id)]))).forEach(([u,y])=>{a.push([u,y])}),s(a)};return await i(),this.api.rpc.chain.subscribeNewHeads(async()=>{i()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,a=new G(t),c=new G(s||i),u=new G(r||0n),y=c.gt(u)?c:u;return a.minus(y)}};import{isAddress as Bt}from"@polkadot/util-crypto";import{fixed_from_rational as vt}from"@galacticcouncil/math-liquidity-mining";var dt=class extends ye{constructor(e){super(e)}secondsInYear=new G(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(u)).unwrap(),x=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:x,priceAdjustment:B}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(u)).unwrap(),x=(await this.api.query.xykWarehouseLM.yieldFarm(e,u,c)).unwrap(),B=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:x,priceAdjustment:B}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new G(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),c=a.price.n.toString(),u=a.price.d.toString(),y;return Number(t)<Number(s)?y=vt(c,u):y=vt(u,c),y}getGlobalRewardPerPeriod(e,t,s,r){let a=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return a.gte(s)?s:a}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!Bt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&Bt(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:c,globalFarm:u,priceAdjustment:y})=>{let x=new G(u.totalSharesZ.toString()),B=u.plannedYieldingPeriods.toString(),N=new G(u.yieldPerPeriod.toString()),F=new G(u.maxRewardPerPeriod.toString()),_=u.blocksPerPeriod.toString(),D=new G(c.multiplier.toString()).shiftedBy(-18),k=this.secondsInYear.div(new G(s).times(_)),H;if(x.isZero())H=N.times(D).times(k);else{let de=this.getGlobalRewardPerPeriod(x,N,F,y);H=this.getPoolYieldPerPeriod(de,D,x,y).times(k)}let w=new G(u.pendingRewards.toString()).plus(u.accumulatedPaidRewards.toString()),J=F.times(B);return w.div(J).gte(.99)?R:H.times(100)}).reduce((c,u)=>c.plus(u),R).toString():void 0}};var he=class extends _e{pools=[];subs=[];assets=new Map([]);mem=0;memPools=ze(e=>(console.log(this.getPoolType(),"mem pools",e,"\u2705"),this.getPools()));constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getMemPools(){return this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=await this.subscribe();let e=this.getPoolType();return console.log(e,`pools(${this.augmentedPools.length})`,"\u2705"),console.log(e,`subs(${this.subs.length})`,"\u2705"),this.augmentedPools}async subscribe(){let e=this.augmentedPools.map(async s=>{let r=[await this.subscribeTokensPoolBalance(s)];try{let i=await this.subscribePoolChange(s);r.push(i)}catch{}if(this.hasSystemAsset(s)){let i=await this.subscribeSystemPoolBalance(s);r.push(i)}if(this.hasErc20Asset(s)){let i=await this.subscribeErc20PoolBalance(s);r.push(i)}if(this.hasShareAsset(s)){let i=await this.subscribeSharePoolBalance(s);r.push(i)}return this.subscribeLog(s),r});return(await Promise.all(e)).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasShareAsset(e){return e.type==="Stableswap"&&e.id}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e()})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}subscribeSharePoolBalance(e){let t=this.assets.get(e.id);return this.subscribeTokenBalance(Ye,[t],this.updateBalancesCallback(e,()=>!0))}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,i])=>{let a=e.tokens.findIndex(c=>c.id==r);a>=0&&t(e,r)&&(e.tokens[a].balance=i.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(i=>i.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var $e=class extends he{MAX_FINAL_WEIGHT=j(v(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,a])=>this.isActivePool(a.unwrap(),s)).map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=await this.getPoolDelta(u,c,s.toString());return this.poolsData.set(i.toString(),c),{address:u,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:u,repayTarget:y,feeCollector:x}=t,B=me.calculateLinearWeights(r.toString(),i.toString(),c.toString(),u.toString(),s),[N,F]=a,_=N.toString(),D=v(B),k=F.toString(),H=this.MAX_FINAL_WEIGHT.minus(v(D)),[w,J,se]=await Promise.all([this.isRepayFeeApplied(_,y.toString(),x.toString()),this.getBalance(e,_),this.getBalance(e,k)]);return{repayFeeApply:w,tokens:[{id:_,weight:D,balance:J.toString()},{id:k,weight:H,balance:se.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=v(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{encodeAddress as Zt}from"@polkadot/util-crypto";import{stringToU8a as Qt}from"@polkadot/util";function K(m,e){return m.shiftedBy(-1*e).toString()}function ue(m){return m[0]/m[1]*100}function ee(m){return m[0]/m[1]}function pe(m){return[m/ht,ht]}var Je=class extends he{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=s.map(async([{args:[u]},y])=>{let{hubReserve:x,shares:B,tradable:N}=y.unwrap(),F=await this.getBalance(t,u.toString());return{id:u.toString(),hubReserves:v(x.toString()),shares:v(B.toString()),tradeable:N.bits.toNumber(),balance:F.toString()}}),c=await Promise.all(a);return c.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:c,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=await this.api.query.dynamicFees.assetFee(e),r=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,a=r.minFee.toNumber()+i.minFee.toNumber(),c=r.maxFee.toNumber()+i.maxFee.toNumber();if(s.isSome){let{assetFee:u,protocolFee:y}=s.unwrap();return{assetFee:pe(u.toNumber()),protocolFee:pe(y.toNumber()),min:pe(a),max:pe(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:pe(a),max:pe(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let a=e.tokens[i];if(r.isNone)return a;let c=r.unwrap();return this.updateTokenState(a,c)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i}=t;return{...e,hubReserves:v(s.toString()),shares:v(r.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return pe(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return pe(t)}getPoolId(){return Zt(Qt("modlomnipool".padEnd(32,"\0")),Te)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var je=class extends he{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[a,c]=r.unwrap(),[u,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:u.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}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 ls,encodeAddress as us}from"@polkadot/util-crypto";import{calculate_in_given_out as Vt,calculate_out_given_in as es,calculate_amplification as ts,calculate_add_one_asset as ss,calculate_liquidity_out_one_asset as rs,calculate_pool_trade_fee as is,calculate_shares as ns,calculate_shares_for_amount as os,pool_account_name as as}from"@galacticcouncil/math-stableswap";var te=class{static getPoolAddress(e){return as(e)}static calculateAmplification(e,t,s,r,i){return ts(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return Vt(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return ss(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return os(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return es(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return rs(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return ns(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return is(e,t,s)}};var Ke=class extends he{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=this.getPoolAddress(u),[x,B]=await Promise.all([this.getPoolDelta(u,c,s.toString()),this.getPoolTokens(y,u,c)]);return this.stablePools.set(y,c),{address:y,id:u,type:"Stableswap",fee:pe(c.fee.toNumber()),tokens:B,...x,...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,u=te.calculateAmplification(r.toString(),i.toString(),a.toString(),c.toString(),s),y=await this.api.query.tokens.totalIssuance(e);return{amplification:u,totalIssuance:y.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async u=>{let[y,x]=await Promise.all([this.api.query.stableswap.assetTradability(t,u.toString()),this.getBalance(e,u.toString())]);return{id:u.toString(),tradeable:y.bits.toNumber(),balance:x.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:u}=c.unwrap(),y=await this.getBalance(Ye,t);a.push({id:t,tradeable:u.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),s=te.getPoolAddress(t);return us(ls(s),Te)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function ft(m){return m.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 Ze=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},It=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ee=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},At=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Tt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Ft=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Re=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=ze(e=>(console.log("Registry mem sync",e,"\u2705"),this.syncRegistry()));constructor(e){this.api=e,this.assetClient=new Fe(this.api),this.xykClient=new je(this.api),this.omniClient=new Je(this.api),this.lbpClient=new $e(this.api),this.stableClient=new Ke(this.api),this.clients=[this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getMemPools()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getMemPools()))).flat()}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}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 Ze(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(),ft(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(),ft(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var ke=(m,e)=>m===e?0:m==null?e==null?0:-1:e==null?m==null?0:1:typeof m.compare=="function"?m.compare(e):typeof e.compare=="function"?-e.compare(m):m<e?-1:m>e?1:0;var Qe=(m,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(m(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var cs=Qe(()=>"illegal argument(s)"),_t=m=>{throw new cs(m)};var ms=Qe(()=>"index out of bounds"),Pt=m=>{throw new ms(m)},Ve=(m,e,t)=>(m<e||m>=t)&&Pt(m);var Et=23283064365386963e-26,et=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 tt=class extends et{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var Rt=new tt(Math.random);var kt=m=>m!=null&&typeof m!="function"&&m.length!==void 0;var Lt=Object.getPrototypeOf({}),st="function",Mt="string",Oe=(m,e)=>{let t;if(m===e)return!0;if(m!=null){if(typeof m.equiv===st)return m.equiv(e)}else return m==e;if(e!=null){if(typeof e.equiv===st)return e.equiv(m)}else return m==e;return typeof m===Mt||typeof e===Mt?!1:(t=Object.getPrototypeOf(m),(t==null||t===Lt)&&(t=Object.getPrototypeOf(e),t==null||t===Lt)?ds(m,e):typeof m!==st&&m.length!==void 0&&typeof e!==st&&e.length!==void 0?ps(m,e):m instanceof Set&&e instanceof Set?gs(m,e):m instanceof Map&&e instanceof Map?hs(m,e):m instanceof Date&&e instanceof Date?m.getTime()===e.getTime():m instanceof RegExp&&e instanceof RegExp?m.toString()===e.toString():m!==m&&e!==e)},ps=(m,e,t=Oe)=>{let s=m.length;if(s===e.length)for(;s-- >0&&t(m[s],e[s]););return s<0},gs=(m,e,t=Oe)=>m.size===e.size&&t([...m.keys()].sort(),[...e.keys()].sort()),hs=(m,e,t=Oe)=>m.size===e.size&&t([...m].sort(),[...e].sort()),ds=(m,e,t=Oe)=>{if(Object.keys(m).length!==Object.keys(e).length)return!1;for(let s in m)if(!e.hasOwnProperty(s)||!t(m[s],e[s]))return!1;return!0};var bt=class{value;constructor(e){this.value=e}deref(){return this.value}};var Dt=m=>m instanceof bt;var rt=class m{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Ct("next",this._head)}reverseIterator(){return Ct("prev",this.tail)}clear(){this.release()}compare(e,t=ke){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,a=0;for(;s-- >0&&a===0;)a=t(r.value,i.value),r=r.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof m||kt(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(!Oe(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||ke;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!Dt(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&&Pt(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*Ct(m,e){for(;e;)yield e.value,e=e[m]}var it=class m extends rt{_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 m(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 m}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):(Ve(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):(Ve(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new m,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=Rt){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)&&_t("invalid indices: ${from} / ${to}");let i=new m,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=ke){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,a=0;for(let u=0;u<t&&(a++,i=i.next,!!i);u++);let c=t;for(;a>0||c>0&&i;){let u;a===0?(u=i,i=i.next,c--):!i||c===0||e(s.value,i.value)<=0?(u=s,s=s.next,a--):(u=i,i=i.next,c--),this._tail?this._tail.next=u:this._head=u,u.prev=this._tail,this._tail=u}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),Ve(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new m;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 nt=class m{map;items;opts;_size;constructor(e,t){let s={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=s.map(),this.items=new it,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(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}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 m(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),i=Math.max(0,s-(r?r.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(r,e,t,s):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let s=this.map.get(e);return s?this.resetEntry(s):this.set(e,await t())}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{release:e,maxsize:t,maxlen:s}=this.opts;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),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?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(this.opts.update?.(t,e.value.v,s),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 yt=class extends Re{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new nt(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
-
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Le=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new m(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(u=>[u.id,u])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let c=this.calculateTradeFee(t,s),u=ue(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(c),x=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return x.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:x,calculatedIn:x,amountOut:t,feePct:u,errors:i}}else{let c=this.calculateInGivenOut(e,t),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,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),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),u=this.calculateTradeFee(c,s),y=ue(this.repayFeeApply?s.repayFee:s.exchangeFee),x=c.minus(u),B=e.balanceOut.div(this.maxOutRatio);return x.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:x,feePct:y,errors:i}}}calculateInGivenOut(e,t){let s=me.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?R:r}calculateOutGivenIn(e,t){let s=me.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?R:r}spotPriceInGivenOut(e){let t=me.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),j(le,e.decimalsOut).toString());return v(t)}spotPriceOutGivenIn(e){let t=me.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),j(le,e.decimalsIn).toString());return v(t)}calculateTradeFee(e,t){let s=me.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return v(s)}};import{calculate_in_given_out as fs,calculate_lrna_in_given_out as Ps,calculate_out_given_in as bs,calculate_out_given_lrna_in as ys,calculate_pool_trade_fee as Ss,calculate_spot_price as ws,calculate_lrna_spot_price as Os,calculate_shares as xs,calculate_liquidity_out as Bs,calculate_liquidity_lrna_out as vs,verify_asset_cap as Is,calculate_liquidity_hub_in as As,is_sell_allowed as Ns,is_buy_allowed as Ts,is_add_liquidity_allowed as Fs,is_remove_liquidity_allowed as _s}from"@galacticcouncil/math-omnipool";var W=class{static calculateSpotPrice(e,t,s,r){return ws(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return Os(e,t)}static calculateInGivenOut(e,t,s,r,i,a,c,u,y){return fs(e,t,s,r,i,a,c,u,y)}static calculateLrnaInGivenOut(e,t,s,r,i){return Ps(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,a,c,u,y){return bs(e,t,s,r,i,a,c,u,y)}static calculateOutGivenLrnaIn(e,t,s,r,i){return ys(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Ss(e,t,s)}static calculateShares(e,t,s,r){return xs(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,a,c,u){return Bs(e,t,s,r,i,a,c,u)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,c,u){return vs(e,t,s,r,i,a,c,u)}static calculateCapDifference(e,t,s,r){let i=G(t),a=G(e),c=G(r),y=G(s).shiftedBy(-18);if(i.div(c).lt(y)){let B=y.times(c).minus(i).times(a),N=i.times(G(1).minus(y));return B.div(N).toFixed(0)}else return"0"}static verifyAssetCap(e,t,s,r){return Is(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return As(e,t,s,r)}static isSellAllowed(e){return Ns(e)}static isBuyAllowed(e){return Ts(e)}static isAddLiquidityAllowed(e){return Fs(e)}static isRemoveLiquidityAllowed(e){return _s(e)}};var Me=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new m(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(x=>[x.id,x])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance),u=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:u,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),c=r===R?R:a.div(r).multipliedBy(100).decimalPlaces(2),u=[],y=W.isSellAllowed(e.tradeableIn),x=W.isBuyAllowed(e.tradeableOut);(!y||!x)&&u.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&u.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&u.push("MaxOutRatioExceeded");let N=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(N)&&u.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:c.toNumber(),errors:u}}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),u=[],y=W.isSellAllowed(e.tradeableIn),x=W.isBuyAllowed(e.tradeableOut);(!y||!x)&&u.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&u.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&u.push("MaxInRatioExceeded");let N=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(N)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:c.toNumber(),errors:u}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=W.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():R.toString(),s?ee(s.protocolFee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateLrnaInGivenOut(e,t,s){let r=W.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=W.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():R.toString(),s?ee(s.protocolFee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateOutGivenLrnaIn(e,t,s){let r=W.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=W.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=W.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=W.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=W.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Ne-e.decimalsIn)).decimalPlaces(0,1)}};var De=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new m(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,u,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=u,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(x=>[x.id,x])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance),u=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?gt:r.tradeable,tradeableOut:this.id===t?gt:i.tradeable,assetInED:u,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=ue(s.fee),c=[],u=W.isSellAllowed(e.tradeableIn),y=W.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=ue(s.fee),c=[],u=W.isSellAllowed(e.tradeableIn),y=W.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,s){let r=te.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ee(s.fee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateAddOneAsset(e,t,s){let r=te.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?ee(s.fee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateSharesForAmount(e,t,s){let r=te.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?ee(s.fee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=j(le,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,s){let r=te.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ee(s.fee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateWithdrawOneAsset(e,t,s){let r=te.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?ee(s.fee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateShares(e,t,s){let r=te.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?ee(s.fee).toString():R.toString()),i=v(r);return i.isNegative()?R:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=j(le,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=te.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return v(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{calculate_in_given_out as Es,calculate_out_given_in as Rs,calculate_pool_trade_fee as ks,get_spot_price as Ls,calculate_liquidity_in as Ms,calculate_shares as Ds,calculate_spot_price as Cs,calculate_spot_price_with_fee as Gs,calculate_liquidity_out_asset_a as qs,calculate_liquidity_out_asset_b as Hs}from"@galacticcouncil/math-xyk";var Pe=class{static getSpotPrice(e,t,s){return Ls(e,t,s)}static calculateInGivenOut(e,t,s){return Es(e,t,s)}static calculateOutGivenIn(e,t,s){return Rs(e,t,s)}static calculatePoolTradeFee(e,t,s){return ks(e,t,s)}static calculateLiquidityIn(e,t,s){return Ms(e,t,s)}static calculateSpotPrice(e,t){return Cs(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return Gs(e,t,s,r)}static calculateShares(e,t,s){return Ds(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return qs(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Hs(e,t,s,r)}};var Ce=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new m(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(x=>[x.id,x])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance),u=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,assetInED:u,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=ue(s.exchangeFee),c=r.plus(i),u=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&u.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&u.push("MaxOutRatioExceeded");let x=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(x)&&u.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:r,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=ue(s.exchangeFee),c=r.minus(i),u=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&u.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&u.push("MaxInRatioExceeded");let x=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(x)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:a,errors:u}}calculateInGivenOut(e,t){let s=Pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?R:r}calculateOutGivenIn(e,t){let s=Pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?R:r}spotPriceInGivenOut(e){let t=Pe.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=j(le,18-e.decimalsOut);return v(t).div(s)}spotPriceOutGivenIn(e){let t=Pe.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=j(le,18-e.decimalsIn);return v(t).div(s)}calculateTradeFee(e,t){let s=Pe.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return v(s)}};var Ge=class{static get(e){switch(e.type){case"Xyk":return Ce.fromPool(e);case"Omnipool":return Me.fromPool(e);case"Lbp":return Le.fromPool(e);case"Stableswap":return De.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var xe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ie,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),a=this.getPaths(e,null,r,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(a)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,origin:r.origin,meta:r.meta,externalId:r.externalId,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(c=>this.validPath(c,s)).map(c=>this.toHops(c,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,Ge.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let a=t.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function ml(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function qe(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Gt(m,e){return le.minus(e.div(m)).multipliedBy(100).decimalPlaces(2)}function qt(m,e){return e.div(m).minus(le).multipliedBy(100).decimalPlaces(2)}var ot=class extends xe{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,a=r[r.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[s,r]}}getPoolFeeRange(e){let t=e.min?ue(e.min):void 0,s=e.max?ue(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ee(e,t);let u;if(r)u=await this.toSellSwaps(s,r,a);else{let E=c.map(async n=>await this.toSellSwaps(s,n,a)),X=await Promise.all(E);u=this.findBestSellRoute(X)}let y=u[0],x=u[u.length-1],B=this.isDirectTrade(u),N=u.map(E=>E.spotPrice.shiftedBy(-1*E.assetOutDecimals)).reduce((E,X)=>E.multipliedBy(X)),F=j(N,x.assetOutDecimals),_=B?x.calculatedOut:this.calculateDelta0Y(y.amountIn,u,a),D=x.amountOut,k=B?x.tradeFeePct:Gt(_,D).toNumber(),H=_.minus(D),w=this.getRouteFeeRange(u),J=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(F),se=qe(_,J),de=E=>this.poolService.buildSellTx(e,t,y.amountIn,E,u.map(X=>X));return{type:"Sell",amountIn:y.amountIn,amountOut:x.amountOut,spotPrice:F,tradeFee:H,tradeFeePct:k,tradeFeeRange:w,priceImpactPct:se.toNumber(),swaps:u,toTx:de,toHuman(){return{type:"Sell",amountIn:K(y.amountIn,y.assetInDecimals),amountOut:K(x.amountOut,x.assetOutDecimals),spotPrice:K(F,x.assetOutDecimals),tradeFee:K(H,x.assetOutDecimals),tradeFeePct:k,tradeFeeRange:w,priceImpactPct:se.toNumber(),swaps:u.map(E=>E.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1]:y=e;let x=c.calculateOutGivenIn(u,y);r.push(x)}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 u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1].amountOut:y=j(v(e),u.decimalsIn).decimalPlaces(0,1);let x=await this.poolService.getPoolFees(u.assetOut,c),{amountOut:B,calculatedOut:N,feePct:F,errors:_}=c.validateAndSell(u,y,x),D=this.getPoolFeeRange(x),k=c.spotPriceOutGivenIn(u),H=y.shiftedBy(-1*u.decimalsIn).multipliedBy(k),w=qe(N,H);r.push({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountIn:y,calculatedOut:N,amountOut:B,spotPrice:k,tradeFeePct:F,tradeFeeRange:D,priceImpactPct:w.toNumber(),errors:_,toHuman(){return{...a,amountIn:K(y,u.decimalsIn),calculatedOut:K(N,u.decimalsOut),amountOut:K(B,u.decimalsOut),spotPrice:K(k,u.decimalsOut),tradeFeePct:F,tradeFeeRange:D,priceImpactPct:w.toNumber(),errors:_}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(w=>w.tokens.find(J=>J.id===e)).filter(w=>!!w).sort((w,J)=>Number(J.balance)-Number(w.balance)),{balance:c,decimals:u}=a[0],x=v(c).shiftedBy(-1*u).div(100).multipliedBy(.1),B=i.map(async w=>await this.toSellSwaps(x,w,r)),N=await Promise.all(B),F=this.findBestSellRoute(N),_=await this.toSellSwaps("1",F,r),D=_.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,J)=>w.multipliedBy(J)),k=_[_.length-1].assetOutDecimals;return{amount:j(D,k),decimals:k}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,a=r[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ee(e,t);let u;if(r)u=await this.toBuySwaps(s,r,a);else{let E=c.map(async n=>await this.toBuySwaps(s,n,a)),X=await Promise.all(E);u=this.findBestBuyRoute(X)}let y=u[u.length-1],x=u[0],B=this.isDirectTrade(u),N=u.map(E=>E.spotPrice.shiftedBy(-1*E.assetInDecimals)).reduce((E,X)=>E.multipliedBy(X)),F=j(N,x.assetInDecimals),_=B?x.calculatedIn:this.calculateDelta0X(y.amountOut,u,a),D=x.amountIn,k=B?x.tradeFeePct:qt(_,D).toNumber(),H=D.minus(_),w=this.getRouteFeeRange(u),J=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(F),se;_.isZero()?se=-100:se=qe(J,_).toNumber();let de=E=>this.poolService.buildBuyTx(e,t,y.amountOut,E,u.map(X=>X));return{type:"Buy",amountOut:y.amountOut,amountIn:x.amountIn,spotPrice:F,tradeFee:H,tradeFeePct:k,tradeFeeRange:w,priceImpactPct:se,swaps:u,toTx:de,toHuman(){return{type:"Buy",amountOut:K(y.amountOut,y.assetOutDecimals),amountIn:K(x.amountIn,x.assetInDecimals),spotPrice:K(F,x.assetInDecimals),tradeFee:K(H,x.assetInDecimals),tradeFeePct:k,tradeFeeRange:w,priceImpactPct:se,swaps:u.map(E=>E.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=r[0];let x=c.calculateInGivenOut(u,y);r.unshift(x)}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 u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=j(v(e),u.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let x=await this.poolService.getPoolFees(u.assetOut,c),{amountIn:B,calculatedIn:N,feePct:F,errors:_}=c.validateAndBuy(u,y,x),D=this.getPoolFeeRange(x),k=c.spotPriceInGivenOut(u),H=y.shiftedBy(-1*u.decimalsOut).multipliedBy(k),w;N.isZero()?w=-100:w=qe(H,N).toNumber(),r.unshift({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountOut:y,calculatedIn:N,amountIn:B,spotPrice:k,tradeFeePct:F,tradeFeeRange:D,priceImpactPct:w,errors:_,toHuman(){return{...a,amountOut:K(y,u.decimalsOut),calculatedIn:K(N,u.decimalsIn),amountIn:K(B,u.decimalsIn),spotPrice:K(k,u.decimalsIn),tradeFeePct:F,tradeFeeRange:D,priceImpactPct:w,errors:_}}})}return r}};export{Fe as AssetClient,At as AssetNotFound,fr as BASILISK_PARACHAIN_ID,_e as BalanceClient,G as BigNumber,yt as CachingPoolService,zt as DECIMAL_PLACES,ht as DENOMINATOR,dt as FarmClient,Ye as HYDRADX_OMNIPOOL_ADDRESS,dr as HYDRADX_PARACHAIN_ID,Te as HYDRADX_SS58_PREFIX,ar as INFINITY,me as LbpMath,Le as LbpPool,le as ONE,W as OmniMath,Me as OmniPool,It as PoolConfigNotFound,Ae as PoolError,Ge as PoolFactory,Ze as PoolNotFound,Re as PoolService,re as PoolType,Ft as ProviderConfigNotFound,Ne as RUNTIME_DECIMALS,Ee as RouteNotFound,xe as Router,hr as SYSTEM_ASSET_DECIMALS,we as SYSTEM_ASSET_ID,te as StableMath,De as StableSwap,Nt as StorageConfigNotFound,Tt as SubscriptionNotSupported,gt as TRADEABLE_DEFAULT,ot as TradeRouter,Ot as TradeType,Pe as XykMath,Ce as XykPool,R as ZERO,v as bnum,ft as buildRoute,qt as calculateBuyFee,ml as calculateDiffToAvg,qe as calculateDiffToRef,Gt as calculateSellFee,xt as findNestedKey,br as findNestedObj,j as scale};
|
|
1
|
+
var Ue=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 qt=5,Ae=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 Ue,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let c=i.dequeue();if(c==null||c.length>qt)return r;let u=c[c.length-1];(s===null||u[0]===s)&&r.push(c),e.get(u[0])?.forEach(x=>{if(this.isNotVisited(x,c)){let O=[...c];O.push(x),i.enqueue(O)}})}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),u=parseInt(a);s.get(c)?.push([u,r])}return s}};function ut(m){let e={};for(let t of m){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 Ne=class{getProposals(e,t,s){let r=ut(s),i=Object.keys(r),a=i.map(x=>r[x]).flat(),c=new Ae,u=c.buildAndPopulateGraph(i,a),y=c.findPaths(u,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let 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 ze=(m,e=new Map)=>t=>{let s;return e.has(t)?e.get(t):(e.set(t,s=m(t)),s)};var Ht=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,ct=Math.ceil,oe=Math.floor,Q="[BigNumber Error] ",St=Q+"Number primitive has more than 15 significant digits: ",ce=1e14,N=14,mt=9007199254740991,pt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],be=1e7,$=1e9;function wt(m){var e,t,s,r=w.prototype={constructor:w,toString:null,valueOf:null},i=new w(1),a=20,c=4,u=-7,y=21,x=-1e7,O=1e7,T=!1,_=1,F=0,D={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},k="0123456789abcdefghijklmnopqrstuvwxyz",H=!0;function w(n,o){var l,P,g,d,S,p,h,b,f=this;if(!(f instanceof w))return new w(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>O?f.c=f.e=null:n.e<x?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((p=typeof n=="number")&&n*0==0){if(f.s=1/n<0?(n=-n,-1):1,n===~~n){for(d=0,S=n;S>=10;S/=10,d++);d>O?f.c=f.e=null:(f.e=d,f.c=[n]);return}b=String(n)}else{if(!Ht.test(b=String(n)))return s(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(q(o,2,k.length,"Base"),o==10&&H)return f=new w(n),R(f,a+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return s(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,w.DEBUG&&b.replace(/^0\.0*|\./,"").length>15)throw Error(St+n)}else f.s=b.charCodeAt(0)===45?(b=b.slice(1),-1):1;for(l=k.slice(0,o),d=S=0,h=b.length;S<h;S++)if(l.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=h;continue}}else if(!g&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){g=!0,S=-1,d=0;continue}return s(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(h=b.length;b.charCodeAt(--h)===48;);if(b=b.slice(S,++h)){if(h-=S,p&&w.DEBUG&&h>15&&(n>mt||n!==oe(n)))throw Error(St+f.s*n);if((d=d-S-1)>O)f.c=f.e=null;else if(d<x)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%N,d<0&&(S+=N),S<h){for(S&&f.c.push(+b.slice(0,S)),h-=N;S<h;)f.c.push(+b.slice(S,S+=N));S=N-(b=b.slice(S)).length}else S-=h;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}w.clone=wt,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(n){var o,l;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(l=n[o],q(l,0,$,o),a=l),n.hasOwnProperty(o="ROUNDING_MODE")&&(l=n[o],q(l,0,8,o),c=l),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(l=n[o],l&&l.pop?(q(l[0],-$,0,o),q(l[1],0,$,o),u=l[0],y=l[1]):(q(l,-$,$,o),u=-(y=l<0?-l:l))),n.hasOwnProperty(o="RANGE"))if(l=n[o],l&&l.pop)q(l[0],-$,-1,o),q(l[1],1,$,o),x=l[0],O=l[1];else if(q(l,-$,$,o),l)x=-(O=l<0?-l:l);else throw Error(Q+o+" cannot be zero: "+l);if(n.hasOwnProperty(o="CRYPTO"))if(l=n[o],l===!!l)if(l)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))T=l;else throw T=!l,Error(Q+"crypto unavailable");else T=l;else throw Error(Q+o+" not true or false: "+l);if(n.hasOwnProperty(o="MODULO_MODE")&&(l=n[o],q(l,0,9,o),_=l),n.hasOwnProperty(o="POW_PRECISION")&&(l=n[o],q(l,0,$,o),F=l),n.hasOwnProperty(o="FORMAT"))if(l=n[o],typeof l=="object")D=l;else throw Error(Q+o+" not an object: "+l);if(n.hasOwnProperty(o="ALPHABET"))if(l=n[o],typeof l=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(l))H=l.slice(0,10)=="0123456789",k=l;else throw Error(Q+o+" invalid: "+l)}else throw Error(Q+"Object expected: "+n);return{DECIMAL_PLACES:a,ROUNDING_MODE:c,EXPONENTIAL_AT:[u,y],RANGE:[x,O],CRYPTO:T,MODULO_MODE:_,POW_PRECISION:F,FORMAT:D,ALPHABET:k}},w.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!w.DEBUG)return!0;var o,l,P=n.c,g=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&g>=-$&&g<=$&&g===oe(g)){if(P[0]===0){if(g===0&&P.length===1)return!0;break e}if(o=(g+1)%N,o<1&&(o+=N),String(P[0]).length==o){for(o=0;o<P.length;o++)if(l=P[o],l<0||l>=ce||l!==oe(l))break e;if(l!==0)return!0}}}else if(P===null&&g===null&&(d===null||d===1||d===-1))return!0;throw Error(Q+"Invalid BigNumber: "+n)},w.maximum=w.max=function(){return se(arguments,-1)},w.minimum=w.min=function(){return se(arguments,1)},w.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return oe(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(l){var P,g,d,S,p,h=0,b=[],f=new w(i);if(l==null?l=a:q(l,0,$),S=ct(l/N),T)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));h<S;)p=P[h]*131072+(P[h+1]>>>11),p>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),P[h]=g[0],P[h+1]=g[1]):(b.push(p%1e14),h+=2);h=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);h<S;)p=(P[h]&31)*281474976710656+P[h+1]*1099511627776+P[h+2]*4294967296+P[h+3]*16777216+(P[h+4]<<16)+(P[h+5]<<8)+P[h+6],p>=9e15?crypto.randomBytes(7).copy(P,h):(b.push(p%1e14),h+=7);h=S/7}else throw T=!1,Error(Q+"crypto unavailable");if(!T)for(;h<S;)p=o(),p<9e15&&(b[h++]=p%1e14);for(S=b[--h],l%=N,S&&l&&(p=pt[N-l],b[h]=oe(S/p)*p);b[h]===0;b.pop(),h--);if(h<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=N);for(h=1,p=b[0];p>=10;p/=10,h++);h<N&&(d-=N-h)}return f.e=d,f.c=b,f}}(),w.sum=function(){for(var n=1,o=arguments,l=new w(o[0]);n<o.length;)l=l.plus(o[n++]);return l},t=function(){var n="0123456789";function o(l,P,g,d){for(var S,p=[0],h,b=0,f=l.length;b<f;){for(h=p.length;h--;p[h]*=P);for(p[0]+=d.indexOf(l.charAt(b++)),S=0;S<p.length;S++)p[S]>g-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/g|0,p[S]%=g)}return p.reverse()}return function(l,P,g,d,S){var p,h,b,f,B,I,A,M,U=l.indexOf("."),Y=a,L=c;for(U>=0&&(f=F,F=0,l=l.replace(".",""),M=new w(P),I=M.pow(l.length-U),F=f,M.c=o(fe(ne(I.c),I.e,"0"),10,g,n),M.e=M.c.length),A=o(l,P,g,S?(p=k,n):(p=n,k)),b=f=A.length;A[--f]==0;A.pop());if(!A[0])return p.charAt(0);if(U<0?--b:(I.c=A,I.e=b,I.s=d,I=e(I,M,Y,L,g),A=I.c,B=I.r,b=I.e),h=b+Y+1,U=A[h],f=g/2,B=B||h<0||A[h+1]!=null,B=L<4?(U!=null||B)&&(L==0||L==(I.s<0?3:2)):U>f||U==f&&(L==4||B||L==6&&A[h-1]&1||L==(I.s<0?8:7)),h<1||!A[0])l=B?fe(p.charAt(1),-Y,p.charAt(0)):p.charAt(0);else{if(A.length=h,B)for(--g;++A[--h]>g;)A[h]=0,h||(++b,A=[1].concat(A));for(f=A.length;!A[--f];);for(U=0,l="";U<=f;l+=p.charAt(A[U++]));l=fe(l,b,p.charAt(0))}return l}}(),e=function(){function n(P,g,d){var S,p,h,b,f=0,B=P.length,I=g%be,A=g/be|0;for(P=P.slice();B--;)h=P[B]%be,b=P[B]/be|0,S=A*h+b*I,p=I*h+S%be*be+f,f=(p/d|0)+(S/be|0)+A*b,P[B]=p%d;return f&&(P=[f].concat(P)),P}function o(P,g,d,S){var p,h;if(d!=S)h=d>S?1:-1;else for(p=h=0;p<d;p++)if(P[p]!=g[p]){h=P[p]>g[p]?1:-1;break}return h}function l(P,g,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<g[d]?1:0,P[d]=p*S+P[d]-g[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,g,d,S,p){var h,b,f,B,I,A,M,U,Y,L,C,Z,He,at,lt,ge,Ie,ie=P.s==g.s?1:-1,K=P.c,z=g.c;if(!K||!K[0]||!z||!z[0])return new w(!P.s||!g.s||(K?z&&K[0]==z[0]:!z)?NaN:K&&K[0]==0||!z?ie*0:ie/0);for(U=new w(ie),Y=U.c=[],b=P.e-g.e,ie=d+b+1,p||(p=ce,b=ae(P.e/N)-ae(g.e/N),ie=ie/N|0),f=0;z[f]==(K[f]||0);f++);if(z[f]>(K[f]||0)&&b--,ie<0)Y.push(1),B=!0;else{for(at=K.length,ge=z.length,f=0,ie+=2,I=oe(p/(z[0]+1)),I>1&&(z=n(z,I,p),K=n(K,I,p),ge=z.length,at=K.length),He=ge,L=K.slice(0,ge),C=L.length;C<ge;L[C++]=0);Ie=z.slice(),Ie=[0].concat(Ie),lt=z[0],z[1]>=p/2&<++;do{if(I=0,h=o(z,L,ge,C),h<0){if(Z=L[0],ge!=C&&(Z=Z*p+(L[1]||0)),I=oe(Z/lt),I>1)for(I>=p&&(I=p-1),A=n(z,I,p),M=A.length,C=L.length;o(A,L,M,C)==1;)I--,l(A,ge<M?Ie:z,M,p),M=A.length,h=1;else I==0&&(h=I=1),A=z.slice(),M=A.length;if(M<C&&(A=[0].concat(A)),l(L,A,C,p),C=L.length,h==-1)for(;o(z,L,ge,C)<1;)I++,l(L,ge<C?Ie:z,C,p),C=L.length}else h===0&&(I++,L=[0]);Y[f++]=I,L[0]?L[C++]=K[He]||0:(L=[K[He]],C=1)}while((He++<at||L[0]!=null)&&ie--);B=L[0]!=null,Y[0]||Y.splice(0,1)}if(p==ce){for(f=1,ie=Y[0];ie>=10;ie/=10,f++);R(U,d+(U.e=f+b*N-1)+1,S,B)}else U.e=b,U.r=+B;return U}}();function J(n,o,l,P){var g,d,S,p,h;if(l==null?l=c:q(l,0,8),!n.c)return n.toString();if(g=n.c[0],S=n.e,o==null)h=ne(n.c),h=P==1||P==2&&(S<=u||S>=y)?Xe(h,S):fe(h,S,"0");else if(n=R(new w(n),o,l),d=n.e,h=ne(n.c),p=h.length,P==1||P==2&&(o<=d||d<=u)){for(;p<o;h+="0",p++);h=Xe(h,d)}else if(o-=S,h=fe(h,d,"0"),d+1>p){if(--o>0)for(h+=".";o--;h+="0");}else if(o+=d-p,o>0)for(d+1==p&&(h+=".");o--;h+="0");return n.s<0&&g?"-"+h:h}function se(n,o){for(var l,P,g=1,d=new w(n[0]);g<n.length;g++)P=new w(n[g]),(!P.s||(l=Se(d,P))===o||l===0&&d.s===o)&&(d=P);return d}function de(n,o,l){for(var P=1,g=o.length;!o[--g];o.pop());for(g=o[0];g>=10;g/=10,P++);return(l=P+l*N-1)>O?n.c=n.e=null:l<x?n.c=[n.e=0]:(n.e=l,n.c=o),n}s=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,l=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,h){var b,f=p?S:S.replace(g,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(B,I,A){return b=(A=A.toLowerCase())=="x"?16:A=="b"?2:8,!h||h==b?I:B}),h&&(b=h,f=f.replace(o,"$1").replace(l,"0.$1")),S!=f))return new w(f,b);if(w.DEBUG)throw Error(Q+"Not a"+(h?" base "+h:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function R(n,o,l,P){var g,d,S,p,h,b,f,B=n.c,I=pt;if(B){e:{for(g=1,p=B[0];p>=10;p/=10,g++);if(d=o-g,d<0)d+=N,S=o,h=B[b=0],f=oe(h/I[g-S-1]%10);else if(b=ct((d+1)/N),b>=B.length)if(P){for(;B.length<=b;B.push(0));h=f=0,g=1,d%=N,S=d-N+1}else break e;else{for(h=p=B[b],g=1;p>=10;p/=10,g++);d%=N,S=d-N+g,f=S<0?0:oe(h/I[g-S-1]%10)}if(P=P||o<0||B[b+1]!=null||(S<0?h:h%I[g-S-1]),P=l<4?(f||P)&&(l==0||l==(n.s<0?3:2)):f>5||f==5&&(l==4||P||l==6&&(d>0?S>0?h/I[g-S]:0:B[b-1])%10&1||l==(n.s<0?8:7)),o<1||!B[0])return B.length=0,P?(o-=n.e+1,B[0]=I[(N-o%N)%N],n.e=-o||0):B[0]=n.e=0,n;if(d==0?(B.length=b,p=1,b--):(B.length=b+1,p=I[N-d],B[b]=S>0?oe(h/I[g-S]%I[S])*p:0),P)for(;;)if(b==0){for(d=1,S=B[0];S>=10;S/=10,d++);for(S=B[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,B[0]==ce&&(B[0]=1));break}else{if(B[b]+=p,B[b]!=ce)break;B[b--]=0,p=1}for(d=B.length;B[--d]===0;B.pop());}n.e>O?n.c=n.e=null:n.e<x&&(n.c=[n.e=0])}return n}function W(n){var o,l=n.e;return l===null?n.toString():(o=ne(n.c),o=l<=u||l>=y?Xe(o,l):fe(o,l,"0"),n.s<0?"-"+o:o)}return r.absoluteValue=r.abs=function(){var n=new w(this);return n.s<0&&(n.s=1),n},r.comparedTo=function(n,o){return Se(this,new w(n,o))},r.decimalPlaces=r.dp=function(n,o){var l,P,g,d=this;if(n!=null)return q(n,0,$),o==null?o=c:q(o,0,8),R(new w(d),n+d.e+1,o);if(!(l=d.c))return null;if(P=((g=l.length-1)-ae(this.e/N))*N,g=l[g])for(;g%10==0;g/=10,P--);return P<0&&(P=0),P},r.dividedBy=r.div=function(n,o){return e(this,new w(n,o),a,c)},r.dividedToIntegerBy=r.idiv=function(n,o){return e(this,new w(n,o),0,1)},r.exponentiatedBy=r.pow=function(n,o){var l,P,g,d,S,p,h,b,f,B=this;if(n=new w(n),n.c&&!n.isInteger())throw Error(Q+"Exponent not an integer: "+W(n));if(o!=null&&(o=new w(o)),p=n.e>14,!B.c||!B.c[0]||B.c[0]==1&&!B.e&&B.c.length==1||!n.c||!n.c[0])return f=new w(Math.pow(+W(B),p?n.s*(2-We(n)):+W(n))),o?f.mod(o):f;if(h=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new w(NaN);P=!h&&B.isInteger()&&o.isInteger(),P&&(B=B.mod(o))}else{if(n.e>9&&(B.e>0||B.e<-1||(B.e==0?B.c[0]>1||p&&B.c[1]>=24e7:B.c[0]<8e13||p&&B.c[0]<=9999975e7)))return d=B.s<0&&We(n)?-0:0,B.e>-1&&(d=1/d),new w(h?1/d:d);F&&(d=ct(F/N+2))}for(p?(l=new w(.5),h&&(n.s=1),b=We(n)):(g=Math.abs(+W(n)),b=g%2),f=new w(i);;){if(b){if(f=f.times(B),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(g){if(g=oe(g/2),g===0)break;b=g%2}else if(n=n.times(l),R(n,n.e+1,1),n.e>14)b=We(n);else{if(g=+W(n),g===0)break;b=g%2}B=B.times(B),d?B.c&&B.c.length>d&&(B.c.length=d):P&&(B=B.mod(o))}return P?f:(h&&(f=i.div(f)),o?f.mod(o):d?R(f,F,c,S):f)},r.integerValue=function(n){var o=new w(this);return n==null?n=c:q(n,0,8),R(o,o.e+1,n)},r.isEqualTo=r.eq=function(n,o){return Se(this,new w(n,o))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(n,o){return Se(this,new w(n,o))>0},r.isGreaterThanOrEqualTo=r.gte=function(n,o){return(o=Se(this,new w(n,o)))===1||o===0},r.isInteger=function(){return!!this.c&&ae(this.e/N)>this.c.length-2},r.isLessThan=r.lt=function(n,o){return Se(this,new w(n,o))<0},r.isLessThanOrEqualTo=r.lte=function(n,o){return(o=Se(this,new w(n,o)))===-1||o===0},r.isNaN=function(){return!this.s},r.isNegative=function(){return this.s<0},r.isPositive=function(){return this.s>0},r.isZero=function(){return!!this.c&&this.c[0]==0},r.minus=function(n,o){var l,P,g,d,S=this,p=S.s;if(n=new w(n,o),o=n.s,!p||!o)return new w(NaN);if(p!=o)return n.s=-o,S.plus(n);var h=S.e/N,b=n.e/N,f=S.c,B=n.c;if(!h||!b){if(!f||!B)return f?(n.s=-o,n):new w(B?S:NaN);if(!f[0]||!B[0])return B[0]?(n.s=-o,n):new w(f[0]?S:c==3?-0:0)}if(h=ae(h),b=ae(b),f=f.slice(),p=h-b){for((d=p<0)?(p=-p,g=f):(b=h,g=B),g.reverse(),o=p;o--;g.push(0));g.reverse()}else for(P=(d=(p=f.length)<(o=B.length))?p:o,p=o=0;o<P;o++)if(f[o]!=B[o]){d=f[o]<B[o];break}if(d&&(g=f,f=B,B=g,n.s=-n.s),o=(P=B.length)-(l=f.length),o>0)for(;o--;f[l++]=0);for(o=ce-1;P>p;){if(f[--P]<B[P]){for(l=P;l&&!f[--l];f[l]=o);--f[l],f[P]+=ce}f[P]-=B[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?de(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},r.modulo=r.mod=function(n,o){var l,P,g=this;return n=new w(n,o),!g.c||!n.s||n.c&&!n.c[0]?new w(NaN):!n.c||g.c&&!g.c[0]?new w(g):(_==9?(P=n.s,n.s=1,l=e(g,n,0,3),n.s=P,l.s*=P):l=e(g,n,0,_),n=g.minus(l.times(n)),!n.c[0]&&_==1&&(n.s=g.s),n)},r.multipliedBy=r.times=function(n,o){var l,P,g,d,S,p,h,b,f,B,I,A,M,U,Y,L=this,C=L.c,Z=(n=new w(n,o)).c;if(!C||!Z||!C[0]||!Z[0])return!L.s||!n.s||C&&!C[0]&&!Z||Z&&!Z[0]&&!C?n.c=n.e=n.s=null:(n.s*=L.s,!C||!Z?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=ae(L.e/N)+ae(n.e/N),n.s*=L.s,h=C.length,B=Z.length,h<B&&(M=C,C=Z,Z=M,g=h,h=B,B=g),g=h+B,M=[];g--;M.push(0));for(U=ce,Y=be,g=B;--g>=0;){for(l=0,I=Z[g]%Y,A=Z[g]/Y|0,S=h,d=g+S;d>g;)b=C[--S]%Y,f=C[S]/Y|0,p=A*b+f*I,b=I*b+p%Y*Y+M[d]+l,l=(b/U|0)+(p/Y|0)+A*f,M[d--]=b%U;M[d]=l}return l?++P:M.splice(0,1),de(n,M,P)},r.negated=function(){var n=new w(this);return n.s=-n.s||null,n},r.plus=function(n,o){var l,P=this,g=P.s;if(n=new w(n,o),o=n.s,!g||!o)return new w(NaN);if(g!=o)return n.s=-o,P.minus(n);var d=P.e/N,S=n.e/N,p=P.c,h=n.c;if(!d||!S){if(!p||!h)return new w(g/0);if(!p[0]||!h[0])return h[0]?n:new w(p[0]?P:g*0)}if(d=ae(d),S=ae(S),p=p.slice(),g=d-S){for(g>0?(S=d,l=h):(g=-g,l=p),l.reverse();g--;l.push(0));l.reverse()}for(g=p.length,o=h.length,g-o<0&&(l=h,h=p,p=l,o=g),g=0;o;)g=(p[--o]=p[o]+h[o]+g)/ce|0,p[o]=ce===p[o]?0:p[o]%ce;return g&&(p=[g].concat(p),++S),de(n,p,S)},r.precision=r.sd=function(n,o){var l,P,g,d=this;if(n!=null&&n!==!!n)return q(n,1,$),o==null?o=c:q(o,0,8),R(new w(d),n,o);if(!(l=d.c))return null;if(g=l.length-1,P=g*N+1,g=l[g]){for(;g%10==0;g/=10,P--);for(g=l[0];g>=10;g/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},r.shiftedBy=function(n){return q(n,-mt,mt),this.times("1e"+n)},r.squareRoot=r.sqrt=function(){var n,o,l,P,g,d=this,S=d.c,p=d.s,h=d.e,b=a+4,f=new w("0.5");if(p!==1||!S||!S[0])return new w(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+W(d)),p==0||p==1/0?(o=ne(S),(o.length+h)%2==0&&(o+="0"),p=Math.sqrt(+o),h=ae((h+1)/2)-(h<0||h%2),p==1/0?o="5e"+h:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+h),l=new w(o)):l=new w(p+""),l.c[0]){for(h=l.e,p=h+b,p<3&&(p=0);;)if(g=l,l=f.times(g.plus(e(d,g,b,1))),ne(g.c).slice(0,p)===(o=ne(l.c)).slice(0,p))if(l.e<h&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(R(g,g.e+a+2,0),g.times(g).eq(d))){l=g;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(R(l,l.e+a+2,1),n=!l.times(l).eq(d));break}}return R(l,l.e+a+1,c,n)},r.toExponential=function(n,o){return n!=null&&(q(n,0,$),n++),J(this,n,o,1)},r.toFixed=function(n,o){return n!=null&&(q(n,0,$),n=n+this.e+1),J(this,n,o)},r.toFormat=function(n,o,l){var P,g=this;if(l==null)n!=null&&o&&typeof o=="object"?(l=o,o=null):n&&typeof n=="object"?(l=n,n=o=null):l=D;else if(typeof l!="object")throw Error(Q+"Argument not an object: "+l);if(P=g.toFixed(n,o),g.c){var d,S=P.split("."),p=+l.groupSize,h=+l.secondaryGroupSize,b=l.groupSeparator||"",f=S[0],B=S[1],I=g.s<0,A=I?f.slice(1):f,M=A.length;if(h&&(d=p,p=h,h=d,M-=d),p>0&&M>0){for(d=M%p||p,f=A.substr(0,d);d<M;d+=p)f+=b+A.substr(d,p);h>0&&(f+=b+A.slice(d)),I&&(f="-"+f)}P=B?f+(l.decimalSeparator||"")+((h=+l.fractionGroupSize)?B.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(l.fractionGroupSeparator||"")):B):f}return(l.prefix||"")+P+(l.suffix||"")},r.toFraction=function(n){var o,l,P,g,d,S,p,h,b,f,B,I,A=this,M=A.c;if(n!=null&&(p=new w(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(Q+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+W(p));if(!M)return new w(A);for(o=new w(i),b=l=new w(i),P=h=new w(i),I=ne(M),d=o.e=I.length-A.e-1,o.c[0]=pt[(S=d%N)<0?N+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=O,O=1/0,p=new w(I),h.c[0]=0;f=e(p,o,0,1),g=l.plus(f.times(P)),g.comparedTo(n)!=1;)l=P,P=g,b=h.plus(f.times(g=b)),h=g,o=p.minus(f.times(g=o)),p=g;return g=e(n.minus(l),P,0,1),h=h.plus(g.times(b)),l=l.plus(g.times(P)),h.s=b.s=A.s,d=d*2,B=e(b,P,d,c).minus(A).abs().comparedTo(e(h,l,d,c).minus(A).abs())<1?[b,P]:[h,l],O=S,B},r.toNumber=function(){return+W(this)},r.toPrecision=function(n,o){return n!=null&&q(n,1,$),J(this,n,o,2)},r.toString=function(n){var o,l=this,P=l.s,g=l.e;return g===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=g<=u||g>=y?Xe(ne(l.c),g):fe(ne(l.c),g,"0"):n===10&&H?(l=R(new w(l),a+g+1,c),o=fe(ne(l.c),l.e,"0")):(q(n,2,k.length,"Base"),o=t(fe(ne(l.c),g,"0"),10,n,P,!0)),P<0&&l.c[0]&&(o="-"+o)),o},r.valueOf=r.toJSON=function(){return W(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,m!=null&&w.set(m),w}function ae(m){var e=m|0;return m>0||m===e?e:e-1}function ne(m){for(var e,t,s=1,r=m.length,i=m[0]+"";s<r;){for(e=m[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 Se(m,e){var t,s,r=m.c,i=e.c,a=m.s,c=e.s,u=m.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=u==y,!r||!i)return s?0:!r^t?1:-1;if(!s)return u>y^t?1:-1;for(c=(u=r.length)<(y=i.length)?u:y,a=0;a<c;a++)if(r[a]!=i[a])return r[a]>i[a]^t?1:-1;return u==y?0:u>y^t?1:-1}function q(m,e,t,s){if(m<e||m>t||m!==oe(m))throw Error(Q+(s||"Argument")+(typeof m=="number"?m<e||m>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(m))}function We(m){var e=m.c.length-1;return ae(m.e/N)==e&&m.c[e]%2!=0}function Xe(m,e){return(m.length>1?m.charAt(0)+"."+m.slice(1):m)+(e<0?"e":"e+")+e}function fe(m,e,t){var s,r;if(e<0){for(r=t+".";++e;r+=t);m=r+m}else if(s=m.length,++e>s){for(r=t,e-=s;--e;r+=t);m+=r}else e<s&&(m=m.slice(0,e)+"."+m.slice(e));return m}var G=wt();var Ut=12;G.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Ut});var E=v(0),le=v(1),or=v("Infinity");function j(m,e){let t=new G(e.toString()),s=new G(10).pow(t);return m.times(s)}function v(m){return new G(m.toString())}var re=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(re||{}),Te=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(Te||{}),Bt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Bt||{});import{calculate_in_given_out as zt,calculate_out_given_in as Wt,calculate_linear_weights as Xt,calculate_pool_trade_fee as Yt,get_spot_price as $t}from"@galacticcouncil/math-lbp";var me=class{static getSpotPrice(e,t,s,r,i){return $t(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return zt(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return Wt(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return Xt(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Yt(e,t,s)}};import{encodeAddress as Jt}from"@polkadot/util-crypto";import{stringToU8a as jt}from"@polkadot/util";var Fe=18,gt=15,we="0",gr=12,hr=2034,_e=63,dr=2090,ht=1e3,Ye=Jt(jt("modlomnipool".padEnd(32,"\0")),_e);import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";import"@polkadot/types/lookup";import"@polkadot/api-base/types/consts";import"@polkadot/api-base/types/errors";import"@polkadot/api-base/types/events";import"@polkadot/api-base/types/storage";import"@polkadot/api-base/types/submittable";import"@polkadot/rpc-core/types/jsonrpc";import"@polkadot/api-base/types/calls";import"@polkadot/types/types/registry";var ye=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Be=class extends ye{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==we){let O=this.api.consts.balances.existentialDeposit;return{id:we,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:O.toString()}}let{name:i,assetType:a,isSufficient:c,existentialDeposit:u}=t,{symbol:y,decimals:x}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:y,decimals:x,icon:y,type:a.toHuman(),isSufficient:c?c.toHuman():!0,location:r?.toJSON(),existentialDeposit:u.toString()}}getBond(e,t,s,r){let[i,a]=r,{assetType:c,isSufficient:u,existentialDeposit:y}=t,{symbol:x,decimals:O}=this.getToken(i.toString(),t,s),T=a.toNumber(),_=new Intl.DateTimeFormat("en-GB"),F=[x,"Bond",_.format(T)].join(" ");return{id:e,name:F,symbol:x+"b",decimals:O,icon:x,type:c.toString(),isSufficient:u.toHuman(),existentialDeposit:y.toString(),underlyingAssetId:i.toString(),maturity:T}}getShares(e,t,s,r){let{assets:i}=r,{name:a,symbol:c,assetType:u,isSufficient:y,existentialDeposit:x}=t,T=i.map(D=>D.toString()).map(D=>{let{symbol:k}=this.getToken(D,t,s);return[D,k]}),_=Object.fromEntries(T),F=Object.values(_);return{id:e,name:F.join(", "),symbol:c?.isSome?c.toHuman():a.toHuman(),decimals:18,icon:F.join("/"),type:u.toString(),isSufficient:y.toHuman(),existentialDeposit:x.toString(),meta:_}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),a=s?.find(c=>c.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:a}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,i,a,c]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),u=this.getSupportedAssets(s),y=this.normalizeMetadata(u,c),x=u.map(([{args:[O]},T])=>{let _=T.unwrap(),F=r.get(O.toString()),{assetType:D}=_;switch(D.toString()){case"Bond":let k=a.get(O.toString());return this.getBond(O.toString(),_,y,k);case"StableSwap":let H=i.get(O.toString());return this.getShares(O.toString(),_,y,H);case"External":return this.getExternal(O.toString(),_,t,F);default:return this.getToken(O.toString(),_,y,F)}});return e?x:x.filter(O=>this.isValidAsset(O))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var xe=class extends ye{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===we?this.getSystemBalance(e):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 getErc20Balance(e,t){let{free:s,reserved:r,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(we,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let i=t.filter(a=>a.type!=="Erc20").filter(a=>a.id!==we).map(a=>[e,a.id]);return this.api.query.tokens.accounts.multi(i,a=>{let c=[];a.forEach((u,y)=>{let x=this.calculateFreeBalance(u),O=i[y][1];c.push([O,x])}),s(c)})}async subscribeErc20Balance(e,t,s){let r=t.filter(a=>a.type==="Erc20"),i=async()=>{let a=[];(await Promise.all(r.map(async u=>[u.id,await this.getErc20Balance(e,u.id)]))).forEach(([u,y])=>{a.push([u,y])}),s(a)};return await i(),this.api.rpc.chain.subscribeNewHeads(async()=>{i()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,a=new G(t),c=new G(s||i),u=new G(r||0n),y=c.gt(u)?c:u;return a.minus(y)}};import{isAddress as xt}from"@polkadot/util-crypto";import{fixed_from_rational as Ot}from"@galacticcouncil/math-liquidity-mining";var dt=class extends ye{constructor(e){super(e)}secondsInYear=new G(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.omnipoolWarehouseLM.globalFarm(u)).unwrap(),x=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,u,c)).unwrap(),O=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:x,priceAdjustment:O}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,a]=r.args,c=i.unwrap().toString(),u=a.toString(),y=(await this.api.query.xykWarehouseLM.globalFarm(u)).unwrap(),x=(await this.api.query.xykWarehouseLM.yieldFarm(e,u,c)).unwrap(),O=await this.getOraclePrice(y)??y.priceAdjustment.toString();return{assetId:e,globalFarm:y,yieldFarm:x,priceAdjustment:O}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new G(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),c=a.price.n.toString(),u=a.price.d.toString(),y;return Number(t)<Number(s)?y=Ot(c,u):y=Ot(u,c),y}getGlobalRewardPerPeriod(e,t,s,r){let a=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return a.gte(s)?s:a}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!xt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&xt(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:c,globalFarm:u,priceAdjustment:y})=>{let x=new G(u.totalSharesZ.toString()),O=u.plannedYieldingPeriods.toString(),T=new G(u.yieldPerPeriod.toString()),_=new G(u.maxRewardPerPeriod.toString()),F=u.blocksPerPeriod.toString(),D=new G(c.multiplier.toString()).shiftedBy(-18),k=this.secondsInYear.div(new G(s).times(F)),H;if(x.isZero())H=T.times(D).times(k);else{let de=this.getGlobalRewardPerPeriod(x,T,_,y);H=this.getPoolYieldPerPeriod(de,D,x,y).times(k)}let w=new G(u.pendingRewards.toString()).plus(u.accumulatedPaidRewards.toString()),J=_.times(O);return w.div(J).gte(.99)?E:H.times(100)}).reduce((c,u)=>c.plus(u),E).toString():void 0}};var he=class extends xe{pools=[];subs=[];assets=new Map([]);mem=0;memPools=ze(e=>(console.log(this.getPoolType(),"mem pools",e,"\u2705"),this.getPools()));constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=await this.subscribe();let e=this.getPoolType();return console.log(e,`pools(${this.augmentedPools.length})`,"\u2705"),console.log(e,`subs(${this.subs.length})`,"\u2705"),this.augmentedPools}async subscribe(){let e=this.augmentedPools.map(async s=>{let r=[await this.subscribeTokensPoolBalance(s)];try{let i=await this.subscribePoolChange(s);r.push(i)}catch{}if(this.hasSystemAsset(s)){let i=await this.subscribeSystemPoolBalance(s);r.push(i)}if(this.hasErc20Asset(s)){let i=await this.subscribeErc20PoolBalance(s);r.push(i)}if(this.hasShareAsset(s)){let i=await this.subscribeSharePoolBalance(s);r.push(i)}return this.subscribeLog(s),r});return(await Promise.all(e)).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasShareAsset(e){return e.type==="Stableswap"&&e.id}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e()})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}subscribeSharePoolBalance(e){let t=this.assets.get(e.id);return this.subscribeTokenBalance(Ye,[t],this.updateBalancesCallback(e,()=>!0))}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,i])=>{let a=e.tokens.findIndex(c=>c.id==r);a>=0&&t(e,r)&&(e.tokens[a].balance=i.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(i=>i.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var $e=class extends he{MAX_FINAL_WEIGHT=j(v(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,a])=>this.isActivePool(a.unwrap(),s)).map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=await this.getPoolDelta(u,c,s.toString());return this.poolsData.set(i.toString(),c),{address:u,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:u,repayTarget:y,feeCollector:x}=t,O=me.calculateLinearWeights(r.toString(),i.toString(),c.toString(),u.toString(),s),[T,_]=a,F=T.toString(),D=v(O),k=_.toString(),H=this.MAX_FINAL_WEIGHT.minus(v(D)),[w,J,se]=await Promise.all([this.isRepayFeeApplied(F,y.toString(),x.toString()),this.getBalance(e,F),this.getBalance(e,k)]);return{repayFeeApply:w,tokens:[{id:F,weight:D,balance:J.toString()},{id:k,weight:H,balance:se.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=v(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{encodeAddress as Vt}from"@polkadot/util-crypto";import{stringToU8a as Zt}from"@polkadot/util";function V(m,e){return m.shiftedBy(-1*e).toString()}function ue(m){return m[0]/m[1]*100}function ee(m){return m[0]/m[1]}function pe(m){return[m/ht,ht]}var Je=class extends he{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=s.map(async([{args:[u]},y])=>{let{hubReserve:x,shares:O,tradable:T}=y.unwrap(),_=await this.getBalance(t,u.toString());return{id:u.toString(),hubReserves:v(x.toString()),shares:v(O.toString()),tradeable:T.bits.toNumber(),balance:_.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:u,protocolFee:y}=s.unwrap();return{assetFee:pe(u.toNumber()),protocolFee:pe(y.toNumber()),min:pe(a),max:pe(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:pe(a),max:pe(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let a=e.tokens[i];if(r.isNone)return a;let c=r.unwrap();return this.updateTokenState(a,c)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i}=t;return{...e,hubReserves:v(s.toString()),shares:v(r.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return pe(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return pe(t)}getPoolId(){return Vt(Zt("modlomnipool".padEnd(32,"\0")),_e)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var je=class extends he{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[a,c]=r.unwrap(),[u,y]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:u.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}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 as,encodeAddress as ls}from"@polkadot/util-crypto";import{calculate_in_given_out as Kt,calculate_out_given_in as Qt,calculate_amplification as es,calculate_add_one_asset as ts,calculate_liquidity_out_one_asset as ss,calculate_pool_trade_fee as rs,calculate_shares as is,calculate_shares_for_amount as ns,pool_account_name as os}from"@galacticcouncil/math-stableswap";var te=class{static getPoolAddress(e){return os(e)}static calculateAmplification(e,t,s,r,i){return es(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,a){return Kt(e,t,s,r,i,a)}static calculateAddOneAsset(e,t,s,r,i,a){return ts(e,t,s,r,i,a)}static calculateSharesForAmount(e,t,s,r,i,a){return ns(e,t,s,r,i,a)}static calculateOutGivenIn(e,t,s,r,i,a){return Qt(e,t,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,s,r,i,a){return ss(e,t,s,r,i,a)}static calculateShares(e,t,s,r,i){return is(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return rs(e,t,s)}};var Ve=class extends he{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},a])=>{let c=a.unwrap(),u=i.toString(),y=this.getPoolAddress(u),[x,O]=await Promise.all([this.getPoolDelta(u,c,s.toString()),this.getPoolTokens(y,u,c)]);return this.stablePools.set(y,c),{address:y,id:u,type:"Stableswap",fee:pe(c.fee.toNumber()),tokens:O,...x,...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,u=te.calculateAmplification(r.toString(),i.toString(),a.toString(),c.toString(),s),y=await this.api.query.tokens.totalIssuance(e);return{amplification:u,totalIssuance:y.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async u=>{let[y,x]=await Promise.all([this.api.query.stableswap.assetTradability(t,u.toString()),this.getBalance(e,u.toString())]);return{id:u.toString(),tradeable:y.bits.toNumber(),balance:x.toString()}}),a=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:u}=c.unwrap(),y=await this.getBalance(Ye,t);a.push({id:t,tradeable:u.bits.toNumber(),balance:y.toString()})}return a}getPoolAddress(e){let t=Number(e),s=te.getPoolAddress(t);return ls(as(s),_e)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function ft(m){return m.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 Ze=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},vt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ee=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},It=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},At=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Tt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Re=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=ze(e=>(console.log("Registry mem sync",e,"\u2705"),this.syncRegistry()));constructor(e){this.api=e,this.assetClient=new Be(this.api),this.xykClient=new je(this.api),this.omniClient=new Je(this.api),this.lbpClient=new $e(this.api),this.stableClient=new Ve(this.api),this.clients=[this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}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 Ze(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(),ft(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(),ft(i));let c=()=>a;return{hex:a.toHex(),name:"RouterSell",get:c}}};var ke=(m,e)=>m===e?0:m==null?e==null?0:-1:e==null?m==null?0:1:typeof m.compare=="function"?m.compare(e):typeof e.compare=="function"?-e.compare(m):m<e?-1:m>e?1:0;var Ke=(m,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(m(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var us=Ke(()=>"illegal argument(s)"),Ft=m=>{throw new us(m)};var cs=Ke(()=>"index out of bounds"),Pt=m=>{throw new cs(m)},Qe=(m,e,t)=>(m<e||m>=t)&&Pt(m);var _t=23283064365386963e-26,et=class{float(e=1){return this.int()*_t*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*_t-.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 tt=class extends et{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var Et=new tt(Math.random);var Rt=m=>m!=null&&typeof m!="function"&&m.length!==void 0;var kt=Object.getPrototypeOf({}),st="function",Lt="string",Oe=(m,e)=>{let t;if(m===e)return!0;if(m!=null){if(typeof m.equiv===st)return m.equiv(e)}else return m==e;if(e!=null){if(typeof e.equiv===st)return e.equiv(m)}else return m==e;return typeof m===Lt||typeof e===Lt?!1:(t=Object.getPrototypeOf(m),(t==null||t===kt)&&(t=Object.getPrototypeOf(e),t==null||t===kt)?hs(m,e):typeof m!==st&&m.length!==void 0&&typeof e!==st&&e.length!==void 0?ms(m,e):m instanceof Set&&e instanceof Set?ps(m,e):m instanceof Map&&e instanceof Map?gs(m,e):m instanceof Date&&e instanceof Date?m.getTime()===e.getTime():m instanceof RegExp&&e instanceof RegExp?m.toString()===e.toString():m!==m&&e!==e)},ms=(m,e,t=Oe)=>{let s=m.length;if(s===e.length)for(;s-- >0&&t(m[s],e[s]););return s<0},ps=(m,e,t=Oe)=>m.size===e.size&&t([...m.keys()].sort(),[...e.keys()].sort()),gs=(m,e,t=Oe)=>m.size===e.size&&t([...m].sort(),[...e].sort()),hs=(m,e,t=Oe)=>{if(Object.keys(m).length!==Object.keys(e).length)return!1;for(let s in m)if(!e.hasOwnProperty(s)||!t(m[s],e[s]))return!1;return!0};var bt=class{value;constructor(e){this.value=e}deref(){return this.value}};var Mt=m=>m instanceof bt;var rt=class m{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Dt("next",this._head)}reverseIterator(){return Dt("prev",this.tail)}clear(){this.release()}compare(e,t=ke){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,a=0;for(;s-- >0&&a===0;)a=t(r.value,i.value),r=r.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof m||Rt(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(!Oe(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||ke;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!Mt(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&&Pt(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*Dt(m,e){for(;e;)yield e.value,e=e[m]}var it=class m extends rt{_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 m(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 m}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(Qe(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(Qe(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new m,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=Et){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)&&Ft("invalid indices: ${from} / ${to}");let i=new m,a=this.nthCell(s);for(;a&&++s<=r;)i.push(a.value),a=a.next;return i}sort(e=ke){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,a=0;for(let u=0;u<t&&(a++,i=i.next,!!i);u++);let c=t;for(;a>0||c>0&&i;){let u;a===0?(u=i,i=i.next,c--):!i||c===0||e(s.value,i.value)<=0?(u=s,s=s.next,a--):(u=i,i=i.next,c--),this._tail?this._tail.next=u:this._head=u,u.prev=this._tail,this._tail=u}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),Qe(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new m;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 nt=class m{map;items;opts;_size;constructor(e,t){let s={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=s.map(),this.items=new it,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(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}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 m(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),i=Math.max(0,s-(r?r.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(r,e,t,s):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let s=this.map.get(e);return s?this.resetEntry(s):this.set(e,await t())}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{release:e,maxsize:t,maxlen:s}=this.opts;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),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?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(this.opts.update?.(t,e.value.v,s),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 yt=class extends Re{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new nt(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
|
|
2
|
+
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Le=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new m(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(u=>[u.id,u])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let c=this.calculateTradeFee(t,s),u=ue(this.repayFeeApply?s.repayFee:s.exchangeFee),y=t.plus(c),x=this.calculateInGivenOut(e,y),O=e.balanceIn.div(this.maxInRatio);return x.isGreaterThan(O)&&i.push("MaxInRatioExceeded"),{amountIn:x,calculatedIn:x,amountOut:t,feePct:u,errors:i}}else{let c=this.calculateInGivenOut(e,t),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,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),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),u=this.calculateTradeFee(c,s),y=ue(this.repayFeeApply?s.repayFee:s.exchangeFee),x=c.minus(u),O=e.balanceOut.div(this.maxOutRatio);return x.isGreaterThan(O)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:x,feePct:y,errors:i}}}calculateInGivenOut(e,t){let s=me.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=me.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=me.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),j(le,e.decimalsOut).toString());return v(t)}spotPriceOutGivenIn(e){let t=me.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),j(le,e.decimalsIn).toString());return v(t)}calculateTradeFee(e,t){let s=me.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return v(s)}};import{calculate_in_given_out as ds,calculate_lrna_in_given_out as fs,calculate_out_given_in as Ps,calculate_out_given_lrna_in as bs,calculate_pool_trade_fee as ys,calculate_spot_price as Ss,calculate_lrna_spot_price as ws,calculate_shares as Bs,calculate_liquidity_out as xs,calculate_liquidity_lrna_out as Os,verify_asset_cap as vs,calculate_liquidity_hub_in as Is,is_sell_allowed as As,is_buy_allowed as Ns,is_add_liquidity_allowed as Ts,is_remove_liquidity_allowed as Fs}from"@galacticcouncil/math-omnipool";var X=class{static calculateSpotPrice(e,t,s,r){return Ss(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return ws(e,t)}static calculateInGivenOut(e,t,s,r,i,a,c,u,y){return ds(e,t,s,r,i,a,c,u,y)}static calculateLrnaInGivenOut(e,t,s,r,i){return fs(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,a,c,u,y){return Ps(e,t,s,r,i,a,c,u,y)}static calculateOutGivenLrnaIn(e,t,s,r,i){return bs(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return ys(e,t,s)}static calculateShares(e,t,s,r){return Bs(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,a,c,u){return xs(e,t,s,r,i,a,c,u)}static calculateLiquidityLRNAOut(e,t,s,r,i,a,c,u){return Os(e,t,s,r,i,a,c,u)}static calculateCapDifference(e,t,s,r){let i=G(t),a=G(e),c=G(r),y=G(s).shiftedBy(-18);if(i.div(c).lt(y)){let O=y.times(c).minus(i).times(a),T=i.times(G(1).minus(y));return O.div(T).toFixed(0)}else return"0"}static verifyAssetCap(e,t,s,r){return vs(e,t,s,r)}static calculateLimitHubIn(e,t,s,r){return Is(e,t,s,r)}static isSellAllowed(e){return As(e)}static isBuyAllowed(e){return Ns(e)}static isAddLiquidityAllowed(e){return Ts(e)}static isRemoveLiquidityAllowed(e){return Fs(e)}};var Me=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new m(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(x=>[x.id,x])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance),u=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:u,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=i.minus(r),c=r===E?E:a.div(r).multipliedBy(100).decimalPlaces(2),u=[],y=X.isSellAllowed(e.tradeableIn),x=X.isBuyAllowed(e.tradeableOut);(!y||!x)&&u.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&u.push("InsufficientTradingAmount");let O=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(O)&&u.push("MaxOutRatioExceeded");let T=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(T)&&u.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:c.toNumber(),errors:u}}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),u=[],y=X.isSellAllowed(e.tradeableIn),x=X.isBuyAllowed(e.tradeableOut);(!y||!x)&&u.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&u.push("InsufficientTradingAmount");let O=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(O)&&u.push("MaxInRatioExceeded");let T=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(T)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:c.toNumber(),errors:u}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=X.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():E.toString(),s?ee(s.protocolFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateLrnaInGivenOut(e,t,s){let r=X.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=X.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():E.toString(),s?ee(s.protocolFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateOutGivenLrnaIn(e,t,s){let r=X.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?ee(s.assetFee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=X.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return v(t).shiftedBy(-1*(Fe-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=X.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return v(t).shiftedBy(-1*(Fe-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=X.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Fe-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=X.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return v(t).shiftedBy(-1*(Fe-e.decimalsIn)).decimalPlaces(0,1)}};var De=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new m(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,u,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=u,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(x=>[x.id,x])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance),u=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:c,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?gt:r.tradeable,tradeableOut:this.id===t?gt:i.tradeable,assetInED:u,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),a=ue(s.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a,errors:c}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=ue(s.fee),c=[],u=X.isSellAllowed(e.tradeableIn),y=X.isBuyAllowed(e.tradeableOut);return(!u||!y)&&c.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a,errors:c}}calculateIn(e,t,s){let r=te.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ee(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateAddOneAsset(e,t,s){let r=te.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?ee(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateSharesForAmount(e,t,s){let r=te.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?ee(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=j(le,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,s){let r=te.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?ee(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateWithdrawOneAsset(e,t,s){let r=te.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?ee(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateShares(e,t,s){let r=te.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?ee(s.fee).toString():E.toString()),i=v(r);return i.isNegative()?E:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=j(le,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let s=te.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return v(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{calculate_in_given_out as _s,calculate_out_given_in as Es,calculate_pool_trade_fee as Rs,get_spot_price as ks,calculate_liquidity_in as Ls,calculate_shares as Ms,calculate_spot_price as Ds,calculate_spot_price_with_fee as Cs,calculate_liquidity_out_asset_a as Gs,calculate_liquidity_out_asset_b as qs}from"@galacticcouncil/math-xyk";var Pe=class{static getSpotPrice(e,t,s){return ks(e,t,s)}static calculateInGivenOut(e,t,s){return _s(e,t,s)}static calculateOutGivenIn(e,t,s){return Es(e,t,s)}static calculatePoolTradeFee(e,t,s){return Rs(e,t,s)}static calculateLiquidityIn(e,t,s){return Ls(e,t,s)}static calculateSpotPrice(e,t){return Ds(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return Cs(e,t,s,r)}static calculateShares(e,t,s){return Ms(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return Gs(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return qs(e,t,s,r)}};var Ce=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new m(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(x=>[x.id,x])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let a=v(r.balance),c=v(i.balance),u=v(r.existentialDeposit),y=v(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:c,assetInED:u,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),a=ue(s.exchangeFee),c=r.plus(i),u=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&u.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&u.push("MaxOutRatioExceeded");let x=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(x)&&u.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:r,amountOut:t,feePct:a,errors:u}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),a=ue(s.exchangeFee),c=r.minus(i),u=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&u.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&u.push("MaxInRatioExceeded");let x=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(x)&&u.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:a,errors:u}}calculateInGivenOut(e,t){let s=Pe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}calculateOutGivenIn(e,t){let s=Pe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=v(s);return r.isNegative()?E:r}spotPriceInGivenOut(e){let t=Pe.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=j(le,18-e.decimalsOut);return v(t).div(s)}spotPriceOutGivenIn(e){let t=Pe.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=j(le,18-e.decimalsIn);return v(t).div(s)}calculateTradeFee(e,t){let s=Pe.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return v(s)}};var Ge=class{static get(e){switch(e.type){case"Xyk":return Ce.fromPool(e);case"Omnipool":return Me.fromPool(e);case"Lbp":return Le.fromPool(e);case"Stableswap":return De.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var ve=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ne,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,meta:r.meta,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(c=>this.validPath(c,s)).map(c=>this.toHops(c,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,Ge.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let a=t.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function al(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function qe(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ct(m,e){return le.minus(e.div(m)).multipliedBy(100).decimalPlaces(2)}function Gt(m,e){return e.div(m).minus(le).multipliedBy(100).decimalPlaces(2)}var ot=class extends ve{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,a=r[r.length-1].amountOut;return i.isGreaterThan(a)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[s,r]}}getPoolFeeRange(e){let t=e.min?ue(e.min):void 0,s=e.max?ue(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ee(e,t);let u;if(r)u=await this.toSellSwaps(s,r,a);else{let R=c.map(async n=>await this.toSellSwaps(s,n,a)),W=await Promise.all(R);u=this.findBestSellRoute(W)}let y=u[0],x=u[u.length-1],O=this.isDirectTrade(u),T=u.map(R=>R.spotPrice.shiftedBy(-1*R.assetOutDecimals)).reduce((R,W)=>R.multipliedBy(W)),_=j(T,x.assetOutDecimals),F=O?x.calculatedOut:this.calculateDelta0Y(y.amountIn,u,a),D=x.amountOut,k=O?x.tradeFeePct:Ct(F,D).toNumber(),H=F.minus(D),w=this.getRouteFeeRange(u),J=y.amountIn.shiftedBy(-1*y.assetInDecimals).multipliedBy(_),se=qe(F,J),de=R=>this.poolService.buildSellTx(e,t,y.amountIn,R,u.map(W=>W));return{type:"Sell",amountIn:y.amountIn,amountOut:x.amountOut,spotPrice:_,tradeFee:H,tradeFeePct:k,tradeFeeRange:w,priceImpactPct:se.toNumber(),swaps:u,toTx:de,toHuman(){return{type:"Sell",amountIn:V(y.amountIn,y.assetInDecimals),amountOut:V(x.amountOut,x.assetOutDecimals),spotPrice:V(_,x.assetOutDecimals),tradeFee:V(H,x.assetOutDecimals),tradeFeePct:k,tradeFeeRange:w,priceImpactPct:se.toNumber(),swaps:u.map(R=>R.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1]:y=e;let x=c.calculateOutGivenIn(u,y);r.push(x)}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 u=c.parsePair(a.assetIn,a.assetOut),y;i>0?y=r[i-1].amountOut:y=j(v(e),u.decimalsIn).decimalPlaces(0,1);let x=await this.poolService.getPoolFees(u.assetOut,c),{amountOut:O,calculatedOut:T,feePct:_,errors:F}=c.validateAndSell(u,y,x),D=this.getPoolFeeRange(x),k=c.spotPriceOutGivenIn(u),H=y.shiftedBy(-1*u.decimalsIn).multipliedBy(k),w=qe(T,H);r.push({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountIn:y,calculatedOut:T,amountOut:O,spotPrice:k,tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w.toNumber(),errors:F,toHuman(){return{...a,amountIn:V(y,u.decimalsIn),calculatedOut:V(T,u.decimalsOut),amountOut:V(O,u.decimalsOut),spotPrice:V(k,u.decimalsOut),tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w.toNumber(),errors:F}}})}return r}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)return Promise.resolve(void 0);let a=s.map(w=>w.tokens.find(J=>J.id===e)).filter(w=>!!w).sort((w,J)=>Number(J.balance)-Number(w.balance)),{balance:c,decimals:u}=a[0],x=v(c).shiftedBy(-1*u).div(100).multipliedBy(.1),O=i.map(async w=>await this.toSellSwaps(x,w,r)),T=await Promise.all(O),_=this.findBestSellRoute(T),F=await this.toSellSwaps("1",_,r),D=F.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,J)=>w.multipliedBy(J)),k=F[F.length-1].assetOutDecimals;return{amount:j(D,k),decimals:k}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,a=r[0].amountIn;return i.isGreaterThan(a)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,i),c=super.getPaths(e,t,a,i);if(c.length===0)throw new Ee(e,t);let u;if(r)u=await this.toBuySwaps(s,r,a);else{let R=c.map(async n=>await this.toBuySwaps(s,n,a)),W=await Promise.all(R);u=this.findBestBuyRoute(W)}let y=u[u.length-1],x=u[0],O=this.isDirectTrade(u),T=u.map(R=>R.spotPrice.shiftedBy(-1*R.assetInDecimals)).reduce((R,W)=>R.multipliedBy(W)),_=j(T,x.assetInDecimals),F=O?x.calculatedIn:this.calculateDelta0X(y.amountOut,u,a),D=x.amountIn,k=O?x.tradeFeePct:Gt(F,D).toNumber(),H=D.minus(F),w=this.getRouteFeeRange(u),J=y.amountOut.shiftedBy(-1*y.assetOutDecimals).multipliedBy(_),se;F.isZero()?se=-100:se=qe(J,F).toNumber();let de=R=>this.poolService.buildBuyTx(e,t,y.amountOut,R,u.map(W=>W));return{type:"Buy",amountOut:y.amountOut,amountIn:x.amountIn,spotPrice:_,tradeFee:H,tradeFeePct:k,tradeFeeRange:w,priceImpactPct:se,swaps:u,toTx:de,toHuman(){return{type:"Buy",amountOut:V(y.amountOut,y.assetOutDecimals),amountIn:V(x.amountIn,x.assetInDecimals),spotPrice:V(_,x.assetInDecimals),tradeFee:V(H,x.assetInDecimals),tradeFeePct:k,tradeFeeRange:w,priceImpactPct:se,swaps:u.map(R=>R.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let a=t[i],c=s.get(a.poolAddress);if(c==null)throw new Error("Pool does not exit");let u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=e:y=r[0];let x=c.calculateInGivenOut(u,y);r.unshift(x)}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 u=c.parsePair(a.assetIn,a.assetOut),y;i==t.length-1?y=j(v(e),u.decimalsOut).decimalPlaces(0,1):y=r[0].amountIn;let x=await this.poolService.getPoolFees(u.assetOut,c),{amountIn:O,calculatedIn:T,feePct:_,errors:F}=c.validateAndBuy(u,y,x),D=this.getPoolFeeRange(x),k=c.spotPriceInGivenOut(u),H=y.shiftedBy(-1*u.decimalsOut).multipliedBy(k),w;T.isZero()?w=-100:w=qe(H,T).toNumber(),r.unshift({...a,assetInDecimals:u.decimalsIn,assetOutDecimals:u.decimalsOut,amountOut:y,calculatedIn:T,amountIn:O,spotPrice:k,tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w,errors:F,toHuman(){return{...a,amountOut:V(y,u.decimalsOut),calculatedIn:V(T,u.decimalsIn),amountIn:V(O,u.decimalsIn),spotPrice:V(k,u.decimalsIn),tradeFeePct:_,tradeFeeRange:D,priceImpactPct:w,errors:F}}})}return r}};function Ml(m,e){let t=[];return JSON.stringify(m,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function Dl(m,e,t){let s;return JSON.stringify(m,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}export{Be as AssetClient,It as AssetNotFound,dr as BASILISK_PARACHAIN_ID,xe as BalanceClient,G as BigNumber,yt as CachingPoolService,Ut as DECIMAL_PLACES,ht as DENOMINATOR,dt as FarmClient,Ye as HYDRADX_OMNIPOOL_ADDRESS,hr as HYDRADX_PARACHAIN_ID,_e as HYDRADX_SS58_PREFIX,or as INFINITY,me as LbpMath,Le as LbpPool,le as ONE,X as OmniMath,Me as OmniPool,vt as PoolConfigNotFound,Te as PoolError,Ge as PoolFactory,Ze as PoolNotFound,Re as PoolService,re as PoolType,Tt as ProviderConfigNotFound,Fe as RUNTIME_DECIMALS,Ee as RouteNotFound,ve as Router,gr as SYSTEM_ASSET_DECIMALS,we as SYSTEM_ASSET_ID,te as StableMath,De as StableSwap,At as StorageConfigNotFound,Nt as SubscriptionNotSupported,gt as TRADEABLE_DEFAULT,ot as TradeRouter,Bt as TradeType,Pe as XykMath,Ce as XykPool,E as ZERO,v as bnum,ft as buildRoute,Gt as calculateBuyFee,al as calculateDiffToAvg,qe as calculateDiffToRef,Ct as calculateSellFee,Ml as findNestedKey,Dl as findNestedObj,j as scale};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ApiPromise } from '@polkadot/api';
|
|
2
|
+
import { VoidFn } from '@polkadot/api-base/types';
|
|
3
|
+
import { AssetClient, BalanceClient } from '../client';
|
|
4
|
+
import { BigNumber } from '../utils/bignumber';
|
|
5
|
+
export declare class WalletCtx extends BalanceClient {
|
|
6
|
+
protected readonly assetClient: AssetClient;
|
|
7
|
+
protected ctx: Map<string, BigNumber>;
|
|
8
|
+
protected subs: VoidFn[];
|
|
9
|
+
private assets;
|
|
10
|
+
private memBalances;
|
|
11
|
+
constructor(api: ApiPromise);
|
|
12
|
+
getBalancesMem(account: string): Promise<Map<string, BigNumber>>;
|
|
13
|
+
private getBalances;
|
|
14
|
+
unsubscribe(): void;
|
|
15
|
+
private getAccountBalanceData;
|
|
16
|
+
private subscribeTokensAccountBalance;
|
|
17
|
+
private subscribeErc20AccountBalance;
|
|
18
|
+
private subscribeSystemAccountBalance;
|
|
19
|
+
private updateCtxCallback;
|
|
20
|
+
}
|
|
@@ -21,7 +21,7 @@ export declare abstract class PoolClient extends BalanceClient {
|
|
|
21
21
|
* @param assets - registry assets
|
|
22
22
|
*/
|
|
23
23
|
withAssets(assets: Asset[]): Promise<void>;
|
|
24
|
-
|
|
24
|
+
getPoolsMem(): Promise<PoolBase[]>;
|
|
25
25
|
getPools(): Promise<PoolBase[]>;
|
|
26
26
|
private subscribe;
|
|
27
27
|
private hasSystemAsset;
|
package/build/types/types.d.ts
CHANGED
|
@@ -126,8 +126,7 @@ export interface Asset extends AssetMetadata {
|
|
|
126
126
|
type: string;
|
|
127
127
|
existentialDeposit: string;
|
|
128
128
|
isSufficient: boolean;
|
|
129
|
-
|
|
130
|
-
externalId?: number;
|
|
129
|
+
location?: any;
|
|
131
130
|
meta?: Record<string, string>;
|
|
132
131
|
isWhiteListed?: boolean;
|
|
133
132
|
}
|