@galacticcouncil/sdk-next 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/aave/AaveLog.d.ts +4 -0
- package/build/aave/index.cjs +1 -1
- package/build/aave/index.d.ts +2 -0
- package/build/aave/index.mjs +1 -1
- package/build/aave/types.d.ts +7 -0
- package/build/evm/adapter.d.ts +3 -1
- package/build/evm/client.d.ts +3 -1
- package/build/evm/index.cjs +1 -1
- package/build/evm/index.mjs +1 -1
- package/build/gho/GhoTokenLog.d.ts +4 -0
- package/build/gho/index.d.ts +4 -2
- package/build/{pool/hsm → gho}/types.d.ts +1 -1
- package/build/index.cjs +1 -1
- package/build/index.d.ts +1 -0
- package/build/index.mjs +1 -1
- package/build/indexer/BlockFetcher.d.ts +10 -0
- package/build/indexer/Indexer.d.ts +19 -0
- package/build/indexer/IndexerStats.d.ts +33 -0
- package/build/indexer/RpcPool.d.ts +12 -0
- package/build/indexer/Semaphore.d.ts +9 -0
- package/build/indexer/index.cjs +1 -0
- package/build/indexer/index.d.ts +9 -0
- package/build/indexer/index.mjs +1 -0
- package/build/indexer/scale.d.ts +1 -0
- package/build/indexer/types.d.ts +17 -0
- package/build/oracle/MmOracleClient.d.ts +1 -1
- package/build/oracle/MmOracleLog.d.ts +4 -0
- package/build/oracle/abi.d.ts +11 -84
- package/build/oracle/index.d.ts +2 -0
- package/build/oracle/mappings.d.ts +25 -0
- package/build/oracle/types.d.ts +11 -0
- package/build/pool/aave/AavePoolClient.d.ts +0 -1
- package/build/pool/aave/types.d.ts +0 -6
- package/build/pool/hsm/HsmPoolClient.d.ts +0 -1
- package/build/pool/index.cjs +1 -1
- package/build/pool/index.mjs +1 -1
- package/build/pool/stable/StableSwap.d.ts +1 -1
- package/build/pool/stable/StableSwapClient.d.ts +12 -3
- package/build/pool/stable/StableSwapPeg.d.ts +7 -0
- package/build/pool/stable/types.d.ts +12 -1
- package/build/sor/index.cjs +1 -1
- package/build/sor/index.mjs +1 -1
- package/build/tx/TxBuilder.d.ts +2 -2
- package/build/tx/TxBuilderFactory.d.ts +3 -1
- package/build/tx/index.cjs +1 -1
- package/build/tx/index.mjs +1 -1
- package/package.json +6 -1
- package/build/pool/aave/AaveAbi.d.ts +0 -126
package/build/pool/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var ai=Object.create;var Lt=Object.defineProperty;var ni=Object.getOwnPropertyDescriptor;var ri=Object.getOwnPropertyNames;var oi=Object.getPrototypeOf,li=Object.prototype.hasOwnProperty;var G=(o,t)=>{for(var e in t)Lt(o,e,{get:t[e],enumerable:!0})},Se=(o,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ri(t))!li.call(o,s)&&s!==e&&Lt(o,s,{get:()=>t[s],enumerable:!(i=ni(t,s))||i.enumerable});return o};var ce=(o,t,e)=>(e=o!=null?ai(oi(o)):{},Se(t||!o||!o.__esModule?Lt(e,"default",{value:o,enumerable:!0}):e,o)),ci=o=>Se(Lt({},"__esModule",{value:!0}),o);var Gi={};G(Gi,{PoolContextProvider:()=>oe,PoolError:()=>Z,PoolFactory:()=>re,PoolType:()=>I,SnapshotPoolCtxProvider:()=>le,aave:()=>Pe,hsm:()=>ve,lbp:()=>de,omni:()=>ge,stable:()=>be,xyk:()=>fe});module.exports=ci(Gi);var de={};G(de,{LbpMath:()=>N,LbpPool:()=>St,LbpPoolClient:()=>wt});var z=require("@galacticcouncil/math-lbp"),N=class{static getSpotPrice(t,e,i,s,a){return(0,z.get_spot_price)(t,e,i,s,a)}static calculateInGivenOut(t,e,i,s,a){return(0,z.calculate_in_given_out)(t,e,i,s,a)}static calculateOutGivenIn(t,e,i,s,a){return(0,z.calculate_out_given_in)(t,e,i,s,a)}static calculateLinearWeights(t,e,i,s,a){return(0,z.calculate_linear_weights)(t,e,i,s,a)}static calculatePoolTradeFee(t,e,i){return(0,z.calculate_pool_trade_fee)(t,e,i)}};var lt=require("@galacticcouncil/common");var I=(n=>(n.Aave="Aave",n.LBP="LBP",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="XYK",n.HSM="HSM",n))(I||{}),Z=(c=>(c.UnknownError="UnknownError",c.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",c.InsufficientTradingAmount="InsufficientTradingAmount",c.InsufficientCollateral="InsufficientCollateral",c.MaxHoldingExceeded="MaxHoldingExceeded",c.MaxInRatioExceeded="MaxInRatioExceeded",c.MaxOutRatioExceeded="MaxOutRatioExceeded",c.TradeNotAllowed="TradeNotAllowed",c.MaxBuyBackExceeded="MaxBuyBackExceeded",c.MaxBuyPriceExceeded="MaxBuyPriceExceeded",c))(Z||{});var Dt={};G(Dt,{withTimeout:()=>ui});function ui(o,t,e="timeout"){return new Promise((i,s)=>{let a=setTimeout(()=>s(new Error(e)),t);o.then(n=>{clearTimeout(a),i(n)},n=>{clearTimeout(a),s(n)})})}var pi=require("@galacticcouncil/common");var x={};G(x,{FeeUtils:()=>ue,shiftNeg:()=>hi});var xe=ce(require("big.js"));var ue=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 hi(o,t){let e=(0,xe.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var yt={};G(yt,{findNestedKey:()=>gi,findNestedObj:()=>bi,jsonFormatter:()=>fi});var gi=(o,t)=>{let e=[];return JSON.stringify(o,(i,s)=>(s&&s[t]&&e.push(s),s)),e[0]},bi=(o,t,e)=>{let i;return JSON.stringify(o,(s,a)=>(a&&a[t]===e&&(i=a),a)),i},fi=(o,t)=>typeof t=="bigint"?t.toString():t;var tt={};G(tt,{calculateBuyFee:()=>Si,calculateDiffToAvg:()=>Pi,calculateDiffToRef:()=>yi,calculateSellFee:()=>vi});var V=ce(require("big.js"));function Pi(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 yi(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 vi(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 Si(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 vt=(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 qt=(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 xi=qt(()=>"illegal argument(s)"),we=o=>{throw new xi(o)};var wi=qt(()=>"index out of bounds"),pe=o=>{throw new wi(o)},Gt=(o,t,e)=>(o<t||o>=e)&&pe(o);var Oe=23283064365386963e-26,Nt=class{float(t=1){return this.int()*Oe*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*Oe-.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 zt=class extends Nt{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 Ie=new zt(Math.random);var Te=o=>o!=null&&typeof o!="function"&&o.length!==void 0;var _e=Object.getPrototypeOf({}),Vt="function",Ae="string",ot=(o,t)=>{let e;if(o===t)return!0;if(o!=null){if(typeof o.equiv===Vt)return o.equiv(t)}else return o==t;if(t!=null){if(typeof t.equiv===Vt)return t.equiv(o)}else return o==t;return typeof o===Ae||typeof t===Ae?!1:(e=Object.getPrototypeOf(o),(e==null||e===_e)&&(e=Object.getPrototypeOf(t),e==null||e===_e)?_i(o,t):typeof o!==Vt&&o.length!==void 0&&typeof t!==Vt&&t.length!==void 0?Oi(o,t):o instanceof Set&&t instanceof Set?Ii(o,t):o instanceof Map&&t instanceof Map?Ti(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)},Oi=(o,t,e=ot)=>{let i=o.length;if(i===t.length)for(;i-- >0&&e(o[i],t[i]););return i<0},Ii=(o,t,e=ot)=>o.size===t.size&&e([...o.keys()].sort(),[...t.keys()].sort()),Ti=(o,t,e=ot)=>o.size===t.size&&e([...o].sort(),[...t].sort()),_i=(o,t,e=ot)=>{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 me=class{value;constructor(t){this.value=t}deref(){return this.value}};var Be=o=>o instanceof me;var $t=class o{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Fe("next",this._head)}reverseIterator(){return Fe("prev",this.tail)}clear(){this.release()}compare(t,e=vt){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,a=t._head,n=0;for(;i-- >0&&n===0;)n=e(s.value,a.value),s=s.next,a=a.next;return n}}concat(...t){let e=this.copy();for(let i of t)e.into(i);return e}equiv(t){if(!(t instanceof o||Te(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(!ot(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||vt;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&&!Be(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&&pe(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*Fe(o,t){for(;t;)yield t.value,t=t[o]}var Ut=class o extends $t{_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):(Gt(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):(Gt(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),a=n=>({first(){return n.value},next(){return n!==s&&n.next?a(n.next):void 0}});return i?a(i):void 0}shuffle(t,e=Ie){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)&&we("invalid indices: ${from} / ${to}");let a=new o,n=this.nthCell(i);for(;n&&++i<=s;)a.push(n.value),n=n.next;return a}sort(t=vt){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 a=i,n=0;for(let l=0;l<e&&(n++,a=a.next,!!a);l++);let r=e;for(;n>0||r>0&&a;){let l;n===0?(l=a,a=a.next,r--):!a||r===0||t(i.value,a.value)<=0?(l=i,i=i.next,n--):(l=a,a=a.next,r--),this._tail?this._tail.next=l:this._head=l,l.prev=this._tail,this._tail=l}i=a}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),Gt(t,0,this._length),s=this.nthCellUnsafe(t)):s=t;let a=new o;if(e>0)for(;s&&e-- >0;)this.remove(s),a.push(s.value),s=s.next;else s&&(s=s.next);if(i)if(s)for(let n of i)this.insertBefore(s,n);else for(let n of i)this.push(n);return a}};var Wt=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 Ut,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),a=Math.max(0,i-(s?s.value.s:0));return this._size+=a,this.ensureSize()?this.doSetEntry(s,t,e,i):this._size-=a,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 st=class o extends Wt{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),a=this.map.get(t),n=Math.max(0,s-(a?a.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(a,t,e,s,i):this._size-=n,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,a=this.opts.ttl){let n=Date.now()+a;t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=s,t.value.t=n,this.items.asTail(t)):(this.items.push({k:e,v:i,s,t:n,ttl:a}),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 Yt=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 a=new Map,n=s!==void 0?new st(null,{ttl:s}):new st;return{get:(...c)=>{let p=i(...c);if(a.has(p)){this.log("[live]",t,p);let b=a.get(p);return Promise.resolve(b)}if(n.has(p))return this.log("[memo]",t,p),n.get(p);this.log("[fetch]",t,p);let g=e(...c).catch(b=>{throw n.delete(p),b});return n.set(p,g),g},set:(c,...p)=>{let g=i(...p);this.log("[set-live]",t,g),a.set(g,c)},clear:()=>{this.log("[clear]",t),a.clear(),n.release()}}}};var{FeeUtils:ke}=x,St=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(n=>[n.id,n])),s=i.get(t),a=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,weightIn:s.weight,weightOut:a.weight}}validateAndBuy(t,e,i){let s=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let n=t.balanceOut/this.maxOutRatio;if(e>n&&a.push("MaxOutRatioExceeded"),s===t.assetOut){let r=this.calculateTradeFee(e,i),l=ke.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),u=e+r,c=this.calculateInGivenOut(t,u),p=t.balanceIn/this.maxInRatio;return c>p&&a.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:l,errors:a}}else{let r=this.calculateInGivenOut(t,e),l=t.balanceIn/this.maxInRatio;return r>l&&a.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:a}}}validateAndSell(t,e,i){let s=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let n=t.balanceIn/this.maxInRatio;if(e>n&&a.push("MaxInRatioExceeded"),s===t.assetIn){let r=this.calculateOutGivenIn(t,e),l=t.balanceOut/this.maxOutRatio;return r>l&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:a}}else{let r=this.calculateOutGivenIn(t,e),l=this.calculateTradeFee(r,i),u=ke.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),c=r-l,p=t.balanceOut/this.maxOutRatio;return c>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:c,feePct:u,errors:a}}}calculateInGivenOut(t,e){let i=N.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=N.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=N.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),lt.big.toBigInt(1,lt.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=N.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),lt.big.toBigInt(1,lt.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let i=N.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var He=require("polkadot-api"),et=require("rxjs");var Ee=(o,t=new Map)=>e=>{let i;return t.has(e)?t.get(e):(t.set(e,i=o(e)),i)};var P=require("rxjs"),m=require("rxjs/operators");var ut=require("@galacticcouncil/descriptors");var Ce=require("@galacticcouncil/common"),ct=require("rxjs");var j=require("rxjs"),T=require("rxjs/operators");function Re(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)(a=>(0,j.timer)(a.delayMs).pipe((0,T.switchMap)(i),(0,T.map)(n=>({state:n,delayMs:t})))),(0,T.skip)(1),(0,T.map)(a=>a.state),(0,T.distinctUntilChanged)(),(0,T.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Ai}=Ce.log,Xt=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,ct.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Re(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,ct.tap)({error:i=>Ai.error(t,i)}),(0,ct.shareReplay)({bufferSize:1,refCount:!0}))}};var $=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(ut.hydration),this.apiNext=this.client.getTypedApi(ut.hydrationNext),this.apiIce=this.client.getTypedApi(ut.hydrationIce),this.watcher=Xt.getInstance(this.client),this.at=e??"best"}};var Bi=require("polkadot-api/ws"),Fi=require("polkadot-api/logs-provider");var ki=require("polkadot-api");var Me=require("@galacticcouncil/common"),C=require("rxjs"),d=require("rxjs/operators");var{logger:pt}=Me.log,xt=class extends ${erc20Ids=null;constructor(t,e){super(t,e)}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:this.at});return this.getBreakdown(i)}async getTokenBalance(t,e){let s=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});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)(a=>(0,C.concat)(a.pipe((0,d.take)(1)),a.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:()=>pt.debug("balance: subscribe",t),error:e=>pt.error("balance",e)}),(0,d.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,C.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,d.map)(({value:i})=>({id:0,balance:this.getBreakdown(i.data)})),(0,d.tap)({error:i=>pt.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return(0,C.defer)(()=>i.watchValue(t,e,{at:"best"})).pipe((0,d.map)(({value:s})=>({id:e,balance:this.getBreakdown(s)})),(0,d.tap)({error:s=>pt.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(a=>{let[n,r]=a.args;s.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(a=>{let[n,r]=a.args;s.push({id:r,balance:this.getBreakdown(a.value)})}),s}),(0,d.tap)({error:i=>pt.error("balance(tokens)",i)}))}watchErc20Balance(t,e){let i=async()=>{if(this.erc20Ids)return this.erc20Ids;let a=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=a.filter(({value:n})=>n.asset_type.type==="Erc20").map(({keyArgs:n})=>{let[r]=n;return r}),this.erc20Ids},s=async a=>(await Promise.all(a.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)(a=>this.watcher.bestBlock$.pipe((0,d.switchMap)(()=>(0,C.from)(s(a))))),(0,d.startWith)([]),(0,d.bufferCount)(2,1),(0,d.map)(([a,n],r)=>r===0?n.filter(l=>l.balance.total>0n):this.getDeltas(a,n)),(0,d.distinctUntilChanged)((a,n)=>n.length===0),(0,d.tap)({error:a=>pt.error("balance(erc20)",a)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});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=(a,n)=>a!==void 0&&n!==void 0&&a.transferable===n.transferable&&a.total===n.total,s=t.reduce((a,n)=>(a.set(n.id,n.balance),a),new Map);return e.filter(a=>!i(a.balance,s.get(a.id)))}};var Le=require("rxjs"),Kt=class{store$=new Le.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),a=e.slice(),n=new Set;for(let r of s){let l=i.get(r.address);l===void 0?(i.set(r.address,a.length),a.push(r)):a[l]=r,n.add(r.address)}this.changeset=n,this.store$.next(a)}).catch(console.error)}destroy(){this.store$.complete()}};var De=require("@galacticcouncil/common");var Ei={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:jt}=De.log,Jt=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${Ei[this.type]})`,10)}trace(t,...e){jt.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){jt.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){jt.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){jt.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:Ri}=Dt,Ci=3e3,E=class extends ${evm;balance;store=new Kt;log;shared$;resync$=new P.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new st(null,{ttl:6*1e3});memPools=Ee(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e,i){super(t,i),this.evm=e,this.balance=new xt(t,i),this.log=new Jt(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){let e=(await this.getMemPools()).filter(i=>this.hasValidAssets(i));return this.store.set(e),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,P.defer)(()=>{let t=new P.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,m.switchMap)(()=>{let e=new P.Subscription;return(0,P.from)(Ri(this.getMemPools(),6e4,"getMemPools stalled")).pipe((0,m.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,m.map)(s=>s.filter(a=>this.hasValidAssets(a))),(0,m.tap)(s=>this.store.set(s)),(0,m.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),P.EMPTY))).pipe((0,m.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,m.switchMap)(s=>(0,P.merge)((0,P.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 P.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 a=this.balance.watchSystemBalance(i);s.push(a)}if(this.hasErc20Asset(e)){let a=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),n=this.balance.watchErc20Balance(i,a);s.push(n)}return(0,P.combineLatest)(s).pipe((0,m.map)(a=>a.flat()),(0,m.pairwise)(),(0,m.map)(([a,n])=>this.balance.getDeltas(a,n)),(0,m.filter)(a=>a.length>0),(0,m.map)(a=>[i,a]))});return(0,P.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(a=>[a.address,a]));for(let[a,n]of e){let r=s.get(a);if(r){let l=r.tokens.map(u=>{let c=n.find(p=>p.id===u.id);return c&&u.id!==r.id?{...u,balance:c.balance.transferable}:u});i.push({...r,tokens:l})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<Ci||(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)(([r,l])=>r==="offline"&&l==="online"),(0,m.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,m.catchError)(r=>(this.log.error("watchdog_recovery_error",r),P.EMPTY)),(0,m.repeat)({delay:1e3})),a=this.watcher.finalizedBlock$.pipe((0,m.pairwise)(),(0,m.tap)(([r,l])=>{let u=Number(r.number),c=Number(l.number),p=c-u;p>=3&&(this.log.debug("watchdog_gap",{from:u,to:c,gap:p}),this.requestResync())}),(0,m.catchError)(r=>(this.log.error("watchdog_gap_error",r),P.EMPTY)),(0,m.repeat)({delay:1e3})),n=(0,P.interval)(36e5).pipe((0,m.tap)(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),(0,m.catchError)(r=>(this.log.error("watchdog_periodic_error",r),P.EMPTY)),(0,m.repeat)({delay:1e3}));return(0,P.merge)(s,a,n).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)(()=>P.EMPTY))}};var wt=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:a,final_weight:n}=t,r=N.calculateLinearWeights(i?i.toString():"0",s?s.toString():"0",a.toString(),n.toString(),e.toString()),l=BigInt(r),u=this.MAX_FINAL_WEIGHT-BigInt(l);return[l,u]}async isSupported(){return(await this.api.getStaticApis()).compat.query.LBP.PoolData.isCompatible(He.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:this.at}),this.api.query.ParachainSystem.ValidationData.getValue({at:this.at}),this.getPoolLimits()]),s=e?.relay_parent_number||0,a=t.filter(({value:n})=>e&&this.isActivePool(n,s)).map(async({keyArgs:n,value:r})=>{let[l]=n,u=l.toString(),c=await this.getPoolDelta(u,r,s);return{address:u,type:"LBP",fee:r.fee,...c,...i}});return Promise.all(a)}async getPoolDelta(t,e,i){let{assets:s,repay_target:a,fee_collector:n}=e,[r,l]=this.getPoolWeights(e,i),[u,c]=s,[p,g,b,f,S]=await Promise.all([this.isRepayFeeApplied(u,a,n.toString()),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u,{at:this.at}),this.balance.getBalance(t,c),this.api.query.AssetRegistry.Assets.getValue(c,{at:this.at})]);return{repayFeeApply:p,tokens:[{id:u,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:g.transferable,weight:r,type:b?.asset_type.type},{id:c,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:f.transferable,weight:l,type:S?.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(a=>a.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:i.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue({at:"best"}).pipe((0,et.map)(({value:t})=>t),(0,et.filter)(t=>t!==void 0),(0,et.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 a=this.poolsData.get(s.address);if(a){let{assets:n,repay_target:r,fee_collector:l}=a,[u]=n,[c,p]=this.getPoolWeights(a,t),[g,b]=s.tokens,f=[{...g,weight:c},{...b,weight:p}],S=await this.isRepayFeeApplied(u,r,l.toString());i.push({...s,tokens:f,repayFeeApply:S})}}return i})})}subscribeUpdates(){let t=new et.Subscription;return t.add(this.subscribeValidationData()),t}};var ge={};G(ge,{OmniMath:()=>v,OmniPool:()=>Ot,OmniPoolClient:()=>It,OmniPoolFee:()=>nt,getEmaKey:()=>Zt,getEmaPair:()=>mt});var h=require("@galacticcouncil/math-omnipool"),at=ce(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,a,n,r,l,u,c){return(0,h.calculate_in_given_out)(t,e,i,s,a,n,r,l,u,c)}static calculateLrnaInGivenOut(t,e,i,s,a,n){return(0,h.calculate_lrna_in_given_out)(t,e,i,s,a,n)}static calculateOutGivenIn(t,e,i,s,a,n,r,l,u,c){return(0,h.calculate_out_given_in)(t,e,i,s,a,n,r,l,u,c)}static calculateOutGivenLrnaIn(t,e,i,s,a,n){return(0,h.calculate_out_given_lrna_in)(t,e,i,s,a,n)}static calculateShares(t,e,i,s){return(0,h.calculate_shares)(t,e,i,s)}static calculateLiquidityOut(t,e,i,s,a,n,r,l){return(0,h.calculate_liquidity_out)(t,e,i,s,a,n,r,l)}static calculateLiquidityLRNAOut(t,e,i,s,a,n,r,l){return(0,h.calculate_liquidity_lrna_out)(t,e,i,s,a,n,r,l)}static calculateCapDifference(t,e,i,s){let a=(0,at.default)(e),n=(0,at.default)(t),r=(0,at.default)(s),l=(0,at.default)(i),u=(0,at.default)(10).pow(18),c=l.div(u);if(a.div(r).lt(c)){let g=c.times(r).minus(a).times(n),b=a.times((0,at.default)(1).minus(c));return g.div(b).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,a,n,r,l,u,c,p){return(0,h.recalculate_asset_fee)(t,e,i,s,a,n,r,l,u,c,p)}static recalculateProtocolFee(t,e,i,s,a,n,r,l,u,c,p){return(0,h.recalculate_protocol_fee)(t,e,i,s,a,n,r,l,u,c,p)}static verifyAssetCap(t,e,i,s){return(0,h.verify_asset_cap)(t,e,i,s)}};var qe=require("@galacticcouncil/common");var{FeeUtils:W}=x,Ot=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(n=>[n.id,n])),s=i.get(t),a=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:s.hubReserves,hubReservesOut:a.hubReserves,sharesIn:s.shares,sharesOut:a.shares,decimalsIn:s.decimals,decimalsOut:a.decimals,balanceIn:s.balance,balanceOut:a.balance,tradeableIn:s.tradeable,tradeableOut:a.tradeable,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,i),n=s===0n?0:tt.calculateBuyFee(s,a),r=[],l=v.isSellAllowed(t.tradeableIn),u=v.isBuyAllowed(t.tradeableOut);(!l||!u)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&r.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return a>p&&r.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:n,errors:r}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,i),n=tt.calculateSellFee(s,a),r=[],l=v.isSellAllowed(t.tradeableIn),u=v.isBuyAllowed(t.tradeableOut);(!l||!u)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&r.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return a>p&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:n,errors:r}}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"),a=BigInt(s);return a<0n?0n:a}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"),a=BigInt(s);return a<0n?0n:a}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"),a=BigInt(s);return a<0n?0n:a}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"),a=BigInt(s);return a<0n?0n:a}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 a=qe.big.pow10(Math.abs(s));return s>0?t*a:t/a}};var J=require("polkadot-api"),ze=require("@polkadot-api/utils"),y=require("rxjs"),Ve=require("@galacticcouncil/common");var{FeeUtils:_}=x,nt=class o{static compute(t,e,i,s,a,n,r,l){let u=t.assetIn,[c,p,g]=o.getAssetFee(t,e,i,s,n),b=0,f=0,S=0;u!==1&&([b,f,S]=o.getProtocolFee(t,e,i,a,r));let Y=c+b,X=g+S;return{assetFee:_.fromPermill(p),protocolFee:_.fromPermill(f),maxSlipFee:_.fromPermill(l),min:_.fromPermill(Y),max:_.fromPermill(X)}}static getAssetFee(t,e,i,s,a){let{assetOut:n,balanceOut:r}=t,{min_fee:l,max_fee:u,decay:c,amplification:p}=a;if(!i||!s)return[l,l,u];let g=_.fromPermill(l),b=_.fromPermill(u),[f]=s,{asset_fee:S,timestamp:Y}=i,X=Math.max(1,e-Y),K=f.volume.b_in.toString(),H=f.volume.b_out.toString(),q=f.liquidity.b.toString();n===0&&(K=f.volume.a_in.toString(),H=f.volume.a_out.toString(),q=f.liquidity.a.toString());let it=_.fromPermill(S),Pt=v.recalculateAssetFee(K,H,q,"9",r.toString(),_.toRaw(it).toString(),X.toString(),_.toRaw(g).toString(),_.toRaw(b).toString(),c.toString(),p.toString());return[l,Number(Pt)*1e6,u]}static getProtocolFee(t,e,i,s,a){let{assetIn:n,balanceIn:r}=t,{min_fee:l,max_fee:u,decay:c,amplification:p}=a;if(!i||!s)return[l,l,u];let g=_.fromPermill(l),b=_.fromPermill(u),[f]=s,{protocol_fee:S,timestamp:Y}=i,X=Math.max(1,e-Y),K=f.volume.b_in.toString(),H=f.volume.b_out.toString(),q=f.liquidity.b.toString();n===0&&(K=f.volume.a_in.toString(),H=f.volume.a_out.toString(),q=f.liquidity.a.toString());let it=_.fromPermill(S),Pt=v.recalculateProtocolFee(K,H,q,"9",r.toString(),_.toRaw(it).toString(),X.toString(),_.toRaw(g).toString(),_.toRaw(b).toString(),c.toString(),p.toString());return[l,Number(Pt)*1e6,u]}};var mt=o=>o===0?[0,1]:[1,o],Zt=o=>mt(o).join(":");var{FeeUtils:he}=x,Ge=J.Binary.toHex(J.Binary.fromText("omnipool")),Ne=(0,J.Enum)("Short"),It=class extends E{queryBus=new Yt;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:this.at}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:this.at}),t=>String(t),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:this.at}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(Ge,t,Ne,{at:this.at}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,ze.toHex)(e);return(0,J.AccountId)(Ve.HYDRATION_SS58_PREFIX).dec(i)}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(){return(await this.api.getStaticApis()).compat.query.Omnipool.Assets.isCompatible(J.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,s,a,n,r,l]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:this.at}),this.api.query.Omnipool.HubAssetTradability.getValue({at:this.at}),this.api.query.AssetRegistry.Assets.getValue(t,{at:this.at}),this.balance.getBalance(e,t),this.getPoolLimits(),this.api.query.System.Number.getValue({at:this.at})]);this.block=l;let u=i.map(async({keyArgs:p,value:g})=>{let[b]=p,{hub_reserve:f,shares:S,tradable:Y,cap:X,protocol_shares:K}=g,[H,q]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(b,{at:this.at}),this.balance.getBalance(e,b)]);return{id:b,decimals:H?.decimals,existentialDeposit:H?.existential_deposit,balance:q.transferable,cap:X,hubReserves:f,protocolShares:K,shares:S,tradeable:Y,type:H?.asset_type.type}}),c=await Promise.all(u);return c.push({id:t,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:n.transferable,tradeable:s,type:a?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:c,...r}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,a=await this.maxSlipFee.get()??0,n=await this.dynamicFeesConfig.get(e);if(n?.type==="Fixed"){let{asset_fee:g,protocol_fee:b}=n.value;return{assetFee:he.fromPermill(g),protocolFee:he.fromPermill(b),maxSlipFee:he.fromPermill(a)}}let[r,l,u,c,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(mt(e)),this.emaOracles.get(mt(i)),n?n.value.asset_fee_params:this.api.constants.DynamicFees.AssetFeeParameters(),n?n.value.protocol_fee_params:this.api.constants.DynamicFees.ProtocolFeeParameters()]);return nt.compute(t,this.block,r,l,u,c,p,a)}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(s=>s.id).map(s=>mt(s)).map(s=>this.api.query.EmaOracle.Oracles.watchValue(Ge,s,Ne,{at:"best"}).pipe((0,y.map)(({value:a})=>a),(0,y.filter)(a=>a!==void 0),(0,y.map)((a,n)=>({value:a,index:n})),(0,y.tap)(({index:a})=>{a>0&&this.log.trace("emaOracle.Oracles",s.join(":"))}),(0,y.map)(({value:a})=>({pair:s,value:a}))));return(0,y.merge)(...i).pipe((0,y.finalize)(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(s=>{let{pair:a,value:n}=s;this.emaOracles.set(n,a)})}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((a,n)=>{let[r]=n.args;return a.set(r,n.value),a},new Map),s=e.tokens.map(a=>{let n=i?.get(a.id);return n?this.updateTokenState(a,n):a});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:a,cap:n,protocol_shares:r}=e;return{...t,cap:n,hubReserves:i,protocolShares:r,shares:s,tradeable:a}}};var be={};G(be,{StableMath:()=>B,StableSwap:()=>rt,StableSwapClient:()=>_t});var w=require("@galacticcouncil/math-stableswap"),B=class{static getPoolAddress(t){return(0,w.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,a){return(0,w.calculate_amplification)(t,e,i,s,a)}static calculateInGivenOut(t,e,i,s,a,n,r){return(0,w.calculate_in_given_out)(t,e,i,s,a,n,r)}static calculateAddOneAsset(t,e,i,s,a,n,r){return(0,w.calculate_add_one_asset)(t,e,i,s,a,n,r)}static calculateSharesForAmount(t,e,i,s,a,n,r){return(0,w.calculate_shares_for_amount)(t,e,i,s,a,n,r)}static calculateOutGivenIn(t,e,i,s,a,n,r){return(0,w.calculate_out_given_in)(t,e,i,s,a,n,r)}static calculateLiquidityOutOneAsset(t,e,i,s,a,n,r){return(0,w.calculate_liquidity_out_one_asset)(t,e,i,s,a,n,r)}static calculateShares(t,e,i,s,a,n){return(0,w.calculate_shares)(t,e,i,s,a,n)}static calculateSpotPriceWithFee(t,e,i,s,a,n,r,l){return(0,w.calculate_spot_price_with_fee)(t,e,i,s,a,n,r,l)}static recalculatePegs(t,e,i,s,a,n){let r=(0,w.recalculate_peg)(t,e,i,s,a,n);return JSON.parse(r)}};var Tt=require("@galacticcouncil/common");var{FeeUtils:dt}=x,rt=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(n=>[n.id,n])),s=i.get(t),a=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:a.tradeable,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,i),n=s===0n?0:tt.calculateBuyFee(s,a),r=[],l=v.isSellAllowed(t.tradeableIn),u=v.isBuyAllowed(t.tradeableOut);return(!l||!u)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:n,errors:r}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,i),n=tt.calculateSellFee(s,a),r=[],l=v.isSellAllowed(t.tradeableIn),u=v.isBuyAllowed(t.tradeableOut);return(!l||!u)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:n,errors:r}}calculateIn(t,e,i){let s=B.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?dt.toRaw(i.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateAddOneAsset(t,e,i){let s=B.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?dt.toRaw(i.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateSharesForAmount(t,e,i){let s=B.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?dt.toRaw(i.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}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=B.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=B.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?dt.toRaw(i.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateWithdrawOneAsset(t,e,i){let s=B.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?dt.toRaw(i.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateShares(t,e,i){let s=B.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?dt.toRaw(i.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}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=B.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,yt.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],yt.jsonFormatter)}normalizeSpot(t,e,i,s,a){return e?t*Tt.big.pow10(Tt.RUNTIME_DECIMALS-a):i?t/Tt.big.pow10(a-s):t}};var ee=require("polkadot-api"),$e=require("@polkadot-api/utils"),Ue=require("@noble/hashes/blake2b"),R=require("rxjs"),ie=require("@galacticcouncil/common");var{FeeUtils:Mi}=x,_t=class extends E{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=B.getPoolAddress(t),i=(0,Ue.blake2b)(e,{dkLen:32}),s=(0,$e.toHex)(i);return(0,ee.AccountId)(ie.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:a,final_block:n}=t,r=B.calculateAmplification(i.toString(),s.toString(),a.toString(),n.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 a=>{let[n,r,l]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,a,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(a,{at:this.at}),this.balance.getBalance(i,a)]);return{id:a,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:l.transferable,tradeable:n,type:r?.asset_type.type}});return Promise.all(s)}async isSupported(){return(await this.api.getStaticApis()).compat.query.Stableswap.Pools.isCompatible(ee.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:this.at}),this.api.query.System.Number.getValue({at:this.at}),this.getPoolLimits()]),s=t.map(async({keyArgs:a,value:n})=>{let[r]=a,l=this.getPoolAddress(r),[u,c,p]=await Promise.all([this.getPoolTokens(r,n),this.api.query.Stableswap.PoolPegs.getValue(r,{at:this.at}),this.api.query.Tokens.TotalIssuance.getValue(r,{at:this.at})]),g=this.getPoolAmplification(n,e),b=c?this.getRecentPegs(c):this.getDefaultPegs(n);return u.push({id:r,tradeable:15,balance:p,decimals:ie.RUNTIME_DECIMALS}),this.poolsData.set(r,n),{address:l,id:r,type:"Stableswap",fee:Mi.fromPermill(n.fee),tokens:u,totalIssuance:p,pegs:b,...i,...g}});return Promise.all(s)}async getPoolFees(t,e){return{fee:this.store.pools.find(s=>s.address===e).fee}}getDefaultPegs(t){return B.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([i,s])=>s.map(a=>a.toString()))}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,{at:"best"}).pipe((0,R.map)(({value:s})=>s),(0,R.map)((s,a)=>({value:s,index:a})),(0,R.tap)(({index:s,value:a})=>{s>0&&this.log.trace("tokens.TotalIssuance",i,a)}),(0,R.map)(({value:s})=>({id:i,value:s}))));return(0,R.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:s,value:a}=i;this.store.update(n=>{let r=[];return n.filter(l=>l.id===s).forEach(l=>{let u=l.tokens.map(c=>c.id===s?{...c,balance:a}:c);r.push({...l,tokens:u,totalIssuance:a})}),r})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,R.distinctUntilChanged)((t,e)=>!e.deltas),(0,R.map)((t,e)=>({value:t,index:e})),(0,R.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(a=>[a.id,a]));return t?.upserted.forEach(({args:a,value:n})=>{let[r]=a,l=s.get(r);if(l){let u=this.getRecentPegs(n);i.push({...l,pegs:u})}}),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 a=this.poolsData.get(s.id);if(a){let n=this.getPoolAmplification(a,t);i.push({...s,...n})}}),i})})}subscribeUpdates(){let t=new R.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 fe={};G(fe,{XykMath:()=>Q,XykPool:()=>At,XykPoolClient:()=>Bt});var O=require("@galacticcouncil/math-xyk"),Q=class{static getSpotPrice(t,e,i){return(0,O.get_spot_price)(t,e,i)}static calculateInGivenOut(t,e,i){return(0,O.calculate_in_given_out)(t,e,i)}static calculateOutGivenIn(t,e,i){return(0,O.calculate_out_given_in)(t,e,i)}static calculatePoolTradeFee(t,e,i){return(0,O.calculate_pool_trade_fee)(t,e,i)}static calculateLiquidityIn(t,e,i){return(0,O.calculate_liquidity_in)(t,e,i)}static calculateSpotPrice(t,e){return(0,O.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,i,s){return(0,O.calculate_spot_price_with_fee)(t,e,i,s)}static calculateShares(t,e,i){return(0,O.calculate_shares)(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,s){return(0,O.calculate_liquidity_out_asset_a)(t,e,i,s)}static calculateLiquidityOutAssetB(t,e,i,s){return(0,O.calculate_liquidity_out_asset_b)(t,e,i,s)}};var Ye=require("@galacticcouncil/common");var{FeeUtils:We}=x,At=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(n=>[n.id,n])),s=i.get(t),a=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:s.decimals,decimalsOut:a.decimals,balanceIn:s.balance,balanceOut:a.balance,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),a=this.calculateTradeFee(s,i),n=We.toPct(i.exchangeFee),r=s+a,l=[];(e<this.minTradingLimit||s<t.assetInEd)&&l.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&l.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return r>c&&l.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:n,errors:l}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),a=this.calculateTradeFee(s,i),n=We.toPct(i.exchangeFee),r=s-a,l=[];(e<this.minTradingLimit||s<t.assetOutEd)&&l.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&l.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return r>c&&l.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:n,errors:l}}calculateInGivenOut(t,e){let i=Q.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e){let i=Q.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){let e=Q.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=Q.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=Q.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 a=Ye.big.pow10(Math.abs(s));return s>0?t*a:t/a}};var Xe=require("polkadot-api"),Ke=require("rxjs");var Bt=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(){return(await this.api.getStaticApis()).compat.query.XYK.PoolAssets.isCompatible(Xe.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries({at:this.at}),this.getPoolLimits()]),i=t.map(async({keyArgs:s,value:a})=>{let[n]=s,[r,l]=a,[u,c,p,g]=await Promise.all([this.balance.getBalance(n,r),this.api.query.AssetRegistry.Assets.getValue(r,{at:this.at}),this.balance.getBalance(n,l),this.api.query.AssetRegistry.Assets.getValue(l,{at:this.at})]);return{address:n,type:"XYK",tokens:[{id:r,decimals:c?.decimals||this.decimals.get(r),existentialDeposit:c?.existential_deposit,balance:u.transferable,type:c?.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 Ke.Subscription.EMPTY}};var Pe={};G(Pe,{AavePool:()=>Ft,AavePoolClient:()=>kt});var ht=require("@galacticcouncil/common");var Ft=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(n=>[n.id,n])),s=i.get(t),a=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),a=[];return e>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:a}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),a=[];return s>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:a}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return ht.big.toBigInt(1,ht.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return ht.big.toBigInt(1,ht.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var se=require("polkadot-api"),Je=require("@polkadot-api/utils"),M=require("rxjs"),Qe=require("viem"),ae=require("@galacticcouncil/common");var je=[{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:Li}=ae.erc20,Di=["Supply","Withdraw","Repay","Borrow"],kt=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")),a=(0,Je.toHex)(s);return(0,se.AccountId)(ae.HYDRATION_SS58_PREFIX).dec(a)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:this.at})).map(async({reserve:i,atoken:s,liqudity_in:a,liqudity_out:n})=>{let[r,l,u,c]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(i,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(s,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(s,{at:this.at})]);return{address:this.getPoolId(i,s),type:"Aave",tokens:[{id:i,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:a,location:l,type:r?.asset_type.type},{id:s,decimals:u?.decimals,existentialDeposit:u?.existential_deposit,balance:n,location:c,type:u?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:s,liqudity_out:a}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:this.at});return t.tokens.map(n=>{let r=n.id===e.id?s:a;return{...n,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}throw new Error("Invalid aave reserve multilocation")}return Li.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,a=se.Binary.toHex(i);try{let{eventName:n,args:r}=(0,Qe.decodeEventLog)({abi:je,topics:s,data:a}),l=r.reserve.toLowerCase();return{eventName:n,reserve:l,key:`${n}:${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,M.mergeMap)(({events:i})=>i),(0,M.map)(({payload:i})=>this.parseRouterLog(i)),(0,M.filter)(({assetIn:i,assetOut:s})=>e.includes(i)||e.includes(s)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:s,key:a})=>{this.log.trace("router.Executed",a),this.store.update(async n=>{let r=[];for(let l of n){let[u,c]=l.tokens;if(c.id===i||c.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,M.mergeMap)(({events:t})=>t),(0,M.map)(({payload:t})=>this.parseEvmLog(t)),(0,M.filter)(t=>t!==void 0),(0,M.filter)(({eventName:t})=>Di.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 a of i){let[n]=a.tokens;if(this.getReserveH160Id(n).toLowerCase()===t){let l=await this.getPoolDelta(a);s.push({...a,tokens:l})}}return s})})}subscribeBalances(){return M.Subscription.EMPTY}subscribeUpdates(){let t=new M.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var ve={};G(ve,{HsmMath:()=>L,HsmPool:()=>Et,HsmPoolClient:()=>Mt});var F=require("@galacticcouncil/math-hsm"),L=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,F.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,F.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,F.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,F.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,F.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,F.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,F.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,F.calculate_max_price)(t,e)}};var k=require("@galacticcouncil/common");var{FeeUtils:gt}=x,Et=class o extends rt{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),a=super.calculateInGivenOut(s,e,{fee:this.fee}),n=this.calculateBuybackLimit(t);e>n&&i.push("MaxBuyBackExceeded");let r=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,a)>r&&i.push("MaxBuyPriceExceeded"),a>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=L.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),gt.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=L.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),gt.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=L.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),gt.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=L.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),gt.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=L.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=L.calculateBuybackLimit(e.toString(),gt.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let s=L.calculateBuybackPriceWithFee(i.toString(),e.toString(),gt.toRaw(this.buyBackFee).toString()),[a,n]=JSON.parse(s),r=k.big.pow10(t.decimalsIn+k.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(a)*r/BigInt(n)}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=L.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[s,a]=JSON.parse(i),n=k.big.pow10(k.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(s)*n/BigInt(a)}spotPriceInGivenOut(t){let e=k.big.toBigInt(1,t.decimalsOut),s=this.calculateInGivenOut(t,e)*k.big.pow10(k.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(s,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=k.big.toBigInt(1,t.decimalsIn),s=this.calculateOutGivenIn(t,e)*k.big.pow10(k.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)?[k.big.toBigInt(1,18).toString(),k.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 a=k.big.pow10(Math.abs(s));return s>0?t*a:t/a}};var bt=require("polkadot-api"),ti=require("@polkadot-api/utils"),A=require("rxjs"),ei=require("viem"),ne=require("@galacticcouncil/common");var Rt=[{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 Ct=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,s]=await this.client.readContract({abi:Rt,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-s}};var{FeeUtils:ye}=x,{H160:Ze}=ne.h160,Hi=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Mt=class extends E{ghoClient;stableClient;constructor(t,e,i,s){super(t,e,s),this.stableClient=i,this.ghoClient=new Ct(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}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),i=new TextEncoder().encode(e),s=(0,ti.toHex)(i);return(0,bt.AccountId)(ne.HYDRATION_SS58_PREFIX).dec(s)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(bt.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,s]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t,{at:this.at}),this.api.query.HSM.Collaterals.getEntries({at:this.at}),this.stableClient.getPools()]);if(i.length===0)return[];let a=this.getFacilitatorAddress(),n=Ze.fromAny(a),r=this.getHollarAddress(e),l=await this.ghoClient.getFacilitatorCapacity(r,n),u=i.map(async({keyArgs:p,value:g})=>{let[b]=p,{pool_id:f,max_buy_price_coefficient:S,max_in_holding:Y,purchase_fee:X,buy_back_fee:K,buyback_rate:H}=g,q=s.find(it=>it.id===f);if(q){let it=this.getPoolId(f),Pt=await this.balance.getBalance(a,b);return{...q,address:it,type:"HSM",tokens:q.tokens.filter(si=>si.id!==f),hsmAddress:a,hsmMintCapacity:l,hollarId:t,hollarH160:r,collateralId:b,collateralBalance:Pt.transferable,maxBuyPriceCoefficient:S,maxInHolding:Y,purchaseFee:ye.fromPermill(X),buyBackFee:ye.fromPermill(K),buyBackRate:ye.fromPerbill(H)}}});return(await Promise.all(u)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:i}=t.log,s=e,a=bt.Binary.toHex(i);try{let{eventName:n,args:r}=(0,ei.decodeEventLog)({abi:Rt,topics:s,data:a}),l=r.facilitatorAddress.toLowerCase();return{eventName:n,facilitator:l,key:`${n}:${l}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,A.mergeMap)(({events:t})=>t),(0,A.map)(({payload:t})=>this.parseEvmLog(t)),(0,A.filter)(t=>t!==void 0),(0,A.filter)(({eventName:t})=>Hi.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:a,hollarH160:n}]=i,r=Ze.fromAny(a);if(r.toLowerCase()===e){let u=await this.ghoClient.getFacilitatorCapacity(n,r);for(let c of i)s.push({...c,hsmMintCapacity:u})}return s})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(a=>{let{tokens:n,collateralId:r}=a;n.find(u=>u.id===r).type==="Erc20"?e.push(r):t.push(r)});let[{hsmAddress:i}]=this.store.pools,s=[];if(t.length>0){let a=this.balance.watchTokensBalance(i);s.push(a)}if(e.length>0){let a=this.balance.watchErc20Balance(i,e);s.push(a)}return s.length>0?(0,A.combineLatest)(s).pipe((0,A.map)(a=>a.flat()),(0,A.pairwise)(),(0,A.map)(([a,n])=>this.balance.getDeltas(a,n)),this.watchGuard("balances")).subscribe(a=>{this.store.update(n=>{let r=[],l=new Map(n.map(u=>[u.collateralId,u]));return a.forEach(({id:u,balance:c})=>{let p=l.get(u);p&&(this.log.trace("balances",{id:u,balance:c}),r.push({...p,collateralBalance:c.transferable}))}),r})}):A.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 a of i){let n=e.get(a.id);n&&s.push({...a,fee:n.fee,tokens:n.tokens.filter(r=>r.id!==a.id),totalIssuance:n.totalIssuance,pegs:n.pegs,amplification:n.amplification,isRampPeriod:n.isRampPeriod})}return s})})}subscribeBalances(){return A.Subscription.EMPTY}subscribeUpdates(){let t=new A.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var re=class{static get(t){switch(t.type){case"Aave":return Ft.fromPool(t);case"XYK":return At.fromPool(t);case"Omnipool":return Ot.fromPool(t);case"LBP":return St.fromPool(t);case"Stableswap":return rt.fromPool(t);case"HSM":return Et.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var ii=require("@galacticcouncil/common"),D=require("rxjs");var ft=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}};var{logger:qi}=ii.log,oe=class extends ${evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=D.Subscription.EMPTY;omniSub=D.Subscription.EMPTY;stableSub=D.Subscription.EMPTY;hsmSub=D.Subscription.EMPTY;xykSub=D.Subscription.EMPTY;lbpSub=D.Subscription.EMPTY;isReady=!1;isDestroyed=new D.Subject;constructor(t,e,i){super(t,i),this.evm=e,this.aave=new kt(t,e,i),this.omnipool=new It(t,e,i),this.stableswap=new _t(t,e,i),this.hsm=new Mt(t,e,this.stableswap,i),this.xyk=new Bt(t,e,i),this.lbp=new wt(t,e,i),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}get isHistorical(){return this.at!=="best"&&this.at!=="finalized"}subscribe(t){return this.isHistorical?D.Subscription.EMPTY:t.getSubscriber().pipe((0,D.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")||(qi.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 ft(e.type)}};var le=class{constructor(t){this.snapshot=t;let{aave:e,xyk:i,lbp:s,stable:a,omni:n}=t.pools;this.flat=[...e,...i,...s,...a,...n]}flat;async getPools(){return this.flat}async getPoolFees(t,e){let{block:i,states:s}=this.snapshot;switch(e.type){case"Aave":return{};case"XYK":{let{exchangeFee:a}=s.xyk;return{exchangeFee:a}}case"LBP":{let{repayFee:a}=s.lbp;return{exchangeFee:e.fee,repayFee:a}}case"Stableswap":return{fee:e.fee};case"Omnipool":{let a=t.assetOut,n=t.assetIn,{dynamicFees:r,emaOracles:l,assetFeeParams:u,protocolFeeParams:c,maxSlipFee:p}=s.omni,g=r.find(({asset:S})=>S===a)?.fee,b=l.find(({pair:S})=>S.join(":")===Zt(a))?.oracle,f=l.find(({pair:S})=>S.join(":")===Zt(n))?.oracle;return nt.compute(t,i,g,b,f,u,c,p)}default:throw new ft(e.type)}}};0&&(module.exports={PoolContextProvider,PoolError,PoolFactory,PoolType,SnapshotPoolCtxProvider,aave,hsm,lbp,omni,stable,xyk});
|
|
1
|
+
"use strict";var xi=Object.create;var Ht=Object.defineProperty;var Ti=Object.getOwnPropertyDescriptor;var wi=Object.getOwnPropertyNames;var Ai=Object.getPrototypeOf,Ii=Object.prototype.hasOwnProperty;var U=(o,t)=>{for(var e in t)Ht(o,e,{get:t[e],enumerable:!0})},Ee=(o,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of wi(t))!Ii.call(o,s)&&s!==e&&Ht(o,s,{get:()=>t[s],enumerable:!(i=Ti(t,s))||i.enumerable});return o};var Gt=(o,t,e)=>(e=o!=null?xi(Ai(o)):{},Ee(t||!o||!o.__esModule?Ht(e,"default",{value:o,enumerable:!0}):e,o)),Oi=o=>Ee(Ht({},"__esModule",{value:!0}),o);var rs={};U(rs,{PoolContextProvider:()=>he,PoolError:()=>Z,PoolFactory:()=>de,PoolType:()=>I,SnapshotPoolCtxProvider:()=>ge,aave:()=>Oe,hsm:()=>Be,lbp:()=>Pe,omni:()=>Se,stable:()=>we,xyk:()=>Ae});module.exports=Oi(rs);var Pe={};U(Pe,{LbpMath:()=>V,LbpPool:()=>Tt,LbpPoolClient:()=>At});var z=require("@galacticcouncil/math-lbp"),V=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 ut=require("@galacticcouncil/common");var I=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a.HSM="HSM",a))(I||{}),Z=(c=>(c.UnknownError="UnknownError",c.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",c.InsufficientTradingAmount="InsufficientTradingAmount",c.InsufficientCollateral="InsufficientCollateral",c.MaxHoldingExceeded="MaxHoldingExceeded",c.MaxInRatioExceeded="MaxInRatioExceeded",c.MaxOutRatioExceeded="MaxOutRatioExceeded",c.TradeNotAllowed="TradeNotAllowed",c.MaxBuyBackExceeded="MaxBuyBackExceeded",c.MaxBuyPriceExceeded="MaxBuyPriceExceeded",c))(Z||{});var Ut={};U(Ut,{withTimeout:()=>_i});function _i(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 Bi=require("@galacticcouncil/common");var x={};U(x,{FeeUtils:()=>be,shiftNeg:()=>Fi});var Re=Gt(require("big.js"));var be=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 Fi(o,t){let e=(0,Re.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var St={};U(St,{findNestedKey:()=>ki,findNestedObj:()=>Ci,jsonFormatter:()=>Mi});var ki=(o,t)=>{let e=[];return JSON.stringify(o,(i,s)=>(s&&s[t]&&e.push(s),s)),e[0]},Ci=(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 tt={};U(tt,{calculateBuyFee:()=>Ni,calculateDiffToAvg:()=>Li,calculateDiffToRef:()=>Di,calculateSellFee:()=>qi});var W=Gt(require("big.js"));function Li(o,t){let e=(0,W.default)(o.toString()),i=(0,W.default)(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function Di(o,t){if(t===0n)return 0;let e=(0,W.default)(o.toString()),i=(0,W.default)(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function qi(o,t){if(o===0n)return 0;let e=(0,W.default)(o.toString()),i=(0,W.default)(t.toString());return(0,W.default)(1).minus(i.div(e)).mul(100).round(2).toNumber()}function Ni(o,t){if(o===0n)return 0;let e=(0,W.default)(o.toString());return(0,W.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var xt=(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 Vt=(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 Hi=Vt(()=>"illegal argument(s)"),Fe=o=>{throw new Hi(o)};var Gi=Vt(()=>"index out of bounds"),ye=o=>{throw new Gi(o)},$t=(o,t,e)=>(o<t||o>=e)&&ye(o);var ke=23283064365386963e-26,zt=class{float(t=1){return this.int()*ke*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*ke-.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 Wt=class extends zt{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 Ce=new Wt(Math.random);var Me=o=>o!=null&&typeof o!="function"&&o.length!==void 0;var Le=Object.getPrototypeOf({}),Yt="function",De="string",lt=(o,t)=>{let e;if(o===t)return!0;if(o!=null){if(typeof o.equiv===Yt)return o.equiv(t)}else return o==t;if(t!=null){if(typeof t.equiv===Yt)return t.equiv(o)}else return o==t;return typeof o===De||typeof t===De?!1:(e=Object.getPrototypeOf(o),(e==null||e===Le)&&(e=Object.getPrototypeOf(t),e==null||e===Le)?zi(o,t):typeof o!==Yt&&o.length!==void 0&&typeof t!==Yt&&t.length!==void 0?Ui(o,t):o instanceof Set&&t instanceof Set?Vi(o,t):o instanceof Map&&t instanceof Map?$i(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)},Ui=(o,t,e=lt)=>{let i=o.length;if(i===t.length)for(;i-- >0&&e(o[i],t[i]););return i<0},Vi=(o,t,e=lt)=>o.size===t.size&&e([...o.keys()].sort(),[...t.keys()].sort()),$i=(o,t,e=lt)=>o.size===t.size&&e([...o].sort(),[...t].sort()),zi=(o,t,e=lt)=>{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 fe=class{value;constructor(t){this.value=t}deref(){return this.value}};var qe=o=>o instanceof fe;var Xt=class o{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Ne("next",this._head)}reverseIterator(){return Ne("prev",this.tail)}clear(){this.release()}compare(t,e=xt){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||Me(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(!lt(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||xt;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&&!qe(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&&ye(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*Ne(o,t){for(;t;)yield t.value,t=t[o]}var Kt=class o extends Xt{_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):($t(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):($t(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=Ce){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=xt){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),$t(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 jt=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 Kt,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 st=class o extends jt{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 ct=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 st(null,{ttl:s}):new st;return{get:(...c)=>{let p=i(...c);if(n.has(p)){this.log("[live]",t,p);let h=n.get(p);return Promise.resolve(h)}if(a.has(p))return this.log("[memo]",t,p),a.get(p);this.log("[fetch]",t,p);let d=e(...c).catch(h=>{throw a.delete(p),h});return a.set(p,d),d},set:(c,...p)=>{let d=i(...p);this.log("[set-live]",t,d),n.set(d,c)},clear:()=>{this.log("[clear]",t),n.clear(),a.release()}}}};var{FeeUtils:He}=x,Tt=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=He.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),u=e+r,c=this.calculateInGivenOut(t,u),p=t.balanceIn/this.maxInRatio;return c>p&&n.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,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),u=He.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),c=r-l,p=t.balanceOut/this.maxOutRatio;return c>p&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:c,feePct:u,errors:n}}}calculateInGivenOut(t,e){let i=V.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=V.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=V.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),ut.big.toBigInt(1,ut.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=V.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),ut.big.toBigInt(1,ut.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let i=V.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var Ye=require("polkadot-api"),et=require("rxjs");var Ge=(o,t=new Map)=>e=>{let i;return t.has(e)?t.get(e):(t.set(e,i=o(e)),i)};var P=require("rxjs"),m=require("rxjs/operators");var mt=require("@galacticcouncil/descriptors");var Ve=require("@galacticcouncil/common"),pt=require("rxjs");var j=require("rxjs"),O=require("rxjs/operators");function Ue(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>(0,j.defer)(()=>(0,j.from)(o._request("system_health",[]))).pipe((0,O.timeout)({first:e}),(0,O.map)(()=>"online"),(0,O.catchError)(()=>(0,j.of)("offline")));return(0,j.of)({state:"offline",delayMs:0}).pipe((0,O.expand)(n=>(0,j.timer)(n.delayMs).pipe((0,O.switchMap)(i),(0,O.map)(a=>({state:a,delayMs:t})))),(0,O.skip)(1),(0,O.map)(n=>n.state),(0,O.distinctUntilChanged)(),(0,O.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Wi}=Ve.log,Jt=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,pt.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Ue(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,pt.tap)({error:i=>Wi.error(t,i)}),(0,pt.shareReplay)({bufferSize:1,refCount:!0}))}};var Y=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(mt.hydration),this.apiNext=this.client.getTypedApi(mt.hydrationNext),this.apiIce=this.client.getTypedApi(mt.hydrationIce),this.watcher=Jt.getInstance(this.client),this.at=e??"best"}};var Yi=require("polkadot-api/ws"),Xi=require("polkadot-api/logs-provider");var Ki=require("polkadot-api");var $e=require("@galacticcouncil/common"),C=require("rxjs"),b=require("rxjs/operators");var{logger:dt}=$e.log,wt=class extends Y{erc20Ids=null;constructor(t,e){super(t,e)}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:this.at});return this.getBreakdown(i)}async getTokenBalance(t,e){let s=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});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,b.connect)(n=>(0,C.concat)(n.pipe((0,b.take)(1)),n.pipe((0,b.skip)(1),(0,b.debounceTime)(250)))))}).pipe((0,b.map)(e=>e.flat()),(0,b.startWith)([]),(0,b.bufferCount)(2,1),(0,b.map)(([e,i],s)=>s===0?i:this.getDeltas(e,i))).pipe((0,b.tap)({subscribe:()=>dt.debug("balance: subscribe",t),error:e=>dt.error("balance",e)}),(0,b.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,C.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,b.map)(({value:i})=>({id:0,balance:this.getBreakdown(i.data)})),(0,b.tap)({error:i=>dt.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return(0,C.defer)(()=>i.watchValue(t,e,{at:"best"})).pipe((0,b.map)(({value:s})=>({id:e,balance:this.getBreakdown(s)})),(0,b.tap)({error:s=>dt.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,C.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,b.distinctUntilChanged)((i,s)=>!s.deltas),(0,b.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,b.tap)({error:i=>dt.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,b.switchMap)(n=>this.watcher.bestBlock$.pipe((0,b.switchMap)(()=>(0,C.from)(s(n))))),(0,b.startWith)([]),(0,b.bufferCount)(2,1),(0,b.map)(([n,a],r)=>r===0?a.filter(l=>l.balance.total>0n):this.getDeltas(n,a)),(0,b.distinctUntilChanged)((n,a)=>a.length===0),(0,b.tap)({error:n=>dt.error("balance(erc20)",n)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});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 ze=require("rxjs"),Qt=class{store$=new ze.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 We=require("@galacticcouncil/common");var ji={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Zt}=We.log,te=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${ji[this.type]})`,10)}trace(t,...e){Zt.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){Zt.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){Zt.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){Zt.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:Ji}=Ut,Qi=3e3,k=class extends Y{evm;balance;store=new Qt;log;shared$;resync$=new P.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new st(null,{ttl:6*1e3});memPools=Ge(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e,i){super(t,i),this.evm=e,this.balance=new wt(t,i),this.log=new te(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){let e=(await this.getMemPools()).filter(i=>this.hasValidAssets(i));return this.store.set(e),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,P.defer)(()=>{let t=new P.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,m.switchMap)(()=>{let e=new P.Subscription;return(0,P.from)(Ji(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(),P.EMPTY))).pipe((0,m.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,m.switchMap)(s=>(0,P.merge)((0,P.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 P.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,P.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,P.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(u=>{let c=a.find(p=>p.id===u.id);return c&&u.id!==r.id?{...u,balance:c.balance.transferable}:u});i.push({...r,tokens:l})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<Qi||(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)(([r,l])=>r==="offline"&&l==="online"),(0,m.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,m.catchError)(r=>(this.log.error("watchdog_recovery_error",r),P.EMPTY)),(0,m.repeat)({delay:1e3})),n=this.watcher.finalizedBlock$.pipe((0,m.pairwise)(),(0,m.tap)(([r,l])=>{let u=Number(r.number),c=Number(l.number),p=c-u;p>=3&&(this.log.debug("watchdog_gap",{from:u,to:c,gap:p}),this.requestResync())}),(0,m.catchError)(r=>(this.log.error("watchdog_gap_error",r),P.EMPTY)),(0,m.repeat)({delay:1e3})),a=(0,P.interval)(36e5).pipe((0,m.tap)(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),(0,m.catchError)(r=>(this.log.error("watchdog_periodic_error",r),P.EMPTY)),(0,m.repeat)({delay:1e3}));return(0,P.merge)(s,n,a).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)(()=>P.EMPTY))}};var At=class extends k{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=V.calculateLinearWeights(i?i.toString():"0",s?s.toString():"0",n.toString(),a.toString(),e.toString()),l=BigInt(r),u=this.MAX_FINAL_WEIGHT-BigInt(l);return[l,u]}async isSupported(){return(await this.api.getStaticApis()).compat.query.LBP.PoolData.isCompatible(Ye.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:this.at}),this.api.query.ParachainSystem.ValidationData.getValue({at:this.at}),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,u=l.toString(),c=await this.getPoolDelta(u,r,s);return{address:u,type:"LBP",fee:r.fee,...c,...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),[u,c]=s,[p,d,h,g,f]=await Promise.all([this.isRepayFeeApplied(u,n,a.toString()),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u,{at:this.at}),this.balance.getBalance(t,c),this.api.query.AssetRegistry.Assets.getValue(c,{at:this.at})]);return{repayFeeApply:p,tokens:[{id:u,decimals:h?.decimals,existentialDeposit:h?.existential_deposit,balance:d.transferable,weight:r,type:h?.asset_type.type},{id:c,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:g.transferable,weight:l,type:f?.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({at:"best"}).pipe((0,et.map)(({value:t})=>t),(0,et.filter)(t=>t!==void 0),(0,et.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,[u]=a,[c,p]=this.getPoolWeights(n,t),[d,h]=s.tokens,g=[{...d,weight:c},{...h,weight:p}],f=await this.isRepayFeeApplied(u,r,l.toString());i.push({...s,tokens:g,repayFeeApply:f})}}return i})})}subscribeUpdates(){let t=new et.Subscription;return t.add(this.subscribeValidationData()),t}};var Se={};U(Se,{OmniMath:()=>S,OmniPool:()=>It,OmniPoolClient:()=>Ot,OmniPoolFee:()=>at,getEmaKey:()=>ie,getEmaPair:()=>ht});var y=require("@galacticcouncil/math-omnipool"),nt=Gt(require("big.js")),S=class{static calculateSpotPrice(t,e,i,s){return(0,y.calculate_spot_price)(t,e,i,s)}static calculateLrnaSpotPrice(t,e){return(0,y.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,i,s,n,a,r,l,u,c){return(0,y.calculate_in_given_out)(t,e,i,s,n,a,r,l,u,c)}static calculateLrnaInGivenOut(t,e,i,s,n,a){return(0,y.calculate_lrna_in_given_out)(t,e,i,s,n,a)}static calculateOutGivenIn(t,e,i,s,n,a,r,l,u,c){return(0,y.calculate_out_given_in)(t,e,i,s,n,a,r,l,u,c)}static calculateOutGivenLrnaIn(t,e,i,s,n,a){return(0,y.calculate_out_given_lrna_in)(t,e,i,s,n,a)}static calculateShares(t,e,i,s){return(0,y.calculate_shares)(t,e,i,s)}static calculateLiquidityOut(t,e,i,s,n,a,r,l){return(0,y.calculate_liquidity_out)(t,e,i,s,n,a,r,l)}static calculateLiquidityLRNAOut(t,e,i,s,n,a,r,l){return(0,y.calculate_liquidity_lrna_out)(t,e,i,s,n,a,r,l)}static calculateCapDifference(t,e,i,s){let n=(0,nt.default)(e),a=(0,nt.default)(t),r=(0,nt.default)(s),l=(0,nt.default)(i),u=(0,nt.default)(10).pow(18),c=l.div(u);if(n.div(r).lt(c)){let d=c.times(r).minus(n).times(a),h=n.times((0,nt.default)(1).minus(c));return d.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,s){return(0,y.calculate_liquidity_hub_in)(t,e,i,s)}static isSellAllowed(t){return(0,y.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,y.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,y.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,y.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,i,s,n,a,r,l,u,c,p){return(0,y.recalculate_asset_fee)(t,e,i,s,n,a,r,l,u,c,p)}static recalculateProtocolFee(t,e,i,s,n,a,r,l,u,c,p){return(0,y.recalculate_protocol_fee)(t,e,i,s,n,a,r,l,u,c,p)}static verifyAssetCap(t,e,i,s){return(0,y.verify_asset_cap)(t,e,i,s)}};var Xe=require("@galacticcouncil/common");var{FeeUtils:K}=x,It=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:tt.calculateBuyFee(s,n),r=[],l=S.isSellAllowed(t.tradeableIn),u=S.isBuyAllowed(t.tradeableOut);(!l||!u)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&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=tt.calculateSellFee(s,n),r=[],l=S.isSellAllowed(t.tradeableIn),u=S.isBuyAllowed(t.tradeableOut);(!l||!u)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&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=S.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?K.toRaw(i.assetFee).toString():"0",i?K.toRaw(i.protocolFee).toString():"0",i?K.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateLrnaInGivenOut(t,e,i){let s=S.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?K.toRaw(i.assetFee).toString():"0",i?K.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=S.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?K.toRaw(i.assetFee).toString():"0",i?K.toRaw(i.protocolFee).toString():"0",i?K.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateOutGivenLrnaIn(t,e,i){let s=S.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?K.toRaw(i.assetFee).toString():"0",i?K.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=S.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=S.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=S.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=S.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=Xe.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var J=require("polkadot-api"),Je=require("@polkadot-api/utils"),v=require("rxjs"),Qe=require("@galacticcouncil/common");var{FeeUtils:B}=x,at=class o{static compute(t,e,i,s,n,a,r,l){let u=t.assetIn,[c,p,d]=o.getAssetFee(t,e,i,s,a),h=0,g=0,f=0;u!==1&&([h,g,f]=o.getProtocolFee(t,e,i,n,r));let $=c+h,q=d+f;return{assetFee:B.fromPermill(p),protocolFee:B.fromPermill(g),maxSlipFee:B.fromPermill(l),min:B.fromPermill($),max:B.fromPermill(q)}}static getAssetFee(t,e,i,s,n){let{assetOut:a,balanceOut:r}=t,{min_fee:l,max_fee:u,decay:c,amplification:p}=n;if(!i||!s)return[l,l,u];let d=B.fromPermill(l),h=B.fromPermill(u),[g]=s,{asset_fee:f,timestamp:$}=i,q=Math.max(1,e-$),N=g.volume.b_in.toString(),H=g.volume.b_out.toString(),G=g.liquidity.b.toString();a===0&&(N=g.volume.a_in.toString(),H=g.volume.a_out.toString(),G=g.liquidity.a.toString());let it=B.fromPermill(f),vt=S.recalculateAssetFee(N,H,G,"9",r.toString(),B.toRaw(it).toString(),q.toString(),B.toRaw(d).toString(),B.toRaw(h).toString(),c.toString(),p.toString());return[l,Number(vt)*1e6,u]}static getProtocolFee(t,e,i,s,n){let{assetIn:a,balanceIn:r}=t,{min_fee:l,max_fee:u,decay:c,amplification:p}=n;if(!i||!s)return[l,l,u];let d=B.fromPermill(l),h=B.fromPermill(u),[g]=s,{protocol_fee:f,timestamp:$}=i,q=Math.max(1,e-$),N=g.volume.b_in.toString(),H=g.volume.b_out.toString(),G=g.liquidity.b.toString();a===0&&(N=g.volume.a_in.toString(),H=g.volume.a_out.toString(),G=g.liquidity.a.toString());let it=B.fromPermill(f),vt=S.recalculateProtocolFee(N,H,G,"9",r.toString(),B.toRaw(it).toString(),q.toString(),B.toRaw(d).toString(),B.toRaw(h).toString(),c.toString(),p.toString());return[l,Number(vt)*1e6,u]}};var ht=o=>o===0?[0,1]:[1,o],ie=o=>ht(o).join(":");var{FeeUtils:ve}=x,Ke=J.Binary.toHex(J.Binary.fromText("omnipool")),je=(0,J.Enum)("Short"),Ot=class extends k{queryBus=new ct;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:this.at}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:this.at}),t=>String(t),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:this.at}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(Ke,t,je,{at:this.at}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,Je.toHex)(e);return(0,J.AccountId)(Qe.HYDRATION_SS58_PREFIX).dec(i)}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(){return(await this.api.getStaticApis()).compat.query.Omnipool.Assets.isCompatible(J.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,s,n,a,r,l]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:this.at}),this.api.query.Omnipool.HubAssetTradability.getValue({at:this.at}),this.api.query.AssetRegistry.Assets.getValue(t,{at:this.at}),this.balance.getBalance(e,t),this.getPoolLimits(),this.api.query.System.Number.getValue({at:this.at})]);this.block=l;let u=i.map(async({keyArgs:p,value:d})=>{let[h]=p,{hub_reserve:g,shares:f,tradable:$,cap:q,protocol_shares:N}=d,[H,G]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(h,{at:this.at}),this.balance.getBalance(e,h)]);return{id:h,decimals:H?.decimals,existentialDeposit:H?.existential_deposit,balance:G.transferable,cap:q,hubReserves:g,protocolShares:N,shares:f,tradeable:$,type:H?.asset_type.type}}),c=await Promise.all(u);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,n=await this.maxSlipFee.get()??0,a=await this.dynamicFeesConfig.get(e);if(a?.type==="Fixed"){let{asset_fee:d,protocol_fee:h}=a.value;return{assetFee:ve.fromPermill(d),protocolFee:ve.fromPermill(h),maxSlipFee:ve.fromPermill(n)}}let[r,l,u,c,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(ht(e)),this.emaOracles.get(ht(i)),a?a.value.asset_fee_params:this.api.constants.DynamicFees.AssetFeeParameters(),a?a.value.protocol_fee_params:this.api.constants.DynamicFees.ProtocolFeeParameters()]);return at.compute(t,this.block,r,l,u,c,p,n)}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(s=>s.id).map(s=>ht(s)).map(s=>this.api.query.EmaOracle.Oracles.watchValue(Ke,s,je,{at:"best"}).pipe((0,v.map)(({value:n})=>n),(0,v.filter)(n=>n!==void 0),(0,v.map)((n,a)=>({value:n,index:a})),(0,v.tap)(({index:n})=>{n>0&&this.log.trace("emaOracle.Oracles",s.join(":"))}),(0,v.map)(({value:n})=>({pair:s,value:n}))));return(0,v.merge)(...i).pipe((0,v.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,v.distinctUntilChanged)((t,e)=>!e.deltas),(0,v.map)((t,e)=>({value:t,index:e})),(0,v.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),(0,v.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,v.distinctUntilChanged)((t,e)=>!e.deltas),(0,v.map)((t,e)=>({value:t,index:e})),(0,v.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),(0,v.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,v.distinctUntilChanged)((t,e)=>!e.deltas),(0,v.map)((t,e)=>({value:t,index:e})),(0,v.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 v.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 we={};U(we,{StableMath:()=>_,StableSwap:()=>rt,StableSwapClient:()=>Ft});var T=require("@galacticcouncil/math-stableswap"),_=class{static getPoolAddress(t){return(0,T.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,T.calculate_amplification)(t,e,i,s,n)}static calculateInGivenOut(t,e,i,s,n,a,r){return(0,T.calculate_in_given_out)(t,e,i,s,n,a,r)}static calculateAddOneAsset(t,e,i,s,n,a,r){return(0,T.calculate_add_one_asset)(t,e,i,s,n,a,r)}static calculateSharesForAmount(t,e,i,s,n,a,r){return(0,T.calculate_shares_for_amount)(t,e,i,s,n,a,r)}static calculateOutGivenIn(t,e,i,s,n,a,r){return(0,T.calculate_out_given_in)(t,e,i,s,n,a,r)}static calculateLiquidityOutOneAsset(t,e,i,s,n,a,r){return(0,T.calculate_liquidity_out_one_asset)(t,e,i,s,n,a,r)}static calculateShares(t,e,i,s,n,a){return(0,T.calculate_shares)(t,e,i,s,n,a)}static calculateSpotPriceWithFee(t,e,i,s,n,a,r,l){return(0,T.calculate_spot_price_with_fee)(t,e,i,s,n,a,r,l)}static recalculatePegs(t,e,i,s,n,a){let r=(0,T.recalculate_peg)(t,e,i,s,n,a);return JSON.parse(r)}};var _t=require("@galacticcouncil/common");var{FeeUtils:gt}=x,rt=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:tt.calculateBuyFee(s,n),r=[],l=S.isSellAllowed(t.tradeableIn),u=S.isBuyAllowed(t.tradeableOut);return(!l||!u)&&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=tt.calculateSellFee(s,n),r=[],l=S.isSellAllowed(t.tradeableIn),u=S.isBuyAllowed(t.tradeableOut);return(!l||!u)&&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?gt.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?gt.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?gt.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?gt.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?gt.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?gt.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,St.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],St.jsonFormatter)}normalizeSpot(t,e,i,s,n){return e?t*_t.big.pow10(_t.RUNTIME_DECIMALS-n):i?t/_t.big.pow10(n-s):t}};var ne=require("polkadot-api"),ri=require("@polkadot-api/utils"),oi=require("@noble/hashes/blake2b"),w=require("rxjs"),ae=require("@galacticcouncil/common");var ei=require("polkadot-api"),Te=require("viem");var xe=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}],Ze=[{anonymous:!1,inputs:[{indexed:!1,name:"key",type:"string"},{indexed:!1,name:"value",type:"uint128"},{indexed:!1,name:"timestamp",type:"uint128"}],name:"OracleUpdate",type:"event"}],ti=[{anonymous:!1,inputs:[{indexed:!0,name:"roundId",type:"uint80"},{indexed:!1,name:"answer",type:"int256"},{indexed:!1,name:"timestamp",type:"uint256"}],name:"PriceUpdated",type:"event"}];var Bt=class{static parse(t){let{address:e,topics:i,data:s}=t.log,n=e.toLowerCase(),a=ei.Binary.toHex(s);try{let{eventName:r,args:l}=(0,Te.decodeEventLog)({abi:ti,topics:i,data:a});return{eventName:`ManagedOracle.${r}`,emitter:n,value:l.answer,timestamp:l.timestamp}}catch{}try{let{eventName:r,args:l}=(0,Te.decodeEventLog)({abi:Ze,topics:i,data:a});return{eventName:`DIA.${r}`,emitter:n,key:l.key,value:l.value,timestamp:l.timestamp}}catch{}}};var Et=class{adapter;constructor(t){this.adapter=t.getRPCAdapter()}async getData(t,e=6){let[i,s,n]=await Promise.all([this.adapter.readContract({abi:xe,address:t,functionName:"latestRoundData"}),this.adapter.readContract({abi:xe,address:t,functionName:"decimals"}),this.adapter.getBlock()]),[a,r,l,u]=i,c=n.number-(n.timestamp-u)/BigInt(e),p=Number(c);return{price:r,decimals:s,updatedAt:p<0?0:p}}};var ii={"EUR/USD":"0xaa47a5662269270d3df33ae08f806e383611575c","sUSDs/USD":"0x4b32bffc6acd751446e79e8687ef3815fd7924fd","sUSDe/USD":"0x22cdea305cee63d082e79f8c5db939eecd0265d0"},si={"0xcfab6a4031c70da0f0cf6f31a252c16119db3611":"0xaafd758688cefd0a7b7770a825f1aad551e16185"},ni={"bifrosto:5:15:LastBlock":"0xaafd758688cefd0a7b7770a825f1aad551e16185"};function ai(o,t,e){let i=Buffer.from(o.replace(/^0x/,""),"hex").toString("ascii").replace(/\0+$/,""),[s,n]=[t[0],t[1]].sort((a,r)=>a-r);return`${i}:${s}:${n}:${e}`}var{FeeUtils:bt}=x,Rt=class o{static compute(t,e,i,s){let n=o.getRecent(e),a=bt.fromPermill(t.fee),r=bt.fromPerbill(e.max_peg_update),l=i.map(({pair:g,updatedAt:f})=>[g,f]),u=i.find(g=>g.source),c=e.updated_at?e.updated_at.toString():u?.updatedAt;if(!c)throw new Error("Current peg unknown!");let[p,d]=_.recalculatePegs(JSON.stringify(n),c,JSON.stringify(l),s.toString(),bt.toRaw(r).toString(),bt.toRaw(a).toString()),h=Number(p)*1e6;return{pegsFee:bt.fromPermill(h),pegs:d}}static getDefault(t){return{pegsFee:bt.fromPermill(t.fee),pegs:_.defaultPegs(t.assets.length)}}static getRecent(t){let{current:e}=t;return Array.from(e.entries()).map(([i,s])=>s.map(n=>n.toString()))}};var{FeeUtils:Zi}=x,ts=["ManagedOracle.PriceUpdated","DIA.OracleUpdate"],Ft=class extends k{poolsData=new Map([]);mmOracle=new Et(this.evm);mmAddresses=new Set;mmRouting={byEmitter:new Map,byDiaKey:new Map,byEma:new Map};queryBus=new ct;emaOracles=this.queryBus.scope("EmaOracle.Oracles",(t,e,i)=>this.api.query.EmaOracle.Oracles.getValue(t,e,i,{at:this.at}),(t,e,i)=>`${t.toString()}:${e.join(":")}:${i.type}`,6*1e3);mmOracles=this.queryBus.scope("MmOracle",t=>this.mmOracle.getData(t),t=>t.toLowerCase(),600*1e3);pegs=this.queryBus.scope("Stableswap.PoolPegs",t=>this.api.query.Stableswap.PoolPegs.getValue(t,{at:this.at}),t=>String(t),6*1e3);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=_.getPoolAddress(t),i=(0,oi.blake2b)(e,{dkLen:32}),s=(0,ri.toHex)(i);return(0,ne.AccountId)(ae.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,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(n,{at:this.at}),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)}buildRouting(){this.mmRouting.byEmitter.clear(),this.mmRouting.byDiaKey.clear(),this.mmRouting.byEma.clear();for(let t of this.mmAddresses)this.mmRouting.byEmitter.set(t,t);for(let[t,e]of Object.entries(si)){let i=t.toLowerCase(),s=e.toLowerCase();this.mmAddresses.has(s)&&this.mmRouting.byEmitter.set(i,s)}for(let[t,e]of Object.entries(ii)){let i=e.toLowerCase();this.mmAddresses.has(i)&&this.mmRouting.byDiaKey.set(t,i)}for(let[t,e]of Object.entries(ni)){let i=e.toLowerCase();this.mmAddresses.has(i)&&this.mmRouting.byEma.set(t,i)}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Stableswap.Pools.isCompatible(ne.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,i,s]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:this.at}),this.api.query.Stableswap.PoolPegs.getEntries({at:this.at}),this.api.query.System.Number.getValue({at:this.at}),this.getPoolLimits()]);for(let{keyArgs:a,value:r}of e){let[l]=a;this.pegs.set(r,l);for(let u of r.source)u.type==="MMOracle"&&this.mmAddresses.add(u.value.toString().toLowerCase())}this.buildRouting();let n=t.map(async({keyArgs:a,value:r})=>{let[l]=a,u=this.getPoolAddress(l),[c,p,d,h]=await Promise.all([this.getPoolTokens(l,r),this.getPoolAmplification(r,i),this.getPoolPegs(l,r,i),this.api.query.Tokens.TotalIssuance.getValue(l,{at:this.at})]);return c.push({id:l,tradeable:15,balance:h,decimals:ae.RUNTIME_DECIMALS}),this.poolsData.set(l,r),{address:u,id:l,type:"Stableswap",fee:Zi.fromPermill(r.fee),tokens:c,totalIssuance:h,...d,...s,...p}});return Promise.all(n)}async getPoolFees(t,e){return{fee:this.store.pools.find(s=>s.address===e).fee}}async getPoolPegs(t,e,i){let s=await this.pegs.get(t);if(!s)return Rt.getDefault(e);let n=await this.getLatestPegs(e,s,i);return Rt.compute(e,s,n,i)}async getLatestPegs(t,e,i){let{source:s}=e,n=t.assets,a=s.map(async(r,l)=>{if(r.type==="Oracle"){let[u,c,p]=r.value,d=[p,n[l]].sort((q,N)=>q-N),h=await this.emaOracles.get(u,d,c);if(!h)throw new Error("EmaOracle missing for "+u+" / "+d);let[{price:g,updated_at:f}]=h;return{pair:p===d[0]?[g.n.toString(),g.d.toString()]:[g.d.toString(),g.n.toString()],updatedAt:f.toString(),source:r.type}}if(r.type==="MMOracle"){let u=r.value.toString(),{price:c,decimals:p,updatedAt:d}=await this.mmOracles.get(u),h=(10n**BigInt(p)).toString();return{pair:[c.toString(),h],updatedAt:d.toString(),source:r.type}}if(r.type==="Value")return{pair:r.value.map(c=>c.toString()),updatedAt:i.toString()};throw new Error(r+" source not supported")});return Promise.all(a)}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,{at:"best"}).pipe((0,w.map)(({value:s})=>s),(0,w.map)((s,n)=>({value:s,index:n})),(0,w.tap)(({index:s,value:n})=>{s>0&&this.log.trace("tokens.TotalIssuance",i,n)}),(0,w.map)(({value:s})=>({id:i,value:s}))));return(0,w.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 u=l.tokens.map(c=>c.id===s?{...c,balance:n}:c);r.push({...l,tokens:u,totalIssuance:n})}),r})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,w.distinctUntilChanged)((t,e)=>!e.deltas),(0,w.map)((t,e)=>({value:t,index:e})),(0,w.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}})=>{for(let{args:e,value:i}of t?.upserted??[]){let[s]=e;this.pegs.set(i,s)}}})}subscribeEmaOracles(){return this.api.query.EmaOracle.Oracles.watchEntries({at:"best"}).pipe((0,w.distinctUntilChanged)((t,e)=>!e.deltas),(0,w.map)((t,e)=>({value:t,index:e})),(0,w.tap)(({value:t,index:e})=>{e>0&&this.log.trace("emaOracle.Oracles",t.deltas?.upserted)}),this.watchGuard("emaOracle.Oracles")).subscribe(async({value:{deltas:t}})=>{let e=new Set;for(let{args:i,value:s}of t?.upserted??[]){let[n,a,r]=i;this.emaOracles.set(s,n,a,r);let l=ai(n,a,r.type),u=this.mmRouting.byEma.get(l);u&&e.add(u)}for(let i of e){let s=await this.mmOracle.getData(i);this.log.trace("mmOracle.Hybrid",{h160:i,fresh:s}),this.mmOracles.set(s,i)}})}subscribeMMOracles(){return this.api.event.EVM.Log.watch().pipe((0,w.map)(({events:t})=>t.map(e=>Bt.parse(e.payload)).filter(e=>!!e).filter(({eventName:e})=>ts.includes(e))),(0,w.filter)(t=>t.length>0),this.watchGuard("evm.Log")).subscribe(async t=>{let e=new Set;for(let i of t){if(console.log(i),i.eventName==="ManagedOracle.PriceUpdated"){let s=this.mmRouting.byEmitter.get(i.emitter);s&&e.add(s)}if(i.eventName==="DIA.OracleUpdate"&&i.key){let s=this.mmRouting.byDiaKey.get(i.key);s&&e.add(s)}}for(let i of e){let s=await this.mmOracle.getData(i);this.log.trace("mmOracle",{h160:i,fresh:s}),this.mmOracles.set(s,i)}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(async e=>{let i=[];for(let s of e){let n=this.poolsData.get(s.id);if(n){let a=await this.getPoolPegs(s.id,n,t),r=this.getPoolAmplification(n,t);i.push({...s,...a,...r})}}return i})})}subscribeUpdates(){let t=new w.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeMMOracles()),t.add(this.subscribeIssuance()),t.add(this.subscribeBlock()),t}};var Ae={};U(Ae,{XykMath:()=>Q,XykPool:()=>kt,XykPoolClient:()=>Ct});var A=require("@galacticcouncil/math-xyk"),Q=class{static getSpotPrice(t,e,i){return(0,A.get_spot_price)(t,e,i)}static calculateInGivenOut(t,e,i){return(0,A.calculate_in_given_out)(t,e,i)}static calculateOutGivenIn(t,e,i){return(0,A.calculate_out_given_in)(t,e,i)}static calculatePoolTradeFee(t,e,i){return(0,A.calculate_pool_trade_fee)(t,e,i)}static calculateLiquidityIn(t,e,i){return(0,A.calculate_liquidity_in)(t,e,i)}static calculateSpotPrice(t,e){return(0,A.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,i,s){return(0,A.calculate_spot_price_with_fee)(t,e,i,s)}static calculateShares(t,e,i){return(0,A.calculate_shares)(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,s){return(0,A.calculate_liquidity_out_asset_a)(t,e,i,s)}static calculateLiquidityOutAssetB(t,e,i,s){return(0,A.calculate_liquidity_out_asset_b)(t,e,i,s)}};var ci=require("@galacticcouncil/common");var{FeeUtils:li}=x,kt=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=li.toPct(i.exchangeFee),r=s+n,l=[];(e<this.minTradingLimit||s<t.assetInEd)&&l.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&l.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return r>c&&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=li.toPct(i.exchangeFee),r=s-n,l=[];(e<this.minTradingLimit||s<t.assetOutEd)&&l.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&l.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return r>c&&l.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:a,errors:l}}calculateInGivenOut(t,e){let i=Q.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e){let i=Q.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){let e=Q.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=Q.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=Q.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=ci.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var ui=require("polkadot-api"),pi=require("rxjs");var Ct=class extends k{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(){return(await this.api.getStaticApis()).compat.query.XYK.PoolAssets.isCompatible(ui.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries({at:this.at}),this.getPoolLimits()]),i=t.map(async({keyArgs:s,value:n})=>{let[a]=s,[r,l]=n,[u,c,p,d]=await Promise.all([this.balance.getBalance(a,r),this.api.query.AssetRegistry.Assets.getValue(r,{at:this.at}),this.balance.getBalance(a,l),this.api.query.AssetRegistry.Assets.getValue(l,{at:this.at})]);return{address:a,type:"XYK",tokens:[{id:r,decimals:c?.decimals||this.decimals.get(r),existentialDeposit:c?.existential_deposit,balance:u.transferable,type:c?.asset_type.type},{id:l,decimals:d?.decimals||this.decimals.get(l),existentialDeposit:d?.existential_deposit,balance:p.transferable,type:d?.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 pi.Subscription.EMPTY}};var Oe={};U(Oe,{AavePool:()=>Mt,AavePoolClient:()=>Dt});var yt=require("@galacticcouncil/common");var Mt=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 yt.big.toBigInt(1,yt.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return yt.big.toBigInt(1,yt.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var hi=require("polkadot-api"),gi=require("@polkadot-api/utils"),M=require("rxjs"),oe=require("@galacticcouncil/common");var Ie=[{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"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{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"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{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"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var Mo=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var mi=require("polkadot-api"),di=require("viem");var re=class{static parse(t){let{topics:e,data:i}=t.log,s=mi.Binary.toHex(i);try{let{eventName:n,args:a}=(0,di.decodeEventLog)({abi:Ie,topics:e,data:s}),r=a.reserve.toLowerCase();return{eventName:n,reserve:r,key:`${n}:${r}`}}catch{return}}};var es=Gt(require("big.js")),Lt=require("@galacticcouncil/common");var{ERC20:Xo}=Lt.erc20,{H160:Ko}=Lt.h160;var jo=10n**27n;var{ERC20:is}=oe.erc20,ss=["Supply","Withdraw","Repay","Borrow"],Dt=class extends k{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,s=new TextEncoder().encode(i.padEnd(32,"\0")),n=(0,gi.toHex)(s);return(0,hi.AccountId)(oe.HYDRATION_SS58_PREFIX).dec(n)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:this.at})).map(async({reserve:i,atoken:s,liqudity_in:n,liqudity_out:a})=>{let[r,l,u,c]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(i,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(s,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(s,{at:this.at})]);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:u?.decimals,existentialDeposit:u?.existential_deposit,balance:a,location:c,type:u?.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:this.at});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}throw new Error("Invalid aave reserve multilocation")}return is.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:i}=t;return{assetIn:e,assetOut:i,key:`${e}:${i}`}}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,M.mergeMap)(({events:i})=>i),(0,M.map)(({payload:i})=>this.parseRouterLog(i)),(0,M.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[u,c]=l.tokens;if(c.id===i||c.id===s){let d=await this.getPoolDelta(l);r.push({...l,tokens:d})}}return r})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,M.mergeMap)(({events:t})=>t),(0,M.map)(({payload:t})=>re.parse(t)),(0,M.filter)(t=>t!==void 0),(0,M.filter)(({eventName:t})=>ss.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 M.Subscription.EMPTY}subscribeUpdates(){let t=new M.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var Be={};U(Be,{HsmMath:()=>L,HsmPool:()=>qt,HsmPoolClient:()=>Nt});var R=require("@galacticcouncil/math-hsm"),L=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,R.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,R.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,R.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,R.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,R.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,R.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,R.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,R.calculate_max_price)(t,e)}};var F=require("@galacticcouncil/common");var{FeeUtils:ft}=x,qt=class o extends rt{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=L.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),ft.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=L.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),ft.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=L.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),ft.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=L.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),ft.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=L.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=L.calculateBuybackLimit(e.toString(),ft.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let s=L.calculateBuybackPriceWithFee(i.toString(),e.toString(),ft.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=L.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 pe=require("polkadot-api"),Pi=require("@polkadot-api/utils"),E=require("rxjs"),me=require("@galacticcouncil/common");var bi=require("polkadot-api"),yi=require("viem");var le=[{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 ce=class{static parse(t){let{topics:e,data:i}=t.log,s=bi.Binary.toHex(i);try{let{eventName:n,args:a}=(0,yi.decodeEventLog)({abi:le,topics:e,data:s}),r=a.facilitatorAddress.toLowerCase();return{eventName:n,facilitator:r,key:`${n}:${r}`}}catch{return}}};var ue=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,s]=await this.client.readContract({abi:le,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-s}};var{FeeUtils:_e}=x,{H160:fi}=me.h160,ns=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Nt=class extends k{ghoClient;stableClient;constructor(t,e,i,s){super(t,e,s),this.stableClient=i,this.ghoClient=new ue(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}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),i=new TextEncoder().encode(e),s=(0,Pi.toHex)(i);return(0,pe.AccountId)(me.HYDRATION_SS58_PREFIX).dec(s)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(pe.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,s]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t,{at:this.at}),this.api.query.HSM.Collaterals.getEntries({at:this.at}),this.stableClient.getPools()]);if(i.length===0)return[];let n=this.getFacilitatorAddress(),a=fi.fromAny(n),r=this.getHollarAddress(e),l=await this.ghoClient.getFacilitatorCapacity(r,a),u=i.map(async({keyArgs:p,value:d})=>{let[h]=p,{pool_id:g,max_buy_price_coefficient:f,max_in_holding:$,purchase_fee:q,buy_back_fee:N,buyback_rate:H}=d,G=s.find(it=>it.id===g);if(G){let it=this.getPoolId(g),vt=await this.balance.getBalance(n,h);return{...G,address:it,type:"HSM",tokens:G.tokens.filter(Si=>Si.id!==g),hsmAddress:n,hsmMintCapacity:l,hollarId:t,hollarH160:r,collateralId:h,collateralBalance:vt.transferable,maxBuyPriceCoefficient:f,maxInHolding:$,purchaseFee:_e.fromPermill(q),buyBackFee:_e.fromPermill(N),buyBackRate:_e.fromPerbill(H)}}});return(await Promise.all(u)).filter(p=>p!==null)}async getPoolFees(){return{}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,E.mergeMap)(({events:t})=>t),(0,E.map)(({payload:t})=>ce.parse(t)),(0,E.filter)(t=>t!==void 0),(0,E.filter)(({eventName:t})=>ns.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=fi.fromAny(n);if(r.toLowerCase()===e){let u=await this.ghoClient.getFacilitatorCapacity(a,r);for(let c of i)s.push({...c,hsmMintCapacity:u})}return s})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(n=>{let{tokens:a,collateralId:r}=n;a.find(u=>u.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,E.combineLatest)(s).pipe((0,E.map)(n=>n.flat()),(0,E.pairwise)(),(0,E.map)(([n,a])=>this.balance.getDeltas(n,a)),this.watchGuard("balances")).subscribe(n=>{this.store.update(a=>{let r=[],l=new Map(a.map(u=>[u.collateralId,u]));return n.forEach(({id:u,balance:c})=>{let p=l.get(u);p&&(this.log.trace("balances",{id:u,balance:c}),r.push({...p,collateralBalance:c.transferable}))}),r})}):E.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 E.Subscription.EMPTY}subscribeUpdates(){let t=new E.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var de=class{static get(t){switch(t.type){case"Aave":return Mt.fromPool(t);case"XYK":return kt.fromPool(t);case"Omnipool":return It.fromPool(t);case"LBP":return Tt.fromPool(t);case"Stableswap":return rt.fromPool(t);case"HSM":return qt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var vi=require("@galacticcouncil/common"),D=require("rxjs");var Pt=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}};var{logger:as}=vi.log,he=class extends Y{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=D.Subscription.EMPTY;omniSub=D.Subscription.EMPTY;stableSub=D.Subscription.EMPTY;hsmSub=D.Subscription.EMPTY;xykSub=D.Subscription.EMPTY;lbpSub=D.Subscription.EMPTY;isReady=!1;isDestroyed=new D.Subject;constructor(t,e,i){super(t,i),this.evm=e,this.aave=new Dt(t,e,i),this.omnipool=new Ot(t,e,i),this.stableswap=new Ft(t,e,i),this.hsm=new Nt(t,e,this.stableswap,i),this.xyk=new Ct(t,e,i),this.lbp=new At(t,e,i),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}get isHistorical(){return this.at!=="best"&&this.at!=="finalized"}subscribe(t){return this.isHistorical?D.Subscription.EMPTY:t.getSubscriber().pipe((0,D.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")||(as.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 Pt(e.type)}};var ge=class{constructor(t){this.snapshot=t;let{aave:e,xyk:i,lbp:s,stable:n,omni:a}=t.pools;this.flat=[...e,...i,...s,...n,...a]}flat;async getPools(){return this.flat}async getPoolFees(t,e){let{block:i,states:s}=this.snapshot;switch(e.type){case"Aave":return{};case"XYK":{let{exchangeFee:n}=s.xyk;return{exchangeFee:n}}case"LBP":{let{repayFee:n}=s.lbp;return{exchangeFee:e.fee,repayFee:n}}case"Stableswap":return{fee:e.fee};case"Omnipool":{let n=t.assetOut,a=t.assetIn,{dynamicFees:r,emaOracles:l,assetFeeParams:u,protocolFeeParams:c,maxSlipFee:p}=s.omni,d=r.find(({asset:f})=>f===n)?.fee,h=l.find(({pair:f})=>f.join(":")===ie(n))?.oracle,g=l.find(({pair:f})=>f.join(":")===ie(a))?.oracle;return at.compute(t,i,d,h,g,u,c,p)}default:throw new Pt(e.type)}}};0&&(module.exports={PoolContextProvider,PoolError,PoolFactory,PoolType,SnapshotPoolCtxProvider,aave,hsm,lbp,omni,stable,xyk});
|