@galacticcouncil/sdk 6.1.1 → 6.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
1
  "use strict";var De=Object.defineProperty;var ft=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames;var St=Object.prototype.hasOwnProperty;var xt=(l,e)=>{for(var t in e)De(l,t,{get:e[t],enumerable:!0})},vt=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of yt(e))!St.call(l,r)&&r!==t&&De(l,r,{get:()=>e[r],enumerable:!(s=ft(e,r))||s.enumerable});return l};var Bt=l=>vt(De({},"__esModule",{value:!0}),l);var qt={};xt(qt,{AMOUNT_MAX:()=>bt,AavePool:()=>fe,AavePoolClient:()=>le,AssetClient:()=>J,AssetNotFound:()=>$e,BASILISK_PARACHAIN_ID:()=>Tt,BalanceClient:()=>W,BigNumber:()=>v.BigNumber,CachingPoolService:()=>Me,DECIMAL_PLACES:()=>ct,DENOMINATOR:()=>Be,FarmClient:()=>Re,HUB_ASSET_ID:()=>oe,HYDRADX_OMNIPOOL_ADDRESS:()=>At,HYDRADX_PARACHAIN_ID:()=>It,HYDRADX_SS58_PREFIX:()=>X,INFINITY:()=>Dt,LbpMath:()=>H,LbpPool:()=>de,LbpPoolClient:()=>ue,ONE:()=>_,OmniMath:()=>B,OmniPool:()=>he,OmniPoolClient:()=>ce,PolkadotApiClient:()=>G,PoolConfigNotFound:()=>Xe,PoolError:()=>$,PoolFactory:()=>se,PoolNotFound:()=>ge,PoolService:()=>te,PoolType:()=>k,ProviderConfigNotFound:()=>Ke,RUNTIME_DECIMALS:()=>Z,RouteNotFound:()=>j,Router:()=>K,SYSTEM_ASSET_DECIMALS:()=>Ot,SYSTEM_ASSET_ID:()=>C,StableMath:()=>E,StableSwap:()=>Pe,StableSwapClient:()=>pe,StorageConfigNotFound:()=>Je,SubscriptionNotSupported:()=>je,TRADEABLE_DEFAULT:()=>V,TradeRouter:()=>ye,TradeType:()=>Ge,XykMath:()=>Y,XykPool:()=>be,XykPoolClient:()=>me,ZERO:()=>b,bnFormatter:()=>Ft,bnum:()=>p,buildRoute:()=>Le,calculateBuyFee:()=>Ve,calculateDiffToAvg:()=>Gt,calculateDiffToRef:()=>re,calculateSellFee:()=>Ze,findNestedKey:()=>qe,findNestedObj:()=>Nt,scale:()=>w});module.exports=Bt(qt);var xe=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 wt=5,ie=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],i=new xe,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let o=i.dequeue();if(o==null||o.length>wt)return r;let a=o[o.length-1];(s===null||a[0]===s)&&r.push(o),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let m=[...o];m.push(c),i.enqueue(m)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,n]of t){let o=parseInt(i),a=parseInt(n);s.get(o)?.push([a,r])}return s}};function Ce(l){let e={};for(let t of l){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let i=0;i<s;i++){if(r==i)continue;let n=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(n)}}}return e}var ne=class{getProposals(e,t,s){let r=Ce(s),i=Object.keys(r),n=i.map(c=>r[c]).flat(),o=new ie,a=o.buildAndPopulateGraph(i,n),u=o.findPaths(a,parseInt(e),t?parseInt(t):null);return this.parsePaths(u)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let n=s[i],o=s[i+1];if(o==null)break;r.push(this.toEdge(n,o))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ve=(l,e=new Map)=>t=>{let s;return e.has(t)?e.get(t):(e.set(t,s=l(t)),s)};var pt=require("@polkadot/util-crypto"),gt=require("@polkadot/util"),dt=require("viem");var Qe=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"}];var et=require("@polkadot/util-crypto"),tt=require("@polkadot/util"),Z=18,V=15,C="0",Ot=12,oe="1",It=2034,X=63,Tt=2090,Be=1e3,At=(0,et.encodeAddress)((0,tt.stringToU8a)("modlomnipool".padEnd(32,"\0")),X);var k=(i=>(i.Aave="Aave",i.LBP="Lbp",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="Xyk",i))(k||{}),$=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))($||{}),Ge=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Ge||{});var we=class{static encodeEvmAddress(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static decodeEvmAddress(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),s=Buffer.from(e.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(t.subarray(0,16))}};function qe(l,e){let t=[];return JSON.stringify(l,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function Nt(l,e,t){let s;return JSON.stringify(l,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}var Ft=(l,e)=>typeof e=="bigint"?e.toString():e;var ae=(l,e)=>l===e?0:l==null?e==null?0:-1:e==null?l==null?0:1:typeof l.compare=="function"?l.compare(e):typeof e.compare=="function"?-e.compare(l):l<e?-1:l>e?1:0;var Oe=(l,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(l(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var _t=Oe(()=>"illegal argument(s)"),st=l=>{throw new _t(l)};var Et=Oe(()=>"index out of bounds"),He=l=>{throw new Et(l)},Ie=(l,e,t)=>(l<e||l>=t)&&He(l);var rt=23283064365386963e-26,Te=class{float(e=1){return this.int()*rt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*rt-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var Ae=class extends Te{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var it=new Ae(Math.random);var nt=l=>l!=null&&typeof l!="function"&&l.length!==void 0;var ot=Object.getPrototypeOf({}),Ne="function",at="string",Q=(l,e)=>{let t;if(l===e)return!0;if(l!=null){if(typeof l.equiv===Ne)return l.equiv(e)}else return l==e;if(e!=null){if(typeof e.equiv===Ne)return e.equiv(l)}else return l==e;return typeof l===at||typeof e===at?!1:(t=Object.getPrototypeOf(l),(t==null||t===ot)&&(t=Object.getPrototypeOf(e),t==null||t===ot)?Mt(l,e):typeof l!==Ne&&l.length!==void 0&&typeof e!==Ne&&e.length!==void 0?Rt(l,e):l instanceof Set&&e instanceof Set?kt(l,e):l instanceof Map&&e instanceof Map?Lt(l,e):l instanceof Date&&e instanceof Date?l.getTime()===e.getTime():l instanceof RegExp&&e instanceof RegExp?l.toString()===e.toString():l!==l&&e!==e)},Rt=(l,e,t=Q)=>{let s=l.length;if(s===e.length)for(;s-- >0&&t(l[s],e[s]););return s<0},kt=(l,e,t=Q)=>l.size===e.size&&t([...l.keys()].sort(),[...e.keys()].sort()),Lt=(l,e,t=Q)=>l.size===e.size&&t([...l].sort(),[...e].sort()),Mt=(l,e,t=Q)=>{if(Object.keys(l).length!==Object.keys(e).length)return!1;for(let s in l)if(!e.hasOwnProperty(s)||!t(l[s],e[s]))return!1;return!0};var ze=class{value;constructor(e){this.value=e}deref(){return this.value}};var lt=l=>l instanceof ze;var Fe=class l{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return ut("next",this._head)}reverseIterator(){return ut("prev",this.tail)}clear(){this.release()}compare(e,t=ae){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,n=0;for(;s-- >0&&n===0;)n=t(r.value,i.value),r=r.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof l||nt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!Q(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||ae;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!lt(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&He(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*ut(l,e){for(;e;)yield e.value,e=e[l]}var _e=class l extends Fe{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new l(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 l}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(Ie(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(Ie(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new l,e)}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let s=this.nthCell(e),r=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==r&&n.next?i(n.next):void 0}});return s?i(s):void 0}shuffle(e,t=it){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&st("invalid indices: ${from} / ${to}");let i=new l,n=this.nthCell(s);for(;n&&++s<=r;)i.push(n.value),n=n.next;return i}sort(e=ae){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,n=0;for(let a=0;a<t&&(n++,i=i.next,!!i);a++);let o=t;for(;n>0||o>0&&i;){let a;n===0?(a=i,i=i.next,o--):!i||o===0||e(s.value,i.value)<=0?(a=s,s=s.next,n--):(a=i,i=i.next,o--),this._tail?this._tail.next=a:this._head=a,a.prev=this._tail,this._tail=a}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),Ie(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new l;if(t>0)for(;r&&t-- >0;)this.remove(r),i.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let n of s)this.insertBefore(r,n);else for(let n of s)this.push(n);return i}};var ee=class l{map;items;opts;_size;constructor(e,t){let s={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=s.map(),this.items=new _e,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new l(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e),i=Math.max(0,s-(r?r.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(r,e,t,s):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let s=this.map.get(e);return s?this.resetEntry(s):this.set(e,await t())}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let{release:e,maxsize:t,maxlen:s}=this.opts;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e?.(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(this.opts.update?.(t,e.value.v,s),e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Ee=class l extends ee{constructor(e,t){super(e,{ttl:60*60*1e3,autoExtend:!1,...t})}empty(){return new l(null,this.opts)}has(e){return this.get(e)!==void 0}get(e,t){let s=this.map.get(e);if(s){if(s.value.t>=Date.now())return this.resetEntry(s);this.removeEntry(s)}return t}set(e,t,s=this.opts.ttl){let r=this.opts.ksize(e)+this.opts.vsize(t),i=this.map.get(e),n=Math.max(0,r-(i?i.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(i,e,t,r,s):this._size-=n,t}async getSet(e,t,s=this.opts.ttl){let r=this.get(e);return r!==void 0?r:this.set(e,await t(),s)}prune(){let e=Date.now(),t=this.items.head,s=0;for(;t;)t.value.t<e&&(this.removeEntry(t),s++),t=t.next;return s}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,s=Date.now(),r=this.items.head;for(;r&&(this._size>t||this.length>=e);)r.value.t<s&&this.removeEntry(r),r=r.next;return super.ensureSize()}doSetEntry(e,t,s,r,i=this.opts.ttl){let n=Date.now()+i;e?(this.opts.update?.(t,e.value.v,s),e.value.v=s,e.value.s=r,e.value.t=n,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r,t:n,ttl:i}),this.map.set(t,this.items.tail))}resetEntry(e){return this.opts.autoExtend&&(e.value.t=Date.now()+e.value.ttl),super.resetEntry(e)}};var Hs=require("@galacticcouncil/api-augment/hydradx"),zs=require("@galacticcouncil/api-augment/basilisk"),G=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let s=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");this.getLogValue(s)&&console.log(e,...t)}getLogValue(e){switch(e){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}};var J=class extends G{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==C){let m=this.api.consts.balances.existentialDeposit;return{id:C,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:o,existentialDeposit:a}=t,{symbol:u,decimals:c}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:u,decimals:c,icon:u,type:n.toHuman(),isSufficient:o?o.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[i,n]=r,{assetType:o,isSufficient:a,existentialDeposit:u}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,s),h=n.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(h)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:m,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:u.toString(),underlyingAssetId:i.toString(),maturity:h}}getShares(e,t,s,r){let{assets:i}=r,{name:n,symbol:o,assetType:a,isSufficient:u,existentialDeposit:c}=t,h=i.map(P=>P.toString()).map(P=>{let{symbol:y}=this.getToken(P,t,s);return[P,y]}),d=Object.fromEntries(h),g=Object.values(d);return{id:e,name:g.join(", "),symbol:o?.isSome?o.toHuman():n.toHuman(),decimals:18,icon:g.join("/"),type:a.toString(),isSufficient:u.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),n=s?.find(o=>o.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:n}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,i,n,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(s),u=this.normalizeMetadata(a,o),c=a.map(([{args:[m]},h])=>{let d=h.unwrap(),g=r.get(m.toString()),{assetType:P}=d;switch(P.toString()){case"Bond":let y=n.get(m.toString());return this.getBond(m.toString(),d,u,y);case"StableSwap":let x=i.get(m.toString());return this.getShares(m.toString(),d,u,x);case"External":return this.getExternal(m.toString(),d,t,g);default:return this.getToken(m.toString(),d,u,g)}});return e?c:c.filter(m=>this.isValidAsset(m))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var v=require("bignumber.js"),ct=12;v.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:ct});var b=p(0),_=p(1),Dt=p("Infinity");function w(l,e){let t=new v.BigNumber(e.toString()),s=new v.BigNumber(10).pow(t);return l.times(s)}function p(l){return new v.BigNumber(l.toString())}var W=class extends G{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===C?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:0n,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(C,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let i=t.filter(n=>n.type!=="Erc20").filter(n=>n.id!==C).map(n=>[e,n.id]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,u)=>{let c=this.calculateFreeBalance(a),m=i[u][1];o.push([m,c])}),s(o)})}async subscribeErc20Balance(e,t,s){let r=t.filter(n=>n.type==="Erc20"),i=async()=>{let n=[];(await Promise.all(r.map(async a=>[a.id,await this.getErc20Balance(e,a.id)]))).forEach(([a,u])=>{n.push([a,u])}),s(n)};return await i(),this.api.rpc.chain.subscribeNewHeads(async()=>{i()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,n=new v.BigNumber(t),o=new v.BigNumber(s||i),a=new v.BigNumber(r||0n),u=o.gt(a)?o:a;return n.minus(u)}};var Ue=require("@polkadot/util-crypto"),We=require("@galacticcouncil/math-liquidity-mining");var mt=require("@polkadot/types"),Ye=require("@polkadot/util"),Re=class extends G{balanceClient;constructor(e){super(e),this.balanceClient=new W(e)}secondsInYear=new v.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,n]=r.args,o=i.unwrap().toString(),a=n.toString(),u=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),g=u.rewardCurrency.toString(),P=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:P.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,n]=r.args,o=i.unwrap().toString(),a=n.toString(),u=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),g=u.rewardCurrency.toString(),P=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:P.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new v.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),o=n.price.n.toString(),a=n.price.d.toString(),u;return Number(t)<Number(s)?u=(0,We.fixed_from_rational)(o,a):u=(0,We.fixed_from_rational)(a,o),u}getGlobalRewardPerPeriod(e,t,s,r){let n=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return n.gte(s)?s:n}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}padEndU8a(e,t){return(0,Ye.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",i=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new mt.GenericAccountId32(e,this.padEndU8a((0,Ye.u8aConcat)(r,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,Ue.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,Ue.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:o,globalFarm:a,priceAdjustment:u,potBalance:c})=>{let m=new v.BigNumber(a.totalSharesZ.toString()),h=a.plannedYieldingPeriods.toString(),d=new v.BigNumber(a.yieldPerPeriod.toString()),g=new v.BigNumber(a.maxRewardPerPeriod.toString()),P=a.blocksPerPeriod.toString(),y=new v.BigNumber(o.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new v.BigNumber(s).times(P)),S;if(m.isZero())S=d.times(y).times(x);else{let D=this.getGlobalRewardPerPeriod(m,d,g,u);S=this.getPoolYieldPerPeriod(D,y,m,u).times(x)}let N=new v.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),F=g.times(h),U=c?N.plus(c):F;return N.div(U).gte(.999)?b:S.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),b).toString():void 0}};var q=class extends W{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Ee(null,{maxlen:1,ttl:60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=ve(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let i=this.subscribePoolChange(t);s.push(i)}catch{}if(t.type==="Aave")return s;let r=this.subscribeTokensPoolBalance(t);if(s.push(r),this.hasSystemAsset(t)){let i=this.subscribeSystemPoolBalance(t);s.push(i)}if(this.hasErc20Asset(t)){let i=this.subscribeErc20PoolBalance(t);s.push(i)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,i])=>{let n=e.tokens.findIndex(o=>o.id==r);n>=0&&t(e,r)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(i=>i.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var Ct=["Supply","Withdraw","Repay","Borrow"],le=class extends q{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:s,liqudityIn:r,liqudityOut:i})=>({address:this.getPoolId(t.toString(),s.toString()),type:"Aave",tokens:[{id:t.toString(),balance:r.toString()},{id:s.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let s=e+"/"+t;return(0,pt.encodeAddress)((0,gt.stringToU8a)(s.padEnd(32,"\0")),X)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);return this.api.query.system.events(i=>{i.forEach(n=>{let{event:o}=n,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:u,assetOut:c}=o.data.toHuman(),m=u.replace(/,/g,""),h=c.replace(/,/g,"");(m===s.id||h===s.id)&&(this.log(`Sync AAVE [router:Executed] :: ${m}:${h}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:u}=o.data.toHuman();try{let{eventName:c,args:m}=(0,dt.decodeEventLog)({abi:Qe,topics:u.topics,data:u.data});Ct.includes(c)&&m.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,s.id);e.tokens=e.tokens.map(n=>{let o=n.id===t.id?r.toString():i.toString();return{...n,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?qe(e.location,"accountKey20").accountKey20.key:we.encodeEvmAddress(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};var z=require("@galacticcouncil/math-lbp"),H=class{static getSpotPrice(e,t,s,r,i){return(0,z.get_spot_price)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return(0,z.calculate_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return(0,z.calculate_out_given_in)(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return(0,z.calculate_linear_weights)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,z.calculate_pool_trade_fee)(e,t,s)}};var ue=class extends q{MAX_FINAL_WEIGHT=w(p(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,n])=>this.isActivePool(n.unwrap(),s)).map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),u=await this.getPoolDelta(a,o,s.toString());return this.poolsData.set(i.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...u,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let n=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,n)}else{let n=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(n,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:n,initialWeight:o,finalWeight:a,repayTarget:u,feeCollector:c}=t,m=H.calculateLinearWeights(r.toString(),i.toString(),o.toString(),a.toString(),s),[h,d]=n,g=h.toString(),P=p(m),y=d.toString(),x=this.MAX_FINAL_WEIGHT.minus(p(P)),[S,N,F]=await Promise.all([this.isRepayFeeApplied(g,u.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,y)]);return{repayFeeApply:S,tokens:[{id:g,weight:P,balance:N.toString()},{id:y,weight:x,balance:F.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=p(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var ht=require("@polkadot/util-crypto"),Pt=require("@polkadot/util");function R(l,e){return l.shiftedBy(-1*e).toString()}function A(l){return l[0]/l[1]*100}function M(l){return l[0]/l[1]}function L(l){return[l/Be,Be]}var f=require("@galacticcouncil/math-omnipool");var B=class{static calculateSpotPrice(e,t,s,r){return(0,f.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,f.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,n,o,a,u){return(0,f.calculate_in_given_out)(e,t,s,r,i,n,o,a,u)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,f.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,n,o,a,u){return(0,f.calculate_out_given_in)(e,t,s,r,i,n,o,a,u)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,f.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,f.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,f.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,n,o,a){return(0,f.calculate_liquidity_out)(e,t,s,r,i,n,o,a)}static calculateLiquidityLRNAOut(e,t,s,r,i,n,o,a){return(0,f.calculate_liquidity_lrna_out)(e,t,s,r,i,n,o,a)}static calculateCapDifference(e,t,s,r){let i=(0,v.BigNumber)(t),n=(0,v.BigNumber)(e),o=(0,v.BigNumber)(r),u=(0,v.BigNumber)(s).shiftedBy(-18);if(i.div(o).lt(u)){let m=u.times(o).minus(i).times(n),h=i.times((0,v.BigNumber)(1).minus(u));return m.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return(0,f.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,f.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,f.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,f.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,f.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,s,r,i,n,o,a,u,c,m){return(0,f.recalculate_asset_fee)(e,t,s,r,i,n,o,a,u,c,m)}static recalculateProtocolFee(e,t,s,r,i,n,o,a,u,c,m){return(0,f.recalculate_protocol_fee)(e,t,s,r,i,n,o,a,u,c,m)}static verifyAssetCap(e,t,s,r){return(0,f.verify_asset_cap)(e,t,s,r)}};var ce=class extends q{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=s.map(async([{args:[a]},u])=>{let{hubReserve:c,shares:m,tradable:h,cap:d,protocolShares:g}=u.unwrap(),P=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:h.bits.toNumber(),balance:P.toString(),cap:p(d.toString()),protocolShares:p(g.toString())}}),o=await Promise.all(n);return o.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,i="omnipool",n="Short",o=F=>F===C?[C,oe]:[oe,F],[a,u,c,m]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(i,o(s),n),this.api.query.emaOracle.oracles(i,o(r),n)]),[h,d,g]=this.getAssetFee(e,a.toNumber(),u,c),[P,y,x]=r===oe?[0,0,0]:this.getProtocolFee(e,a.toNumber(),u,m),S=h+P,N=g+x;return{assetFee:L(d),protocolFee:L(y),min:L(S),max:L(N)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,i)=>{let n=e.tokens[i];if(r.isNone)return n;let o=r.unwrap();return this.updateTokenState(n,o)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i,cap:n,protocolShares:o}=t;return{...e,hubReserves:p(s.toString()),shares:p(r.toString()),cap:p(n.toString()),protocolShares:p(o.toString()),tradeable:i.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:i,balanceOut:n}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,m=L(o.toNumber()),h=L(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{assetFee:g,timestamp:P}=s.unwrap(),y=t-P.toNumber(),x=d.volume.bIn.toString(),S=d.volume.bOut.toString(),N=d.liquidity.b.toString();i===C&&(x=d.volume.aIn.toString(),S=d.volume.aOut.toString(),N=d.liquidity.a.toString());let F=L(g.toNumber()),U=B.recalculateAssetFee(x,S,N,"9",n.toString(),A(F).toString(),y.toString(),A(m).toString(),A(h).toString(),u.toString(),c.toString());return[o.toNumber(),Number(U)*1e4,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:i,balanceIn:n}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,m=L(o.toNumber()),h=L(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{protocolFee:g,timestamp:P}=s.unwrap(),y=t-P.toNumber(),x=d.volume.bIn.toString(),S=d.volume.bOut.toString(),N=d.liquidity.b.toString();i===C&&(x=d.volume.aIn.toString(),S=d.volume.aOut.toString(),N=d.liquidity.a.toString());let F=L(g.toNumber()),U=B.recalculateProtocolFee(x,S,N,"9",n.toString(),A(F).toString(),y.toString(),A(m).toString(),A(h).toString(),u.toString(),c.toString());return[o.toNumber(),Number(U)*1e4,a.toNumber()]}getPoolId(){return(0,ht.encodeAddress)((0,Pt.stringToU8a)("modlomnipool".padEnd(32,"\0")),X)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var me=class extends q{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[n,o]=r.unwrap(),[a,u]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,o.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:a.toString()},{id:o.toString(),balance:u.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var ke=require("@polkadot/util-crypto");var I=require("@galacticcouncil/math-stableswap"),E=class{static getPoolAddress(e){return(0,I.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let s=0;s<e;s++)t.push(["1","1"]);return t}static calculateAmplification(e,t,s,r,i){return(0,I.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,n,o){return(0,I.calculate_in_given_out)(e,t,s,r,i,n,o)}static calculateAddOneAsset(e,t,s,r,i,n,o){return(0,I.calculate_add_one_asset)(e,t,s,r,i,n,o)}static calculateSharesForAmount(e,t,s,r,i,n,o){return(0,I.calculate_shares_for_amount)(e,t,s,r,i,n,o)}static calculateOutGivenIn(e,t,s,r,i,n,o){return(0,I.calculate_out_given_in)(e,t,s,r,i,n,o)}static calculateLiquidityOutOneAsset(e,t,s,r,i,n,o){return(0,I.calculate_liquidity_out_one_asset)(e,t,s,r,i,n,o)}static calculateShares(e,t,s,r,i,n){return(0,I.calculate_shares)(e,t,s,r,i,n)}static calculateSpotPriceWithFee(e,t,s,r,i,n,o,a){return(0,I.calculate_spot_price_with_fee)(e,t,s,r,i,n,o,a)}static calculatePoolTradeFee(e,t,s){return(0,I.calculate_pool_trade_fee)(e,t,s)}static recalculatePegs(e,t,s,r,i){let n=(0,I.recalculate_peg)(e,t,s,r,i);return JSON.parse(n)}};var bt=340282366920938463463374607431768211455n,pe=class extends q{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),u=this.getPoolAddress(a),[c,m,h]=await Promise.all([this.getPoolDelta(a,o,s.toString()),this.getPoolTokens(u,a,o),this.getPoolPegs(a,o,s.toString())]);return this.stablePools.set(u,o),{address:u,id:a,type:"Stableswap",fee:L(o.fee.toNumber()),tokens:m,...c,...h,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toString(),r=this.stablePools.get(e.address);if(r){let[i,n]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,i,n)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:n,finalBlock:o}=t,a=E.calculateAmplification(r.toString(),i.toString(),n.toString(),o.toString(),s),u=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:u.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async o=>{let[a,u]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:a.bits.toNumber(),balance:u.toString()}}),n=await Promise.all(i);return n.push({id:t,tradeable:V,balance:bt.toString()}),n}getPoolDefaultPegs(e){let t=e.fee,s=E.defaultPegs(e.assets.length);return{pegsFee:L(t.toNumber()),pegs:s}}async getPoolPegs(e,t,s){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let r=await this.api.query.stableswap.poolPegs(e);if(r.isNone)return this.getPoolDefaultPegs(t);let i=r.unwrap(),n=await this.getLatestPegs(t,i,s),o=this.getRecentPegs(i),a=i.maxPegUpdate.toHuman(),u=t.fee.toHuman(),[c,m]=E.recalculatePegs(JSON.stringify(o),JSON.stringify(n),s,a.replace(/%/g,""),u.replace(/%/g,"")),h=Number(c)*1e4;return{pegsFee:L(h),pegs:m}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([s,r])=>r.map(i=>i.toString()))}async getLatestPegs(e,t,s){let{source:r}=t,i=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),n=r.map(async(o,a)=>{if(o.isOracle){let[u,c,m]=o.asOracle,h=[m.toString(),i[a]].map(S=>Number(S)).sort((S,N)=>S-N),d=await this.api.query.emaOracle.oracles(u,h,c),[{price:g,updatedAt:P}]=d.unwrap(),y=g.n.toString(),x=g.d.toString();return m.toString()===h[0].toString()?[[y,x],P.toString()]:[[x,y],P.toString()]}else return[o.asValue.map(u=>u.toString()),s]});return Promise.all(n)}getPoolAddress(e){let t=Number(e),s=E.getPoolAddress(t);return(0,ke.encodeAddress)((0,ke.blake2AsHex)(s),X)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function Le(l){return l.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var ge=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Xe=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},j=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},$e=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Je=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},je=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Ke=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var te=class extends G{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=ve(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new J(this.api),this.aaveClient=new le(this.api),this.xykClient=new me(this.api),this.omniClient=new ce(this.api),this.lbpClient=new ue(this.api),this.stableClient=new pe(this.api),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}unsubscribe(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new ge(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let n;this.isDirectOmnipoolTrade(i)?n=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):n=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),Le(i));let o=()=>n;return{hex:n.toHex(),name:"RouterBuy",get:o}}buildSellTx(e,t,s,r,i){let n;this.isDirectOmnipoolTrade(i)?n=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):n=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),Le(i));let o=()=>n;return{hex:n.toHex(),name:"RouterSell",get:o}}};var Me=class extends te{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new ee(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){this.log(`Destroying pool cache!
2
- Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var de=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,n,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=n,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let o=this.calculateTradeFee(t,s),a=A(this.repayFeeApply?s.repayFee:s.exchangeFee),u=t.plus(o),c=this.calculateInGivenOut(e,u),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:i}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,s),u=A(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:u,errors:i}}}calculateInGivenOut(e,t){let s=H.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=H.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=H.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),w(_,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=H.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),w(_,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let s=H.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(s)}};var he=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,n){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=n}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance),a=p(r.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=i.minus(r),o=r===b?b:n.div(r).multipliedBy(100).decimalPlaces(2),a=[],u=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&a.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(h)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),o=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),a=[],u=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&a.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(h)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=B.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?M(s.assetFee).toString():b.toString(),s?M(s.protocolFee).toString():b.toString()),i=p(r);return i.isNegative()?b:i}calculateLrnaInGivenOut(e,t,s){let r=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?M(s.assetFee).toString():b.toString()),i=p(r);return i.isNegative()?b:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=B.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?M(s.assetFee).toString():b.toString(),s?M(s.protocolFee).toString():b.toString()),i=p(r);return i.isNegative()?b:i}calculateOutGivenLrnaIn(e,t,s){let r=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?M(s.assetFee).toString():b.toString()),i=p(r);return i.isNegative()?b:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=B.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(Z-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=B.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(Z-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=B.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(Z-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(Z-e.decimalsIn)).decimalPlaces(0,1)}};var Pe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,i,n,o,a,u,c,m){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=n,this.id=o,this.fee=a,this.totalIssuance=u,this.pegs=c,this.pegsFee=m}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance),a=p(r.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?V:r.tradeable,tradeableOut:this.id===t?V:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=A(s.fee),o=[],a=B.isSellAllowed(e.tradeableIn),u=B.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),n=A(s.fee),o=[],a=B.isSellAllowed(e.tradeableIn),u=B.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:n,errors:o}}calculateIn(e,t,s){let r=E.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?M(s.fee).toString():b.toString(),this.getPegs()),i=p(r);return i.isNegative()?b:i}calculateAddOneAsset(e,t,s){let r=E.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?M(s.fee).toString():b.toString(),this.getPegs()),i=p(r);return i.isNegative()?b:i}calculateSharesForAmount(e,t,s){let r=E.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?M(s.fee).toString():b.toString(),this.getPegs()),i=p(r);return i.isNegative()?b:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=E.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let r=w(_,e.decimalsIn-e.decimalsOut);return p(t).div(r)}let s=w(_,18-e.decimalsIn);return p(t).div(s)}calculateOut(e,t,s){let r=E.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?M(s.fee).toString():b.toString(),this.getPegs()),i=p(r);return i.isNegative()?b:i}calculateWithdrawOneAsset(e,t,s){let r=E.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?M(s.fee).toString():b.toString(),this.getPegs()),i=p(r);return i.isNegative()?b:i}calculateShares(e,t,s){let r=E.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?M(s.fee).toString():b.toString(),this.getPegs()),i=p(r);return i.isNegative()?b:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=E.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let r=w(_,e.decimalsOut-e.decimalsIn);return p(t).div(r)}let s=w(_,18-e.decimalsOut);return p(t).div(s)}calculateTradeFee(e,t){let s=E.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return p(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var T=require("@galacticcouncil/math-xyk"),Y=class{static getSpotPrice(e,t,s){return(0,T.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,T.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,T.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,T.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,T.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,T.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,T.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,T.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,T.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,T.calculate_liquidity_out_asset_b)(e,t,s,r)}};var be=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance),a=p(r.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),n=A(s.exchangeFee),o=r.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),n=A(s.exchangeFee),o=r.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:n,errors:a}}calculateInGivenOut(e,t){let s=Y.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=Y.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=Y.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=w(_,18-e.decimalsOut);return p(t).div(s)}spotPriceOutGivenIn(e){let t=Y.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=w(_,18-e.decimalsIn);return p(t).div(s)}calculateTradeFee(e,t){let s=Y.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(s)}};var fe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:b,assetOutED:b}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=[],n=e.balanceOut;t.isGreaterThan(n)&&i.push("TradeNotAllowed");let o=e.balanceIn;return r.isGreaterThan(o)&&i.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=[],n=e.balanceIn;t.isGreaterThan(n)&&i.push("TradeNotAllowed");let o=e.balanceOut;return r.isGreaterThan(o)&&i.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:i}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return w(_,e.decimalsOut)}spotPriceOutGivenIn(e){return w(_,e.decimalsIn)}calculateTradeFee(e,t){return b}};var se=class{static get(e){switch(e.type){case"Aave":return fe.fromPool(e);case"Xyk":return be.fromPool(e);case"Omnipool":return he.fromPool(e);case"Lbp":return de.fromPool(e);case"Stableswap":return Pe.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var K=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new ne,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),n=this.getPaths(e,null,r,t).map(o=>o[o.length-1].assetOut);return this.toAssets([...new Set(n)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,meta:r.meta,location:r.location,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,se.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let n=t.get(s);return{poolAddress:s,poolId:n?.id,pool:n?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function Gt(l,e){return l.minus(e).abs().div(l.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function re(l,e){return l.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ze(l,e){return _.minus(e.div(l)).multipliedBy(100).decimalPlaces(2)}function Ve(l,e){return e.div(l).minus(_).multipliedBy(100).decimalPlaces(2)}var ye=class extends K{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,n=r[r.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[s,r]}}getPoolFeeRange(e){let t=e.min?A(e.min):void 0,s=e.max?A(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new j(e,t);let a;if(r)a=await this.toSellSwaps(s,r,n);else{let O=o.map(async Se=>await this.toSellSwaps(s,Se,n)),D=await Promise.all(O);a=this.findBestSellRoute(D)}let u=a[0],c=a[a.length-1],m=this.isDirectTrade(a),h=a.map(O=>O.spotPrice.shiftedBy(-1*O.assetOutDecimals)).reduce((O,D)=>O.multipliedBy(D)),d=w(h,c.assetOutDecimals),g=m?c.calculatedOut:this.calculateDelta0Y(u.amountIn,a,n),P=c.amountOut,y=m?c.tradeFeePct:Ze(g,P).toNumber(),x=g.minus(P),S=this.getRouteFeeRange(a),N=u.amountIn.shiftedBy(-1*u.assetInDecimals).multipliedBy(d),F=re(g,N),U=O=>this.poolService.buildSellTx(e,t,u.amountIn,O,a.map(D=>D));return{type:"Sell",amountIn:u.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:x,tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F.toNumber(),swaps:a,toTx:U,toHuman(){return{type:"Sell",amountIn:R(u.amountIn,u.assetInDecimals),amountOut:R(c.amountOut,c.assetOutDecimals),spotPrice:R(d,c.assetOutDecimals),tradeFee:R(x,c.assetOutDecimals),tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F.toNumber(),swaps:a.map(O=>O.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i>0?u=r[i-1]:u=e;let c=o.calculateOutGivenIn(a,u);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i>0?u=r[i-1].amountOut:u=w(p(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:m,calculatedOut:h,feePct:d,errors:g}=o.validateAndSell(a,u,c),P=this.getPoolFeeRange(c),y=o.spotPriceOutGivenIn(a),x=u.shiftedBy(-1*a.decimalsIn).multipliedBy(y),S=re(h,x);r.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,calculatedOut:h,amountOut:m,spotPrice:y,tradeFeePct:d,tradeFeeRange:P,priceImpactPct:S.toNumber(),errors:g,toHuman(){return{...n,amountIn:R(u,a.decimalsIn),calculatedOut:R(h,a.decimalsOut),amountOut:R(m,a.decimalsOut),spotPrice:R(y,a.decimalsOut),tradeFeePct:d,tradeFeeRange:P,priceImpactPct:S.toNumber(),errors:g}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)throw new j(e,t);let n=s.map(g=>g.tokens.find(P=>P.id===e)).filter(g=>!!g).sort((g,P)=>Number(P.balance)-Number(g.balance)),{balance:o,decimals:a}=n[0],c=p(o).shiftedBy(-1*a).div(100).multipliedBy(.1),m=i.map(async g=>await this.toSellSwaps(c,g,r)),h=await Promise.all(m);return this.findBestSellRoute(h).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut}))}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s);if(super.getPaths(e,t,r,s).length===0)return Promise.resolve(void 0);let n=await this.getMostLiquidRoute(e,t),o=await this.toSellSwaps("1",n,r),a=o.map(m=>m.spotPrice.shiftedBy(-1*m.assetOutDecimals)).reduce((m,h)=>m.multipliedBy(h)),u=o[o.length-1].assetOutDecimals;return{amount:w(a,u),decimals:u}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,n=r[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new j(e,t);let a;if(r)a=await this.toBuySwaps(s,r,n);else{let O=o.map(async Se=>await this.toBuySwaps(s,Se,n)),D=await Promise.all(O);a=this.findBestBuyRoute(D)}let u=a[a.length-1],c=a[0],m=this.isDirectTrade(a),h=a.map(O=>O.spotPrice.shiftedBy(-1*O.assetInDecimals)).reduce((O,D)=>O.multipliedBy(D)),d=w(h,c.assetInDecimals),g=m?c.calculatedIn:this.calculateDelta0X(u.amountOut,a,n),P=c.amountIn,y=m?c.tradeFeePct:Ve(g,P).toNumber(),x=P.minus(g),S=this.getRouteFeeRange(a),N=u.amountOut.shiftedBy(-1*u.assetOutDecimals).multipliedBy(d),F;g.isZero()?F=-100:F=re(N,g).toNumber();let U=O=>this.poolService.buildBuyTx(e,t,u.amountOut,O,a.map(D=>D));return{type:"Buy",amountOut:u.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:x,tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F,swaps:a,toTx:U,toHuman(){return{type:"Buy",amountOut:R(u.amountOut,u.assetOutDecimals),amountIn:R(c.amountIn,c.assetInDecimals),spotPrice:R(d,c.assetInDecimals),tradeFee:R(x,c.assetInDecimals),tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F,swaps:a.map(O=>O.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=e:u=r[0];let c=o.calculateInGivenOut(a,u);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=w(p(e),a.decimalsOut).decimalPlaces(0,1):u=r[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:m,calculatedIn:h,feePct:d,errors:g}=o.validateAndBuy(a,u,c),P=this.getPoolFeeRange(c),y=o.spotPriceInGivenOut(a),x=u.shiftedBy(-1*a.decimalsOut).multipliedBy(y),S;h.isZero()?S=-100:S=re(x,h).toNumber(),r.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:u,calculatedIn:h,amountIn:m,spotPrice:y,tradeFeePct:d,tradeFeeRange:P,priceImpactPct:S,errors:g,toHuman(){return{...n,amountOut:R(u,a.decimalsOut),calculatedIn:R(h,a.decimalsIn),amountIn:R(m,a.decimalsIn),spotPrice:R(y,a.decimalsIn),tradeFeePct:d,tradeFeeRange:P,priceImpactPct:S,errors:g}}})}return r}};0&&(module.exports={AMOUNT_MAX,AavePool,AavePoolClient,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,FarmClient,HUB_ASSET_ID,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,ONE,OmniMath,OmniPool,OmniPoolClient,PolkadotApiClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StableSwapClient,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
2
+ Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var de=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,n,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=n,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let o=this.calculateTradeFee(t,s),a=A(this.repayFeeApply?s.repayFee:s.exchangeFee),u=t.plus(o),c=this.calculateInGivenOut(e,u),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:i}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,s),u=A(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:u,errors:i}}}calculateInGivenOut(e,t){let s=H.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=H.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=H.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),w(_,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=H.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),w(_,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let s=H.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(s)}};var he=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,n){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=n}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance),a=p(r.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=i.minus(r),o=r===b?b:n.div(r).multipliedBy(100).decimalPlaces(2),a=[],u=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&a.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(h)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),o=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),a=[],u=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&a.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(h)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=B.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?M(s.assetFee).toString():b.toString(),s?M(s.protocolFee).toString():b.toString()),i=p(r);return i.isNegative()?b:i}calculateLrnaInGivenOut(e,t,s){let r=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?M(s.assetFee).toString():b.toString()),i=p(r);return i.isNegative()?b:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=B.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?M(s.assetFee).toString():b.toString(),s?M(s.protocolFee).toString():b.toString()),i=p(r);return i.isNegative()?b:i}calculateOutGivenLrnaIn(e,t,s){let r=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?M(s.assetFee).toString():b.toString()),i=p(r);return i.isNegative()?b:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=B.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(Z-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=B.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(Z-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=B.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(Z-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(Z-e.decimalsIn)).decimalPlaces(0,1)}};var Pe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,i,n,o,a,u,c,m){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=n,this.id=o,this.fee=a,this.totalIssuance=u,this.pegs=c,this.pegsFee=m}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance),a=p(r.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?V:r.tradeable,tradeableOut:this.id===t?V:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=A(s.fee),o=[],a=B.isSellAllowed(e.tradeableIn),u=B.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),n=A(s.fee),o=[],a=B.isSellAllowed(e.tradeableIn),u=B.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:n,errors:o}}calculateIn(e,t,s){let r=E.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?M(s.fee).toString():b.toString(),this.getPegs()),i=p(r);return i.isNegative()?b:i}calculateAddOneAsset(e,t,s){let r=E.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?M(s.fee).toString():b.toString(),this.getPegs()),i=p(r);return i.isNegative()?b:i}calculateSharesForAmount(e,t,s){let r=E.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?M(s.fee).toString():b.toString(),this.getPegs()),i=p(r);return i.isNegative()?b:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=E.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let r=w(_,e.decimalsIn-e.decimalsOut);return p(t).div(r)}let s=w(_,18-e.decimalsIn);return p(t).div(s)}calculateOut(e,t,s){let r=E.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?M(s.fee).toString():b.toString(),this.getPegs()),i=p(r);return i.isNegative()?b:i}calculateWithdrawOneAsset(e,t,s){let r=E.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?M(s.fee).toString():b.toString(),this.getPegs()),i=p(r);return i.isNegative()?b:i}calculateShares(e,t,s){let r=E.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?M(s.fee).toString():b.toString(),this.getPegs()),i=p(r);return i.isNegative()?b:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=E.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let r=w(_,e.decimalsOut-e.decimalsIn);return p(t).div(r)}let s=w(_,18-e.decimalsOut);return p(t).div(s)}calculateTradeFee(e,t){let s=E.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return p(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var T=require("@galacticcouncil/math-xyk"),Y=class{static getSpotPrice(e,t,s){return(0,T.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,T.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,T.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,T.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,T.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,T.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,T.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,T.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,T.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,T.calculate_liquidity_out_asset_b)(e,t,s,r)}};var be=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance),a=p(r.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),n=A(s.exchangeFee),o=r.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),n=A(s.exchangeFee),o=r.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:n,errors:a}}calculateInGivenOut(e,t){let s=Y.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=Y.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=Y.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=w(_,18-e.decimalsOut);return p(t).div(s)}spotPriceOutGivenIn(e){let t=Y.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=w(_,18-e.decimalsIn);return p(t).div(s)}calculateTradeFee(e,t){let s=Y.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(s)}};var fe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),o=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:b,assetOutED:b}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=[],n=e.balanceOut;t.isGreaterThan(n)&&i.push("TradeNotAllowed");let o=e.balanceIn;return r.isGreaterThan(o)&&i.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=[],n=e.balanceIn;t.isGreaterThan(n)&&i.push("TradeNotAllowed");let o=e.balanceOut;return r.isGreaterThan(o)&&i.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:i}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return w(_,e.decimalsOut)}spotPriceOutGivenIn(e){return w(_,e.decimalsIn)}calculateTradeFee(e,t){return b}};var se=class{static get(e){switch(e.type){case"Aave":return fe.fromPool(e);case"Xyk":return be.fromPool(e);case"Omnipool":return he.fromPool(e);case"Lbp":return de.fromPool(e);case"Stableswap":return Pe.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var K=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new ne,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),n=this.getPaths(e,null,r,t).map(o=>o[o.length-1].assetOut);return this.toAssets([...new Set(n)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,meta:r.meta,location:r.location,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(s);return{assets:r,poolsMap:i}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,se.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,i])=>{let n=t.get(s);return{poolAddress:s,poolId:n?.id,pool:n?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function Gt(l,e){return l.minus(e).abs().div(l.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function re(l,e){return l.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ze(l,e){return _.minus(e.div(l)).multipliedBy(100).decimalPlaces(2)}function Ve(l,e){return e.div(l).minus(_).multipliedBy(100).decimalPlaces(2)}var ye=class extends K{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,n=r[r.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[s,r]}}getPoolFeeRange(e){let t=e.min?A(e.min):void 0,s=e.max?A(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new j(e,t);let a;if(r)a=await this.toSellSwaps(s,r,n);else{let O=o.map(async Se=>await this.toSellSwaps(s,Se,n)),D=await Promise.all(O);a=this.findBestSellRoute(D)}let u=a[0],c=a[a.length-1],m=this.isDirectTrade(a),h=a.map(O=>O.spotPrice.shiftedBy(-1*O.assetOutDecimals)).reduce((O,D)=>O.multipliedBy(D)),d=w(h,c.assetOutDecimals),g=m?c.calculatedOut:this.calculateDelta0Y(u.amountIn,a,n),P=c.amountOut,y=m?c.tradeFeePct:Ze(g,P).toNumber(),x=g.minus(P),S=this.getRouteFeeRange(a),N=u.amountIn.shiftedBy(-1*u.assetInDecimals).multipliedBy(d),F=re(g,N),U=O=>this.poolService.buildSellTx(e,t,u.amountIn,O,a.map(D=>D));return{type:"Sell",amountIn:u.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:x,tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F.toNumber(),swaps:a,toTx:U,toHuman(){return{type:"Sell",amountIn:R(u.amountIn,u.assetInDecimals),amountOut:R(c.amountOut,c.assetOutDecimals),spotPrice:R(d,c.assetOutDecimals),tradeFee:R(x,c.assetOutDecimals),tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F.toNumber(),swaps:a.map(O=>O.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i>0?u=r[i-1]:u=e;let c=o.calculateOutGivenIn(a,u);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i>0?u=r[i-1].amountOut:u=w(p(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:m,calculatedOut:h,feePct:d,errors:g}=o.validateAndSell(a,u,c),P=this.getPoolFeeRange(c),y=o.spotPriceOutGivenIn(a),x=u.shiftedBy(-1*a.decimalsIn).multipliedBy(y),S=re(h,x);r.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,calculatedOut:h,amountOut:m,spotPrice:y,tradeFeePct:d,tradeFeeRange:P,priceImpactPct:S.toNumber(),errors:g,toHuman(){return{...n,amountIn:R(u,a.decimalsIn),calculatedOut:R(h,a.decimalsOut),amountOut:R(m,a.decimalsOut),spotPrice:R(y,a.decimalsOut),tradeFeePct:d,tradeFeeRange:P,priceImpactPct:S.toNumber(),errors:g}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)throw new j(e,t);let n=s.map(g=>g.tokens.find(P=>P.id===e&&P.id!==g.id)).filter(g=>!!g).sort((g,P)=>Number(P.balance)-Number(g.balance)),{balance:o,decimals:a}=n[0],c=p(o).shiftedBy(-1*a).div(100).multipliedBy(.1),m=i.map(async g=>await this.toSellSwaps(c,g,r)),h=await Promise.all(m);return this.findBestSellRoute(h).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut}))}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s);if(super.getPaths(e,t,r,s).length===0)return Promise.resolve(void 0);let n=await this.getMostLiquidRoute(e,t),o=await this.toSellSwaps("1",n,r),a=o.map(m=>m.spotPrice.shiftedBy(-1*m.assetOutDecimals)).reduce((m,h)=>m.multipliedBy(h)),u=o[o.length-1].assetOutDecimals;return{amount:w(a,u),decimals:u}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,n=r[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new j(e,t);let a;if(r)a=await this.toBuySwaps(s,r,n);else{let O=o.map(async Se=>await this.toBuySwaps(s,Se,n)),D=await Promise.all(O);a=this.findBestBuyRoute(D)}let u=a[a.length-1],c=a[0],m=this.isDirectTrade(a),h=a.map(O=>O.spotPrice.shiftedBy(-1*O.assetInDecimals)).reduce((O,D)=>O.multipliedBy(D)),d=w(h,c.assetInDecimals),g=m?c.calculatedIn:this.calculateDelta0X(u.amountOut,a,n),P=c.amountIn,y=m?c.tradeFeePct:Ve(g,P).toNumber(),x=P.minus(g),S=this.getRouteFeeRange(a),N=u.amountOut.shiftedBy(-1*u.assetOutDecimals).multipliedBy(d),F;g.isZero()?F=-100:F=re(N,g).toNumber();let U=O=>this.poolService.buildBuyTx(e,t,u.amountOut,O,a.map(D=>D));return{type:"Buy",amountOut:u.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:x,tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F,swaps:a,toTx:U,toHuman(){return{type:"Buy",amountOut:R(u.amountOut,u.assetOutDecimals),amountIn:R(c.amountIn,c.assetInDecimals),spotPrice:R(d,c.assetInDecimals),tradeFee:R(x,c.assetInDecimals),tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F,swaps:a.map(O=>O.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=e:u=r[0];let c=o.calculateInGivenOut(a,u);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=s.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=w(p(e),a.decimalsOut).decimalPlaces(0,1):u=r[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:m,calculatedIn:h,feePct:d,errors:g}=o.validateAndBuy(a,u,c),P=this.getPoolFeeRange(c),y=o.spotPriceInGivenOut(a),x=u.shiftedBy(-1*a.decimalsOut).multipliedBy(y),S;h.isZero()?S=-100:S=re(x,h).toNumber(),r.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:u,calculatedIn:h,amountIn:m,spotPrice:y,tradeFeePct:d,tradeFeeRange:P,priceImpactPct:S,errors:g,toHuman(){return{...n,amountOut:R(u,a.decimalsOut),calculatedIn:R(h,a.decimalsIn),amountIn:R(m,a.decimalsIn),spotPrice:R(y,a.decimalsIn),tradeFeePct:d,tradeFeeRange:P,priceImpactPct:S,errors:g}}})}return r}};0&&(module.exports={AMOUNT_MAX,AavePool,AavePoolClient,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,FarmClient,HUB_ASSET_ID,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,ONE,OmniMath,OmniPool,OmniPoolClient,PolkadotApiClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StableSwapClient,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
package/build/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  var te=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 _e=5,z=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],o=new te,n=[];for(n.push([t,""]),o.enqueue(n);o.size()>0;){let i=o.dequeue();if(i==null||i.length>_e)return r;let a=i[i.length-1];(s===null||a[0]===s)&&r.push(i),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,i)){let u=[...i];u.push(c),o.enqueue(u)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,o,n]of t){let i=parseInt(o),a=parseInt(n);s.get(i)?.push([a,r])}return s}};function be(p){let e={};for(let t of p){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let o=0;o<s;o++){if(r==o)continue;let n=[t.address,t.tokens[r].id,t.tokens[o].id];e[t.tokens[r].id].push(n)}}}return e}var J=class{getProposals(e,t,s){let r=be(s),o=Object.keys(r),n=o.map(c=>r[c]).flat(),i=new z,a=i.buildAndPopulateGraph(o,n),l=i.findPaths(a,parseInt(e),t?parseInt(t):null);return this.parsePaths(l)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let o=0;o<s.length;o++){let n=s[o],i=s[o+1];if(i==null)break;r.push(this.toEdge(n,i))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};import{memoize1 as Ft}from"@thi.ng/memoize";import{encodeAddress as He}from"@polkadot/util-crypto";import{stringToU8a as Ue}from"@polkadot/util";import{decodeEventLog as We}from"viem";var Be=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"}];import{encodeAddress as Le}from"@polkadot/util-crypto";import{stringToU8a as De}from"@polkadot/util";var K=18,j=15,L="0",as=12,se="1",ls=2034,U=63,cs=2090,he=1e3,us=Le(De("modlomnipool".padEnd(32,"\0")),U);var R=(o=>(o.Aave="Aave",o.LBP="Lbp",o.Omni="Omnipool",o.Stable="Stableswap",o.XYK="Xyk",o))(R||{}),W=(o=>(o.UnknownError="UnknownError",o.InsufficientTradingAmount="InsufficientTradingAmount",o.MaxInRatioExceeded="MaxInRatioExceeded",o.MaxOutRatioExceeded="MaxOutRatioExceeded",o.TradeNotAllowed="TradeNotAllowed",o))(W||{}),Oe=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Oe||{});var re=class{static encodeEvmAddress(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static decodeEvmAddress(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),s=Buffer.from(e.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(t.subarray(0,16))}};function xe(p,e){let t=[];return JSON.stringify(p,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function ds(p,e,t){let s;return JSON.stringify(p,(r,o)=>(o&&o[e]===t&&(s=o),o)),s}var Ps=(p,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as Ge}from"@thi.ng/memoize";import{TLRUCache as qe}from"@thi.ng/cache";import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var M=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let s=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");this.getLogValue(s)&&console.log(e,...t)}getLogValue(e){switch(e){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}};var X=class extends M{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:o}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:o.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==L){let u=this.api.consts.balances.existentialDeposit;return{id:L,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:u.toString()}}let{name:o,assetType:n,isSufficient:i,existentialDeposit:a}=t,{symbol:l,decimals:c}=s.get(e)??{};return{id:e,name:o.toHuman(),symbol:l,decimals:c,icon:l,type:n.toHuman(),isSufficient:i?i.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[o,n]=r,{assetType:i,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(o.toString(),t,s),P=n.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(P)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:u,icon:c,type:i.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:o.toString(),maturity:P}}getShares(e,t,s,r){let{assets:o}=r,{name:n,symbol:i,assetType:a,isSufficient:l,existentialDeposit:c}=t,P=o.map(b=>b.toString()).map(b=>{let{symbol:f}=this.getToken(b,t,s);return[b,f]}),d=Object.fromEntries(P),g=Object.values(d);return{id:e,name:g.join(", "),symbol:i?.isSome?i.toHuman():n.toHuman(),decimals:18,icon:g.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,s,r){let o=this.getToken(e,t,new Map,r),n=s?.find(i=>i.internalId===o.id);return n?{...o,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:o}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:o,symbol:n}=r.unwrap();return[s.toString(),{decimals:Number(o.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,o,n,i]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(s),l=this.normalizeMetadata(a,i),c=a.map(([{args:[u]},P])=>{let d=P.unwrap(),g=r.get(u.toString()),{assetType:b}=d;switch(b.toString()){case"Bond":let f=n.get(u.toString());return this.getBond(u.toString(),d,l,f);case"StableSwap":let S=o.get(u.toString());return this.getShares(u.toString(),d,l,S);case"External":return this.getExternal(u.toString(),d,t,g);default:return this.getToken(u.toString(),d,l,g)}});return e?c:c.filter(u=>this.isValidAsset(u))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};import{BigNumber as B}from"bignumber.js";var Me=12;B.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Me});var h=m(0),v=m(1),ws=m("Infinity");function w(p,e){let t=new B(e.toString()),s=new B(10).pow(t);return p.times(s)}function m(p){return new B(p.toString())}var q=class extends M{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===L?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:o}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:o})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:o}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:0n,frozen:o})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(L,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let o=t.filter(n=>n.type!=="Erc20").filter(n=>n.id!==L).map(n=>[e,n.id]);return this.api.query.tokens.accounts.multi(o,n=>{let i=[];n.forEach((a,l)=>{let c=this.calculateFreeBalance(a),u=o[l][1];i.push([u,c])}),s(i)})}async subscribeErc20Balance(e,t,s){let r=t.filter(n=>n.type==="Erc20"),o=async()=>{let n=[];(await Promise.all(r.map(async a=>[a.id,await this.getErc20Balance(e,a.id)]))).forEach(([a,l])=>{n.push([a,l])}),s(n)};return await o(),this.api.rpc.chain.subscribeNewHeads(async()=>{o()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:o}=e,n=new B(t),i=new B(s||o),a=new B(r||0n),l=i.gt(a)?i:a;return n.minus(l)}};import{isAddress as we}from"@polkadot/util-crypto";import{fixed_from_rational as Ie}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as Ce}from"@polkadot/types";import{u8aConcat as Te}from"@polkadot/util";var fe=class extends M{balanceClient;constructor(e){super(e),this.balanceClient=new q(e)}secondsInYear=new B(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,o])=>{let[,n]=r.args,i=o.unwrap().toString(),a=n.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,i)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,o])=>{let[,n]=r.args,i=o.unwrap().toString(),a=n.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,i)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new B(1).shiftedBy(18).toString();let o=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(o.isNone)return;let[n]=o.unwrap(),i=n.price.n.toString(),a=n.price.d.toString(),l;return Number(t)<Number(s)?l=Ie(i,a):l=Ie(a,i),l}getGlobalRewardPerPeriod(e,t,s,r){let n=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return n.gte(s)?s:n}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}padEndU8a(e,t){return Te(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",o=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Ce(e,this.padEndU8a(Te(r,o,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!we(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&we(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:i,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let u=new B(a.totalSharesZ.toString()),P=a.plannedYieldingPeriods.toString(),d=new B(a.yieldPerPeriod.toString()),g=new B(a.maxRewardPerPeriod.toString()),b=a.blocksPerPeriod.toString(),f=new B(i.multiplier.toString()).shiftedBy(-18),S=this.secondsInYear.div(new B(s).times(b)),y;if(u.isZero())y=d.times(f).times(S);else{let _=this.getGlobalRewardPerPeriod(u,d,g,l);y=this.getPoolYieldPerPeriod(_,f,u,l).times(S)}let T=new B(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),A=g.times(P),G=c?T.plus(c):A;return T.div(G).gte(.999)?h:y.div(t==="isolatedpool"?2:1).times(100)}).reduce((i,a)=>i.plus(a),h).toString():void 0}};var D=class extends q{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new qe(null,{maxlen:1,ttl:60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=Ge(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let o=this.subscribePoolChange(t);s.push(o)}catch{}if(t.type==="Aave")return s;let r=this.subscribeTokensPoolBalance(t);if(s.push(r),this.hasSystemAsset(t)){let o=this.subscribeSystemPoolBalance(t);s.push(o)}if(this.hasErc20Asset(t)){let o=this.subscribeErc20PoolBalance(t);s.push(o)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,o])=>{let n=e.tokens.findIndex(i=>i.id==r);n>=0&&t(e,r)&&(e.tokens[n].balance=o.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(o=>o.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var Xe=["Supply","Withdraw","Repay","Borrow"],oe=class extends D{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:s,liqudityIn:r,liqudityOut:o})=>({address:this.getPoolId(t.toString(),s.toString()),type:"Aave",tokens:[{id:t.toString(),balance:r.toString()},{id:s.toString(),balance:o.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let s=e+"/"+t;return He(Ue(s.padEnd(32,"\0")),U)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);return this.api.query.system.events(o=>{o.forEach(n=>{let{event:i}=n,a=`${i.section}:${i.method}`;if(a==="router:Executed"){let{assetIn:l,assetOut:c}=i.data.toHuman(),u=l.replace(/,/g,""),P=c.replace(/,/g,"");(u===s.id||P===s.id)&&(this.log(`Sync AAVE [router:Executed] :: ${u}:${P}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=i.data.toHuman();try{let{eventName:c,args:u}=We({abi:Be,topics:l.topics,data:l.data});Xe.includes(c)&&u.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut:o}=await this.api.call.aaveTradeExecutor.pool(t.id,s.id);e.tokens=e.tokens.map(n=>{let i=n.id===t.id?r.toString():o.toString();return{...n,balance:i}})}getReserveH160Id(e){return e.type==="Erc20"?xe(e.location,"accountKey20").accountKey20.key:re.encodeEvmAddress(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as Ye,calculate_out_given_in as $e,calculate_linear_weights as ze,calculate_pool_trade_fee as Je,get_spot_price as Ke}from"@galacticcouncil/math-lbp";var C=class{static getSpotPrice(e,t,s,r,o){return Ke(e,t,s,r,o)}static calculateInGivenOut(e,t,s,r,o){return Ye(e,t,s,r,o)}static calculateOutGivenIn(e,t,s,r,o){return $e(e,t,s,r,o)}static calculateLinearWeights(e,t,s,r,o){return ze(e,t,s,r,o)}static calculatePoolTradeFee(e,t,s){return Je(e,t,s)}};var ie=class extends D{MAX_FINAL_WEIGHT=w(m(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([o,n])=>this.isActivePool(n.unwrap(),s)).map(async([{args:[o]},n])=>{let i=n.unwrap(),a=o.toString(),l=await this.getPoolDelta(a,i,s.toString());return this.poolsData.set(o.toString(),i),{address:a,type:"Lbp",fee:i.fee.toJSON(),...l,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let n=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,n)}else{let n=this.pools.findIndex(i=>i.address==e.address);this.pools.splice(n,1)}})}async getPoolDelta(e,t,s){let{start:r,end:o,assets:n,initialWeight:i,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=C.calculateLinearWeights(r.toString(),o.toString(),i.toString(),a.toString(),s),[P,d]=n,g=P.toString(),b=m(u),f=d.toString(),S=this.MAX_FINAL_WEIGHT.minus(m(b)),[y,T,A]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,f)]);return{repayFeeApply:y,tokens:[{id:g,weight:b,balance:T.toString()},{id:f,weight:S,balance:A.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=m(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{encodeAddress as dt}from"@polkadot/util-crypto";import{stringToU8a as Pt}from"@polkadot/util";function N(p,e){return p.shiftedBy(-1*e).toString()}function I(p){return p[0]/p[1]*100}function k(p){return p[0]/p[1]}function E(p){return[p/he,he]}import{calculate_in_given_out as je,calculate_lrna_in_given_out as Ze,calculate_out_given_in as Ve,calculate_out_given_lrna_in as Qe,calculate_pool_trade_fee as et,calculate_spot_price as tt,calculate_lrna_spot_price as st,calculate_shares as rt,calculate_liquidity_out as ot,calculate_liquidity_lrna_out as it,calculate_liquidity_hub_in as nt,is_sell_allowed as at,is_buy_allowed as lt,is_add_liquidity_allowed as ct,is_remove_liquidity_allowed as ut,recalculate_asset_fee as mt,recalculate_protocol_fee as pt,verify_asset_cap as gt}from"@galacticcouncil/math-omnipool";var O=class{static calculateSpotPrice(e,t,s,r){return tt(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return st(e,t)}static calculateInGivenOut(e,t,s,r,o,n,i,a,l){return je(e,t,s,r,o,n,i,a,l)}static calculateLrnaInGivenOut(e,t,s,r,o){return Ze(e,t,s,r,o)}static calculateOutGivenIn(e,t,s,r,o,n,i,a,l){return Ve(e,t,s,r,o,n,i,a,l)}static calculateOutGivenLrnaIn(e,t,s,r,o){return Qe(e,t,s,r,o)}static calculatePoolTradeFee(e,t,s){return et(e,t,s)}static calculateShares(e,t,s,r){return rt(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,o,n,i,a){return ot(e,t,s,r,o,n,i,a)}static calculateLiquidityLRNAOut(e,t,s,r,o,n,i,a){return it(e,t,s,r,o,n,i,a)}static calculateCapDifference(e,t,s,r){let o=B(t),n=B(e),i=B(r),l=B(s).shiftedBy(-18);if(o.div(i).lt(l)){let u=l.times(i).minus(o).times(n),P=o.times(B(1).minus(l));return u.div(P).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return nt(e,t,s,r)}static isSellAllowed(e){return at(e)}static isBuyAllowed(e){return lt(e)}static isAddLiquidityAllowed(e){return ct(e)}static isRemoveLiquidityAllowed(e){return ut(e)}static recalculateAssetFee(e,t,s,r,o,n,i,a,l,c,u){return mt(e,t,s,r,o,n,i,a,l,c,u)}static recalculateProtocolFee(e,t,s,r,o,n,i,a,l,c,u){return pt(e,t,s,r,o,n,i,a,l,c,u)}static verifyAssetCap(e,t,s,r){return gt(e,t,s,r)}};var ne=class extends D{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,o]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=s.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:u,tradable:P,cap:d,protocolShares:g}=l.unwrap(),b=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:P.bits.toNumber(),balance:b.toString(),cap:m(d.toString()),protocolShares:m(g.toString())}}),i=await Promise.all(n);return i.push({id:e,tradeable:r.bits.toNumber(),balance:o.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:i,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,o="omnipool",n="Short",i=A=>A===L?[L,se]:[se,A],[a,l,c,u]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(o,i(s),n),this.api.query.emaOracle.oracles(o,i(r),n)]),[P,d,g]=this.getAssetFee(e,a.toNumber(),l,c),[b,f,S]=r===se?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,u),y=P+b,T=g+S;return{assetFee:E(d),protocolFee:E(f),min:E(y),max:E(T)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,o)=>{let n=e.tokens[o];if(r.isNone)return n;let i=r.unwrap();return this.updateTokenState(n,i)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:o,cap:n,protocolShares:i}=t;return{...e,hubReserves:m(s.toString()),shares:m(r.toString()),cap:m(n.toString()),protocolShares:m(i.toString()),tradeable:o.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:o,balanceOut:n}=e,{minFee:i,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,u=E(i.toNumber()),P=E(a.toNumber());if(s.isNone||r.isNone)return[i.toNumber(),i.toNumber(),a.toNumber()];let[d]=r.unwrap(),{assetFee:g,timestamp:b}=s.unwrap(),f=t-b.toNumber(),S=d.volume.bIn.toString(),y=d.volume.bOut.toString(),T=d.liquidity.b.toString();o===L&&(S=d.volume.aIn.toString(),y=d.volume.aOut.toString(),T=d.liquidity.a.toString());let A=E(g.toNumber()),G=O.recalculateAssetFee(S,y,T,"9",n.toString(),I(A).toString(),f.toString(),I(u).toString(),I(P).toString(),l.toString(),c.toString());return[i.toNumber(),Number(G)*1e4,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:o,balanceIn:n}=e,{minFee:i,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,u=E(i.toNumber()),P=E(a.toNumber());if(s.isNone||r.isNone)return[i.toNumber(),i.toNumber(),a.toNumber()];let[d]=r.unwrap(),{protocolFee:g,timestamp:b}=s.unwrap(),f=t-b.toNumber(),S=d.volume.bIn.toString(),y=d.volume.bOut.toString(),T=d.liquidity.b.toString();o===L&&(S=d.volume.aIn.toString(),y=d.volume.aOut.toString(),T=d.liquidity.a.toString());let A=E(g.toNumber()),G=O.recalculateProtocolFee(S,y,T,"9",n.toString(),I(A).toString(),f.toString(),I(u).toString(),I(P).toString(),l.toString(),c.toString());return[i.toNumber(),Number(G)*1e4,a.toNumber()]}getPoolId(){return dt(Pt("modlomnipool".padEnd(32,"\0")),U)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var ae=class extends D{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let o=s.toString(),[n,i]=r.unwrap(),[a,l]=await Promise.all([this.getBalance(o,n.toString()),this.getBalance(o,i.toString())]);return{address:o,type:"Xyk",tokens:[{id:n.toString(),balance:a.toString()},{id:i.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{blake2AsHex as At,encodeAddress as vt}from"@polkadot/util-crypto";import{calculate_in_given_out as bt,calculate_out_given_in as ht,calculate_amplification as ft,calculate_add_one_asset as yt,calculate_liquidity_out_one_asset as St,calculate_pool_trade_fee as Bt,calculate_shares as Ot,calculate_shares_for_amount as xt,calculate_spot_price_with_fee as wt,pool_account_name as It,recalculate_peg as Tt}from"@galacticcouncil/math-stableswap";var F=class{static getPoolAddress(e){return It(e)}static defaultPegs(e){let t=[];for(let s=0;s<e;s++)t.push(["1","1"]);return t}static calculateAmplification(e,t,s,r,o){return ft(e,t,s,r,o)}static calculateInGivenOut(e,t,s,r,o,n,i){return bt(e,t,s,r,o,n,i)}static calculateAddOneAsset(e,t,s,r,o,n,i){return yt(e,t,s,r,o,n,i)}static calculateSharesForAmount(e,t,s,r,o,n,i){return xt(e,t,s,r,o,n,i)}static calculateOutGivenIn(e,t,s,r,o,n,i){return ht(e,t,s,r,o,n,i)}static calculateLiquidityOutOneAsset(e,t,s,r,o,n,i){return St(e,t,s,r,o,n,i)}static calculateShares(e,t,s,r,o,n){return Ot(e,t,s,r,o,n)}static calculateSpotPriceWithFee(e,t,s,r,o,n,i,a){return wt(e,t,s,r,o,n,i,a)}static calculatePoolTradeFee(e,t,s){return Bt(e,t,s)}static recalculatePegs(e,t,s,r,o){let n=Tt(e,t,s,r,o);return JSON.parse(n)}};var Nt=340282366920938463463374607431768211455n,le=class extends D{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[o]},n])=>{let i=n.unwrap(),a=o.toString(),l=this.getPoolAddress(a),[c,u,P]=await Promise.all([this.getPoolDelta(a,i,s.toString()),this.getPoolTokens(l,a,i),this.getPoolPegs(a,i,s.toString())]);return this.stablePools.set(l,i),{address:l,id:a,type:"Stableswap",fee:E(i.fee.toNumber()),tokens:u,...c,...P,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toString(),r=this.stablePools.get(e.address);if(r){let[o,n]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,o,n)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:o,initialBlock:n,finalBlock:i}=t,a=F.calculateAmplification(r.toString(),o.toString(),n.toString(),i.toString(),s),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,o=r.map(async i=>{let[a,l]=await Promise.all([this.api.query.stableswap.assetTradability(t,i.toString()),this.getBalance(e,i.toString())]);return{id:i.toString(),tradeable:a.bits.toNumber(),balance:l.toString()}}),n=await Promise.all(o);return n.push({id:t,tradeable:j,balance:Nt.toString()}),n}getPoolDefaultPegs(e){let t=e.fee,s=F.defaultPegs(e.assets.length);return{pegsFee:E(t.toNumber()),pegs:s}}async getPoolPegs(e,t,s){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let r=await this.api.query.stableswap.poolPegs(e);if(r.isNone)return this.getPoolDefaultPegs(t);let o=r.unwrap(),n=await this.getLatestPegs(t,o,s),i=this.getRecentPegs(o),a=o.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[c,u]=F.recalculatePegs(JSON.stringify(i),JSON.stringify(n),s,a.replace(/%/g,""),l.replace(/%/g,"")),P=Number(c)*1e4;return{pegsFee:E(P),pegs:u}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([s,r])=>r.map(o=>o.toString()))}async getLatestPegs(e,t,s){let{source:r}=t,o=Array.from(e.assets.entries()).map(([i,a])=>a.toString()),n=r.map(async(i,a)=>{if(i.isOracle){let[l,c,u]=i.asOracle,P=[u.toString(),o[a]].map(y=>Number(y)).sort((y,T)=>y-T),d=await this.api.query.emaOracle.oracles(l,P,c),[{price:g,updatedAt:b}]=d.unwrap(),f=g.n.toString(),S=g.d.toString();return u.toString()===P[0].toString()?[[f,S],b.toString()]:[[S,f],b.toString()]}else return[i.asValue.map(l=>l.toString()),s]});return Promise.all(n)}getPoolAddress(e){let t=Number(e),s=F.getPoolAddress(t);return vt(At(s),U)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function ye(p){return p.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var ce=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Ae=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Y=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},ve=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Ne=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Fe=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Re=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Z=class extends M{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=Ft(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new X(this.api),this.aaveClient=new oe(this.api),this.xykClient=new ae(this.api),this.omniClient=new ne(this.api),this.lbpClient=new ie(this.api),this.stableClient=new le(this.api),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}unsubscribe(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new ce(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,o){let n;this.isDirectOmnipoolTrade(o)?n=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):n=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),ye(o));let i=()=>n;return{hex:n.toHex(),name:"RouterBuy",get:i}}buildSellTx(e,t,s,r,o){let n;this.isDirectOmnipoolTrade(o)?n=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):n=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),ye(o));let i=()=>n;return{hex:n.toHex(),name:"RouterSell",get:i}}};import{LRUCache as Rt}from"@thi.ng/cache";var Se=class extends Z{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Rt(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let o=await super.getPoolFees(e,t);return this.feeCache.set(s,o),o}}async destroy(){this.log(`Destroying pool cache!
2
- Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var ue=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,o,n,i){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o,this.fee=n,this.repayFeeApply=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),o=s.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 n=m(r.balance),i=m(o.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:i,decimalsIn:r.decimals,decimalsOut:o.decimals,weightIn:r.weight,weightOut:o.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,o=[];t.isLessThan(this.minTradingLimit)&&o.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&o.push("MaxOutRatioExceeded"),r===e.assetOut){let i=this.calculateTradeFee(t,s),a=I(this.repayFeeApply?s.repayFee:s.exchangeFee),l=t.plus(i),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&o.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:o}}else{let i=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(a)&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:i,amountOut:t,feePct:0,errors:o}}}validateAndSell(e,t,s){let r=this.tokens[0].id,o=[];t.isLessThan(this.minTradingLimit)&&o.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&o.push("MaxInRatioExceeded"),r===e.assetIn){let i=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(a)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:i,feePct:0,errors:o}}else{let i=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(i,s),l=I(this.repayFeeApply?s.repayFee:s.exchangeFee),c=i.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:c,feePct:l,errors:o}}}calculateInGivenOut(e,t){let s=C.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?h:r}calculateOutGivenIn(e,t){let s=C.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?h:r}spotPriceInGivenOut(e){let t=C.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),w(v,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=C.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),w(v,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let s=C.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(s)}};var me=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,o,n){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o,this.hubAssetId=n}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),o=s.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 n=m(r.balance),i=m(o.balance),a=m(r.existentialDeposit),l=m(o.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:o.hubReserves,sharesIn:r.shares,sharesOut:o.shares,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:n,balanceOut:i,tradeableIn:r.tradeable,tradeableOut:o.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,s),n=o.minus(r),i=r===h?h:n.div(r).multipliedBy(100).decimalPlaces(2),a=[],l=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let P=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(P)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:i.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=this.calculateOutGivenIn(e,t,s),i=r.minus(o).div(r).multipliedBy(100).decimalPlaces(2),a=[],l=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let P=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(P)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:i.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=O.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():h.toString(),s?k(s.protocolFee).toString():h.toString()),o=m(r);return o.isNegative()?h:o}calculateLrnaInGivenOut(e,t,s){let r=O.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():h.toString()),o=m(r);return o.isNegative()?h:o}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=O.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():h.toString(),s?k(s.protocolFee).toString():h.toString()),o=m(r);return o.isNegative()?h:o}calculateOutGivenLrnaIn(e,t,s){let r=O.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():h.toString()),o=m(r);return o.isNegative()?h:o}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=O.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(K-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=O.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(K-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=O.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(K-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=O.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(K-e.decimalsIn)).decimalPlaces(0,1)}};var pe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,o,n,i,a,l,c,u){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o,this.amplification=n,this.id=i,this.fee=a,this.totalIssuance=l,this.pegs=c,this.pegsFee=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),o=s.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 n=m(r.balance),i=m(o.balance),a=m(r.existentialDeposit),l=m(o.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:i,decimalsIn:r.decimals,decimalsOut:o.decimals,tradeableIn:this.id===e?j:r.tradeable,tradeableOut:this.id===t?j:o.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,s),n=I(s.fee),i=[],a=O.isSellAllowed(e.tradeableIn),l=O.isBuyAllowed(e.tradeableOut);return(!a||!l)&&i.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&i.push("InsufficientTradingAmount"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:n,errors:i}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=this.calculateOutGivenIn(e,t,s),n=I(s.fee),i=[],a=O.isSellAllowed(e.tradeableIn),l=O.isBuyAllowed(e.tradeableOut);return(!a||!l)&&i.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&i.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:n,errors:i}}calculateIn(e,t,s){let r=F.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateAddOneAsset(e,t,s){let r=F.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateSharesForAmount(e,t,s){let r=F.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=F.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let r=w(v,e.decimalsIn-e.decimalsOut);return m(t).div(r)}let s=w(v,18-e.decimalsIn);return m(t).div(s)}calculateOut(e,t,s){let r=F.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateWithdrawOneAsset(e,t,s){let r=F.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateShares(e,t,s){let r=F.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=F.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let r=w(v,e.decimalsOut-e.decimalsIn);return m(t).div(r)}let s=w(v,18-e.decimalsOut);return m(t).div(s)}calculateTradeFee(e,t){let s=F.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return m(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{calculate_in_given_out as Et,calculate_out_given_in as kt,calculate_pool_trade_fee as _t,get_spot_price as Lt,calculate_liquidity_in as Dt,calculate_shares as Mt,calculate_spot_price as Ct,calculate_spot_price_with_fee as Gt,calculate_liquidity_out_asset_a as qt,calculate_liquidity_out_asset_b as Ht}from"@galacticcouncil/math-xyk";var H=class{static getSpotPrice(e,t,s){return Lt(e,t,s)}static calculateInGivenOut(e,t,s){return Et(e,t,s)}static calculateOutGivenIn(e,t,s){return kt(e,t,s)}static calculatePoolTradeFee(e,t,s){return _t(e,t,s)}static calculateLiquidityIn(e,t,s){return Dt(e,t,s)}static calculateSpotPrice(e,t){return Ct(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return Gt(e,t,s,r)}static calculateShares(e,t,s){return Mt(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return qt(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Ht(e,t,s,r)}};var ge=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,o){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),o=s.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 n=m(r.balance),i=m(o.balance),a=m(r.existentialDeposit),l=m(o.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:n,balanceOut:i,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateTradeFee(r,s),n=I(s.exchangeFee),i=r.plus(o),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(r,s),n=I(s.exchangeFee),i=r.minus(o),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:n,errors:a}}calculateInGivenOut(e,t){let s=H.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?h:r}calculateOutGivenIn(e,t){let s=H.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?h:r}spotPriceInGivenOut(e){let t=H.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=w(v,18-e.decimalsOut);return m(t).div(s)}spotPriceOutGivenIn(e){let t=H.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=w(v,18-e.decimalsIn);return m(t).div(s)}calculateTradeFee(e,t){let s=H.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(s)}};var de=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,o){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),o=s.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 n=m(r.balance),i=m(o.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:n,balanceOut:i,assetInED:h,assetOutED:h}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=[],n=e.balanceOut;t.isGreaterThan(n)&&o.push("TradeNotAllowed");let i=e.balanceIn;return r.isGreaterThan(i)&&o.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=[],n=e.balanceIn;t.isGreaterThan(n)&&o.push("TradeNotAllowed");let i=e.balanceOut;return r.isGreaterThan(i)&&o.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:o}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return w(v,e.decimalsOut)}spotPriceOutGivenIn(e){return w(v,e.decimalsIn)}calculateTradeFee(e,t){return h}};var V=class{static get(e){switch(e.type){case"Aave":return de.fromPool(e);case"Xyk":return ge.fromPool(e);case"Omnipool":return me.fromPool(e);case"Lbp":return ue.fromPool(e);case"Stableswap":return pe.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var $=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new J,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),n=this.getPaths(e,null,r,t).map(i=>i[i.length-1].assetOut);return this.toAssets([...new Set(n)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,meta:r.meta,location:r.location,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let o=this.getPoolMap(s);return{assets:r,poolsMap:o}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,V.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,o])=>{let n=t.get(s);return{poolAddress:s,poolId:n?.id,pool:n?.type,assetIn:r,assetOut:o}})}toAssets(e,t){return e.map(s=>t.get(s))}};function ea(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Q(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ee(p,e){return v.minus(e.div(p)).multipliedBy(100).decimalPlaces(2)}function ke(p,e){return e.div(p).minus(v).multipliedBy(100).decimalPlaces(2)}var Pe=class extends ${isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let o=s[s.length-1].amountOut,n=r[r.length-1].amountOut;return o.isGreaterThan(n)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(o=>o.tradeFeeRange?.[0]??o.tradeFeePct).reduce((o,n)=>o+n),r=e.map(o=>o.tradeFeeRange?.[1]??o.tradeFeePct).reduce((o,n)=>o+n);return[s,r]}}getPoolFeeRange(e){let t=e.min?I(e.min):void 0,s=e.max?I(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let o=await super.getPools();if(o.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,o),i=super.getPaths(e,t,n,o);if(i.length===0)throw new Y(e,t);let a;if(r)a=await this.toSellSwaps(s,r,n);else{let x=i.map(async ee=>await this.toSellSwaps(s,ee,n)),_=await Promise.all(x);a=this.findBestSellRoute(_)}let l=a[0],c=a[a.length-1],u=this.isDirectTrade(a),P=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,_)=>x.multipliedBy(_)),d=w(P,c.assetOutDecimals),g=u?c.calculatedOut:this.calculateDelta0Y(l.amountIn,a,n),b=c.amountOut,f=u?c.tradeFeePct:Ee(g,b).toNumber(),S=g.minus(b),y=this.getRouteFeeRange(a),T=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(d),A=Q(g,T),G=x=>this.poolService.buildSellTx(e,t,l.amountIn,x,a.map(_=>_));return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:S,tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A.toNumber(),swaps:a,toTx:G,toHuman(){return{type:"Sell",amountIn:N(l.amountIn,l.assetInDecimals),amountOut:N(c.amountOut,c.assetOutDecimals),spotPrice:N(d,c.assetOutDecimals),tradeFee:N(S,c.assetOutDecimals),tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A.toNumber(),swaps:a.map(x=>x.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let o=0;o<t.length;o++){let n=t[o],i=s.get(n.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(n.assetIn,n.assetOut),l;o>0?l=r[o-1]:l=e;let c=i.calculateOutGivenIn(a,l);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let o=0;o<t.length;o++){let n=t[o],i=s.get(n.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(n.assetIn,n.assetOut),l;o>0?l=r[o-1].amountOut:l=w(m(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,i),{amountOut:u,calculatedOut:P,feePct:d,errors:g}=i.validateAndSell(a,l,c),b=this.getPoolFeeRange(c),f=i.spotPriceOutGivenIn(a),S=l.shiftedBy(-1*a.decimalsIn).multipliedBy(f),y=Q(P,S);r.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,calculatedOut:P,amountOut:u,spotPrice:f,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y.toNumber(),errors:g,toHuman(){return{...n,amountIn:N(l,a.decimalsIn),calculatedOut:N(P,a.decimalsOut),amountOut:N(u,a.decimalsOut),spotPrice:N(f,a.decimalsOut),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y.toNumber(),errors:g}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),o=super.getPaths(e,t,r,s);if(o.length===0)throw new Y(e,t);let n=s.map(g=>g.tokens.find(b=>b.id===e)).filter(g=>!!g).sort((g,b)=>Number(b.balance)-Number(g.balance)),{balance:i,decimals:a}=n[0],c=m(i).shiftedBy(-1*a).div(100).multipliedBy(.1),u=o.map(async g=>await this.toSellSwaps(c,g,r)),P=await Promise.all(u);return this.findBestSellRoute(P).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut}))}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s);if(super.getPaths(e,t,r,s).length===0)return Promise.resolve(void 0);let n=await this.getMostLiquidRoute(e,t),i=await this.toSellSwaps("1",n,r),a=i.map(u=>u.spotPrice.shiftedBy(-1*u.assetOutDecimals)).reduce((u,P)=>u.multipliedBy(P)),l=i[i.length-1].assetOutDecimals;return{amount:w(a,l),decimals:l}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let o=s[0].amountIn,n=r[0].amountIn;return o.isGreaterThan(n)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let o=await super.getPools();if(o.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,o),i=super.getPaths(e,t,n,o);if(i.length===0)throw new Y(e,t);let a;if(r)a=await this.toBuySwaps(s,r,n);else{let x=i.map(async ee=>await this.toBuySwaps(s,ee,n)),_=await Promise.all(x);a=this.findBestBuyRoute(_)}let l=a[a.length-1],c=a[0],u=this.isDirectTrade(a),P=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetInDecimals)).reduce((x,_)=>x.multipliedBy(_)),d=w(P,c.assetInDecimals),g=u?c.calculatedIn:this.calculateDelta0X(l.amountOut,a,n),b=c.amountIn,f=u?c.tradeFeePct:ke(g,b).toNumber(),S=b.minus(g),y=this.getRouteFeeRange(a),T=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(d),A;g.isZero()?A=-100:A=Q(T,g).toNumber();let G=x=>this.poolService.buildBuyTx(e,t,l.amountOut,x,a.map(_=>_));return{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:S,tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A,swaps:a,toTx:G,toHuman(){return{type:"Buy",amountOut:N(l.amountOut,l.assetOutDecimals),amountIn:N(c.amountIn,c.assetInDecimals),spotPrice:N(d,c.assetInDecimals),tradeFee:N(S,c.assetInDecimals),tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A,swaps:a.map(x=>x.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let o=t.length-1;o>=0;o--){let n=t[o],i=s.get(n.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(n.assetIn,n.assetOut),l;o==t.length-1?l=e:l=r[0];let c=i.calculateInGivenOut(a,l);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let o=t.length-1;o>=0;o--){let n=t[o],i=s.get(n.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(n.assetIn,n.assetOut),l;o==t.length-1?l=w(m(e),a.decimalsOut).decimalPlaces(0,1):l=r[0].amountIn;let c=await this.poolService.getPoolFees(a,i),{amountIn:u,calculatedIn:P,feePct:d,errors:g}=i.validateAndBuy(a,l,c),b=this.getPoolFeeRange(c),f=i.spotPriceInGivenOut(a),S=l.shiftedBy(-1*a.decimalsOut).multipliedBy(f),y;P.isZero()?y=-100:y=Q(S,P).toNumber(),r.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:l,calculatedIn:P,amountIn:u,spotPrice:f,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y,errors:g,toHuman(){return{...n,amountOut:N(l,a.decimalsOut),calculatedIn:N(P,a.decimalsIn),amountIn:N(u,a.decimalsIn),spotPrice:N(f,a.decimalsIn),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y,errors:g}}})}return r}};import{memoize1 as Ba}from"@thi.ng/memoize";export{Nt as AMOUNT_MAX,de as AavePool,oe as AavePoolClient,X as AssetClient,ve as AssetNotFound,cs as BASILISK_PARACHAIN_ID,q as BalanceClient,B as BigNumber,Se as CachingPoolService,Me as DECIMAL_PLACES,he as DENOMINATOR,fe as FarmClient,se as HUB_ASSET_ID,us as HYDRADX_OMNIPOOL_ADDRESS,ls as HYDRADX_PARACHAIN_ID,U as HYDRADX_SS58_PREFIX,ws as INFINITY,C as LbpMath,ue as LbpPool,ie as LbpPoolClient,v as ONE,O as OmniMath,me as OmniPool,ne as OmniPoolClient,M as PolkadotApiClient,Ae as PoolConfigNotFound,W as PoolError,V as PoolFactory,ce as PoolNotFound,Z as PoolService,R as PoolType,Re as ProviderConfigNotFound,K as RUNTIME_DECIMALS,Y as RouteNotFound,$ as Router,as as SYSTEM_ASSET_DECIMALS,L as SYSTEM_ASSET_ID,F as StableMath,pe as StableSwap,le as StableSwapClient,Ne as StorageConfigNotFound,Fe as SubscriptionNotSupported,j as TRADEABLE_DEFAULT,Pe as TradeRouter,Oe as TradeType,H as XykMath,ge as XykPool,ae as XykPoolClient,h as ZERO,Ps as bnFormatter,m as bnum,ye as buildRoute,ke as calculateBuyFee,ea as calculateDiffToAvg,Q as calculateDiffToRef,Ee as calculateSellFee,xe as findNestedKey,ds as findNestedObj,w as scale};
2
+ Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var ue=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,o,n,i){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o,this.fee=n,this.repayFeeApply=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),o=s.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 n=m(r.balance),i=m(o.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:i,decimalsIn:r.decimals,decimalsOut:o.decimals,weightIn:r.weight,weightOut:o.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,o=[];t.isLessThan(this.minTradingLimit)&&o.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&o.push("MaxOutRatioExceeded"),r===e.assetOut){let i=this.calculateTradeFee(t,s),a=I(this.repayFeeApply?s.repayFee:s.exchangeFee),l=t.plus(i),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&o.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:o}}else{let i=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(a)&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:i,amountOut:t,feePct:0,errors:o}}}validateAndSell(e,t,s){let r=this.tokens[0].id,o=[];t.isLessThan(this.minTradingLimit)&&o.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&o.push("MaxInRatioExceeded"),r===e.assetIn){let i=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(a)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:i,feePct:0,errors:o}}else{let i=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(i,s),l=I(this.repayFeeApply?s.repayFee:s.exchangeFee),c=i.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:c,feePct:l,errors:o}}}calculateInGivenOut(e,t){let s=C.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?h:r}calculateOutGivenIn(e,t){let s=C.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?h:r}spotPriceInGivenOut(e){let t=C.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),w(v,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=C.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),w(v,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let s=C.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(s)}};var me=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,o,n){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o,this.hubAssetId=n}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),o=s.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 n=m(r.balance),i=m(o.balance),a=m(r.existentialDeposit),l=m(o.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:o.hubReserves,sharesIn:r.shares,sharesOut:o.shares,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:n,balanceOut:i,tradeableIn:r.tradeable,tradeableOut:o.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,s),n=o.minus(r),i=r===h?h:n.div(r).multipliedBy(100).decimalPlaces(2),a=[],l=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let P=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(P)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:i.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=this.calculateOutGivenIn(e,t,s),i=r.minus(o).div(r).multipliedBy(100).decimalPlaces(2),a=[],l=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let P=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(P)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:i.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=O.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():h.toString(),s?k(s.protocolFee).toString():h.toString()),o=m(r);return o.isNegative()?h:o}calculateLrnaInGivenOut(e,t,s){let r=O.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():h.toString()),o=m(r);return o.isNegative()?h:o}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=O.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():h.toString(),s?k(s.protocolFee).toString():h.toString()),o=m(r);return o.isNegative()?h:o}calculateOutGivenLrnaIn(e,t,s){let r=O.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():h.toString()),o=m(r);return o.isNegative()?h:o}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=O.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(K-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=O.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(K-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=O.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(K-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=O.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(K-e.decimalsIn)).decimalPlaces(0,1)}};var pe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,o,n,i,a,l,c,u){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o,this.amplification=n,this.id=i,this.fee=a,this.totalIssuance=l,this.pegs=c,this.pegsFee=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),o=s.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 n=m(r.balance),i=m(o.balance),a=m(r.existentialDeposit),l=m(o.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:i,decimalsIn:r.decimals,decimalsOut:o.decimals,tradeableIn:this.id===e?j:r.tradeable,tradeableOut:this.id===t?j:o.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,s),n=I(s.fee),i=[],a=O.isSellAllowed(e.tradeableIn),l=O.isBuyAllowed(e.tradeableOut);return(!a||!l)&&i.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&i.push("InsufficientTradingAmount"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:n,errors:i}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=this.calculateOutGivenIn(e,t,s),n=I(s.fee),i=[],a=O.isSellAllowed(e.tradeableIn),l=O.isBuyAllowed(e.tradeableOut);return(!a||!l)&&i.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&i.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:n,errors:i}}calculateIn(e,t,s){let r=F.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateAddOneAsset(e,t,s){let r=F.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateSharesForAmount(e,t,s){let r=F.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=F.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let r=w(v,e.decimalsIn-e.decimalsOut);return m(t).div(r)}let s=w(v,18-e.decimalsIn);return m(t).div(s)}calculateOut(e,t,s){let r=F.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateWithdrawOneAsset(e,t,s){let r=F.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateShares(e,t,s){let r=F.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=F.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let r=w(v,e.decimalsOut-e.decimalsIn);return m(t).div(r)}let s=w(v,18-e.decimalsOut);return m(t).div(s)}calculateTradeFee(e,t){let s=F.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return m(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{calculate_in_given_out as Et,calculate_out_given_in as kt,calculate_pool_trade_fee as _t,get_spot_price as Lt,calculate_liquidity_in as Dt,calculate_shares as Mt,calculate_spot_price as Ct,calculate_spot_price_with_fee as Gt,calculate_liquidity_out_asset_a as qt,calculate_liquidity_out_asset_b as Ht}from"@galacticcouncil/math-xyk";var H=class{static getSpotPrice(e,t,s){return Lt(e,t,s)}static calculateInGivenOut(e,t,s){return Et(e,t,s)}static calculateOutGivenIn(e,t,s){return kt(e,t,s)}static calculatePoolTradeFee(e,t,s){return _t(e,t,s)}static calculateLiquidityIn(e,t,s){return Dt(e,t,s)}static calculateSpotPrice(e,t){return Ct(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return Gt(e,t,s,r)}static calculateShares(e,t,s){return Mt(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return qt(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Ht(e,t,s,r)}};var ge=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,o){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),o=s.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 n=m(r.balance),i=m(o.balance),a=m(r.existentialDeposit),l=m(o.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:n,balanceOut:i,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateTradeFee(r,s),n=I(s.exchangeFee),i=r.plus(o),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(r,s),n=I(s.exchangeFee),i=r.minus(o),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:n,errors:a}}calculateInGivenOut(e,t){let s=H.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?h:r}calculateOutGivenIn(e,t){let s=H.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?h:r}spotPriceInGivenOut(e){let t=H.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=w(v,18-e.decimalsOut);return m(t).div(s)}spotPriceOutGivenIn(e){let t=H.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=w(v,18-e.decimalsIn);return m(t).div(s)}calculateTradeFee(e,t){let s=H.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(s)}};var de=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,o){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),o=s.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 n=m(r.balance),i=m(o.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:n,balanceOut:i,assetInED:h,assetOutED:h}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=[],n=e.balanceOut;t.isGreaterThan(n)&&o.push("TradeNotAllowed");let i=e.balanceIn;return r.isGreaterThan(i)&&o.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=[],n=e.balanceIn;t.isGreaterThan(n)&&o.push("TradeNotAllowed");let i=e.balanceOut;return r.isGreaterThan(i)&&o.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:o}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return w(v,e.decimalsOut)}spotPriceOutGivenIn(e){return w(v,e.decimalsIn)}calculateTradeFee(e,t){return h}};var V=class{static get(e){switch(e.type){case"Aave":return de.fromPool(e);case"Xyk":return ge.fromPool(e);case"Omnipool":return me.fromPool(e);case"Lbp":return ue.fromPool(e);case"Stableswap":return pe.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var $=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new J,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),n=this.getPaths(e,null,r,t).map(i=>i[i.length-1].assetOut);return this.toAssets([...new Set(n)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,meta:r.meta,location:r.location,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let o=this.getPoolMap(s);return{assets:r,poolsMap:o}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,V.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,o])=>{let n=t.get(s);return{poolAddress:s,poolId:n?.id,pool:n?.type,assetIn:r,assetOut:o}})}toAssets(e,t){return e.map(s=>t.get(s))}};function ea(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Q(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ee(p,e){return v.minus(e.div(p)).multipliedBy(100).decimalPlaces(2)}function ke(p,e){return e.div(p).minus(v).multipliedBy(100).decimalPlaces(2)}var Pe=class extends ${isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let o=s[s.length-1].amountOut,n=r[r.length-1].amountOut;return o.isGreaterThan(n)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(o=>o.tradeFeeRange?.[0]??o.tradeFeePct).reduce((o,n)=>o+n),r=e.map(o=>o.tradeFeeRange?.[1]??o.tradeFeePct).reduce((o,n)=>o+n);return[s,r]}}getPoolFeeRange(e){let t=e.min?I(e.min):void 0,s=e.max?I(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let o=await super.getPools();if(o.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,o),i=super.getPaths(e,t,n,o);if(i.length===0)throw new Y(e,t);let a;if(r)a=await this.toSellSwaps(s,r,n);else{let x=i.map(async ee=>await this.toSellSwaps(s,ee,n)),_=await Promise.all(x);a=this.findBestSellRoute(_)}let l=a[0],c=a[a.length-1],u=this.isDirectTrade(a),P=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,_)=>x.multipliedBy(_)),d=w(P,c.assetOutDecimals),g=u?c.calculatedOut:this.calculateDelta0Y(l.amountIn,a,n),b=c.amountOut,f=u?c.tradeFeePct:Ee(g,b).toNumber(),S=g.minus(b),y=this.getRouteFeeRange(a),T=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(d),A=Q(g,T),G=x=>this.poolService.buildSellTx(e,t,l.amountIn,x,a.map(_=>_));return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:S,tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A.toNumber(),swaps:a,toTx:G,toHuman(){return{type:"Sell",amountIn:N(l.amountIn,l.assetInDecimals),amountOut:N(c.amountOut,c.assetOutDecimals),spotPrice:N(d,c.assetOutDecimals),tradeFee:N(S,c.assetOutDecimals),tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A.toNumber(),swaps:a.map(x=>x.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let o=0;o<t.length;o++){let n=t[o],i=s.get(n.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(n.assetIn,n.assetOut),l;o>0?l=r[o-1]:l=e;let c=i.calculateOutGivenIn(a,l);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let o=0;o<t.length;o++){let n=t[o],i=s.get(n.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(n.assetIn,n.assetOut),l;o>0?l=r[o-1].amountOut:l=w(m(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,i),{amountOut:u,calculatedOut:P,feePct:d,errors:g}=i.validateAndSell(a,l,c),b=this.getPoolFeeRange(c),f=i.spotPriceOutGivenIn(a),S=l.shiftedBy(-1*a.decimalsIn).multipliedBy(f),y=Q(P,S);r.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,calculatedOut:P,amountOut:u,spotPrice:f,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y.toNumber(),errors:g,toHuman(){return{...n,amountIn:N(l,a.decimalsIn),calculatedOut:N(P,a.decimalsOut),amountOut:N(u,a.decimalsOut),spotPrice:N(f,a.decimalsOut),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y.toNumber(),errors:g}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),o=super.getPaths(e,t,r,s);if(o.length===0)throw new Y(e,t);let n=s.map(g=>g.tokens.find(b=>b.id===e&&b.id!==g.id)).filter(g=>!!g).sort((g,b)=>Number(b.balance)-Number(g.balance)),{balance:i,decimals:a}=n[0],c=m(i).shiftedBy(-1*a).div(100).multipliedBy(.1),u=o.map(async g=>await this.toSellSwaps(c,g,r)),P=await Promise.all(u);return this.findBestSellRoute(P).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut}))}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s);if(super.getPaths(e,t,r,s).length===0)return Promise.resolve(void 0);let n=await this.getMostLiquidRoute(e,t),i=await this.toSellSwaps("1",n,r),a=i.map(u=>u.spotPrice.shiftedBy(-1*u.assetOutDecimals)).reduce((u,P)=>u.multipliedBy(P)),l=i[i.length-1].assetOutDecimals;return{amount:w(a,l),decimals:l}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let o=s[0].amountIn,n=r[0].amountIn;return o.isGreaterThan(n)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let o=await super.getPools();if(o.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,o),i=super.getPaths(e,t,n,o);if(i.length===0)throw new Y(e,t);let a;if(r)a=await this.toBuySwaps(s,r,n);else{let x=i.map(async ee=>await this.toBuySwaps(s,ee,n)),_=await Promise.all(x);a=this.findBestBuyRoute(_)}let l=a[a.length-1],c=a[0],u=this.isDirectTrade(a),P=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetInDecimals)).reduce((x,_)=>x.multipliedBy(_)),d=w(P,c.assetInDecimals),g=u?c.calculatedIn:this.calculateDelta0X(l.amountOut,a,n),b=c.amountIn,f=u?c.tradeFeePct:ke(g,b).toNumber(),S=b.minus(g),y=this.getRouteFeeRange(a),T=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(d),A;g.isZero()?A=-100:A=Q(T,g).toNumber();let G=x=>this.poolService.buildBuyTx(e,t,l.amountOut,x,a.map(_=>_));return{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:S,tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A,swaps:a,toTx:G,toHuman(){return{type:"Buy",amountOut:N(l.amountOut,l.assetOutDecimals),amountIn:N(c.amountIn,c.assetInDecimals),spotPrice:N(d,c.assetInDecimals),tradeFee:N(S,c.assetInDecimals),tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A,swaps:a.map(x=>x.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let o=t.length-1;o>=0;o--){let n=t[o],i=s.get(n.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(n.assetIn,n.assetOut),l;o==t.length-1?l=e:l=r[0];let c=i.calculateInGivenOut(a,l);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let o=t.length-1;o>=0;o--){let n=t[o],i=s.get(n.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(n.assetIn,n.assetOut),l;o==t.length-1?l=w(m(e),a.decimalsOut).decimalPlaces(0,1):l=r[0].amountIn;let c=await this.poolService.getPoolFees(a,i),{amountIn:u,calculatedIn:P,feePct:d,errors:g}=i.validateAndBuy(a,l,c),b=this.getPoolFeeRange(c),f=i.spotPriceInGivenOut(a),S=l.shiftedBy(-1*a.decimalsOut).multipliedBy(f),y;P.isZero()?y=-100:y=Q(S,P).toNumber(),r.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:l,calculatedIn:P,amountIn:u,spotPrice:f,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y,errors:g,toHuman(){return{...n,amountOut:N(l,a.decimalsOut),calculatedIn:N(P,a.decimalsIn),amountIn:N(u,a.decimalsIn),spotPrice:N(f,a.decimalsIn),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y,errors:g}}})}return r}};import{memoize1 as Ba}from"@thi.ng/memoize";export{Nt as AMOUNT_MAX,de as AavePool,oe as AavePoolClient,X as AssetClient,ve as AssetNotFound,cs as BASILISK_PARACHAIN_ID,q as BalanceClient,B as BigNumber,Se as CachingPoolService,Me as DECIMAL_PLACES,he as DENOMINATOR,fe as FarmClient,se as HUB_ASSET_ID,us as HYDRADX_OMNIPOOL_ADDRESS,ls as HYDRADX_PARACHAIN_ID,U as HYDRADX_SS58_PREFIX,ws as INFINITY,C as LbpMath,ue as LbpPool,ie as LbpPoolClient,v as ONE,O as OmniMath,me as OmniPool,ne as OmniPoolClient,M as PolkadotApiClient,Ae as PoolConfigNotFound,W as PoolError,V as PoolFactory,ce as PoolNotFound,Z as PoolService,R as PoolType,Re as ProviderConfigNotFound,K as RUNTIME_DECIMALS,Y as RouteNotFound,$ as Router,as as SYSTEM_ASSET_DECIMALS,L as SYSTEM_ASSET_ID,F as StableMath,pe as StableSwap,le as StableSwapClient,Ne as StorageConfigNotFound,Fe as SubscriptionNotSupported,j as TRADEABLE_DEFAULT,Pe as TradeRouter,Oe as TradeType,H as XykMath,ge as XykPool,ae as XykPoolClient,h as ZERO,Ps as bnFormatter,m as bnum,ye as buildRoute,ke as calculateBuyFee,ea as calculateDiffToAvg,Q as calculateDiffToRef,Ee as calculateSellFee,xe as findNestedKey,ds as findNestedObj,w as scale};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk",
3
- "version": "6.1.1",
3
+ "version": "6.1.2",
4
4
  "description": "Galactic off-chain routing & optimization of orders across pools for best price execution",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {