@galacticcouncil/sdk 0.6.3 → 0.6.4
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 +1 -1
- package/build/index.mjs +1 -1
- package/build/types/types.d.ts +1 -0
- package/package.json +1 -1
package/build/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use strict";var En=Object.create;var _t=Object.defineProperty;var Rn=Object.getOwnPropertyDescriptor;var Mn=Object.getOwnPropertyNames;var Ln=Object.getPrototypeOf,Dn=Object.prototype.hasOwnProperty;var Ht=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Gn=(i,e)=>{for(var t in e)_t(i,t,{get:e[t],enumerable:!0})},an=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Mn(e))!Dn.call(i,r)&&r!==t&&_t(i,r,{get:()=>e[r],enumerable:!(n=Rn(e,r))||n.enumerable});return i};var Wt=(i,e,t)=>(t=i!=null?En(Ln(i)):{},an(e||!i||!i.__esModule?_t(t,"default",{value:i,enumerable:!0}):t,i)),Cn=i=>an(_t({},"__esModule",{value:!0}),i);var pn=Ht((Wr,qe)=>{var Un={},F,{TextEncoder:zn,TextDecoder:Xn}=require("util"),Z=0,gt=null;function ht(){return(gt===null||gt.buffer!==F.memory.buffer)&&(gt=new Uint8Array(F.memory.buffer)),gt}var bt=new zn("utf-8"),$n=typeof bt.encodeInto=="function"?function(i,e){return bt.encodeInto(i,e)}:function(i,e){let t=bt.encode(i);return e.set(t),{read:i.length,written:t.length}};function oe(i,e,t){if(t===void 0){let u=bt.encode(i),p=e(u.length);return ht().subarray(p,p+u.length).set(u),Z=u.length,p}let n=i.length,r=e(n),o=ht(),a=0;for(;a<n;a++){let u=i.charCodeAt(a);if(u>127)break;o[r+a]=u}if(a!==n){a!==0&&(i=i.slice(a)),r=t(r,n,n=a+i.length*3);let u=ht().subarray(r+a,r+n),p=$n(i,u);a+=p.written}return Z=a,r}var ft=null;function Ie(){return(ft===null||ft.buffer!==F.memory.buffer)&&(ft=new Int32Array(F.memory.buffer)),ft}var _n=new Xn("utf-8",{ignoreBOM:!0,fatal:!0});_n.decode();function ot(i,e){return _n.decode(ht().subarray(i,i+e))}qe.exports.calculate_pool_trade_fee=function(i,e,t){try{let o=F.__wbindgen_add_to_stack_pointer(-16),a=oe(i,F.__wbindgen_malloc,F.__wbindgen_realloc),u=Z;F.calculate_pool_trade_fee(o,a,u,e,t);var n=Ie()[o/4+0],r=Ie()[o/4+1];return ot(n,r)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(n,r)}};qe.exports.get_spot_price=function(i,e,t,n,r){try{let u=F.__wbindgen_add_to_stack_pointer(-16),p=oe(i,F.__wbindgen_malloc,F.__wbindgen_realloc),b=Z,x=oe(e,F.__wbindgen_malloc,F.__wbindgen_realloc),O=Z,N=oe(t,F.__wbindgen_malloc,F.__wbindgen_realloc),A=Z,k=oe(n,F.__wbindgen_malloc,F.__wbindgen_realloc),L=Z,E=oe(r,F.__wbindgen_malloc,F.__wbindgen_realloc),q=Z;F.get_spot_price(u,p,b,x,O,N,A,k,L,E,q);var o=Ie()[u/4+0],a=Ie()[u/4+1];return ot(o,a)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(o,a)}};qe.exports.calculate_out_given_in=function(i,e,t,n,r){try{let u=F.__wbindgen_add_to_stack_pointer(-16),p=oe(i,F.__wbindgen_malloc,F.__wbindgen_realloc),b=Z,x=oe(e,F.__wbindgen_malloc,F.__wbindgen_realloc),O=Z,N=oe(t,F.__wbindgen_malloc,F.__wbindgen_realloc),A=Z,k=oe(n,F.__wbindgen_malloc,F.__wbindgen_realloc),L=Z,E=oe(r,F.__wbindgen_malloc,F.__wbindgen_realloc),q=Z;F.calculate_out_given_in(u,p,b,x,O,N,A,k,L,E,q);var o=Ie()[u/4+0],a=Ie()[u/4+1];return ot(o,a)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(o,a)}};qe.exports.calculate_in_given_out=function(i,e,t,n,r){try{let u=F.__wbindgen_add_to_stack_pointer(-16),p=oe(i,F.__wbindgen_malloc,F.__wbindgen_realloc),b=Z,x=oe(e,F.__wbindgen_malloc,F.__wbindgen_realloc),O=Z,N=oe(t,F.__wbindgen_malloc,F.__wbindgen_realloc),A=Z,k=oe(n,F.__wbindgen_malloc,F.__wbindgen_realloc),L=Z,E=oe(r,F.__wbindgen_malloc,F.__wbindgen_realloc),q=Z;F.calculate_in_given_out(u,p,b,x,O,N,A,k,L,E,q);var o=Ie()[u/4+0],a=Ie()[u/4+1];return ot(o,a)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(o,a)}};qe.exports.calculate_linear_weights=function(i,e,t,n,r){try{let u=F.__wbindgen_add_to_stack_pointer(-16),p=oe(i,F.__wbindgen_malloc,F.__wbindgen_realloc),b=Z,x=oe(e,F.__wbindgen_malloc,F.__wbindgen_realloc),O=Z,N=oe(t,F.__wbindgen_malloc,F.__wbindgen_realloc),A=Z,k=oe(n,F.__wbindgen_malloc,F.__wbindgen_realloc),L=Z,E=oe(r,F.__wbindgen_malloc,F.__wbindgen_realloc),q=Z;F.calculate_linear_weights(u,p,b,x,O,N,A,k,L,E,q);var o=Ie()[u/4+0],a=Ie()[u/4+1];return ot(o,a)}finally{F.__wbindgen_add_to_stack_pointer(16),F.__wbindgen_free(o,a)}};var Yn=require("path").join(__dirname,"hydra_dx_wasm_bg.wasm"),Jn=require("fs").readFileSync(Yn),Vn=new WebAssembly.Module(Jn),Kn=new WebAssembly.Instance(Vn,Un);F=Kn.exports;qe.exports.__wasm=F});var Fn=Ht((Hs,Q)=>{var rr={},l,{TextEncoder:or,TextDecoder:ir}=require("util"),I=0,At=null;function Et(){return(At===null||At.byteLength===0)&&(At=new Uint8Array(l.memory.buffer)),At}var Rt=new or("utf-8"),sr=typeof Rt.encodeInto=="function"?function(i,e){return Rt.encodeInto(i,e)}:function(i,e){let t=Rt.encode(i);return e.set(t),{read:i.length,written:t.length}};function B(i,e,t){if(t===void 0){let u=Rt.encode(i),p=e(u.length)>>>0;return Et().subarray(p,p+u.length).set(u),I=u.length,p}let n=i.length,r=e(n)>>>0,o=Et(),a=0;for(;a<n;a++){let u=i.charCodeAt(a);if(u>127)break;o[r+a]=u}if(a!==n){a!==0&&(i=i.slice(a)),r=t(r,n,n=a+i.length*3)>>>0;let u=Et().subarray(r+a,r+n),p=sr(i,u);a+=p.written}return I=a,r}var kt=null;function z(){return(kt===null||kt.byteLength===0)&&(kt=new Int32Array(l.memory.buffer)),kt}var Nn=new ir("utf-8",{ignoreBOM:!0,fatal:!0});Nn.decode();function ce(i,e){return i=i>>>0,Nn.decode(Et().subarray(i,i+e))}Q.exports.calculate_shares=function(i,e,t,n){let r,o;try{let p=l.__wbindgen_add_to_stack_pointer(-16),b=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),x=I,O=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),N=I,A=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),k=I,L=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),E=I;l.calculate_shares(p,b,x,O,N,A,k,L,E);var a=z()[p/4+0],u=z()[p/4+1];return r=a,o=u,ce(a,u)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(r,o)}};Q.exports.calculate_withdrawal_fee=function(i,e,t){let n,r;try{let u=l.__wbindgen_add_to_stack_pointer(-16),p=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),b=I,x=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),O=I,N=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),A=I;l.calculate_withdrawal_fee(u,p,b,x,O,N,A);var o=z()[u/4+0],a=z()[u/4+1];return n=o,r=a,ce(o,a)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(n,r)}};Q.exports.calculate_liquidity_out=function(i,e,t,n,r,o,a,u){let p,b;try{let N=l.__wbindgen_add_to_stack_pointer(-16),A=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),k=I,L=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),E=I,q=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),v=I,Y=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),ee=I,K=B(r,l.__wbindgen_malloc,l.__wbindgen_realloc),X=I,G=B(o,l.__wbindgen_malloc,l.__wbindgen_realloc),s=I,c=B(a,l.__wbindgen_malloc,l.__wbindgen_realloc),_=I,f=B(u,l.__wbindgen_malloc,l.__wbindgen_realloc),m=I;l.calculate_liquidity_out(N,A,k,L,E,q,v,Y,ee,K,X,G,s,c,_,f,m);var x=z()[N/4+0],O=z()[N/4+1];return p=x,b=O,ce(x,O)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(p,b)}};Q.exports.calculate_liquidity_lrna_out=function(i,e,t,n,r,o,a,u){let p,b;try{let N=l.__wbindgen_add_to_stack_pointer(-16),A=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),k=I,L=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),E=I,q=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),v=I,Y=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),ee=I,K=B(r,l.__wbindgen_malloc,l.__wbindgen_realloc),X=I,G=B(o,l.__wbindgen_malloc,l.__wbindgen_realloc),s=I,c=B(a,l.__wbindgen_malloc,l.__wbindgen_realloc),_=I,f=B(u,l.__wbindgen_malloc,l.__wbindgen_realloc),m=I;l.calculate_liquidity_lrna_out(N,A,k,L,E,q,v,Y,ee,K,X,G,s,c,_,f,m);var x=z()[N/4+0],O=z()[N/4+1];return p=x,b=O,ce(x,O)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(p,b)}};Q.exports.recalculate_asset_fee=function(i,e,t,n,r,o,a,u,p){let b,x;try{let A=l.__wbindgen_add_to_stack_pointer(-16),k=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),L=I,E=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),q=I,v=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),Y=I,ee=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),K=I,X=B(r,l.__wbindgen_malloc,l.__wbindgen_realloc),G=I,s=B(o,l.__wbindgen_malloc,l.__wbindgen_realloc),c=I,_=B(a,l.__wbindgen_malloc,l.__wbindgen_realloc),f=I,m=B(u,l.__wbindgen_malloc,l.__wbindgen_realloc),h=I,P=B(p,l.__wbindgen_malloc,l.__wbindgen_realloc),d=I;l.recalculate_asset_fee(A,k,L,E,q,v,Y,ee,K,X,G,s,c,_,f,m,h,P,d);var O=z()[A/4+0],N=z()[A/4+1];return b=O,x=N,ce(O,N)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(b,x)}};Q.exports.recalculate_protocol_fee=function(i,e,t,n,r,o,a,u,p){let b,x;try{let A=l.__wbindgen_add_to_stack_pointer(-16),k=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),L=I,E=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),q=I,v=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),Y=I,ee=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),K=I,X=B(r,l.__wbindgen_malloc,l.__wbindgen_realloc),G=I,s=B(o,l.__wbindgen_malloc,l.__wbindgen_realloc),c=I,_=B(a,l.__wbindgen_malloc,l.__wbindgen_realloc),f=I,m=B(u,l.__wbindgen_malloc,l.__wbindgen_realloc),h=I,P=B(p,l.__wbindgen_malloc,l.__wbindgen_realloc),d=I;l.recalculate_protocol_fee(A,k,L,E,q,v,Y,ee,K,X,G,s,c,_,f,m,h,P,d);var O=z()[A/4+0],N=z()[A/4+1];return b=O,x=N,ce(O,N)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(b,x)}};Q.exports.calculate_out_given_in=function(i,e,t,n,r,o,a,u,p){let b,x;try{let A=l.__wbindgen_add_to_stack_pointer(-16),k=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),L=I,E=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),q=I,v=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),Y=I,ee=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),K=I,X=B(r,l.__wbindgen_malloc,l.__wbindgen_realloc),G=I,s=B(o,l.__wbindgen_malloc,l.__wbindgen_realloc),c=I,_=B(a,l.__wbindgen_malloc,l.__wbindgen_realloc),f=I,m=B(u,l.__wbindgen_malloc,l.__wbindgen_realloc),h=I,P=B(p,l.__wbindgen_malloc,l.__wbindgen_realloc),d=I;l.calculate_out_given_in(A,k,L,E,q,v,Y,ee,K,X,G,s,c,_,f,m,h,P,d);var O=z()[A/4+0],N=z()[A/4+1];return b=O,x=N,ce(O,N)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(b,x)}};Q.exports.calculate_out_given_lrna_in=function(i,e,t,n,r){let o,a;try{let b=l.__wbindgen_add_to_stack_pointer(-16),x=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),O=I,N=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),A=I,k=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),L=I,E=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),q=I,v=B(r,l.__wbindgen_malloc,l.__wbindgen_realloc),Y=I;l.calculate_out_given_lrna_in(b,x,O,N,A,k,L,E,q,v,Y);var u=z()[b/4+0],p=z()[b/4+1];return o=u,a=p,ce(u,p)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(o,a)}};Q.exports.calculate_in_given_out=function(i,e,t,n,r,o,a,u,p){let b,x;try{let A=l.__wbindgen_add_to_stack_pointer(-16),k=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),L=I,E=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),q=I,v=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),Y=I,ee=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),K=I,X=B(r,l.__wbindgen_malloc,l.__wbindgen_realloc),G=I,s=B(o,l.__wbindgen_malloc,l.__wbindgen_realloc),c=I,_=B(a,l.__wbindgen_malloc,l.__wbindgen_realloc),f=I,m=B(u,l.__wbindgen_malloc,l.__wbindgen_realloc),h=I,P=B(p,l.__wbindgen_malloc,l.__wbindgen_realloc),d=I;l.calculate_in_given_out(A,k,L,E,q,v,Y,ee,K,X,G,s,c,_,f,m,h,P,d);var O=z()[A/4+0],N=z()[A/4+1];return b=O,x=N,ce(O,N)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(b,x)}};Q.exports.calculate_lrna_in_given_out=function(i,e,t,n,r){let o,a;try{let b=l.__wbindgen_add_to_stack_pointer(-16),x=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),O=I,N=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),A=I,k=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),L=I,E=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),q=I,v=B(r,l.__wbindgen_malloc,l.__wbindgen_realloc),Y=I;l.calculate_lrna_in_given_out(b,x,O,N,A,k,L,E,q,v,Y);var u=z()[b/4+0],p=z()[b/4+1];return o=u,a=p,ce(u,p)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(o,a)}};Q.exports.calculate_spot_price=function(i,e,t,n){let r,o;try{let p=l.__wbindgen_add_to_stack_pointer(-16),b=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),x=I,O=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),N=I,A=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),k=I,L=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),E=I;l.calculate_spot_price(p,b,x,O,N,A,k,L,E);var a=z()[p/4+0],u=z()[p/4+1];return r=a,o=u,ce(a,u)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(r,o)}};Q.exports.calculate_lrna_spot_price=function(i,e){let t,n;try{let a=l.__wbindgen_add_to_stack_pointer(-16),u=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),p=I,b=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),x=I;l.calculate_lrna_spot_price(a,u,p,b,x);var r=z()[a/4+0],o=z()[a/4+1];return t=r,n=o,ce(r,o)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(t,n)}};Q.exports.calculate_cap_difference=function(i,e,t,n){let r,o;try{let p=l.__wbindgen_add_to_stack_pointer(-16),b=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),x=I,O=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),N=I,A=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),k=I,L=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),E=I;l.calculate_cap_difference(p,b,x,O,N,A,k,L,E);var a=z()[p/4+0],u=z()[p/4+1];return r=a,o=u,ce(a,u)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(r,o)}};Q.exports.verify_asset_cap=function(i,e,t,n){let r=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),o=I,a=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),u=I,p=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),b=I,x=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),O=I;return l.verify_asset_cap(r,o,a,u,p,b,x,O)!==0};Q.exports.calculate_tvl_cap_difference=function(i,e,t,n,r,o){let a,u;try{let x=l.__wbindgen_add_to_stack_pointer(-16),O=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),N=I,A=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),k=I,L=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),E=I,q=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),v=I,Y=B(r,l.__wbindgen_malloc,l.__wbindgen_realloc),ee=I,K=B(o,l.__wbindgen_malloc,l.__wbindgen_realloc),X=I;l.calculate_tvl_cap_difference(x,O,N,A,k,L,E,q,v,Y,ee,K,X);var p=z()[x/4+0],b=z()[x/4+1];return a=p,u=b,ce(p,b)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(a,u)}};Q.exports.calculate_liquidity_hub_in=function(i,e,t,n){let r,o;try{let p=l.__wbindgen_add_to_stack_pointer(-16),b=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),x=I,O=B(e,l.__wbindgen_malloc,l.__wbindgen_realloc),N=I,A=B(t,l.__wbindgen_malloc,l.__wbindgen_realloc),k=I,L=B(n,l.__wbindgen_malloc,l.__wbindgen_realloc),E=I;l.calculate_liquidity_hub_in(p,b,x,O,N,A,k,L,E);var a=z()[p/4+0],u=z()[p/4+1];return r=a,o=u,ce(a,u)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(r,o)}};Q.exports.is_sell_allowed=function(i){return l.is_sell_allowed(i)!==0};Q.exports.is_buy_allowed=function(i){return l.is_buy_allowed(i)!==0};Q.exports.is_add_liquidity_allowed=function(i){return l.is_add_liquidity_allowed(i)!==0};Q.exports.is_remove_liquidity_allowed=function(i){return l.is_remove_liquidity_allowed(i)!==0};Q.exports.calculate_pool_trade_fee=function(i,e,t){let n,r;try{let u=l.__wbindgen_add_to_stack_pointer(-16),p=B(i,l.__wbindgen_malloc,l.__wbindgen_realloc),b=I;l.calculate_pool_trade_fee(u,p,b,e,t);var o=z()[u/4+0],a=z()[u/4+1];return n=o,r=a,ce(o,a)}finally{l.__wbindgen_add_to_stack_pointer(16),l.__wbindgen_free(n,r)}};var ar=require("path").join(__dirname,"hydra_dx_wasm_bg.wasm"),lr=require("fs").readFileSync(ar),cr=new WebAssembly.Module(lr),ur=new WebAssembly.Instance(cr,rr);l=ur.exports;Q.exports.__wasm=l});var kn=Ht((oa,Ne)=>{var _r={},T,{TextEncoder:pr,TextDecoder:dr}=require("util"),J=0,Mt=null;function Dt(){return(Mt===null||Mt.buffer!==T.memory.buffer)&&(Mt=new Uint8Array(T.memory.buffer)),Mt}var Gt=new pr("utf-8"),mr=typeof Gt.encodeInto=="function"?function(i,e){return Gt.encodeInto(i,e)}:function(i,e){let t=Gt.encode(i);return e.set(t),{read:i.length,written:t.length}};function V(i,e,t){if(t===void 0){let u=Gt.encode(i),p=e(u.length);return Dt().subarray(p,p+u.length).set(u),J=u.length,p}let n=i.length,r=e(n),o=Dt(),a=0;for(;a<n;a++){let u=i.charCodeAt(a);if(u>127)break;o[r+a]=u}if(a!==n){a!==0&&(i=i.slice(a)),r=t(r,n,n=a+i.length*3);let u=Dt().subarray(r+a,r+n),p=mr(i,u);a+=p.written}return J=a,r}var Lt=null;function ue(){return(Lt===null||Lt.buffer!==T.memory.buffer)&&(Lt=new Int32Array(T.memory.buffer)),Lt}var An=new dr("utf-8",{ignoreBOM:!0,fatal:!0});An.decode();function Ge(i,e){return An.decode(Dt().subarray(i,i+e))}Ne.exports.calculate_pool_trade_fee=function(i,e,t){try{let o=T.__wbindgen_add_to_stack_pointer(-16),a=V(i,T.__wbindgen_malloc,T.__wbindgen_realloc),u=J;T.calculate_pool_trade_fee(o,a,u,e,t);var n=ue()[o/4+0],r=ue()[o/4+1];return Ge(n,r)}finally{T.__wbindgen_add_to_stack_pointer(16),T.__wbindgen_free(n,r)}};Ne.exports.get_spot_price=function(i,e,t){try{let o=T.__wbindgen_add_to_stack_pointer(-16),a=V(i,T.__wbindgen_malloc,T.__wbindgen_realloc),u=J,p=V(e,T.__wbindgen_malloc,T.__wbindgen_realloc),b=J,x=V(t,T.__wbindgen_malloc,T.__wbindgen_realloc),O=J;T.get_spot_price(o,a,u,p,b,x,O);var n=ue()[o/4+0],r=ue()[o/4+1];return Ge(n,r)}finally{T.__wbindgen_add_to_stack_pointer(16),T.__wbindgen_free(n,r)}};Ne.exports.calculate_out_given_in=function(i,e,t){try{let o=T.__wbindgen_add_to_stack_pointer(-16),a=V(i,T.__wbindgen_malloc,T.__wbindgen_realloc),u=J,p=V(e,T.__wbindgen_malloc,T.__wbindgen_realloc),b=J,x=V(t,T.__wbindgen_malloc,T.__wbindgen_realloc),O=J;T.calculate_out_given_in(o,a,u,p,b,x,O);var n=ue()[o/4+0],r=ue()[o/4+1];return Ge(n,r)}finally{T.__wbindgen_add_to_stack_pointer(16),T.__wbindgen_free(n,r)}};Ne.exports.calculate_in_given_out=function(i,e,t){try{let o=T.__wbindgen_add_to_stack_pointer(-16),a=V(i,T.__wbindgen_malloc,T.__wbindgen_realloc),u=J,p=V(e,T.__wbindgen_malloc,T.__wbindgen_realloc),b=J,x=V(t,T.__wbindgen_malloc,T.__wbindgen_realloc),O=J;T.calculate_in_given_out(o,a,u,p,b,x,O);var n=ue()[o/4+0],r=ue()[o/4+1];return Ge(n,r)}finally{T.__wbindgen_add_to_stack_pointer(16),T.__wbindgen_free(n,r)}};Ne.exports.calculate_liquidity_in=function(i,e,t){try{let o=T.__wbindgen_add_to_stack_pointer(-16),a=V(i,T.__wbindgen_malloc,T.__wbindgen_realloc),u=J,p=V(e,T.__wbindgen_malloc,T.__wbindgen_realloc),b=J,x=V(t,T.__wbindgen_malloc,T.__wbindgen_realloc),O=J;T.calculate_liquidity_in(o,a,u,p,b,x,O);var n=ue()[o/4+0],r=ue()[o/4+1];return Ge(n,r)}finally{T.__wbindgen_add_to_stack_pointer(16),T.__wbindgen_free(n,r)}};Ne.exports.calculate_shares=function(i,e,t){try{let o=T.__wbindgen_add_to_stack_pointer(-16),a=V(i,T.__wbindgen_malloc,T.__wbindgen_realloc),u=J,p=V(e,T.__wbindgen_malloc,T.__wbindgen_realloc),b=J,x=V(t,T.__wbindgen_malloc,T.__wbindgen_realloc),O=J;T.calculate_shares(o,a,u,p,b,x,O);var n=ue()[o/4+0],r=ue()[o/4+1];return Ge(n,r)}finally{T.__wbindgen_add_to_stack_pointer(16),T.__wbindgen_free(n,r)}};Ne.exports.calculate_liquidity_out_asset_a=function(i,e,t,n){try{let a=T.__wbindgen_add_to_stack_pointer(-16),u=V(i,T.__wbindgen_malloc,T.__wbindgen_realloc),p=J,b=V(e,T.__wbindgen_malloc,T.__wbindgen_realloc),x=J,O=V(t,T.__wbindgen_malloc,T.__wbindgen_realloc),N=J,A=V(n,T.__wbindgen_malloc,T.__wbindgen_realloc),k=J;T.calculate_liquidity_out_asset_a(a,u,p,b,x,O,N,A,k);var r=ue()[a/4+0],o=ue()[a/4+1];return Ge(r,o)}finally{T.__wbindgen_add_to_stack_pointer(16),T.__wbindgen_free(r,o)}};Ne.exports.calculate_liquidity_out_asset_b=function(i,e,t,n){try{let a=T.__wbindgen_add_to_stack_pointer(-16),u=V(i,T.__wbindgen_malloc,T.__wbindgen_realloc),p=J,b=V(e,T.__wbindgen_malloc,T.__wbindgen_realloc),x=J,O=V(t,T.__wbindgen_malloc,T.__wbindgen_realloc),N=J,A=V(n,T.__wbindgen_malloc,T.__wbindgen_realloc),k=J;T.calculate_liquidity_out_asset_b(a,u,p,b,x,O,N,A,k);var r=ue()[a/4+0],o=ue()[a/4+1];return Ge(r,o)}finally{T.__wbindgen_add_to_stack_pointer(16),T.__wbindgen_free(r,o)}};var gr=require("path").join(__dirname,"hydra_dx_wasm_bg.wasm"),fr=require("fs").readFileSync(gr),hr=new WebAssembly.Module(fr),br=new WebAssembly.Instance(hr,_r);T=br.exports;Ne.exports.__wasm=T});var Pr={};Gn(Pr,{AssetClient:()=>Xe,AssetNotFound:()=>Kt,BASILISK_PARACHAIN_ID:()=>$r,BalanceClient:()=>$e,BigNumber:()=>ve,CachingPoolService:()=>Ft,DECIMAL_PLACES:()=>un,DENOMINATOR:()=>Jt,HYDRADX_PARACHAIN_ID:()=>Xr,HYDRADX_SS58_PREFIX:()=>dn,INFINITY:()=>Wn,LbpMath:()=>we,LbpPool:()=>Le,ONE:()=>Oe,OmniMath:()=>ge,OmniPool:()=>De,PoolConfigNotFound:()=>Vt,PoolError:()=>rt,PoolFactory:()=>Ze,PoolNotFound:()=>st,PoolService:()=>Je,PoolType:()=>Se,ProviderConfigNotFound:()=>Qt,RUNTIME_DECIMALS:()=>it,RouteNotFound:()=>Ye,Router:()=>We,SYSTEM_ASSET_DECIMALS:()=>zr,SYSTEM_ASSET_ID:()=>ze,StorageConfigNotFound:()=>jt,SubscriptionNotSupported:()=>Zt,TradeRouter:()=>ct,TradeType:()=>Yt,XykMath:()=>Fe,XykPool:()=>Ce,ZERO:()=>re,bnum:()=>D,calculateBuyFee:()=>sn,calculateDiffToAvg:()=>wr,calculateDiffToRef:()=>Qe,calculateSellFee:()=>on,scale:()=>de});module.exports=Cn(Pr);var pt=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 qn=4,tt=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 pt,a=[];for(a.push([t,""]),o.enqueue(a);o.size()>0;){let u=o.dequeue();if(u==null||u.length>qn)return r;let p=u[u.length-1];(n===null||p[0]===n)&&r.push(u),e[p[0]].forEach(x=>{if(this.isNotVisited(x,u)){let O=[...u];O.push(x),o.enqueue(O)}})}return r}buildAndPopulateGraph(e,t){let n=e[e.length-1],r=[];for(let o=0;o<=parseInt(n);o++)r.push([]);for(let[o,a,u]of t){let p=parseInt(a),b=parseInt(u);r[p].push([b,o])}return r}};function Ut(i){let e={};for(let t of i){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 a=[t.address,t.tokens[r].id,t.tokens[o].id];e[t.tokens[r].id].push(a)}}}return e}var nt=class{getProposals(e,t,n){let r=Ut(n),o=Object.keys(r),a=o.map(x=>r[x]).flat(),u=new tt,p=u.buildAndPopulateGraph(o,a),b=u.findPaths(p,parseInt(e),t?parseInt(t):null);return this.parsePaths(b)}parsePaths(e){let t=[];for(let n of e){let r=[];for(let o=0;o<n.length;o++){let a=n[o],u=n[o+1];if(u==null)break;r.push(this.toEdge(a,u))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var Hn=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,zt=Math.ceil,xe=Math.floor,me="[BigNumber Error] ",ln=me+"Number primitive has more than 15 significant digits: ",Pe=1e14,C=14,Xt=9007199254740991,$t=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Re=1e7,se=1e9;function cn(i){var e,t,n,r=v.prototype={constructor:v,toString:null,valueOf:null},o=new v(1),a=20,u=4,p=-7,b=21,x=-1e7,O=1e7,N=!1,A=1,k=0,L={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},E="0123456789abcdefghijklmnopqrstuvwxyz",q=!0;function v(s,c){var _,f,m,h,P,d,g,y,w=this;if(!(w instanceof v))return new v(s,c);if(c==null){if(s&&s._isBigNumber===!0){w.s=s.s,!s.c||s.e>O?w.c=w.e=null:s.e<x?w.c=[w.e=0]:(w.e=s.e,w.c=s.c.slice());return}if((d=typeof s=="number")&&s*0==0){if(w.s=1/s<0?(s=-s,-1):1,s===~~s){for(h=0,P=s;P>=10;P/=10,h++);h>O?w.c=w.e=null:(w.e=h,w.c=[s]);return}y=String(s)}else{if(!Hn.test(y=String(s)))return n(w,y,d);w.s=y.charCodeAt(0)==45?(y=y.slice(1),-1):1}(h=y.indexOf("."))>-1&&(y=y.replace(".","")),(P=y.search(/e/i))>0?(h<0&&(h=P),h+=+y.slice(P+1),y=y.substring(0,P)):h<0&&(h=y.length)}else{if(j(c,2,E.length,"Base"),c==10&&q)return w=new v(s),X(w,a+w.e+1,u);if(y=String(s),d=typeof s=="number"){if(s*0!=0)return n(w,y,d,c);if(w.s=1/s<0?(y=y.slice(1),-1):1,v.DEBUG&&y.replace(/^0\.0*|\./,"").length>15)throw Error(ln+s)}else w.s=y.charCodeAt(0)===45?(y=y.slice(1),-1):1;for(_=E.slice(0,c),h=P=0,g=y.length;P<g;P++)if(_.indexOf(f=y.charAt(P))<0){if(f=="."){if(P>h){h=g;continue}}else if(!m&&(y==y.toUpperCase()&&(y=y.toLowerCase())||y==y.toLowerCase()&&(y=y.toUpperCase()))){m=!0,P=-1,h=0;continue}return n(w,String(s),d,c)}d=!1,y=t(y,c,10,w.s),(h=y.indexOf("."))>-1?y=y.replace(".",""):h=y.length}for(P=0;y.charCodeAt(P)===48;P++);for(g=y.length;y.charCodeAt(--g)===48;);if(y=y.slice(P,++g)){if(g-=P,d&&v.DEBUG&&g>15&&(s>Xt||s!==xe(s)))throw Error(ln+w.s*s);if((h=h-P-1)>O)w.c=w.e=null;else if(h<x)w.c=[w.e=0];else{if(w.e=h,w.c=[],P=(h+1)%C,h<0&&(P+=C),P<g){for(P&&w.c.push(+y.slice(0,P)),g-=C;P<g;)w.c.push(+y.slice(P,P+=C));P=C-(y=y.slice(P)).length}else P-=g;for(;P--;y+="0");w.c.push(+y)}}else w.c=[w.e=0]}v.clone=cn,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(s){var c,_;if(s!=null)if(typeof s=="object"){if(s.hasOwnProperty(c="DECIMAL_PLACES")&&(_=s[c],j(_,0,se,c),a=_),s.hasOwnProperty(c="ROUNDING_MODE")&&(_=s[c],j(_,0,8,c),u=_),s.hasOwnProperty(c="EXPONENTIAL_AT")&&(_=s[c],_&&_.pop?(j(_[0],-se,0,c),j(_[1],0,se,c),p=_[0],b=_[1]):(j(_,-se,se,c),p=-(b=_<0?-_:_))),s.hasOwnProperty(c="RANGE"))if(_=s[c],_&&_.pop)j(_[0],-se,-1,c),j(_[1],1,se,c),x=_[0],O=_[1];else if(j(_,-se,se,c),_)x=-(O=_<0?-_:_);else throw Error(me+c+" cannot be zero: "+_);if(s.hasOwnProperty(c="CRYPTO"))if(_=s[c],_===!!_)if(_)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))N=_;else throw N=!_,Error(me+"crypto unavailable");else N=_;else throw Error(me+c+" not true or false: "+_);if(s.hasOwnProperty(c="MODULO_MODE")&&(_=s[c],j(_,0,9,c),A=_),s.hasOwnProperty(c="POW_PRECISION")&&(_=s[c],j(_,0,se,c),k=_),s.hasOwnProperty(c="FORMAT"))if(_=s[c],typeof _=="object")L=_;else throw Error(me+c+" not an object: "+_);if(s.hasOwnProperty(c="ALPHABET"))if(_=s[c],typeof _=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(_))q=_.slice(0,10)=="0123456789",E=_;else throw Error(me+c+" invalid: "+_)}else throw Error(me+"Object expected: "+s);return{DECIMAL_PLACES:a,ROUNDING_MODE:u,EXPONENTIAL_AT:[p,b],RANGE:[x,O],CRYPTO:N,MODULO_MODE:A,POW_PRECISION:k,FORMAT:L,ALPHABET:E}},v.isBigNumber=function(s){if(!s||s._isBigNumber!==!0)return!1;if(!v.DEBUG)return!0;var c,_,f=s.c,m=s.e,h=s.s;e:if({}.toString.call(f)=="[object Array]"){if((h===1||h===-1)&&m>=-se&&m<=se&&m===xe(m)){if(f[0]===0){if(m===0&&f.length===1)return!0;break e}if(c=(m+1)%C,c<1&&(c+=C),String(f[0]).length==c){for(c=0;c<f.length;c++)if(_=f[c],_<0||_>=Pe||_!==xe(_))break e;if(_!==0)return!0}}}else if(f===null&&m===null&&(h===null||h===1||h===-1))return!0;throw Error(me+"Invalid BigNumber: "+s)},v.maximum=v.max=function(){return ee(arguments,r.lt)},v.minimum=v.min=function(){return ee(arguments,r.gt)},v.random=function(){var s=9007199254740992,c=Math.random()*s&2097151?function(){return xe(Math.random()*s)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(_){var f,m,h,P,d,g=0,y=[],w=new v(o);if(_==null?_=a:j(_,0,se),P=zt(_/C),N)if(crypto.getRandomValues){for(f=crypto.getRandomValues(new Uint32Array(P*=2));g<P;)d=f[g]*131072+(f[g+1]>>>11),d>=9e15?(m=crypto.getRandomValues(new Uint32Array(2)),f[g]=m[0],f[g+1]=m[1]):(y.push(d%1e14),g+=2);g=P/2}else if(crypto.randomBytes){for(f=crypto.randomBytes(P*=7);g<P;)d=(f[g]&31)*281474976710656+f[g+1]*1099511627776+f[g+2]*4294967296+f[g+3]*16777216+(f[g+4]<<16)+(f[g+5]<<8)+f[g+6],d>=9e15?crypto.randomBytes(7).copy(f,g):(y.push(d%1e14),g+=7);g=P/7}else throw N=!1,Error(me+"crypto unavailable");if(!N)for(;g<P;)d=c(),d<9e15&&(y[g++]=d%1e14);for(P=y[--g],_%=C,P&&_&&(d=$t[C-_],y[g]=xe(P/d)*d);y[g]===0;y.pop(),g--);if(g<0)y=[h=0];else{for(h=-1;y[0]===0;y.splice(0,1),h-=C);for(g=1,d=y[0];d>=10;d/=10,g++);g<C&&(h-=C-g)}return w.e=h,w.c=y,w}}(),v.sum=function(){for(var s=1,c=arguments,_=new v(c[0]);s<c.length;)_=_.plus(c[s++]);return _},t=function(){var s="0123456789";function c(_,f,m,h){for(var P,d=[0],g,y=0,w=_.length;y<w;){for(g=d.length;g--;d[g]*=f);for(d[0]+=h.indexOf(_.charAt(y++)),P=0;P<d.length;P++)d[P]>m-1&&(d[P+1]==null&&(d[P+1]=0),d[P+1]+=d[P]/m|0,d[P]%=m)}return d.reverse()}return function(_,f,m,h,P){var d,g,y,w,S,R,M,U,te=_.indexOf("."),ie=a,W=u;for(te>=0&&(w=k,k=0,_=_.replace(".",""),U=new v(f),R=U.pow(_.length-te),k=w,U.c=c(Ae(he(R.c),R.e,"0"),10,m,s),U.e=U.c.length),M=c(_,f,m,P?(d=E,s):(d=s,E)),y=w=M.length;M[--w]==0;M.pop());if(!M[0])return d.charAt(0);if(te<0?--y:(R.c=M,R.e=y,R.s=h,R=e(R,U,ie,W,m),M=R.c,S=R.r,y=R.e),g=y+ie+1,te=M[g],w=m/2,S=S||g<0||M[g+1]!=null,S=W<4?(te!=null||S)&&(W==0||W==(R.s<0?3:2)):te>w||te==w&&(W==4||S||W==6&&M[g-1]&1||W==(R.s<0?8:7)),g<1||!M[0])_=S?Ae(d.charAt(1),-ie,d.charAt(0)):d.charAt(0);else{if(M.length=g,S)for(--m;++M[--g]>m;)M[g]=0,g||(++y,M=[1].concat(M));for(w=M.length;!M[--w];);for(te=0,_="";te<=w;_+=d.charAt(M[te++]));_=Ae(_,y,d.charAt(0))}return _}}(),e=function(){function s(f,m,h){var P,d,g,y,w=0,S=f.length,R=m%Re,M=m/Re|0;for(f=f.slice();S--;)g=f[S]%Re,y=f[S]/Re|0,P=M*g+y*R,d=R*g+P%Re*Re+w,w=(d/h|0)+(P/Re|0)+M*y,f[S]=d%h;return w&&(f=[w].concat(f)),f}function c(f,m,h,P){var d,g;if(h!=P)g=h>P?1:-1;else for(d=g=0;d<h;d++)if(f[d]!=m[d]){g=f[d]>m[d]?1:-1;break}return g}function _(f,m,h,P){for(var d=0;h--;)f[h]-=d,d=f[h]<m[h]?1:0,f[h]=d*P+f[h]-m[h];for(;!f[0]&&f.length>1;f.splice(0,1));}return function(f,m,h,P,d){var g,y,w,S,R,M,U,te,ie,W,$,le,ut,Ct,qt,ye,et,fe=f.s==m.s?1:-1,pe=f.c,ne=m.c;if(!pe||!pe[0]||!ne||!ne[0])return new v(!f.s||!m.s||(pe?ne&&pe[0]==ne[0]:!ne)?NaN:pe&&pe[0]==0||!ne?fe*0:fe/0);for(te=new v(fe),ie=te.c=[],y=f.e-m.e,fe=h+y+1,d||(d=Pe,y=be(f.e/C)-be(m.e/C),fe=fe/C|0),w=0;ne[w]==(pe[w]||0);w++);if(ne[w]>(pe[w]||0)&&y--,fe<0)ie.push(1),S=!0;else{for(Ct=pe.length,ye=ne.length,w=0,fe+=2,R=xe(d/(ne[0]+1)),R>1&&(ne=s(ne,R,d),pe=s(pe,R,d),ye=ne.length,Ct=pe.length),ut=ye,W=pe.slice(0,ye),$=W.length;$<ye;W[$++]=0);et=ne.slice(),et=[0].concat(et),qt=ne[0],ne[1]>=d/2&&qt++;do{if(R=0,g=c(ne,W,ye,$),g<0){if(le=W[0],ye!=$&&(le=le*d+(W[1]||0)),R=xe(le/qt),R>1)for(R>=d&&(R=d-1),M=s(ne,R,d),U=M.length,$=W.length;c(M,W,U,$)==1;)R--,_(M,ye<U?et:ne,U,d),U=M.length,g=1;else R==0&&(g=R=1),M=ne.slice(),U=M.length;if(U<$&&(M=[0].concat(M)),_(W,M,$,d),$=W.length,g==-1)for(;c(ne,W,ye,$)<1;)R++,_(W,ye<$?et:ne,$,d),$=W.length}else g===0&&(R++,W=[0]);ie[w++]=R,W[0]?W[$++]=pe[ut]||0:(W=[pe[ut]],$=1)}while((ut++<Ct||W[0]!=null)&&fe--);S=W[0]!=null,ie[0]||ie.splice(0,1)}if(d==Pe){for(w=1,fe=ie[0];fe>=10;fe/=10,w++);X(te,h+(te.e=w+y*C-1)+1,P,S)}else te.e=y,te.r=+S;return te}}();function Y(s,c,_,f){var m,h,P,d,g;if(_==null?_=u:j(_,0,8),!s.c)return s.toString();if(m=s.c[0],P=s.e,c==null)g=he(s.c),g=f==1||f==2&&(P<=p||P>=b)?mt(g,P):Ae(g,P,"0");else if(s=X(new v(s),c,_),h=s.e,g=he(s.c),d=g.length,f==1||f==2&&(c<=h||h<=p)){for(;d<c;g+="0",d++);g=mt(g,h)}else if(c-=P,g=Ae(g,h,"0"),h+1>d){if(--c>0)for(g+=".";c--;g+="0");}else if(c+=h-d,c>0)for(h+1==d&&(g+=".");c--;g+="0");return s.s<0&&m?"-"+g:g}function ee(s,c){for(var _,f=1,m=new v(s[0]);f<s.length;f++)if(_=new v(s[f]),_.s)c.call(m,_)&&(m=_);else{m=_;break}return m}function K(s,c,_){for(var f=1,m=c.length;!c[--m];c.pop());for(m=c[0];m>=10;m/=10,f++);return(_=f+_*C-1)>O?s.c=s.e=null:_<x?s.c=[s.e=0]:(s.e=_,s.c=c),s}n=function(){var s=/^(-?)0([xbo])(?=\w[\w.]*$)/i,c=/^([^.]+)\.$/,_=/^\.([^.]+)$/,f=/^-?(Infinity|NaN)$/,m=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(h,P,d,g){var y,w=d?P:P.replace(m,"");if(f.test(w))h.s=isNaN(w)?null:w<0?-1:1;else{if(!d&&(w=w.replace(s,function(S,R,M){return y=(M=M.toLowerCase())=="x"?16:M=="b"?2:8,!g||g==y?R:S}),g&&(y=g,w=w.replace(c,"$1").replace(_,"0.$1")),P!=w))return new v(w,y);if(v.DEBUG)throw Error(me+"Not a"+(g?" base "+g:"")+" number: "+P);h.s=null}h.c=h.e=null}}();function X(s,c,_,f){var m,h,P,d,g,y,w,S=s.c,R=$t;if(S){e:{for(m=1,d=S[0];d>=10;d/=10,m++);if(h=c-m,h<0)h+=C,P=c,g=S[y=0],w=g/R[m-P-1]%10|0;else if(y=zt((h+1)/C),y>=S.length)if(f){for(;S.length<=y;S.push(0));g=w=0,m=1,h%=C,P=h-C+1}else break e;else{for(g=d=S[y],m=1;d>=10;d/=10,m++);h%=C,P=h-C+m,w=P<0?0:g/R[m-P-1]%10|0}if(f=f||c<0||S[y+1]!=null||(P<0?g:g%R[m-P-1]),f=_<4?(w||f)&&(_==0||_==(s.s<0?3:2)):w>5||w==5&&(_==4||f||_==6&&(h>0?P>0?g/R[m-P]:0:S[y-1])%10&1||_==(s.s<0?8:7)),c<1||!S[0])return S.length=0,f?(c-=s.e+1,S[0]=R[(C-c%C)%C],s.e=-c||0):S[0]=s.e=0,s;if(h==0?(S.length=y,d=1,y--):(S.length=y+1,d=R[C-h],S[y]=P>0?xe(g/R[m-P]%R[P])*d:0),f)for(;;)if(y==0){for(h=1,P=S[0];P>=10;P/=10,h++);for(P=S[0]+=d,d=1;P>=10;P/=10,d++);h!=d&&(s.e++,S[0]==Pe&&(S[0]=1));break}else{if(S[y]+=d,S[y]!=Pe)break;S[y--]=0,d=1}for(h=S.length;S[--h]===0;S.pop());}s.e>O?s.c=s.e=null:s.e<x&&(s.c=[s.e=0])}return s}function G(s){var c,_=s.e;return _===null?s.toString():(c=he(s.c),c=_<=p||_>=b?mt(c,_):Ae(c,_,"0"),s.s<0?"-"+c:c)}return r.absoluteValue=r.abs=function(){var s=new v(this);return s.s<0&&(s.s=1),s},r.comparedTo=function(s,c){return Ue(this,new v(s,c))},r.decimalPlaces=r.dp=function(s,c){var _,f,m,h=this;if(s!=null)return j(s,0,se),c==null?c=u:j(c,0,8),X(new v(h),s+h.e+1,c);if(!(_=h.c))return null;if(f=((m=_.length-1)-be(this.e/C))*C,m=_[m])for(;m%10==0;m/=10,f--);return f<0&&(f=0),f},r.dividedBy=r.div=function(s,c){return e(this,new v(s,c),a,u)},r.dividedToIntegerBy=r.idiv=function(s,c){return e(this,new v(s,c),0,1)},r.exponentiatedBy=r.pow=function(s,c){var _,f,m,h,P,d,g,y,w,S=this;if(s=new v(s),s.c&&!s.isInteger())throw Error(me+"Exponent not an integer: "+G(s));if(c!=null&&(c=new v(c)),d=s.e>14,!S.c||!S.c[0]||S.c[0]==1&&!S.e&&S.c.length==1||!s.c||!s.c[0])return w=new v(Math.pow(+G(S),d?s.s*(2-dt(s)):+G(s))),c?w.mod(c):w;if(g=s.s<0,c){if(c.c?!c.c[0]:!c.s)return new v(NaN);f=!g&&S.isInteger()&&c.isInteger(),f&&(S=S.mod(c))}else{if(s.e>9&&(S.e>0||S.e<-1||(S.e==0?S.c[0]>1||d&&S.c[1]>=24e7:S.c[0]<8e13||d&&S.c[0]<=9999975e7)))return h=S.s<0&&dt(s)?-0:0,S.e>-1&&(h=1/h),new v(g?1/h:h);k&&(h=zt(k/C+2))}for(d?(_=new v(.5),g&&(s.s=1),y=dt(s)):(m=Math.abs(+G(s)),y=m%2),w=new v(o);;){if(y){if(w=w.times(S),!w.c)break;h?w.c.length>h&&(w.c.length=h):f&&(w=w.mod(c))}if(m){if(m=xe(m/2),m===0)break;y=m%2}else if(s=s.times(_),X(s,s.e+1,1),s.e>14)y=dt(s);else{if(m=+G(s),m===0)break;y=m%2}S=S.times(S),h?S.c&&S.c.length>h&&(S.c.length=h):f&&(S=S.mod(c))}return f?w:(g&&(w=o.div(w)),c?w.mod(c):h?X(w,k,u,P):w)},r.integerValue=function(s){var c=new v(this);return s==null?s=u:j(s,0,8),X(c,c.e+1,s)},r.isEqualTo=r.eq=function(s,c){return Ue(this,new v(s,c))===0},r.isFinite=function(){return!!this.c},r.isGreaterThan=r.gt=function(s,c){return Ue(this,new v(s,c))>0},r.isGreaterThanOrEqualTo=r.gte=function(s,c){return(c=Ue(this,new v(s,c)))===1||c===0},r.isInteger=function(){return!!this.c&&be(this.e/C)>this.c.length-2},r.isLessThan=r.lt=function(s,c){return Ue(this,new v(s,c))<0},r.isLessThanOrEqualTo=r.lte=function(s,c){return(c=Ue(this,new v(s,c)))===-1||c===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(s,c){var _,f,m,h,P=this,d=P.s;if(s=new v(s,c),c=s.s,!d||!c)return new v(NaN);if(d!=c)return s.s=-c,P.plus(s);var g=P.e/C,y=s.e/C,w=P.c,S=s.c;if(!g||!y){if(!w||!S)return w?(s.s=-c,s):new v(S?P:NaN);if(!w[0]||!S[0])return S[0]?(s.s=-c,s):new v(w[0]?P:u==3?-0:0)}if(g=be(g),y=be(y),w=w.slice(),d=g-y){for((h=d<0)?(d=-d,m=w):(y=g,m=S),m.reverse(),c=d;c--;m.push(0));m.reverse()}else for(f=(h=(d=w.length)<(c=S.length))?d:c,d=c=0;c<f;c++)if(w[c]!=S[c]){h=w[c]<S[c];break}if(h&&(m=w,w=S,S=m,s.s=-s.s),c=(f=S.length)-(_=w.length),c>0)for(;c--;w[_++]=0);for(c=Pe-1;f>d;){if(w[--f]<S[f]){for(_=f;_&&!w[--_];w[_]=c);--w[_],w[f]+=Pe}w[f]-=S[f]}for(;w[0]==0;w.splice(0,1),--y);return w[0]?K(s,w,y):(s.s=u==3?-1:1,s.c=[s.e=0],s)},r.modulo=r.mod=function(s,c){var _,f,m=this;return s=new v(s,c),!m.c||!s.s||s.c&&!s.c[0]?new v(NaN):!s.c||m.c&&!m.c[0]?new v(m):(A==9?(f=s.s,s.s=1,_=e(m,s,0,3),s.s=f,_.s*=f):_=e(m,s,0,A),s=m.minus(_.times(s)),!s.c[0]&&A==1&&(s.s=m.s),s)},r.multipliedBy=r.times=function(s,c){var _,f,m,h,P,d,g,y,w,S,R,M,U,te,ie,W=this,$=W.c,le=(s=new v(s,c)).c;if(!$||!le||!$[0]||!le[0])return!W.s||!s.s||$&&!$[0]&&!le||le&&!le[0]&&!$?s.c=s.e=s.s=null:(s.s*=W.s,!$||!le?s.c=s.e=null:(s.c=[0],s.e=0)),s;for(f=be(W.e/C)+be(s.e/C),s.s*=W.s,g=$.length,S=le.length,g<S&&(U=$,$=le,le=U,m=g,g=S,S=m),m=g+S,U=[];m--;U.push(0));for(te=Pe,ie=Re,m=S;--m>=0;){for(_=0,R=le[m]%ie,M=le[m]/ie|0,P=g,h=m+P;h>m;)y=$[--P]%ie,w=$[P]/ie|0,d=M*y+w*R,y=R*y+d%ie*ie+U[h]+_,_=(y/te|0)+(d/ie|0)+M*w,U[h--]=y%te;U[h]=_}return _?++f:U.splice(0,1),K(s,U,f)},r.negated=function(){var s=new v(this);return s.s=-s.s||null,s},r.plus=function(s,c){var _,f=this,m=f.s;if(s=new v(s,c),c=s.s,!m||!c)return new v(NaN);if(m!=c)return s.s=-c,f.minus(s);var h=f.e/C,P=s.e/C,d=f.c,g=s.c;if(!h||!P){if(!d||!g)return new v(m/0);if(!d[0]||!g[0])return g[0]?s:new v(d[0]?f:m*0)}if(h=be(h),P=be(P),d=d.slice(),m=h-P){for(m>0?(P=h,_=g):(m=-m,_=d),_.reverse();m--;_.push(0));_.reverse()}for(m=d.length,c=g.length,m-c<0&&(_=g,g=d,d=_,c=m),m=0;c;)m=(d[--c]=d[c]+g[c]+m)/Pe|0,d[c]=Pe===d[c]?0:d[c]%Pe;return m&&(d=[m].concat(d),++P),K(s,d,P)},r.precision=r.sd=function(s,c){var _,f,m,h=this;if(s!=null&&s!==!!s)return j(s,1,se),c==null?c=u:j(c,0,8),X(new v(h),s,c);if(!(_=h.c))return null;if(m=_.length-1,f=m*C+1,m=_[m]){for(;m%10==0;m/=10,f--);for(m=_[0];m>=10;m/=10,f++);}return s&&h.e+1>f&&(f=h.e+1),f},r.shiftedBy=function(s){return j(s,-Xt,Xt),this.times("1e"+s)},r.squareRoot=r.sqrt=function(){var s,c,_,f,m,h=this,P=h.c,d=h.s,g=h.e,y=a+4,w=new v("0.5");if(d!==1||!P||!P[0])return new v(!d||d<0&&(!P||P[0])?NaN:P?h:1/0);if(d=Math.sqrt(+G(h)),d==0||d==1/0?(c=he(P),(c.length+g)%2==0&&(c+="0"),d=Math.sqrt(+c),g=be((g+1)/2)-(g<0||g%2),d==1/0?c="5e"+g:(c=d.toExponential(),c=c.slice(0,c.indexOf("e")+1)+g),_=new v(c)):_=new v(d+""),_.c[0]){for(g=_.e,d=g+y,d<3&&(d=0);;)if(m=_,_=w.times(m.plus(e(h,m,y,1))),he(m.c).slice(0,d)===(c=he(_.c)).slice(0,d))if(_.e<g&&--d,c=c.slice(d-3,d+1),c=="9999"||!f&&c=="4999"){if(!f&&(X(m,m.e+a+2,0),m.times(m).eq(h))){_=m;break}y+=4,d+=4,f=1}else{(!+c||!+c.slice(1)&&c.charAt(0)=="5")&&(X(_,_.e+a+2,1),s=!_.times(_).eq(h));break}}return X(_,_.e+a+1,u,s)},r.toExponential=function(s,c){return s!=null&&(j(s,0,se),s++),Y(this,s,c,1)},r.toFixed=function(s,c){return s!=null&&(j(s,0,se),s=s+this.e+1),Y(this,s,c)},r.toFormat=function(s,c,_){var f,m=this;if(_==null)s!=null&&c&&typeof c=="object"?(_=c,c=null):s&&typeof s=="object"?(_=s,s=c=null):_=L;else if(typeof _!="object")throw Error(me+"Argument not an object: "+_);if(f=m.toFixed(s,c),m.c){var h,P=f.split("."),d=+_.groupSize,g=+_.secondaryGroupSize,y=_.groupSeparator||"",w=P[0],S=P[1],R=m.s<0,M=R?w.slice(1):w,U=M.length;if(g&&(h=d,d=g,g=h,U-=h),d>0&&U>0){for(h=U%d||d,w=M.substr(0,h);h<U;h+=d)w+=y+M.substr(h,d);g>0&&(w+=y+M.slice(h)),R&&(w="-"+w)}f=S?w+(_.decimalSeparator||"")+((g=+_.fractionGroupSize)?S.replace(new RegExp("\\d{"+g+"}\\B","g"),"$&"+(_.fractionGroupSeparator||"")):S):w}return(_.prefix||"")+f+(_.suffix||"")},r.toFraction=function(s){var c,_,f,m,h,P,d,g,y,w,S,R,M=this,U=M.c;if(s!=null&&(d=new v(s),!d.isInteger()&&(d.c||d.s!==1)||d.lt(o)))throw Error(me+"Argument "+(d.isInteger()?"out of range: ":"not an integer: ")+G(d));if(!U)return new v(M);for(c=new v(o),y=_=new v(o),f=g=new v(o),R=he(U),h=c.e=R.length-M.e-1,c.c[0]=$t[(P=h%C)<0?C+P:P],s=!s||d.comparedTo(c)>0?h>0?c:y:d,P=O,O=1/0,d=new v(R),g.c[0]=0;w=e(d,c,0,1),m=_.plus(w.times(f)),m.comparedTo(s)!=1;)_=f,f=m,y=g.plus(w.times(m=y)),g=m,c=d.minus(w.times(m=c)),d=m;return m=e(s.minus(_),f,0,1),g=g.plus(m.times(y)),_=_.plus(m.times(f)),g.s=y.s=M.s,h=h*2,S=e(y,f,h,u).minus(M).abs().comparedTo(e(g,_,h,u).minus(M).abs())<1?[y,f]:[g,_],O=P,S},r.toNumber=function(){return+G(this)},r.toPrecision=function(s,c){return s!=null&&j(s,1,se),Y(this,s,c,2)},r.toString=function(s){var c,_=this,f=_.s,m=_.e;return m===null?f?(c="Infinity",f<0&&(c="-"+c)):c="NaN":(s==null?c=m<=p||m>=b?mt(he(_.c),m):Ae(he(_.c),m,"0"):s===10&&q?(_=X(new v(_),a+m+1,u),c=Ae(he(_.c),_.e,"0")):(j(s,2,E.length,"Base"),c=t(Ae(he(_.c),m,"0"),10,s,f,!0)),f<0&&_.c[0]&&(c="-"+c)),c},r.valueOf=r.toJSON=function(){return G(this)},r._isBigNumber=!0,r[Symbol.toStringTag]="BigNumber",r[Symbol.for("nodejs.util.inspect.custom")]=r.valueOf,i!=null&&v.set(i),v}function be(i){var e=i|0;return i>0||i===e?e:e-1}function he(i){for(var e,t,n=1,r=i.length,o=i[0]+"";n<r;){for(e=i[n++]+"",t=C-e.length;t--;e="0"+e);o+=e}for(r=o.length;o.charCodeAt(--r)===48;);return o.slice(0,r+1||1)}function Ue(i,e){var t,n,r=i.c,o=e.c,a=i.s,u=e.s,p=i.e,b=e.e;if(!a||!u)return null;if(t=r&&!r[0],n=o&&!o[0],t||n)return t?n?0:-u:a;if(a!=u)return a;if(t=a<0,n=p==b,!r||!o)return n?0:!r^t?1:-1;if(!n)return p>b^t?1:-1;for(u=(p=r.length)<(b=o.length)?p:b,a=0;a<u;a++)if(r[a]!=o[a])return r[a]>o[a]^t?1:-1;return p==b?0:p>b^t?1:-1}function j(i,e,t,n){if(i<e||i>t||i!==xe(i))throw Error(me+(n||"Argument")+(typeof i=="number"?i<e||i>t?" out of range: ":" not an integer: ":" not a primitive number: ")+String(i))}function dt(i){var e=i.c.length-1;return be(i.e/C)==e&&i.c[e]%2!=0}function mt(i,e){return(i.length>1?i.charAt(0)+"."+i.slice(1):i)+(e<0?"e":"e+")+e}function Ae(i,e,t){var n,r;if(e<0){for(r=t+".";++e;r+=t);i=r+i}else if(n=i.length,++e>n){for(r=t,e-=n;--e;r+=t);i+=r}else e<n&&(i=i.slice(0,e)+"."+i.slice(e));return i}var ve=cn();var un=12;ve.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:un});var re=D(0),Oe=D(1),Wn=D("Infinity");function de(i,e){let t=new ve(e.toString()),n=new ve(10).pow(t);return i.times(n)}function D(i){return new ve(i.toString())}var Se=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(Se||{}),rt=(r=>(r.UnknownError="UnknownError",r.InsufficientTradingAmount="InsufficientTradingAmount",r.MaxInRatioExceeded="MaxInRatioExceeded",r.MaxOutRatioExceeded="MaxOutRatioExceeded",r))(rt||{}),Yt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Yt||{});var Be=Wt(pn()),we=class{static getSpotPrice(e,t,n,r,o){return(0,Be.get_spot_price)(e,t,n,r,o)}static calculateInGivenOut(e,t,n,r,o){return(0,Be.calculate_in_given_out)(e,t,n,r,o)}static calculateOutGivenIn(e,t,n,r,o){return(0,Be.calculate_out_given_in)(e,t,n,r,o)}static calculateLinearWeights(e,t,n,r,o){return(0,Be.calculate_linear_weights)(e,t,n,r,o)}static calculatePoolTradeFee(e,t,n){return(0,Be.calculate_pool_trade_fee)(e,t,n)}};var it=18,ze="0",zr=12,Xr=2034,dn=63,$r=2090,Jt=1e3;var Jr=require("@polkadot/types/lookup");var Vr=require("@polkadot/api-base/types/consts");var Kr=require("@polkadot/api-base/types/errors");var jr=require("@polkadot/api-base/types/events");var Zr=require("@polkadot/api-base/types/storage");var Qr=require("@polkadot/api-base/types/submittable");var eo=require("@polkadot/rpc-core/types/jsonrpc");var to=require("@polkadot/api-base/types/calls");var co=require("@polkadot/types/types/registry");var mo=require("@polkadot/types/lookup");var go=require("@polkadot/api-base/types/consts");var fo=require("@polkadot/api-base/types/errors");var ho=require("@polkadot/api-base/types/events");var bo=require("@polkadot/api-base/types/storage");var wo=require("@polkadot/api-base/types/submittable");var Po=require("@polkadot/rpc-core/types/jsonrpc");var yo=require("@polkadot/api-base/types/calls");var No=require("@polkadot/types/types/registry");var wt=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var Xe=class extends wt{constructor(e){super(e)}async getAssetMetadata(e){try{let t=await this.api.query.bonds.bonds(e);if(t.isSome){let[n]=t.unwrap(),r=n.toString();return this.getBondMetadata(r)}return this.getTokenMetadata(e)}catch{return this.getTokenMetadata(e)}}async getTokenMetadata(e){if(e==ze)return{symbol:this.chainToken,origin:this.chainToken,decimals:this.chainDecimals};let t=await this.api.query.assetRegistry.assetMetadataMap(e),{symbol:n,decimals:r}=t.unwrap();return{symbol:n.toHuman(),origin:n.toHuman(),decimals:r.toNumber()}}async getBondMetadata(e){let{symbol:t,decimals:n}=await this.getTokenMetadata(e);return{symbol:t+"b",origin:t,decimals:n}}async getAssetDetail(e){try{let t=await this.api.query.bonds.bonds(e);if(t.isSome){let[n,r]=t.unwrap(),o=n.toString(),a=r.toNumber();return this.getBondDetail(e,o,a)}return this.getTokenDetail(e)}catch{return this.getTokenDetail(e)}}async getTokenDetail(e){if(e==ze){let a=this.api.consts.balances.existentialDeposit;return{name:this.chainToken,assetType:"Token",existentialDeposit:a.toString()}}let t=await this.api.query.assetRegistry.assets(e),{name:n,assetType:r,existentialDeposit:o}=t.unwrap();return{name:n.toHuman(),assetType:r.toHuman(),existentialDeposit:o.toString()}}async getBondDetail(e,t,n){let{assetType:r,existentialDeposit:o}=await this.getTokenDetail(e),{origin:a}=await this.getBondMetadata(t),u=new Intl.DateTimeFormat("en-GB");return{name:[a,"Bond",u.format(n)].join(" "),assetType:r,existentialDeposit:o}}};var $e=class extends Xe{constructor(e){super(e)}async getAccountBalance(e,t){let n=t===ze?await this.getSystemAccountBalance(e):await this.getTokenAccountBalance(e,t),r=await this.getAssetMetadata(t);return{amount:n,decimals:r.decimals}}async getSystemAccountBalance(e){let{data:{free:t,miscFrozen:n,feeFrozen:r}}=await this.api.query.system.account(e);return this.calculateFreeBalance(t.toString(),n.toString(),r.toString())}async getTokenAccountBalance(e,t){let{free:n,reserved:r,frozen:o}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(n.toString(),re.toFixed(),o.toString())}calculateFreeBalance(e,t,n){let r=new ve(e),o=new ve(t),a=new ve(n),u=o.gt(a)?o:a;return r.minus(u)}};var Me=class extends $e{constructor(e){super(e)}getStorageKey(e,t){return e[0].toHuman()[t]}getStorageEntryArray(e){return e[1].toHuman()}async getPoolTokens(e,t){let n=t.map(async r=>{let o=await this.getAccountBalance(e,r),a=await this.getAssetMetadata(r);return{id:r,balance:o.amount.toString(),decimals:a.decimals,symbol:a.symbol,origin:a.origin}});return Promise.all(n)}async syncPoolTokens(e,t){let n=t.map(async r=>{let o=await this.getAccountBalance(e,r.id);return{...r,balance:o.amount.toString()}});return Promise.all(n)}};var Pt=class extends Me{MAX_FINAL_WEIGHT=de(D(100),6);poolsData=new Map([]);pools=[];_poolsLoaded=!1;async getPools(){let e=await this.getRelayChainBlock();return this._poolsLoaded?this.pools=await this.syncPools(e):(this.pools=await this.loadPools(e),this._poolsLoaded=!0),this.pools.filter(t=>{let n=this.poolsData.get(t.address);return n?this.isActivePool(n,e):!1})}async loadPools(e){let n=(await this.api.query.lbp.poolData.entries()).map(async r=>{let o=this.getStorageKey(r,0),a=r[1].unwrap(),u=a.assets.map(A=>A.toString()),p=await this.getPoolTokens(o,u),b=await this.getLinearWeight(a,e),x=D(b),O=this.MAX_FINAL_WEIGHT.minus(D(x)),N=p[0].id;return this.poolsData.set(o,a),{address:o,type:"Lbp",fee:a.fee.toJSON(),repayFeeApply:await this.isRepayFeeApplied(N,a),tokens:[{...p[0],weight:x},{...p[1],weight:O}],...this.getPoolLimits()}});return Promise.all(n)}async syncPools(e){let t=this.pools.map(async n=>{let r=this.poolsData.get(n.address),o=await this.syncPoolTokens(n.address,n.tokens),a=await this.getLinearWeight(r,e),u=D(a),p=this.MAX_FINAL_WEIGHT.minus(D(u)),b=o[0].id;return{...n,repayFeeApply:await this.isRepayFeeApplied(b,r),tokens:[{...o[0],weight:u},{...o[1],weight:p}]}});return Promise.all(t)}async getRelayChainBlock(){return(await this.api.query.parachainSystem.validationData()).unwrap().relayParentNumber.toNumber()}isActivePool(e,t){let n=e.start.toString(),r=e.end.toString();return t>=Number(n)&&t<Number(r)}async getLinearWeight(e,t){return we.calculateLinearWeights(e.start.toString(),e.end.toString(),e.initialWeight.toString(),e.finalWeight.toString(),t.toString())}async isRepayFeeApplied(e,t){let n=D(t.repayTarget.toString());if(n.isZero())return!1;try{return(await this.getAccountBalance(e,t.feeCollector.toString())).amount.isLessThan(n)}catch{return!0}}async getPoolFees(e,t){let n=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:n.fee}}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 mn=require("@polkadot/util-crypto"),gn=require("@polkadot/util");function ae(i,e){return i.shiftedBy(-1*e).toString()}function ke(i){return i[0]/i[1]*100}function He(i){return i[0]/i[1]}function Ee(i){return[i/1e3,1e3]}var yt=class extends Me{pools=[];_poolLoaded=!1;async getPools(){if(this._poolLoaded){let e=await this.syncPool();this.pools=[e]}else{let e=await this.loadPool();this.pools=[e],this._poolLoaded=!0}return this.pools}async loadPool(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=await this.api.query.omnipool.assets.entries(),n=t.map(u=>this.getStorageKey(u,0)).concat(e),r=this.getPoolId(),o=await this.getPoolTokens(r,n),a=this.getPoolTokenState(t,o,e);return{address:r,type:"Omnipool",hubAssetId:e,tokens:a,...this.getPoolLimits()}}async syncPool(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=await this.api.query.omnipool.assets.entries(),n=await this.syncPoolTokens(this.pools[0].address,this.pools[0].tokens),r=this.getPoolTokenState(t,n,e);return{...this.pools[0],tokens:r}}getPoolTokenState(e,t,n){return t.map((r,o)=>{if(n===r.id)return r;let u=e[o][1].unwrap();return{...r,hubReserves:D(u.hubReserve.toString()),shares:D(u.shares.toString())}})}async getPoolFees(e,t){try{let n=await this.api.query.dynamicFees.assetFee(e),r=this.api.consts.dynamicFees.assetFeeParameters,o=this.api.consts.dynamicFees.protocolFeeParameters,a=r.minFee.toNumber()+o.minFee.toNumber(),u=r.maxFee.toNumber()+o.maxFee.toNumber();if(n.isSome){let{assetFee:p,protocolFee:b}=n.unwrap();return{assetFee:Ee(p.toNumber()),protocolFee:Ee(b.toNumber()),min:Ee(a),max:Ee(u)}}else return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee(),min:Ee(a),max:Ee(u)}}catch{return{assetFee:this.getAssetFee(),protocolFee:this.getProtocolFee()}}}getAssetFee(){let e;try{e=this.api.consts.dynamicFees.assetFeeParameters.minFee.toNumber()}catch{e=this.api.consts.omnipool.assetFee.toJSON()}return Ee(e)}getProtocolFee(){let e;try{e=this.api.consts.dynamicFees.protocolFeeParameters.minFee.toNumber()}catch{e=this.api.consts.omnipool.protocolFee.toJSON()}return Ee(e)}getPoolId(){return(0,mn.encodeAddress)((0,gn.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}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 xt=class extends Me{pools=[];_poolsLoaded=!1;async getPools(){return this._poolsLoaded?this.pools=await this.syncPools():(this.pools=await this.loadPools(),this._poolsLoaded=!0),this.pools}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async n=>{let r=this.getStorageKey(n,0),o=this.getStorageEntryArray(n),a=await this.getPoolTokens(r,o);return{address:r,type:"Xyk",tokens:a,...this.getPoolLimits()}});return Promise.all(t)}async syncPools(){let e=this.pools.map(async t=>({...t,tokens:await this.syncPoolTokens(t.address,t.tokens)}));return Promise.all(e)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}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 st=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Vt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ye=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Kt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},jt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Zt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Qt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Je=class{api;xykClient;omniClient;lbpClient;constructor(e){this.api=e,this.xykClient=new xt(this.api),this.omniClient=new yt(this.api),this.lbpClient=new Pt(this.api)}async getPools(e){if(e.length==0)return(await Promise.all([this.xykClient.getPools(),this.omniClient.getPools(),this.lbpClient.getPools()])).flat();let t=[];return e.forEach(r=>{switch(r){case"Xyk":t.push(this.xykClient.getPools());break;case"Omnipool":t.push(this.omniClient.getPools());break;case"Lbp":t.push(this.lbpClient.getPools());break}}),(await Promise.all(t)).flat()}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);default:throw new st(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,n,r,o){let a;this.isDirectOmnipoolTrade(o)?a=this.api.tx.omnipool.buy(t,e,n.toFixed(),r.toFixed()):a=this.api.tx.router.buy(e,t,n.toFixed(),r.toFixed(),o);let u=()=>a;return{hex:a.toHex(),name:"RouterBuy",get:u}}buildSellTx(e,t,n,r,o){let a;this.isDirectOmnipoolTrade(o)?a=this.api.tx.omnipool.sell(e,t,n.toFixed(),r.toFixed()):a=this.api.tx.router.sell(e,t,n.toFixed(),r.toFixed(),o);let u=()=>a;return{hex:a.toHex(),name:"RouterSell",get:u}}};var at=(i,e)=>i===e?0:i==null?e==null?0:-1:e==null?i==null?0:1:typeof i.compare=="function"?i.compare(e):typeof e.compare=="function"?-e.compare(i):i<e?-1:i>e?1:0;var vt=(i,e=t=>t!==void 0?": "+t:"")=>class extends Error{constructor(t){super(i(t)+e(t))}};var jn=vt(()=>"illegal argument(s)"),fn=i=>{throw new jn(i)};var Zn=vt(()=>"index out of bounds"),en=i=>{throw new Zn(i)},Ot=(i,e,t)=>(i<e||i>=t)&&en(i);var hn=23283064365386963e-26,St=class{float(e=1){return this.int()*hn*e}norm(e=1){return(this.int()*hn-.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){return e|=0,t|=0,e+(this.float()*(t-e)|0)}};var tn=Math.random,nn=class extends St{int(){return tn()*4294967296>>>0}float(e=1){return tn()*e}norm(e=1){return(tn()-.5)*2*e}},bn=new nn;var wn=i=>i!=null&&typeof i!="function"&&i.length!==void 0;var Pn=Object.getPrototypeOf({}),It="function",yn="string",Ve=(i,e)=>{let t;if(i===e)return!0;if(i!=null){if(typeof i.equiv===It)return i.equiv(e)}else return i==e;if(e!=null){if(typeof e.equiv===It)return e.equiv(i)}else return i==e;return typeof i===yn||typeof e===yn?!1:(t=Object.getPrototypeOf(i),(t==null||t===Pn)&&(t=Object.getPrototypeOf(e),t==null||t===Pn)?nr(i,e):typeof i!==It&&i.length!==void 0&&typeof e!==It&&e.length!==void 0?Qn(i,e):i instanceof Set&&e instanceof Set?er(i,e):i instanceof Map&&e instanceof Map?tr(i,e):i instanceof Date&&e instanceof Date?i.getTime()===e.getTime():i instanceof RegExp&&e instanceof RegExp?i.toString()===e.toString():i!==i&&e!==e)},Qn=(i,e,t=Ve)=>{let n=i.length;if(n===e.length)for(;n-- >0&&t(i[n],e[n]););return n<0},er=(i,e,t=Ve)=>i.size===e.size&&t([...i.keys()].sort(),[...e.keys()].sort()),tr=(i,e,t=Ve)=>i.size===e.size&&t([...i].sort(),[...e].sort()),nr=(i,e,t=Ve)=>{if(Object.keys(i).length!==Object.keys(e).length)return!1;for(let n in i)if(!e.hasOwnProperty(n)||!t(i[n],e[n]))return!1;return!0};var xn=(i,e)=>i!=null&&typeof i[e]=="function";var vn=i=>xn(i,"xform")?i.xform():i;var Bt=Symbol(),rn=()=>{};var On=i=>i!=null&&typeof i[Symbol.iterator]=="function";var Tt=class{constructor(e){this.value=e}deref(){return this.value}};var Nt=i=>i instanceof Tt;var Sn=i=>i instanceof Tt?i.deref():i;function*In(i,e){let t=vn(i)([rn,rn,(n,r)=>r])[2];for(let n of e){let r=t(Bt,n);if(Nt(r)){r=Sn(r.deref()),r!==Bt&&(yield r);return}r!==Bt&&(yield r)}}var Bn=(i,e)=>[i[0],i[1],e];function lt(i,e){return On(e)?In(lt(i),e):t=>{let n=t[2];return Bn(t,(r,o)=>n(r,i(o)))}}var Ke=class{constructor(e){this._length=0,e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Tn("next",this._head)}reverseIterator(){return Tn("prev",this.tail)}clear(){this.release()}compare(e,t=at){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,a=0;for(;n-- >0&&a===0;)a=t(r.value,o.value),r=r.next,o=o.next;return a}}concat(...e){let t=this.copy();for(let n of e)t.into(n);return t}equiv(e){if(!(e instanceof Ke||wn(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(!Ve(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||at;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&&!Nt(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&&en(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*Tn(i,e){for(;e;)yield e.value,e=e[i]}var Te=class extends Ke{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 Te(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 Te}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):(Ot(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):(Ot(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new Te,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=a=>({first(){return a.value},next(){return a!==r&&a.next?o(a.next):void 0}});return n?o(n):void 0}shuffle(e,t=bn){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.float()<.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)&&fn("invalid indices: ${from} / ${to}");let o=new Te,a=this.nthCell(n);for(;a&&++n<=r;)o.push(a.value),a=a.next;return o}sort(e=at){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,a=0;for(let p=0;p<t&&(a++,o=o.next,!!o);p++);let u=t;for(;a>0||u>0&&o;){let p;a===0?(p=o,o=o.next,u--):!o||u===0||e(n.value,o.value)<=0?(p=n,n=n.next,a--):(p=o,o=o.next,u--),this._tail?this._tail.next=p:this._head=p,p.prev=this._tail,this._tail=p}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),Ot(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let o=new Te;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 a of n)this.insertBefore(r,a);else for(let a of n)this.push(a);return o}};var je=class{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 Te,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 lt(e=>[e.k,e],this.items)}keys(){return lt(e=>e.k,this.items)}values(){return lt(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 je(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 Ft=class extends Je{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new je(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 Le=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Le(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,n,r,o,a,u){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=o,this.fee=a,this.repayFeeApply=u}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(p=>[p.id,p])),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 a=D(r.balance),u=D(o.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,weightIn:r.weight,weightOut:o.weight,balanceIn:a,balanceOut:u}}validateAndBuy(e,t,n){let r=this.tokens[0].id,o=[];t.isLessThan(this.minTradingLimit)&&o.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&o.push("MaxOutRatioExceeded"),r===e.assetOut){let u=this.calculateTradeFee(t,n),p=ke(this.repayFeeApply?n.repayFee:n.exchangeFee),b=t.plus(u),x=this.calculateInGivenOut(e,b),O=e.balanceIn.div(this.maxInRatio);return x.isGreaterThan(O)&&o.push("MaxInRatioExceeded"),{amountIn:x,calculatedIn:x,amountOut:t,feePct:p,errors:o}}else{let u=this.calculateInGivenOut(e,t),p=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(p)&&o.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,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 a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&o.push("MaxInRatioExceeded"),r===e.assetIn){let u=this.calculateOutGivenIn(e,t),p=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(p)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:u,amountOut:u,feePct:0,errors:o}}else{let u=this.calculateOutGivenIn(e,t),p=this.calculateTradeFee(u,n),b=ke(this.repayFeeApply?n.repayFee:n.exchangeFee),x=u.minus(p),O=e.balanceOut.div(this.maxOutRatio);return x.isGreaterThan(O)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:u,amountOut:x,feePct:b,errors:o}}}calculateInGivenOut(e,t){let n=we.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=D(n);return r.isNegative()?re:r}calculateOutGivenIn(e,t){let n=we.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=D(n);return r.isNegative()?re:r}spotPriceInGivenOut(e){let t=we.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),de(Oe,e.decimalsOut).toString());return D(t)}spotPriceOutGivenIn(e){let t=we.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),de(Oe,e.decimalsIn).toString());return D(t)}calculateTradeFee(e,t){let n=we.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return D(n)}};var H=Wt(Fn()),ge=class{static calculateSpotPrice(e,t,n,r){return(0,H.calculate_spot_price)(e,t,n,r)}static calculateLrnaSpotPrice(e,t){return(0,H.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,n,r,o,a,u,p,b){return(0,H.calculate_in_given_out)(e,t,n,r,o,a,u,p,b)}static calculateLrnaInGivenOut(e,t,n,r,o){return(0,H.calculate_lrna_in_given_out)(e,t,n,r,o)}static calculateOutGivenIn(e,t,n,r,o,a,u,p,b){return(0,H.calculate_out_given_in)(e,t,n,r,o,a,u,p,b)}static calculateOutGivenLrnaIn(e,t,n,r,o){return(0,H.calculate_out_given_lrna_in)(e,t,n,r,o)}static calculatePoolTradeFee(e,t,n){return(0,H.calculate_pool_trade_fee)(e,t,n)}static calculateShares(e,t,n,r){return(0,H.calculate_shares)(e,t,n,r)}static calculateLiquidityOut(e,t,n,r,o,a,u,p){return(0,H.calculate_liquidity_out)(e,t,n,r,o,a,u,p)}static calculateLiquidityLRNAOut(e,t,n,r,o,a,u,p){return(0,H.calculate_liquidity_lrna_out)(e,t,n,r,o,a,u,p)}static calculateCapDifference(e,t,n,r){return(0,H.calculate_cap_difference)(e,t,n,r)}static verifyAssetCap(e,t,n,r){return(0,H.verify_asset_cap)(e,t,n,r)}static calculateLimitHubIn(e,t,n,r){return(0,H.calculate_liquidity_hub_in)(e,t,n,r)}static isSellAllowed(e){return(0,H.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,H.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,H.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,H.is_remove_liquidity_allowed)(e)}};var De=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new De(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,n,r,o,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=o,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let n=new Map(this.tokens.map(p=>[p.id,p])),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 a=D(r.balance),u=D(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:a,balanceOut:u}}validateAndBuy(e,t,n){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,n),a=o.minus(r),u=r===re?re:a.div(r).multipliedBy(100).decimalPlaces(2),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let b=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(b)&&p.push("MaxOutRatioExceeded");let x=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(x)&&p.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:u.toNumber(),errors:p}}validateAndSell(e,t,n){let r=this.calculateOutGivenIn(e,t),o=this.calculateOutGivenIn(e,t,n),u=r.minus(o).div(r).multipliedBy(100).decimalPlaces(2),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let b=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(b)&&p.push("MaxInRatioExceeded");let x=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(x)&&p.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:u.toNumber(),errors:p}}calculateInGivenOut(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,n);let r=ge.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),n?He(n.assetFee).toString():re.toString(),n?He(n.protocolFee).toString():re.toString()),o=D(r);return o.isNegative()?re:o}calculateLrnaInGivenOut(e,t,n){let r=ge.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),n?He(n.assetFee).toString():re.toString()),o=D(r);return o.isNegative()?re:o}calculateOutGivenIn(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,n);let r=ge.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),n?He(n.assetFee).toString():re.toString(),n?He(n.protocolFee).toString():re.toString()),o=D(r);return o.isNegative()?re:o}calculateOutGivenLrnaIn(e,t,n){let r=ge.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),n?He(n.assetFee).toString():re.toString()),o=D(r);return o.isNegative()?re:o}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=ge.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return D(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=ge.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return D(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=ge.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return D(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=ge.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return D(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var _e=Wt(kn()),Fe=class{static getSpotPrice(e,t,n){return(0,_e.get_spot_price)(e,t,n)}static calculateInGivenOut(e,t,n){return(0,_e.calculate_in_given_out)(e,t,n)}static calculateOutGivenIn(e,t,n){return(0,_e.calculate_out_given_in)(e,t,n)}static calculatePoolTradeFee(e,t,n){return(0,_e.calculate_pool_trade_fee)(e,t,n)}static calculateLiquidityIn(e,t,n){return(0,_e.calculate_liquidity_in)(e,t,n)}static calculateShares(e,t,n){return(0,_e.calculate_shares)(e,t,n)}static calculateLiquidityOutAssetA(e,t,n,r){return(0,_e.calculate_liquidity_out_asset_a)(e,t,n,r)}static calculateLiquidityOutAssetB(e,t,n,r){return(0,_e.calculate_liquidity_out_asset_b)(e,t,n,r)}};var Ce=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Ce(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(p=>[p.id,p])),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 a=D(r.balance),u=D(o.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:a,balanceOut:u}}validateAndBuy(e,t,n){let r=this.calculateInGivenOut(e,t),o=this.calculateTradeFee(r,n),a=ke(n.exchangeFee),u=r.plus(o),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let b=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(b)&&p.push("MaxOutRatioExceeded");let x=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(x)&&p.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:r,amountOut:t,feePct:a,errors:p}}validateAndSell(e,t,n){let r=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(r,n),a=ke(n.exchangeFee),u=r.minus(o),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let b=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(b)&&p.push("MaxInRatioExceeded");let x=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(x)&&p.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:u,feePct:a,errors:p}}calculateInGivenOut(e,t){let n=Fe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=D(n);return r.isNegative()?re:r}calculateOutGivenIn(e,t){let n=Fe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=D(n);return r.isNegative()?re:r}spotPriceInGivenOut(e){let t=Fe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),de(Oe,e.decimalsOut).toString());return D(t)}spotPriceOutGivenIn(e){let t=Fe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),de(Oe,e.decimalsIn).toString());return D(t)}calculateTradeFee(e,t){let n=Fe.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return D(n)}};var Ze=class{static get(e){switch(e.type){case"Xyk":return Ce.fromPool(e);case"Omnipool":return De.fromPool(e);case"Lbp":return Le.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var We=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new nt,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),a=this.getPaths(e,null,r,t).map(u=>u[u.length-1].assetOut);return this.toPoolAssets([...new Set(a)],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(({id:r,symbol:o})=>({id:r,symbol:o}))).flat();return new Map(t.map(n=>[n.id,n]))}getPaths(e,t,n,r){return this.routeSuggester.getProposals(e,t,r).filter(u=>this.validPath(u,n)).map(u=>this.toHops(u,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,Ze.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 a=t.get(n);return{poolId:n,pool:a?.type,assetIn:r,assetOut:o}})}toPoolAssets(e,t){return e.map(n=>{let r=t.get(n);return{id:n,symbol:r?.symbol}})}};function wr(i,e){return i.minus(e).abs().div(i.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Qe(i,e){return i.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function on(i,e){return Oe.minus(e.div(i)).multipliedBy(100).decimalPlaces(2)}function sn(i,e){return e.div(i).minus(Oe).multipliedBy(100).decimalPlaces(2)}var ct=class extends We{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((n,r)=>{let o=n[n.length-1].amountOut,a=r[r.length-1].amountOut;return o.isGreaterThan(a)?-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,a)=>o+a),r=e.map(o=>o.tradeFeeRange?.[1]??o.tradeFeePct).reduce((o,a)=>o+a);return[n,r]}}getPoolFeeRange(e){let t=e.min?ke(e.min):void 0,n=e.max?ke(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),a=super.getPaths(e,t,o,r);if(a.length===0)throw new Ye(e,t);let u=a.map(async G=>await this.toSellSwaps(n,G,o)),p=await Promise.all(u),b=this.findBestSellRoute(p),x=b[0],O=b[b.length-1],N=this.isDirectTrade(b),A=b.map(G=>G.spotPrice.shiftedBy(-1*G.assetOutDecimals)).reduce((G,s)=>G.multipliedBy(s)),k=de(A,O.assetOutDecimals).decimalPlaces(0,1),L=x.amountIn.shiftedBy(-1*x.assetInDecimals).multipliedBy(k),E=Qe(O.calculatedOut,L),q=N?O.calculatedOut:this.calculateDelta0Y(x.amountIn,b,o),v=O.amountOut,Y=N?O.tradeFeePct:on(q,v).toNumber(),ee=q.minus(v),K=this.getRouteFeeRange(b),X=G=>this.poolService.buildSellTx(e,t,x.amountIn,G,b.map(({assetIn:s,assetOut:c,pool:_,poolId:f})=>({assetIn:s,assetOut:c,pool:_,poolId:f})));return{type:"Sell",amountIn:x.amountIn,amountOut:O.amountOut,spotPrice:k,tradeFee:ee,tradeFeePct:Y,tradeFeeRange:K,priceImpactPct:E.toNumber(),swaps:b,toTx:X,toHuman(){return{type:"Sell",amountIn:ae(x.amountIn,x.assetInDecimals),amountOut:ae(O.amountOut,O.assetOutDecimals),spotPrice:ae(k,O.assetOutDecimals),tradeFee:ae(ee,O.assetOutDecimals),tradeFeePct:Y,tradeFeeRange:K,priceImpactPct:E.toNumber(),swaps:b.map(G=>G.toHuman())}}}}calculateDelta0Y(e,t,n){let r=[];for(let o=0;o<t.length;o++){let a=t[o],u=n.get(a.poolId);if(u==null)throw new Error("Pool does not exit");let p=u.parsePair(a.assetIn,a.assetOut),b;o>0?b=r[o-1]:b=e;let x=u.calculateOutGivenIn(p,b);r.push(x)}return r[r.length-1]}async toSellSwaps(e,t,n){let r=[];for(let o=0;o<t.length;o++){let a=t[o],u=n.get(a.poolId);if(u==null)throw new Error("Pool does not exit");let p=u.parsePair(a.assetIn,a.assetOut),b;o>0?b=r[o-1].amountOut:b=de(D(e),p.decimalsIn).decimalPlaces(0,1);let x=await this.poolService.getPoolFees(p.assetOut,u),{amountOut:O,calculatedOut:N,feePct:A,errors:k}=u.validateAndSell(p,b,x),L=this.getPoolFeeRange(x),E=u.spotPriceOutGivenIn(p),q=b.shiftedBy(-1*p.decimalsIn).multipliedBy(E),v=Qe(N,q);r.push({...a,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountIn:b,calculatedOut:N,amountOut:O,spotPrice:E,tradeFeePct:A,tradeFeeRange:L,priceImpactPct:v.toNumber(),errors:k,toHuman(){return{...a,amountIn:ae(b,p.decimalsIn),calculatedOut:ae(N,p.decimalsOut),amountOut:ae(O,p.decimalsOut),spotPrice:ae(E,p.decimalsOut),tradeFeePct:A,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 a=o.map(async N=>await this.toSellSwaps("1",N,r)),u=await Promise.all(a),p=this.findBestSellRoute(u),b=p.map(N=>N.spotPrice.shiftedBy(-1*N.assetOutDecimals)).reduce((N,A)=>N.multipliedBy(A)),x=p[p.length-1].assetOutDecimals;return{amount:de(b,x).decimalPlaces(0,1),decimals:x}}findBestBuyRoute(e){let t=e.sort((n,r)=>{let o=n[0].amountIn,a=r[0].amountIn;return o.isGreaterThan(a)?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),a=super.getPaths(e,t,o,r);if(a.length===0)throw new Ye(e,t);let u=a.map(async G=>await this.toBuySwaps(n,G,o)),p=await Promise.all(u),b=this.findBestBuyRoute(p),x=b[b.length-1],O=b[0],N=this.isDirectTrade(b),A=b.map(G=>G.spotPrice.shiftedBy(-1*G.assetInDecimals)).reduce((G,s)=>G.multipliedBy(s)),k=de(A,O.assetInDecimals).decimalPlaces(0,1),L=x.amountOut.shiftedBy(-1*x.assetOutDecimals).multipliedBy(k),E;O.calculatedIn.isZero()?E=-100:E=Qe(L,O.calculatedIn).toNumber();let q=N?O.calculatedIn:this.calculateDelta0X(x.amountOut,b,o),v=O.amountIn,Y=N?O.tradeFeePct:sn(q,v),ee=v.minus(q),K=this.getRouteFeeRange(b),X=G=>this.poolService.buildBuyTx(e,t,x.amountOut,G,b.map(({assetIn:s,assetOut:c,pool:_,poolId:f})=>({assetIn:s,assetOut:c,pool:_,poolId:f})));return{type:"Buy",amountOut:x.amountOut,amountIn:O.amountIn,spotPrice:k,tradeFee:ee,tradeFeePct:Y,tradeFeeRange:K,priceImpactPct:E,swaps:b,toTx:X,toHuman(){return{type:"Buy",amountOut:ae(x.amountOut,x.assetOutDecimals),amountIn:ae(O.amountIn,O.assetInDecimals),spotPrice:ae(k,O.assetInDecimals),tradeFee:ae(ee,O.assetInDecimals),tradeFeePct:Y,tradeFeeRange:K,priceImpactPct:E,swaps:b.map(G=>G.toHuman())}}}}calculateDelta0X(e,t,n){let r=[];for(let o=t.length-1;o>=0;o--){let a=t[o],u=n.get(a.poolId);if(u==null)throw new Error("Pool does not exit");let p=u.parsePair(a.assetIn,a.assetOut),b;o==t.length-1?b=e:b=r[0];let x=u.calculateInGivenOut(p,b);r.unshift(x)}return r[0]}async toBuySwaps(e,t,n){let r=[];for(let o=t.length-1;o>=0;o--){let a=t[o],u=n.get(a.poolId);if(u==null)throw new Error("Pool does not exit");let p=u.parsePair(a.assetIn,a.assetOut),b;o==t.length-1?b=de(D(e),p.decimalsOut).decimalPlaces(0,1):b=r[0].amountIn;let x=await this.poolService.getPoolFees(p.assetIn,u),{amountIn:O,calculatedIn:N,feePct:A,errors:k}=u.validateAndBuy(p,b,x),L=this.getPoolFeeRange(x),E=u.spotPriceInGivenOut(p),q=b.shiftedBy(-1*p.decimalsOut).multipliedBy(E),v;N.isZero()?v=-100:v=Qe(q,N).toNumber(),r.unshift({...a,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountOut:b,calculatedIn:N,amountIn:O,spotPrice:E,tradeFeePct:A,tradeFeeRange:L,priceImpactPct:v,errors:k,toHuman(){return{...a,amountOut:ae(b,p.decimalsOut),calculatedIn:ae(N,p.decimalsIn),amountIn:ae(O,p.decimalsIn),spotPrice:ae(E,p.decimalsIn),tradeFeePct:A,tradeFeeRange:L,priceImpactPct:v,errors:k}}})}return r}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,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,StorageConfigNotFound,SubscriptionNotSupported,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,scale});
|
|
2
|
+
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Le=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new Le(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,n,r,o,a,u){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=o,this.fee=a,this.repayFeeApply=u}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(p=>[p.id,p])),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 a=D(r.balance),u=D(o.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,weightIn:r.weight,weightOut:o.weight,balanceIn:a,balanceOut:u}}validateAndBuy(e,t,n){let r=this.tokens[0].id,o=[];t.isLessThan(this.minTradingLimit)&&o.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&o.push("MaxOutRatioExceeded"),r===e.assetOut){let u=this.calculateTradeFee(t,n),p=ke(this.repayFeeApply?n.repayFee:n.exchangeFee),b=t.plus(u),x=this.calculateInGivenOut(e,b),O=e.balanceIn.div(this.maxInRatio);return x.isGreaterThan(O)&&o.push("MaxInRatioExceeded"),{amountIn:x,calculatedIn:x,amountOut:t,feePct:p,errors:o}}else{let u=this.calculateInGivenOut(e,t),p=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(p)&&o.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,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 a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&o.push("MaxInRatioExceeded"),r===e.assetIn){let u=this.calculateOutGivenIn(e,t),p=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(p)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:u,amountOut:u,feePct:0,errors:o}}else{let u=this.calculateOutGivenIn(e,t),p=this.calculateTradeFee(u,n),b=ke(this.repayFeeApply?n.repayFee:n.exchangeFee),x=u.minus(p),O=e.balanceOut.div(this.maxOutRatio);return x.isGreaterThan(O)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:u,amountOut:x,feePct:b,errors:o}}}calculateInGivenOut(e,t){let n=we.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=D(n);return r.isNegative()?re:r}calculateOutGivenIn(e,t){let n=we.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=D(n);return r.isNegative()?re:r}spotPriceInGivenOut(e){let t=we.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),de(Oe,e.decimalsOut).toString());return D(t)}spotPriceOutGivenIn(e){let t=we.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),de(Oe,e.decimalsIn).toString());return D(t)}calculateTradeFee(e,t){let n=we.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return D(n)}};var H=Wt(Fn()),ge=class{static calculateSpotPrice(e,t,n,r){return(0,H.calculate_spot_price)(e,t,n,r)}static calculateLrnaSpotPrice(e,t){return(0,H.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,n,r,o,a,u,p,b){return(0,H.calculate_in_given_out)(e,t,n,r,o,a,u,p,b)}static calculateLrnaInGivenOut(e,t,n,r,o){return(0,H.calculate_lrna_in_given_out)(e,t,n,r,o)}static calculateOutGivenIn(e,t,n,r,o,a,u,p,b){return(0,H.calculate_out_given_in)(e,t,n,r,o,a,u,p,b)}static calculateOutGivenLrnaIn(e,t,n,r,o){return(0,H.calculate_out_given_lrna_in)(e,t,n,r,o)}static calculatePoolTradeFee(e,t,n){return(0,H.calculate_pool_trade_fee)(e,t,n)}static calculateShares(e,t,n,r){return(0,H.calculate_shares)(e,t,n,r)}static calculateLiquidityOut(e,t,n,r,o,a,u,p){return(0,H.calculate_liquidity_out)(e,t,n,r,o,a,u,p)}static calculateLiquidityLRNAOut(e,t,n,r,o,a,u,p){return(0,H.calculate_liquidity_lrna_out)(e,t,n,r,o,a,u,p)}static calculateCapDifference(e,t,n,r){return(0,H.calculate_cap_difference)(e,t,n,r)}static verifyAssetCap(e,t,n,r){return(0,H.verify_asset_cap)(e,t,n,r)}static calculateLimitHubIn(e,t,n,r){return(0,H.calculate_liquidity_hub_in)(e,t,n,r)}static isSellAllowed(e){return(0,H.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,H.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,H.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,H.is_remove_liquidity_allowed)(e)}};var De=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new De(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,n,r,o,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=o,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let n=new Map(this.tokens.map(p=>[p.id,p])),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 a=D(r.balance),u=D(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:a,balanceOut:u}}validateAndBuy(e,t,n){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,n),a=o.minus(r),u=r===re?re:a.div(r).multipliedBy(100).decimalPlaces(2),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let b=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(b)&&p.push("MaxOutRatioExceeded");let x=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(x)&&p.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:u.toNumber(),errors:p}}validateAndSell(e,t,n){let r=this.calculateOutGivenIn(e,t),o=this.calculateOutGivenIn(e,t,n),u=r.minus(o).div(r).multipliedBy(100).decimalPlaces(2),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let b=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(b)&&p.push("MaxInRatioExceeded");let x=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(x)&&p.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:u.toNumber(),errors:p}}calculateInGivenOut(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,n);let r=ge.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),n?He(n.assetFee).toString():re.toString(),n?He(n.protocolFee).toString():re.toString()),o=D(r);return o.isNegative()?re:o}calculateLrnaInGivenOut(e,t,n){let r=ge.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),n?He(n.assetFee).toString():re.toString()),o=D(r);return o.isNegative()?re:o}calculateOutGivenIn(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,n);let r=ge.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),n?He(n.assetFee).toString():re.toString(),n?He(n.protocolFee).toString():re.toString()),o=D(r);return o.isNegative()?re:o}calculateOutGivenLrnaIn(e,t,n){let r=ge.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),n?He(n.assetFee).toString():re.toString()),o=D(r);return o.isNegative()?re:o}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=ge.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return D(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=ge.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return D(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=ge.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return D(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=ge.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return D(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var _e=Wt(kn()),Fe=class{static getSpotPrice(e,t,n){return(0,_e.get_spot_price)(e,t,n)}static calculateInGivenOut(e,t,n){return(0,_e.calculate_in_given_out)(e,t,n)}static calculateOutGivenIn(e,t,n){return(0,_e.calculate_out_given_in)(e,t,n)}static calculatePoolTradeFee(e,t,n){return(0,_e.calculate_pool_trade_fee)(e,t,n)}static calculateLiquidityIn(e,t,n){return(0,_e.calculate_liquidity_in)(e,t,n)}static calculateShares(e,t,n){return(0,_e.calculate_shares)(e,t,n)}static calculateLiquidityOutAssetA(e,t,n,r){return(0,_e.calculate_liquidity_out_asset_a)(e,t,n,r)}static calculateLiquidityOutAssetB(e,t,n,r){return(0,_e.calculate_liquidity_out_asset_b)(e,t,n,r)}};var Ce=class{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new Ce(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(p=>[p.id,p])),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 a=D(r.balance),u=D(o.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:a,balanceOut:u}}validateAndBuy(e,t,n){let r=this.calculateInGivenOut(e,t),o=this.calculateTradeFee(r,n),a=ke(n.exchangeFee),u=r.plus(o),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let b=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(b)&&p.push("MaxOutRatioExceeded");let x=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(x)&&p.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:r,amountOut:t,feePct:a,errors:p}}validateAndSell(e,t,n){let r=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(r,n),a=ke(n.exchangeFee),u=r.minus(o),p=[];t.isLessThan(this.minTradingLimit)&&p.push("InsufficientTradingAmount");let b=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(b)&&p.push("MaxInRatioExceeded");let x=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(x)&&p.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:u,feePct:a,errors:p}}calculateInGivenOut(e,t){let n=Fe.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=D(n);return r.isNegative()?re:r}calculateOutGivenIn(e,t){let n=Fe.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=D(n);return r.isNegative()?re:r}spotPriceInGivenOut(e){let t=Fe.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),de(Oe,e.decimalsOut).toString());return D(t)}spotPriceOutGivenIn(e){let t=Fe.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),de(Oe,e.decimalsIn).toString());return D(t)}calculateTradeFee(e,t){let n=Fe.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return D(n)}};var Ze=class{static get(e){switch(e.type){case"Xyk":return Ce.fromPool(e);case"Omnipool":return De.fromPool(e);case"Lbp":return Le.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var We=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new nt,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),a=this.getPaths(e,null,r,t).map(u=>u[u.length-1].assetOut);return this.toPoolAssets([...new Set(a)],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(({id:r,symbol:o,origin:a})=>({id:r,symbol:o,origin:a}))).flat();return new Map(t.map(n=>[n.id,n]))}getPaths(e,t,n,r){return this.routeSuggester.getProposals(e,t,r).filter(u=>this.validPath(u,n)).map(u=>this.toHops(u,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,Ze.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 a=t.get(n);return{poolId:n,pool:a?.type,assetIn:r,assetOut:o}})}toPoolAssets(e,t){return e.map(n=>{let r=t.get(n);return{id:n,symbol:r?.symbol}})}};function wr(i,e){return i.minus(e).abs().div(i.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Qe(i,e){return i.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function on(i,e){return Oe.minus(e.div(i)).multipliedBy(100).decimalPlaces(2)}function sn(i,e){return e.div(i).minus(Oe).multipliedBy(100).decimalPlaces(2)}var ct=class extends We{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((n,r)=>{let o=n[n.length-1].amountOut,a=r[r.length-1].amountOut;return o.isGreaterThan(a)?-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,a)=>o+a),r=e.map(o=>o.tradeFeeRange?.[1]??o.tradeFeePct).reduce((o,a)=>o+a);return[n,r]}}getPoolFeeRange(e){let t=e.min?ke(e.min):void 0,n=e.max?ke(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),a=super.getPaths(e,t,o,r);if(a.length===0)throw new Ye(e,t);let u=a.map(async G=>await this.toSellSwaps(n,G,o)),p=await Promise.all(u),b=this.findBestSellRoute(p),x=b[0],O=b[b.length-1],N=this.isDirectTrade(b),A=b.map(G=>G.spotPrice.shiftedBy(-1*G.assetOutDecimals)).reduce((G,s)=>G.multipliedBy(s)),k=de(A,O.assetOutDecimals).decimalPlaces(0,1),L=x.amountIn.shiftedBy(-1*x.assetInDecimals).multipliedBy(k),E=Qe(O.calculatedOut,L),q=N?O.calculatedOut:this.calculateDelta0Y(x.amountIn,b,o),v=O.amountOut,Y=N?O.tradeFeePct:on(q,v).toNumber(),ee=q.minus(v),K=this.getRouteFeeRange(b),X=G=>this.poolService.buildSellTx(e,t,x.amountIn,G,b.map(({assetIn:s,assetOut:c,pool:_,poolId:f})=>({assetIn:s,assetOut:c,pool:_,poolId:f})));return{type:"Sell",amountIn:x.amountIn,amountOut:O.amountOut,spotPrice:k,tradeFee:ee,tradeFeePct:Y,tradeFeeRange:K,priceImpactPct:E.toNumber(),swaps:b,toTx:X,toHuman(){return{type:"Sell",amountIn:ae(x.amountIn,x.assetInDecimals),amountOut:ae(O.amountOut,O.assetOutDecimals),spotPrice:ae(k,O.assetOutDecimals),tradeFee:ae(ee,O.assetOutDecimals),tradeFeePct:Y,tradeFeeRange:K,priceImpactPct:E.toNumber(),swaps:b.map(G=>G.toHuman())}}}}calculateDelta0Y(e,t,n){let r=[];for(let o=0;o<t.length;o++){let a=t[o],u=n.get(a.poolId);if(u==null)throw new Error("Pool does not exit");let p=u.parsePair(a.assetIn,a.assetOut),b;o>0?b=r[o-1]:b=e;let x=u.calculateOutGivenIn(p,b);r.push(x)}return r[r.length-1]}async toSellSwaps(e,t,n){let r=[];for(let o=0;o<t.length;o++){let a=t[o],u=n.get(a.poolId);if(u==null)throw new Error("Pool does not exit");let p=u.parsePair(a.assetIn,a.assetOut),b;o>0?b=r[o-1].amountOut:b=de(D(e),p.decimalsIn).decimalPlaces(0,1);let x=await this.poolService.getPoolFees(p.assetOut,u),{amountOut:O,calculatedOut:N,feePct:A,errors:k}=u.validateAndSell(p,b,x),L=this.getPoolFeeRange(x),E=u.spotPriceOutGivenIn(p),q=b.shiftedBy(-1*p.decimalsIn).multipliedBy(E),v=Qe(N,q);r.push({...a,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountIn:b,calculatedOut:N,amountOut:O,spotPrice:E,tradeFeePct:A,tradeFeeRange:L,priceImpactPct:v.toNumber(),errors:k,toHuman(){return{...a,amountIn:ae(b,p.decimalsIn),calculatedOut:ae(N,p.decimalsOut),amountOut:ae(O,p.decimalsOut),spotPrice:ae(E,p.decimalsOut),tradeFeePct:A,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 a=o.map(async N=>await this.toSellSwaps("1",N,r)),u=await Promise.all(a),p=this.findBestSellRoute(u),b=p.map(N=>N.spotPrice.shiftedBy(-1*N.assetOutDecimals)).reduce((N,A)=>N.multipliedBy(A)),x=p[p.length-1].assetOutDecimals;return{amount:de(b,x).decimalPlaces(0,1),decimals:x}}findBestBuyRoute(e){let t=e.sort((n,r)=>{let o=n[0].amountIn,a=r[0].amountIn;return o.isGreaterThan(a)?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),a=super.getPaths(e,t,o,r);if(a.length===0)throw new Ye(e,t);let u=a.map(async G=>await this.toBuySwaps(n,G,o)),p=await Promise.all(u),b=this.findBestBuyRoute(p),x=b[b.length-1],O=b[0],N=this.isDirectTrade(b),A=b.map(G=>G.spotPrice.shiftedBy(-1*G.assetInDecimals)).reduce((G,s)=>G.multipliedBy(s)),k=de(A,O.assetInDecimals).decimalPlaces(0,1),L=x.amountOut.shiftedBy(-1*x.assetOutDecimals).multipliedBy(k),E;O.calculatedIn.isZero()?E=-100:E=Qe(L,O.calculatedIn).toNumber();let q=N?O.calculatedIn:this.calculateDelta0X(x.amountOut,b,o),v=O.amountIn,Y=N?O.tradeFeePct:sn(q,v),ee=v.minus(q),K=this.getRouteFeeRange(b),X=G=>this.poolService.buildBuyTx(e,t,x.amountOut,G,b.map(({assetIn:s,assetOut:c,pool:_,poolId:f})=>({assetIn:s,assetOut:c,pool:_,poolId:f})));return{type:"Buy",amountOut:x.amountOut,amountIn:O.amountIn,spotPrice:k,tradeFee:ee,tradeFeePct:Y,tradeFeeRange:K,priceImpactPct:E,swaps:b,toTx:X,toHuman(){return{type:"Buy",amountOut:ae(x.amountOut,x.assetOutDecimals),amountIn:ae(O.amountIn,O.assetInDecimals),spotPrice:ae(k,O.assetInDecimals),tradeFee:ae(ee,O.assetInDecimals),tradeFeePct:Y,tradeFeeRange:K,priceImpactPct:E,swaps:b.map(G=>G.toHuman())}}}}calculateDelta0X(e,t,n){let r=[];for(let o=t.length-1;o>=0;o--){let a=t[o],u=n.get(a.poolId);if(u==null)throw new Error("Pool does not exit");let p=u.parsePair(a.assetIn,a.assetOut),b;o==t.length-1?b=e:b=r[0];let x=u.calculateInGivenOut(p,b);r.unshift(x)}return r[0]}async toBuySwaps(e,t,n){let r=[];for(let o=t.length-1;o>=0;o--){let a=t[o],u=n.get(a.poolId);if(u==null)throw new Error("Pool does not exit");let p=u.parsePair(a.assetIn,a.assetOut),b;o==t.length-1?b=de(D(e),p.decimalsOut).decimalPlaces(0,1):b=r[0].amountIn;let x=await this.poolService.getPoolFees(p.assetIn,u),{amountIn:O,calculatedIn:N,feePct:A,errors:k}=u.validateAndBuy(p,b,x),L=this.getPoolFeeRange(x),E=u.spotPriceInGivenOut(p),q=b.shiftedBy(-1*p.decimalsOut).multipliedBy(E),v;N.isZero()?v=-100:v=Qe(q,N).toNumber(),r.unshift({...a,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountOut:b,calculatedIn:N,amountIn:O,spotPrice:E,tradeFeePct:A,tradeFeeRange:L,priceImpactPct:v,errors:k,toHuman(){return{...a,amountOut:ae(b,p.decimalsOut),calculatedIn:ae(N,p.decimalsIn),amountIn:ae(O,p.decimalsIn),spotPrice:ae(E,p.decimalsIn),tradeFeePct:A,tradeFeeRange:L,priceImpactPct:v,errors:k}}})}return r}};0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,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,StorageConfigNotFound,SubscriptionNotSupported,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,scale});
|