@galacticcouncil/sdk-next 0.41.0 → 0.41.1
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/farm/index.cjs +1 -1
- package/build/farm/index.mjs +1 -1
- package/build/index.cjs +1 -1
- package/build/index.mjs +1 -1
- package/build/pool/index.cjs +1 -1
- package/build/pool/index.mjs +1 -1
- package/build/sor/index.cjs +1 -1
- package/build/sor/index.mjs +1 -1
- package/build/tx/index.cjs +1 -1
- package/build/tx/index.mjs +1 -1
- package/package.json +1 -1
package/build/pool/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Ze=Object.create;var Ft=Object.defineProperty;var ti=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ii=Object.getPrototypeOf,si=Object.prototype.hasOwnProperty;var H=(o,t)=>{for(var e in t)Ft(o,e,{get:t[e],enumerable:!0})},ge=(o,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ei(t))!si.call(o,s)&&s!==e&&Ft(o,s,{get:()=>t[s],enumerable:!(i=ti(t,s))||i.enumerable});return o};var se=(o,t,e)=>(e=o!=null?Ze(ii(o)):{},ge(t||!o||!o.__esModule?Ft(e,"default",{value:o,enumerable:!0}):e,o)),ni=o=>ge(Ft({},"__esModule",{value:!0}),o);var Li={};H(Li,{PoolContextProvider:()=>ie,PoolError:()=>tt,PoolFactory:()=>te,PoolType:()=>O,aave:()=>me,hsm:()=>he,lbp:()=>oe,omni:()=>ce,stable:()=>ue,xyk:()=>pe});module.exports=ni(Li);var oe={};H(oe,{LbpMath:()=>G,LbpPool:()=>gt,LbpPoolClient:()=>ft});var z=require("@galacticcouncil/math-lbp"),G=class{static getSpotPrice(t,e,i,s,n){return(0,z.get_spot_price)(t,e,i,s,n)}static calculateInGivenOut(t,e,i,s,n){return(0,z.calculate_in_given_out)(t,e,i,s,n)}static calculateOutGivenIn(t,e,i,s,n){return(0,z.calculate_out_given_in)(t,e,i,s,n)}static calculateLinearWeights(t,e,i,s,n){return(0,z.calculate_linear_weights)(t,e,i,s,n)}static calculatePoolTradeFee(t,e,i){return(0,z.calculate_pool_trade_fee)(t,e,i)}};var rt=require("@galacticcouncil/common");var O=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a.HSM="HSM",a))(O||{}),tt=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(tt||{});var kt={};H(kt,{withTimeout:()=>ai});function ai(o,t,e="timeout"){return new Promise((i,s)=>{let n=setTimeout(()=>s(new Error(e)),t);o.then(a=>{clearTimeout(n),i(a)},a=>{clearTimeout(n),s(a)})})}var ri=require("@galacticcouncil/common");var I={};H(I,{FeeUtils:()=>ne,shiftNeg:()=>ci});var be=se(require("big.js"));var ne=class o{static toPct(t){let[e,i]=t;return o.safeDivide(e*100,i)}static toRaw(t){let[e,i]=t;return o.safeDivide(e,i)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,i=12){let s=10**i;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function ci(o,t){let e=(0,be.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var dt={};H(dt,{findNestedKey:()=>ui,findNestedObj:()=>pi,jsonFormatter:()=>mi});var ui=(o,t)=>{let e=[];return JSON.stringify(o,(i,s)=>(s&&s[t]&&e.push(s),s)),e[0]},pi=(o,t,e)=>{let i;return JSON.stringify(o,(s,n)=>(n&&n[t]===e&&(i=n),n)),i},mi=(o,t)=>typeof t=="bigint"?t.toString():t;var et={};H(et,{calculateBuyFee:()=>bi,calculateDiffToAvg:()=>di,calculateDiffToRef:()=>hi,calculateSellFee:()=>gi});var V=se(require("big.js"));function di(o,t){let e=(0,V.default)(o.toString()),i=(0,V.default)(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function hi(o,t){if(t===0n)return 0;let e=(0,V.default)(o.toString()),i=(0,V.default)(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function gi(o,t){if(o===0n)return 0;let e=(0,V.default)(o.toString()),i=(0,V.default)(t.toString());return(0,V.default)(1).minus(i.div(e)).mul(100).round(2).toNumber()}function bi(o,t){if(o===0n)return 0;let e=(0,V.default)(o.toString());return(0,V.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var ht=(o,t)=>o===t?0:o==null?t==null?0:-1:t==null?o==null?0:1:typeof o.compare=="function"?o.compare(t):typeof t.compare=="function"?-t.compare(o):o<t?-1:o>t?1:0;var Rt=(o,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(o(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var fi=Rt(()=>"illegal argument(s)"),fe=o=>{throw new fi(o)};var yi=Rt(()=>"index out of bounds"),ae=o=>{throw new yi(o)},Ct=(o,t,e)=>(o<t||o>=e)&&ae(o);var ye=23283064365386963e-26,Mt=class{float(t=1){return this.int()*ye*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*ye-.5)*2*t}normMinMax(t,e){let i=this.minmax(t,e);return this.float()<.5?i:-i}minmax(t,e){return this.float()*(e-t)+t}minmaxInt(t,e){t|=0;let i=(e|0)-t;return i?t+this.int()%i:t}minmaxUint(t,e){t>>>=0;let i=(e>>>0)-t;return i?t+this.int()%i:t}};var Lt=class extends Mt{constructor(t){super(),this.rnd=t}float(t=1){return this.rnd()*t}norm(t=1){return(this.rnd()-.5)*2*t}int(){return this.rnd()*4294967296>>>0}};var Pe=new Lt(Math.random);var ve=o=>o!=null&&typeof o!="function"&&o.length!==void 0;var Se=Object.getPrototypeOf({}),Dt="function",xe="string",at=(o,t)=>{let e;if(o===t)return!0;if(o!=null){if(typeof o.equiv===Dt)return o.equiv(t)}else return o==t;if(t!=null){if(typeof t.equiv===Dt)return t.equiv(o)}else return o==t;return typeof o===xe||typeof t===xe?!1:(e=Object.getPrototypeOf(o),(e==null||e===Se)&&(e=Object.getPrototypeOf(t),e==null||e===Se)?xi(o,t):typeof o!==Dt&&o.length!==void 0&&typeof t!==Dt&&t.length!==void 0?Pi(o,t):o instanceof Set&&t instanceof Set?vi(o,t):o instanceof Map&&t instanceof Map?Si(o,t):o instanceof Date&&t instanceof Date?o.getTime()===t.getTime():o instanceof RegExp&&t instanceof RegExp?o.toString()===t.toString():o!==o&&t!==t)},Pi=(o,t,e=at)=>{let i=o.length;if(i===t.length)for(;i-- >0&&e(o[i],t[i]););return i<0},vi=(o,t,e=at)=>o.size===t.size&&e([...o.keys()].sort(),[...t.keys()].sort()),Si=(o,t,e=at)=>o.size===t.size&&e([...o].sort(),[...t].sort()),xi=(o,t,e=at)=>{if(Object.keys(o).length!==Object.keys(t).length)return!1;for(let i in o)if(!t.hasOwnProperty(i)||!e(o[i],t[i]))return!1;return!0};var re=class{value;constructor(t){this.value=t}deref(){return this.value}};var we=o=>o instanceof re;var qt=class o{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Oe("next",this._head)}reverseIterator(){return Oe("prev",this.tail)}clear(){this.release()}compare(t,e=ht){let i=this._length;if(i<t._length)return-1;if(i>t._length)return 1;if(i===0)return 0;{let s=this._head,n=t._head,a=0;for(;i-- >0&&a===0;)a=e(s.value,n.value),s=s.next,n=n.next;return a}}concat(...t){let e=this.copy();for(let i of t)e.into(i);return e}equiv(t){if(!(t instanceof o||ve(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),i=this._head;for(let s=this._length;s-- >0;){if(!at(i.value,e.next().value))return!1;i=i.next}return!0}filter(t){let e=this.empty();return this.traverse(i=>(t(i.value)&&e.append(i.value),!0)),e}find(t){return this.traverse(e=>e.value!==t)}findWith(t){return this.traverse(e=>!t(e.value))}first(){return this._head?.value}insertSorted(t,e){e=e||ht;for(let i=this._head,s=this._length;s-- >0;){if(e(t,i.value)<=0)return this.insertBefore(i,t);i=i.next}return this.append(t)}into(t){for(let e of t)this.append(e);return this}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCellUnsafe(t){let e,i;for(t<=this._length>>>1?(e=this._head,i="next"):(e=this.tail,i="prev",t=this._length-t-1);t-- >0&&e;)e=e[i];return e}peek(){return this.tail?.value}$reduce(t,e){let i=this._head;for(let s=this._length;s-- >0&&!we(e);)e=t(e,i.value),i=i.next;return e}reduce(t,e){return this.$reduce(t,e)}release(){let t=this._head;if(!t)return!0;let e;for(let i=this._length;i-- >0;)e=t.next,delete t.value,delete t.prev,delete t.next,t=e;return this._head=void 0,this._length=0,!0}reverse(){let t=this._head,e=this.tail,i=(this._length>>>1)+(this._length&1);for(;t&&e&&i>0;){let s=t.value;t.value=e.value,e.value=s,t=t.next,e=e.prev,i--}return this}setHead(t){let e=this._head;return e?(e.value=t,e):this.prepend(t)}setNth(t,e){let i=this.nthCell(t);return!i&&ae(t),i.value=e,i}setTail(t){let e=this.tail;return e?(e.value=t,e):this.append(t)}swap(t,e){if(t!==e){let i=t.value;t.value=e.value,e.value=i}return this}toArray(t=[]){return this.traverse(e=>(t.push(e.value),!0)),t}toJSON(){return this.toArray()}toString(){let t=[];return this.traverse(e=>(t.push(String(e.value)),!0)),t.join(", ")}traverse(t,e=this._head,i){if(!this._head)return;let s=e;do{if(!t(s))break;s=s.next}while(s!==i);return s}_map(t,e){return this.traverse(i=>(t.append(e(i.value)),!0)),t}};function*Oe(o,t){for(;t;)yield t.value,t=t[o]}var Ht=class o extends qt{_tail;constructor(t){super(),t&&this.into(t)}get tail(){return this._tail}append(t){if(this._tail){let e={value:t,prev:this._tail};return this._tail.next=e,this._tail=e,this._length++,e}else return this.prepend(t)}asHead(t){return t===this._head?this:(this.remove(t),this._head.prev=t,t.next=this._head,t.prev=void 0,this._head=t,this._length++,this)}asTail(t){return t===this._tail?this:(this.remove(t),this._tail.next=t,t.prev=this._tail,t.next=void 0,this._tail=t,this._length++,this)}cons(t){return this.prepend(t),this}copy(){return new o(this)}*cycle(){for(;;)yield*this}drop(){let t=this._head;if(t)return this._head=t.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,t.value}empty(){return new o}insertAfter(t,e){let i={value:e,next:t.next,prev:t};return t.next?t.next.prev=i:this._tail=i,t.next=i,this._length++,i}insertAfterNth(t,e){return t<0&&(t+=this._length),t>=this._length-1?this.append(e):(Ct(t,0,this._length),this.insertAfter(this.nthCellUnsafe(t),e))}insertBefore(t,e){let i={value:e,next:t,prev:t.prev};return t.prev?t.prev.next=i:this._head=i,t.prev=i,this._length++,i}insertBeforeNth(t,e){return t<0&&(t+=this._length),t<=0?this.prepend(e):(Ct(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new o,t)}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCell(t){if(t<0&&(t+=this._length),!(t<0||t>=this._length))return this.nthCellUnsafe(t)}pop(){let t=this._tail;if(t)return this._tail=t.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,t.value}prepend(t){let e={value:t,next:this._head};return this._head?this._head.prev=e:this._tail=e,this._head=e,this._length++,e}push(t){return this.append(t),this}release(){return this._tail=void 0,super.release()}remove(t){return t.prev?t.prev.next=t.next:this._head=t.next,t.next?t.next.prev=t.prev:this._tail=t.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 t=this.peek();return this.pop(),this.prepend(t),this}}seq(t=0,e=this.length){if(t>=e||t<0)return;let i=this.nthCell(t),s=this.nthCell(e-1),n=a=>({first(){return a.value},next(){return a!==s&&a.next?n(a.next):void 0}});return i?n(i):void 0}shuffle(t,e=Pe){if(this._length<2)return this;for(t=t!==void 0?t:Math.ceil(1.5*Math.log2(this._length));t>0;t--){let i=this._head;for(;i;){let s=i.next;e.probability(.5)?this.asHead(i):this.asTail(i),i=s}}return this}slice(t=0,e=this.length){let i=t<0?t+this._length:t,s=e<0?e+this._length:e;(i<0||s<0)&&fe("invalid indices: ${from} / ${to}");let n=new o,a=this.nthCell(i);for(;a&&++i<=s;)n.push(a.value),a=a.next;return n}sort(t=ht){if(!this._length)return this;let e=1;for(;;){let i=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;i;){s++;let n=i,a=0;for(let l=0;l<e&&(a++,n=n.next,!!n);l++);let r=e;for(;a>0||r>0&&n;){let l;a===0?(l=n,n=n.next,r--):!n||r===0||t(i.value,n.value)<=0?(l=i,i=i.next,a--):(l=n,n=n.next,r--),this._tail?this._tail.next=l:this._head=l,l.prev=this._tail,this._tail=l}i=n}if(this._tail.next=void 0,s<=1)return this;e*=2}}splice(t,e=0,i){let s;typeof t=="number"?(t<0&&(t+=this._length),Ct(t,0,this._length),s=this.nthCellUnsafe(t)):s=t;let n=new o;if(e>0)for(;s&&e-- >0;)this.remove(s),n.push(s.value),s=s.next;else s&&(s=s.next);if(i)if(s)for(let a of i)this.insertBefore(s,a);else for(let a of i)this.push(a);return n}};var Gt=class o{map;items;opts;_size;constructor(t,e){let i={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...e};this.map=i.map(),this.items=new Ht,this._size=0,this.opts=i,t&&this.into(t)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let t of this.items)yield[t.k,t]}*keys(){for(let t of this.items)yield t.k}*values(){for(let t of this.items)yield t.v}copy(){let t=this.empty();t.items=this.items.copy();let e=t.items.head;for(;e;)t.map.set(e.value.k,e),e=e.next;return t}empty(){return new o(null,this.opts)}release(){this._size=0,this.map.clear();let t=this.opts.release;if(t){let e;for(;e=this.items.drop();)t(e.k,e.v);return!0}return this.items.release()}has(t){return this.map.has(t)}get(t,e){let i=this.map.get(t);return i?this.resetEntry(i):e}set(t,e){let i=this.opts.ksize(t)+this.opts.vsize(e),s=this.map.get(t),n=Math.max(0,i-(s?s.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(s,t,e,i):this._size-=n,e}into(t){for(let e of t)this.set(e[0],e[1]);return this}async getSet(t,e){let i=this.map.get(t);return i?this.resetEntry(i):this.set(t,await e())}delete(t){let e=this.map.get(t);return e?(this.removeEntry(e),!0):!1}resetEntry(t){return this.items.asTail(t),t.value.v}ensureSize(){let{release:t,maxsize:e,maxlen:i}=this.opts;for(;this._size>e||this.length>=i;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),t?.(s.k,s.v),this._size-=s.s}return!0}removeEntry(t){let e=t.value;this.map.delete(e.k),this.items.remove(t),this.opts.release?.(e.k,e.v),this._size-=e.s}doSetEntry(t,e,i,s){t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=s,this.items.asTail(t)):(this.items.push({k:e,v:i,s}),this.map.set(e,this.items.tail))}};var it=class o extends Gt{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new o(null,this.opts)}has(t){return this.get(t)!==void 0}get(t,e){let i=this.map.get(t);if(i){if(i.value.t>=Date.now())return this.resetEntry(i);this.removeEntry(i)}return e}set(t,e,i=this.opts.ttl){let s=this.opts.ksize(t)+this.opts.vsize(e),n=this.map.get(t),a=Math.max(0,s-(n?n.value.s:0));return this._size+=a,this.ensureSize()?this.doSetEntry(n,t,e,s,i):this._size-=a,e}async getSet(t,e,i=this.opts.ttl){let s=this.get(t);return s!==void 0?s:this.set(t,await e(),i)}prune(){let t=Date.now(),e=this.items.head,i=0;for(;e;)e.value.t<t&&(this.removeEntry(e),i++),e=e.next;return i}ensureSize(){let{maxlen:t,maxsize:e}=this.opts,i=Date.now(),s=this.items.head;for(;s&&(this._size>e||this.length>=t);)s.value.t<i&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(t,e,i,s,n=this.opts.ttl){let a=Date.now()+n;t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=s,t.value.t=a,this.items.asTail(t)):(this.items.push({k:e,v:i,s,t:a,ttl:n}),this.map.set(e,this.items.tail))}resetEntry(t){return this.opts.autoExtend&&(t.value.t=Date.now()+t.value.ttl),super.resetEntry(t)}};var Nt=class{debug;constructor(t){this.debug=t||!1}log(t,e,i){this.debug&&console.log(t,e,i)}scope(t,e,i,s){let n=new Map,a=s!==void 0?new it(null,{ttl:s}):new it;return{get:(...u)=>{let p=i(...u);if(n.has(p)){this.log("[live]",t,p);let y=n.get(p);return Promise.resolve(y)}if(a.has(p))return this.log("[memo]",t,p),a.get(p);this.log("[fetch]",t,p);let g=e(...u).catch(y=>{throw a.delete(p),y});return a.set(p,g),g},set:(u,...p)=>{let g=i(...p);this.log("[set-live]",t,g),n.set(g,u)},clear:()=>{this.log("[clear]",t),n.clear(),a.release()}}}};var{FeeUtils:Ie}=I,gt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new o(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(a=>[a.id,a])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,weightIn:s.weight,weightOut:n.weight}}validateAndBuy(t,e,i){let s=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let a=t.balanceOut/this.maxOutRatio;if(e>a&&n.push("MaxOutRatioExceeded"),s===t.assetOut){let r=this.calculateTradeFee(e,i),l=Ie.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),c=e+r,u=this.calculateInGivenOut(t,c),p=t.balanceIn/this.maxInRatio;return u>p&&n.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:l,errors:n}}else{let r=this.calculateInGivenOut(t,e),l=t.balanceIn/this.maxInRatio;return r>l&&n.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:n}}}validateAndSell(t,e,i){let s=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let a=t.balanceIn/this.maxInRatio;if(e>a&&n.push("MaxInRatioExceeded"),s===t.assetIn){let r=this.calculateOutGivenIn(t,e),l=t.balanceOut/this.maxOutRatio;return r>l&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:n}}else{let r=this.calculateOutGivenIn(t,e),l=this.calculateTradeFee(r,i),c=Ie.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),u=r-l,p=t.balanceOut/this.maxOutRatio;return u>p&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:u,feePct:c,errors:n}}}calculateInGivenOut(t,e){let i=G.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e){let i=G.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){let e=G.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),rt.big.toBigInt(1,rt.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=G.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),rt.big.toBigInt(1,rt.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let i=G.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var Ee=require("polkadot-api"),lt=require("rxjs");var Te=(o,t=new Map)=>e=>{let i;return t.has(e)?t.get(e):(t.set(e,i=o(e)),i)};var v=require("rxjs"),m=require("rxjs/operators");var $t=require("@galacticcouncil/descriptors");var Be=require("@galacticcouncil/common"),Vt=require("rxjs");var j=require("rxjs"),T=require("rxjs/operators");function _e(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>(0,j.defer)(()=>(0,j.from)(o._request("system_health",[]))).pipe((0,T.timeout)({first:e}),(0,T.map)(()=>"online"),(0,T.catchError)(()=>(0,j.of)("offline")));return(0,j.of)({state:"offline",delayMs:0}).pipe((0,T.expand)(n=>(0,j.timer)(n.delayMs).pipe((0,T.switchMap)(i),(0,T.map)(a=>({state:a,delayMs:t})))),(0,T.skip)(1),(0,T.map)(n=>n.state),(0,T.distinctUntilChanged)(),(0,T.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:wi}=Be.log,zt=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue("best")),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",_e(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,Vt.tap)({error:i=>wi.error(t,i)}),(0,Vt.shareReplay)({bufferSize:1,refCount:!0}))}};var $=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi($t.hydration),this.apiNext=this.client.getTypedApi($t.hydrationNext),this.watcher=zt.getInstance(this.client)}};var Oi=require("polkadot-api/ws-provider"),Ii=require("polkadot-api/logs-provider"),Ti=require("@polkadot-api/legacy-provider");var _i=require("polkadot-api/sm-provider");var Ae=require("@galacticcouncil/common"),C=require("rxjs"),d=require("rxjs/operators");var{logger:ot}=Ae.log,bt=class extends ${erc20Ids=null;constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:i}=await e.getValue(t,{at:"best"});return this.getBreakdown(i)}async getTokenBalance(t,e){let s=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(s)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,C.defer)(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return(0,C.combineLatest)([e,i,s]).pipe((0,d.connect)(n=>(0,C.concat)(n.pipe((0,d.take)(1)),n.pipe((0,d.skip)(1),(0,d.debounceTime)(250)))))}).pipe((0,d.map)(e=>e.flat()),(0,d.startWith)([]),(0,d.bufferCount)(2,1),(0,d.map)(([e,i],s)=>s===0?i:this.getDeltas(e,i))).pipe((0,d.tap)({subscribe:()=>ot.debug("balance: subscribe",t),error:e=>ot.error("balance",e)}),(0,d.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,C.defer)(()=>e.watchValue(t,"best")).pipe((0,d.map)(i=>({id:0,balance:this.getBreakdown(i.data)})),(0,d.tap)({error:i=>ot.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return(0,C.defer)(()=>i.watchValue(t,e,"best")).pipe((0,d.map)(s=>({id:e,balance:this.getBreakdown(s)})),(0,d.tap)({error:s=>ot.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,C.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,d.distinctUntilChanged)((i,s)=>!s.deltas),(0,d.map)(({deltas:i})=>{let s=[];return i?.deleted.forEach(n=>{let[a,r]=n.args;s.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(n=>{let[a,r]=n.args;s.push({id:r,balance:this.getBreakdown(n.value)})}),s}),(0,d.tap)({error:i=>ot.error("balance(tokens)",i)}))}watchErc20Balance(t,e){let i=async()=>{if(this.erc20Ids)return this.erc20Ids;let n=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=n.filter(({value:a})=>a.asset_type.type==="Erc20").map(({keyArgs:a})=>{let[r]=a;return r}),this.erc20Ids},s=async n=>(await Promise.all(n.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,l])=>({id:r,balance:l}));return(0,C.defer)(()=>(0,C.from)(e?Promise.resolve(e):i()).pipe((0,d.switchMap)(n=>this.watcher.bestBlock$.pipe((0,d.switchMap)(()=>(0,C.from)(s(n))))),(0,d.startWith)([]),(0,d.bufferCount)(2,1),(0,d.map)(([n,a],r)=>r===0?a.filter(l=>l.balance.total>0n):this.getDeltas(n,a)),(0,d.distinctUntilChanged)((n,a)=>a.length===0),(0,d.tap)({error:n=>ot.error("balance(erc20)",n)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.getBreakdown(i)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,i=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:i,transferable:e}}getDeltas(t,e){let i=(n,a)=>n!==void 0&&a!==void 0&&n.transferable===a.transferable&&n.total===a.total,s=t.reduce((n,a)=>(n.set(a.id,a.balance),n),new Map);return e.filter(n=>!i(n.balance,s.get(n.id)))}};var Fe=require("rxjs"),Wt=class{store$=new Fe.BehaviorSubject([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(t){return this.changeset.size===0?[]:t.filter(e=>this.changeset.has(e.address))}set(t){this.changeset=new Set(t.map(e=>e.address)),this.store$.next(t)}update(t){this.updateQueue=this.updateQueue.then(async()=>{let e=this.store$.value,i=new Map(e.map((r,l)=>[r.address,l])),s=await t(e),n=e.slice(),a=new Set;for(let r of s){let l=i.get(r.address);l===void 0?(i.set(r.address,n.length),n.push(r)):n[l]=r,a.add(r.address)}this.changeset=a,this.store$.next(n)}).catch(console.error)}destroy(){this.store$.complete()}};var ke=require("@galacticcouncil/common");var Bi={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Ut}=ke.log,Yt=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${Bi[this.type]})`,10)}trace(t,...e){Ut.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){Ut.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){Ut.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){Ut.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:Ai}=kt,Fi=3e3,E=class extends ${evm;balance;store=new Wt;log;shared$;resync$=new v.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new it(null,{ttl:6*1e3});memPools=Te(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e,this.balance=new bt(t),this.log=new Yt(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){return(await this.getMemPools()).filter(e=>this.hasValidAssets(e))}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe((0,m.startWith)([]),(0,m.bufferCount)(2,1),(0,m.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,m.filter)(t=>t.length>0),(0,m.throttleTime)(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return(0,v.defer)(()=>{let t=new v.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,m.switchMap)(()=>{let e=new v.Subscription;return(0,v.from)(Ai(this.getMemPools(),6e4,"getMemPools stalled")).pipe((0,m.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,m.map)(s=>s.filter(n=>this.hasValidAssets(n))),(0,m.tap)(s=>this.store.set(s)),(0,m.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),v.EMPTY))).pipe((0,m.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,m.switchMap)(s=>(0,v.merge)((0,v.of)(s),this.store.asObservable().pipe((0,m.skip)(1)))),(0,m.finalize)(()=>{e.unsubscribe()}))}),(0,m.finalize)(()=>t.unsubscribe()))}).pipe((0,m.share)({connector:()=>new v.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:i}=e,s=[this.balance.watchTokensBalance(i)];if(this.hasSystemAsset(e)){let n=this.balance.watchSystemBalance(i);s.push(n)}if(this.hasErc20Asset(e)){let n=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),a=this.balance.watchErc20Balance(i,n);s.push(a)}return(0,v.combineLatest)(s).pipe((0,m.map)(n=>n.flat()),(0,m.pairwise)(),(0,m.map)(([n,a])=>this.balance.getDeltas(n,a)),(0,m.filter)(n=>n.length>0),(0,m.map)(n=>[i,n]))});return(0,v.merge)(...t).pipe((0,m.bufferTime)(250),(0,m.filter)(e=>e.length>0),(0,m.map)(e=>new Map(e)),this.watchGuard("balances")).subscribe(e=>{this.store.update(i=>this.updateBalances(i,e))})}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:i})=>t.type==="XYK"?i>0n&&!!e:!!e)}updateBalances=(t,e)=>{let i=[],s=new Map(t.map(n=>[n.address,n]));for(let[n,a]of e){let r=s.get(n);if(r){let l=r.tokens.map(c=>{let u=a.find(p=>p.id===c.id);return u&&c.id!==r.id?{...c,balance:u.balance.transferable}:c});i.push({...r,tokens:l})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<Fi||(this.resyncAt=e,this.mem++,this.resync$.next())}requestResync(t=!1){this.resyncPending||(this.resyncPending=!0,setTimeout(()=>{this.resyncPending=!1,this.resync(t)},0))}startWatchdog(){let i=this.watcher.connection$.pipe((0,m.pairwise)(),(0,m.filter)(([n,a])=>n==="offline"&&a==="online"),(0,m.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,m.catchError)(n=>(this.log.error("watchdog_recovery_error",n),v.EMPTY)),(0,m.repeat)({delay:1e3})),s=this.watcher.finalizedBlock$.pipe((0,m.pairwise)(),(0,m.tap)(([n,a])=>{let r=Number(n.number),l=Number(a.number),c=l-r;c>=3&&(this.log.debug("watchdog_gap",{from:r,to:l,gap:c}),this.requestResync())}),(0,m.catchError)(n=>(this.log.error("watchdog_gap_error",n),v.EMPTY)),(0,m.repeat)({delay:1e3}));return(0,v.merge)(i,s).subscribe()}watchGuard(t){return e=>e.pipe((0,m.tap)({error:i=>{this.log.error(t,i),this.requestResync(!0)}}),(0,m.finalize)(()=>{this.log.debug(t,"unsub")}),(0,m.catchError)(()=>v.EMPTY))}};var ft=class extends E{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}getPoolWeights(t,e){let{start:i,end:s,initial_weight:n,final_weight:a}=t,r=G.calculateLinearWeights(i?i.toString():"0",s?s.toString():"0",n.toString(),a.toString(),e.toString()),l=BigInt(r),c=this.MAX_FINAL_WEIGHT-BigInt(l);return[l,c]}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Ee.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:"best"}),this.api.query.ParachainSystem.ValidationData.getValue({at:"best"}),this.getPoolLimits()]),s=e?.relay_parent_number||0,n=t.filter(({value:a})=>e&&this.isActivePool(a,s)).map(async({keyArgs:a,value:r})=>{let[l]=a,c=l.toString(),u=await this.getPoolDelta(c,r,s);return{address:c,type:"LBP",fee:r.fee,...u,...i}});return Promise.all(n)}async getPoolDelta(t,e,i){let{assets:s,repay_target:n,fee_collector:a}=e,[r,l]=this.getPoolWeights(e,i),[c,u]=s,[p,g,y,b,A]=await Promise.all([this.isRepayFeeApplied(c,n,a.toString()),this.balance.getBalance(t,c),this.api.query.AssetRegistry.Assets.getValue(c),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u)]);return{repayFeeApply:p,tokens:[{id:c,decimals:y?.decimals,existentialDeposit:y?.existential_deposit,balance:g.transferable,weight:r,type:y?.asset_type.type},{id:u,decimals:A?.decimals,existentialDeposit:A?.existential_deposit,balance:b.transferable,weight:l,type:A?.asset_type.type}]}}isActivePool(t,e){let{start:i,end:s}=t;return i&&s?e>=i&&e<s:!1}async isRepayFeeApplied(t,e,i){if(e===0n)return!1;try{return(await this.balance.getBalance(i,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let i=this.store.pools.find(n=>n.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:i.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue("best").pipe((0,lt.filter)(t=>t!==void 0),(0,lt.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let i=[];for(let s of e){let n=this.poolsData.get(s.address);if(n){let{assets:a,repay_target:r,fee_collector:l}=n,[c]=a,[u,p]=this.getPoolWeights(n,t),[g,y]=s.tokens,b=[{...g,weight:u},{...y,weight:p}],A=await this.isRepayFeeApplied(c,r,l.toString());i.push({...s,tokens:b,repayFeeApply:A})}}return i})})}subscribeUpdates(){let t=new lt.Subscription;return t.add(this.subscribeValidationData()),t}};var ce={};H(ce,{OmniMath:()=>P,OmniPool:()=>yt,OmniPoolClient:()=>Pt});var h=require("@galacticcouncil/math-omnipool"),st=se(require("big.js")),P=class{static calculateSpotPrice(t,e,i,s){return(0,h.calculate_spot_price)(t,e,i,s)}static calculateLrnaSpotPrice(t,e){return(0,h.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,i,s,n,a,r,l,c,u){return(0,h.calculate_in_given_out)(t,e,i,s,n,a,r,l,c,u)}static calculateLrnaInGivenOut(t,e,i,s,n,a){return(0,h.calculate_lrna_in_given_out)(t,e,i,s,n,a)}static calculateOutGivenIn(t,e,i,s,n,a,r,l,c,u){return(0,h.calculate_out_given_in)(t,e,i,s,n,a,r,l,c,u)}static calculateOutGivenLrnaIn(t,e,i,s,n,a){return(0,h.calculate_out_given_lrna_in)(t,e,i,s,n,a)}static calculateShares(t,e,i,s){return(0,h.calculate_shares)(t,e,i,s)}static calculateLiquidityOut(t,e,i,s,n,a,r,l){return(0,h.calculate_liquidity_out)(t,e,i,s,n,a,r,l)}static calculateLiquidityLRNAOut(t,e,i,s,n,a,r,l){return(0,h.calculate_liquidity_lrna_out)(t,e,i,s,n,a,r,l)}static calculateCapDifference(t,e,i,s){let n=(0,st.default)(e),a=(0,st.default)(t),r=(0,st.default)(s),l=(0,st.default)(i),c=(0,st.default)(10).pow(18),u=l.div(c);if(n.div(r).lt(u)){let g=u.times(r).minus(n).times(a),y=n.times((0,st.default)(1).minus(u));return g.div(y).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,s){return(0,h.calculate_liquidity_hub_in)(t,e,i,s)}static isSellAllowed(t){return(0,h.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,h.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,h.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,h.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,i,s,n,a,r,l,c,u,p){return(0,h.recalculate_asset_fee)(t,e,i,s,n,a,r,l,c,u,p)}static recalculateProtocolFee(t,e,i,s,n,a,r,l,c,u,p){return(0,h.recalculate_protocol_fee)(t,e,i,s,n,a,r,l,c,u,p)}static verifyAssetCap(t,e,i,s){return(0,h.verify_asset_cap)(t,e,i,s)}};var Re=require("@galacticcouncil/common");var{FeeUtils:W}=I,yt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new o(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let i=new Map(this.tokens.map(a=>[a.id,a])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:s.hubReserves,hubReservesOut:n.hubReserves,sharesIn:s.shares,sharesOut:n.shares,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:s.balance,balanceOut:n.balance,tradeableIn:s.tradeable,tradeableOut:n.tradeable,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,i),a=s===0n?0:et.calculateBuyFee(s,n),r=[],l=P.isSellAllowed(t.tradeableIn),c=P.isBuyAllowed(t.tradeableOut);(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&r.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return n>p&&r.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),a=et.calculateSellFee(s,n),r=[],l=P.isSellAllowed(t.tradeableIn),c=P.isBuyAllowed(t.tradeableOut);(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&r.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return n>p&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:n,feePct:a,errors:r}}calculateInGivenOut(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,i);let s=P.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?W.toRaw(i.assetFee).toString():"0",i?W.toRaw(i.protocolFee).toString():"0",i?W.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateLrnaInGivenOut(t,e,i){let s=P.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?W.toRaw(i.assetFee).toString():"0",i?W.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,i);let s=P.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?W.toRaw(i.assetFee).toString():"0",i?W.toRaw(i.protocolFee).toString():"0",i?W.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateOutGivenLrnaIn(t,e,i){let s=P.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?W.toRaw(i.assetFee).toString():"0",i?W.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=P.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceLrnaInGivenOut(t){let e=P.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=P.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}spotPriceOutGivenLrnaIn(t){let e=P.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,i){let s=e-i;if(s===0)return t;let n=Re.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var Q=require("polkadot-api"),Le=require("@polkadot-api/utils"),f=require("rxjs"),De=require("@galacticcouncil/common");var{FeeUtils:S}=I,Ce=Q.Binary.fromText("omnipool"),Me=(0,Q.Enum)("Short"),Pt=class extends E{queryBus=new Nt;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:"best"}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:"best"}),t=>String(t),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:"best"}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(Ce,t,Me,{at:"best"}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,Le.toHex)(e);return(0,Q.AccountId)(De.HYDRATION_SS58_PREFIX).dec(i)}getOraclePair(t){return t===0?[0,1]:[1,t]}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Q.CompatibilityLevel.BackwardsCompatible,e)}async isSlipFeeSupported(){return this.apiNext.query.Omnipool.SlipFee.isCompatible(Q.CompatibilityLevel.Partial)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,s,n,a,r]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:"best"}),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.balance.getBalance(e,t),this.getPoolLimits()]),l=i.map(async({keyArgs:u,value:p})=>{let[g]=u,{hub_reserve:y,shares:b,tradable:A,cap:Y,protocol_shares:X}=p,[R,q]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(g),this.balance.getBalance(e,g)]);return{id:g,decimals:R?.decimals,existentialDeposit:R?.existential_deposit,balance:q.transferable,cap:Y,hubReserves:y,protocolShares:X,shares:b,tradeable:A,type:R?.asset_type.type}}),c=await Promise.all(l);return c.push({id:t,decimals:n?.decimals,existentialDeposit:n?.existential_deposit,balance:a.transferable,tradeable:s,type:n?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:c,...r}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,s=0;await this.isSlipFeeSupported()&&(s=await this.maxSlipFee.get()??0);let a=await this.dynamicFeesConfig.get(e);if(a?.type==="Fixed"){let{asset_fee:L,protocol_fee:K}=a.value;return{assetFee:S.fromPermill(L),protocolFee:S.fromPermill(K),maxSlipFee:S.fromPermill(s)}}let r=this.getOraclePair(e),l=this.getOraclePair(i),[c,u,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(r),this.emaOracles.get(l)]),[g,y,b]=await this.getAssetFee(t,this.block,c,u,a?.value.asset_fee_params),[A,Y,X]=i===1?[0,0,0]:await this.getProtocolFee(t,this.block,c,p,a?.value.protocol_fee_params),R=g+A,q=b+X;return{assetFee:S.fromPermill(y),protocolFee:S.fromPermill(Y),maxSlipFee:S.fromPermill(s),min:S.fromPermill(R),max:S.fromPermill(q)}}async getAssetFee(t,e,i,s,n){let{assetOut:a,balanceOut:r}=t,{min_fee:l,max_fee:c,decay:u,amplification:p}=n||await this.api.constants.DynamicFees.AssetFeeParameters();if(!i||!s)return[l,l,c];let g=S.fromPermill(l),y=S.fromPermill(c),[b]=s,{asset_fee:A,timestamp:Y}=i,X=Math.max(1,e-Y),R=b.volume.b_in.toString(),q=b.volume.b_out.toString(),L=b.liquidity.b.toString();a===0&&(R=b.volume.a_in.toString(),q=b.volume.a_out.toString(),L=b.liquidity.a.toString());let K=S.fromPermill(A),mt=P.recalculateAssetFee(R,q,L,"9",r.toString(),S.toRaw(K).toString(),X.toString(),S.toRaw(g).toString(),S.toRaw(y).toString(),u.toString(),p.toString());return[l,Number(mt)*1e6,c]}async getProtocolFee(t,e,i,s,n){let{assetIn:a,balanceIn:r}=t,{min_fee:l,max_fee:c,decay:u,amplification:p}=n||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!i||!s)return[l,l,c];let g=S.fromPermill(l),y=S.fromPermill(c),[b]=s,{protocol_fee:A,timestamp:Y}=i,X=Math.max(1,e-Y),R=b.volume.b_in.toString(),q=b.volume.b_out.toString(),L=b.liquidity.b.toString();a===0&&(R=b.volume.a_in.toString(),q=b.volume.a_out.toString(),L=b.liquidity.a.toString());let K=S.fromPermill(A),mt=P.recalculateProtocolFee(R,q,L,"9",r.toString(),S.toRaw(K).toString(),X.toString(),S.toRaw(g).toString(),S.toRaw(y).toString(),u.toString(),p.toString());return[l,Number(mt)*1e6,c]}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(s=>s.id).map(s=>this.getOraclePair(s)).map(s=>this.api.query.EmaOracle.Oracles.watchValue(Ce,s,Me,"best").pipe((0,f.filter)(n=>n!==void 0),(0,f.map)((n,a)=>({value:n,index:a})),(0,f.tap)(({index:n})=>{n>0&&this.log.trace("emaOracle.Oracles",s.join(":"))}),(0,f.map)(({value:n})=>({pair:s,value:n}))));return(0,f.merge)(...i).pipe((0,f.finalize)(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(s=>{let{pair:n,value:a}=s;this.emaOracles.set(a,n)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,f.distinctUntilChanged)((t,e)=>!e.deltas),(0,f.map)((t,e)=>({value:t,index:e})),(0,f.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),(0,f.finalize)(()=>this.dynamicFees.clear()),this.watchGuard("dynamicFees.AssetFee")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFees.set(e.value,i)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe((0,f.distinctUntilChanged)((t,e)=>!e.deltas),(0,f.map)((t,e)=>({value:t,index:e})),(0,f.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),(0,f.finalize)(()=>this.dynamicFeesConfig.clear()),this.watchGuard("dynamicFees.AssetFeeConfiguration")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFeesConfig.set(e.value,i)})})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,f.distinctUntilChanged)((t,e)=>!e.deltas),(0,f.map)((t,e)=>({value:t,index:e})),(0,f.tap)(({value:t,index:e})=>{e>0&&this.log.trace("omnipool.Assets",t.deltas?.upserted)}),this.watchGuard("omnipool.Assets")).subscribe(({value:{deltas:t}})=>{this.store.update(([e])=>{let i=t?.upserted.reduce((n,a)=>{let[r]=a.args;return n.set(r,a.value),n},new Map),s=e.tokens.map(n=>{let a=i?.get(n.id);return a?this.updateTokenState(n,a):n});return[{...e,tokens:s}]})})}subscribeUpdates(){let t=new f.Subscription;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:i,shares:s,tradable:n,cap:a,protocol_shares:r}=e;return{...t,cap:a,hubReserves:i,protocolShares:r,shares:s,tradeable:n}}};var ue={};H(ue,{StableMath:()=>_,StableSwap:()=>nt,StableSwapClient:()=>St});var x=require("@galacticcouncil/math-stableswap"),_=class{static getPoolAddress(t){return(0,x.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let i=0;i<t;i++)e.push(["1","1"]);return e}static calculateAmplification(t,e,i,s,n){return(0,x.calculate_amplification)(t,e,i,s,n)}static calculateInGivenOut(t,e,i,s,n,a,r){return(0,x.calculate_in_given_out)(t,e,i,s,n,a,r)}static calculateAddOneAsset(t,e,i,s,n,a,r){return(0,x.calculate_add_one_asset)(t,e,i,s,n,a,r)}static calculateSharesForAmount(t,e,i,s,n,a,r){return(0,x.calculate_shares_for_amount)(t,e,i,s,n,a,r)}static calculateOutGivenIn(t,e,i,s,n,a,r){return(0,x.calculate_out_given_in)(t,e,i,s,n,a,r)}static calculateLiquidityOutOneAsset(t,e,i,s,n,a,r){return(0,x.calculate_liquidity_out_one_asset)(t,e,i,s,n,a,r)}static calculateShares(t,e,i,s,n,a){return(0,x.calculate_shares)(t,e,i,s,n,a)}static calculateSpotPriceWithFee(t,e,i,s,n,a,r,l){return(0,x.calculate_spot_price_with_fee)(t,e,i,s,n,a,r,l)}static recalculatePegs(t,e,i,s,n,a){let r=(0,x.recalculate_peg)(t,e,i,s,n,a);return JSON.parse(r)}};var vt=require("@galacticcouncil/common");var{FeeUtils:ct}=I,nt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new o(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(a=>[a.id,a])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:n.tradeable,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,i),a=s===0n?0:et.calculateBuyFee(s,n),r=[],l=P.isSellAllowed(t.tradeableIn),c=P.isBuyAllowed(t.tradeableOut);return(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),a=et.calculateSellFee(s,n),r=[],l=P.isSellAllowed(t.tradeableIn),c=P.isBuyAllowed(t.tradeableOut);return(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:n,feePct:a,errors:r}}calculateIn(t,e,i){let s=_.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateAddOneAsset(t,e,i){let s=_.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateSharesForAmount(t,e,i){let s=_.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateInGivenOut(t,e,i){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,i):t.assetIn==this.id?this.calculateSharesForAmount(t,e,i):this.calculateIn(t,e,i)}spotPriceInGivenOut(t){let e=_.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetOut===this.id,t.assetIn===this.id,t.decimalsOut,t.decimalsIn)}calculateOut(t,e,i){let s=_.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateWithdrawOneAsset(t,e,i){let s=_.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateShares(t,e,i){let s=_.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e,i){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,i):t.assetOut==this.id?this.calculateShares(t,e,i):this.calculateOut(t,e,i)}spotPriceOutGivenIn(t){let e=_.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetIn===this.id,t.assetOut===this.id,t.decimalsIn,t.decimalsOut)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:i,decimals:s})=>({asset_id:e,amount:i,decimals:s}));return JSON.stringify(t,dt.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],dt.jsonFormatter)}normalizeSpot(t,e,i,s,n){return e?t*vt.big.pow10(vt.RUNTIME_DECIMALS-n):i?t/vt.big.pow10(n-s):t}};var Kt=require("polkadot-api"),qe=require("@polkadot-api/utils"),He=require("@noble/hashes/blake2b"),M=require("rxjs"),jt=require("@galacticcouncil/common");var{FeeUtils:ki}=I,St=class extends E{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=_.getPoolAddress(t),i=(0,He.blake2b)(e,{dkLen:32}),s=(0,qe.toHex)(i);return(0,Kt.AccountId)(jt.HYDRATION_SS58_PREFIX).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:i,final_amplification:s,initial_block:n,final_block:a}=t,r=_.calculateAmplification(i.toString(),s.toString(),n.toString(),a.toString(),e.toString()),l=Number(r)<s;return{amplification:BigInt(r),isRampPeriod:l}}async getPoolTokens(t,e){let i=this.getPoolAddress(t),s=e.assets.map(async n=>{let[a,r,l]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,n),this.api.query.AssetRegistry.Assets.getValue(n),this.balance.getBalance(i,n)]);return{id:n,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:l.transferable,tradeable:a,type:r?.asset_type.type}});return Promise.all(s)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(Kt.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:"best"}),this.api.query.System.Number.getValue({at:"best"}),this.getPoolLimits()]),s=t.map(async({keyArgs:n,value:a})=>{let[r]=n,l=this.getPoolAddress(r),[c,u,p]=await Promise.all([this.getPoolTokens(r,a),this.api.query.Stableswap.PoolPegs.getValue(r,{at:"best"}),this.api.query.Tokens.TotalIssuance.getValue(r,{at:"best"})]),g=this.getPoolAmplification(a,e),y=u?this.getRecentPegs(u):this.getDefaultPegs(a);return c.push({id:r,tradeable:15,balance:p,decimals:jt.RUNTIME_DECIMALS}),this.poolsData.set(r,a),{address:l,id:r,type:"Stableswap",fee:ki.fromPermill(a.fee),tokens:c,totalIssuance:p,pegs:y,...i,...g}});return Promise.all(s)}async getPoolFees(t,e){return{fee:this.store.pools.find(s=>s.address===e).fee}}getDefaultPegs(t){return _.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([i,s])=>s.map(n=>n.toString()))}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,"best").pipe((0,M.map)((s,n)=>({value:s,index:n})),(0,M.tap)(({index:s,value:n})=>{s>0&&this.log.trace("tokens.TotalIssuance",i,n)}),(0,M.map)(({value:s})=>({id:i,value:s}))));return(0,M.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:s,value:n}=i;this.store.update(a=>{let r=[];return a.filter(l=>l.id===s).forEach(l=>{let c=l.tokens.map(u=>u.id===s?{...u,balance:n}:u);r.push({...l,tokens:c,totalIssuance:n})}),r})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,M.distinctUntilChanged)((t,e)=>!e.deltas),(0,M.map)((t,e)=>({value:t,index:e})),(0,M.tap)(({value:t,index:e})=>{e>0&&this.log.trace("stableswap.PoolPegs",t.deltas?.upserted)}),this.watchGuard("stableswap.PoolPegs")).subscribe({error:t=>this.log.error("stableswap.PoolPegs",t),next:({value:{deltas:t}})=>{this.store.update(e=>{let i=[],s=new Map(e.map(n=>[n.id,n]));return t?.upserted.forEach(({args:n,value:a})=>{let[r]=n,l=s.get(r);if(l){let c=this.getRecentPegs(a);i.push({...l,pegs:c})}}),i})}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(e=>{let i=[];return e.filter(s=>s.isRampPeriod).forEach(s=>{let n=this.poolsData.get(s.id);if(n){let a=this.getPoolAmplification(n,t);i.push({...s,...a})}}),i})})}subscribeUpdates(){let t=new M.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var pe={};H(pe,{XykMath:()=>Z,XykPool:()=>xt,XykPoolClient:()=>wt});var w=require("@galacticcouncil/math-xyk"),Z=class{static getSpotPrice(t,e,i){return(0,w.get_spot_price)(t,e,i)}static calculateInGivenOut(t,e,i){return(0,w.calculate_in_given_out)(t,e,i)}static calculateOutGivenIn(t,e,i){return(0,w.calculate_out_given_in)(t,e,i)}static calculatePoolTradeFee(t,e,i){return(0,w.calculate_pool_trade_fee)(t,e,i)}static calculateLiquidityIn(t,e,i){return(0,w.calculate_liquidity_in)(t,e,i)}static calculateSpotPrice(t,e){return(0,w.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,i,s){return(0,w.calculate_spot_price_with_fee)(t,e,i,s)}static calculateShares(t,e,i){return(0,w.calculate_shares)(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,s){return(0,w.calculate_liquidity_out_asset_a)(t,e,i,s)}static calculateLiquidityOutAssetB(t,e,i,s){return(0,w.calculate_liquidity_out_asset_b)(t,e,i,s)}};var Ne=require("@galacticcouncil/common");var{FeeUtils:Ge}=I,xt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new o(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(a=>[a.id,a])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:s.balance,balanceOut:n.balance,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=this.calculateTradeFee(s,i),a=Ge.toPct(i.exchangeFee),r=s+n,l=[];(e<this.minTradingLimit||s<t.assetInEd)&&l.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&l.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return r>u&&l.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:a,errors:l}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateTradeFee(s,i),a=Ge.toPct(i.exchangeFee),r=s-n,l=[];(e<this.minTradingLimit||s<t.assetOutEd)&&l.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&l.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return r>u&&l.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:a,errors:l}}calculateInGivenOut(t,e){let i=Z.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e){let i=Z.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){let e=Z.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=Z.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=Z.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(i)}normalizeSpot(t,e,i){let s=e-i;if(s===0)return t;let n=Ne.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var ze=require("polkadot-api"),Ve=require("rxjs");var wt=class extends E{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(ze.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries(),this.getPoolLimits()]),i=t.map(async({keyArgs:s,value:n})=>{let[a]=s,[r,l]=n,[c,u,p,g]=await Promise.all([this.balance.getBalance(a,r),this.api.query.AssetRegistry.Assets.getValue(r),this.balance.getBalance(a,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:a,type:"XYK",tokens:[{id:r,decimals:u?.decimals||this.decimals.get(r),existentialDeposit:u?.existential_deposit,balance:c.transferable,type:u?.asset_type.type},{id:l,decimals:g?.decimals||this.decimals.get(l),existentialDeposit:g?.existential_deposit,balance:p.transferable,type:g?.asset_type.type}],...e}});return Promise.all(i)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return Ve.Subscription.EMPTY}};var me={};H(me,{AavePool:()=>Ot,AavePoolClient:()=>It});var ut=require("@galacticcouncil/common");var Ot=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new o(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(a=>[a.id,a])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=[];return e>t.balanceOut&&n.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:n}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=[];return s>t.balanceOut&&n.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:n}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return ut.big.toBigInt(1,ut.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return ut.big.toBigInt(1,ut.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var We=require("polkadot-api"),Ue=require("@polkadot-api/utils"),U=require("rxjs"),Ye=require("viem"),Jt=require("@galacticcouncil/common");var $e=[{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{ERC20:Ei}=Jt.erc20,Ri=["Supply","Withdraw","Repay","Borrow"],It=class extends E{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,s=new TextEncoder().encode(i.padEnd(32,"\0")),n=(0,Ue.toHex)(s);return(0,We.AccountId)(Jt.HYDRATION_SS58_PREFIX).dec(n)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:"best"})).map(async({reserve:i,atoken:s,liqudity_in:n,liqudity_out:a})=>{let[r,l,c,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i),this.api.query.AssetRegistry.AssetLocations.getValue(i),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(i,s),type:"Aave",tokens:[{id:i,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:n,location:l,type:r?.asset_type.type},{id:s,decimals:c?.decimals,existentialDeposit:c?.existential_deposit,balance:a,location:u,type:c?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:s,liqudity_out:n}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:"best"});return t.tokens.map(a=>{let r=a.id===e.id?s:n;return{...a,balance:r}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key.asHex()}throw new Error("Invalid aave reserve multilocation")}return Ei.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:i}=t;return{assetIn:e,assetOut:i,key:`${e}:${i}`}}parseEvmLog(t){let{topics:e,data:i}=t.log,s=e.map(a=>a.asHex()),n=i.asHex();try{let{eventName:a,args:r}=(0,Ye.decodeEventLog)({abi:$e,topics:s,data:n}),l=r.reserve.toLowerCase();return{eventName:a,reserve:l,key:`${a}:${l}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(i=>i.tokens).map(([i,s])=>s).map(i=>i.id);return this.api.event.Router.Executed.watch().pipe((0,U.map)(({payload:i})=>this.parseRouterLog(i)),(0,U.filter)(({assetIn:i,assetOut:s})=>e.includes(i)||e.includes(s)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:s,key:n})=>{this.log.trace("router.Executed",n),this.store.update(async a=>{let r=[];for(let l of a){let[c,u]=l.tokens;if(u.id===i||u.id===s){let g=await this.getPoolDelta(l);r.push({...l,tokens:g})}}return r})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,U.map)(({payload:t})=>this.parseEvmLog(t)),(0,U.filter)(t=>t!==void 0),(0,U.filter)(({eventName:t})=>Ri.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async i=>{let s=[];for(let n of i){let[a]=n.tokens;if(this.getReserveH160Id(a).toLowerCase()===t){let l=await this.getPoolDelta(n);s.push({...n,tokens:l})}}return s})})}subscribeBalances(){return U.Subscription.EMPTY}subscribeUpdates(){let t=new U.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var he={};H(he,{HsmMath:()=>D,HsmPool:()=>Tt,HsmPoolClient:()=>At});var B=require("@galacticcouncil/math-hsm"),D=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,B.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,B.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,B.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,B.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,B.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,B.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,B.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,B.calculate_max_price)(t,e)}};var F=require("@galacticcouncil/common");var{FeeUtils:pt}=I,Tt=class o extends nt{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new o(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,i){let s=this.parsePair(t.assetOut,t.assetIn),n=super.calculateInGivenOut(s,e,{fee:this.fee}),a=this.calculateBuybackLimit(t);e>a&&i.push("MaxBuyBackExceeded");let r=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,n)>r&&i.push("MaxBuyPriceExceeded"),n>this.collateralBalance&&i.push("InsufficientCollateral"),i}validateTradeHollarOut(t,e,i){return this.collateralBalance+t>this.maxInHolding&&i.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&i.push("FacilitatorCapacityExceeded"),i}validateTradeConstraints(t,e,i){let s=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,s):this.validateTradeHollarOut(e,i,s)}validateAndBuy(t,e){let i=this.calculateInGivenOut(t,e),s=this.validateTradeConstraints(t,i,e);return{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e){let i=this.calculateOutGivenIn(t,e),s=this.validateTradeConstraints(t,e,i);return{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(t,e){let i=super.calculateInGivenOut(t,e,{fee:this.fee}),s=D.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),pt.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=D.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),pt.toRaw(this.purchaseFee).toString());return BigInt(i)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let i=super.calculateOutGivenIn(t,e,{fee:this.fee}),s=D.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),pt.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=D.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),pt.toRaw(this.purchaseFee).toString());return BigInt(i)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),i=D.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=D.calculateBuybackLimit(e.toString(),pt.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let s=D.calculateBuybackPriceWithFee(i.toString(),e.toString(),pt.toRaw(this.buyBackFee).toString()),[n,a]=JSON.parse(s),r=F.big.pow10(t.decimalsIn+F.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(n)*r/BigInt(a)}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=D.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[s,n]=JSON.parse(i),a=F.big.pow10(F.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(s)*a/BigInt(n)}spotPriceInGivenOut(t){let e=F.big.toBigInt(1,t.decimalsOut),s=this.calculateInGivenOut(t,e)*F.big.pow10(F.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(s,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=F.big.toBigInt(1,t.decimalsIn),s=this.calculateOutGivenIn(t,e)*F.big.pow10(F.RUNTIME_DECIMALS-t.decimalsIn);return this.normalizeSpotPrice(s,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(s=>s.id!==this.hollarId),e=this.pegs[t],i=this.tokens[t].decimals;return this.isDefaultPeg(e)?[F.big.toBigInt(1,18).toString(),F.big.toBigInt(1,i).toString()]:e}isDefaultPeg(t){let[e,i]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&i==="1"}normalizeSpotPrice(t,e,i){let s=e-i;if(s===0)return t;let n=F.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var Qt=require("polkadot-api"),Ke=require("@polkadot-api/utils"),k=require("rxjs"),je=require("viem"),Zt=require("@galacticcouncil/common");var _t=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var Bt=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,s]=await this.client.readContract({abi:_t,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-s}};var{FeeUtils:de}=I,{H160:Xe}=Zt.h160,Ci=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],At=class extends E{ghoClient;stableClient;constructor(t,e,i){super(t,e),this.stableClient=i,this.ghoClient=new Bt(e)}getPoolType(){return"HSM"}getPoolId(t){return this.getPoolAddress("hsm:"+t)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(t){if(t){let e=t.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key.asHex()}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),i=new TextEncoder().encode(e),s=(0,Ke.toHex)(i);return(0,Qt.AccountId)(Zt.HYDRATION_SS58_PREFIX).dec(s)}async isSupported(){let t=this.api.query.HSM.Collaterals,e=await this.api.compatibilityToken;return t.isCompatible(Qt.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,s]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t),this.api.query.HSM.Collaterals.getEntries({at:"best"}),this.stableClient.getPools()]);if(i.length===0)return[];let n=this.getFacilitatorAddress(),a=Xe.fromAny(n),r=this.getHollarAddress(e),l=await this.ghoClient.getFacilitatorCapacity(r,a),c=i.map(async({keyArgs:p,value:g})=>{let[y]=p,{pool_id:b,max_buy_price_coefficient:A,max_in_holding:Y,purchase_fee:X,buy_back_fee:R,buyback_rate:q}=g,L=s.find(K=>K.id===b);if(L){let K=this.getPoolId(b),mt=await this.balance.getBalance(n,y);return{...L,address:K,type:"HSM",tokens:L.tokens.filter(Qe=>Qe.id!==b),hsmAddress:n,hsmMintCapacity:l,hollarId:t,hollarH160:r,collateralId:y,collateralBalance:mt.transferable,maxBuyPriceCoefficient:A,maxInHolding:Y,purchaseFee:de.fromPermill(X),buyBackFee:de.fromPermill(R),buyBackRate:de.fromPerbill(q)}}});return(await Promise.all(c)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:i}=t.log,s=e.map(a=>a.asHex()),n=i.asHex();try{let{eventName:a,args:r}=(0,je.decodeEventLog)({abi:_t,topics:s,data:n}),l=r.facilitatorAddress.toLowerCase();return{eventName:a,facilitator:l,key:`${a}:${l}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,k.map)(({payload:t})=>this.parseEvmLog(t)),(0,k.filter)(t=>t!==void 0),(0,k.filter)(({eventName:t})=>Ci.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async i=>{let s=[],[{hsmAddress:n,hollarH160:a}]=i,r=Xe.fromAny(n);if(r.toLowerCase()===e){let c=await this.ghoClient.getFacilitatorCapacity(a,r);for(let u of i)s.push({...u,hsmMintCapacity:c})}return s})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(n=>{let{tokens:a,collateralId:r}=n;a.find(c=>c.id===r).type==="Erc20"?e.push(r):t.push(r)});let[{hsmAddress:i}]=this.store.pools,s=[];if(t.length>0){let n=this.balance.watchTokensBalance(i);s.push(n)}if(e.length>0){let n=this.balance.watchErc20Balance(i,e);s.push(n)}return s.length>0?(0,k.combineLatest)(s).pipe((0,k.map)(n=>n.flat()),(0,k.pairwise)(),(0,k.map)(([n,a])=>this.balance.getDeltas(n,a)),this.watchGuard("balances")).subscribe(n=>{this.store.update(a=>{let r=[],l=new Map(a.map(c=>[c.collateralId,c]));return n.forEach(({id:c,balance:u})=>{let p=l.get(c);p&&(this.log.trace("balances",{id:c,balance:u}),r.push({...p,collateralBalance:u.transferable}))}),r})}):k.Subscription.EMPTY}subscribeStableswapUpdates(){return this.stableClient.getSubscriber().pipe(this.watchGuard("stableswap.updates")).subscribe(t=>{let e=new Map(t.map(i=>[i.id,i]));this.store.update(i=>{let s=[];for(let n of i){let a=e.get(n.id);a&&s.push({...n,fee:a.fee,tokens:a.tokens.filter(r=>r.id!==n.id),totalIssuance:a.totalIssuance,pegs:a.pegs,amplification:a.amplification,isRampPeriod:a.isRampPeriod})}return s})})}subscribeBalances(){return k.Subscription.EMPTY}subscribeUpdates(){let t=new k.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var te=class{static get(t){switch(t.type){case"Aave":return Ot.fromPool(t);case"XYK":return xt.fromPool(t);case"Omnipool":return yt.fromPool(t);case"LBP":return gt.fromPool(t);case"Stableswap":return nt.fromPool(t);case"HSM":return Tt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var Je=require("@galacticcouncil/common"),N=require("rxjs");var ee=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}};var{logger:Mi}=Je.log,ie=class extends ${evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=N.Subscription.EMPTY;omniSub=N.Subscription.EMPTY;stableSub=N.Subscription.EMPTY;hsmSub=N.Subscription.EMPTY;xykSub=N.Subscription.EMPTY;lbpSub=N.Subscription.EMPTY;isReady=!1;isDestroyed=new N.Subject;constructor(t,e){super(t),this.evm=e,this.aave=new It(t,e),this.omnipool=new Pt(t,e),this.stableswap=new St(t,e),this.hsm=new At(t,e,this.stableswap),this.xyk=new wt(t,e),this.lbp=new ft(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe((0,N.takeUntil)(this.isDestroyed)).subscribe(e=>{e.forEach(i=>{this.pools.set(i.address,i)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.active.has("Stableswap")||(Mi.info("[PoolContextProvider] auto-activating stableswap"),this.withStableswap()),this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let i=this.clients.find(s=>s.getPoolType()===e.type);if(i)return i.getPoolFees(t,e.address);throw new ee(e.type)}};0&&(module.exports={PoolContextProvider,PoolError,PoolFactory,PoolType,aave,hsm,lbp,omni,stable,xyk});
|
|
1
|
+
"use strict";var Ze=Object.create;var Ft=Object.defineProperty;var ti=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ii=Object.getPrototypeOf,si=Object.prototype.hasOwnProperty;var H=(o,t)=>{for(var e in t)Ft(o,e,{get:t[e],enumerable:!0})},ge=(o,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ei(t))!si.call(o,s)&&s!==e&&Ft(o,s,{get:()=>t[s],enumerable:!(i=ti(t,s))||i.enumerable});return o};var se=(o,t,e)=>(e=o!=null?Ze(ii(o)):{},ge(t||!o||!o.__esModule?Ft(e,"default",{value:o,enumerable:!0}):e,o)),ni=o=>ge(Ft({},"__esModule",{value:!0}),o);var Li={};H(Li,{PoolContextProvider:()=>ie,PoolError:()=>tt,PoolFactory:()=>te,PoolType:()=>O,aave:()=>me,hsm:()=>he,lbp:()=>oe,omni:()=>ce,stable:()=>ue,xyk:()=>pe});module.exports=ni(Li);var oe={};H(oe,{LbpMath:()=>G,LbpPool:()=>gt,LbpPoolClient:()=>ft});var z=require("@galacticcouncil/math-lbp"),G=class{static getSpotPrice(t,e,i,s,n){return(0,z.get_spot_price)(t,e,i,s,n)}static calculateInGivenOut(t,e,i,s,n){return(0,z.calculate_in_given_out)(t,e,i,s,n)}static calculateOutGivenIn(t,e,i,s,n){return(0,z.calculate_out_given_in)(t,e,i,s,n)}static calculateLinearWeights(t,e,i,s,n){return(0,z.calculate_linear_weights)(t,e,i,s,n)}static calculatePoolTradeFee(t,e,i){return(0,z.calculate_pool_trade_fee)(t,e,i)}};var at=require("@galacticcouncil/common");var O=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r.HSM="HSM",r))(O||{}),tt=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(tt||{});var kt={};H(kt,{withTimeout:()=>ri});function ri(o,t,e="timeout"){return new Promise((i,s)=>{let n=setTimeout(()=>s(new Error(e)),t);o.then(r=>{clearTimeout(n),i(r)},r=>{clearTimeout(n),s(r)})})}var ai=require("@galacticcouncil/common");var I={};H(I,{FeeUtils:()=>ne,shiftNeg:()=>ci});var be=se(require("big.js"));var ne=class o{static toPct(t){let[e,i]=t;return o.safeDivide(e*100,i)}static toRaw(t){let[e,i]=t;return o.safeDivide(e,i)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,i=12){let s=10**i;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function ci(o,t){let e=(0,be.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var dt={};H(dt,{findNestedKey:()=>ui,findNestedObj:()=>pi,jsonFormatter:()=>mi});var ui=(o,t)=>{let e=[];return JSON.stringify(o,(i,s)=>(s&&s[t]&&e.push(s),s)),e[0]},pi=(o,t,e)=>{let i;return JSON.stringify(o,(s,n)=>(n&&n[t]===e&&(i=n),n)),i},mi=(o,t)=>typeof t=="bigint"?t.toString():t;var et={};H(et,{calculateBuyFee:()=>bi,calculateDiffToAvg:()=>di,calculateDiffToRef:()=>hi,calculateSellFee:()=>gi});var V=se(require("big.js"));function di(o,t){let e=(0,V.default)(o.toString()),i=(0,V.default)(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function hi(o,t){if(t===0n)return 0;let e=(0,V.default)(o.toString()),i=(0,V.default)(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function gi(o,t){if(o===0n)return 0;let e=(0,V.default)(o.toString()),i=(0,V.default)(t.toString());return(0,V.default)(1).minus(i.div(e)).mul(100).round(2).toNumber()}function bi(o,t){if(o===0n)return 0;let e=(0,V.default)(o.toString());return(0,V.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var ht=(o,t)=>o===t?0:o==null?t==null?0:-1:t==null?o==null?0:1:typeof o.compare=="function"?o.compare(t):typeof t.compare=="function"?-t.compare(o):o<t?-1:o>t?1:0;var Rt=(o,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(o(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var fi=Rt(()=>"illegal argument(s)"),fe=o=>{throw new fi(o)};var yi=Rt(()=>"index out of bounds"),re=o=>{throw new yi(o)},Ct=(o,t,e)=>(o<t||o>=e)&&re(o);var ye=23283064365386963e-26,Mt=class{float(t=1){return this.int()*ye*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*ye-.5)*2*t}normMinMax(t,e){let i=this.minmax(t,e);return this.float()<.5?i:-i}minmax(t,e){return this.float()*(e-t)+t}minmaxInt(t,e){t|=0;let i=(e|0)-t;return i?t+this.int()%i:t}minmaxUint(t,e){t>>>=0;let i=(e>>>0)-t;return i?t+this.int()%i:t}};var Lt=class extends Mt{constructor(t){super(),this.rnd=t}float(t=1){return this.rnd()*t}norm(t=1){return(this.rnd()-.5)*2*t}int(){return this.rnd()*4294967296>>>0}};var Pe=new Lt(Math.random);var ve=o=>o!=null&&typeof o!="function"&&o.length!==void 0;var Se=Object.getPrototypeOf({}),Dt="function",xe="string",rt=(o,t)=>{let e;if(o===t)return!0;if(o!=null){if(typeof o.equiv===Dt)return o.equiv(t)}else return o==t;if(t!=null){if(typeof t.equiv===Dt)return t.equiv(o)}else return o==t;return typeof o===xe||typeof t===xe?!1:(e=Object.getPrototypeOf(o),(e==null||e===Se)&&(e=Object.getPrototypeOf(t),e==null||e===Se)?xi(o,t):typeof o!==Dt&&o.length!==void 0&&typeof t!==Dt&&t.length!==void 0?Pi(o,t):o instanceof Set&&t instanceof Set?vi(o,t):o instanceof Map&&t instanceof Map?Si(o,t):o instanceof Date&&t instanceof Date?o.getTime()===t.getTime():o instanceof RegExp&&t instanceof RegExp?o.toString()===t.toString():o!==o&&t!==t)},Pi=(o,t,e=rt)=>{let i=o.length;if(i===t.length)for(;i-- >0&&e(o[i],t[i]););return i<0},vi=(o,t,e=rt)=>o.size===t.size&&e([...o.keys()].sort(),[...t.keys()].sort()),Si=(o,t,e=rt)=>o.size===t.size&&e([...o].sort(),[...t].sort()),xi=(o,t,e=rt)=>{if(Object.keys(o).length!==Object.keys(t).length)return!1;for(let i in o)if(!t.hasOwnProperty(i)||!e(o[i],t[i]))return!1;return!0};var ae=class{value;constructor(t){this.value=t}deref(){return this.value}};var we=o=>o instanceof ae;var qt=class o{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Oe("next",this._head)}reverseIterator(){return Oe("prev",this.tail)}clear(){this.release()}compare(t,e=ht){let i=this._length;if(i<t._length)return-1;if(i>t._length)return 1;if(i===0)return 0;{let s=this._head,n=t._head,r=0;for(;i-- >0&&r===0;)r=e(s.value,n.value),s=s.next,n=n.next;return r}}concat(...t){let e=this.copy();for(let i of t)e.into(i);return e}equiv(t){if(!(t instanceof o||ve(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),i=this._head;for(let s=this._length;s-- >0;){if(!rt(i.value,e.next().value))return!1;i=i.next}return!0}filter(t){let e=this.empty();return this.traverse(i=>(t(i.value)&&e.append(i.value),!0)),e}find(t){return this.traverse(e=>e.value!==t)}findWith(t){return this.traverse(e=>!t(e.value))}first(){return this._head?.value}insertSorted(t,e){e=e||ht;for(let i=this._head,s=this._length;s-- >0;){if(e(t,i.value)<=0)return this.insertBefore(i,t);i=i.next}return this.append(t)}into(t){for(let e of t)this.append(e);return this}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCellUnsafe(t){let e,i;for(t<=this._length>>>1?(e=this._head,i="next"):(e=this.tail,i="prev",t=this._length-t-1);t-- >0&&e;)e=e[i];return e}peek(){return this.tail?.value}$reduce(t,e){let i=this._head;for(let s=this._length;s-- >0&&!we(e);)e=t(e,i.value),i=i.next;return e}reduce(t,e){return this.$reduce(t,e)}release(){let t=this._head;if(!t)return!0;let e;for(let i=this._length;i-- >0;)e=t.next,delete t.value,delete t.prev,delete t.next,t=e;return this._head=void 0,this._length=0,!0}reverse(){let t=this._head,e=this.tail,i=(this._length>>>1)+(this._length&1);for(;t&&e&&i>0;){let s=t.value;t.value=e.value,e.value=s,t=t.next,e=e.prev,i--}return this}setHead(t){let e=this._head;return e?(e.value=t,e):this.prepend(t)}setNth(t,e){let i=this.nthCell(t);return!i&&re(t),i.value=e,i}setTail(t){let e=this.tail;return e?(e.value=t,e):this.append(t)}swap(t,e){if(t!==e){let i=t.value;t.value=e.value,e.value=i}return this}toArray(t=[]){return this.traverse(e=>(t.push(e.value),!0)),t}toJSON(){return this.toArray()}toString(){let t=[];return this.traverse(e=>(t.push(String(e.value)),!0)),t.join(", ")}traverse(t,e=this._head,i){if(!this._head)return;let s=e;do{if(!t(s))break;s=s.next}while(s!==i);return s}_map(t,e){return this.traverse(i=>(t.append(e(i.value)),!0)),t}};function*Oe(o,t){for(;t;)yield t.value,t=t[o]}var Ht=class o extends qt{_tail;constructor(t){super(),t&&this.into(t)}get tail(){return this._tail}append(t){if(this._tail){let e={value:t,prev:this._tail};return this._tail.next=e,this._tail=e,this._length++,e}else return this.prepend(t)}asHead(t){return t===this._head?this:(this.remove(t),this._head.prev=t,t.next=this._head,t.prev=void 0,this._head=t,this._length++,this)}asTail(t){return t===this._tail?this:(this.remove(t),this._tail.next=t,t.prev=this._tail,t.next=void 0,this._tail=t,this._length++,this)}cons(t){return this.prepend(t),this}copy(){return new o(this)}*cycle(){for(;;)yield*this}drop(){let t=this._head;if(t)return this._head=t.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,t.value}empty(){return new o}insertAfter(t,e){let i={value:e,next:t.next,prev:t};return t.next?t.next.prev=i:this._tail=i,t.next=i,this._length++,i}insertAfterNth(t,e){return t<0&&(t+=this._length),t>=this._length-1?this.append(e):(Ct(t,0,this._length),this.insertAfter(this.nthCellUnsafe(t),e))}insertBefore(t,e){let i={value:e,next:t,prev:t.prev};return t.prev?t.prev.next=i:this._head=i,t.prev=i,this._length++,i}insertBeforeNth(t,e){return t<0&&(t+=this._length),t<=0?this.prepend(e):(Ct(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new o,t)}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCell(t){if(t<0&&(t+=this._length),!(t<0||t>=this._length))return this.nthCellUnsafe(t)}pop(){let t=this._tail;if(t)return this._tail=t.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,t.value}prepend(t){let e={value:t,next:this._head};return this._head?this._head.prev=e:this._tail=e,this._head=e,this._length++,e}push(t){return this.append(t),this}release(){return this._tail=void 0,super.release()}remove(t){return t.prev?t.prev.next=t.next:this._head=t.next,t.next?t.next.prev=t.prev:this._tail=t.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 t=this.peek();return this.pop(),this.prepend(t),this}}seq(t=0,e=this.length){if(t>=e||t<0)return;let i=this.nthCell(t),s=this.nthCell(e-1),n=r=>({first(){return r.value},next(){return r!==s&&r.next?n(r.next):void 0}});return i?n(i):void 0}shuffle(t,e=Pe){if(this._length<2)return this;for(t=t!==void 0?t:Math.ceil(1.5*Math.log2(this._length));t>0;t--){let i=this._head;for(;i;){let s=i.next;e.probability(.5)?this.asHead(i):this.asTail(i),i=s}}return this}slice(t=0,e=this.length){let i=t<0?t+this._length:t,s=e<0?e+this._length:e;(i<0||s<0)&&fe("invalid indices: ${from} / ${to}");let n=new o,r=this.nthCell(i);for(;r&&++i<=s;)n.push(r.value),r=r.next;return n}sort(t=ht){if(!this._length)return this;let e=1;for(;;){let i=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;i;){s++;let n=i,r=0;for(let l=0;l<e&&(r++,n=n.next,!!n);l++);let a=e;for(;r>0||a>0&&n;){let l;r===0?(l=n,n=n.next,a--):!n||a===0||t(i.value,n.value)<=0?(l=i,i=i.next,r--):(l=n,n=n.next,a--),this._tail?this._tail.next=l:this._head=l,l.prev=this._tail,this._tail=l}i=n}if(this._tail.next=void 0,s<=1)return this;e*=2}}splice(t,e=0,i){let s;typeof t=="number"?(t<0&&(t+=this._length),Ct(t,0,this._length),s=this.nthCellUnsafe(t)):s=t;let n=new o;if(e>0)for(;s&&e-- >0;)this.remove(s),n.push(s.value),s=s.next;else s&&(s=s.next);if(i)if(s)for(let r of i)this.insertBefore(s,r);else for(let r of i)this.push(r);return n}};var Gt=class o{map;items;opts;_size;constructor(t,e){let i={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...e};this.map=i.map(),this.items=new Ht,this._size=0,this.opts=i,t&&this.into(t)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let t of this.items)yield[t.k,t]}*keys(){for(let t of this.items)yield t.k}*values(){for(let t of this.items)yield t.v}copy(){let t=this.empty();t.items=this.items.copy();let e=t.items.head;for(;e;)t.map.set(e.value.k,e),e=e.next;return t}empty(){return new o(null,this.opts)}release(){this._size=0,this.map.clear();let t=this.opts.release;if(t){let e;for(;e=this.items.drop();)t(e.k,e.v);return!0}return this.items.release()}has(t){return this.map.has(t)}get(t,e){let i=this.map.get(t);return i?this.resetEntry(i):e}set(t,e){let i=this.opts.ksize(t)+this.opts.vsize(e),s=this.map.get(t),n=Math.max(0,i-(s?s.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(s,t,e,i):this._size-=n,e}into(t){for(let e of t)this.set(e[0],e[1]);return this}async getSet(t,e){let i=this.map.get(t);return i?this.resetEntry(i):this.set(t,await e())}delete(t){let e=this.map.get(t);return e?(this.removeEntry(e),!0):!1}resetEntry(t){return this.items.asTail(t),t.value.v}ensureSize(){let{release:t,maxsize:e,maxlen:i}=this.opts;for(;this._size>e||this.length>=i;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),t?.(s.k,s.v),this._size-=s.s}return!0}removeEntry(t){let e=t.value;this.map.delete(e.k),this.items.remove(t),this.opts.release?.(e.k,e.v),this._size-=e.s}doSetEntry(t,e,i,s){t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=s,this.items.asTail(t)):(this.items.push({k:e,v:i,s}),this.map.set(e,this.items.tail))}};var it=class o extends Gt{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new o(null,this.opts)}has(t){return this.get(t)!==void 0}get(t,e){let i=this.map.get(t);if(i){if(i.value.t>=Date.now())return this.resetEntry(i);this.removeEntry(i)}return e}set(t,e,i=this.opts.ttl){let s=this.opts.ksize(t)+this.opts.vsize(e),n=this.map.get(t),r=Math.max(0,s-(n?n.value.s:0));return this._size+=r,this.ensureSize()?this.doSetEntry(n,t,e,s,i):this._size-=r,e}async getSet(t,e,i=this.opts.ttl){let s=this.get(t);return s!==void 0?s:this.set(t,await e(),i)}prune(){let t=Date.now(),e=this.items.head,i=0;for(;e;)e.value.t<t&&(this.removeEntry(e),i++),e=e.next;return i}ensureSize(){let{maxlen:t,maxsize:e}=this.opts,i=Date.now(),s=this.items.head;for(;s&&(this._size>e||this.length>=t);)s.value.t<i&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(t,e,i,s,n=this.opts.ttl){let r=Date.now()+n;t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=s,t.value.t=r,this.items.asTail(t)):(this.items.push({k:e,v:i,s,t:r,ttl:n}),this.map.set(e,this.items.tail))}resetEntry(t){return this.opts.autoExtend&&(t.value.t=Date.now()+t.value.ttl),super.resetEntry(t)}};var Nt=class{debug;constructor(t){this.debug=t||!1}log(t,e,i){this.debug&&console.log(t,e,i)}scope(t,e,i,s){let n=new Map,r=s!==void 0?new it(null,{ttl:s}):new it;return{get:(...u)=>{let p=i(...u);if(n.has(p)){this.log("[live]",t,p);let P=n.get(p);return Promise.resolve(P)}if(r.has(p))return this.log("[memo]",t,p),r.get(p);this.log("[fetch]",t,p);let g=e(...u).catch(P=>{throw r.delete(p),P});return r.set(p,g),g},set:(u,...p)=>{let g=i(...p);this.log("[set-live]",t,g),n.set(g,u)},clear:()=>{this.log("[clear]",t),n.clear(),r.release()}}}};var{FeeUtils:Ie}=I,gt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new o(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(r=>[r.id,r])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,weightIn:s.weight,weightOut:n.weight}}validateAndBuy(t,e,i){let s=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let r=t.balanceOut/this.maxOutRatio;if(e>r&&n.push("MaxOutRatioExceeded"),s===t.assetOut){let a=this.calculateTradeFee(e,i),l=Ie.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),c=e+a,u=this.calculateInGivenOut(t,c),p=t.balanceIn/this.maxInRatio;return u>p&&n.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:l,errors:n}}else{let a=this.calculateInGivenOut(t,e),l=t.balanceIn/this.maxInRatio;return a>l&&n.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:n}}}validateAndSell(t,e,i){let s=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let r=t.balanceIn/this.maxInRatio;if(e>r&&n.push("MaxInRatioExceeded"),s===t.assetIn){let a=this.calculateOutGivenIn(t,e),l=t.balanceOut/this.maxOutRatio;return a>l&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:n}}else{let a=this.calculateOutGivenIn(t,e),l=this.calculateTradeFee(a,i),c=Ie.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),u=a-l,p=t.balanceOut/this.maxOutRatio;return u>p&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:c,errors:n}}}calculateInGivenOut(t,e){let i=G.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e){let i=G.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){let e=G.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),at.big.toBigInt(1,at.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=G.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),at.big.toBigInt(1,at.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let i=G.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var Ee=require("polkadot-api"),lt=require("rxjs");var Te=(o,t=new Map)=>e=>{let i;return t.has(e)?t.get(e):(t.set(e,i=o(e)),i)};var b=require("rxjs"),m=require("rxjs/operators");var $t=require("@galacticcouncil/descriptors");var Be=require("@galacticcouncil/common"),Vt=require("rxjs");var j=require("rxjs"),T=require("rxjs/operators");function _e(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>(0,j.defer)(()=>(0,j.from)(o._request("system_health",[]))).pipe((0,T.timeout)({first:e}),(0,T.map)(()=>"online"),(0,T.catchError)(()=>(0,j.of)("offline")));return(0,j.of)({state:"offline",delayMs:0}).pipe((0,T.expand)(n=>(0,j.timer)(n.delayMs).pipe((0,T.switchMap)(i),(0,T.map)(r=>({state:r,delayMs:t})))),(0,T.skip)(1),(0,T.map)(n=>n.state),(0,T.distinctUntilChanged)(),(0,T.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:wi}=Be.log,zt=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue("best")),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",_e(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,Vt.tap)({error:i=>wi.error(t,i)}),(0,Vt.shareReplay)({bufferSize:1,refCount:!0}))}};var $=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi($t.hydration),this.apiNext=this.client.getTypedApi($t.hydrationNext),this.watcher=zt.getInstance(this.client)}};var Oi=require("polkadot-api/ws-provider"),Ii=require("polkadot-api/logs-provider"),Ti=require("@polkadot-api/legacy-provider");var _i=require("polkadot-api/sm-provider");var Ae=require("@galacticcouncil/common"),C=require("rxjs"),d=require("rxjs/operators");var{logger:ot}=Ae.log,bt=class extends ${erc20Ids=null;constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:i}=await e.getValue(t,{at:"best"});return this.getBreakdown(i)}async getTokenBalance(t,e){let s=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(s)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,C.defer)(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return(0,C.combineLatest)([e,i,s]).pipe((0,d.connect)(n=>(0,C.concat)(n.pipe((0,d.take)(1)),n.pipe((0,d.skip)(1),(0,d.debounceTime)(250)))))}).pipe((0,d.map)(e=>e.flat()),(0,d.startWith)([]),(0,d.bufferCount)(2,1),(0,d.map)(([e,i],s)=>s===0?i:this.getDeltas(e,i))).pipe((0,d.tap)({subscribe:()=>ot.debug("balance: subscribe",t),error:e=>ot.error("balance",e)}),(0,d.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,C.defer)(()=>e.watchValue(t,"best")).pipe((0,d.map)(i=>({id:0,balance:this.getBreakdown(i.data)})),(0,d.tap)({error:i=>ot.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return(0,C.defer)(()=>i.watchValue(t,e,"best")).pipe((0,d.map)(s=>({id:e,balance:this.getBreakdown(s)})),(0,d.tap)({error:s=>ot.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,C.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,d.distinctUntilChanged)((i,s)=>!s.deltas),(0,d.map)(({deltas:i})=>{let s=[];return i?.deleted.forEach(n=>{let[r,a]=n.args;s.push({id:a,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(n=>{let[r,a]=n.args;s.push({id:a,balance:this.getBreakdown(n.value)})}),s}),(0,d.tap)({error:i=>ot.error("balance(tokens)",i)}))}watchErc20Balance(t,e){let i=async()=>{if(this.erc20Ids)return this.erc20Ids;let n=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=n.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[a]=r;return a}),this.erc20Ids},s=async n=>(await Promise.all(n.map(async a=>[a,await this.getBalanceData(t,a)]))).map(([a,l])=>({id:a,balance:l}));return(0,C.defer)(()=>(0,C.from)(e?Promise.resolve(e):i()).pipe((0,d.switchMap)(n=>this.watcher.bestBlock$.pipe((0,d.switchMap)(()=>(0,C.from)(s(n))))),(0,d.startWith)([]),(0,d.bufferCount)(2,1),(0,d.map)(([n,r],a)=>a===0?r.filter(l=>l.balance.total>0n):this.getDeltas(n,r)),(0,d.distinctUntilChanged)((n,r)=>r.length===0),(0,d.tap)({error:n=>ot.error("balance(erc20)",n)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.getBreakdown(i)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,i=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:i,transferable:e}}getDeltas(t,e){let i=(n,r)=>n!==void 0&&r!==void 0&&n.transferable===r.transferable&&n.total===r.total,s=t.reduce((n,r)=>(n.set(r.id,r.balance),n),new Map);return e.filter(n=>!i(n.balance,s.get(n.id)))}};var Fe=require("rxjs"),Wt=class{store$=new Fe.BehaviorSubject([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(t){return this.changeset.size===0?[]:t.filter(e=>this.changeset.has(e.address))}set(t){this.changeset=new Set(t.map(e=>e.address)),this.store$.next(t)}update(t){this.updateQueue=this.updateQueue.then(async()=>{let e=this.store$.value,i=new Map(e.map((a,l)=>[a.address,l])),s=await t(e),n=e.slice(),r=new Set;for(let a of s){let l=i.get(a.address);l===void 0?(i.set(a.address,n.length),n.push(a)):n[l]=a,r.add(a.address)}this.changeset=r,this.store$.next(n)}).catch(console.error)}destroy(){this.store$.complete()}};var ke=require("@galacticcouncil/common");var Bi={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Ut}=ke.log,Yt=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${Bi[this.type]})`,10)}trace(t,...e){Ut.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){Ut.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){Ut.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){Ut.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:Ai}=kt,Fi=3e3,E=class extends ${evm;balance;store=new Wt;log;shared$;resync$=new b.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new it(null,{ttl:6*1e3});memPools=Te(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e,this.balance=new bt(t),this.log=new Yt(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){return(await this.getMemPools()).filter(e=>this.hasValidAssets(e))}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe((0,m.startWith)([]),(0,m.bufferCount)(2,1),(0,m.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,m.filter)(t=>t.length>0),(0,m.throttleTime)(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return(0,b.defer)(()=>{let t=new b.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,m.switchMap)(()=>{let e=new b.Subscription;return(0,b.from)(Ai(this.getMemPools(),6e4,"getMemPools stalled")).pipe((0,m.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,m.map)(s=>s.filter(n=>this.hasValidAssets(n))),(0,m.tap)(s=>this.store.set(s)),(0,m.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),b.EMPTY))).pipe((0,m.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,m.switchMap)(s=>(0,b.merge)((0,b.of)(s),this.store.asObservable().pipe((0,m.skip)(1)))),(0,m.finalize)(()=>{e.unsubscribe()}))}),(0,m.finalize)(()=>t.unsubscribe()))}).pipe((0,m.share)({connector:()=>new b.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:i}=e,s=[this.balance.watchTokensBalance(i)];if(this.hasSystemAsset(e)){let n=this.balance.watchSystemBalance(i);s.push(n)}if(this.hasErc20Asset(e)){let n=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),r=this.balance.watchErc20Balance(i,n);s.push(r)}return(0,b.combineLatest)(s).pipe((0,m.map)(n=>n.flat()),(0,m.pairwise)(),(0,m.map)(([n,r])=>this.balance.getDeltas(n,r)),(0,m.filter)(n=>n.length>0),(0,m.map)(n=>[i,n]))});return(0,b.merge)(...t).pipe((0,m.bufferTime)(250),(0,m.filter)(e=>e.length>0),(0,m.map)(e=>new Map(e)),this.watchGuard("balances")).subscribe(e=>{this.store.update(i=>this.updateBalances(i,e))})}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:i})=>t.type==="XYK"?i>0n&&!!e:!!e)}updateBalances=(t,e)=>{let i=[],s=new Map(t.map(n=>[n.address,n]));for(let[n,r]of e){let a=s.get(n);if(a){let l=a.tokens.map(c=>{let u=r.find(p=>p.id===c.id);return u&&c.id!==a.id?{...c,balance:u.balance.transferable}:c});i.push({...a,tokens:l})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<Fi||(this.resyncAt=e,this.mem++,this.resync$.next())}requestResync(t=!1){this.resyncPending||(this.resyncPending=!0,setTimeout(()=>{this.resyncPending=!1,this.resync(t)},0))}startWatchdog(){let s=this.watcher.connection$.pipe((0,m.pairwise)(),(0,m.filter)(([a,l])=>a==="offline"&&l==="online"),(0,m.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,m.catchError)(a=>(this.log.error("watchdog_recovery_error",a),b.EMPTY)),(0,m.repeat)({delay:1e3})),n=this.watcher.finalizedBlock$.pipe((0,m.pairwise)(),(0,m.tap)(([a,l])=>{let c=Number(a.number),u=Number(l.number),p=u-c;p>=3&&(this.log.debug("watchdog_gap",{from:c,to:u,gap:p}),this.requestResync())}),(0,m.catchError)(a=>(this.log.error("watchdog_gap_error",a),b.EMPTY)),(0,m.repeat)({delay:1e3})),r=(0,b.interval)(36e5).pipe((0,m.tap)(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),(0,m.catchError)(a=>(this.log.error("watchdog_periodic_error",a),b.EMPTY)),(0,m.repeat)({delay:1e3}));return(0,b.merge)(s,n,r).subscribe()}watchGuard(t){return e=>e.pipe((0,m.tap)({error:i=>{this.log.error(t,i),this.requestResync(!0)}}),(0,m.finalize)(()=>{this.log.debug(t,"unsub")}),(0,m.catchError)(()=>b.EMPTY))}};var ft=class extends E{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}getPoolWeights(t,e){let{start:i,end:s,initial_weight:n,final_weight:r}=t,a=G.calculateLinearWeights(i?i.toString():"0",s?s.toString():"0",n.toString(),r.toString(),e.toString()),l=BigInt(a),c=this.MAX_FINAL_WEIGHT-BigInt(l);return[l,c]}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Ee.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:"best"}),this.api.query.ParachainSystem.ValidationData.getValue({at:"best"}),this.getPoolLimits()]),s=e?.relay_parent_number||0,n=t.filter(({value:r})=>e&&this.isActivePool(r,s)).map(async({keyArgs:r,value:a})=>{let[l]=r,c=l.toString(),u=await this.getPoolDelta(c,a,s);return{address:c,type:"LBP",fee:a.fee,...u,...i}});return Promise.all(n)}async getPoolDelta(t,e,i){let{assets:s,repay_target:n,fee_collector:r}=e,[a,l]=this.getPoolWeights(e,i),[c,u]=s,[p,g,P,f,A]=await Promise.all([this.isRepayFeeApplied(c,n,r.toString()),this.balance.getBalance(t,c),this.api.query.AssetRegistry.Assets.getValue(c),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u)]);return{repayFeeApply:p,tokens:[{id:c,decimals:P?.decimals,existentialDeposit:P?.existential_deposit,balance:g.transferable,weight:a,type:P?.asset_type.type},{id:u,decimals:A?.decimals,existentialDeposit:A?.existential_deposit,balance:f.transferable,weight:l,type:A?.asset_type.type}]}}isActivePool(t,e){let{start:i,end:s}=t;return i&&s?e>=i&&e<s:!1}async isRepayFeeApplied(t,e,i){if(e===0n)return!1;try{return(await this.balance.getBalance(i,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let i=this.store.pools.find(n=>n.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:i.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue("best").pipe((0,lt.filter)(t=>t!==void 0),(0,lt.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let i=[];for(let s of e){let n=this.poolsData.get(s.address);if(n){let{assets:r,repay_target:a,fee_collector:l}=n,[c]=r,[u,p]=this.getPoolWeights(n,t),[g,P]=s.tokens,f=[{...g,weight:u},{...P,weight:p}],A=await this.isRepayFeeApplied(c,a,l.toString());i.push({...s,tokens:f,repayFeeApply:A})}}return i})})}subscribeUpdates(){let t=new lt.Subscription;return t.add(this.subscribeValidationData()),t}};var ce={};H(ce,{OmniMath:()=>v,OmniPool:()=>yt,OmniPoolClient:()=>Pt});var h=require("@galacticcouncil/math-omnipool"),st=se(require("big.js")),v=class{static calculateSpotPrice(t,e,i,s){return(0,h.calculate_spot_price)(t,e,i,s)}static calculateLrnaSpotPrice(t,e){return(0,h.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,i,s,n,r,a,l,c,u){return(0,h.calculate_in_given_out)(t,e,i,s,n,r,a,l,c,u)}static calculateLrnaInGivenOut(t,e,i,s,n,r){return(0,h.calculate_lrna_in_given_out)(t,e,i,s,n,r)}static calculateOutGivenIn(t,e,i,s,n,r,a,l,c,u){return(0,h.calculate_out_given_in)(t,e,i,s,n,r,a,l,c,u)}static calculateOutGivenLrnaIn(t,e,i,s,n,r){return(0,h.calculate_out_given_lrna_in)(t,e,i,s,n,r)}static calculateShares(t,e,i,s){return(0,h.calculate_shares)(t,e,i,s)}static calculateLiquidityOut(t,e,i,s,n,r,a,l){return(0,h.calculate_liquidity_out)(t,e,i,s,n,r,a,l)}static calculateLiquidityLRNAOut(t,e,i,s,n,r,a,l){return(0,h.calculate_liquidity_lrna_out)(t,e,i,s,n,r,a,l)}static calculateCapDifference(t,e,i,s){let n=(0,st.default)(e),r=(0,st.default)(t),a=(0,st.default)(s),l=(0,st.default)(i),c=(0,st.default)(10).pow(18),u=l.div(c);if(n.div(a).lt(u)){let g=u.times(a).minus(n).times(r),P=n.times((0,st.default)(1).minus(u));return g.div(P).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,s){return(0,h.calculate_liquidity_hub_in)(t,e,i,s)}static isSellAllowed(t){return(0,h.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,h.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,h.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,h.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,i,s,n,r,a,l,c,u,p){return(0,h.recalculate_asset_fee)(t,e,i,s,n,r,a,l,c,u,p)}static recalculateProtocolFee(t,e,i,s,n,r,a,l,c,u,p){return(0,h.recalculate_protocol_fee)(t,e,i,s,n,r,a,l,c,u,p)}static verifyAssetCap(t,e,i,s){return(0,h.verify_asset_cap)(t,e,i,s)}};var Re=require("@galacticcouncil/common");var{FeeUtils:W}=I,yt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new o(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let i=new Map(this.tokens.map(r=>[r.id,r])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:s.hubReserves,hubReservesOut:n.hubReserves,sharesIn:s.shares,sharesOut:n.shares,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:s.balance,balanceOut:n.balance,tradeableIn:s.tradeable,tradeableOut:n.tradeable,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,i),r=s===0n?0:et.calculateBuyFee(s,n),a=[],l=v.isSellAllowed(t.tradeableIn),c=v.isBuyAllowed(t.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return n>p&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:r,errors:a}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),r=et.calculateSellFee(s,n),a=[],l=v.isSellAllowed(t.tradeableIn),c=v.isBuyAllowed(t.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return n>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:n,feePct:r,errors:a}}calculateInGivenOut(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,i);let s=v.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?W.toRaw(i.assetFee).toString():"0",i?W.toRaw(i.protocolFee).toString():"0",i?W.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateLrnaInGivenOut(t,e,i){let s=v.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?W.toRaw(i.assetFee).toString():"0",i?W.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,i);let s=v.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?W.toRaw(i.assetFee).toString():"0",i?W.toRaw(i.protocolFee).toString():"0",i?W.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateOutGivenLrnaIn(t,e,i){let s=v.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?W.toRaw(i.assetFee).toString():"0",i?W.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=v.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceLrnaInGivenOut(t){let e=v.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=v.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}spotPriceOutGivenLrnaIn(t){let e=v.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,i){let s=e-i;if(s===0)return t;let n=Re.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var Q=require("polkadot-api"),Le=require("@polkadot-api/utils"),y=require("rxjs"),De=require("@galacticcouncil/common");var{FeeUtils:S}=I,Ce=Q.Binary.fromText("omnipool"),Me=(0,Q.Enum)("Short"),Pt=class extends E{queryBus=new Nt;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:"best"}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:"best"}),t=>String(t),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:"best"}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(Ce,t,Me,{at:"best"}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,Le.toHex)(e);return(0,Q.AccountId)(De.HYDRATION_SS58_PREFIX).dec(i)}getOraclePair(t){return t===0?[0,1]:[1,t]}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Q.CompatibilityLevel.BackwardsCompatible,e)}async isSlipFeeSupported(){return this.apiNext.query.Omnipool.SlipFee.isCompatible(Q.CompatibilityLevel.Partial)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,s,n,r,a]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:"best"}),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.balance.getBalance(e,t),this.getPoolLimits()]),l=i.map(async({keyArgs:u,value:p})=>{let[g]=u,{hub_reserve:P,shares:f,tradable:A,cap:Y,protocol_shares:X}=p,[R,q]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(g),this.balance.getBalance(e,g)]);return{id:g,decimals:R?.decimals,existentialDeposit:R?.existential_deposit,balance:q.transferable,cap:Y,hubReserves:P,protocolShares:X,shares:f,tradeable:A,type:R?.asset_type.type}}),c=await Promise.all(l);return c.push({id:t,decimals:n?.decimals,existentialDeposit:n?.existential_deposit,balance:r.transferable,tradeable:s,type:n?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:c,...a}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,s=0;await this.isSlipFeeSupported()&&(s=await this.maxSlipFee.get()??0);let r=await this.dynamicFeesConfig.get(e);if(r?.type==="Fixed"){let{asset_fee:L,protocol_fee:K}=r.value;return{assetFee:S.fromPermill(L),protocolFee:S.fromPermill(K),maxSlipFee:S.fromPermill(s)}}let a=this.getOraclePair(e),l=this.getOraclePair(i),[c,u,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(a),this.emaOracles.get(l)]),[g,P,f]=await this.getAssetFee(t,this.block,c,u,r?.value.asset_fee_params),[A,Y,X]=i===1?[0,0,0]:await this.getProtocolFee(t,this.block,c,p,r?.value.protocol_fee_params),R=g+A,q=f+X;return{assetFee:S.fromPermill(P),protocolFee:S.fromPermill(Y),maxSlipFee:S.fromPermill(s),min:S.fromPermill(R),max:S.fromPermill(q)}}async getAssetFee(t,e,i,s,n){let{assetOut:r,balanceOut:a}=t,{min_fee:l,max_fee:c,decay:u,amplification:p}=n||await this.api.constants.DynamicFees.AssetFeeParameters();if(!i||!s)return[l,l,c];let g=S.fromPermill(l),P=S.fromPermill(c),[f]=s,{asset_fee:A,timestamp:Y}=i,X=Math.max(1,e-Y),R=f.volume.b_in.toString(),q=f.volume.b_out.toString(),L=f.liquidity.b.toString();r===0&&(R=f.volume.a_in.toString(),q=f.volume.a_out.toString(),L=f.liquidity.a.toString());let K=S.fromPermill(A),mt=v.recalculateAssetFee(R,q,L,"9",a.toString(),S.toRaw(K).toString(),X.toString(),S.toRaw(g).toString(),S.toRaw(P).toString(),u.toString(),p.toString());return[l,Number(mt)*1e6,c]}async getProtocolFee(t,e,i,s,n){let{assetIn:r,balanceIn:a}=t,{min_fee:l,max_fee:c,decay:u,amplification:p}=n||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!i||!s)return[l,l,c];let g=S.fromPermill(l),P=S.fromPermill(c),[f]=s,{protocol_fee:A,timestamp:Y}=i,X=Math.max(1,e-Y),R=f.volume.b_in.toString(),q=f.volume.b_out.toString(),L=f.liquidity.b.toString();r===0&&(R=f.volume.a_in.toString(),q=f.volume.a_out.toString(),L=f.liquidity.a.toString());let K=S.fromPermill(A),mt=v.recalculateProtocolFee(R,q,L,"9",a.toString(),S.toRaw(K).toString(),X.toString(),S.toRaw(g).toString(),S.toRaw(P).toString(),u.toString(),p.toString());return[l,Number(mt)*1e6,c]}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(s=>s.id).map(s=>this.getOraclePair(s)).map(s=>this.api.query.EmaOracle.Oracles.watchValue(Ce,s,Me,"best").pipe((0,y.filter)(n=>n!==void 0),(0,y.map)((n,r)=>({value:n,index:r})),(0,y.tap)(({index:n})=>{n>0&&this.log.trace("emaOracle.Oracles",s.join(":"))}),(0,y.map)(({value:n})=>({pair:s,value:n}))));return(0,y.merge)(...i).pipe((0,y.finalize)(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(s=>{let{pair:n,value:r}=s;this.emaOracles.set(r,n)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,y.distinctUntilChanged)((t,e)=>!e.deltas),(0,y.map)((t,e)=>({value:t,index:e})),(0,y.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),(0,y.finalize)(()=>this.dynamicFees.clear()),this.watchGuard("dynamicFees.AssetFee")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFees.set(e.value,i)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe((0,y.distinctUntilChanged)((t,e)=>!e.deltas),(0,y.map)((t,e)=>({value:t,index:e})),(0,y.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),(0,y.finalize)(()=>this.dynamicFeesConfig.clear()),this.watchGuard("dynamicFees.AssetFeeConfiguration")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFeesConfig.set(e.value,i)})})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,y.distinctUntilChanged)((t,e)=>!e.deltas),(0,y.map)((t,e)=>({value:t,index:e})),(0,y.tap)(({value:t,index:e})=>{e>0&&this.log.trace("omnipool.Assets",t.deltas?.upserted)}),this.watchGuard("omnipool.Assets")).subscribe(({value:{deltas:t}})=>{this.store.update(([e])=>{let i=t?.upserted.reduce((n,r)=>{let[a]=r.args;return n.set(a,r.value),n},new Map),s=e.tokens.map(n=>{let r=i?.get(n.id);return r?this.updateTokenState(n,r):n});return[{...e,tokens:s}]})})}subscribeUpdates(){let t=new y.Subscription;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:i,shares:s,tradable:n,cap:r,protocol_shares:a}=e;return{...t,cap:r,hubReserves:i,protocolShares:a,shares:s,tradeable:n}}};var ue={};H(ue,{StableMath:()=>_,StableSwap:()=>nt,StableSwapClient:()=>St});var x=require("@galacticcouncil/math-stableswap"),_=class{static getPoolAddress(t){return(0,x.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let i=0;i<t;i++)e.push(["1","1"]);return e}static calculateAmplification(t,e,i,s,n){return(0,x.calculate_amplification)(t,e,i,s,n)}static calculateInGivenOut(t,e,i,s,n,r,a){return(0,x.calculate_in_given_out)(t,e,i,s,n,r,a)}static calculateAddOneAsset(t,e,i,s,n,r,a){return(0,x.calculate_add_one_asset)(t,e,i,s,n,r,a)}static calculateSharesForAmount(t,e,i,s,n,r,a){return(0,x.calculate_shares_for_amount)(t,e,i,s,n,r,a)}static calculateOutGivenIn(t,e,i,s,n,r,a){return(0,x.calculate_out_given_in)(t,e,i,s,n,r,a)}static calculateLiquidityOutOneAsset(t,e,i,s,n,r,a){return(0,x.calculate_liquidity_out_one_asset)(t,e,i,s,n,r,a)}static calculateShares(t,e,i,s,n,r){return(0,x.calculate_shares)(t,e,i,s,n,r)}static calculateSpotPriceWithFee(t,e,i,s,n,r,a,l){return(0,x.calculate_spot_price_with_fee)(t,e,i,s,n,r,a,l)}static recalculatePegs(t,e,i,s,n,r){let a=(0,x.recalculate_peg)(t,e,i,s,n,r);return JSON.parse(a)}};var vt=require("@galacticcouncil/common");var{FeeUtils:ct}=I,nt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new o(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(r=>[r.id,r])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:n.tradeable,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,i),r=s===0n?0:et.calculateBuyFee(s,n),a=[],l=v.isSellAllowed(t.tradeableIn),c=v.isBuyAllowed(t.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:r,errors:a}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),r=et.calculateSellFee(s,n),a=[],l=v.isSellAllowed(t.tradeableIn),c=v.isBuyAllowed(t.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:n,feePct:r,errors:a}}calculateIn(t,e,i){let s=_.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateAddOneAsset(t,e,i){let s=_.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateSharesForAmount(t,e,i){let s=_.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateInGivenOut(t,e,i){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,i):t.assetIn==this.id?this.calculateSharesForAmount(t,e,i):this.calculateIn(t,e,i)}spotPriceInGivenOut(t){let e=_.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetOut===this.id,t.assetIn===this.id,t.decimalsOut,t.decimalsIn)}calculateOut(t,e,i){let s=_.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateWithdrawOneAsset(t,e,i){let s=_.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateShares(t,e,i){let s=_.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e,i){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,i):t.assetOut==this.id?this.calculateShares(t,e,i):this.calculateOut(t,e,i)}spotPriceOutGivenIn(t){let e=_.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetIn===this.id,t.assetOut===this.id,t.decimalsIn,t.decimalsOut)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:i,decimals:s})=>({asset_id:e,amount:i,decimals:s}));return JSON.stringify(t,dt.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],dt.jsonFormatter)}normalizeSpot(t,e,i,s,n){return e?t*vt.big.pow10(vt.RUNTIME_DECIMALS-n):i?t/vt.big.pow10(n-s):t}};var Kt=require("polkadot-api"),qe=require("@polkadot-api/utils"),He=require("@noble/hashes/blake2b"),M=require("rxjs"),jt=require("@galacticcouncil/common");var{FeeUtils:ki}=I,St=class extends E{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=_.getPoolAddress(t),i=(0,He.blake2b)(e,{dkLen:32}),s=(0,qe.toHex)(i);return(0,Kt.AccountId)(jt.HYDRATION_SS58_PREFIX).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:i,final_amplification:s,initial_block:n,final_block:r}=t,a=_.calculateAmplification(i.toString(),s.toString(),n.toString(),r.toString(),e.toString()),l=Number(a)<s;return{amplification:BigInt(a),isRampPeriod:l}}async getPoolTokens(t,e){let i=this.getPoolAddress(t),s=e.assets.map(async n=>{let[r,a,l]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,n),this.api.query.AssetRegistry.Assets.getValue(n),this.balance.getBalance(i,n)]);return{id:n,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:l.transferable,tradeable:r,type:a?.asset_type.type}});return Promise.all(s)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(Kt.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:"best"}),this.api.query.System.Number.getValue({at:"best"}),this.getPoolLimits()]),s=t.map(async({keyArgs:n,value:r})=>{let[a]=n,l=this.getPoolAddress(a),[c,u,p]=await Promise.all([this.getPoolTokens(a,r),this.api.query.Stableswap.PoolPegs.getValue(a,{at:"best"}),this.api.query.Tokens.TotalIssuance.getValue(a,{at:"best"})]),g=this.getPoolAmplification(r,e),P=u?this.getRecentPegs(u):this.getDefaultPegs(r);return c.push({id:a,tradeable:15,balance:p,decimals:jt.RUNTIME_DECIMALS}),this.poolsData.set(a,r),{address:l,id:a,type:"Stableswap",fee:ki.fromPermill(r.fee),tokens:c,totalIssuance:p,pegs:P,...i,...g}});return Promise.all(s)}async getPoolFees(t,e){return{fee:this.store.pools.find(s=>s.address===e).fee}}getDefaultPegs(t){return _.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([i,s])=>s.map(n=>n.toString()))}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,"best").pipe((0,M.map)((s,n)=>({value:s,index:n})),(0,M.tap)(({index:s,value:n})=>{s>0&&this.log.trace("tokens.TotalIssuance",i,n)}),(0,M.map)(({value:s})=>({id:i,value:s}))));return(0,M.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:s,value:n}=i;this.store.update(r=>{let a=[];return r.filter(l=>l.id===s).forEach(l=>{let c=l.tokens.map(u=>u.id===s?{...u,balance:n}:u);a.push({...l,tokens:c,totalIssuance:n})}),a})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,M.distinctUntilChanged)((t,e)=>!e.deltas),(0,M.map)((t,e)=>({value:t,index:e})),(0,M.tap)(({value:t,index:e})=>{e>0&&this.log.trace("stableswap.PoolPegs",t.deltas?.upserted)}),this.watchGuard("stableswap.PoolPegs")).subscribe({error:t=>this.log.error("stableswap.PoolPegs",t),next:({value:{deltas:t}})=>{this.store.update(e=>{let i=[],s=new Map(e.map(n=>[n.id,n]));return t?.upserted.forEach(({args:n,value:r})=>{let[a]=n,l=s.get(a);if(l){let c=this.getRecentPegs(r);i.push({...l,pegs:c})}}),i})}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(e=>{let i=[];return e.filter(s=>s.isRampPeriod).forEach(s=>{let n=this.poolsData.get(s.id);if(n){let r=this.getPoolAmplification(n,t);i.push({...s,...r})}}),i})})}subscribeUpdates(){let t=new M.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var pe={};H(pe,{XykMath:()=>Z,XykPool:()=>xt,XykPoolClient:()=>wt});var w=require("@galacticcouncil/math-xyk"),Z=class{static getSpotPrice(t,e,i){return(0,w.get_spot_price)(t,e,i)}static calculateInGivenOut(t,e,i){return(0,w.calculate_in_given_out)(t,e,i)}static calculateOutGivenIn(t,e,i){return(0,w.calculate_out_given_in)(t,e,i)}static calculatePoolTradeFee(t,e,i){return(0,w.calculate_pool_trade_fee)(t,e,i)}static calculateLiquidityIn(t,e,i){return(0,w.calculate_liquidity_in)(t,e,i)}static calculateSpotPrice(t,e){return(0,w.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,i,s){return(0,w.calculate_spot_price_with_fee)(t,e,i,s)}static calculateShares(t,e,i){return(0,w.calculate_shares)(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,s){return(0,w.calculate_liquidity_out_asset_a)(t,e,i,s)}static calculateLiquidityOutAssetB(t,e,i,s){return(0,w.calculate_liquidity_out_asset_b)(t,e,i,s)}};var Ne=require("@galacticcouncil/common");var{FeeUtils:Ge}=I,xt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new o(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(r=>[r.id,r])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:s.balance,balanceOut:n.balance,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=this.calculateTradeFee(s,i),r=Ge.toPct(i.exchangeFee),a=s+n,l=[];(e<this.minTradingLimit||s<t.assetInEd)&&l.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&l.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&l.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:r,errors:l}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateTradeFee(s,i),r=Ge.toPct(i.exchangeFee),a=s-n,l=[];(e<this.minTradingLimit||s<t.assetOutEd)&&l.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&l.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&l.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:r,errors:l}}calculateInGivenOut(t,e){let i=Z.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e){let i=Z.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){let e=Z.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=Z.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=Z.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(i)}normalizeSpot(t,e,i){let s=e-i;if(s===0)return t;let n=Ne.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var ze=require("polkadot-api"),Ve=require("rxjs");var wt=class extends E{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(ze.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries(),this.getPoolLimits()]),i=t.map(async({keyArgs:s,value:n})=>{let[r]=s,[a,l]=n,[c,u,p,g]=await Promise.all([this.balance.getBalance(r,a),this.api.query.AssetRegistry.Assets.getValue(a),this.balance.getBalance(r,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:r,type:"XYK",tokens:[{id:a,decimals:u?.decimals||this.decimals.get(a),existentialDeposit:u?.existential_deposit,balance:c.transferable,type:u?.asset_type.type},{id:l,decimals:g?.decimals||this.decimals.get(l),existentialDeposit:g?.existential_deposit,balance:p.transferable,type:g?.asset_type.type}],...e}});return Promise.all(i)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return Ve.Subscription.EMPTY}};var me={};H(me,{AavePool:()=>Ot,AavePoolClient:()=>It});var ut=require("@galacticcouncil/common");var Ot=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new o(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(r=>[r.id,r])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=[];return e>t.balanceOut&&n.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:n}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=[];return s>t.balanceOut&&n.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:n}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return ut.big.toBigInt(1,ut.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return ut.big.toBigInt(1,ut.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var We=require("polkadot-api"),Ue=require("@polkadot-api/utils"),U=require("rxjs"),Ye=require("viem"),Jt=require("@galacticcouncil/common");var $e=[{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{ERC20:Ei}=Jt.erc20,Ri=["Supply","Withdraw","Repay","Borrow"],It=class extends E{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,s=new TextEncoder().encode(i.padEnd(32,"\0")),n=(0,Ue.toHex)(s);return(0,We.AccountId)(Jt.HYDRATION_SS58_PREFIX).dec(n)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:"best"})).map(async({reserve:i,atoken:s,liqudity_in:n,liqudity_out:r})=>{let[a,l,c,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i),this.api.query.AssetRegistry.AssetLocations.getValue(i),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(i,s),type:"Aave",tokens:[{id:i,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:n,location:l,type:a?.asset_type.type},{id:s,decimals:c?.decimals,existentialDeposit:c?.existential_deposit,balance:r,location:u,type:c?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:s,liqudity_out:n}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:"best"});return t.tokens.map(r=>{let a=r.id===e.id?s:n;return{...r,balance:a}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key.asHex()}throw new Error("Invalid aave reserve multilocation")}return Ei.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:i}=t;return{assetIn:e,assetOut:i,key:`${e}:${i}`}}parseEvmLog(t){let{topics:e,data:i}=t.log,s=e.map(r=>r.asHex()),n=i.asHex();try{let{eventName:r,args:a}=(0,Ye.decodeEventLog)({abi:$e,topics:s,data:n}),l=a.reserve.toLowerCase();return{eventName:r,reserve:l,key:`${r}:${l}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(i=>i.tokens).map(([i,s])=>s).map(i=>i.id);return this.api.event.Router.Executed.watch().pipe((0,U.map)(({payload:i})=>this.parseRouterLog(i)),(0,U.filter)(({assetIn:i,assetOut:s})=>e.includes(i)||e.includes(s)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:s,key:n})=>{this.log.trace("router.Executed",n),this.store.update(async r=>{let a=[];for(let l of r){let[c,u]=l.tokens;if(u.id===i||u.id===s){let g=await this.getPoolDelta(l);a.push({...l,tokens:g})}}return a})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,U.map)(({payload:t})=>this.parseEvmLog(t)),(0,U.filter)(t=>t!==void 0),(0,U.filter)(({eventName:t})=>Ri.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async i=>{let s=[];for(let n of i){let[r]=n.tokens;if(this.getReserveH160Id(r).toLowerCase()===t){let l=await this.getPoolDelta(n);s.push({...n,tokens:l})}}return s})})}subscribeBalances(){return U.Subscription.EMPTY}subscribeUpdates(){let t=new U.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var he={};H(he,{HsmMath:()=>D,HsmPool:()=>Tt,HsmPoolClient:()=>At});var B=require("@galacticcouncil/math-hsm"),D=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,B.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,B.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,B.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,B.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,B.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,B.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,B.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,B.calculate_max_price)(t,e)}};var F=require("@galacticcouncil/common");var{FeeUtils:pt}=I,Tt=class o extends nt{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new o(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,i){let s=this.parsePair(t.assetOut,t.assetIn),n=super.calculateInGivenOut(s,e,{fee:this.fee}),r=this.calculateBuybackLimit(t);e>r&&i.push("MaxBuyBackExceeded");let a=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,n)>a&&i.push("MaxBuyPriceExceeded"),n>this.collateralBalance&&i.push("InsufficientCollateral"),i}validateTradeHollarOut(t,e,i){return this.collateralBalance+t>this.maxInHolding&&i.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&i.push("FacilitatorCapacityExceeded"),i}validateTradeConstraints(t,e,i){let s=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,s):this.validateTradeHollarOut(e,i,s)}validateAndBuy(t,e){let i=this.calculateInGivenOut(t,e),s=this.validateTradeConstraints(t,i,e);return{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e){let i=this.calculateOutGivenIn(t,e),s=this.validateTradeConstraints(t,e,i);return{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(t,e){let i=super.calculateInGivenOut(t,e,{fee:this.fee}),s=D.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),pt.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=D.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),pt.toRaw(this.purchaseFee).toString());return BigInt(i)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let i=super.calculateOutGivenIn(t,e,{fee:this.fee}),s=D.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),pt.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=D.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),pt.toRaw(this.purchaseFee).toString());return BigInt(i)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),i=D.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=D.calculateBuybackLimit(e.toString(),pt.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let s=D.calculateBuybackPriceWithFee(i.toString(),e.toString(),pt.toRaw(this.buyBackFee).toString()),[n,r]=JSON.parse(s),a=F.big.pow10(t.decimalsIn+F.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(n)*a/BigInt(r)}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=D.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[s,n]=JSON.parse(i),r=F.big.pow10(F.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(s)*r/BigInt(n)}spotPriceInGivenOut(t){let e=F.big.toBigInt(1,t.decimalsOut),s=this.calculateInGivenOut(t,e)*F.big.pow10(F.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(s,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=F.big.toBigInt(1,t.decimalsIn),s=this.calculateOutGivenIn(t,e)*F.big.pow10(F.RUNTIME_DECIMALS-t.decimalsIn);return this.normalizeSpotPrice(s,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(s=>s.id!==this.hollarId),e=this.pegs[t],i=this.tokens[t].decimals;return this.isDefaultPeg(e)?[F.big.toBigInt(1,18).toString(),F.big.toBigInt(1,i).toString()]:e}isDefaultPeg(t){let[e,i]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&i==="1"}normalizeSpotPrice(t,e,i){let s=e-i;if(s===0)return t;let n=F.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var Qt=require("polkadot-api"),Ke=require("@polkadot-api/utils"),k=require("rxjs"),je=require("viem"),Zt=require("@galacticcouncil/common");var _t=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var Bt=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,s]=await this.client.readContract({abi:_t,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-s}};var{FeeUtils:de}=I,{H160:Xe}=Zt.h160,Ci=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],At=class extends E{ghoClient;stableClient;constructor(t,e,i){super(t,e),this.stableClient=i,this.ghoClient=new Bt(e)}getPoolType(){return"HSM"}getPoolId(t){return this.getPoolAddress("hsm:"+t)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(t){if(t){let e=t.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key.asHex()}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),i=new TextEncoder().encode(e),s=(0,Ke.toHex)(i);return(0,Qt.AccountId)(Zt.HYDRATION_SS58_PREFIX).dec(s)}async isSupported(){let t=this.api.query.HSM.Collaterals,e=await this.api.compatibilityToken;return t.isCompatible(Qt.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,s]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t),this.api.query.HSM.Collaterals.getEntries({at:"best"}),this.stableClient.getPools()]);if(i.length===0)return[];let n=this.getFacilitatorAddress(),r=Xe.fromAny(n),a=this.getHollarAddress(e),l=await this.ghoClient.getFacilitatorCapacity(a,r),c=i.map(async({keyArgs:p,value:g})=>{let[P]=p,{pool_id:f,max_buy_price_coefficient:A,max_in_holding:Y,purchase_fee:X,buy_back_fee:R,buyback_rate:q}=g,L=s.find(K=>K.id===f);if(L){let K=this.getPoolId(f),mt=await this.balance.getBalance(n,P);return{...L,address:K,type:"HSM",tokens:L.tokens.filter(Qe=>Qe.id!==f),hsmAddress:n,hsmMintCapacity:l,hollarId:t,hollarH160:a,collateralId:P,collateralBalance:mt.transferable,maxBuyPriceCoefficient:A,maxInHolding:Y,purchaseFee:de.fromPermill(X),buyBackFee:de.fromPermill(R),buyBackRate:de.fromPerbill(q)}}});return(await Promise.all(c)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:i}=t.log,s=e.map(r=>r.asHex()),n=i.asHex();try{let{eventName:r,args:a}=(0,je.decodeEventLog)({abi:_t,topics:s,data:n}),l=a.facilitatorAddress.toLowerCase();return{eventName:r,facilitator:l,key:`${r}:${l}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,k.map)(({payload:t})=>this.parseEvmLog(t)),(0,k.filter)(t=>t!==void 0),(0,k.filter)(({eventName:t})=>Ci.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async i=>{let s=[],[{hsmAddress:n,hollarH160:r}]=i,a=Xe.fromAny(n);if(a.toLowerCase()===e){let c=await this.ghoClient.getFacilitatorCapacity(r,a);for(let u of i)s.push({...u,hsmMintCapacity:c})}return s})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(n=>{let{tokens:r,collateralId:a}=n;r.find(c=>c.id===a).type==="Erc20"?e.push(a):t.push(a)});let[{hsmAddress:i}]=this.store.pools,s=[];if(t.length>0){let n=this.balance.watchTokensBalance(i);s.push(n)}if(e.length>0){let n=this.balance.watchErc20Balance(i,e);s.push(n)}return s.length>0?(0,k.combineLatest)(s).pipe((0,k.map)(n=>n.flat()),(0,k.pairwise)(),(0,k.map)(([n,r])=>this.balance.getDeltas(n,r)),this.watchGuard("balances")).subscribe(n=>{this.store.update(r=>{let a=[],l=new Map(r.map(c=>[c.collateralId,c]));return n.forEach(({id:c,balance:u})=>{let p=l.get(c);p&&(this.log.trace("balances",{id:c,balance:u}),a.push({...p,collateralBalance:u.transferable}))}),a})}):k.Subscription.EMPTY}subscribeStableswapUpdates(){return this.stableClient.getSubscriber().pipe(this.watchGuard("stableswap.updates")).subscribe(t=>{let e=new Map(t.map(i=>[i.id,i]));this.store.update(i=>{let s=[];for(let n of i){let r=e.get(n.id);r&&s.push({...n,fee:r.fee,tokens:r.tokens.filter(a=>a.id!==n.id),totalIssuance:r.totalIssuance,pegs:r.pegs,amplification:r.amplification,isRampPeriod:r.isRampPeriod})}return s})})}subscribeBalances(){return k.Subscription.EMPTY}subscribeUpdates(){let t=new k.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var te=class{static get(t){switch(t.type){case"Aave":return Ot.fromPool(t);case"XYK":return xt.fromPool(t);case"Omnipool":return yt.fromPool(t);case"LBP":return gt.fromPool(t);case"Stableswap":return nt.fromPool(t);case"HSM":return Tt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var Je=require("@galacticcouncil/common"),N=require("rxjs");var ee=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}};var{logger:Mi}=Je.log,ie=class extends ${evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=N.Subscription.EMPTY;omniSub=N.Subscription.EMPTY;stableSub=N.Subscription.EMPTY;hsmSub=N.Subscription.EMPTY;xykSub=N.Subscription.EMPTY;lbpSub=N.Subscription.EMPTY;isReady=!1;isDestroyed=new N.Subject;constructor(t,e){super(t),this.evm=e,this.aave=new It(t,e),this.omnipool=new Pt(t,e),this.stableswap=new St(t,e),this.hsm=new At(t,e,this.stableswap),this.xyk=new wt(t,e),this.lbp=new ft(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe((0,N.takeUntil)(this.isDestroyed)).subscribe(e=>{e.forEach(i=>{this.pools.set(i.address,i)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.active.has("Stableswap")||(Mi.info("[PoolContextProvider] auto-activating stableswap"),this.withStableswap()),this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let i=this.clients.find(s=>s.getPoolType()===e.type);if(i)return i.getPoolFees(t,e.address);throw new ee(e.type)}};0&&(module.exports={PoolContextProvider,PoolError,PoolFactory,PoolType,aave,hsm,lbp,omni,stable,xyk});
|