@galacticcouncil/sdk 6.1.3 → 6.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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:()=>At,BalanceClient:()=>W,BigNumber:()=>v.BigNumber,CachingPoolService:()=>Me,DECIMAL_PLACES:()=>ct,DENOMINATOR:()=>Be,FarmClient:()=>Re,HUB_ASSET_ID:()=>oe,HYDRADX_OMNIPOOL_ADDRESS:()=>Tt,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,At=2090,Be=1e3,Tt=(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,Ae=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 Te=class extends Ae{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 Te(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 T(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(),T(F).toString(),y.toString(),T(m).toString(),T(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(),T(F).toString(),y.toString(),T(m).toString(),T(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=T(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=T(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=T(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=T(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 A=require("@galacticcouncil/math-xyk"),Y=class{static getSpotPrice(e,t,s){return(0,A.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,A.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,A.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,A.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,A.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,A.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,A.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,A.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,A.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,A.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=T(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=T(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=[];return t.isGreaterThan(e.balanceIn)&&i.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=[];return t.isGreaterThan(e.balanceOut)&&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?T(e.min):void 0,s=e.max?T(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});
|
|
1
|
+
"use strict";var Me=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var xt=Object.prototype.hasOwnProperty;var vt=(l,e)=>{for(var t in e)Me(l,t,{get:e[t],enumerable:!0})},Bt=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of St(e))!xt.call(l,r)&&r!==t&&Me(l,r,{get:()=>e[r],enumerable:!(s=yt(e,r))||s.enumerable});return l};var wt=l=>Bt(Me({},"__esModule",{value:!0}),l);var Ht={};vt(Ht,{AMOUNT_MAX:()=>ft,AavePool:()=>Se,AavePoolClient:()=>ue,AssetClient:()=>j,AssetNotFound:()=>$e,BASILISK_PARACHAIN_ID:()=>Tt,BalanceClient:()=>Y,BigNumber:()=>v.BigNumber,CachingPoolService:()=>De,DECIMAL_PLACES:()=>ct,DENOMINATOR:()=>we,FarmClient:()=>ke,HUB_ASSET_ID:()=>ae,HYDRADX_OMNIPOOL_ADDRESS:()=>Nt,HYDRADX_PARACHAIN_ID:()=>At,HYDRADX_SS58_PREFIX:()=>$,INFINITY:()=>Ct,LbpMath:()=>H,LbpPool:()=>Pe,LbpPoolClient:()=>ce,ONE:()=>_,OmniMath:()=>B,OmniPool:()=>fe,OmniPoolClient:()=>me,PolkadotApiClient:()=>G,PoolConfigNotFound:()=>Xe,PoolError:()=>J,PoolFactory:()=>re,PoolNotFound:()=>he,PoolService:()=>se,PoolType:()=>E,ProviderConfigNotFound:()=>Ke,RUNTIME_DECIMALS:()=>V,RouteNotFound:()=>K,Router:()=>Z,SYSTEM_ASSET_DECIMALS:()=>It,SYSTEM_ASSET_ID:()=>C,StableMath:()=>R,StableSwap:()=>be,StableSwapClient:()=>ge,StorageConfigNotFound:()=>Je,SubscriptionNotSupported:()=>je,TRADEABLE_DEFAULT:()=>Q,TradeRouter:()=>xe,TradeType:()=>Ge,XykMath:()=>X,XykPool:()=>ye,XykPoolClient:()=>pe,ZERO:()=>P,bnFormatter:()=>_t,bnum:()=>p,buildRoute:()=>de,calculateBuyFee:()=>Ve,calculateDiffToAvg:()=>qt,calculateDiffToRef:()=>ie,calculateSellFee:()=>Ze,findNestedKey:()=>qe,findNestedObj:()=>Ft,scale:()=>O});module.exports=wt(Ht);var ve=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 Ot=5,ne=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 ve,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let o=i.dequeue();if(o==null||o.length>Ot)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 oe=class{getProposals(e,t,s){let r=Ce(s),i=Object.keys(r),n=i.map(c=>r[c]).flat(),o=new ne,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 Be=(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"),V=18,Q=15,C="0",It=12,ae="1",At=2034,$=63,Tt=2090,we=1e3,Nt=(0,et.encodeAddress)((0,tt.stringToU8a)("modlomnipool".padEnd(32,"\0")),$);var E=(i=>(i.Aave="Aave",i.LBP="Lbp",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="Xyk",i))(E||{}),J=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(J||{}),Ge=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Ge||{});var Oe=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 Ft(l,e,t){let s;return JSON.stringify(l,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}var _t=(l,e)=>typeof e=="bigint"?e.toString():e;var le=(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 Ie=(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 Rt=Ie(()=>"illegal argument(s)"),st=l=>{throw new Rt(l)};var Et=Ie(()=>"index out of bounds"),He=l=>{throw new Et(l)},Ae=(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 Ne=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 Ne(Math.random);var nt=l=>l!=null&&typeof l!="function"&&l.length!==void 0;var ot=Object.getPrototypeOf({}),Fe="function",at="string",ee=(l,e)=>{let t;if(l===e)return!0;if(l!=null){if(typeof l.equiv===Fe)return l.equiv(e)}else return l==e;if(e!=null){if(typeof e.equiv===Fe)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!==Fe&&l.length!==void 0&&typeof e!==Fe&&e.length!==void 0?kt(l,e):l instanceof Set&&e instanceof Set?Lt(l,e):l instanceof Map&&e instanceof Map?Dt(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)},kt=(l,e,t=ee)=>{let s=l.length;if(s===e.length)for(;s-- >0&&t(l[s],e[s]););return s<0},Lt=(l,e,t=ee)=>l.size===e.size&&t([...l.keys()].sort(),[...e.keys()].sort()),Dt=(l,e,t=ee)=>l.size===e.size&&t([...l].sort(),[...e].sort()),Mt=(l,e,t=ee)=>{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 _e=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=le){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(!ee(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||le;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 Re=class l extends _e{_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):(Ae(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):(Ae(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=le){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),Ae(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 te=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 Re,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 te{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 zs=require("@galacticcouncil/api-augment/hydradx"),Us=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(),g=new Intl.DateTimeFormat("en-GB"),d=[c,"Bond",g.format(h)].join(" ");return{id:e,name:d,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(f=>f.toString()).map(f=>{let{symbol:y}=this.getToken(f,t,s);return[f,y]}),g=Object.fromEntries(h),d=Object.values(g);return{id:e,name:d.join(", "),symbol:o?.isSome?o.toHuman():n.toHuman(),decimals:18,icon:d.join("/"),type:a.toString(),isSufficient:u.toHuman(),existentialDeposit:c.toString(),meta:g}}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 g=h.unwrap(),d=r.get(m.toString()),{assetType:f}=g;switch(f.toString()){case"Bond":let y=n.get(m.toString());return this.getBond(m.toString(),g,u,y);case"StableSwap":let x=i.get(m.toString());return this.getShares(m.toString(),g,u,x);case"External":return this.getExternal(m.toString(),g,t,d);default:return this.getToken(m.toString(),g,u,d)}});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 P=p(0),_=p(1),Ct=p("Infinity");function O(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 Y=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"),ke=class extends G{balanceClient;constructor(e){super(e),this.balanceClient=new Y(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(),g=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),d=u.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(g,d);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:f.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(),g=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),d=u.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(g,d);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:f.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(),g=new v.BigNumber(a.yieldPerPeriod.toString()),d=new v.BigNumber(a.maxRewardPerPeriod.toString()),f=a.blocksPerPeriod.toString(),y=new v.BigNumber(o.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new v.BigNumber(s).times(f)),S;if(m.isZero())S=g.times(y).times(x);else{let M=this.getGlobalRewardPerPeriod(m,g,d,u);S=this.getPoolYieldPerPeriod(M,y,m,u).times(x)}let N=new v.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),F=d.times(h),U=c?N.plus(c):F;return N.div(U).gte(.999)?P:S.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),P).toString():void 0}};var q=class extends Y{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=Be(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 Gt=["Supply","Withdraw","Repay","Borrow"],ue=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")),$)}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});Gt.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:Oe.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 ce=class extends q{MAX_FINAL_WEIGHT=O(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,g]=n,d=h.toString(),f=p(m),y=g.toString(),x=this.MAX_FINAL_WEIGHT.minus(p(f)),[S,N,F]=await Promise.all([this.isRepayFeeApplied(d,u.toString(),c.toString()),this.getBalance(e,d),this.getBalance(e,y)]);return{repayFeeApply:S,tokens:[{id:d,weight:f,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 k(l,e){return l.shiftedBy(-1*e).toString()}function T(l){return l[0]/l[1]*100}function D(l){return l[0]/l[1]}function L(l){return[l/we,we]}var b=require("@galacticcouncil/math-omnipool");var B=class{static calculateSpotPrice(e,t,s,r){return(0,b.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,b.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,n,o,a,u){return(0,b.calculate_in_given_out)(e,t,s,r,i,n,o,a,u)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,b.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,n,o,a,u){return(0,b.calculate_out_given_in)(e,t,s,r,i,n,o,a,u)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,b.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,b.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,b.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,n,o,a){return(0,b.calculate_liquidity_out)(e,t,s,r,i,n,o,a)}static calculateLiquidityLRNAOut(e,t,s,r,i,n,o,a){return(0,b.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,b.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,b.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,b.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,b.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,b.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,s,r,i,n,o,a,u,c,m){return(0,b.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,b.recalculate_protocol_fee)(e,t,s,r,i,n,o,a,u,c,m)}static verifyAssetCap(e,t,s,r){return(0,b.verify_asset_cap)(e,t,s,r)}};var me=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:g,protocolShares:d}=u.unwrap(),f=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:h.bits.toNumber(),balance:f.toString(),cap:p(g.toString()),protocolShares:p(d.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,ae]:[ae,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,g,d]=this.getAssetFee(e,a.toNumber(),u,c),[f,y,x]=r===ae?[0,0,0]:this.getProtocolFee(e,a.toNumber(),u,m),S=h+f,N=d+x;return{assetFee:L(g),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[g]=r.unwrap(),{assetFee:d,timestamp:f}=s.unwrap(),y=t-f.toNumber(),x=g.volume.bIn.toString(),S=g.volume.bOut.toString(),N=g.liquidity.b.toString();i===C&&(x=g.volume.aIn.toString(),S=g.volume.aOut.toString(),N=g.liquidity.a.toString());let F=L(d.toNumber()),U=B.recalculateAssetFee(x,S,N,"9",n.toString(),T(F).toString(),y.toString(),T(m).toString(),T(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[g]=r.unwrap(),{protocolFee:d,timestamp:f}=s.unwrap(),y=t-f.toNumber(),x=g.volume.bIn.toString(),S=g.volume.bOut.toString(),N=g.liquidity.b.toString();i===C&&(x=g.volume.aIn.toString(),S=g.volume.aOut.toString(),N=g.liquidity.a.toString());let F=L(d.toNumber()),U=B.recalculateProtocolFee(x,S,N,"9",n.toString(),T(F).toString(),y.toString(),T(m).toString(),T(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")),$)}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 pe=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 Le=require("@polkadot/util-crypto");var I=require("@galacticcouncil/math-stableswap"),R=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 ft=340282366920938463463374607431768211455n,ge=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=R.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:Q,balance:ft.toString()}),n}getPoolDefaultPegs(e){let t=e.fee,s=R.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]=R.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),g=await this.api.query.emaOracle.oracles(u,h,c),[{price:d,updatedAt:f}]=g.unwrap(),y=d.n.toString(),x=d.d.toString();return m.toString()===h[0].toString()?[[y,x],f.toString()]:[[x,y],f.toString()]}else return[o.asValue.map(u=>u.toString()),s]});return Promise.all(n)}getPoolAddress(e){let t=Number(e),s=R.getPoolAddress(t);return(0,Le.encodeAddress)((0,Le.blake2AsHex)(s),$)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function de(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 he=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"}},K=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 se=class extends G{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=Be(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 ue(this.api),this.xykClient=new pe(this.api),this.omniClient=new me(this.api),this.lbpClient=new ce(this.api),this.stableClient=new ge(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 he(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}async dryRun(e,t){let s;try{s=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(r){throw console.error(r),new Error("Dry run execution failed!")}if(s.isOk)return s.asOk;throw console.log(s.asErr.toHuman()),new Error("Dry run execution error!")}buildBuyTx(e,t,s,r,i){let n;return 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(),de(i)),{hex:n.toHex(),name:"RouterBuy",get:()=>n,dryRun:o=>this.dryRun(o,n)}}buildSellTx(e,t,s,r,i){let n;return 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(),de(i)),{hex:n.toHex(),name:"RouterSell",get:()=>n,dryRun:o=>this.dryRun(o,n)}}buildSellAllTx(e,t,s,r){let i=this.api.tx.router.sellAll(e,t,s.toFixed(),de(r));return{hex:i.toHex(),name:"RouterSellAll",get:()=>i,dryRun:n=>this.dryRun(n,i)}}};var De=class extends se{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new te(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e.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 Pe=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=T(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=T(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()?P: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()?P:r}spotPriceInGivenOut(e){let t=H.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),O(_,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=H.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),O(_,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 fe=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===P?P: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?D(s.assetFee).toString():P.toString(),s?D(s.protocolFee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}calculateLrnaInGivenOut(e,t,s){let r=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?D(s.assetFee).toString():P.toString()),i=p(r);return i.isNegative()?P: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?D(s.assetFee).toString():P.toString(),s?D(s.protocolFee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}calculateOutGivenLrnaIn(e,t,s){let r=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?D(s.assetFee).toString():P.toString()),i=p(r);return i.isNegative()?P: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*(V-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=B.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(V-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*(V-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(V-e.decimalsIn)).decimalPlaces(0,1)}};var be=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?Q:r.tradeable,tradeableOut:this.id===t?Q:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=T(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=T(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=R.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?D(s.fee).toString():P.toString(),this.getPegs()),i=p(r);return i.isNegative()?P:i}calculateAddOneAsset(e,t,s){let r=R.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?D(s.fee).toString():P.toString(),this.getPegs()),i=p(r);return i.isNegative()?P:i}calculateSharesForAmount(e,t,s){let r=R.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?D(s.fee).toString():P.toString(),this.getPegs()),i=p(r);return i.isNegative()?P: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=R.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=O(_,e.decimalsIn-e.decimalsOut);return p(t).div(r)}let s=O(_,18-e.decimalsIn);return p(t).div(s)}calculateOut(e,t,s){let r=R.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?D(s.fee).toString():P.toString(),this.getPegs()),i=p(r);return i.isNegative()?P:i}calculateWithdrawOneAsset(e,t,s){let r=R.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?D(s.fee).toString():P.toString(),this.getPegs()),i=p(r);return i.isNegative()?P:i}calculateShares(e,t,s){let r=R.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?D(s.fee).toString():P.toString(),this.getPegs()),i=p(r);return i.isNegative()?P: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=R.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=O(_,e.decimalsOut-e.decimalsIn);return p(t).div(r)}let s=O(_,18-e.decimalsOut);return p(t).div(s)}calculateTradeFee(e,t){let s=R.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 A=require("@galacticcouncil/math-xyk"),X=class{static getSpotPrice(e,t,s){return(0,A.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,A.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,A.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,A.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,A.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,A.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,A.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,A.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,A.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,A.calculate_liquidity_out_asset_b)(e,t,s,r)}};var ye=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=T(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=T(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=X.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?P:r}calculateOutGivenIn(e,t){let s=X.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?P:r}spotPriceInGivenOut(e){let t=X.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=O(_,18-e.decimalsOut);return p(t).div(s)}spotPriceOutGivenIn(e){let t=X.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=O(_,18-e.decimalsIn);return p(t).div(s)}calculateTradeFee(e,t){let s=X.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(s)}};var Se=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:P,assetOutED:P}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=[];return t.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=[];return r.isGreaterThan(e.balanceOut)&&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 O(_,e.decimalsOut)}spotPriceOutGivenIn(e){return O(_,e.decimalsIn)}calculateTradeFee(e,t){return P}};var re=class{static get(e){switch(e.type){case"Aave":return Se.fromPool(e);case"Xyk":return ye.fromPool(e);case"Omnipool":return fe.fromPool(e);case"Lbp":return Pe.fromPool(e);case"Stableswap":return be.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Z=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new oe,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,re.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 qt(l,e){return l.minus(e).abs().div(l.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ie(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 xe=class extends Z{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?T(e.min):void 0,s=e.max?T(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 K(e,t);let a;if(r)a=await this.toSellSwaps(s,r,n);else{let w=o.map(async W=>await this.toSellSwaps(s,W,n)),M=await Promise.all(w);a=this.findBestSellRoute(M)}let u=a[0],c=a[a.length-1],m=this.isDirectTrade(a),h=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,M)=>w.multipliedBy(M)),g=O(h,c.assetOutDecimals),d=m?c.calculatedOut:this.calculateDelta0Y(u.amountIn,a,n),f=c.amountOut,y=m?c.tradeFeePct:Ze(d,f).toNumber(),x=d.minus(f),S=this.getRouteFeeRange(a),N=u.amountIn.shiftedBy(-1*u.assetInDecimals).multipliedBy(g),F=ie(d,N),U=(w,M=!1)=>{let W=a.map(bt=>bt);return M?this.poolService.buildSellAllTx(e,t,w,W):this.poolService.buildSellTx(e,t,u.amountIn,w,W)};return{type:"Sell",amountIn:u.amountIn,amountOut:c.amountOut,spotPrice:g,tradeFee:x,tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F.toNumber(),swaps:a,toTx:U,toHuman(){return{type:"Sell",amountIn:k(u.amountIn,u.assetInDecimals),amountOut:k(c.amountOut,c.assetOutDecimals),spotPrice:k(g,c.assetOutDecimals),tradeFee:k(x,c.assetOutDecimals),tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F.toNumber(),swaps:a.map(w=>w.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=O(p(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:m,calculatedOut:h,feePct:g,errors:d}=o.validateAndSell(a,u,c),f=this.getPoolFeeRange(c),y=o.spotPriceOutGivenIn(a),x=u.shiftedBy(-1*a.decimalsIn).multipliedBy(y),S=ie(h,x);r.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,calculatedOut:h,amountOut:m,spotPrice:y,tradeFeePct:g,tradeFeeRange:f,priceImpactPct:S.toNumber(),errors:d,toHuman(){return{...n,amountIn:k(u,a.decimalsIn),calculatedOut:k(h,a.decimalsOut),amountOut:k(m,a.decimalsOut),spotPrice:k(y,a.decimalsOut),tradeFeePct:g,tradeFeeRange:f,priceImpactPct:S.toNumber(),errors:d}}})}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 K(e,t);let u=s.filter(g=>g.tokens.some(d=>d.id===e&&d.id!==g.id)).map(g=>g.type==="Aave"?g.tokens:g.tokens.filter(d=>d.id===e)).map(g=>g.map(d=>p(d.balance).shiftedBy(-1*d.decimals)).reduce((d,f)=>d.plus(f))).sort((g,d)=>d.isLessThan(g)?-1:1)[0].div(100).multipliedBy(.1),c=i.map(async g=>await this.toSellSwaps(u,g,r)),m=await Promise.all(c);return this.findBestSellRoute(m).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:O(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 K(e,t);let a;if(r)a=await this.toBuySwaps(s,r,n);else{let w=o.map(async W=>await this.toBuySwaps(s,W,n)),M=await Promise.all(w);a=this.findBestBuyRoute(M)}let u=a[a.length-1],c=a[0],m=this.isDirectTrade(a),h=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetInDecimals)).reduce((w,M)=>w.multipliedBy(M)),g=O(h,c.assetInDecimals),d=m?c.calculatedIn:this.calculateDelta0X(u.amountOut,a,n),f=c.amountIn,y=m?c.tradeFeePct:Ve(d,f).toNumber(),x=f.minus(d),S=this.getRouteFeeRange(a),N=u.amountOut.shiftedBy(-1*u.assetOutDecimals).multipliedBy(g),F;d.isZero()?F=-100:F=ie(N,d).toNumber();let U=w=>{let M=a.map(W=>W);return this.poolService.buildBuyTx(e,t,u.amountOut,w,M)};return{type:"Buy",amountOut:u.amountOut,amountIn:c.amountIn,spotPrice:g,tradeFee:x,tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F,swaps:a,toTx:U,toHuman(){return{type:"Buy",amountOut:k(u.amountOut,u.assetOutDecimals),amountIn:k(c.amountIn,c.assetInDecimals),spotPrice:k(g,c.assetInDecimals),tradeFee:k(x,c.assetInDecimals),tradeFeePct:y,tradeFeeRange:S,priceImpactPct:F,swaps:a.map(w=>w.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=O(p(e),a.decimalsOut).decimalPlaces(0,1):u=r[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:m,calculatedIn:h,feePct:g,errors:d}=o.validateAndBuy(a,u,c),f=this.getPoolFeeRange(c),y=o.spotPriceInGivenOut(a),x=u.shiftedBy(-1*a.decimalsOut).multipliedBy(y),S;h.isZero()?S=-100:S=ie(x,h).toNumber(),r.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:u,calculatedIn:h,amountIn:m,spotPrice:y,tradeFeePct:g,tradeFeeRange:f,priceImpactPct:S,errors:d,toHuman(){return{...n,amountOut:k(u,a.decimalsOut),calculatedIn:k(h,a.decimalsIn),amountIn:k(m,a.decimalsIn),spotPrice:k(y,a.decimalsIn),tradeFeePct:g,tradeFeeRange:f,priceImpactPct:S,errors:d}}})}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
|
-
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 Nt}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 F(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 N=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 Ft=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=N.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:Ft.toString()}),n}getPoolDefaultPegs(e){let t=e.fee,s=N.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]=N.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=N.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"}},Fe=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Ne=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=Nt(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=N.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=N.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=N.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=N.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=N.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=N.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=N.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=N.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=N.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=[];return t.isGreaterThan(e.balanceIn)&&o.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=[];return t.isGreaterThan(e.balanceOut)&&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:F(l.amountIn,l.assetInDecimals),amountOut:F(c.amountOut,c.assetOutDecimals),spotPrice:F(d,c.assetOutDecimals),tradeFee:F(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:F(l,a.decimalsIn),calculatedOut:F(P,a.decimalsOut),amountOut:F(u,a.decimalsOut),spotPrice:F(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:F(l.amountOut,l.assetOutDecimals),amountIn:F(c.amountIn,c.assetInDecimals),spotPrice:F(d,c.assetInDecimals),tradeFee:F(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:F(l,a.decimalsOut),calculatedIn:F(P,a.decimalsIn),amountIn:F(u,a.decimalsIn),spotPrice:F(f,a.decimalsIn),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y,errors:g}}})}return r}};import{memoize1 as Ba}from"@thi.ng/memoize";export{Ft 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,N as StableMath,pe as StableSwap,le as StableSwapClient,Fe as StorageConfigNotFound,Ne 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};
|
|
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 Le=5,J=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,i=[];for(i.push([t,""]),o.enqueue(i);o.size()>0;){let n=o.dequeue();if(n==null||n.length>Le)return r;let a=n[n.length-1];(s===null||a[0]===s)&&r.push(n),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,n)){let u=[...n];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,i]of t){let n=parseInt(o),a=parseInt(i);s.get(n)?.push([a,r])}return s}};function he(g){let e={};for(let t of g){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 i=[t.address,t.tokens[r].id,t.tokens[o].id];e[t.tokens[r].id].push(i)}}}return e}var K=class{getProposals(e,t,s){let r=he(s),o=Object.keys(r),i=o.map(c=>r[c]).flat(),n=new J,a=n.buildAndPopulateGraph(o,i),l=n.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 i=s[o],n=s[o+1];if(n==null)break;r.push(this.toEdge(i,n))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};import{memoize1 as Rt}from"@thi.ng/memoize";import{encodeAddress as Ue}from"@polkadot/util-crypto";import{stringToU8a as We}from"@polkadot/util";import{decodeEventLog as Xe}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 De}from"@polkadot/util-crypto";import{stringToU8a as Me}from"@polkadot/util";var j=18,Z=15,L="0",ls=12,se="1",cs=2034,W=63,us=2090,fe=1e3,ms=De(Me("modlomnipool".padEnd(32,"\0")),W);var R=(o=>(o.Aave="Aave",o.LBP="Lbp",o.Omni="Omnipool",o.Stable="Stableswap",o.XYK="Xyk",o))(R||{}),X=(o=>(o.UnknownError="UnknownError",o.InsufficientTradingAmount="InsufficientTradingAmount",o.MaxInRatioExceeded="MaxInRatioExceeded",o.MaxOutRatioExceeded="MaxOutRatioExceeded",o.TradeNotAllowed="TradeNotAllowed",o))(X||{}),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(g,e){let t=[];return JSON.stringify(g,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function Ps(g,e,t){let s;return JSON.stringify(g,(r,o)=>(o&&o[e]===t&&(s=o),o)),s}var bs=(g,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as He}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 Y=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:i,isSufficient:n,existentialDeposit:a}=t,{symbol:l,decimals:c}=s.get(e)??{};return{id:e,name:o.toHuman(),symbol:l,decimals:c,icon:l,type:i.toHuman(),isSufficient:n?n.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[o,i]=r,{assetType:n,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(o.toString(),t,s),P=i.toNumber(),p=new Intl.DateTimeFormat("en-GB"),d=[c,"Bond",p.format(P)].join(" ");return{id:e,name:d,symbol:c+"b",decimals:u,icon:c,type:n.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:o.toString(),maturity:P}}getShares(e,t,s,r){let{assets:o}=r,{name:i,symbol:n,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]}),p=Object.fromEntries(P),d=Object.values(p);return{id:e,name:d.join(", "),symbol:n?.isSome?n.toHuman():i.toHuman(),decimals:18,icon:d.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:p}}getExternal(e,t,s,r){let o=this.getToken(e,t,new Map,r),i=s?.find(n=>n.internalId===o.id);return i?{...o,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:o}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:o,symbol:i}=r.unwrap();return[s.toString(),{decimals:Number(o.toString()),symbol:i.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,i,n]=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,n),c=a.map(([{args:[u]},P])=>{let p=P.unwrap(),d=r.get(u.toString()),{assetType:b}=p;switch(b.toString()){case"Bond":let f=i.get(u.toString());return this.getBond(u.toString(),p,l,f);case"StableSwap":let S=o.get(u.toString());return this.getShares(u.toString(),p,l,S);case"External":return this.getExternal(u.toString(),p,t,d);default:return this.getToken(u.toString(),p,l,d)}});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 O}from"bignumber.js";var Ce=12;O.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Ce});var h=m(0),v=m(1),Is=m("Infinity");function w(g,e){let t=new O(e.toString()),s=new O(10).pow(t);return g.times(s)}function m(g){return new O(g.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(i=>i.type!=="Erc20").filter(i=>i.id!==L).map(i=>[e,i.id]);return this.api.query.tokens.accounts.multi(o,i=>{let n=[];i.forEach((a,l)=>{let c=this.calculateFreeBalance(a),u=o[l][1];n.push([u,c])}),s(n)})}async subscribeErc20Balance(e,t,s){let r=t.filter(i=>i.type==="Erc20"),o=async()=>{let i=[];(await Promise.all(r.map(async a=>[a.id,await this.getErc20Balance(e,a.id)]))).forEach(([a,l])=>{i.push([a,l])}),s(i)};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,i=new O(t),n=new O(s||o),a=new O(r||0n),l=n.gt(a)?n:a;return i.minus(l)}};import{isAddress as we}from"@polkadot/util-crypto";import{fixed_from_rational as Ie}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as Ge}from"@polkadot/types";import{u8aConcat as Ae}from"@polkadot/util";var ye=class extends M{balanceClient;constructor(e){super(e),this.balanceClient=new q(e)}secondsInYear=new O(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[,i]=r.args,n=o.unwrap().toString(),a=i.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),p=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),d=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(p,d);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[,i]=r.args,n=o.unwrap().toString(),a=i.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),p=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),d=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(p,d);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 O(1).shiftedBy(18).toString();let o=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(o.isNone)return;let[i]=o.unwrap(),n=i.price.n.toString(),a=i.price.d.toString(),l;return Number(t)<Number(s)?l=Ie(n,a):l=Ie(a,n),l}getGlobalRewardPerPeriod(e,t,s,r){let i=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return i.gte(s)?s:i}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}padEndU8a(e,t){return Ae(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",o=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Ge(e,this.padEndU8a(Ae(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:n,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let u=new O(a.totalSharesZ.toString()),P=a.plannedYieldingPeriods.toString(),p=new O(a.yieldPerPeriod.toString()),d=new O(a.maxRewardPerPeriod.toString()),b=a.blocksPerPeriod.toString(),f=new O(n.multiplier.toString()).shiftedBy(-18),S=this.secondsInYear.div(new O(s).times(b)),y;if(u.isZero())y=p.times(f).times(S);else{let _=this.getGlobalRewardPerPeriod(u,p,d,l);y=this.getPoolYieldPerPeriod(_,f,u,l).times(S)}let A=new O(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),T=d.times(P),G=c?A.plus(c):T;return A.div(G).gte(.999)?h:y.div(t==="isolatedpool"?2:1).times(100)}).reduce((n,a)=>n.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=He(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 i=e.tokens.findIndex(n=>n.id==r);i>=0&&t(e,r)&&(e.tokens[i].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 Ye=["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 Ue(We(s.padEnd(32,"\0")),W)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);return this.api.query.system.events(o=>{o.forEach(i=>{let{event:n}=i,a=`${n.section}:${n.method}`;if(a==="router:Executed"){let{assetIn:l,assetOut:c}=n.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}=n.data.toHuman();try{let{eventName:c,args:u}=Xe({abi:Be,topics:l.topics,data:l.data});Ye.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(i=>{let n=i.id===t.id?r.toString():o.toString();return{...i,balance:n}})}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 $e,calculate_out_given_in as ze,calculate_linear_weights as Je,calculate_pool_trade_fee as Ke,get_spot_price as je}from"@galacticcouncil/math-lbp";var C=class{static getSpotPrice(e,t,s,r,o){return je(e,t,s,r,o)}static calculateInGivenOut(e,t,s,r,o){return $e(e,t,s,r,o)}static calculateOutGivenIn(e,t,s,r,o){return ze(e,t,s,r,o)}static calculateLinearWeights(e,t,s,r,o){return Je(e,t,s,r,o)}static calculatePoolTradeFee(e,t,s){return Ke(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,i])=>this.isActivePool(i.unwrap(),s)).map(async([{args:[o]},i])=>{let n=i.unwrap(),a=o.toString(),l=await this.getPoolDelta(a,n,s.toString());return this.poolsData.set(o.toString(),n),{address:a,type:"Lbp",fee:n.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 i=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,i)}else{let i=this.pools.findIndex(n=>n.address==e.address);this.pools.splice(i,1)}})}async getPoolDelta(e,t,s){let{start:r,end:o,assets:i,initialWeight:n,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=C.calculateLinearWeights(r.toString(),o.toString(),n.toString(),a.toString(),s),[P,p]=i,d=P.toString(),b=m(u),f=p.toString(),S=this.MAX_FINAL_WEIGHT.minus(m(b)),[y,A,T]=await Promise.all([this.isRepayFeeApplied(d,l.toString(),c.toString()),this.getBalance(e,d),this.getBalance(e,f)]);return{repayFeeApply:y,tokens:[{id:d,weight:b,balance:A.toString()},{id:f,weight:S,balance:T.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 Pt}from"@polkadot/util-crypto";import{stringToU8a as bt}from"@polkadot/util";function F(g,e){return g.shiftedBy(-1*e).toString()}function I(g){return g[0]/g[1]*100}function k(g){return g[0]/g[1]}function E(g){return[g/fe,fe]}import{calculate_in_given_out as Ze,calculate_lrna_in_given_out as Ve,calculate_out_given_in as Qe,calculate_out_given_lrna_in as et,calculate_pool_trade_fee as tt,calculate_spot_price as st,calculate_lrna_spot_price as rt,calculate_shares as ot,calculate_liquidity_out as it,calculate_liquidity_lrna_out as nt,calculate_liquidity_hub_in as at,is_sell_allowed as lt,is_buy_allowed as ct,is_add_liquidity_allowed as ut,is_remove_liquidity_allowed as mt,recalculate_asset_fee as pt,recalculate_protocol_fee as gt,verify_asset_cap as dt}from"@galacticcouncil/math-omnipool";var x=class{static calculateSpotPrice(e,t,s,r){return st(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return rt(e,t)}static calculateInGivenOut(e,t,s,r,o,i,n,a,l){return Ze(e,t,s,r,o,i,n,a,l)}static calculateLrnaInGivenOut(e,t,s,r,o){return Ve(e,t,s,r,o)}static calculateOutGivenIn(e,t,s,r,o,i,n,a,l){return Qe(e,t,s,r,o,i,n,a,l)}static calculateOutGivenLrnaIn(e,t,s,r,o){return et(e,t,s,r,o)}static calculatePoolTradeFee(e,t,s){return tt(e,t,s)}static calculateShares(e,t,s,r){return ot(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,o,i,n,a){return it(e,t,s,r,o,i,n,a)}static calculateLiquidityLRNAOut(e,t,s,r,o,i,n,a){return nt(e,t,s,r,o,i,n,a)}static calculateCapDifference(e,t,s,r){let o=O(t),i=O(e),n=O(r),l=O(s).shiftedBy(-18);if(o.div(n).lt(l)){let u=l.times(n).minus(o).times(i),P=o.times(O(1).minus(l));return u.div(P).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return at(e,t,s,r)}static isSellAllowed(e){return lt(e)}static isBuyAllowed(e){return ct(e)}static isAddLiquidityAllowed(e){return ut(e)}static isRemoveLiquidityAllowed(e){return mt(e)}static recalculateAssetFee(e,t,s,r,o,i,n,a,l,c,u){return pt(e,t,s,r,o,i,n,a,l,c,u)}static recalculateProtocolFee(e,t,s,r,o,i,n,a,l,c,u){return gt(e,t,s,r,o,i,n,a,l,c,u)}static verifyAssetCap(e,t,s,r){return dt(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)]),i=s.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:u,tradable:P,cap:p,protocolShares:d}=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(p.toString()),protocolShares:m(d.toString())}}),n=await Promise.all(i);return n.push({id:e,tradeable:r.bits.toNumber(),balance:o.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:n,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,o="omnipool",i="Short",n=T=>T===L?[L,se]:[se,T],[a,l,c,u]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(o,n(s),i),this.api.query.emaOracle.oracles(o,n(r),i)]),[P,p,d]=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,A=d+S;return{assetFee:E(p),protocolFee:E(f),min:E(y),max:E(A)}}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 i=e.tokens[o];if(r.isNone)return i;let n=r.unwrap();return this.updateTokenState(i,n)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:o,cap:i,protocolShares:n}=t;return{...e,hubReserves:m(s.toString()),shares:m(r.toString()),cap:m(i.toString()),protocolShares:m(n.toString()),tradeable:o.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:o,balanceOut:i}=e,{minFee:n,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,u=E(n.toNumber()),P=E(a.toNumber());if(s.isNone||r.isNone)return[n.toNumber(),n.toNumber(),a.toNumber()];let[p]=r.unwrap(),{assetFee:d,timestamp:b}=s.unwrap(),f=t-b.toNumber(),S=p.volume.bIn.toString(),y=p.volume.bOut.toString(),A=p.liquidity.b.toString();o===L&&(S=p.volume.aIn.toString(),y=p.volume.aOut.toString(),A=p.liquidity.a.toString());let T=E(d.toNumber()),G=x.recalculateAssetFee(S,y,A,"9",i.toString(),I(T).toString(),f.toString(),I(u).toString(),I(P).toString(),l.toString(),c.toString());return[n.toNumber(),Number(G)*1e4,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:o,balanceIn:i}=e,{minFee:n,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,u=E(n.toNumber()),P=E(a.toNumber());if(s.isNone||r.isNone)return[n.toNumber(),n.toNumber(),a.toNumber()];let[p]=r.unwrap(),{protocolFee:d,timestamp:b}=s.unwrap(),f=t-b.toNumber(),S=p.volume.bIn.toString(),y=p.volume.bOut.toString(),A=p.liquidity.b.toString();o===L&&(S=p.volume.aIn.toString(),y=p.volume.aOut.toString(),A=p.liquidity.a.toString());let T=E(d.toNumber()),G=x.recalculateProtocolFee(S,y,A,"9",i.toString(),I(T).toString(),f.toString(),I(u).toString(),I(P).toString(),l.toString(),c.toString());return[n.toNumber(),Number(G)*1e4,a.toNumber()]}getPoolId(){return Pt(bt("modlomnipool".padEnd(32,"\0")),W)}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(),[i,n]=r.unwrap(),[a,l]=await Promise.all([this.getBalance(o,i.toString()),this.getBalance(o,n.toString())]);return{address:o,type:"Xyk",tokens:[{id:i.toString(),balance:a.toString()},{id:n.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 vt,encodeAddress as Ft}from"@polkadot/util-crypto";import{calculate_in_given_out as ht,calculate_out_given_in as ft,calculate_amplification as yt,calculate_add_one_asset as St,calculate_liquidity_out_one_asset as Bt,calculate_pool_trade_fee as Ot,calculate_shares as xt,calculate_shares_for_amount as wt,calculate_spot_price_with_fee as It,pool_account_name as At,recalculate_peg as Tt}from"@galacticcouncil/math-stableswap";var N=class{static getPoolAddress(e){return At(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 yt(e,t,s,r,o)}static calculateInGivenOut(e,t,s,r,o,i,n){return ht(e,t,s,r,o,i,n)}static calculateAddOneAsset(e,t,s,r,o,i,n){return St(e,t,s,r,o,i,n)}static calculateSharesForAmount(e,t,s,r,o,i,n){return wt(e,t,s,r,o,i,n)}static calculateOutGivenIn(e,t,s,r,o,i,n){return ft(e,t,s,r,o,i,n)}static calculateLiquidityOutOneAsset(e,t,s,r,o,i,n){return Bt(e,t,s,r,o,i,n)}static calculateShares(e,t,s,r,o,i){return xt(e,t,s,r,o,i)}static calculateSpotPriceWithFee(e,t,s,r,o,i,n,a){return It(e,t,s,r,o,i,n,a)}static calculatePoolTradeFee(e,t,s){return Ot(e,t,s)}static recalculatePegs(e,t,s,r,o){let i=Tt(e,t,s,r,o);return JSON.parse(i)}};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]},i])=>{let n=i.unwrap(),a=o.toString(),l=this.getPoolAddress(a),[c,u,P]=await Promise.all([this.getPoolDelta(a,n,s.toString()),this.getPoolTokens(l,a,n),this.getPoolPegs(a,n,s.toString())]);return this.stablePools.set(l,n),{address:l,id:a,type:"Stableswap",fee:E(n.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,i]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,o,i)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:o,initialBlock:i,finalBlock:n}=t,a=N.calculateAmplification(r.toString(),o.toString(),i.toString(),n.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 n=>{let[a,l]=await Promise.all([this.api.query.stableswap.assetTradability(t,n.toString()),this.getBalance(e,n.toString())]);return{id:n.toString(),tradeable:a.bits.toNumber(),balance:l.toString()}}),i=await Promise.all(o);return i.push({id:t,tradeable:Z,balance:Nt.toString()}),i}getPoolDefaultPegs(e){let t=e.fee,s=N.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(),i=await this.getLatestPegs(t,o,s),n=this.getRecentPegs(o),a=o.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[c,u]=N.recalculatePegs(JSON.stringify(n),JSON.stringify(i),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(([n,a])=>a.toString()),i=r.map(async(n,a)=>{if(n.isOracle){let[l,c,u]=n.asOracle,P=[u.toString(),o[a]].map(y=>Number(y)).sort((y,A)=>y-A),p=await this.api.query.emaOracle.oracles(l,P,c),[{price:d,updatedAt:b}]=p.unwrap(),f=d.n.toString(),S=d.d.toString();return u.toString()===P[0].toString()?[[f,S],b.toString()]:[[S,f],b.toString()]}else return[n.asValue.map(l=>l.toString()),s]});return Promise.all(i)}getPoolAddress(e){let t=Number(e),s=N.getPoolAddress(t);return Ft(vt(s),W)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function ce(g){return g.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 ue=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Te=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},$=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"}},Fe=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Ne=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 V=class extends M{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=Rt(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new Y(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 ue(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}async dryRun(e,t){let s;try{s=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(r){throw console.error(r),new Error("Dry run execution failed!")}if(s.isOk)return s.asOk;throw console.log(s.asErr.toHuman()),new Error("Dry run execution error!")}buildBuyTx(e,t,s,r,o){let i;return this.isDirectOmnipoolTrade(o)?i=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):i=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),ce(o)),{hex:i.toHex(),name:"RouterBuy",get:()=>i,dryRun:n=>this.dryRun(n,i)}}buildSellTx(e,t,s,r,o){let i;return this.isDirectOmnipoolTrade(o)?i=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):i=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),ce(o)),{hex:i.toHex(),name:"RouterSell",get:()=>i,dryRun:n=>this.dryRun(n,i)}}buildSellAllTx(e,t,s,r){let o=this.api.tx.router.sellAll(e,t,s.toFixed(),ce(r));return{hex:o.toHex(),name:"RouterSellAll",get:()=>o,dryRun:i=>this.dryRun(i,o)}}};import{LRUCache as Et}from"@thi.ng/cache";var Se=class extends V{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Et(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 me=class g{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new g(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,o,i,n){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o,this.fee=i,this.repayFeeApply=n}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 i=m(r.balance),n=m(o.balance);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:n,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 i=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(i)&&o.push("MaxOutRatioExceeded"),r===e.assetOut){let n=this.calculateTradeFee(t,s),a=I(this.repayFeeApply?s.repayFee:s.exchangeFee),l=t.plus(n),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 n=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(a)&&o.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:n,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 i=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(i)&&o.push("MaxInRatioExceeded"),r===e.assetIn){let n=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(a)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:n,feePct:0,errors:o}}else{let n=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(n,s),l=I(this.repayFeeApply?s.repayFee:s.exchangeFee),c=n.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,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 pe=class g{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new g(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,o,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o,this.hubAssetId=i}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 i=m(r.balance),n=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:i,balanceOut:n,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),i=o.minus(r),n=r===h?h:i.div(r).multipliedBy(100).decimalPlaces(2),a=[],l=x.isSellAllowed(e.tradeableIn),c=x.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:n.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=this.calculateOutGivenIn(e,t,s),n=r.minus(o).div(r).multipliedBy(100).decimalPlaces(2),a=[],l=x.isSellAllowed(e.tradeableIn),c=x.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:n.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=x.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?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=x.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=x.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=x.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=x.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(j-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=x.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(j-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=x.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(j-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=x.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(j-e.decimalsIn)).decimalPlaces(0,1)}};var ge=class g{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new g(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,i,n,a,l,c,u){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o,this.amplification=i,this.id=n,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 i=m(r.balance),n=m(o.balance),a=m(r.existentialDeposit),l=m(o.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:n,decimalsIn:r.decimals,decimalsOut:o.decimals,tradeableIn:this.id===e?Z:r.tradeable,tradeableOut:this.id===t?Z:o.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,s),i=I(s.fee),n=[],a=x.isSellAllowed(e.tradeableIn),l=x.isBuyAllowed(e.tradeableOut);return(!a||!l)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&n.push("InsufficientTradingAmount"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:i,errors:n}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=this.calculateOutGivenIn(e,t,s),i=I(s.fee),n=[],a=x.isSellAllowed(e.tradeableIn),l=x.isBuyAllowed(e.tradeableOut);return(!a||!l)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&n.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:i,errors:n}}calculateIn(e,t,s){let r=N.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=N.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=N.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=N.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=N.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=N.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=N.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=N.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=N.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 kt,calculate_out_given_in as _t,calculate_pool_trade_fee as Lt,get_spot_price as Dt,calculate_liquidity_in as Mt,calculate_shares as Ct,calculate_spot_price as Gt,calculate_spot_price_with_fee as Ht,calculate_liquidity_out_asset_a as qt,calculate_liquidity_out_asset_b as Ut}from"@galacticcouncil/math-xyk";var U=class{static getSpotPrice(e,t,s){return Dt(e,t,s)}static calculateInGivenOut(e,t,s){return kt(e,t,s)}static calculateOutGivenIn(e,t,s){return _t(e,t,s)}static calculatePoolTradeFee(e,t,s){return Lt(e,t,s)}static calculateLiquidityIn(e,t,s){return Mt(e,t,s)}static calculateSpotPrice(e,t){return Gt(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return Ht(e,t,s,r)}static calculateShares(e,t,s){return Ct(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return qt(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Ut(e,t,s,r)}};var de=class g{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new g(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 i=m(r.balance),n=m(o.balance),a=m(r.existentialDeposit),l=m(o.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:i,balanceOut:n,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateTradeFee(r,s),i=I(s.exchangeFee),n=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 n.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(r,s),i=I(s.exchangeFee),n=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 n.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:i,errors:a}}calculateInGivenOut(e,t){let s=U.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?h:r}calculateOutGivenIn(e,t){let s=U.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?h:r}spotPriceInGivenOut(e){let t=U.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=w(v,18-e.decimalsOut);return m(t).div(s)}spotPriceOutGivenIn(e){let t=U.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=w(v,18-e.decimalsIn);return m(t).div(s)}calculateTradeFee(e,t){let s=U.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(s)}};var Pe=class g{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new g(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 i=m(r.balance),n=m(o.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:i,balanceOut:n,assetInED:h,assetOutED:h}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=[];return t.isGreaterThan(e.balanceOut)&&o.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=[];return r.isGreaterThan(e.balanceOut)&&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 Q=class{static get(e){switch(e.type){case"Aave":return Pe.fromPool(e);case"Xyk":return de.fromPool(e);case"Omnipool":return pe.fromPool(e);case"Lbp":return me.fromPool(e);case"Stableswap":return ge.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var z=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new K,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),i=this.getPaths(e,null,r,t).map(n=>n[n.length-1].assetOut);return this.toAssets([...new Set(i)],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(n=>this.validPath(n,s)).map(n=>this.toHops(n,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,Q.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 i=t.get(s);return{poolAddress:s,poolId:i?.id,pool:i?.type,assetIn:r,assetOut:o}})}toAssets(e,t){return e.map(s=>t.get(s))}};function ta(g,e){return g.minus(e).abs().div(g.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ee(g,e){return g.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ee(g,e){return v.minus(e.div(g)).multipliedBy(100).decimalPlaces(2)}function ke(g,e){return e.div(g).minus(v).multipliedBy(100).decimalPlaces(2)}var be=class extends z{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let o=s[s.length-1].amountOut,i=r[r.length-1].amountOut;return o.isGreaterThan(i)?-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,i)=>o+i),r=e.map(o=>o.tradeFeeRange?.[1]??o.tradeFeePct).reduce((o,i)=>o+i);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:i}=await super.validateTokenPair(e,t,o),n=super.getPaths(e,t,i,o);if(n.length===0)throw new $(e,t);let a;if(r)a=await this.toSellSwaps(s,r,i);else{let B=n.map(async H=>await this.toSellSwaps(s,H,i)),_=await Promise.all(B);a=this.findBestSellRoute(_)}let l=a[0],c=a[a.length-1],u=this.isDirectTrade(a),P=a.map(B=>B.spotPrice.shiftedBy(-1*B.assetOutDecimals)).reduce((B,_)=>B.multipliedBy(_)),p=w(P,c.assetOutDecimals),d=u?c.calculatedOut:this.calculateDelta0Y(l.amountIn,a,i),b=c.amountOut,f=u?c.tradeFeePct:Ee(d,b).toNumber(),S=d.minus(b),y=this.getRouteFeeRange(a),A=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(p),T=ee(d,A),G=(B,_=!1)=>{let H=a.map(_e=>_e);return _?this.poolService.buildSellAllTx(e,t,B,H):this.poolService.buildSellTx(e,t,l.amountIn,B,H)};return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:p,tradeFee:S,tradeFeePct:f,tradeFeeRange:y,priceImpactPct:T.toNumber(),swaps:a,toTx:G,toHuman(){return{type:"Sell",amountIn:F(l.amountIn,l.assetInDecimals),amountOut:F(c.amountOut,c.assetOutDecimals),spotPrice:F(p,c.assetOutDecimals),tradeFee:F(S,c.assetOutDecimals),tradeFeePct:f,tradeFeeRange:y,priceImpactPct:T.toNumber(),swaps:a.map(B=>B.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let o=0;o<t.length;o++){let i=t[o],n=s.get(i.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(i.assetIn,i.assetOut),l;o>0?l=r[o-1]:l=e;let c=n.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 i=t[o],n=s.get(i.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(i.assetIn,i.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,n),{amountOut:u,calculatedOut:P,feePct:p,errors:d}=n.validateAndSell(a,l,c),b=this.getPoolFeeRange(c),f=n.spotPriceOutGivenIn(a),S=l.shiftedBy(-1*a.decimalsIn).multipliedBy(f),y=ee(P,S);r.push({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,calculatedOut:P,amountOut:u,spotPrice:f,tradeFeePct:p,tradeFeeRange:b,priceImpactPct:y.toNumber(),errors:d,toHuman(){return{...i,amountIn:F(l,a.decimalsIn),calculatedOut:F(P,a.decimalsOut),amountOut:F(u,a.decimalsOut),spotPrice:F(f,a.decimalsOut),tradeFeePct:p,tradeFeeRange:b,priceImpactPct:y.toNumber(),errors:d}}})}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 $(e,t);let l=s.filter(p=>p.tokens.some(d=>d.id===e&&d.id!==p.id)).map(p=>p.type==="Aave"?p.tokens:p.tokens.filter(d=>d.id===e)).map(p=>p.map(d=>m(d.balance).shiftedBy(-1*d.decimals)).reduce((d,b)=>d.plus(b))).sort((p,d)=>d.isLessThan(p)?-1:1)[0].div(100).multipliedBy(.1),c=o.map(async p=>await this.toSellSwaps(l,p,r)),u=await Promise.all(c);return this.findBestSellRoute(u).map(p=>({poolAddress:p.poolAddress,poolId:p?.poolId,pool:p.pool,assetIn:p.assetIn,assetOut:p.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 i=await this.getMostLiquidRoute(e,t),n=await this.toSellSwaps("1",i,r),a=n.map(u=>u.spotPrice.shiftedBy(-1*u.assetOutDecimals)).reduce((u,P)=>u.multipliedBy(P)),l=n[n.length-1].assetOutDecimals;return{amount:w(a,l),decimals:l}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let o=s[0].amountIn,i=r[0].amountIn;return o.isGreaterThan(i)?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:i}=await super.validateTokenPair(e,t,o),n=super.getPaths(e,t,i,o);if(n.length===0)throw new $(e,t);let a;if(r)a=await this.toBuySwaps(s,r,i);else{let B=n.map(async H=>await this.toBuySwaps(s,H,i)),_=await Promise.all(B);a=this.findBestBuyRoute(_)}let l=a[a.length-1],c=a[0],u=this.isDirectTrade(a),P=a.map(B=>B.spotPrice.shiftedBy(-1*B.assetInDecimals)).reduce((B,_)=>B.multipliedBy(_)),p=w(P,c.assetInDecimals),d=u?c.calculatedIn:this.calculateDelta0X(l.amountOut,a,i),b=c.amountIn,f=u?c.tradeFeePct:ke(d,b).toNumber(),S=b.minus(d),y=this.getRouteFeeRange(a),A=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(p),T;d.isZero()?T=-100:T=ee(A,d).toNumber();let G=B=>{let _=a.map(H=>H);return this.poolService.buildBuyTx(e,t,l.amountOut,B,_)};return{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:p,tradeFee:S,tradeFeePct:f,tradeFeeRange:y,priceImpactPct:T,swaps:a,toTx:G,toHuman(){return{type:"Buy",amountOut:F(l.amountOut,l.assetOutDecimals),amountIn:F(c.amountIn,c.assetInDecimals),spotPrice:F(p,c.assetInDecimals),tradeFee:F(S,c.assetInDecimals),tradeFeePct:f,tradeFeeRange:y,priceImpactPct:T,swaps:a.map(B=>B.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let o=t.length-1;o>=0;o--){let i=t[o],n=s.get(i.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(i.assetIn,i.assetOut),l;o==t.length-1?l=e:l=r[0];let c=n.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 i=t[o],n=s.get(i.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(i.assetIn,i.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,n),{amountIn:u,calculatedIn:P,feePct:p,errors:d}=n.validateAndBuy(a,l,c),b=this.getPoolFeeRange(c),f=n.spotPriceInGivenOut(a),S=l.shiftedBy(-1*a.decimalsOut).multipliedBy(f),y;P.isZero()?y=-100:y=ee(S,P).toNumber(),r.unshift({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:l,calculatedIn:P,amountIn:u,spotPrice:f,tradeFeePct:p,tradeFeeRange:b,priceImpactPct:y,errors:d,toHuman(){return{...i,amountOut:F(l,a.decimalsOut),calculatedIn:F(P,a.decimalsIn),amountIn:F(u,a.decimalsIn),spotPrice:F(f,a.decimalsIn),tradeFeePct:p,tradeFeeRange:b,priceImpactPct:y,errors:d}}})}return r}};import{memoize1 as Oa}from"@thi.ng/memoize";export{Nt as AMOUNT_MAX,Pe as AavePool,oe as AavePoolClient,Y as AssetClient,ve as AssetNotFound,us as BASILISK_PARACHAIN_ID,q as BalanceClient,O as BigNumber,Se as CachingPoolService,Ce as DECIMAL_PLACES,fe as DENOMINATOR,ye as FarmClient,se as HUB_ASSET_ID,ms as HYDRADX_OMNIPOOL_ADDRESS,cs as HYDRADX_PARACHAIN_ID,W as HYDRADX_SS58_PREFIX,Is as INFINITY,C as LbpMath,me as LbpPool,ie as LbpPoolClient,v as ONE,x as OmniMath,pe as OmniPool,ne as OmniPoolClient,M as PolkadotApiClient,Te as PoolConfigNotFound,X as PoolError,Q as PoolFactory,ue as PoolNotFound,V as PoolService,R as PoolType,Re as ProviderConfigNotFound,j as RUNTIME_DECIMALS,$ as RouteNotFound,z as Router,ls as SYSTEM_ASSET_DECIMALS,L as SYSTEM_ASSET_ID,N as StableMath,ge as StableSwap,le as StableSwapClient,Fe as StorageConfigNotFound,Ne as SubscriptionNotSupported,Z as TRADEABLE_DEFAULT,be as TradeRouter,Oe as TradeType,U as XykMath,de as XykPool,ae as XykPoolClient,h as ZERO,bs as bnFormatter,m as bnum,ce as buildRoute,ke as calculateBuyFee,ta as calculateDiffToAvg,ee as calculateDiffToRef,Ee as calculateSellFee,xe as findNestedKey,Ps as findNestedObj,w as scale};
|
|
@@ -27,6 +27,8 @@ export declare class PoolService extends PolkadotApiClient implements IPoolServi
|
|
|
27
27
|
unsubscribe(): void;
|
|
28
28
|
getPoolFees(poolPair: PoolPair, pool: Pool): Promise<PoolFees>;
|
|
29
29
|
private isDirectOmnipoolTrade;
|
|
30
|
+
private dryRun;
|
|
30
31
|
buildBuyTx(assetIn: string, assetOut: string, amountOut: BigNumber, maxAmountIn: BigNumber, route: Hop[]): Transaction;
|
|
31
32
|
buildSellTx(assetIn: string, assetOut: string, amountIn: BigNumber, minAmountOut: BigNumber, route: Hop[]): Transaction;
|
|
33
|
+
buildSellAllTx(assetIn: string, assetOut: string, minAmountOut: BigNumber, route: Hop[]): Transaction;
|
|
32
34
|
}
|
package/build/types/types.d.ts
CHANGED
|
@@ -72,11 +72,13 @@ export interface IPoolService {
|
|
|
72
72
|
getPoolFees(poolPair: PoolPair, pool: Pool): Promise<PoolFees>;
|
|
73
73
|
buildBuyTx(assetIn: string, assetOut: string, amountOut: BigNumber, maxAmountIn: BigNumber, route: Hop[]): Transaction;
|
|
74
74
|
buildSellTx(assetIn: string, assetOut: string, amountIn: BigNumber, minAmountOut: BigNumber, route: Hop[]): Transaction;
|
|
75
|
+
buildSellAllTx(assetIn: string, assetOut: string, minAmountOut: BigNumber, route: Hop[]): Transaction;
|
|
75
76
|
}
|
|
76
77
|
export interface Transaction {
|
|
77
78
|
hex: string;
|
|
78
79
|
name?: string;
|
|
79
80
|
get<T>(): T;
|
|
81
|
+
dryRun<R>(account: string): Promise<R>;
|
|
80
82
|
}
|
|
81
83
|
export type Hop = {
|
|
82
84
|
pool: PoolType;
|
|
@@ -111,7 +113,7 @@ export interface Trade extends Humanizer {
|
|
|
111
113
|
tradeFeePct: number;
|
|
112
114
|
priceImpactPct: number;
|
|
113
115
|
swaps: Swap[];
|
|
114
|
-
toTx(tradeLimit: BigNumber): Transaction;
|
|
116
|
+
toTx(tradeLimit: BigNumber, tradeAll?: boolean): Transaction;
|
|
115
117
|
}
|
|
116
118
|
export interface Humanizer {
|
|
117
119
|
toHuman(): any;
|