@galacticcouncil/sdk 1.1.3 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var nr=Object.create;var vt=Object.defineProperty;var rr=Object.getOwnPropertyDescriptor;var or=Object.getOwnPropertyNames;var ir=Object.getPrototypeOf,sr=Object.prototype.hasOwnProperty;var Ot=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),ar=(s,e)=>{for(var t in e)vt(s,t,{get:e[t],enumerable:!0})},Bn=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of or(e))!sr.call(s,r)&&r!==t&&vt(s,r,{get:()=>e[r],enumerable:!(n=rr(e,r))||n.enumerable});return s};var Bt=(s,e,t)=>(t=s!=null?nr(ir(s)):{},Bn(e||!s||!s.__esModule?vt(t,"default",{value:s,enumerable:!0}):t,s)),lr=s=>Bn(vt({},"__esModule",{value:!0}),s);var Fn=Ot((vo,Ze)=>{var dr={},R,{TextEncoder:pr,TextDecoder:mr}=require("util"),re=0,Tt=null;function kt(){return(Tt===null||Tt.byteLength===0)&&(Tt=new Uint8Array(R.memory.buffer)),Tt}var Et=new pr("utf-8"),gr=typeof Et.encodeInto=="function"?function(s,e){return Et.encodeInto(s,e)}:function(s,e){let t=Et.encode(s);return e.set(t),{read:s.length,written:t.length}};function le(s,e,t){if(t===void 0){let a=Et.encode(s),c=e(a.length,1)>>>0;return kt().subarray(c,c+a.length).set(a),re=a.length,c}let n=s.length,r=e(n,1)>>>0,o=kt(),i=0;for(;i<n;i++){let a=s.charCodeAt(i);if(a>127)break;o[r+i]=a}if(i!==n){i!==0&&(s=s.slice(i)),r=t(r,n,n=i+s.length*3,1)>>>0;let a=kt().subarray(r+i,r+n),c=gr(s,a);i+=c.written}return re=i,r}var Ft=null;function Me(){return(Ft===null||Ft.byteLength===0)&&(Ft=new Int32Array(R.memory.buffer)),Ft}var Tn=new mr("utf-8",{ignoreBOM:!0,fatal:!0});Tn.decode();function ft(s,e){return s=s>>>0,Tn.decode(kt().subarray(s,s+e))}Ze.exports.calculate_pool_trade_fee=function(s,e,t){let n,r;try{let a=R.__wbindgen_add_to_stack_pointer(-16),c=le(s,R.__wbindgen_malloc,R.__wbindgen_realloc),p=re;R.calculate_pool_trade_fee(a,c,p,e,t);var o=Me()[a/4+0],i=Me()[a/4+1];return n=o,r=i,ft(o,i)}finally{R.__wbindgen_add_to_stack_pointer(16),R.__wbindgen_free(n,r,1)}};Ze.exports.get_spot_price=function(s,e,t,n,r){let o,i;try{let p=R.__wbindgen_add_to_stack_pointer(-16),b=le(s,R.__wbindgen_malloc,R.__wbindgen_realloc),x=re,B=le(e,R.__wbindgen_malloc,R.__wbindgen_realloc),T=re,k=le(t,R.__wbindgen_malloc,R.__wbindgen_realloc),L=re,E=le(n,R.__wbindgen_malloc,R.__wbindgen_realloc),M=re,v=le(r,R.__wbindgen_malloc,R.__wbindgen_realloc),G=re;R.get_spot_price(p,b,x,B,T,k,L,E,M,v,G);var a=Me()[p/4+0],c=Me()[p/4+1];return o=a,i=c,ft(a,c)}finally{R.__wbindgen_add_to_stack_pointer(16),R.__wbindgen_free(o,i,1)}};Ze.exports.calculate_out_given_in=function(s,e,t,n,r){let o,i;try{let p=R.__wbindgen_add_to_stack_pointer(-16),b=le(s,R.__wbindgen_malloc,R.__wbindgen_realloc),x=re,B=le(e,R.__wbindgen_malloc,R.__wbindgen_realloc),T=re,k=le(t,R.__wbindgen_malloc,R.__wbindgen_realloc),L=re,E=le(n,R.__wbindgen_malloc,R.__wbindgen_realloc),M=re,v=le(r,R.__wbindgen_malloc,R.__wbindgen_realloc),G=re;R.calculate_out_given_in(p,b,x,B,T,k,L,E,M,v,G);var a=Me()[p/4+0],c=Me()[p/4+1];return o=a,i=c,ft(a,c)}finally{R.__wbindgen_add_to_stack_pointer(16),R.__wbindgen_free(o,i,1)}};Ze.exports.calculate_in_given_out=function(s,e,t,n,r){let o,i;try{let p=R.__wbindgen_add_to_stack_pointer(-16),b=le(s,R.__wbindgen_malloc,R.__wbindgen_realloc),x=re,B=le(e,R.__wbindgen_malloc,R.__wbindgen_realloc),T=re,k=le(t,R.__wbindgen_malloc,R.__wbindgen_realloc),L=re,E=le(n,R.__wbindgen_malloc,R.__wbindgen_realloc),M=re,v=le(r,R.__wbindgen_malloc,R.__wbindgen_realloc),G=re;R.calculate_in_given_out(p,b,x,B,T,k,L,E,M,v,G);var a=Me()[p/4+0],c=Me()[p/4+1];return o=a,i=c,ft(a,c)}finally{R.__wbindgen_add_to_stack_pointer(16),R.__wbindgen_free(o,i,1)}};Ze.exports.calculate_linear_weights=function(s,e,t,n,r){let o,i;try{let p=R.__wbindgen_add_to_stack_pointer(-16),b=le(s,R.__wbindgen_malloc,R.__wbindgen_realloc),x=re,B=le(e,R.__wbindgen_malloc,R.__wbindgen_realloc),T=re,k=le(t,R.__wbindgen_malloc,R.__wbindgen_realloc),L=re,E=le(n,R.__wbindgen_malloc,R.__wbindgen_realloc),M=re,v=le(r,R.__wbindgen_malloc,R.__wbindgen_realloc),G=re;R.calculate_linear_weights(p,b,x,B,T,k,L,E,M,v,G);var a=Me()[p/4+0],c=Me()[p/4+1];return o=a,i=c,ft(a,c)}finally{R.__wbindgen_add_to_stack_pointer(16),R.__wbindgen_free(o,i,1)}};var fr=require("path").join(__dirname,"hydra_dx_wasm_bg.wasm"),hr=require("fs").readFileSync(fr),br=new WebAssembly.Module(hr),wr=new WebAssembly.Instance(br,dr);R=wr.exports;Ze.exports.__wasm=R});var Cn=Ot((ls,Ee)=>{var xr={},O,{TextEncoder:vr,TextDecoder:Or}=require("util"),W=0,qt=null;function bt(){return(qt===null||qt.byteLength===0)&&(qt=new Uint8Array(O.memory.buffer)),qt}var Ht=new vr("utf-8"),Br=typeof Ht.encodeInto=="function"?function(s,e){return Ht.encodeInto(s,e)}:function(s,e){let t=Ht.encode(s);return e.set(t),{read:s.length,written:t.length}};function z(s,e,t){if(t===void 0){let a=Ht.encode(s),c=e(a.length,1)>>>0;return bt().subarray(c,c+a.length).set(a),W=a.length,c}let n=s.length,r=e(n,1)>>>0,o=bt(),i=0;for(;i<n;i++){let a=s.charCodeAt(i);if(a>127)break;o[r+i]=a}if(i!==n){i!==0&&(s=s.slice(i)),r=t(r,n,n=i+s.length*3,1)>>>0;let a=bt().subarray(r+i,r+n),c=Br(s,a);i+=c.written}return W=i,r}var Gt=null;function de(){return(Gt===null||Gt.byteLength===0)&&(Gt=new Int32Array(O.memory.buffer)),Gt}var Dn=new Or("utf-8",{ignoreBOM:!0,fatal:!0});Dn.decode();function Xe(s,e){return s=s>>>0,Dn.decode(bt().subarray(s,s+e))}Ee.exports.calculate_pool_trade_fee=function(s,e,t){let n,r;try{let a=O.__wbindgen_add_to_stack_pointer(-16),c=z(s,O.__wbindgen_malloc,O.__wbindgen_realloc),p=W;O.calculate_pool_trade_fee(a,c,p,e,t);var o=de()[a/4+0],i=de()[a/4+1];return n=o,r=i,Xe(o,i)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(n,r,1)}};Ee.exports.calculate_out_given_in=function(s,e,t,n,r,o){let i,a;try{let b=O.__wbindgen_add_to_stack_pointer(-16),x=z(s,O.__wbindgen_malloc,O.__wbindgen_realloc),B=W,T=z(n,O.__wbindgen_malloc,O.__wbindgen_realloc),k=W,L=z(r,O.__wbindgen_malloc,O.__wbindgen_realloc),E=W,M=z(o,O.__wbindgen_malloc,O.__wbindgen_realloc),v=W;O.calculate_out_given_in(b,x,B,e,t,T,k,L,E,M,v);var c=de()[b/4+0],p=de()[b/4+1];return i=c,a=p,Xe(c,p)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(i,a,1)}};Ee.exports.calculate_in_given_out=function(s,e,t,n,r,o){let i,a;try{let b=O.__wbindgen_add_to_stack_pointer(-16),x=z(s,O.__wbindgen_malloc,O.__wbindgen_realloc),B=W,T=z(n,O.__wbindgen_malloc,O.__wbindgen_realloc),k=W,L=z(r,O.__wbindgen_malloc,O.__wbindgen_realloc),E=W,M=z(o,O.__wbindgen_malloc,O.__wbindgen_realloc),v=W;O.calculate_in_given_out(b,x,B,e,t,T,k,L,E,M,v);var c=de()[b/4+0],p=de()[b/4+1];return i=c,a=p,Xe(c,p)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(i,a,1)}};Ee.exports.calculate_amplification=function(s,e,t,n,r){let o,i;try{let p=O.__wbindgen_add_to_stack_pointer(-16),b=z(s,O.__wbindgen_malloc,O.__wbindgen_realloc),x=W,B=z(e,O.__wbindgen_malloc,O.__wbindgen_realloc),T=W,k=z(t,O.__wbindgen_malloc,O.__wbindgen_realloc),L=W,E=z(n,O.__wbindgen_malloc,O.__wbindgen_realloc),M=W,v=z(r,O.__wbindgen_malloc,O.__wbindgen_realloc),G=W;O.calculate_amplification(p,b,x,B,T,k,L,E,M,v,G);var a=de()[p/4+0],c=de()[p/4+1];return o=a,i=c,Xe(a,c)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(o,i,1)}};Ee.exports.calculate_shares=function(s,e,t,n,r){let o,i;try{let p=O.__wbindgen_add_to_stack_pointer(-16),b=z(s,O.__wbindgen_malloc,O.__wbindgen_realloc),x=W,B=z(e,O.__wbindgen_malloc,O.__wbindgen_realloc),T=W,k=z(t,O.__wbindgen_malloc,O.__wbindgen_realloc),L=W,E=z(n,O.__wbindgen_malloc,O.__wbindgen_realloc),M=W,v=z(r,O.__wbindgen_malloc,O.__wbindgen_realloc),G=W;O.calculate_shares(p,b,x,B,T,k,L,E,M,v,G);var a=de()[p/4+0],c=de()[p/4+1];return o=a,i=c,Xe(a,c)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(o,i,1)}};Ee.exports.calculate_shares_for_amount=function(s,e,t,n,r,o){let i,a;try{let b=O.__wbindgen_add_to_stack_pointer(-16),x=z(s,O.__wbindgen_malloc,O.__wbindgen_realloc),B=W,T=z(t,O.__wbindgen_malloc,O.__wbindgen_realloc),k=W,L=z(n,O.__wbindgen_malloc,O.__wbindgen_realloc),E=W,M=z(r,O.__wbindgen_malloc,O.__wbindgen_realloc),v=W,G=z(o,O.__wbindgen_malloc,O.__wbindgen_realloc),V=W;O.calculate_shares_for_amount(b,x,B,e,T,k,L,E,M,v,G,V);var c=de()[b/4+0],p=de()[b/4+1];return i=c,a=p,Xe(c,p)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(i,a,1)}};Ee.exports.calculate_add_one_asset=function(s,e,t,n,r,o){let i,a;try{let b=O.__wbindgen_add_to_stack_pointer(-16),x=z(s,O.__wbindgen_malloc,O.__wbindgen_realloc),B=W,T=z(e,O.__wbindgen_malloc,O.__wbindgen_realloc),k=W,L=z(n,O.__wbindgen_malloc,O.__wbindgen_realloc),E=W,M=z(r,O.__wbindgen_malloc,O.__wbindgen_realloc),v=W,G=z(o,O.__wbindgen_malloc,O.__wbindgen_realloc),V=W;O.calculate_add_one_asset(b,x,B,T,k,t,L,E,M,v,G,V);var c=de()[b/4+0],p=de()[b/4+1];return i=c,a=p,Xe(c,p)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(i,a,1)}};function Ir(s,e){return s=s>>>0,bt().subarray(s/1,s/1+e)}Ee.exports.pool_account_name=function(s){try{let r=O.__wbindgen_add_to_stack_pointer(-16);O.pool_account_name(r,s);var e=de()[r/4+0],t=de()[r/4+1],n=Ir(e,t).slice();return O.__wbindgen_free(e,t*1),n}finally{O.__wbindgen_add_to_stack_pointer(16)}};Ee.exports.calculate_liquidity_out_one_asset=function(s,e,t,n,r,o){let i,a;try{let b=O.__wbindgen_add_to_stack_pointer(-16),x=z(s,O.__wbindgen_malloc,O.__wbindgen_realloc),B=W,T=z(e,O.__wbindgen_malloc,O.__wbindgen_realloc),k=W,L=z(n,O.__wbindgen_malloc,O.__wbindgen_realloc),E=W,M=z(r,O.__wbindgen_malloc,O.__wbindgen_realloc),v=W,G=z(o,O.__wbindgen_malloc,O.__wbindgen_realloc),V=W;O.calculate_liquidity_out_one_asset(b,x,B,T,k,t,L,E,M,v,G,V);var c=de()[b/4+0],p=de()[b/4+1];return i=c,a=p,Xe(c,p)}finally{O.__wbindgen_add_to_stack_pointer(16),O.__wbindgen_free(i,a,1)}};var Ar=require("path").join(__dirname,"hydra_dx_wasm_bg.wasm"),Nr=require("fs").readFileSync(Ar),Tr=new WebAssembly.Module(Nr),Fr=new WebAssembly.Instance(Tr,xr);O=Fr.exports;Ee.exports.__wasm=O});var Kn=Ot((Ya,oe)=>{var Cr={},u,{TextEncoder:qr,TextDecoder:Gr}=require("util"),A=0,Kt=null;function tn(){return(Kt===null||Kt.byteLength===0)&&(Kt=new Uint8Array(u.memory.buffer)),Kt}var nn=new qr("utf-8"),Hr=typeof nn.encodeInto=="function"?function(s,e){return nn.encodeInto(s,e)}:function(s,e){let t=nn.encode(s);return e.set(t),{read:s.length,written:t.length}};function N(s,e,t){if(t===void 0){let a=nn.encode(s),c=e(a.length)>>>0;return tn().subarray(c,c+a.length).set(a),A=a.length,c}let n=s.length,r=e(n)>>>0,o=tn(),i=0;for(;i<n;i++){let a=s.charCodeAt(i);if(a>127)break;o[r+i]=a}if(i!==n){i!==0&&(s=s.slice(i)),r=t(r,n,n=i+s.length*3)>>>0;let a=tn().subarray(r+i,r+n),c=Hr(s,a);i+=c.written}return A=i,r}var en=null;function j(){return(en===null||en.byteLength===0)&&(en=new Int32Array(u.memory.buffer)),en}var Zn=new Gr("utf-8",{ignoreBOM:!0,fatal:!0});Zn.decode();function fe(s,e){return s=s>>>0,Zn.decode(tn().subarray(s,s+e))}oe.exports.calculate_shares=function(s,e,t,n){let r,o;try{let c=u.__wbindgen_add_to_stack_pointer(-16),p=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),b=A,x=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),B=A,T=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),k=A,L=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),E=A;u.calculate_shares(c,p,b,x,B,T,k,L,E);var i=j()[c/4+0],a=j()[c/4+1];return r=i,o=a,fe(i,a)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(r,o)}};oe.exports.calculate_withdrawal_fee=function(s,e,t){let n,r;try{let a=u.__wbindgen_add_to_stack_pointer(-16),c=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),p=A,b=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),x=A,B=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),T=A;u.calculate_withdrawal_fee(a,c,p,b,x,B,T);var o=j()[a/4+0],i=j()[a/4+1];return n=o,r=i,fe(o,i)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(n,r)}};oe.exports.calculate_liquidity_out=function(s,e,t,n,r,o,i,a){let c,p;try{let B=u.__wbindgen_add_to_stack_pointer(-16),T=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),k=A,L=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),E=A,M=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),v=A,G=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),V=A,te=N(r,u.__wbindgen_malloc,u.__wbindgen_realloc),Q=A,H=N(o,u.__wbindgen_malloc,u.__wbindgen_realloc),l=A,_=N(i,u.__wbindgen_malloc,u.__wbindgen_realloc),d=A,w=N(a,u.__wbindgen_malloc,u.__wbindgen_realloc),g=A;u.calculate_liquidity_out(B,T,k,L,E,M,v,G,V,te,Q,H,l,_,d,w,g);var b=j()[B/4+0],x=j()[B/4+1];return c=b,p=x,fe(b,x)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(c,p)}};oe.exports.calculate_liquidity_lrna_out=function(s,e,t,n,r,o,i,a){let c,p;try{let B=u.__wbindgen_add_to_stack_pointer(-16),T=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),k=A,L=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),E=A,M=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),v=A,G=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),V=A,te=N(r,u.__wbindgen_malloc,u.__wbindgen_realloc),Q=A,H=N(o,u.__wbindgen_malloc,u.__wbindgen_realloc),l=A,_=N(i,u.__wbindgen_malloc,u.__wbindgen_realloc),d=A,w=N(a,u.__wbindgen_malloc,u.__wbindgen_realloc),g=A;u.calculate_liquidity_lrna_out(B,T,k,L,E,M,v,G,V,te,Q,H,l,_,d,w,g);var b=j()[B/4+0],x=j()[B/4+1];return c=b,p=x,fe(b,x)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(c,p)}};oe.exports.recalculate_asset_fee=function(s,e,t,n,r,o,i,a,c){let p,b;try{let T=u.__wbindgen_add_to_stack_pointer(-16),k=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),L=A,E=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),M=A,v=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),G=A,V=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),te=A,Q=N(r,u.__wbindgen_malloc,u.__wbindgen_realloc),H=A,l=N(o,u.__wbindgen_malloc,u.__wbindgen_realloc),_=A,d=N(i,u.__wbindgen_malloc,u.__wbindgen_realloc),w=A,g=N(a,u.__wbindgen_malloc,u.__wbindgen_realloc),f=A,y=N(c,u.__wbindgen_malloc,u.__wbindgen_realloc),m=A;u.recalculate_asset_fee(T,k,L,E,M,v,G,V,te,Q,H,l,_,d,w,g,f,y,m);var x=j()[T/4+0],B=j()[T/4+1];return p=x,b=B,fe(x,B)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(p,b)}};oe.exports.recalculate_protocol_fee=function(s,e,t,n,r,o,i,a,c){let p,b;try{let T=u.__wbindgen_add_to_stack_pointer(-16),k=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),L=A,E=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),M=A,v=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),G=A,V=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),te=A,Q=N(r,u.__wbindgen_malloc,u.__wbindgen_realloc),H=A,l=N(o,u.__wbindgen_malloc,u.__wbindgen_realloc),_=A,d=N(i,u.__wbindgen_malloc,u.__wbindgen_realloc),w=A,g=N(a,u.__wbindgen_malloc,u.__wbindgen_realloc),f=A,y=N(c,u.__wbindgen_malloc,u.__wbindgen_realloc),m=A;u.recalculate_protocol_fee(T,k,L,E,M,v,G,V,te,Q,H,l,_,d,w,g,f,y,m);var x=j()[T/4+0],B=j()[T/4+1];return p=x,b=B,fe(x,B)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(p,b)}};oe.exports.calculate_out_given_in=function(s,e,t,n,r,o,i,a,c){let p,b;try{let T=u.__wbindgen_add_to_stack_pointer(-16),k=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),L=A,E=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),M=A,v=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),G=A,V=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),te=A,Q=N(r,u.__wbindgen_malloc,u.__wbindgen_realloc),H=A,l=N(o,u.__wbindgen_malloc,u.__wbindgen_realloc),_=A,d=N(i,u.__wbindgen_malloc,u.__wbindgen_realloc),w=A,g=N(a,u.__wbindgen_malloc,u.__wbindgen_realloc),f=A,y=N(c,u.__wbindgen_malloc,u.__wbindgen_realloc),m=A;u.calculate_out_given_in(T,k,L,E,M,v,G,V,te,Q,H,l,_,d,w,g,f,y,m);var x=j()[T/4+0],B=j()[T/4+1];return p=x,b=B,fe(x,B)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(p,b)}};oe.exports.calculate_out_given_lrna_in=function(s,e,t,n,r){let o,i;try{let p=u.__wbindgen_add_to_stack_pointer(-16),b=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),x=A,B=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),T=A,k=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),L=A,E=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),M=A,v=N(r,u.__wbindgen_malloc,u.__wbindgen_realloc),G=A;u.calculate_out_given_lrna_in(p,b,x,B,T,k,L,E,M,v,G);var a=j()[p/4+0],c=j()[p/4+1];return o=a,i=c,fe(a,c)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(o,i)}};oe.exports.calculate_in_given_out=function(s,e,t,n,r,o,i,a,c){let p,b;try{let T=u.__wbindgen_add_to_stack_pointer(-16),k=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),L=A,E=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),M=A,v=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),G=A,V=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),te=A,Q=N(r,u.__wbindgen_malloc,u.__wbindgen_realloc),H=A,l=N(o,u.__wbindgen_malloc,u.__wbindgen_realloc),_=A,d=N(i,u.__wbindgen_malloc,u.__wbindgen_realloc),w=A,g=N(a,u.__wbindgen_malloc,u.__wbindgen_realloc),f=A,y=N(c,u.__wbindgen_malloc,u.__wbindgen_realloc),m=A;u.calculate_in_given_out(T,k,L,E,M,v,G,V,te,Q,H,l,_,d,w,g,f,y,m);var x=j()[T/4+0],B=j()[T/4+1];return p=x,b=B,fe(x,B)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(p,b)}};oe.exports.calculate_lrna_in_given_out=function(s,e,t,n,r){let o,i;try{let p=u.__wbindgen_add_to_stack_pointer(-16),b=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),x=A,B=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),T=A,k=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),L=A,E=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),M=A,v=N(r,u.__wbindgen_malloc,u.__wbindgen_realloc),G=A;u.calculate_lrna_in_given_out(p,b,x,B,T,k,L,E,M,v,G);var a=j()[p/4+0],c=j()[p/4+1];return o=a,i=c,fe(a,c)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(o,i)}};oe.exports.calculate_spot_price=function(s,e,t,n){let r,o;try{let c=u.__wbindgen_add_to_stack_pointer(-16),p=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),b=A,x=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),B=A,T=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),k=A,L=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),E=A;u.calculate_spot_price(c,p,b,x,B,T,k,L,E);var i=j()[c/4+0],a=j()[c/4+1];return r=i,o=a,fe(i,a)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(r,o)}};oe.exports.calculate_lrna_spot_price=function(s,e){let t,n;try{let i=u.__wbindgen_add_to_stack_pointer(-16),a=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),c=A,p=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),b=A;u.calculate_lrna_spot_price(i,a,c,p,b);var r=j()[i/4+0],o=j()[i/4+1];return t=r,n=o,fe(r,o)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(t,n)}};oe.exports.calculate_cap_difference=function(s,e,t,n){let r,o;try{let c=u.__wbindgen_add_to_stack_pointer(-16),p=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),b=A,x=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),B=A,T=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),k=A,L=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),E=A;u.calculate_cap_difference(c,p,b,x,B,T,k,L,E);var i=j()[c/4+0],a=j()[c/4+1];return r=i,o=a,fe(i,a)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(r,o)}};oe.exports.verify_asset_cap=function(s,e,t,n){let r=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),o=A,i=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),a=A,c=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),p=A,b=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),x=A;return u.verify_asset_cap(r,o,i,a,c,p,b,x)!==0};oe.exports.calculate_tvl_cap_difference=function(s,e,t,n,r,o){let i,a;try{let b=u.__wbindgen_add_to_stack_pointer(-16),x=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),B=A,T=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),k=A,L=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),E=A,M=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),v=A,G=N(r,u.__wbindgen_malloc,u.__wbindgen_realloc),V=A,te=N(o,u.__wbindgen_malloc,u.__wbindgen_realloc),Q=A;u.calculate_tvl_cap_difference(b,x,B,T,k,L,E,M,v,G,V,te,Q);var c=j()[b/4+0],p=j()[b/4+1];return i=c,a=p,fe(c,p)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(i,a)}};oe.exports.calculate_liquidity_hub_in=function(s,e,t,n){let r,o;try{let c=u.__wbindgen_add_to_stack_pointer(-16),p=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),b=A,x=N(e,u.__wbindgen_malloc,u.__wbindgen_realloc),B=A,T=N(t,u.__wbindgen_malloc,u.__wbindgen_realloc),k=A,L=N(n,u.__wbindgen_malloc,u.__wbindgen_realloc),E=A;u.calculate_liquidity_hub_in(c,p,b,x,B,T,k,L,E);var i=j()[c/4+0],a=j()[c/4+1];return r=i,o=a,fe(i,a)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(r,o)}};oe.exports.is_sell_allowed=function(s){return u.is_sell_allowed(s)!==0};oe.exports.is_buy_allowed=function(s){return u.is_buy_allowed(s)!==0};oe.exports.is_add_liquidity_allowed=function(s){return u.is_add_liquidity_allowed(s)!==0};oe.exports.is_remove_liquidity_allowed=function(s){return u.is_remove_liquidity_allowed(s)!==0};oe.exports.calculate_pool_trade_fee=function(s,e,t){let n,r;try{let a=u.__wbindgen_add_to_stack_pointer(-16),c=N(s,u.__wbindgen_malloc,u.__wbindgen_realloc),p=A;u.calculate_pool_trade_fee(a,c,p,e,t);var o=j()[a/4+0],i=j()[a/4+1];return n=o,r=i,fe(o,i)}finally{u.__wbindgen_add_to_stack_pointer(16),u.__wbindgen_free(n,r)}};var Ur=require("path").join(__dirname,"hydra_dx_wasm_bg.wasm"),Wr=require("fs").readFileSync(Ur),zr=new WebAssembly.Module(Wr),Xr=new WebAssembly.Instance(zr,Cr);u=Xr.exports;oe.exports.__wasm=u});var tr=Ot((Ol,Ge)=>{var Yr={},F,{TextEncoder:$r,TextDecoder:Jr}=require("util"),K=0,rn=null;function sn(){return(rn===null||rn.buffer!==F.memory.buffer)&&(rn=new Uint8Array(F.memory.buffer)),rn}var an=new $r("utf-8"),jr=typeof an.encodeInto=="function"?function(s,e){return an.encodeInto(s,e)}:function(s,e){let t=an.encode(s);return e.set(t),{read:s.length,written:t.length}};function ee(s,e,t){if(t===void 0){let a=an.encode(s),c=e(a.length);return sn().subarray(c,c+a.length).set(a),K=a.length,c}let n=s.length,r=e(n),o=sn(),i=0;for(;i<n;i++){let a=s.charCodeAt(i);if(a>127)break;o[r+i]=a}if(i!==n){i!==0&&(s=s.slice(i)),r=t(r,n,n=i+s.length*3);let a=sn().subarray(r+i,r+n),c=jr(s,a);i+=c.written}return K=i,r}var on=null;function he(){return(on===null||on.buffer!==F.memory.buffer)&&(on=new Int32Array(F.memory.buffer)),on}var er=new Jr("utf-8",{ignoreBOM:!0,fatal:!0});er.decode();function je(s,e){return er.decode(sn().subarray(s,s+e))}Ge.exports.calculate_pool_trade_fee=function(s,e,t){try{let o=F.__wbindgen_add_to_stack_pointer(-16),i=ee(s,F.__wbindgen_malloc,F.__wbindgen_realloc),a=K;F.calculate_pool_trade_fee(o,i,a,e,t);var n=he()[o/4+0],r=he()[o/4+1];return je(n,r)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(n,r)}};Ge.exports.get_spot_price=function(s,e,t){try{let o=F.__wbindgen_add_to_stack_pointer(-16),i=ee(s,F.__wbindgen_malloc,F.__wbindgen_realloc),a=K,c=ee(e,F.__wbindgen_malloc,F.__wbindgen_realloc),p=K,b=ee(t,F.__wbindgen_malloc,F.__wbindgen_realloc),x=K;F.get_spot_price(o,i,a,c,p,b,x);var n=he()[o/4+0],r=he()[o/4+1];return je(n,r)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(n,r)}};Ge.exports.calculate_out_given_in=function(s,e,t){try{let o=F.__wbindgen_add_to_stack_pointer(-16),i=ee(s,F.__wbindgen_malloc,F.__wbindgen_realloc),a=K,c=ee(e,F.__wbindgen_malloc,F.__wbindgen_realloc),p=K,b=ee(t,F.__wbindgen_malloc,F.__wbindgen_realloc),x=K;F.calculate_out_given_in(o,i,a,c,p,b,x);var n=he()[o/4+0],r=he()[o/4+1];return je(n,r)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(n,r)}};Ge.exports.calculate_in_given_out=function(s,e,t){try{let o=F.__wbindgen_add_to_stack_pointer(-16),i=ee(s,F.__wbindgen_malloc,F.__wbindgen_realloc),a=K,c=ee(e,F.__wbindgen_malloc,F.__wbindgen_realloc),p=K,b=ee(t,F.__wbindgen_malloc,F.__wbindgen_realloc),x=K;F.calculate_in_given_out(o,i,a,c,p,b,x);var n=he()[o/4+0],r=he()[o/4+1];return je(n,r)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(n,r)}};Ge.exports.calculate_liquidity_in=function(s,e,t){try{let o=F.__wbindgen_add_to_stack_pointer(-16),i=ee(s,F.__wbindgen_malloc,F.__wbindgen_realloc),a=K,c=ee(e,F.__wbindgen_malloc,F.__wbindgen_realloc),p=K,b=ee(t,F.__wbindgen_malloc,F.__wbindgen_realloc),x=K;F.calculate_liquidity_in(o,i,a,c,p,b,x);var n=he()[o/4+0],r=he()[o/4+1];return je(n,r)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(n,r)}};Ge.exports.calculate_shares=function(s,e,t){try{let o=F.__wbindgen_add_to_stack_pointer(-16),i=ee(s,F.__wbindgen_malloc,F.__wbindgen_realloc),a=K,c=ee(e,F.__wbindgen_malloc,F.__wbindgen_realloc),p=K,b=ee(t,F.__wbindgen_malloc,F.__wbindgen_realloc),x=K;F.calculate_shares(o,i,a,c,p,b,x);var n=he()[o/4+0],r=he()[o/4+1];return je(n,r)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(n,r)}};Ge.exports.calculate_liquidity_out_asset_a=function(s,e,t,n){try{let i=F.__wbindgen_add_to_stack_pointer(-16),a=ee(s,F.__wbindgen_malloc,F.__wbindgen_realloc),c=K,p=ee(e,F.__wbindgen_malloc,F.__wbindgen_realloc),b=K,x=ee(t,F.__wbindgen_malloc,F.__wbindgen_realloc),B=K,T=ee(n,F.__wbindgen_malloc,F.__wbindgen_realloc),k=K;F.calculate_liquidity_out_asset_a(i,a,c,p,b,x,B,T,k);var r=he()[i/4+0],o=he()[i/4+1];return je(r,o)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(r,o)}};Ge.exports.calculate_liquidity_out_asset_b=function(s,e,t,n){try{let i=F.__wbindgen_add_to_stack_pointer(-16),a=ee(s,F.__wbindgen_malloc,F.__wbindgen_realloc),c=K,p=ee(e,F.__wbindgen_malloc,F.__wbindgen_realloc),b=K,x=ee(t,F.__wbindgen_malloc,F.__wbindgen_realloc),B=K,T=ee(n,F.__wbindgen_malloc,F.__wbindgen_realloc),k=K;F.calculate_liquidity_out_asset_b(i,a,c,p,b,x,B,T,k);var r=he()[i/4+0],o=he()[i/4+1];return je(r,o)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(r,o)}};var Vr=require("path").join(__dirname,"hydra_dx_wasm_bg.wasm"),Qr=require("fs").readFileSync(Vr),Zr=new WebAssembly.Module(Qr),Kr=new WebAssembly.Instance(Zr,Yr);F=Kr.exports;Ge.exports.__wasm=F});var to={};ar(to,{AssetClient:()=>ot,AssetNotFound:()=>fn,BASILISK_PARACHAIN_ID:()=>Sr,BalanceClient:()=>it,BigNumber:()=>Le,CachingPoolService:()=>Zt,DECIMAL_PLACES:()=>Nn,DENOMINATOR:()=>Lt,HYDRADX_OMNIPOOL_ADDRESS:()=>ht,HYDRADX_PARACHAIN_ID:()=>yr,HYDRADX_SS58_PREFIX:()=>nt,INFINITY:()=>_r,LbpMath:()=>Ne,LbpPool:()=>Ye,ONE:()=>ve,OmniMath:()=>ae,OmniPool:()=>$e,PoolConfigNotFound:()=>gn,PoolError:()=>et,PoolFactory:()=>_t,PoolNotFound:()=>wt,PoolService:()=>at,PoolType:()=>Se,ProviderConfigNotFound:()=>wn,RUNTIME_DECIMALS:()=>tt,RouteNotFound:()=>st,Router:()=>Ke,SYSTEM_ASSET_DECIMALS:()=>Pr,SYSTEM_ASSET_ID:()=>We,StableMath:()=>Pe,StableSwap:()=>Je,StorageConfigNotFound:()=>hn,SubscriptionNotSupported:()=>bn,TRADEABLE_DEFAULT:()=>Rt,TradeRouter:()=>St,TradeType:()=>mn,XykMath:()=>He,XykPool:()=>Ve,ZERO:()=>$,bnum:()=>C,buildRoute:()=>zt,calculateBuyFee:()=>On,calculateDiffToAvg:()=>eo,calculateDiffToRef:()=>dt,calculateSellFee:()=>vn,scale:()=>_e});module.exports=lr(to);var It=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 cr=4,mt=class{isNotVisited(e,t){let n=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(n=!1)}),n}findPaths(e,t,n){let r=[],o=new It,i=[];for(i.push([t,""]),o.enqueue(i);o.size()>0;){let a=o.dequeue();if(a==null||a.length>cr)return r;let c=a[a.length-1];(n===null||c[0]===n)&&r.push(a),e.get(c[0])?.forEach(b=>{if(this.isNotVisited(b,a)){let x=[...a];x.push(b),o.enqueue(x)}})}return r}buildAndPopulateGraph(e,t){let n=new Map;for(let r of e)n.set(parseInt(r),[]);for(let[r,o,i]of t){let a=parseInt(o),c=parseInt(i);n.get(a)?.push([c,r])}return n}};function un(s){let e={};for(let t of s){let n=t.tokens.length;for(let r=0;r<n;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let o=0;o<n;o++){if(r==o)continue;let i=[t.address,t.tokens[r].id,t.tokens[o].id];e[t.tokens[r].id].push(i)}}}return e}var gt=class{getProposals(e,t,n){let r=un(n),o=Object.keys(r),i=o.map(b=>r[b]).flat(),a=new mt,c=a.buildAndPopulateGraph(o,i),p=a.findPaths(c,parseInt(e),t?parseInt(t):null);return this.parsePaths(p)}parsePaths(e){let t=[];for(let n of e){let r=[];for(let o=0;o<n.length;o++){let i=n[o],a=n[o+1];if(a==null)break;r.push(this.toEdge(i,a))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ur=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,_n=Math.ceil,Ie=Math.floor,ye="[BigNumber Error] ",In=ye+"Number primitive has more than 15 significant digits: ",Fe=1e14,U=14,dn=9007199254740991,pn=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],ze=1e7,ue=1e9;function An(s){var e,t,n,r=v.prototype={constructor:v,toString:null,valueOf:null},o=new v(1),i=20,a=4,c=-7,p=21,b=-1e7,x=1e7,B=!1,T=1,k=0,L={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},E="0123456789abcdefghijklmnopqrstuvwxyz",M=!0;function v(l,_){var d,w,g,f,y,m,h,S,P=this;if(!(P instanceof v))return new v(l,_);if(_==null){if(l&&l._isBigNumber===!0){P.s=l.s,!l.c||l.e>x?P.c=P.e=null:l.e<b?P.c=[P.e=0]:(P.e=l.e,P.c=l.c.slice());return}if((m=typeof l=="number")&&l*0==0){if(P.s=1/l<0?(l=-l,-1):1,l===~~l){for(f=0,y=l;y>=10;y/=10,f++);f>x?P.c=P.e=null:(P.e=f,P.c=[l]);return}S=String(l)}else{if(!ur.test(S=String(l)))return n(P,S,m);P.s=S.charCodeAt(0)==45?(S=S.slice(1),-1):1}(f=S.indexOf("."))>-1&&(S=S.replace(".","")),(y=S.search(/e/i))>0?(f<0&&(f=y),f+=+S.slice(y+1),S=S.substring(0,y)):f<0&&(f=S.length)}else{if(ne(_,2,E.length,"Base"),_==10&&M)return P=new v(l),Q(P,i+P.e+1,a);if(S=String(l),m=typeof l=="number"){if(l*0!=0)return n(P,S,m,_);if(P.s=1/l<0?(S=S.slice(1),-1):1,v.DEBUG&&S.replace(/^0\.0*|\./,"").length>15)throw Error(In+l)}else P.s=S.charCodeAt(0)===45?(S=S.slice(1),-1):1;for(d=E.slice(0,_),f=y=0,h=S.length;y<h;y++)if(d.indexOf(w=S.charAt(y))<0){if(w=="."){if(y>f){f=h;continue}}else if(!g&&(S==S.toUpperCase()&&(S=S.toLowerCase())||S==S.toLowerCase()&&(S=S.toUpperCase()))){g=!0,y=-1,f=0;continue}return n(P,String(l),m,_)}m=!1,S=t(S,_,10,P.s),(f=S.indexOf("."))>-1?S=S.replace(".",""):f=S.length}for(y=0;S.charCodeAt(y)===48;y++);for(h=S.length;S.charCodeAt(--h)===48;);if(S=S.slice(y,++h)){if(h-=y,m&&v.DEBUG&&h>15&&(l>dn||l!==Ie(l)))throw Error(In+P.s*l);if((f=f-y-1)>x)P.c=P.e=null;else if(f<b)P.c=[P.e=0];else{if(P.e=f,P.c=[],y=(f+1)%U,f<0&&(y+=U),y<h){for(y&&P.c.push(+S.slice(0,y)),h-=U;y<h;)P.c.push(+S.slice(y,y+=U));y=U-(S=S.slice(y)).length}else y-=h;for(;y--;S+="0");P.c.push(+S)}}else P.c=[P.e=0]}v.clone=An,v.ROUND_UP=0,v.ROUND_DOWN=1,v.ROUND_CEIL=2,v.ROUND_FLOOR=3,v.ROUND_HALF_UP=4,v.ROUND_HALF_DOWN=5,v.ROUND_HALF_EVEN=6,v.ROUND_HALF_CEIL=7,v.ROUND_HALF_FLOOR=8,v.EUCLID=9,v.config=v.set=function(l){var _,d;if(l!=null)if(typeof l=="object"){if(l.hasOwnProperty(_="DECIMAL_PLACES")&&(d=l[_],ne(d,0,ue,_),i=d),l.hasOwnProperty(_="ROUNDING_MODE")&&(d=l[_],ne(d,0,8,_),a=d),l.hasOwnProperty(_="EXPONENTIAL_AT")&&(d=l[_],d&&d.pop?(ne(d[0],-ue,0,_),ne(d[1],0,ue,_),c=d[0],p=d[1]):(ne(d,-ue,ue,_),c=-(p=d<0?-d:d))),l.hasOwnProperty(_="RANGE"))if(d=l[_],d&&d.pop)ne(d[0],-ue,-1,_),ne(d[1],1,ue,_),b=d[0],x=d[1];else if(ne(d,-ue,ue,_),d)b=-(x=d<0?-d:d);else throw Error(ye+_+" cannot be zero: "+d);if(l.hasOwnProperty(_="CRYPTO"))if(d=l[_],d===!!d)if(d)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))B=d;else throw B=!d,Error(ye+"crypto unavailable");else B=d;else throw Error(ye+_+" not true or false: "+d);if(l.hasOwnProperty(_="MODULO_MODE")&&(d=l[_],ne(d,0,9,_),T=d),l.hasOwnProperty(_="POW_PRECISION")&&(d=l[_],ne(d,0,ue,_),k=d),l.hasOwnProperty(_="FORMAT"))if(d=l[_],typeof d=="object")L=d;else throw Error(ye+_+" not an object: "+d);if(l.hasOwnProperty(_="ALPHABET"))if(d=l[_],typeof d=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(d))M=d.slice(0,10)=="0123456789",E=d;else throw Error(ye+_+" invalid: "+d)}else throw Error(ye+"Object expected: "+l);return{DECIMAL_PLACES:i,ROUNDING_MODE:a,EXPONENTIAL_AT:[c,p],RANGE:[b,x],CRYPTO:B,MODULO_MODE:T,POW_PRECISION:k,FORMAT:L,ALPHABET:E}},v.isBigNumber=function(l){if(!l||l._isBigNumber!==!0)return!1;if(!v.DEBUG)return!0;var _,d,w=l.c,g=l.e,f=l.s;e:if({}.toString.call(w)=="[object Array]"){if((f===1||f===-1)&&g>=-ue&&g<=ue&&g===Ie(g)){if(w[0]===0){if(g===0&&w.length===1)return!0;break e}if(_=(g+1)%U,_<1&&(_+=U),String(w[0]).length==_){for(_=0;_<w.length;_++)if(d=w[_],d<0||d>=Fe||d!==Ie(d))break e;if(d!==0)return!0}}}else if(w===null&&g===null&&(f===null||f===1||f===-1))return!0;throw Error(ye+"Invalid BigNumber: "+l)},v.maximum=v.max=function(){return V(arguments,-1)},v.minimum=v.min=function(){return V(arguments,1)},v.random=function(){var l=9007199254740992,_=Math.random()*l&2097151?function(){return Ie(Math.random()*l)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(d){var w,g,f,y,m,h=0,S=[],P=new v(o);if(d==null?d=i:ne(d,0,ue),y=_n(d/U),B)if(crypto.getRandomValues){for(w=crypto.getRandomValues(new Uint32Array(y*=2));h<y;)m=w[h]*131072+(w[h+1]>>>11),m>=9e15?(g=crypto.getRandomValues(new Uint32Array(2)),w[h]=g[0],w[h+1]=g[1]):(S.push(m%1e14),h+=2);h=y/2}else if(crypto.randomBytes){for(w=crypto.randomBytes(y*=7);h<y;)m=(w[h]&31)*281474976710656+w[h+1]*1099511627776+w[h+2]*4294967296+w[h+3]*16777216+(w[h+4]<<16)+(w[h+5]<<8)+w[h+6],m>=9e15?crypto.randomBytes(7).copy(w,h):(S.push(m%1e14),h+=7);h=y/7}else throw B=!1,Error(ye+"crypto unavailable");if(!B)for(;h<y;)m=_(),m<9e15&&(S[h++]=m%1e14);for(y=S[--h],d%=U,y&&d&&(m=pn[U-d],S[h]=Ie(y/m)*m);S[h]===0;S.pop(),h--);if(h<0)S=[f=0];else{for(f=-1;S[0]===0;S.splice(0,1),f-=U);for(h=1,m=S[0];m>=10;m/=10,h++);h<U&&(f-=U-h)}return P.e=f,P.c=S,P}}(),v.sum=function(){for(var l=1,_=arguments,d=new v(_[0]);l<_.length;)d=d.plus(_[l++]);return d},t=function(){var l="0123456789";function _(d,w,g,f){for(var y,m=[0],h,S=0,P=d.length;S<P;){for(h=m.length;h--;m[h]*=w);for(m[0]+=f.indexOf(d.charAt(S++)),y=0;y<m.length;y++)m[y]>g-1&&(m[y+1]==null&&(m[y+1]=0),m[y+1]+=m[y]/g|0,m[y]%=g)}return m.reverse()}return function(d,w,g,f,y){var m,h,S,P,I,D,q,J,ie=d.indexOf("."),ce=i,Y=a;for(ie>=0&&(P=k,k=0,d=d.replace(".",""),J=new v(w),D=J.pow(d.length-ie),k=P,J.c=_(Ue(Be(D.c),D.e,"0"),10,g,l),J.e=J.c.length),q=_(d,w,g,y?(m=E,l):(m=l,E)),S=P=q.length;q[--P]==0;q.pop());if(!q[0])return m.charAt(0);if(ie<0?--S:(D.c=q,D.e=S,D.s=f,D=e(D,J,ce,Y,g),q=D.c,I=D.r,S=D.e),h=S+ce+1,ie=q[h],P=g/2,I=I||h<0||q[h+1]!=null,I=Y<4?(ie!=null||I)&&(Y==0||Y==(D.s<0?3:2)):ie>P||ie==P&&(Y==4||I||Y==6&&q[h-1]&1||Y==(D.s<0?8:7)),h<1||!q[0])d=I?Ue(m.charAt(1),-ce,m.charAt(0)):m.charAt(0);else{if(q.length=h,I)for(--g;++q[--h]>g;)q[h]=0,h||(++S,q=[1].concat(q));for(P=q.length;!q[--P];);for(ie=0,d="";ie<=P;d+=m.charAt(q[ie++]));d=Ue(d,S,m.charAt(0))}return d}}(),e=function(){function l(w,g,f){var y,m,h,S,P=0,I=w.length,D=g%ze,q=g/ze|0;for(w=w.slice();I--;)h=w[I]%ze,S=w[I]/ze|0,y=q*h+S*D,m=D*h+y%ze*ze+P,P=(m/f|0)+(y/ze|0)+q*S,w[I]=m%f;return P&&(w=[P].concat(w)),w}function _(w,g,f,y){var m,h;if(f!=y)h=f>y?1:-1;else for(m=h=0;m<f;m++)if(w[m]!=g[m]){h=w[m]>g[m]?1:-1;break}return h}function d(w,g,f,y){for(var m=0;f--;)w[f]-=m,m=w[f]<g[f]?1:0,w[f]=m*y+w[f]-g[f];for(;!w[0]&&w.length>1;w.splice(0,1));}return function(w,g,f,y,m){var h,S,P,I,D,q,J,ie,ce,Y,Z,ge,xt,ln,cn,Re,pt,Oe=w.s==g.s?1:-1,we=w.c,se=g.c;if(!we||!we[0]||!se||!se[0])return new v(!w.s||!g.s||(we?se&&we[0]==se[0]:!se)?NaN:we&&we[0]==0||!se?Oe*0:Oe/0);for(ie=new v(Oe),ce=ie.c=[],S=w.e-g.e,Oe=f+S+1,m||(m=Fe,S=Ae(w.e/U)-Ae(g.e/U),Oe=Oe/U|0),P=0;se[P]==(we[P]||0);P++);if(se[P]>(we[P]||0)&&S--,Oe<0)ce.push(1),I=!0;else{for(ln=we.length,Re=se.length,P=0,Oe+=2,D=Ie(m/(se[0]+1)),D>1&&(se=l(se,D,m),we=l(we,D,m),Re=se.length,ln=we.length),xt=Re,Y=we.slice(0,Re),Z=Y.length;Z<Re;Y[Z++]=0);pt=se.slice(),pt=[0].concat(pt),cn=se[0],se[1]>=m/2&&cn++;do{if(D=0,h=_(se,Y,Re,Z),h<0){if(ge=Y[0],Re!=Z&&(ge=ge*m+(Y[1]||0)),D=Ie(ge/cn),D>1)for(D>=m&&(D=m-1),q=l(se,D,m),J=q.length,Z=Y.length;_(q,Y,J,Z)==1;)D--,d(q,Re<J?pt:se,J,m),J=q.length,h=1;else D==0&&(h=D=1),q=se.slice(),J=q.length;if(J<Z&&(q=[0].concat(q)),d(Y,q,Z,m),Z=Y.length,h==-1)for(;_(se,Y,Re,Z)<1;)D++,d(Y,Re<Z?pt:se,Z,m),Z=Y.length}else h===0&&(D++,Y=[0]);ce[P++]=D,Y[0]?Y[Z++]=we[xt]||0:(Y=[we[xt]],Z=1)}while((xt++<ln||Y[0]!=null)&&Oe--);I=Y[0]!=null,ce[0]||ce.splice(0,1)}if(m==Fe){for(P=1,Oe=ce[0];Oe>=10;Oe/=10,P++);Q(ie,f+(ie.e=P+S*U-1)+1,y,I)}else ie.e=S,ie.r=+I;return ie}}();function G(l,_,d,w){var g,f,y,m,h;if(d==null?d=a:ne(d,0,8),!l.c)return l.toString();if(g=l.c[0],y=l.e,_==null)h=Be(l.c),h=w==1||w==2&&(y<=c||y>=p)?Nt(h,y):Ue(h,y,"0");else if(l=Q(new v(l),_,d),f=l.e,h=Be(l.c),m=h.length,w==1||w==2&&(_<=f||f<=c)){for(;m<_;h+="0",m++);h=Nt(h,f)}else if(_-=y,h=Ue(h,f,"0"),f+1>m){if(--_>0)for(h+=".";_--;h+="0");}else if(_+=f-m,_>0)for(f+1==m&&(h+=".");_--;h+="0");return l.s<0&&g?"-"+h:h}function V(l,_){for(var d,w,g=1,f=new v(l[0]);g<l.length;g++)w=new v(l[g]),(!w.s||(d=Qe(f,w))===_||d===0&&f.s===_)&&(f=w);return f}function te(l,_,d){for(var w=1,g=_.length;!_[--g];_.pop());for(g=_[0];g>=10;g/=10,w++);return(d=w+d*U-1)>x?l.c=l.e=null:d<b?l.c=[l.e=0]:(l.e=d,l.c=_),l}n=function(){var l=/^(-?)0([xbo])(?=\w[\w.]*$)/i,_=/^([^.]+)\.$/,d=/^\.([^.]+)$/,w=/^-?(Infinity|NaN)$/,g=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(f,y,m,h){var S,P=m?y:y.replace(g,"");if(w.test(P))f.s=isNaN(P)?null:P<0?-1:1;else{if(!m&&(P=P.replace(l,function(I,D,q){return S=(q=q.toLowerCase())=="x"?16:q=="b"?2:8,!h||h==S?D:I}),h&&(S=h,P=P.replace(_,"$1").replace(d,"0.$1")),y!=P))return new v(P,S);if(v.DEBUG)throw Error(ye+"Not a"+(h?" base "+h:"")+" number: "+y);f.s=null}f.c=f.e=null}}();function Q(l,_,d,w){var g,f,y,m,h,S,P,I=l.c,D=pn;if(I){e:{for(g=1,m=I[0];m>=10;m/=10,g++);if(f=_-g,f<0)f+=U,y=_,h=I[S=0],P=Ie(h/D[g-y-1]%10);else if(S=_n((f+1)/U),S>=I.length)if(w){for(;I.length<=S;I.push(0));h=P=0,g=1,f%=U,y=f-U+1}else break e;else{for(h=m=I[S],g=1;m>=10;m/=10,g++);f%=U,y=f-U+g,P=y<0?0:Ie(h/D[g-y-1]%10)}if(w=w||_<0||I[S+1]!=null||(y<0?h:h%D[g-y-1]),w=d<4?(P||w)&&(d==0||d==(l.s<0?3:2)):P>5||P==5&&(d==4||w||d==6&&(f>0?y>0?h/D[g-y]:0:I[S-1])%10&1||d==(l.s<0?8:7)),_<1||!I[0])return I.length=0,w?(_-=l.e+1,I[0]=D[(U-_%U)%U],l.e=-_||0):I[0]=l.e=0,l;if(f==0?(I.length=S,m=1,S--):(I.length=S+1,m=D[U-f],I[S]=y>0?Ie(h/D[g-y]%D[y])*m:0),w)for(;;)if(S==0){for(f=1,y=I[0];y>=10;y/=10,f++);for(y=I[0]+=m,m=1;y>=10;y/=10,m++);f!=m&&(l.e++,I[0]==Fe&&(I[0]=1));break}else{if(I[S]+=m,I[S]!=Fe)break;I[S--]=0,m=1}for(f=I.length;I[--f]===0;I.pop());}l.e>x?l.c=l.e=null:l.e<b&&(l.c=[l.e=0])}return l}function H(l){var _,d=l.e;return d===null?l.toString():(_=Be(l.c),_=d<=c||d>=p?Nt(_,d):Ue(_,d,"0"),l.s<0?"-"+_:_)}return r.absoluteValue=r.abs=function(){var l=new v(this);return l.s<0&&(l.s=1),l},r.comparedTo=function(l,_){return Qe(this,new v(l,_))},r.decimalPlaces=r.dp=function(l,_){var d,w,g,f=this;if(l!=null)return ne(l,0,ue),_==null?_=a:ne(_,0,8),Q(new v(f),l+f.e+1,_);if(!(d=f.c))return null;if(w=((g=d.length-1)-Ae(this.e/U))*U,g=d[g])for(;g%10==0;g/=10,w--);return w<0&&(w=0),w},r.dividedBy=r.div=function(l,_){return e(this,new v(l,_),i,a)},r.dividedToIntegerBy=r.idiv=function(l,_){return e(this,new v(l,_),0,1)},r.exponentiatedBy=r.pow=function(l,_){var d,w,g,f,y,m,h,S,P,I=this;if(l=new v(l),l.c&&!l.isInteger())throw Error(ye+"Exponent not an integer: "+H(l));if(_!=null&&(_=new v(_)),m=l.e>14,!I.c||!I.c[0]||I.c[0]==1&&!I.e&&I.c.length==1||!l.c||!l.c[0])return P=new v(Math.pow(+H(I),m?l.s*(2-At(l)):+H(l))),_?P.mod(_):P;if(h=l.s<0,_){if(_.c?!_.c[0]:!_.s)return new v(NaN);w=!h&&I.isInteger()&&_.isInteger(),w&&(I=I.mod(_))}else{if(l.e>9&&(I.e>0||I.e<-1||(I.e==0?I.c[0]>1||m&&I.c[1]>=24e7:I.c[0]<8e13||m&&I.c[0]<=9999975e7)))return f=I.s<0&&At(l)?-0:0,I.e>-1&&(f=1/f),new v(h?1/f:f);k&&(f=_n(k/U+2))}for(m?(d=new v(.5),h&&(l.s=1),S=At(l)):(g=Math.abs(+H(l)),S=g%2),P=new v(o);;){if(S){if(P=P.times(I),!P.c)break;f?P.c.length>f&&(P.c.length=f):w&&(P=P.mod(_))}if(g){if(g=Ie(g/2),g===0)break;S=g%2}else if(l=l.times(d),Q(l,l.e+1,1),l.e>14)S=At(l);else{if(g=+H(l),g===0)break;S=g%2}I=I.times(I),f?I.c&&I.c.length>f&&(I.c.length=f):w&&(I=I.mod(_))}return w?P:(h&&(P=o.div(P)),_?P.mod(_):f?Q(P,k,a,y):P)},r.integerValue=function(l){var _=new v(this);return l==null?l=a:ne(l,0,8),Q(_,_.e+1,l)},r.isEqualTo=r.eq=function(l,_){return Qe(this,new v(l,_))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(l,_){return Qe(this,new v(l,_))>0},r.isGreaterThanOrEqualTo=r.gte=function(l,_){return(_=Qe(this,new v(l,_)))===1||_===0},r.isInteger=function(){return!!this.c&&Ae(this.e/U)>this.c.length-2},r.isLessThan=r.lt=function(l,_){return Qe(this,new v(l,_))<0},r.isLessThanOrEqualTo=r.lte=function(l,_){return(_=Qe(this,new v(l,_)))===-1||_===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(l,_){var d,w,g,f,y=this,m=y.s;if(l=new v(l,_),_=l.s,!m||!_)return new v(NaN);if(m!=_)return l.s=-_,y.plus(l);var h=y.e/U,S=l.e/U,P=y.c,I=l.c;if(!h||!S){if(!P||!I)return P?(l.s=-_,l):new v(I?y:NaN);if(!P[0]||!I[0])return I[0]?(l.s=-_,l):new v(P[0]?y:a==3?-0:0)}if(h=Ae(h),S=Ae(S),P=P.slice(),m=h-S){for((f=m<0)?(m=-m,g=P):(S=h,g=I),g.reverse(),_=m;_--;g.push(0));g.reverse()}else for(w=(f=(m=P.length)<(_=I.length))?m:_,m=_=0;_<w;_++)if(P[_]!=I[_]){f=P[_]<I[_];break}if(f&&(g=P,P=I,I=g,l.s=-l.s),_=(w=I.length)-(d=P.length),_>0)for(;_--;P[d++]=0);for(_=Fe-1;w>m;){if(P[--w]<I[w]){for(d=w;d&&!P[--d];P[d]=_);--P[d],P[w]+=Fe}P[w]-=I[w]}for(;P[0]==0;P.splice(0,1),--S);return P[0]?te(l,P,S):(l.s=a==3?-1:1,l.c=[l.e=0],l)},r.modulo=r.mod=function(l,_){var d,w,g=this;return l=new v(l,_),!g.c||!l.s||l.c&&!l.c[0]?new v(NaN):!l.c||g.c&&!g.c[0]?new v(g):(T==9?(w=l.s,l.s=1,d=e(g,l,0,3),l.s=w,d.s*=w):d=e(g,l,0,T),l=g.minus(d.times(l)),!l.c[0]&&T==1&&(l.s=g.s),l)},r.multipliedBy=r.times=function(l,_){var d,w,g,f,y,m,h,S,P,I,D,q,J,ie,ce,Y=this,Z=Y.c,ge=(l=new v(l,_)).c;if(!Z||!ge||!Z[0]||!ge[0])return!Y.s||!l.s||Z&&!Z[0]&&!ge||ge&&!ge[0]&&!Z?l.c=l.e=l.s=null:(l.s*=Y.s,!Z||!ge?l.c=l.e=null:(l.c=[0],l.e=0)),l;for(w=Ae(Y.e/U)+Ae(l.e/U),l.s*=Y.s,h=Z.length,I=ge.length,h<I&&(J=Z,Z=ge,ge=J,g=h,h=I,I=g),g=h+I,J=[];g--;J.push(0));for(ie=Fe,ce=ze,g=I;--g>=0;){for(d=0,D=ge[g]%ce,q=ge[g]/ce|0,y=h,f=g+y;f>g;)S=Z[--y]%ce,P=Z[y]/ce|0,m=q*S+P*D,S=D*S+m%ce*ce+J[f]+d,d=(S/ie|0)+(m/ce|0)+q*P,J[f--]=S%ie;J[f]=d}return d?++w:J.splice(0,1),te(l,J,w)},r.negated=function(){var l=new v(this);return l.s=-l.s||null,l},r.plus=function(l,_){var d,w=this,g=w.s;if(l=new v(l,_),_=l.s,!g||!_)return new v(NaN);if(g!=_)return l.s=-_,w.minus(l);var f=w.e/U,y=l.e/U,m=w.c,h=l.c;if(!f||!y){if(!m||!h)return new v(g/0);if(!m[0]||!h[0])return h[0]?l:new v(m[0]?w:g*0)}if(f=Ae(f),y=Ae(y),m=m.slice(),g=f-y){for(g>0?(y=f,d=h):(g=-g,d=m),d.reverse();g--;d.push(0));d.reverse()}for(g=m.length,_=h.length,g-_<0&&(d=h,h=m,m=d,_=g),g=0;_;)g=(m[--_]=m[_]+h[_]+g)/Fe|0,m[_]=Fe===m[_]?0:m[_]%Fe;return g&&(m=[g].concat(m),++y),te(l,m,y)},r.precision=r.sd=function(l,_){var d,w,g,f=this;if(l!=null&&l!==!!l)return ne(l,1,ue),_==null?_=a:ne(_,0,8),Q(new v(f),l,_);if(!(d=f.c))return null;if(g=d.length-1,w=g*U+1,g=d[g]){for(;g%10==0;g/=10,w--);for(g=d[0];g>=10;g/=10,w++);}return l&&f.e+1>w&&(w=f.e+1),w},r.shiftedBy=function(l){return ne(l,-dn,dn),this.times("1e"+l)},r.squareRoot=r.sqrt=function(){var l,_,d,w,g,f=this,y=f.c,m=f.s,h=f.e,S=i+4,P=new v("0.5");if(m!==1||!y||!y[0])return new v(!m||m<0&&(!y||y[0])?NaN:y?f:1/0);if(m=Math.sqrt(+H(f)),m==0||m==1/0?(_=Be(y),(_.length+h)%2==0&&(_+="0"),m=Math.sqrt(+_),h=Ae((h+1)/2)-(h<0||h%2),m==1/0?_="5e"+h:(_=m.toExponential(),_=_.slice(0,_.indexOf("e")+1)+h),d=new v(_)):d=new v(m+""),d.c[0]){for(h=d.e,m=h+S,m<3&&(m=0);;)if(g=d,d=P.times(g.plus(e(f,g,S,1))),Be(g.c).slice(0,m)===(_=Be(d.c)).slice(0,m))if(d.e<h&&--m,_=_.slice(m-3,m+1),_=="9999"||!w&&_=="4999"){if(!w&&(Q(g,g.e+i+2,0),g.times(g).eq(f))){d=g;break}S+=4,m+=4,w=1}else{(!+_||!+_.slice(1)&&_.charAt(0)=="5")&&(Q(d,d.e+i+2,1),l=!d.times(d).eq(f));break}}return Q(d,d.e+i+1,a,l)},r.toExponential=function(l,_){return l!=null&&(ne(l,0,ue),l++),G(this,l,_,1)},r.toFixed=function(l,_){return l!=null&&(ne(l,0,ue),l=l+this.e+1),G(this,l,_)},r.toFormat=function(l,_,d){var w,g=this;if(d==null)l!=null&&_&&typeof _=="object"?(d=_,_=null):l&&typeof l=="object"?(d=l,l=_=null):d=L;else if(typeof d!="object")throw Error(ye+"Argument not an object: "+d);if(w=g.toFixed(l,_),g.c){var f,y=w.split("."),m=+d.groupSize,h=+d.secondaryGroupSize,S=d.groupSeparator||"",P=y[0],I=y[1],D=g.s<0,q=D?P.slice(1):P,J=q.length;if(h&&(f=m,m=h,h=f,J-=f),m>0&&J>0){for(f=J%m||m,P=q.substr(0,f);f<J;f+=m)P+=S+q.substr(f,m);h>0&&(P+=S+q.slice(f)),D&&(P="-"+P)}w=I?P+(d.decimalSeparator||"")+((h=+d.fractionGroupSize)?I.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(d.fractionGroupSeparator||"")):I):P}return(d.prefix||"")+w+(d.suffix||"")},r.toFraction=function(l){var _,d,w,g,f,y,m,h,S,P,I,D,q=this,J=q.c;if(l!=null&&(m=new v(l),!m.isInteger()&&(m.c||m.s!==1)||m.lt(o)))throw Error(ye+"Argument "+(m.isInteger()?"out of range: ":"not an integer: ")+H(m));if(!J)return new v(q);for(_=new v(o),S=d=new v(o),w=h=new v(o),D=Be(J),f=_.e=D.length-q.e-1,_.c[0]=pn[(y=f%U)<0?U+y:y],l=!l||m.comparedTo(_)>0?f>0?_:S:m,y=x,x=1/0,m=new v(D),h.c[0]=0;P=e(m,_,0,1),g=d.plus(P.times(w)),g.comparedTo(l)!=1;)d=w,w=g,S=h.plus(P.times(g=S)),h=g,_=m.minus(P.times(g=_)),m=g;return g=e(l.minus(d),w,0,1),h=h.plus(g.times(S)),d=d.plus(g.times(w)),h.s=S.s=q.s,f=f*2,I=e(S,w,f,a).minus(q).abs().comparedTo(e(h,d,f,a).minus(q).abs())<1?[S,w]:[h,d],x=y,I},r.toNumber=function(){return+H(this)},r.toPrecision=function(l,_){return l!=null&&ne(l,1,ue),G(this,l,_,2)},r.toString=function(l){var _,d=this,w=d.s,g=d.e;return g===null?w?(_="Infinity",w<0&&(_="-"+_)):_="NaN":(l==null?_=g<=c||g>=p?Nt(Be(d.c),g):Ue(Be(d.c),g,"0"):l===10&&M?(d=Q(new v(d),i+g+1,a),_=Ue(Be(d.c),d.e,"0")):(ne(l,2,E.length,"Base"),_=t(Ue(Be(d.c),g,"0"),10,l,w,!0)),w<0&&d.c[0]&&(_="-"+_)),_},r.valueOf=r.toJSON=function(){return H(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,s!=null&&v.set(s),v}function Ae(s){var e=s|0;return s>0||s===e?e:e-1}function Be(s){for(var e,t,n=1,r=s.length,o=s[0]+"";n<r;){for(e=s[n++]+"",t=U-e.length;t--;e="0"+e);o+=e}for(r=o.length;o.charCodeAt(--r)===48;);return o.slice(0,r+1||1)}function Qe(s,e){var t,n,r=s.c,o=e.c,i=s.s,a=e.s,c=s.e,p=e.e;if(!i||!a)return null;if(t=r&&!r[0],n=o&&!o[0],t||n)return t?n?0:-a:i;if(i!=a)return i;if(t=i<0,n=c==p,!r||!o)return n?0:!r^t?1:-1;if(!n)return c>p^t?1:-1;for(a=(c=r.length)<(p=o.length)?c:p,i=0;i<a;i++)if(r[i]!=o[i])return r[i]>o[i]^t?1:-1;return c==p?0:c>p^t?1:-1}function ne(s,e,t,n){if(s<e||s>t||s!==Ie(s))throw Error(ye+(n||"Argument")+(typeof s=="number"?s<e||s>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(s))}function At(s){var e=s.c.length-1;return Ae(s.e/U)==e&&s.c[e]%2!=0}function Nt(s,e){return(s.length>1?s.charAt(0)+"."+s.slice(1):s)+(e<0?"e":"e+")+e}function Ue(s,e,t){var n,r;if(e<0){for(r=t+".";++e;r+=t);s=r+s}else if(n=s.length,++e>n){for(r=t,e-=n;--e;r+=t);s+=r}else e<n&&(s=s.slice(0,e)+"."+s.slice(e));return s}var Le=An();var Nn=12;Le.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Nn});var $=C(0),ve=C(1),_r=C("Infinity");function _e(s,e){let t=new Le(e.toString()),n=new Le(10).pow(t);return s.times(n)}function C(s){return new Le(s.toString())}var Se=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(Se||{}),et=(o=>(o.UnknownError="UnknownError",o.InsufficientTradingAmount="InsufficientTradingAmount",o.MaxInRatioExceeded="MaxInRatioExceeded",o.MaxOutRatioExceeded="MaxOutRatioExceeded",o.TradeNotAllowed="TradeNotAllowed",o))(et||{}),mn=(t=>(t.Buy="Buy",t.Sell="Sell",t))(mn||{});var De=Bt(Fn()),Ne=class{static getSpotPrice(e,t,n,r,o){return(0,De.get_spot_price)(e,t,n,r,o)}static calculateInGivenOut(e,t,n,r,o){return(0,De.calculate_in_given_out)(e,t,n,r,o)}static calculateOutGivenIn(e,t,n,r,o){return(0,De.calculate_out_given_in)(e,t,n,r,o)}static calculateLinearWeights(e,t,n,r,o){return(0,De.calculate_linear_weights)(e,t,n,r,o)}static calculatePoolTradeFee(e,t,n){return(0,De.calculate_pool_trade_fee)(e,t,n)}};var kn=require("@polkadot/util-crypto"),En=require("@polkadot/util"),tt=18,Rt=15,We="0",Pr=12,yr=2034,nt=63,Sr=2090,Lt=1e3,ht=(0,kn.encodeAddress)((0,En.stringToU8a)("modlomnipool".padEnd(32,"\0")),nt);function Rn(s,e){let t;return JSON.stringify(s,(n,r)=>(r&&r[e]&&(t=r),r)),t}var Ao=require("@polkadot/types/lookup");var No=require("@polkadot/api-base/types/consts");var To=require("@polkadot/api-base/types/errors");var Fo=require("@polkadot/api-base/types/events");var ko=require("@polkadot/api-base/types/storage");var Eo=require("@polkadot/api-base/types/submittable");var Ro=require("@polkadot/rpc-core/types/jsonrpc");var Lo=require("@polkadot/api-base/types/calls");var Wo=require("@polkadot/types/types/registry");var $o=require("@polkadot/types/lookup");var Jo=require("@polkadot/api-base/types/consts");var jo=require("@polkadot/api-base/types/errors");var Vo=require("@polkadot/api-base/types/events");var Qo=require("@polkadot/api-base/types/storage");var Zo=require("@polkadot/api-base/types/submittable");var Ko=require("@polkadot/rpc-core/types/jsonrpc");var ei=require("@polkadot/api-base/types/calls");var li=require("@polkadot/types/types/registry");var rt=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var ot=class extends rt{SUPPORTED_TYPES=["StableSwap","Bond","Token"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},n])=>[t.toString(),n.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},n])=>[t.toString(),n.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},n])=>[t.toString(),n.unwrap()]))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},n])=>[t.toString(),n.unwrap()]))}catch{return new Map([])}}getTokens(e,t,n,r){if(e==We){let x=this.api.consts.balances.existentialDeposit;return{id:We,name:this.chainToken,symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",existentialDeposit:x.toString()}}let{name:o,assetType:i,existentialDeposit:a}=t,{symbol:c,decimals:p}=n.get(e),b=r?r.get(e):void 0;return{id:e,name:o.toHuman(),symbol:c.toHuman(),decimals:p.toNumber(),icon:c.toHuman(),type:i.toHuman(),origin:b&&this.parseLocation(b),existentialDeposit:a.toString()}}getBonds(e,t,n,r){let[o,i]=r,{assetType:a,existentialDeposit:c}=t,{symbol:p,decimals:b}=this.getTokens(o.toString(),t,n),x=i.toNumber(),B=new Intl.DateTimeFormat("en-GB"),T=[p,"Bond",B.format(x)].join(" ");return{id:e,name:T,symbol:p+"b",decimals:b,icon:p,type:a.toString(),existentialDeposit:c.toString()}}getShares(e,t,n,r){let{assets:o}=r,{name:i,assetType:a,existentialDeposit:c}=t,b=o.map(T=>T.toString()).map(T=>{let{symbol:k}=this.getTokens(T,t,n);return[T,k]}),x=Object.fromEntries(b),B=Object.values(x);return{id:e,name:B.join(", "),symbol:i.length>0?i.toHuman():e,decimals:18,icon:B.join("/"),type:a.toString(),existentialDeposit:c.toString(),meta:x}}async getOnChainAssets(){let[e,t,n,r,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.metadataQuery(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery()]);return e.filter(([i,a])=>this.isSupportedType(a.unwrap())).map(([{args:[i]},a])=>{let c=a.unwrap(),{assetType:p}=c;switch(p.toString()){case"Bond":let b=o.get(i.toString());return this.getBonds(i.toString(),c,t,b);case"StableSwap":let x=r.get(i.toString());return this.getShares(i.toString(),c,t,x);default:return this.getTokens(i.toString(),c,t,n)}})}isSupportedType(e){return this.SUPPORTED_TYPES.includes(e.assetType.toString())}parseLocation(e){if(e){let t=Rn(e.toJSON(),"parachain");return t&&t.parachain}else return}};var it=class extends rt{constructor(e){super(e)}async getBalance(e,t){return t===We?await this.getSystemBalance(e):await this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:n,reserved:r,frozen:o}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:n,feeFrozen:r,frozen:o})}async subscribeBalance(e,t,n){let r=t.filter(o=>o!==We).map(o=>[e,o]);return this.api.query.tokens.accounts.multi(r,o=>{o.forEach(({free:i,reserved:a,frozen:c},p)=>{let b=this.calculateFreeBalance({free:i,feeFrozen:a,frozen:c}),x=r[p][1];n(x,b)})})}async subscribeTokenBalance(e,t,n){let r=t.filter(o=>o!==We).map(o=>[e,o]);return this.api.query.tokens.accounts.multi(r,o=>{o.forEach((i,a)=>{let c=this.calculateFreeBalance(i),p=r[a][1];n(p,c)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:n})=>t(We,this.calculateFreeBalance(n)))}calculateFreeBalance(e){let{free:t,miscFrozen:n,feeFrozen:r,frozen:o}=e,i=new Le(t),a=new Le(n||o),c=new Le(r||0),p=a.gt(c)?a:c;return i.minus(p)}};var Ce=class extends it{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async n=>{let r=[await this.subscribePoolChange(n),await this.subscribeTokensPoolBalance(n),await this.subscribeSystemPoolBalance(n)];if(this.hasShareAsset(n)){let o=await this.subscribeSharePoolBalance(n);r.push(o)}return this.subscribeLog(n),r});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,n)=>t.id!==n))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance(ht,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(n,r){let o=e.tokens.findIndex(i=>i.id==n);o>=0&&t(e,n)&&(e.tokens[o].balance=r.toString())}}};var Mt=class extends Ce{MAX_FINAL_WEIGHT=_e(C(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:n}=t.unwrap(),r=e.filter(([o,i])=>this.isActivePool(i.unwrap(),n)).map(async([{args:[o]},i])=>{let a=i.unwrap(),c=o.toString(),p=await this.getPoolDelta(c,a,n.toString());return this.poolsData.set(o.toString(),a),{address:c,type:"Lbp",fee:a.fee.toJSON(),...p,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let n=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:n.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:n}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,n)){let i=await this.getPoolDelta(e.address,r,n.toString());e.tokens=i.tokens??e.tokens,e.repayFeeApply=i.repayFeeApply??e.repayFeeApply}else{let i=this.pools.findIndex(a=>a.address==e.address);this.pools.splice(i,1)}})}async getPoolDelta(e,t,n){let{start:r,end:o,assets:i,initialWeight:a,finalWeight:c,repayTarget:p,feeCollector:b}=t,x=Ne.calculateLinearWeights(r.toString(),o.toString(),a.toString(),c.toString(),n),[B,T]=i,k=B.toString(),L=C(x),E=T.toString(),M=this.MAX_FINAL_WEIGHT.minus(C(L)),[v,G,V]=await Promise.all([this.isRepayFeeApplied(k,p.toString(),b.toString()),this.getBalance(e,k),this.getBalance(e,E)]);return{repayFeeApply:v,tokens:[{id:k,weight:L,balance:G.toString()},{id:E,weight:M,balance:V.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let n=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=n&&t.toNumber()<r}async isRepayFeeApplied(e,t,n){let r=C(t);if(r.isZero())return!1;try{return(await this.getBalance(e,n)).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(),n=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}};var Ln=require("@polkadot/util-crypto"),Mn=require("@polkadot/util");function me(s,e){return s.shiftedBy(-1*e).toString()}function Te(s){return s[0]/s[1]*100}function xe(s){return s[0]/s[1]}function ke(s){return[s/Lt,Lt]}var Dt=class extends Ce{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[n,r,o]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),i=n.map(async([{args:[c]},p])=>{let{hubReserve:b,shares:x,tradable:B}=p.unwrap(),T=await this.getBalance(t,c.toString());return{id:c.toString(),hubReserves:C(b.toString()),shares:C(x.toString()),tradeable:B.bits.toNumber(),balance:T.toString()}}),a=await Promise.all(i);return a.push({id:e,tradeable:r.bits.toNumber(),balance:o.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:a,...this.getPoolLimits()}]}async getPoolFees(e,t){let n=await this.api.query.dynamicFees.assetFee(e),r=this.api.consts.dynamicFees.assetFeeParameters,o=this.api.consts.dynamicFees.protocolFeeParameters,i=r.minFee.toNumber()+o.minFee.toNumber(),a=r.maxFee.toNumber()+o.maxFee.toNumber();if(n.isSome){let{assetFee:c,protocolFee:p}=n.unwrap();return{assetFee:ke(c.toNumber()),protocolFee:ke(p.toNumber()),min:ke(i),max:ke(a)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:ke(i),max:ke(a)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(n=>n.id);return this.api.query.omnipool.assets.multi(t,n=>{e.tokens=n.map((r,o)=>{let i=e.tokens[o];if(r.isNone)return i;let a=r.unwrap();return this.updateTokenState(i,a)})})}updateTokenState(e,t){let{hubReserve:n,shares:r,tradable:o}=t;return{...e,hubReserves:C(n.toString()),shares:C(r.toString()),tradeable:o.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return ke(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return ke(t)}getPoolId(){return(0,Ln.encodeAddress)((0,Mn.stringToU8a)("modlomnipool".padEnd(32,"\0")),nt)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),n=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}};var Ct=class extends Ce{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[n]},r])=>{let o=n.toString(),[i,a]=r.unwrap(),[c,p]=await Promise.all([this.getBalance(o,i.toString()),this.getBalance(o,a.toString())]);return{address:o,type:"Xyk",tokens:[{id:i.toString(),balance:c.toString()},{id:a.toString(),balance:p.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),n=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}};var Wt=require("@polkadot/util-crypto");var pe=Bt(Cn()),Pe=class{static getPoolAddress(e){return(0,pe.pool_account_name)(e)}static calculateAmplification(e,t,n,r,o){return(0,pe.calculate_amplification)(e,t,n,r,o)}static calculateInGivenOut(e,t,n,r,o,i){return(0,pe.calculate_in_given_out)(e,t,n,r,o,i)}static calculateAddOneAsset(e,t,n,r,o,i){return(0,pe.calculate_add_one_asset)(e,t,n,r,o,i)}static calculateSharesForAmount(e,t,n,r,o,i){return(0,pe.calculate_shares_for_amount)(e,t,n,r,o,i)}static calculateOutGivenIn(e,t,n,r,o,i){return(0,pe.calculate_out_given_in)(e,t,n,r,o,i)}static calculateLiquidityOutOneAsset(e,t,n,r,o,i){return(0,pe.calculate_liquidity_out_one_asset)(e,t,n,r,o,i)}static calculateShares(e,t,n,r,o){return(0,pe.calculate_shares)(e,t,n,r,o)}static calculatePoolTradeFee(e,t,n){return(0,pe.calculate_pool_trade_fee)(e,t,n)}};var Ut=class extends Ce{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()]),n=t.toNumber(),r=e.map(async([{args:[o]},i])=>{let a=i.unwrap(),c=o.toString(),p=this.getPoolAddress(c),[b,x]=await Promise.all([this.getPoolDelta(c,a,n.toString()),this.getPoolTokens(p,c,a)]);return this.stablePools.set(p,a),{address:p,id:c,type:"Stableswap",fee:ke(a.fee.toNumber()),tokens:x,...b,...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 n=t.toNumber(),r=this.stablePools.get(e.address),o=await this.getPoolDelta(e.id,r,n.toString());e={...e,...o}})}async getPoolDelta(e,t,n){let{initialAmplification:r,finalAmplification:o,initialBlock:i,finalBlock:a}=t,c=Pe.calculateAmplification(r.toString(),o.toString(),i.toString(),a.toString(),n),p=await this.api.query.tokens.totalIssuance(e);return{amplification:c,totalIssuance:p.toString()}}async getPoolTokens(e,t,n){let{assets:r}=n,o=r.map(async c=>{let[p,b]=await Promise.all([this.api.query.stableswap.assetTradability(t,c.toString()),this.getBalance(e,c.toString())]);return{id:c.toString(),tradeable:p.bits.toNumber(),balance:b.toString()}}),i=await Promise.all(o),a=await this.api.query.omnipool.assets(t);if(a.isSome){let{tradable:c}=a.unwrap(),p=await this.getBalance(ht,t);i.push({id:t,tradeable:c.bits.toNumber(),balance:p.toString()})}return i}getPoolAddress(e){let t=Number(e),n=Pe.getPoolAddress(t);return(0,Wt.encodeAddress)((0,Wt.blake2AsHex)(n),nt)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function zt(s){return s.map(({assetIn:e,assetOut:t,pool:n,poolId:r})=>n==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:n,assetIn:e,assetOut:t})}var wt=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},gn=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},st=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},fn=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},hn=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},bn=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},wn=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var at=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new ot(this.api),this.xykClient=new Ct(this.api),this.omniClient=new Dt(this.api),this.lbpClient=new Mt(this.api),this.stableClient=new Ut(this.api)}async getPools(e){if(this.onChainAssetsLoaded||(this.onChainAssets=await this.assetClient.getOnChainAssets(),this.onChainAssetsLoaded=!0),e.length==0){let i=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(a=>a.isSupported()).map(a=>a.getPools()))).flat();return this.withMetadata(i)}let t=[];e.forEach(o=>{switch(o){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break;case"Stableswap":t.push(this.stableClient.getPools());break}});let r=(await Promise.all(t)).flat();return this.withMetadata(r)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(n=>[n.id,n]));return e.map(n=>{let r=n.tokens.map(o=>{let i=t.get(o.id);return{...o,...i}});return{...n,tokens:r}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new wt(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,n,r,o){let i;this.isDirectOmnipoolTrade(o)?i=this.api.tx.omnipool.buy(t,e,n.toFixed(),r.toFixed()):i=this.api.tx.router.buy(e,t,n.toFixed(),r.toFixed(),zt(o));let a=()=>i;return{hex:i.toHex(),name:"RouterBuy",get:a}}buildSellTx(e,t,n,r,o){let i;this.isDirectOmnipoolTrade(o)?i=this.api.tx.omnipool.sell(e,t,n.toFixed(),r.toFixed()):i=this.api.tx.router.sell(e,t,n.toFixed(),r.toFixed(),zt(o));let a=()=>i;return{hex:i.toHex(),name:"RouterSell",get:a}}};var Pt=(s,e)=>s===e?0:s==null?e==null?0:-1:e==null?s==null?0:1:typeof s.compare=="function"?s.compare(e):typeof e.compare=="function"?-e.compare(s):s<e?-1:s>e?1:0;var Xt=(s,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(s(t)+e(t))}};var kr=Xt(()=>"illegal argument(s)"),qn=s=>{throw new kr(s)};var Er=Xt(()=>"index out of bounds"),Pn=s=>{throw new Er(s)},Yt=(s,e,t)=>(s<e||s>=t)&&Pn(s);var Gn=23283064365386963e-26,$t=class{float(e=1){return this.int()*Gn*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Gn-.5)*2*e}normMinMax(e,t){let n=this.minmax(e,t);return this.float()<.5?n:-n}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let n=(t|0)-e;return n?e+this.int()%n:e}minmaxUint(e,t){e>>>=0;let n=(t>>>0)-e;return n?e+this.int()%n:e}};var yn=Math.random,Sn=class extends $t{int(){return yn()*4294967296>>>0}float(e=1){return yn()*e}norm(e=1){return(yn()-.5)*2*e}},Hn=new Sn;var Un=s=>s!=null&&typeof s!="function"&&s.length!==void 0;var Wn=Object.getPrototypeOf({}),Jt="function",zn="string",lt=(s,e)=>{let t;if(s===e)return!0;if(s!=null){if(typeof s.equiv===Jt)return s.equiv(e)}else return s==e;if(e!=null){if(typeof e.equiv===Jt)return e.equiv(s)}else return s==e;return typeof s===zn||typeof e===zn?!1:(t=Object.getPrototypeOf(s),(t==null||t===Wn)&&(t=Object.getPrototypeOf(e),t==null||t===Wn)?Dr(s,e):typeof s!==Jt&&s.length!==void 0&&typeof e!==Jt&&e.length!==void 0?Rr(s,e):s instanceof Set&&e instanceof Set?Lr(s,e):s instanceof Map&&e instanceof Map?Mr(s,e):s instanceof Date&&e instanceof Date?s.getTime()===e.getTime():s instanceof RegExp&&e instanceof RegExp?s.toString()===e.toString():s!==s&&e!==e)},Rr=(s,e,t=lt)=>{let n=s.length;if(n===e.length)for(;n-- >0&&t(s[n],e[n]););return n<0},Lr=(s,e,t=lt)=>s.size===e.size&&t([...s.keys()].sort(),[...e.keys()].sort()),Mr=(s,e,t=lt)=>s.size===e.size&&t([...s].sort(),[...e].sort()),Dr=(s,e,t=lt)=>{if(Object.keys(s).length!==Object.keys(e).length)return!1;for(let n in s)if(!e.hasOwnProperty(n)||!t(s[n],e[n]))return!1;return!0};var Xn=(s,e)=>s!=null&&typeof s[e]=="function";var Yn=s=>Xn(s,"xform")?s.xform():s;var jt=Symbol(),xn=()=>{};var $n=s=>s!=null&&typeof s[Symbol.iterator]=="function";var Vt=class{value;constructor(e){this.value=e}deref(){return this.value}};var Qt=s=>s instanceof Vt;var Jn=s=>s instanceof Vt?s.deref():s;function*jn(s,e){let t=Yn(s)([xn,xn,(n,r)=>r])[2];for(let n of e){let r=t(jt,n);if(Qt(r)){r=Jn(r.deref()),r!==jt&&(yield r);return}r!==jt&&(yield r)}}var Vn=(s,e)=>[s[0],s[1],e];function yt(s,e){return $n(e)?jn(yt(s),e):t=>{let n=t[2];return Vn(t,(r,o)=>n(r,s(o)))}}var ct=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Qn("next",this._head)}reverseIterator(){return Qn("prev",this.tail)}clear(){this.release()}compare(e,t=Pt){let n=this._length;if(n<e._length)return-1;if(n>e._length)return 1;if(n===0)return 0;{let r=this._head,o=e._head,i=0;for(;n-- >0&&i===0;)i=t(r.value,o.value),r=r.next,o=o.next;return i}}concat(...e){let t=this.copy();for(let n of e)t.into(n);return t}equiv(e){if(!(e instanceof ct||Un(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),n=this._head;for(let r=this._length;r-- >0;){if(!lt(n.value,t.next().value))return!1;n=n.next}return!0}filter(e){let t=this.empty();return this.traverse(n=>(e(n.value)&&t.append(n.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||Pt;for(let n=this._head,r=this._length;r-- >0;){if(t(e,n.value)<=0)return this.insertBefore(n,e);n=n.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let n=this.nthCell(e);return n?n.value:t}nthCellUnsafe(e){let t,n;for(e<=this._length>>>1?(t=this._head,n="next"):(t=this.tail,n="prev",e=this._length-e-1);e-- >0&&t;)t=t[n];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let n=this._head;for(let r=this._length;r-- >0&&!Qt(t);)t=e(t,n.value),n=n.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let n=this._length;n-- >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,n=(this._length>>>1)+(this._length&1);for(;e&&t&&n>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,n--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let n=this.nthCell(e);return!n&&Pn(e),n.value=t,n}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let n=e.value;e.value=t.value,t.value=n}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,n){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==n);return r}_map(e,t){return this.traverse(n=>(e.append(t(n.value)),!0)),e}};function*Qn(s,e){for(;e;)yield e.value,e=e[s]}var qe=class extends ct{_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 qe(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 qe}insertAfter(e,t){let n={value:t,next:e.next,prev:e};return e.next?e.next.prev=n:this._tail=n,e.next=n,this._length++,n}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(Yt(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let n={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=n:this._head=n,e.prev=n,this._length++,n}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(Yt(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new qe,e)}nth(e,t){let n=this.nthCell(e);return n?n.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 n=this.nthCell(e),r=this.nthCell(t-1),o=i=>({first(){return i.value},next(){return i!==r&&i.next?o(i.next):void 0}});return n?o(n):void 0}shuffle(e,t=Hn){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let n=this._head;for(;n;){let r=n.next;t.probability(.5)?this.asHead(n):this.asTail(n),n=r}}return this}slice(e=0,t=this.length){let n=e<0?e+this._length:e,r=t<0?t+this._length:t;(n<0||r<0)&&qn("invalid indices: ${from} / ${to}");let o=new qe,i=this.nthCell(n);for(;i&&++n<=r;)o.push(i.value),i=i.next;return o}sort(e=Pt){if(!this._length)return this;let t=1;for(;;){let n=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;n;){r++;let o=n,i=0;for(let c=0;c<t&&(i++,o=o.next,!!o);c++);let a=t;for(;i>0||a>0&&o;){let c;i===0?(c=o,o=o.next,a--):!o||a===0||e(n.value,o.value)<=0?(c=n,n=n.next,i--):(c=o,o=o.next,a--),this._tail?this._tail.next=c:this._head=c,c.prev=this._tail,this._tail=c}n=o}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,n){let r;typeof e=="number"?(e<0&&(e+=this._length),Yt(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let o=new qe;if(t>0)for(;r&&t-- >0;)this.remove(r),o.push(r.value),r=r.next;else r&&(r=r.next);if(n)if(r)for(let i of n)this.insertBefore(r,i);else for(let i of n)this.push(i);return o}};var ut=class{map;items;opts;_size;constructor(e,t){let n=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=n.map(),this.items=new qe,this._size=0,this.opts=n,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return yt(e=>[e.k,e],this.items)}keys(){return yt(e=>e.k,this.items)}values(){return yt(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new ut(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 n=this.map.get(e);return n?this.resetEntry(n):t}set(e,t){let n=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e);return this._size+=Math.max(0,n-(r?r.value.s:0)),this.ensureSize()&&this.doSetEntry(r,e,t,n),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let n=this.map.get(e);return n?Promise.resolve(this.resetEntry(n)):t().then(r=>this.set(e,r))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,n=this.opts.maxlen;for(;this._size>t||this.length>=n;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e&&e(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,n,r){e?(e.value.v=n,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:n,s:r}),this.map.set(t,this.items.tail))}};var Zt=class extends at{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new ut(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let n=[t.address,e].join("-");if(this.feeCache.has(n))return this.feeCache.get(n);{let o=await super.getPoolFees(e,t);return this.feeCache.set(n,o),o}}async destroy(){console.log(`Destroying pool cache!
2
- Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Ye=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Ye(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,n,r,o,i,a){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=o,this.fee=i,this.repayFeeApply=a}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(c=>[c.id,c])),r=n.get(e),o=n.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(o==null)throw new Error("Pool does not contain tokenOut");let i=C(r.balance),a=C(o.balance);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:a,decimalsIn:r.decimals,decimalsOut:o.decimals,weightIn:r.weight,weightOut:o.weight}}validateAndBuy(e,t,n){let r=this.tokens[0].id,o=[];t.isLessThan(this.minTradingLimit)&&o.push("InsufficientTradingAmount");let i=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(i)&&o.push("MaxOutRatioExceeded"),r===e.assetOut){let a=this.calculateTradeFee(t,n),c=Te(this.repayFeeApply?n.repayFee:n.exchangeFee),p=t.plus(a),b=this.calculateInGivenOut(e,p),x=e.balanceIn.div(this.maxInRatio);return b.isGreaterThan(x)&&o.push("MaxInRatioExceeded"),{amountIn:b,calculatedIn:b,amountOut:t,feePct:c,errors:o}}else{let a=this.calculateInGivenOut(e,t),c=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(c)&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:t,feePct:0,errors:o}}}validateAndSell(e,t,n){let r=this.tokens[0].id,o=[];t.isLessThan(this.minTradingLimit)&&o.push("InsufficientTradingAmount");let i=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(i)&&o.push("MaxInRatioExceeded"),r===e.assetIn){let a=this.calculateOutGivenIn(e,t),c=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(c)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:a,feePct:0,errors:o}}else{let a=this.calculateOutGivenIn(e,t),c=this.calculateTradeFee(a,n),p=Te(this.repayFeeApply?n.repayFee:n.exchangeFee),b=a.minus(c),x=e.balanceOut.div(this.maxOutRatio);return b.isGreaterThan(x)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:b,feePct:p,errors:o}}}calculateInGivenOut(e,t){let n=Ne.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=C(n);return r.isNegative()?$:r}calculateOutGivenIn(e,t){let n=Ne.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=C(n);return r.isNegative()?$:r}spotPriceInGivenOut(e){let t=Ne.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),_e(ve,e.decimalsOut).toString());return C(t)}spotPriceOutGivenIn(e){let t=Ne.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),_e(ve,e.decimalsIn).toString());return C(t)}calculateTradeFee(e,t){let n=Ne.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return C(n)}};var X=Bt(Kn()),ae=class{static calculateSpotPrice(e,t,n,r){return(0,X.calculate_spot_price)(e,t,n,r)}static calculateLrnaSpotPrice(e,t){return(0,X.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,n,r,o,i,a,c,p){return(0,X.calculate_in_given_out)(e,t,n,r,o,i,a,c,p)}static calculateLrnaInGivenOut(e,t,n,r,o){return(0,X.calculate_lrna_in_given_out)(e,t,n,r,o)}static calculateOutGivenIn(e,t,n,r,o,i,a,c,p){return(0,X.calculate_out_given_in)(e,t,n,r,o,i,a,c,p)}static calculateOutGivenLrnaIn(e,t,n,r,o){return(0,X.calculate_out_given_lrna_in)(e,t,n,r,o)}static calculatePoolTradeFee(e,t,n){return(0,X.calculate_pool_trade_fee)(e,t,n)}static calculateShares(e,t,n,r){return(0,X.calculate_shares)(e,t,n,r)}static calculateLiquidityOut(e,t,n,r,o,i,a,c){return(0,X.calculate_liquidity_out)(e,t,n,r,o,i,a,c)}static calculateLiquidityLRNAOut(e,t,n,r,o,i,a,c){return(0,X.calculate_liquidity_lrna_out)(e,t,n,r,o,i,a,c)}static calculateCapDifference(e,t,n,r){return(0,X.calculate_cap_difference)(e,t,n,r)}static verifyAssetCap(e,t,n,r){return(0,X.verify_asset_cap)(e,t,n,r)}static calculateLimitHubIn(e,t,n,r){return(0,X.calculate_liquidity_hub_in)(e,t,n,r)}static isSellAllowed(e){return(0,X.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,X.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,X.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,X.is_remove_liquidity_allowed)(e)}};var $e=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new $e(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,n,r,o,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=o,this.hubAssetId=i}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let n=new Map(this.tokens.map(c=>[c.id,c])),r=n.get(e),o=n.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(o==null)throw new Error("Pool does not contain tokenOut");let i=C(r.balance),a=C(o.balance);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:o.hubReserves,sharesIn:r.shares,sharesOut:o.shares,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:i,balanceOut:a,tradeableIn:r.tradeable,tradeableOut:o.tradeable}}validateAndBuy(e,t,n){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,n),i=o.minus(r),a=r===$?$:i.div(r).multipliedBy(100).decimalPlaces(2),c=[],p=ae.isSellAllowed(e.tradeableIn),b=ae.isBuyAllowed(e.tradeableOut);(!p||!b)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let x=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(x)&&c.push("MaxOutRatioExceeded");let B=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(B)&&c.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:a.toNumber(),errors:c}}validateAndSell(e,t,n){let r=this.calculateOutGivenIn(e,t),o=this.calculateOutGivenIn(e,t,n),a=r.minus(o).div(r).multipliedBy(100).decimalPlaces(2),c=[],p=ae.isSellAllowed(e.tradeableIn),b=ae.isBuyAllowed(e.tradeableOut);(!p||!b)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let x=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(x)&&c.push("MaxInRatioExceeded");let B=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(B)&&c.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:a.toNumber(),errors:c}}calculateInGivenOut(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,n);let r=ae.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),n?xe(n.assetFee).toString():$.toString(),n?xe(n.protocolFee).toString():$.toString()),o=C(r);return o.isNegative()?$:o}calculateLrnaInGivenOut(e,t,n){let r=ae.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),n?xe(n.assetFee).toString():$.toString()),o=C(r);return o.isNegative()?$:o}calculateOutGivenIn(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,n);let r=ae.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),n?xe(n.assetFee).toString():$.toString(),n?xe(n.protocolFee).toString():$.toString()),o=C(r);return o.isNegative()?$:o}calculateOutGivenLrnaIn(e,t,n){let r=ae.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),n?xe(n.assetFee).toString():$.toString()),o=C(r);return o.isNegative()?$:o}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=ae.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return C(t).shiftedBy(-1*(tt-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=ae.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return C(t).shiftedBy(-1*(tt-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=ae.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return C(t).shiftedBy(-1*(tt-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=ae.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return C(t).shiftedBy(-1*(tt-e.decimalsIn)).decimalPlaces(0,1)}};var Je=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Je(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,n,r,o,i,a,c,p){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=o,this.amplification=i,this.id=a,this.fee=c,this.totalIssuance=p}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(c=>[c.id,c])),r=n.get(e),o=n.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(o==null)throw new Error("Pool does not contain tokenOut");let i=C(r.balance),a=C(o.balance);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:a,decimalsIn:r.decimals,decimalsOut:o.decimals,tradeableIn:this.id===e?Rt:r.tradeable,tradeableOut:this.id===t?Rt:o.tradeable}}validateAndBuy(e,t,n){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,n),i=Te(n.fee),a=[],c=ae.isSellAllowed(e.tradeableIn),p=ae.isBuyAllowed(e.tradeableOut);return(!c||!p)&&a.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&a.push("InsufficientTradingAmount"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,n){let r=this.calculateOutGivenIn(e,t),o=this.calculateOutGivenIn(e,t,n),i=Te(n.fee),a=[],c=ae.isSellAllowed(e.tradeableIn),p=ae.isBuyAllowed(e.tradeableOut);return(!c||!p)&&a.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:i,errors:a}}calculateIn(e,t,n){let r=Pe.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,n?xe(n.fee).toString():$.toString()),o=C(r);return o.isNegative()?$:o}calculateAddOneAsset(e,t,n){let r=Pe.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,n?xe(n.fee).toString():$.toString()),o=C(r);return o.isNegative()?$:o}calculateSharesForAmount(e,t,n){let r=Pe.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,n?xe(n.fee).toString():$.toString()),o=C(r);return o.isNegative()?$:o}calculateInGivenOut(e,t,n){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,n):e.assetIn==this.id?this.calculateSharesForAmount(e,t,n):this.calculateIn(e,t,n)}spotPriceInGivenOut(e){let t=_e(ve,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,n){let r=Pe.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,n?xe(n.fee).toString():$.toString()),o=C(r);return o.isNegative()?$:o}calculateWithdrawOneAsset(e,t,n){let r=Pe.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,n?xe(n.fee).toString():$.toString()),o=C(r);return o.isNegative()?$:o}calculateShares(e,t,n){let r=Pe.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,n?xe(n.fee).toString():$.toString()),o=C(r);return o.isNegative()?$:o}calculateOutGivenIn(e,t,n){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,n):e.assetOut==this.id?this.calculateShares(e,t,n):this.calculateOut(e,t,n)}spotPriceOutGivenIn(e){let t=_e(ve,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 n=Pe.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return C(n)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:n,decimals:r})=>({asset_id:Number(t),amount:n,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let n={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([n])}};var be=Bt(tr()),He=class{static getSpotPrice(e,t,n){return(0,be.get_spot_price)(e,t,n)}static calculateInGivenOut(e,t,n){return(0,be.calculate_in_given_out)(e,t,n)}static calculateOutGivenIn(e,t,n){return(0,be.calculate_out_given_in)(e,t,n)}static calculatePoolTradeFee(e,t,n){return(0,be.calculate_pool_trade_fee)(e,t,n)}static calculateLiquidityIn(e,t,n){return(0,be.calculate_liquidity_in)(e,t,n)}static calculateShares(e,t,n){return(0,be.calculate_shares)(e,t,n)}static calculateLiquidityOutAssetA(e,t,n,r){return(0,be.calculate_liquidity_out_asset_a)(e,t,n,r)}static calculateLiquidityOutAssetB(e,t,n,r){return(0,be.calculate_liquidity_out_asset_b)(e,t,n,r)}};var Ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,n,r,o){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=o}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(c=>[c.id,c])),r=n.get(e),o=n.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(o==null)throw new Error("Pool does not contain tokenOut");let i=C(r.balance),a=C(o.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:i,balanceOut:a}}validateAndBuy(e,t,n){let r=this.calculateInGivenOut(e,t),o=this.calculateTradeFee(r,n),i=Te(n.exchangeFee),a=r.plus(o),c=[];t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let p=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(p)&&c.push("MaxOutRatioExceeded");let b=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(b)&&c.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:r,amountOut:t,feePct:i,errors:c}}validateAndSell(e,t,n){let r=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(r,n),i=Te(n.exchangeFee),a=r.minus(o),c=[];t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount");let p=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(p)&&c.push("MaxInRatioExceeded");let b=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(b)&&c.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:a,feePct:i,errors:c}}calculateInGivenOut(e,t){let n=He.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=C(n);return r.isNegative()?$:r}calculateOutGivenIn(e,t){let n=He.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=C(n);return r.isNegative()?$:r}spotPriceInGivenOut(e){let t=He.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),_e(ve,e.decimalsOut).toString());return C(t)}spotPriceOutGivenIn(e){let t=He.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),_e(ve,e.decimalsIn).toString());return C(t)}calculateTradeFee(e,t){let n=He.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return C(n)}};var _t=class{static get(e){switch(e.type){case"Xyk":return Ve.fromPool(e);case"Omnipool":return $e.fromPool(e);case"Lbp":return Ye.fromPool(e);case"Stableswap":return Je.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Ke=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new gt,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:n,poolsMap:r}=await this.validateToken(e,t),i=this.getPaths(e,null,r,t).map(a=>a[a.length-1].assetOut);return this.toAssets([...new Set(i)],n)}async getAllPaths(e,t){let n=await this.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,n);return this.getPaths(e,t,r,n)}async getAssets(e){let t=e.map(n=>n.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,existentialDeposit:r.existentialDeposit,origin:r.origin,meta:r.meta}))).flat();return new Map(t.map(n=>[n.id,n]))}getPaths(e,t,n,r){return this.routeSuggester.getProposals(e,t,r).filter(a=>this.validPath(a,n)).map(a=>this.toHops(a,n))}async validateTokenPair(e,t,n){let r=await this.getAssets(n);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 o=this.getPoolMap(n);return{assets:r,poolsMap:o}}async validateToken(e,t){let n=await this.getAssets(t);if(n.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:n,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,_t.get(t)]))}validPath(e,t){return e.length>0&&e.map(n=>this.validEdge(n,t)).reduce((n,r)=>n&&r)}validEdge([e,t,n],r){return r.get(e)?.validatePair(t,n)||!1}toHops(e,t){return e.map(([n,r,o])=>{let i=t.get(n);return{poolAddress:n,poolId:i?.id,pool:i?.type,assetIn:r,assetOut:o}})}toAssets(e,t){return e.map(n=>t.get(n))}};function eo(s,e){return s.minus(e).abs().div(s.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function dt(s,e){return s.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function vn(s,e){return ve.minus(e.div(s)).multipliedBy(100).decimalPlaces(2)}function On(s,e){return e.div(s).minus(ve).multipliedBy(100).decimalPlaces(2)}var St=class extends Ke{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((n,r)=>{let o=n[n.length-1].amountOut,i=r[r.length-1].amountOut;return o.isGreaterThan(i)?-1:1});return t.find(n=>n.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(n=>n.tradeFeeRange).length>0){let n=e.map(o=>o.tradeFeeRange?.[0]??o.tradeFeePct).reduce((o,i)=>o+i),r=e.map(o=>o.tradeFeeRange?.[1]??o.tradeFeePct).reduce((o,i)=>o+i);return[n,r]}}getPoolFeeRange(e){let t=e.min?Te(e.min):void 0,n=e.max?Te(e.max):void 0;if(t&&n)return[t,n]}async getBestSell(e,t,n){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:o}=await super.validateTokenPair(e,t,r),i=super.getPaths(e,t,o,r);if(i.length===0)throw new st(e,t);let a=i.map(async H=>await this.toSellSwaps(n,H,o)),c=await Promise.all(a),p=this.findBestSellRoute(c),b=p[0],x=p[p.length-1],B=this.isDirectTrade(p),T=p.map(H=>H.spotPrice.shiftedBy(-1*H.assetOutDecimals)).reduce((H,l)=>H.multipliedBy(l)),k=_e(T,x.assetOutDecimals).decimalPlaces(0,1),L=b.amountIn.shiftedBy(-1*b.assetInDecimals).multipliedBy(k),E=dt(x.calculatedOut,L),M=B?x.calculatedOut:this.calculateDelta0Y(b.amountIn,p,o),v=x.amountOut,G=B?x.tradeFeePct:vn(M,v).toNumber(),V=M.minus(v),te=this.getRouteFeeRange(p),Q=H=>this.poolService.buildSellTx(e,t,b.amountIn,H,p.map(l=>l));return{type:"Sell",amountIn:b.amountIn,amountOut:x.amountOut,spotPrice:k,tradeFee:V,tradeFeePct:G,tradeFeeRange:te,priceImpactPct:E.toNumber(),swaps:p,toTx:Q,toHuman(){return{type:"Sell",amountIn:me(b.amountIn,b.assetInDecimals),amountOut:me(x.amountOut,x.assetOutDecimals),spotPrice:me(k,x.assetOutDecimals),tradeFee:me(V,x.assetOutDecimals),tradeFeePct:G,tradeFeeRange:te,priceImpactPct:E.toNumber(),swaps:p.map(H=>H.toHuman())}}}}calculateDelta0Y(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let c=a.parsePair(i.assetIn,i.assetOut),p;o>0?p=r[o-1]:p=e;let b=a.calculateOutGivenIn(c,p);r.push(b)}return r[r.length-1]}async toSellSwaps(e,t,n){let r=[];for(let o=0;o<t.length;o++){let i=t[o],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let c=a.parsePair(i.assetIn,i.assetOut),p;o>0?p=r[o-1].amountOut:p=_e(C(e),c.decimalsIn).decimalPlaces(0,1);let b=await this.poolService.getPoolFees(c.assetOut,a),{amountOut:x,calculatedOut:B,feePct:T,errors:k}=a.validateAndSell(c,p,b),L=this.getPoolFeeRange(b),E=a.spotPriceOutGivenIn(c),M=p.shiftedBy(-1*c.decimalsIn).multipliedBy(E),v=dt(B,M);r.push({...i,assetInDecimals:c.decimalsIn,assetOutDecimals:c.decimalsOut,amountIn:p,calculatedOut:B,amountOut:x,spotPrice:E,tradeFeePct:T,tradeFeeRange:L,priceImpactPct:v.toNumber(),errors:k,toHuman(){return{...i,amountIn:me(p,c.decimalsIn),calculatedOut:me(B,c.decimalsOut),amountOut:me(x,c.decimalsOut),spotPrice:me(E,c.decimalsOut),tradeFeePct:T,tradeFeeRange:L,priceImpactPct:v.toNumber(),errors:k}}})}return r}async getBestSpotPrice(e,t){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,n),o=super.getPaths(e,t,r,n);if(o.length===0)return Promise.resolve(void 0);let i=o.map(async B=>await this.toSellSwaps("1",B,r)),a=await Promise.all(i),c=this.findBestSellRoute(a),p=c.map(B=>B.spotPrice.shiftedBy(-1*B.assetOutDecimals)).reduce((B,T)=>B.multipliedBy(T)),b=c[c.length-1].assetOutDecimals;return{amount:_e(p,b).decimalPlaces(0,1),decimals:b}}findBestBuyRoute(e){let t=e.sort((n,r)=>{let o=n[0].amountIn,i=r[0].amountIn;return o.isGreaterThan(i)?1:-1});return t.find(n=>n.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,n){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:o}=await super.validateTokenPair(e,t,r),i=super.getPaths(e,t,o,r);if(i.length===0)throw new st(e,t);let a=i.map(async H=>await this.toBuySwaps(n,H,o)),c=await Promise.all(a),p=this.findBestBuyRoute(c),b=p[p.length-1],x=p[0],B=this.isDirectTrade(p),T=p.map(H=>H.spotPrice.shiftedBy(-1*H.assetInDecimals)).reduce((H,l)=>H.multipliedBy(l)),k=_e(T,x.assetInDecimals).decimalPlaces(0,1),L=b.amountOut.shiftedBy(-1*b.assetOutDecimals).multipliedBy(k),E;x.calculatedIn.isZero()?E=-100:E=dt(L,x.calculatedIn).toNumber();let M=B?x.calculatedIn:this.calculateDelta0X(b.amountOut,p,o),v=x.amountIn,G=B?x.tradeFeePct:On(M,v),V=v.minus(M),te=this.getRouteFeeRange(p),Q=H=>this.poolService.buildBuyTx(e,t,b.amountOut,H,p.map(l=>l));return{type:"Buy",amountOut:b.amountOut,amountIn:x.amountIn,spotPrice:k,tradeFee:V,tradeFeePct:G,tradeFeeRange:te,priceImpactPct:E,swaps:p,toTx:Q,toHuman(){return{type:"Buy",amountOut:me(b.amountOut,b.assetOutDecimals),amountIn:me(x.amountIn,x.assetInDecimals),spotPrice:me(k,x.assetInDecimals),tradeFee:me(V,x.assetInDecimals),tradeFeePct:G,tradeFeeRange:te,priceImpactPct:E,swaps:p.map(H=>H.toHuman())}}}}calculateDelta0X(e,t,n){let r=[];for(let o=t.length-1;o>=0;o--){let i=t[o],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let c=a.parsePair(i.assetIn,i.assetOut),p;o==t.length-1?p=e:p=r[0];let b=a.calculateInGivenOut(c,p);r.unshift(b)}return r[0]}async toBuySwaps(e,t,n){let r=[];for(let o=t.length-1;o>=0;o--){let i=t[o],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let c=a.parsePair(i.assetIn,i.assetOut),p;o==t.length-1?p=_e(C(e),c.decimalsOut).decimalPlaces(0,1):p=r[0].amountIn;let b=await this.poolService.getPoolFees(c.assetIn,a),{amountIn:x,calculatedIn:B,feePct:T,errors:k}=a.validateAndBuy(c,p,b),L=this.getPoolFeeRange(b),E=a.spotPriceInGivenOut(c),M=p.shiftedBy(-1*c.decimalsOut).multipliedBy(E),v;B.isZero()?v=-100:v=dt(M,B).toNumber(),r.unshift({...i,assetInDecimals:c.decimalsIn,assetOutDecimals:c.decimalsOut,amountOut:p,calculatedIn:B,amountIn:x,spotPrice:E,tradeFeePct:T,tradeFeeRange:L,priceImpactPct:v,errors:k,toHuman(){return{...i,amountOut:me(p,c.decimalsOut),calculatedIn:me(B,c.decimalsIn),amountIn:me(x,c.decimalsIn),spotPrice:me(E,c.decimalsIn),tradeFeePct:T,tradeFeeRange:L,priceImpactPct:v,errors:k}}})}return r}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,scale});
1
+ "use strict";var yt=Object.defineProperty;var ir=Object.getOwnPropertyDescriptor;var nr=Object.getOwnPropertyNames;var or=Object.prototype.hasOwnProperty;var ar=(u,e)=>{for(var t in e)yt(u,t,{get:e[t],enumerable:!0})},lr=(u,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of nr(e))!or.call(u,s)&&s!==t&&yt(u,s,{get:()=>e[s],enumerable:!(r=ir(e,s))||r.enumerable});return u};var ur=u=>lr(yt({},"__esModule",{value:!0}),u);var wr={};ar(wr,{AssetClient:()=>Le,AssetNotFound:()=>Nt,BASILISK_PARACHAIN_ID:()=>dr,BalanceClient:()=>Me,BigNumber:()=>fe,CachingPoolService:()=>Pt,DECIMAL_PLACES:()=>Gt,DENOMINATOR:()=>st,HYDRADX_OMNIPOOL_ADDRESS:()=>$e,HYDRADX_PARACHAIN_ID:()=>gr,HYDRADX_SS58_PREFIX:()=>Ee,INFINITY:()=>mr,LbpMath:()=>ue,LbpPool:()=>ve,ONE:()=>ie,OmniMath:()=>U,OmniPool:()=>Ie,PoolConfigNotFound:()=>It,PoolError:()=>_e,PoolFactory:()=>Ue,PoolNotFound:()=>Je,PoolService:()=>Ce,PoolType:()=>re,ProviderConfigNotFound:()=>Ft,RUNTIME_DECIMALS:()=>Re,RouteNotFound:()=>De,Router:()=>Fe,SYSTEM_ASSET_DECIMALS:()=>hr,SYSTEM_ASSET_ID:()=>we,StableMath:()=>ee,StableSwap:()=>Ne,StorageConfigNotFound:()=>At,SubscriptionNotSupported:()=>Tt,TRADEABLE_DEFAULT:()=>rt,TradeRouter:()=>Ve,TradeType:()=>vt,XykMath:()=>ye,XykPool:()=>Ae,ZERO:()=>R,bnum:()=>I,buildRoute:()=>ut,calculateBuyFee:()=>Mt,calculateDiffToAvg:()=>Or,calculateDiffToRef:()=>ze,calculateSellFee:()=>Lt,scale:()=>W});module.exports=ur(wr);var Ke=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var cr=4,We=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new Ke,l=[];for(l.push([t,""]),i.enqueue(l);i.size()>0;){let c=i.dequeue();if(c==null||c.length>cr)return s;let h=c[c.length-1];(r===null||h[0]===r)&&s.push(c),e.get(h[0])?.forEach(w=>{if(this.isNotVisited(w,c)){let B=[...c];B.push(w),i.enqueue(B)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,l]of t){let c=parseInt(i),h=parseInt(l);r.get(c)?.push([h,s])}return r}};function xt(u){let e={};for(let t of u){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let l=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(l)}}}return e}var Ye=class{getProposals(e,t,r){let s=xt(r),i=Object.keys(s),l=i.map(w=>s[w]).flat(),c=new We,h=c.buildAndPopulateGraph(i,l),y=c.findPaths(h,parseInt(e),t?parseInt(t):null);return this.parsePaths(y)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let l=r[i],c=r[i+1];if(c==null)break;s.push(this.toEdge(l,c))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var pr=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ot=Math.ceil,ae=Math.floor,te="[BigNumber Error] ",Dt=te+"Number primitive has more than 15 significant digits: ",me=1e14,A=14,wt=9007199254740991,Bt=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Be=1e7,X=1e9;function Ct(u){var e,t,r,s=O.prototype={constructor:O,toString:null,valueOf:null},i=new O(1),l=20,c=4,h=-7,y=21,w=-1e7,B=1e7,T=!1,L=1,M=0,J={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},C="0123456789abcdefghijklmnopqrstuvwxyz",Z=!0;function O(n,o){var a,P,m,d,S,p,g,b,f=this;if(!(f instanceof O))return new O(n,o);if(o==null){if(n&&n._isBigNumber===!0){f.s=n.s,!n.c||n.e>B?f.c=f.e=null:n.e<w?f.c=[f.e=0]:(f.e=n.e,f.c=n.c.slice());return}if((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(!pr.test(b=String(n)))return r(f,b,p);f.s=b.charCodeAt(0)==45?(b=b.slice(1),-1):1}(d=b.indexOf("."))>-1&&(b=b.replace(".","")),(S=b.search(/e/i))>0?(d<0&&(d=S),d+=+b.slice(S+1),b=b.substring(0,S)):d<0&&(d=b.length)}else{if(G(o,2,C.length,"Base"),o==10&&Z)return f=new O(n),j(f,l+f.e+1,c);if(b=String(n),p=typeof n=="number"){if(n*0!=0)return r(f,b,p,o);if(f.s=1/n<0?(b=b.slice(1),-1):1,O.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(a=C.slice(0,o),d=S=0,g=b.length;S<g;S++)if(a.indexOf(P=b.charAt(S))<0){if(P=="."){if(S>d){d=g;continue}}else if(!m&&(b==b.toUpperCase()&&(b=b.toLowerCase())||b==b.toLowerCase()&&(b=b.toUpperCase()))){m=!0,S=-1,d=0;continue}return r(f,String(n),p,o)}p=!1,b=t(b,o,10,f.s),(d=b.indexOf("."))>-1?b=b.replace(".",""):d=b.length}for(S=0;b.charCodeAt(S)===48;S++);for(g=b.length;b.charCodeAt(--g)===48;);if(b=b.slice(S,++g)){if(g-=S,p&&O.DEBUG&&g>15&&(n>wt||n!==ae(n)))throw Error(Dt+f.s*n);if((d=d-S-1)>B)f.c=f.e=null;else if(d<w)f.c=[f.e=0];else{if(f.e=d,f.c=[],S=(d+1)%A,d<0&&(S+=A),S<g){for(S&&f.c.push(+b.slice(0,S)),g-=A;S<g;)f.c.push(+b.slice(S,S+=A));S=A-(b=b.slice(S)).length}else S-=g;for(;S--;b+="0");f.c.push(+b)}}else f.c=[f.e=0]}O.clone=Ct,O.ROUND_UP=0,O.ROUND_DOWN=1,O.ROUND_CEIL=2,O.ROUND_FLOOR=3,O.ROUND_HALF_UP=4,O.ROUND_HALF_DOWN=5,O.ROUND_HALF_EVEN=6,O.ROUND_HALF_CEIL=7,O.ROUND_HALF_FLOOR=8,O.EUCLID=9,O.config=O.set=function(n){var o,a;if(n!=null)if(typeof n=="object"){if(n.hasOwnProperty(o="DECIMAL_PLACES")&&(a=n[o],G(a,0,X,o),l=a),n.hasOwnProperty(o="ROUNDING_MODE")&&(a=n[o],G(a,0,8,o),c=a),n.hasOwnProperty(o="EXPONENTIAL_AT")&&(a=n[o],a&&a.pop?(G(a[0],-X,0,o),G(a[1],0,X,o),h=a[0],y=a[1]):(G(a,-X,X,o),h=-(y=a<0?-a:a))),n.hasOwnProperty(o="RANGE"))if(a=n[o],a&&a.pop)G(a[0],-X,-1,o),G(a[1],1,X,o),w=a[0],B=a[1];else if(G(a,-X,X,o),a)w=-(B=a<0?-a:a);else throw Error(te+o+" cannot be zero: "+a);if(n.hasOwnProperty(o="CRYPTO"))if(a=n[o],a===!!a)if(a)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))T=a;else throw T=!a,Error(te+"crypto unavailable");else T=a;else throw Error(te+o+" not true or false: "+a);if(n.hasOwnProperty(o="MODULO_MODE")&&(a=n[o],G(a,0,9,o),L=a),n.hasOwnProperty(o="POW_PRECISION")&&(a=n[o],G(a,0,X,o),M=a),n.hasOwnProperty(o="FORMAT"))if(a=n[o],typeof a=="object")J=a;else throw Error(te+o+" not an object: "+a);if(n.hasOwnProperty(o="ALPHABET"))if(a=n[o],typeof a=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(a))Z=a.slice(0,10)=="0123456789",C=a;else throw Error(te+o+" invalid: "+a)}else throw Error(te+"Object expected: "+n);return{DECIMAL_PLACES:l,ROUNDING_MODE:c,EXPONENTIAL_AT:[h,y],RANGE:[w,B],CRYPTO:T,MODULO_MODE:L,POW_PRECISION:M,FORMAT:J,ALPHABET:C}},O.isBigNumber=function(n){if(!n||n._isBigNumber!==!0)return!1;if(!O.DEBUG)return!0;var o,a,P=n.c,m=n.e,d=n.s;e:if({}.toString.call(P)=="[object Array]"){if((d===1||d===-1)&&m>=-X&&m<=X&&m===ae(m)){if(P[0]===0){if(m===0&&P.length===1)return!0;break e}if(o=(m+1)%A,o<1&&(o+=A),String(P[0]).length==o){for(o=0;o<P.length;o++)if(a=P[o],a<0||a>=me||a!==ae(a))break e;if(a!==0)return!0}}}else if(P===null&&m===null&&(d===null||d===1||d===-1))return!0;throw Error(te+"Invalid BigNumber: "+n)},O.maximum=O.max=function(){return ge(arguments,-1)},O.minimum=O.min=function(){return ge(arguments,1)},O.random=function(){var n=9007199254740992,o=Math.random()*n&2097151?function(){return ae(Math.random()*n)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(a){var P,m,d,S,p,g=0,b=[],f=new O(i);if(a==null?a=l:G(a,0,X),S=Ot(a/A),T)if(crypto.getRandomValues){for(P=crypto.getRandomValues(new Uint32Array(S*=2));g<S;)p=P[g]*131072+(P[g+1]>>>11),p>=9e15?(m=crypto.getRandomValues(new Uint32Array(2)),P[g]=m[0],P[g+1]=m[1]):(b.push(p%1e14),g+=2);g=S/2}else if(crypto.randomBytes){for(P=crypto.randomBytes(S*=7);g<S;)p=(P[g]&31)*281474976710656+P[g+1]*1099511627776+P[g+2]*4294967296+P[g+3]*16777216+(P[g+4]<<16)+(P[g+5]<<8)+P[g+6],p>=9e15?crypto.randomBytes(7).copy(P,g):(b.push(p%1e14),g+=7);g=S/7}else throw T=!1,Error(te+"crypto unavailable");if(!T)for(;g<S;)p=o(),p<9e15&&(b[g++]=p%1e14);for(S=b[--g],a%=A,S&&a&&(p=Bt[A-a],b[g]=ae(S/p)*p);b[g]===0;b.pop(),g--);if(g<0)b=[d=0];else{for(d=-1;b[0]===0;b.splice(0,1),d-=A);for(g=1,p=b[0];p>=10;p/=10,g++);g<A&&(d-=A-g)}return f.e=d,f.c=b,f}}(),O.sum=function(){for(var n=1,o=arguments,a=new O(o[0]);n<o.length;)a=a.plus(o[n++]);return a},t=function(){var n="0123456789";function o(a,P,m,d){for(var S,p=[0],g,b=0,f=a.length;b<f;){for(g=p.length;g--;p[g]*=P);for(p[0]+=d.indexOf(a.charAt(b++)),S=0;S<p.length;S++)p[S]>m-1&&(p[S+1]==null&&(p[S+1]=0),p[S+1]+=p[S]/m|0,p[S]%=m)}return p.reverse()}return function(a,P,m,d,S){var p,g,b,f,x,v,N,E,q=a.indexOf("."),z=l,_=c;for(q>=0&&(f=M,M=0,a=a.replace(".",""),E=new O(P),v=E.pow(a.length-q),M=f,E.c=o(Oe(oe(v.c),v.e,"0"),10,m,n),E.e=E.c.length),N=o(a,P,m,S?(p=C,n):(p=n,C)),b=f=N.length;N[--f]==0;N.pop());if(!N[0])return p.charAt(0);if(q<0?--b:(v.c=N,v.e=b,v.s=d,v=e(v,E,z,_,m),N=v.c,x=v.r,b=v.e),g=b+z+1,q=N[g],f=m/2,x=x||g<0||N[g+1]!=null,x=_<4?(q!=null||x)&&(_==0||_==(v.s<0?3:2)):q>f||q==f&&(_==4||x||_==6&&N[g-1]&1||_==(v.s<0?8:7)),g<1||!N[0])a=x?Oe(p.charAt(1),-z,p.charAt(0)):p.charAt(0);else{if(N.length=g,x)for(--m;++N[--g]>m;)N[g]=0,g||(++b,N=[1].concat(N));for(f=N.length;!N[--f];);for(q=0,a="";q<=f;a+=p.charAt(N[q++]));a=Oe(a,b,p.charAt(0))}return a}}(),e=function(){function n(P,m,d){var S,p,g,b,f=0,x=P.length,v=m%Be,N=m/Be|0;for(P=P.slice();x--;)g=P[x]%Be,b=P[x]/Be|0,S=N*g+b*v,p=v*g+S%Be*Be+f,f=(p/d|0)+(S/Be|0)+N*b,P[x]=p%d;return f&&(P=[f].concat(P)),P}function o(P,m,d,S){var p,g;if(d!=S)g=d>S?1:-1;else for(p=g=0;p<d;p++)if(P[p]!=m[p]){g=P[p]>m[p]?1:-1;break}return g}function a(P,m,d,S){for(var p=0;d--;)P[d]-=p,p=P[d]<m[d]?1:0,P[d]=p*S+P[d]-m[d];for(;!P[0]&&P.length>1;P.splice(0,1));}return function(P,m,d,S,p){var g,b,f,x,v,N,E,q,z,_,D,Q,Ze,bt,St,de,Xe,ne=P.s==m.s?1:-1,K=P.c,H=m.c;if(!K||!K[0]||!H||!H[0])return new O(!P.s||!m.s||(K?H&&K[0]==H[0]:!H)?NaN:K&&K[0]==0||!H?ne*0:ne/0);for(q=new O(ne),z=q.c=[],b=P.e-m.e,ne=d+b+1,p||(p=me,b=le(P.e/A)-le(m.e/A),ne=ne/A|0),f=0;H[f]==(K[f]||0);f++);if(H[f]>(K[f]||0)&&b--,ne<0)z.push(1),x=!0;else{for(bt=K.length,de=H.length,f=0,ne+=2,v=ae(p/(H[0]+1)),v>1&&(H=n(H,v,p),K=n(K,v,p),de=H.length,bt=K.length),Ze=de,_=K.slice(0,de),D=_.length;D<de;_[D++]=0);Xe=H.slice(),Xe=[0].concat(Xe),St=H[0],H[1]>=p/2&&St++;do{if(v=0,g=o(H,_,de,D),g<0){if(Q=_[0],de!=D&&(Q=Q*p+(_[1]||0)),v=ae(Q/St),v>1)for(v>=p&&(v=p-1),N=n(H,v,p),E=N.length,D=_.length;o(N,_,E,D)==1;)v--,a(N,de<E?Xe:H,E,p),E=N.length,g=1;else v==0&&(g=v=1),N=H.slice(),E=N.length;if(E<D&&(N=[0].concat(N)),a(_,N,D,p),D=_.length,g==-1)for(;o(H,_,de,D)<1;)v++,a(_,de<D?Xe:H,D,p),D=_.length}else g===0&&(v++,_=[0]);z[f++]=v,_[0]?_[D++]=K[Ze]||0:(_=[K[Ze]],D=1)}while((Ze++<bt||_[0]!=null)&&ne--);x=_[0]!=null,z[0]||z.splice(0,1)}if(p==me){for(f=1,ne=z[0];ne>=10;ne/=10,f++);j(q,d+(q.e=f+b*A-1)+1,S,x)}else q.e=b,q.r=+x;return q}}();function pe(n,o,a,P){var m,d,S,p,g;if(a==null?a=c:G(a,0,8),!n.c)return n.toString();if(m=n.c[0],S=n.e,o==null)g=oe(n.c),g=P==1||P==2&&(S<=h||S>=y)?tt(g,S):Oe(g,S,"0");else if(n=j(new O(n),o,a),d=n.e,g=oe(n.c),p=g.length,P==1||P==2&&(o<=d||d<=h)){for(;p<o;g+="0",p++);g=tt(g,d)}else if(o-=S,g=Oe(g,d,"0"),d+1>p){if(--o>0)for(g+=".";o--;g+="0");}else if(o+=d-p,o>0)for(d+1==p&&(g+=".");o--;g+="0");return n.s<0&&m?"-"+g:g}function ge(n,o){for(var a,P,m=1,d=new O(n[0]);m<n.length;m++)P=new O(n[m]),(!P.s||(a=Te(d,P))===o||a===0&&d.s===o)&&(d=P);return d}function xe(n,o,a){for(var P=1,m=o.length;!o[--m];o.pop());for(m=o[0];m>=10;m/=10,P++);return(a=P+a*A-1)>B?n.c=n.e=null:a<w?n.c=[n.e=0]:(n.e=a,n.c=o),n}r=function(){var n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,o=/^([^.]+)\.$/,a=/^\.([^.]+)$/,P=/^-?(Infinity|NaN)$/,m=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(d,S,p,g){var b,f=p?S:S.replace(m,"");if(P.test(f))d.s=isNaN(f)?null:f<0?-1:1;else{if(!p&&(f=f.replace(n,function(x,v,N){return b=(N=N.toLowerCase())=="x"?16:N=="b"?2:8,!g||g==b?v:x}),g&&(b=g,f=f.replace(o,"$1").replace(a,"0.$1")),S!=f))return new O(f,b);if(O.DEBUG)throw Error(te+"Not a"+(g?" base "+g:"")+" number: "+S);d.s=null}d.c=d.e=null}}();function j(n,o,a,P){var m,d,S,p,g,b,f,x=n.c,v=Bt;if(x){e:{for(m=1,p=x[0];p>=10;p/=10,m++);if(d=o-m,d<0)d+=A,S=o,g=x[b=0],f=ae(g/v[m-S-1]%10);else if(b=Ot((d+1)/A),b>=x.length)if(P){for(;x.length<=b;x.push(0));g=f=0,m=1,d%=A,S=d-A+1}else break e;else{for(g=p=x[b],m=1;p>=10;p/=10,m++);d%=A,S=d-A+m,f=S<0?0:ae(g/v[m-S-1]%10)}if(P=P||o<0||x[b+1]!=null||(S<0?g:g%v[m-S-1]),P=a<4?(f||P)&&(a==0||a==(n.s<0?3:2)):f>5||f==5&&(a==4||P||a==6&&(d>0?S>0?g/v[m-S]:0:x[b-1])%10&1||a==(n.s<0?8:7)),o<1||!x[0])return x.length=0,P?(o-=n.e+1,x[0]=v[(A-o%A)%A],n.e=-o||0):x[0]=n.e=0,n;if(d==0?(x.length=b,p=1,b--):(x.length=b+1,p=v[A-d],x[b]=S>0?ae(g/v[m-S]%v[S])*p:0),P)for(;;)if(b==0){for(d=1,S=x[0];S>=10;S/=10,d++);for(S=x[0]+=p,p=1;S>=10;S/=10,p++);d!=p&&(n.e++,x[0]==me&&(x[0]=1));break}else{if(x[b]+=p,x[b]!=me)break;x[b--]=0,p=1}for(d=x.length;x[--d]===0;x.pop());}n.e>B?n.c=n.e=null:n.e<w&&(n.c=[n.e=0])}return n}function k(n){var o,a=n.e;return a===null?n.toString():(o=oe(n.c),o=a<=h||a>=y?tt(o,a):Oe(o,a,"0"),n.s<0?"-"+o:o)}return s.absoluteValue=s.abs=function(){var n=new O(this);return n.s<0&&(n.s=1),n},s.comparedTo=function(n,o){return Te(this,new O(n,o))},s.decimalPlaces=s.dp=function(n,o){var a,P,m,d=this;if(n!=null)return G(n,0,X),o==null?o=c:G(o,0,8),j(new O(d),n+d.e+1,o);if(!(a=d.c))return null;if(P=((m=a.length-1)-le(this.e/A))*A,m=a[m])for(;m%10==0;m/=10,P--);return P<0&&(P=0),P},s.dividedBy=s.div=function(n,o){return e(this,new O(n,o),l,c)},s.dividedToIntegerBy=s.idiv=function(n,o){return e(this,new O(n,o),0,1)},s.exponentiatedBy=s.pow=function(n,o){var a,P,m,d,S,p,g,b,f,x=this;if(n=new O(n),n.c&&!n.isInteger())throw Error(te+"Exponent not an integer: "+k(n));if(o!=null&&(o=new O(o)),p=n.e>14,!x.c||!x.c[0]||x.c[0]==1&&!x.e&&x.c.length==1||!n.c||!n.c[0])return f=new O(Math.pow(+k(x),p?n.s*(2-et(n)):+k(n))),o?f.mod(o):f;if(g=n.s<0,o){if(o.c?!o.c[0]:!o.s)return new O(NaN);P=!g&&x.isInteger()&&o.isInteger(),P&&(x=x.mod(o))}else{if(n.e>9&&(x.e>0||x.e<-1||(x.e==0?x.c[0]>1||p&&x.c[1]>=24e7:x.c[0]<8e13||p&&x.c[0]<=9999975e7)))return d=x.s<0&&et(n)?-0:0,x.e>-1&&(d=1/d),new O(g?1/d:d);M&&(d=Ot(M/A+2))}for(p?(a=new O(.5),g&&(n.s=1),b=et(n)):(m=Math.abs(+k(n)),b=m%2),f=new O(i);;){if(b){if(f=f.times(x),!f.c)break;d?f.c.length>d&&(f.c.length=d):P&&(f=f.mod(o))}if(m){if(m=ae(m/2),m===0)break;b=m%2}else if(n=n.times(a),j(n,n.e+1,1),n.e>14)b=et(n);else{if(m=+k(n),m===0)break;b=m%2}x=x.times(x),d?x.c&&x.c.length>d&&(x.c.length=d):P&&(x=x.mod(o))}return P?f:(g&&(f=i.div(f)),o?f.mod(o):d?j(f,M,c,S):f)},s.integerValue=function(n){var o=new O(this);return n==null?n=c:G(n,0,8),j(o,o.e+1,n)},s.isEqualTo=s.eq=function(n,o){return Te(this,new O(n,o))===0},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(n,o){return Te(this,new O(n,o))>0},s.isGreaterThanOrEqualTo=s.gte=function(n,o){return(o=Te(this,new O(n,o)))===1||o===0},s.isInteger=function(){return!!this.c&&le(this.e/A)>this.c.length-2},s.isLessThan=s.lt=function(n,o){return Te(this,new O(n,o))<0},s.isLessThanOrEqualTo=s.lte=function(n,o){return(o=Te(this,new O(n,o)))===-1||o===0},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&this.c[0]==0},s.minus=function(n,o){var a,P,m,d,S=this,p=S.s;if(n=new O(n,o),o=n.s,!p||!o)return new O(NaN);if(p!=o)return n.s=-o,S.plus(n);var g=S.e/A,b=n.e/A,f=S.c,x=n.c;if(!g||!b){if(!f||!x)return f?(n.s=-o,n):new O(x?S:NaN);if(!f[0]||!x[0])return x[0]?(n.s=-o,n):new O(f[0]?S:c==3?-0:0)}if(g=le(g),b=le(b),f=f.slice(),p=g-b){for((d=p<0)?(p=-p,m=f):(b=g,m=x),m.reverse(),o=p;o--;m.push(0));m.reverse()}else for(P=(d=(p=f.length)<(o=x.length))?p:o,p=o=0;o<P;o++)if(f[o]!=x[o]){d=f[o]<x[o];break}if(d&&(m=f,f=x,x=m,n.s=-n.s),o=(P=x.length)-(a=f.length),o>0)for(;o--;f[a++]=0);for(o=me-1;P>p;){if(f[--P]<x[P]){for(a=P;a&&!f[--a];f[a]=o);--f[a],f[P]+=me}f[P]-=x[P]}for(;f[0]==0;f.splice(0,1),--b);return f[0]?xe(n,f,b):(n.s=c==3?-1:1,n.c=[n.e=0],n)},s.modulo=s.mod=function(n,o){var a,P,m=this;return n=new O(n,o),!m.c||!n.s||n.c&&!n.c[0]?new O(NaN):!n.c||m.c&&!m.c[0]?new O(m):(L==9?(P=n.s,n.s=1,a=e(m,n,0,3),n.s=P,a.s*=P):a=e(m,n,0,L),n=m.minus(a.times(n)),!n.c[0]&&L==1&&(n.s=m.s),n)},s.multipliedBy=s.times=function(n,o){var a,P,m,d,S,p,g,b,f,x,v,N,E,q,z,_=this,D=_.c,Q=(n=new O(n,o)).c;if(!D||!Q||!D[0]||!Q[0])return!_.s||!n.s||D&&!D[0]&&!Q||Q&&!Q[0]&&!D?n.c=n.e=n.s=null:(n.s*=_.s,!D||!Q?n.c=n.e=null:(n.c=[0],n.e=0)),n;for(P=le(_.e/A)+le(n.e/A),n.s*=_.s,g=D.length,x=Q.length,g<x&&(E=D,D=Q,Q=E,m=g,g=x,x=m),m=g+x,E=[];m--;E.push(0));for(q=me,z=Be,m=x;--m>=0;){for(a=0,v=Q[m]%z,N=Q[m]/z|0,S=g,d=m+S;d>m;)b=D[--S]%z,f=D[S]/z|0,p=N*b+f*v,b=v*b+p%z*z+E[d]+a,a=(b/q|0)+(p/z|0)+N*f,E[d--]=b%q;E[d]=a}return a?++P:E.splice(0,1),xe(n,E,P)},s.negated=function(){var n=new O(this);return n.s=-n.s||null,n},s.plus=function(n,o){var a,P=this,m=P.s;if(n=new O(n,o),o=n.s,!m||!o)return new O(NaN);if(m!=o)return n.s=-o,P.minus(n);var d=P.e/A,S=n.e/A,p=P.c,g=n.c;if(!d||!S){if(!p||!g)return new O(m/0);if(!p[0]||!g[0])return g[0]?n:new O(p[0]?P:m*0)}if(d=le(d),S=le(S),p=p.slice(),m=d-S){for(m>0?(S=d,a=g):(m=-m,a=p),a.reverse();m--;a.push(0));a.reverse()}for(m=p.length,o=g.length,m-o<0&&(a=g,g=p,p=a,o=m),m=0;o;)m=(p[--o]=p[o]+g[o]+m)/me|0,p[o]=me===p[o]?0:p[o]%me;return m&&(p=[m].concat(p),++S),xe(n,p,S)},s.precision=s.sd=function(n,o){var a,P,m,d=this;if(n!=null&&n!==!!n)return G(n,1,X),o==null?o=c:G(o,0,8),j(new O(d),n,o);if(!(a=d.c))return null;if(m=a.length-1,P=m*A+1,m=a[m]){for(;m%10==0;m/=10,P--);for(m=a[0];m>=10;m/=10,P++);}return n&&d.e+1>P&&(P=d.e+1),P},s.shiftedBy=function(n){return G(n,-wt,wt),this.times("1e"+n)},s.squareRoot=s.sqrt=function(){var n,o,a,P,m,d=this,S=d.c,p=d.s,g=d.e,b=l+4,f=new O("0.5");if(p!==1||!S||!S[0])return new O(!p||p<0&&(!S||S[0])?NaN:S?d:1/0);if(p=Math.sqrt(+k(d)),p==0||p==1/0?(o=oe(S),(o.length+g)%2==0&&(o+="0"),p=Math.sqrt(+o),g=le((g+1)/2)-(g<0||g%2),p==1/0?o="5e"+g:(o=p.toExponential(),o=o.slice(0,o.indexOf("e")+1)+g),a=new O(o)):a=new O(p+""),a.c[0]){for(g=a.e,p=g+b,p<3&&(p=0);;)if(m=a,a=f.times(m.plus(e(d,m,b,1))),oe(m.c).slice(0,p)===(o=oe(a.c)).slice(0,p))if(a.e<g&&--p,o=o.slice(p-3,p+1),o=="9999"||!P&&o=="4999"){if(!P&&(j(m,m.e+l+2,0),m.times(m).eq(d))){a=m;break}b+=4,p+=4,P=1}else{(!+o||!+o.slice(1)&&o.charAt(0)=="5")&&(j(a,a.e+l+2,1),n=!a.times(a).eq(d));break}}return j(a,a.e+l+1,c,n)},s.toExponential=function(n,o){return n!=null&&(G(n,0,X),n++),pe(this,n,o,1)},s.toFixed=function(n,o){return n!=null&&(G(n,0,X),n=n+this.e+1),pe(this,n,o)},s.toFormat=function(n,o,a){var P,m=this;if(a==null)n!=null&&o&&typeof o=="object"?(a=o,o=null):n&&typeof n=="object"?(a=n,n=o=null):a=J;else if(typeof a!="object")throw Error(te+"Argument not an object: "+a);if(P=m.toFixed(n,o),m.c){var d,S=P.split("."),p=+a.groupSize,g=+a.secondaryGroupSize,b=a.groupSeparator||"",f=S[0],x=S[1],v=m.s<0,N=v?f.slice(1):f,E=N.length;if(g&&(d=p,p=g,g=d,E-=d),p>0&&E>0){for(d=E%p||p,f=N.substr(0,d);d<E;d+=p)f+=b+N.substr(d,p);g>0&&(f+=b+N.slice(d)),v&&(f="-"+f)}P=x?f+(a.decimalSeparator||"")+((g=+a.fractionGroupSize)?x.replace(new RegExp("\\d{"+g+"}\\B","g"),"$&"+(a.fractionGroupSeparator||"")):x):f}return(a.prefix||"")+P+(a.suffix||"")},s.toFraction=function(n){var o,a,P,m,d,S,p,g,b,f,x,v,N=this,E=N.c;if(n!=null&&(p=new O(n),!p.isInteger()&&(p.c||p.s!==1)||p.lt(i)))throw Error(te+"Argument "+(p.isInteger()?"out of range: ":"not an integer: ")+k(p));if(!E)return new O(N);for(o=new O(i),b=a=new O(i),P=g=new O(i),v=oe(E),d=o.e=v.length-N.e-1,o.c[0]=Bt[(S=d%A)<0?A+S:S],n=!n||p.comparedTo(o)>0?d>0?o:b:p,S=B,B=1/0,p=new O(v),g.c[0]=0;f=e(p,o,0,1),m=a.plus(f.times(P)),m.comparedTo(n)!=1;)a=P,P=m,b=g.plus(f.times(m=b)),g=m,o=p.minus(f.times(m=o)),p=m;return m=e(n.minus(a),P,0,1),g=g.plus(m.times(b)),a=a.plus(m.times(P)),g.s=b.s=N.s,d=d*2,x=e(b,P,d,c).minus(N).abs().comparedTo(e(g,a,d,c).minus(N).abs())<1?[b,P]:[g,a],B=S,x},s.toNumber=function(){return+k(this)},s.toPrecision=function(n,o){return n!=null&&G(n,1,X),pe(this,n,o,2)},s.toString=function(n){var o,a=this,P=a.s,m=a.e;return m===null?P?(o="Infinity",P<0&&(o="-"+o)):o="NaN":(n==null?o=m<=h||m>=y?tt(oe(a.c),m):Oe(oe(a.c),m,"0"):n===10&&Z?(a=j(new O(a),l+m+1,c),o=Oe(oe(a.c),a.e,"0")):(G(n,2,C.length,"Base"),o=t(Oe(oe(a.c),m,"0"),10,n,P,!0)),P<0&&a.c[0]&&(o="-"+o)),o},s.valueOf=s.toJSON=function(){return k(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,u!=null&&O.set(u),O}function le(u){var e=u|0;return u>0||u===e?e:e-1}function oe(u){for(var e,t,r=1,s=u.length,i=u[0]+"";r<s;){for(e=u[r++]+"",t=A-e.length;t--;e="0"+e);i+=e}for(s=i.length;i.charCodeAt(--s)===48;);return i.slice(0,s+1||1)}function Te(u,e){var t,r,s=u.c,i=e.c,l=u.s,c=e.s,h=u.e,y=e.e;if(!l||!c)return null;if(t=s&&!s[0],r=i&&!i[0],t||r)return t?r?0:-c:l;if(l!=c)return l;if(t=l<0,r=h==y,!s||!i)return r?0:!s^t?1:-1;if(!r)return h>y^t?1:-1;for(c=(h=s.length)<(y=i.length)?h:y,l=0;l<c;l++)if(s[l]!=i[l])return s[l]>i[l]^t?1:-1;return h==y?0:h>y^t?1:-1}function G(u,e,t,r){if(u<e||u>t||u!==ae(u))throw Error(te+(r||"Argument")+(typeof u=="number"?u<e||u>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(u))}function et(u){var e=u.c.length-1;return le(u.e/A)==e&&u.c[e]%2!=0}function tt(u,e){return(u.length>1?u.charAt(0)+"."+u.slice(1):u)+(e<0?"e":"e+")+e}function Oe(u,e,t){var r,s;if(e<0){for(s=t+".";++e;s+=t);u=s+u}else if(r=u.length,++e>r){for(s=t,e-=r;--e;s+=t);u+=s}else e<r&&(u=u.slice(0,e)+"."+u.slice(e));return u}var fe=Ct();var Gt=12;fe.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Gt});var R=I(0),ie=I(1),mr=I("Infinity");function W(u,e){let t=new fe(e.toString()),r=new fe(10).pow(t);return u.times(r)}function I(u){return new fe(u.toString())}var re=(s=>(s.XYK="Xyk",s.LBP="Lbp",s.Stable="Stableswap",s.Omni="Omnipool",s))(re||{}),_e=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(_e||{}),vt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(vt||{});var Pe=require("@galacticcouncil/math-lbp"),ue=class{static getSpotPrice(e,t,r,s,i){return(0,Pe.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,Pe.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,Pe.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,Pe.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,Pe.calculate_pool_trade_fee)(e,t,r)}};var qt=require("@polkadot/util-crypto"),Ht=require("@polkadot/util"),Re=18,rt=15,we="0",hr=12,gr=2034,Ee=63,dr=2090,st=1e3,$e=(0,qt.encodeAddress)((0,Ht.stringToU8a)("modlomnipool".padEnd(32,"\0")),Ee);function Ut(u,e){let t;return JSON.stringify(u,(r,s)=>(s&&s[e]&&(t=s),s)),t}var Jr=require("@polkadot/types/lookup");var jr=require("@polkadot/api-base/types/consts");var Qr=require("@polkadot/api-base/types/errors");var Vr=require("@polkadot/api-base/types/events");var Zr=require("@polkadot/api-base/types/storage");var Kr=require("@polkadot/api-base/types/submittable");var es=require("@polkadot/rpc-core/types/jsonrpc");var ts=require("@polkadot/api-base/types/calls");var us=require("@polkadot/types/types/registry");var hs=require("@polkadot/types/lookup");var gs=require("@polkadot/api-base/types/consts");var ds=require("@polkadot/api-base/types/errors");var fs=require("@polkadot/api-base/types/events");var Ps=require("@polkadot/api-base/types/storage");var bs=require("@polkadot/api-base/types/submittable");var Ss=require("@polkadot/rpc-core/types/jsonrpc");var ys=require("@polkadot/api-base/types/calls");var As=require("@polkadot/types/types/registry");var ke=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Le=class extends ke{SUPPORTED_TYPES=["StableSwap","Bond","Token"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getTokens(e,t,r,s){if(e==we){let B=this.api.consts.balances.existentialDeposit;return{id:we,name:this.chainToken,symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",existentialDeposit:B.toString()}}let{name:i,assetType:l,existentialDeposit:c}=t,{symbol:h,decimals:y}=r.get(e),w=s?s.get(e):void 0;return{id:e,name:i.toHuman(),symbol:h.toHuman(),decimals:y.toNumber(),icon:h.toHuman(),type:l.toHuman(),origin:w&&this.parseLocation(w),existentialDeposit:c.toString()}}getBonds(e,t,r,s){let[i,l]=s,{assetType:c,existentialDeposit:h}=t,{symbol:y,decimals:w}=this.getTokens(i.toString(),t,r),B=l.toNumber(),T=new Intl.DateTimeFormat("en-GB"),L=[y,"Bond",T.format(B)].join(" ");return{id:e,name:L,symbol:y+"b",decimals:w,icon:y,type:c.toString(),existentialDeposit:h.toString()}}getShares(e,t,r,s){let{assets:i}=s,{name:l,assetType:c,existentialDeposit:h}=t,w=i.map(L=>L.toString()).map(L=>{let{symbol:M}=this.getTokens(L,t,r);return[L,M]}),B=Object.fromEntries(w),T=Object.values(B);return{id:e,name:T.join(", "),symbol:l.length>0?l.toHuman():e,decimals:18,icon:T.join("/"),type:c.toString(),existentialDeposit:h.toString(),meta:B}}async getOnChainAssets(){let[e,t,r,s,i]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.metadataQuery(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery()]);return e.filter(([l,c])=>this.isSupportedType(c.unwrap())).map(([{args:[l]},c])=>{let h=c.unwrap(),{assetType:y}=h;switch(y.toString()){case"Bond":let w=i.get(l.toString());return this.getBonds(l.toString(),h,t,w);case"StableSwap":let B=s.get(l.toString());return this.getShares(l.toString(),h,t,B);default:return this.getTokens(l.toString(),h,t,r)}})}isSupportedType(e){return this.SUPPORTED_TYPES.includes(e.assetType.toString())}parseLocation(e){if(e){let t=Ut(e.toJSON(),"parachain");return t&&t.parachain}else return}};var Me=class extends ke{constructor(e){super(e)}async getBalance(e,t){return t===we?await this.getSystemBalance(e):await this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:i})}async subscribeBalance(e,t,r){let s=t.filter(i=>i!==we).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach(({free:l,reserved:c,frozen:h},y)=>{let w=this.calculateFreeBalance({free:l,feeFrozen:c,frozen:h}),B=s[y][1];r(B,w)})})}async subscribeTokenBalance(e,t,r){let s=t.filter(i=>i!==we).map(i=>[e,i]);return this.api.query.tokens.accounts.multi(s,i=>{i.forEach((l,c)=>{let h=this.calculateFreeBalance(l),y=s[c][1];r(y,h)})})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(we,this.calculateFreeBalance(r)))}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:i}=e,l=new fe(t),c=new fe(r||i),h=new fe(s||0),y=c.gt(h)?c:h;return l.minus(y)}};var be=class extends Me{pools=[];subs=[];poolsLoaded=!1;constructor(e){super(e)}async getPools(){return this.poolsLoaded?this.pools:(this.pools=await this.loadPools(),this.subs=await this.subscribe(),this.poolsLoaded=!0,this.pools)}async subscribe(){let e=this.pools.map(async r=>{let s=[await this.subscribePoolChange(r),await this.subscribeTokensPoolBalance(r),await this.subscribeSystemPoolBalance(r)];if(this.hasShareAsset(r)){let i=await this.subscribeSharePoolBalance(r);s.push(i)}return this.subscribeLog(r),s});return(await Promise.all(e)).flat()}subscribeLog(e){let t=e.address.substring(0,10).concat("...");console.log(`${e.type} [${t}] balance subscribed`)}unsubscribe(){this.subs.forEach(e=>{e()})}hasShareAsset(e){return e.type==="Stableswap"&&e.id}subscribeTokensPoolBalance(e){return this.subscribeTokenBalance(e.address,e.tokens.map(t=>t.id),this.updateBalanceCallback(e,(t,r)=>t.id!==r))}subscribeSharePoolBalance(e){return this.subscribeTokenBalance($e,[e.id],this.updateBalanceCallback(e,()=>!0))}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e,()=>!0))}updateBalanceCallback(e,t){return function(r,s){let i=e.tokens.findIndex(l=>l.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=s.toString())}}};var it=class extends be{MAX_FINAL_WEIGHT=W(I(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,l])=>this.isActivePool(l.unwrap(),r)).map(async([{args:[i]},l])=>{let c=l.unwrap(),h=i.toString(),y=await this.getPoolDelta(h,c,r.toString());return this.poolsData.set(i.toString(),c),{address:h,type:"Lbp",fee:c.fee.toJSON(),...y,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let l=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,l)}else{let l=this.pools.findIndex(c=>c.address==e.address);this.pools.splice(l,1)}})}async getPoolDelta(e,t,r){let{start:s,end:i,assets:l,initialWeight:c,finalWeight:h,repayTarget:y,feeCollector:w}=t,B=ue.calculateLinearWeights(s.toString(),i.toString(),c.toString(),h.toString(),r),[T,L]=l,M=T.toString(),J=I(B),C=L.toString(),Z=this.MAX_FINAL_WEIGHT.minus(I(J)),[O,pe,ge]=await Promise.all([this.isRepayFeeApplied(M,y.toString(),w.toString()),this.getBalance(e,M),this.getBalance(e,C)]);return{repayFeeApply:O,tokens:[{id:M,weight:J,balance:pe.toString()},{id:C,weight:Z,balance:ge.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=I(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var zt=require("@polkadot/util-crypto"),Xt=require("@polkadot/util");function $(u,e){return u.shiftedBy(-1*e).toString()}function ce(u){return u[0]/u[1]*100}function se(u){return u[0]/u[1]}function he(u){return[u/st,st]}var nt=class extends be{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),l=r.map(async([{args:[h]},y])=>{let{hubReserve:w,shares:B,tradable:T}=y.unwrap(),L=await this.getBalance(t,h.toString());return{id:h.toString(),hubReserves:I(w.toString()),shares:I(B.toString()),tradeable:T.bits.toNumber(),balance:L.toString()}}),c=await Promise.all(l);return c.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:c,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=await this.api.query.dynamicFees.assetFee(e),s=this.api.consts.dynamicFees.assetFeeParameters,i=this.api.consts.dynamicFees.protocolFeeParameters,l=s.minFee.toNumber()+i.minFee.toNumber(),c=s.maxFee.toNumber()+i.maxFee.toNumber();if(r.isSome){let{assetFee:h,protocolFee:y}=r.unwrap();return{assetFee:he(h.toNumber()),protocolFee:he(y.toNumber()),min:he(l),max:he(c)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:he(l),max:he(c)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,i)=>{let l=e.tokens[i];if(s.isNone)return l;let c=s.unwrap();return this.updateTokenState(l,c)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i}=t;return{...e,hubReserves:I(r.toString()),shares:I(s.toString()),tradeable:i.bits.toNumber()}}getAssetFee(){let t=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber();return he(t)}getProtocolFee(){let t=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber();return he(t)}getPoolId(){return(0,zt.encodeAddress)((0,Xt.stringToU8a)("modlomnipool".padEnd(32,"\0")),Ee)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var ot=class extends be{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[l,c]=s.unwrap(),[h,y]=await Promise.all([this.getBalance(i,l.toString()),this.getBalance(i,c.toString())]);return{address:i,type:"Xyk",tokens:[{id:l.toString(),balance:h.toString()},{id:c.toString(),balance:y.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){return this.api.query.xyk.poolAssets(e.address,t=>{})}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var lt=require("@polkadot/util-crypto");var Y=require("@galacticcouncil/math-stableswap"),ee=class{static getPoolAddress(e){return(0,Y.pool_account_name)(e)}static calculateAmplification(e,t,r,s,i){return(0,Y.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,l){return(0,Y.calculate_in_given_out)(e,t,r,s,i,l)}static calculateAddOneAsset(e,t,r,s,i,l){return(0,Y.calculate_add_one_asset)(e,t,r,s,i,l)}static calculateSharesForAmount(e,t,r,s,i,l){return(0,Y.calculate_shares_for_amount)(e,t,r,s,i,l)}static calculateOutGivenIn(e,t,r,s,i,l){return(0,Y.calculate_out_given_in)(e,t,r,s,i,l)}static calculateLiquidityOutOneAsset(e,t,r,s,i,l){return(0,Y.calculate_liquidity_out_one_asset)(e,t,r,s,i,l)}static calculateShares(e,t,r,s,i){return(0,Y.calculate_shares)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,Y.calculate_pool_trade_fee)(e,t,r)}};var at=class extends be{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[i]},l])=>{let c=l.unwrap(),h=i.toString(),y=this.getPoolAddress(h),[w,B]=await Promise.all([this.getPoolDelta(h,c,r.toString()),this.getPoolTokens(y,h,c)]);return this.stablePools.set(y,c),{address:y,id:h,type:"Stableswap",fee:he(c.fee.toNumber()),tokens:B,...w,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toNumber(),s=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,s,r.toString());Object.assign(e,i)})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:l,finalBlock:c}=t,h=ee.calculateAmplification(s.toString(),i.toString(),l.toString(),c.toString(),r),y=await this.api.query.tokens.totalIssuance(e);return{amplification:h,totalIssuance:y.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async h=>{let[y,w]=await Promise.all([this.api.query.stableswap.assetTradability(t,h.toString()),this.getBalance(e,h.toString())]);return{id:h.toString(),tradeable:y.bits.toNumber(),balance:w.toString()}}),l=await Promise.all(i),c=await this.api.query.omnipool.assets(t);if(c.isSome){let{tradable:h}=c.unwrap(),y=await this.getBalance($e,t);l.push({id:t,tradeable:h.bits.toNumber(),balance:y.toString()})}return l}getPoolAddress(e){let t=Number(e),r=ee.getPoolAddress(t);return(0,lt.encodeAddress)((0,lt.blake2AsHex)(r),Ee)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function ut(u){return u.map(({assetIn:e,assetOut:t,pool:r,poolId:s})=>r==="Stableswap"?{pool:{Stableswap:s},assetIn:e,assetOut:t}:{pool:r,assetIn:e,assetOut:t})}var Je=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},It=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},De=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},At=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 Ce=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;onChainAssets=[];onChainAssetsLoaded=!1;constructor(e){this.api=e,this.assetClient=new Le(this.api),this.xykClient=new ot(this.api),this.omniClient=new nt(this.api),this.lbpClient=new it(this.api),this.stableClient=new at(this.api)}async getPools(e){if(this.onChainAssetsLoaded||(this.onChainAssets=await this.assetClient.getOnChainAssets(),this.onChainAssetsLoaded=!0),e.length==0){let l=(await Promise.all([this.xykClient,this.omniClient,this.lbpClient,this.stableClient].filter(c=>c.isSupported()).map(c=>c.getPools()))).flat();return this.withMetadata(l)}let t=[];e.forEach(i=>{switch(i){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break;case"Stableswap":t.push(this.stableClient.getPools());break}});let s=(await Promise.all(t)).flat();return this.withMetadata(s)}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async withMetadata(e){let t=new Map(this.onChainAssets.map(r=>[r.id,r]));return e.map(r=>{let s=r.tokens.map(i=>{let l=t.get(i.id);return{...i,...l}});return{...r,tokens:s}})}async getPoolFees(e,t){switch(t.type){case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new Je(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,r,s,i){let l;this.isDirectOmnipoolTrade(i)?l=this.api.tx.omnipool.buy(t,e,r.toFixed(),s.toFixed()):l=this.api.tx.router.buy(e,t,r.toFixed(),s.toFixed(),ut(i));let c=()=>l;return{hex:l.toHex(),name:"RouterBuy",get:c}}buildSellTx(e,t,r,s,i){let l;this.isDirectOmnipoolTrade(i)?l=this.api.tx.omnipool.sell(e,t,r.toFixed(),s.toFixed()):l=this.api.tx.router.sell(e,t,r.toFixed(),s.toFixed(),ut(i));let c=()=>l;return{hex:l.toHex(),name:"RouterSell",get:c}}};var je=(u,e)=>u===e?0:u==null?e==null?0:-1:e==null?u==null?0:1:typeof u.compare=="function"?u.compare(e):typeof e.compare=="function"?-e.compare(u):u<e?-1:u>e?1:0;var ct=(u,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(u(t)+e(t))}};var fr=ct(()=>"illegal argument(s)"),Wt=u=>{throw new fr(u)};var Pr=ct(()=>"index out of bounds"),_t=u=>{throw new Pr(u)},pt=(u,e,t)=>(u<e||u>=t)&&_t(u);var Yt=23283064365386963e-26,mt=class{float(e=1){return this.int()*Yt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Yt-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var Rt=Math.random,Et=class extends mt{int(){return Rt()*4294967296>>>0}float(e=1){return Rt()*e}norm(e=1){return(Rt()-.5)*2*e}},$t=new Et;var Jt=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var jt=Object.getPrototypeOf({}),ht="function",Qt="string",Ge=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===ht)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===ht)return e.equiv(u)}else return u==e;return typeof u===Qt||typeof e===Qt?!1:(t=Object.getPrototypeOf(u),(t==null||t===jt)&&(t=Object.getPrototypeOf(e),t==null||t===jt)?xr(u,e):typeof u!==ht&&u.length!==void 0&&typeof e!==ht&&e.length!==void 0?br(u,e):u instanceof Set&&e instanceof Set?Sr(u,e):u instanceof Map&&e instanceof Map?yr(u,e):u instanceof Date&&e instanceof Date?u.getTime()===e.getTime():u instanceof RegExp&&e instanceof RegExp?u.toString()===e.toString():u!==u&&e!==e)},br=(u,e,t=Ge)=>{let r=u.length;if(r===e.length)for(;r-- >0&&t(u[r],e[r]););return r<0},Sr=(u,e,t=Ge)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),yr=(u,e,t=Ge)=>u.size===e.size&&t([...u].sort(),[...e].sort()),xr=(u,e,t=Ge)=>{if(Object.keys(u).length!==Object.keys(e).length)return!1;for(let r in u)if(!e.hasOwnProperty(r)||!t(u[r],e[r]))return!1;return!0};var Vt=(u,e)=>u!=null&&typeof u[e]=="function";var Zt=u=>Vt(u,"xform")?u.xform():u;var gt=Symbol(),kt=()=>{};var Kt=u=>u!=null&&typeof u[Symbol.iterator]=="function";var dt=class{value;constructor(e){this.value=e}deref(){return this.value}};var ft=u=>u instanceof dt;var er=u=>u instanceof dt?u.deref():u;function*tr(u,e){let t=Zt(u)([kt,kt,(r,s)=>s])[2];for(let r of e){let s=t(gt,r);if(ft(s)){s=er(s.deref()),s!==gt&&(yield s);return}s!==gt&&(yield s)}}var rr=(u,e)=>[u[0],u[1],e];function Qe(u,e){return Kt(e)?tr(Qe(u),e):t=>{let r=t[2];return rr(t,(s,i)=>r(s,u(i)))}}var qe=class{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return sr("next",this._head)}reverseIterator(){return sr("prev",this.tail)}clear(){this.release()}compare(e,t=je){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,l=0;for(;r-- >0&&l===0;)l=t(s.value,i.value),s=s.next,i=i.next;return l}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof qe||Jt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!Ge(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||je;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!ft(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&_t(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*sr(u,e){for(;e;)yield e.value,e=e[u]}var Se=class extends qe{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new Se(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new Se}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(pt(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(pt(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new Se,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=l=>({first(){return l.value},next(){return l!==s&&l.next?i(l.next):void 0}});return r?i(r):void 0}shuffle(e,t=$t){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&Wt("invalid indices: ${from} / ${to}");let i=new Se,l=this.nthCell(r);for(;l&&++r<=s;)i.push(l.value),l=l.next;return i}sort(e=je){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,l=0;for(let h=0;h<t&&(l++,i=i.next,!!i);h++);let c=t;for(;l>0||c>0&&i;){let h;l===0?(h=i,i=i.next,c--):!i||c===0||e(r.value,i.value)<=0?(h=r,r=r.next,l--):(h=i,i=i.next,c--),this._tail?this._tail.next=h:this._head=h,h.prev=this._tail,this._tail=h}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),pt(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new Se;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let l of r)this.insertBefore(s,l);else for(let l of r)this.push(l);return i}};var He=class{map;items;opts;_size;constructor(e,t){let r=Object.assign({maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0},t);this.map=r.map(),this.items=new Se,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}entries(){return Qe(e=>[e.k,e],this.items)}keys(){return Qe(e=>e.k,this.items)}values(){return Qe(e=>e.v,this.items)}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new He(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e);return this._size+=Math.max(0,r-(s?s.value.s:0)),this.ensureSize()&&this.doSetEntry(s,e,t,r),t}into(e){for(let t of e)this.set(t[0],t[1]);return this}getSet(e,t){let r=this.map.get(e);return r?Promise.resolve(this.resetEntry(r)):t().then(s=>this.set(e,s))}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let e=this.opts.release,t=this.opts.maxsize,r=this.opts.maxlen;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e&&e(s.k,s.v),this._size-=s.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release&&this.opts.release(t.k,t.v),this._size-=t.s}doSetEntry(e,t,r,s){e?(e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var Pt=class extends Ce{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new He(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let r=[t.address,e].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let i=await super.getPoolFees(e,t);return this.feeCache.set(r,i),i}}async destroy(){console.log(`Destroying pool cache!
2
+ Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var ve=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new ve(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,i,l,c){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=l,this.repayFeeApply=c}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(h=>[h.id,h])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:l,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(l)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let c=this.calculateTradeFee(t,r),h=ce(this.repayFeeApply?r.repayFee:r.exchangeFee),y=t.plus(c),w=this.calculateInGivenOut(e,y),B=e.balanceIn.div(this.maxInRatio);return w.isGreaterThan(B)&&i.push("MaxInRatioExceeded"),{amountIn:w,calculatedIn:w,amountOut:t,feePct:h,errors:i}}else{let c=this.calculateInGivenOut(e,t),h=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(h)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(l)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let c=this.calculateOutGivenIn(e,t),h=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(h)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:c,feePct:0,errors:i}}else{let c=this.calculateOutGivenIn(e,t),h=this.calculateTradeFee(c,r),y=ce(this.repayFeeApply?r.repayFee:r.exchangeFee),w=c.minus(h),B=e.balanceOut.div(this.maxOutRatio);return w.isGreaterThan(B)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:c,amountOut:w,feePct:y,errors:i}}}calculateInGivenOut(e,t){let r=ue.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?R:s}calculateOutGivenIn(e,t){let r=ue.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?R:s}spotPriceInGivenOut(e){let t=ue.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),W(ie,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=ue.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),W(ie,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let r=ue.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return I(r)}};var F=require("@galacticcouncil/math-omnipool"),U=class{static calculateSpotPrice(e,t,r,s){return(0,F.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,F.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,l,c,h,y){return(0,F.calculate_in_given_out)(e,t,r,s,i,l,c,h,y)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,F.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,l,c,h,y){return(0,F.calculate_out_given_in)(e,t,r,s,i,l,c,h,y)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,F.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,F.calculate_pool_trade_fee)(e,t,r)}static calculateShares(e,t,r,s){return(0,F.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,l,c,h){return(0,F.calculate_liquidity_out)(e,t,r,s,i,l,c,h)}static calculateLiquidityLRNAOut(e,t,r,s,i,l,c,h){return(0,F.calculate_liquidity_lrna_out)(e,t,r,s,i,l,c,h)}static calculateCapDifference(e,t,r,s){return(0,F.calculate_cap_difference)(e,t,r,s)}static verifyAssetCap(e,t,r,s){return(0,F.verify_asset_cap)(e,t,r,s)}static calculateLimitHubIn(e,t,r,s){return(0,F.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,F.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,F.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,F.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,F.is_remove_liquidity_allowed)(e)}};var Ie=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new Ie(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,i,l){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.hubAssetId=l}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(h=>[h.id,h])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:l,balanceOut:c,tradeableIn:s.tradeable,tradeableOut:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),l=i.minus(s),c=s===R?R:l.div(s).multipliedBy(100).decimalPlaces(2),h=[],y=U.isSellAllowed(e.tradeableIn),w=U.isBuyAllowed(e.tradeableOut);(!y||!w)&&h.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let B=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(B)&&h.push("MaxOutRatioExceeded");let T=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(T)&&h.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:c.toNumber(),errors:h}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),c=s.minus(i).div(s).multipliedBy(100).decimalPlaces(2),h=[],y=U.isSellAllowed(e.tradeableIn),w=U.isBuyAllowed(e.tradeableOut);(!y||!w)&&h.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let B=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(B)&&h.push("MaxInRatioExceeded");let T=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(T)&&h.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:c.toNumber(),errors:h}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=U.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?se(r.assetFee).toString():R.toString(),r?se(r.protocolFee).toString():R.toString()),i=I(s);return i.isNegative()?R:i}calculateLrnaInGivenOut(e,t,r){let s=U.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?se(r.assetFee).toString():R.toString()),i=I(s);return i.isNegative()?R:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=U.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?se(r.assetFee).toString():R.toString(),r?se(r.protocolFee).toString():R.toString()),i=I(s);return i.isNegative()?R:i}calculateOutGivenLrnaIn(e,t,r){let s=U.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?se(r.assetFee).toString():R.toString()),i=I(s);return i.isNegative()?R:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=U.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return I(t).shiftedBy(-1*(Re-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=U.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return I(t).shiftedBy(-1*(Re-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=U.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Re-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=U.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return I(t).shiftedBy(-1*(Re-e.decimalsIn)).decimalPlaces(0,1)}};var Ne=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new Ne(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,r,s,i,l,c,h,y){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.amplification=l,this.id=c,this.fee=h,this.totalIssuance=y}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(h=>[h.id,h])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,balanceIn:l,balanceOut:c,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?rt:s.tradeable,tradeableOut:this.id===t?rt:i.tradeable}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),l=ce(r.fee),c=[],h=U.isSellAllowed(e.tradeableIn),y=U.isBuyAllowed(e.tradeableOut);return(!h||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:l,errors:c}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),l=ce(r.fee),c=[],h=U.isSellAllowed(e.tradeableIn),y=U.isBuyAllowed(e.tradeableOut);return(!h||!y)&&c.push("TradeNotAllowed"),t.isLessThan(this.minTradingLimit)&&c.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:l,errors:c}}calculateIn(e,t,r){let s=ee.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?se(r.fee).toString():R.toString()),i=I(s);return i.isNegative()?R:i}calculateAddOneAsset(e,t,r){let s=ee.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?se(r.fee).toString():R.toString()),i=I(s);return i.isNegative()?R:i}calculateSharesForAmount(e,t,r){let s=ee.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?se(r.fee).toString():R.toString()),i=I(s);return i.isNegative()?R:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=W(ie,e.decimalsOut);return e.assetOut==this.id?this.calculateAddOneAsset(e,t):e.assetIn==this.id?this.calculateSharesForAmount(e,t):this.calculateIn(e,t)}calculateOut(e,t,r){let s=ee.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?se(r.fee).toString():R.toString()),i=I(s);return i.isNegative()?R:i}calculateWithdrawOneAsset(e,t,r){let s=ee.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?se(r.fee).toString():R.toString()),i=I(s);return i.isNegative()?R:i}calculateShares(e,t,r){let s=ee.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?se(r.fee).toString():R.toString()),i=I(s);return i.isNegative()?R:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=W(ie,e.decimalsIn);return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t):e.assetOut==this.id?this.calculateShares(e,t):this.calculateOut(e,t)}calculateTradeFee(e,t){let r=ee.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return I(r)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};var V=require("@galacticcouncil/math-xyk"),ye=class{static getSpotPrice(e,t,r){return(0,V.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,V.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,V.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,V.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,V.calculate_liquidity_in)(e,t,r)}static calculateShares(e,t,r){return(0,V.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,V.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,V.calculate_liquidity_out_asset_b)(e,t,r,s)}};var Ae=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Ae(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(h=>[h.id,h])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let l=I(s.balance),c=I(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:l,balanceOut:c}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),l=ce(r.exchangeFee),c=s.plus(i),h=[];t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let y=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(y)&&h.push("MaxOutRatioExceeded");let w=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(w)&&h.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:s,amountOut:t,feePct:l,errors:h}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),l=ce(r.exchangeFee),c=s.minus(i),h=[];t.isLessThan(this.minTradingLimit)&&h.push("InsufficientTradingAmount");let y=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(y)&&h.push("MaxInRatioExceeded");let w=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(w)&&h.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:c,feePct:l,errors:h}}calculateInGivenOut(e,t){let r=ye.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?R:s}calculateOutGivenIn(e,t){let r=ye.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=I(r);return s.isNegative()?R:s}spotPriceInGivenOut(e){let t=ye.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),W(ie,e.decimalsOut).toString());return I(t)}spotPriceOutGivenIn(e){let t=ye.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),W(ie,e.decimalsIn).toString());return I(t)}calculateTradeFee(e,t){let r=ye.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return I(r)}};var Ue=class{static get(e){switch(e.type){case"Xyk":return Ae.fromPool(e);case"Omnipool":return Ie.fromPool(e);case"Lbp":return ve.fromPool(e);case"Stableswap":return Ne.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Fe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ye,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),l=this.getPaths(e,null,s,t).map(c=>c[c.length-1].assetOut);return this.toAssets([...new Set(l)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,existentialDeposit:s.existentialDeposit,origin:s.origin,meta:s.meta}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(c=>this.validPath(c,r)).map(c=>this.toHops(c,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(r);return{assets:s,poolsMap:i}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,Ue.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,i])=>{let l=t.get(r);return{poolAddress:r,poolId:l?.id,pool:l?.type,assetIn:s,assetOut:i}})}toAssets(e,t){return e.map(r=>t.get(r))}};function Or(u,e){return u.minus(e).abs().div(u.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ze(u,e){return u.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Lt(u,e){return ie.minus(e.div(u)).multipliedBy(100).decimalPlaces(2)}function Mt(u,e){return e.div(u).minus(ie).multipliedBy(100).decimalPlaces(2)}var Ve=class extends Fe{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,l=s[s.length-1].amountOut;return i.isGreaterThan(l)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,l)=>i+l),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,l)=>i+l);return[r,s]}}getPoolFeeRange(e){let t=e.min?ce(e.min):void 0,r=e.max?ce(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,s),l=super.getPaths(e,t,i,s);if(l.length===0)throw new De(e,t);let c=l.map(async k=>await this.toSellSwaps(r,k,i)),h=await Promise.all(c),y=this.findBestSellRoute(h),w=y[0],B=y[y.length-1],T=this.isDirectTrade(y),L=y.map(k=>k.spotPrice.shiftedBy(-1*k.assetOutDecimals)).reduce((k,n)=>k.multipliedBy(n)),M=W(L,B.assetOutDecimals).decimalPlaces(0,1),J=w.amountIn.shiftedBy(-1*w.assetInDecimals).multipliedBy(M),C=ze(B.calculatedOut,J),Z=T?B.calculatedOut:this.calculateDelta0Y(w.amountIn,y,i),O=B.amountOut,pe=T?B.tradeFeePct:Lt(Z,O).toNumber(),ge=Z.minus(O),xe=this.getRouteFeeRange(y),j=k=>this.poolService.buildSellTx(e,t,w.amountIn,k,y.map(n=>n));return{type:"Sell",amountIn:w.amountIn,amountOut:B.amountOut,spotPrice:M,tradeFee:ge,tradeFeePct:pe,tradeFeeRange:xe,priceImpactPct:C.toNumber(),swaps:y,toTx:j,toHuman(){return{type:"Sell",amountIn:$(w.amountIn,w.assetInDecimals),amountOut:$(B.amountOut,B.assetOutDecimals),spotPrice:$(M,B.assetOutDecimals),tradeFee:$(ge,B.assetOutDecimals),tradeFeePct:pe,tradeFeeRange:xe,priceImpactPct:C.toNumber(),swaps:y.map(k=>k.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let l=t[i],c=r.get(l.poolAddress);if(c==null)throw new Error("Pool does not exit");let h=c.parsePair(l.assetIn,l.assetOut),y;i>0?y=s[i-1]:y=e;let w=c.calculateOutGivenIn(h,y);s.push(w)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let l=t[i],c=r.get(l.poolAddress);if(c==null)throw new Error("Pool does not exit");let h=c.parsePair(l.assetIn,l.assetOut),y;i>0?y=s[i-1].amountOut:y=W(I(e),h.decimalsIn).decimalPlaces(0,1);let w=await this.poolService.getPoolFees(h.assetOut,c),{amountOut:B,calculatedOut:T,feePct:L,errors:M}=c.validateAndSell(h,y,w),J=this.getPoolFeeRange(w),C=c.spotPriceOutGivenIn(h),Z=y.shiftedBy(-1*h.decimalsIn).multipliedBy(C),O=ze(T,Z);s.push({...l,assetInDecimals:h.decimalsIn,assetOutDecimals:h.decimalsOut,amountIn:y,calculatedOut:T,amountOut:B,spotPrice:C,tradeFeePct:L,tradeFeeRange:J,priceImpactPct:O.toNumber(),errors:M,toHuman(){return{...l,amountIn:$(y,h.decimalsIn),calculatedOut:$(T,h.decimalsOut),amountOut:$(B,h.decimalsOut),spotPrice:$(C,h.decimalsOut),tradeFeePct:L,tradeFeeRange:J,priceImpactPct:O.toNumber(),errors:M}}})}return s}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r),i=super.getPaths(e,t,s,r);if(i.length===0)return Promise.resolve(void 0);let l=i.map(async T=>await this.toSellSwaps("1",T,s)),c=await Promise.all(l),h=this.findBestSellRoute(c),y=h.map(T=>T.spotPrice.shiftedBy(-1*T.assetOutDecimals)).reduce((T,L)=>T.multipliedBy(L)),w=h[h.length-1].assetOutDecimals;return{amount:W(y,w).decimalPlaces(0,1),decimals:w}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,l=s[0].amountIn;return i.isGreaterThan(l)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,s),l=super.getPaths(e,t,i,s);if(l.length===0)throw new De(e,t);let c=l.map(async k=>await this.toBuySwaps(r,k,i)),h=await Promise.all(c),y=this.findBestBuyRoute(h),w=y[y.length-1],B=y[0],T=this.isDirectTrade(y),L=y.map(k=>k.spotPrice.shiftedBy(-1*k.assetInDecimals)).reduce((k,n)=>k.multipliedBy(n)),M=W(L,B.assetInDecimals).decimalPlaces(0,1),J=w.amountOut.shiftedBy(-1*w.assetOutDecimals).multipliedBy(M),C;B.calculatedIn.isZero()?C=-100:C=ze(J,B.calculatedIn).toNumber();let Z=T?B.calculatedIn:this.calculateDelta0X(w.amountOut,y,i),O=B.amountIn,pe=T?B.tradeFeePct:Mt(Z,O),ge=O.minus(Z),xe=this.getRouteFeeRange(y),j=k=>this.poolService.buildBuyTx(e,t,w.amountOut,k,y.map(n=>n));return{type:"Buy",amountOut:w.amountOut,amountIn:B.amountIn,spotPrice:M,tradeFee:ge,tradeFeePct:pe,tradeFeeRange:xe,priceImpactPct:C,swaps:y,toTx:j,toHuman(){return{type:"Buy",amountOut:$(w.amountOut,w.assetOutDecimals),amountIn:$(B.amountIn,B.assetInDecimals),spotPrice:$(M,B.assetInDecimals),tradeFee:$(ge,B.assetInDecimals),tradeFeePct:pe,tradeFeeRange:xe,priceImpactPct:C,swaps:y.map(k=>k.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let l=t[i],c=r.get(l.poolAddress);if(c==null)throw new Error("Pool does not exit");let h=c.parsePair(l.assetIn,l.assetOut),y;i==t.length-1?y=e:y=s[0];let w=c.calculateInGivenOut(h,y);s.unshift(w)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let l=t[i],c=r.get(l.poolAddress);if(c==null)throw new Error("Pool does not exit");let h=c.parsePair(l.assetIn,l.assetOut),y;i==t.length-1?y=W(I(e),h.decimalsOut).decimalPlaces(0,1):y=s[0].amountIn;let w=await this.poolService.getPoolFees(h.assetIn,c),{amountIn:B,calculatedIn:T,feePct:L,errors:M}=c.validateAndBuy(h,y,w),J=this.getPoolFeeRange(w),C=c.spotPriceInGivenOut(h),Z=y.shiftedBy(-1*h.decimalsOut).multipliedBy(C),O;T.isZero()?O=-100:O=ze(Z,T).toNumber(),s.unshift({...l,assetInDecimals:h.decimalsIn,assetOutDecimals:h.decimalsOut,amountOut:y,calculatedIn:T,amountIn:B,spotPrice:C,tradeFeePct:L,tradeFeeRange:J,priceImpactPct:O,errors:M,toHuman(){return{...l,amountOut:$(y,h.decimalsOut),calculatedIn:$(T,h.decimalsIn),amountIn:$(B,h.decimalsIn),spotPrice:$(C,h.decimalsIn),tradeFeePct:L,tradeFeeRange:J,priceImpactPct:O,errors:M}}})}return s}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,scale});