@galacticcouncil/sdk-next 1.3.0 → 1.4.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.
@@ -7,6 +7,7 @@ import { LbpPoolClient } from './lbp';
7
7
  import { OmniPoolClient } from './omni';
8
8
  import { XykPoolClient } from './xyk';
9
9
  import { StableSwapClient } from './stable';
10
+ import { UniswapV3PoolClient } from './uniswapv3';
10
11
  import { IPoolCtxProvider, Pool, PoolBase, PoolFees, PoolPair, PoolTokenOverride } from './types';
11
12
  export declare class PoolContextProvider extends Papi implements IPoolCtxProvider {
12
13
  readonly evm: EvmClient;
@@ -16,6 +17,7 @@ export declare class PoolContextProvider extends Papi implements IPoolCtxProvide
16
17
  readonly hsm: HsmPoolClient;
17
18
  readonly xyk: XykPoolClient;
18
19
  readonly lbp: LbpPoolClient;
20
+ readonly uniswapv3: UniswapV3PoolClient;
19
21
  private readonly active;
20
22
  private readonly pools;
21
23
  private readonly clients;
@@ -25,6 +27,7 @@ export declare class PoolContextProvider extends Papi implements IPoolCtxProvide
25
27
  private hsmSub;
26
28
  private xykSub;
27
29
  private lbpSub;
30
+ private v3Sub;
28
31
  private isReady;
29
32
  private isDestroyed;
30
33
  constructor(client: PolkadotClient, evm: EvmClient, at?: BlockAt);
@@ -36,6 +39,7 @@ export declare class PoolContextProvider extends Papi implements IPoolCtxProvide
36
39
  withHsm(): this;
37
40
  withXyk(override?: PoolTokenOverride[]): this;
38
41
  withLbp(): this;
42
+ withV3(): this;
39
43
  destroy(): void;
40
44
  getPools(): Promise<PoolBase[]>;
41
45
  getPoolFees(poolPair: PoolPair, pool: Pool): Promise<PoolFees>;
@@ -1 +1 @@
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});
1
+ "use strict";var zi=Object.create;var Jt=Object.defineProperty;var Xi=Object.getOwnPropertyDescriptor;var Yi=Object.getOwnPropertyNames;var Ki=Object.getPrototypeOf,ji=Object.prototype.hasOwnProperty;var W=(o,t)=>{for(var e in t)Jt(o,e,{get:t[e],enumerable:!0})},Xe=(o,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Yi(t))!ji.call(o,s)&&s!==e&&Jt(o,s,{get:()=>t[s],enumerable:!(i=Xi(t,s))||i.enumerable});return o};var _t=(o,t,e)=>(e=o!=null?zi(Ki(o)):{},Xe(t||!o||!o.__esModule?Jt(e,"default",{value:o,enumerable:!0}):e,o)),Ji=o=>Xe(Jt({},"__esModule",{value:!0}),o);var Fs={};W(Fs,{PoolContextProvider:()=>Ae,PoolError:()=>et,PoolFactory:()=>Ie,PoolType:()=>w,SnapshotPoolCtxProvider:()=>Oe,aave:()=>Ne,hsm:()=>Ve,lbp:()=>Ee,omni:()=>Fe,stable:()=>Le,uniswapv3:()=>ze,xyk:()=>De});module.exports=Ji(Fs);var Ee={};W(Ee,{LbpMath:()=>Y,LbpPool:()=>Et,LbpPoolClient:()=>Ft});var j=require("@galacticcouncil/math-lbp"),Y=class{static getSpotPrice(t,e,i,s,n){return(0,j.get_spot_price)(t,e,i,s,n)}static calculateInGivenOut(t,e,i,s,n){return(0,j.calculate_in_given_out)(t,e,i,s,n)}static calculateOutGivenIn(t,e,i,s,n){return(0,j.calculate_out_given_in)(t,e,i,s,n)}static calculateLinearWeights(t,e,i,s,n){return(0,j.calculate_linear_weights)(t,e,i,s,n)}static calculatePoolTradeFee(t,e,i){return(0,j.calculate_pool_trade_fee)(t,e,i)}};var ft=require("@galacticcouncil/common");var w=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r.HSM="HSM",r.V3="UniswapV3",r))(w||{}),et=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(et||{});var Qt={};W(Qt,{withTimeout:()=>Qi});function Qi(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 Zi=require("@galacticcouncil/common");var T={};W(T,{FeeUtils:()=>_e,shiftNeg:()=>is});var Ye=_t(require("big.js"));var _e=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 is(o,t){let e=(0,Ye.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Bt={};W(Bt,{findNestedKey:()=>ss,findNestedObj:()=>ns,jsonFormatter:()=>as});var ss=(o,t)=>{let e=[];return JSON.stringify(o,(i,s)=>(s&&s[t]&&e.push(s),s)),e[0]},ns=(o,t,e)=>{let i;return JSON.stringify(o,(s,n)=>(n&&n[t]===e&&(i=n),n)),i},as=(o,t)=>typeof t=="bigint"?t.toString():t;var K={};W(K,{calculateBuyFee:()=>cs,calculateDiffToAvg:()=>rs,calculateDiffToRef:()=>os,calculateSellFee:()=>ls});var J=_t(require("big.js"));function rs(o,t){let e=(0,J.default)(o.toString()),i=(0,J.default)(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function os(o,t){if(t===0n)return 0;let e=(0,J.default)(o.toString()),i=(0,J.default)(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function ls(o,t){if(o===0n)return 0;let e=(0,J.default)(o.toString()),i=(0,J.default)(t.toString());return(0,J.default)(1).minus(i.div(e)).mul(100).round(2).toNumber()}function cs(o,t){if(o===0n)return 0;let e=(0,J.default)(o.toString());return(0,J.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var kt=(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 Zt=(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 us=Zt(()=>"illegal argument(s)"),Ke=o=>{throw new us(o)};var ps=Zt(()=>"index out of bounds"),Be=o=>{throw new ps(o)},te=(o,t,e)=>(o<t||o>=e)&&Be(o);var je=23283064365386963e-26,ee=class{float(t=1){return this.int()*je*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*je-.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 ie=class extends ee{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 Je=new ie(Math.random);var Qe=o=>o!=null&&typeof o!="function"&&o.length!==void 0;var Ze=Object.getPrototypeOf({}),se="function",ti="string",gt=(o,t)=>{let e;if(o===t)return!0;if(o!=null){if(typeof o.equiv===se)return o.equiv(t)}else return o==t;if(t!=null){if(typeof t.equiv===se)return t.equiv(o)}else return o==t;return typeof o===ti||typeof t===ti?!1:(e=Object.getPrototypeOf(o),(e==null||e===Ze)&&(e=Object.getPrototypeOf(t),e==null||e===Ze)?gs(o,t):typeof o!==se&&o.length!==void 0&&typeof t!==se&&t.length!==void 0?ms(o,t):o instanceof Set&&t instanceof Set?ds(o,t):o instanceof Map&&t instanceof Map?hs(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)},ms=(o,t,e=gt)=>{let i=o.length;if(i===t.length)for(;i-- >0&&e(o[i],t[i]););return i<0},ds=(o,t,e=gt)=>o.size===t.size&&e([...o.keys()].sort(),[...t.keys()].sort()),hs=(o,t,e=gt)=>o.size===t.size&&e([...o].sort(),[...t].sort()),gs=(o,t,e=gt)=>{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 ke=class{value;constructor(t){this.value=t}deref(){return this.value}};var ei=o=>o instanceof ke;var ne=class o{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return ii("next",this._head)}reverseIterator(){return ii("prev",this.tail)}clear(){this.release()}compare(t,e=kt){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||Qe(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(!gt(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||kt;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&&!ei(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&&Be(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*ii(o,t){for(;t;)yield t.value,t=t[o]}var ae=class o extends ne{_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):(te(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):(te(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=Je){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)&&Ke("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=kt){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),te(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 re=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 ae,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 ct=class o extends re{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 bt=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 ct(null,{ttl:s}):new ct;return{get:(...u)=>{let p=i(...u);if(n.has(p)){this.log("[live]",t,p);let m=n.get(p);return Promise.resolve(m)}if(a.has(p))return this.log("[memo]",t,p),a.get(p);this.log("[fetch]",t,p);let h=e(...u).catch(m=>{throw a.delete(p),m});return a.set(p,h),h},set:(u,...p)=>{let h=i(...p);this.log("[set-live]",t,h),n.set(h,u)},clear:()=>{this.log("[clear]",t),n.clear(),a.release()}}}};var{FeeUtils:si}=T,Et=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=si.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),c=e+r,u=this.calculateInGivenOut(t,c),p=t.balanceIn/this.maxInRatio;return u>p&&n.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:l,errors:n}}else{let r=this.calculateInGivenOut(t,e),l=t.balanceIn/this.maxInRatio;return r>l&&n.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:n}}}validateAndSell(t,e,i){let s=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let a=t.balanceIn/this.maxInRatio;if(e>a&&n.push("MaxInRatioExceeded"),s===t.assetIn){let r=this.calculateOutGivenIn(t,e),l=t.balanceOut/this.maxOutRatio;return r>l&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:n}}else{let r=this.calculateOutGivenIn(t,e),l=this.calculateTradeFee(r,i),c=si.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),u=r-l,p=t.balanceOut/this.maxOutRatio;return u>p&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:u,feePct:c,errors:n}}}calculateInGivenOut(t,e){let i=Y.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=Y.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=Y.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),ft.big.toBigInt(1,ft.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=Y.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),ft.big.toBigInt(1,ft.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let i=Y.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var ui=require("polkadot-api"),at=require("rxjs");var ni=(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"),g=require("rxjs/operators");var Pt=require("@galacticcouncil/descriptors");var ri=require("@galacticcouncil/common"),yt=require("rxjs");var it=require("rxjs"),k=require("rxjs/operators");function ai(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>(0,it.defer)(()=>(0,it.from)(o._request("system_health",[]))).pipe((0,k.timeout)({first:e}),(0,k.map)(()=>"online"),(0,k.catchError)(()=>(0,it.of)("offline")));return(0,it.of)({state:"offline",delayMs:0}).pipe((0,k.expand)(n=>(0,it.timer)(n.delayMs).pipe((0,k.switchMap)(i),(0,k.map)(a=>({state:a,delayMs:t})))),(0,k.skip)(1),(0,k.map)(n=>n.state),(0,k.distinctUntilChanged)(),(0,k.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:bs}=ri.log,oe=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,yt.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",ai(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,yt.tap)({error:i=>bs.error(t,i)}),(0,yt.shareReplay)({bufferSize:1,refCount:!0}))}};var Q=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(Pt.hydration),this.apiNext=this.client.getTypedApi(Pt.hydrationNext),this.apiIce=this.client.getTypedApi(Pt.hydrationIce),this.watcher=oe.getInstance(this.client),this.at=e??"best"}};var fs=require("polkadot-api/ws"),ys=require("polkadot-api/logs-provider");var Ps=require("polkadot-api");var oi=require("@galacticcouncil/common"),V=require("rxjs"),f=require("rxjs/operators");var{logger:vt}=oi.log,Rt=class extends Q{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,V.defer)(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return(0,V.combineLatest)([e,i,s]).pipe((0,f.connect)(n=>(0,V.concat)(n.pipe((0,f.take)(1)),n.pipe((0,f.skip)(1),(0,f.debounceTime)(250)))))}).pipe((0,f.map)(e=>e.flat()),(0,f.startWith)([]),(0,f.bufferCount)(2,1),(0,f.map)(([e,i],s)=>s===0?i:this.getDeltas(e,i))).pipe((0,f.tap)({subscribe:()=>vt.debug("balance: subscribe",t),error:e=>vt.error("balance",e)}),(0,f.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,V.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,f.map)(({value:i})=>({id:0,balance:this.getBreakdown(i.data)})),(0,f.tap)({error:i=>vt.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return(0,V.defer)(()=>i.watchValue(t,e,{at:"best"})).pipe((0,f.map)(({value:s})=>({id:e,balance:this.getBreakdown(s)})),(0,f.tap)({error:s=>vt.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,V.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,f.distinctUntilChanged)((i,s)=>!s.deltas),(0,f.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,f.tap)({error:i=>vt.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,V.defer)(()=>(0,V.from)(e?Promise.resolve(e):i()).pipe((0,f.switchMap)(n=>this.watcher.bestBlock$.pipe((0,f.switchMap)(()=>(0,V.from)(s(n))))),(0,f.startWith)([]),(0,f.bufferCount)(2,1),(0,f.map)(([n,a],r)=>r===0?a.filter(l=>l.balance.total>0n):this.getDeltas(n,a)),(0,f.distinctUntilChanged)((n,a)=>a.length===0),(0,f.tap)({error:n=>vt.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 li=require("rxjs"),le=class{store$=new li.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 ci=require("@galacticcouncil/common");var vs={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM",UniswapV3:"UNIV3"},{logger:ce}=ci.log,ue=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${vs[this.type]})`,10)}trace(t,...e){ce.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){ce.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){ce.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){ce.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:Ss}=Qt,xs=3e3,L=class extends Q{evm;balance;store=new le;log;shared$;resync$=new P.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new ct(null,{ttl:6*1e3});memPools=ni(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 Rt(t,i),this.log=new ue(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,g.startWith)([]),(0,g.bufferCount)(2,1),(0,g.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,g.filter)(t=>t.length>0),(0,g.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,g.switchMap)(()=>{let e=new P.Subscription;return(0,P.from)(Ss(this.getMemPools(),6e4,"getMemPools stalled")).pipe((0,g.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,g.map)(s=>s.filter(n=>this.hasValidAssets(n))),(0,g.tap)(s=>this.store.set(s)),(0,g.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),P.EMPTY))).pipe((0,g.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,g.switchMap)(s=>(0,P.merge)((0,P.of)(s),this.store.asObservable().pipe((0,g.skip)(1)))),(0,g.finalize)(()=>{e.unsubscribe()}))}),(0,g.finalize)(()=>t.unsubscribe()))}).pipe((0,g.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,g.map)(n=>n.flat()),(0,g.pairwise)(),(0,g.map)(([n,a])=>this.balance.getDeltas(n,a)),(0,g.filter)(n=>n.length>0),(0,g.map)(n=>[i,n]))});return(0,P.merge)(...t).pipe((0,g.bufferTime)(250),(0,g.filter)(e=>e.length>0),(0,g.map)(e=>new Map(e)),this.watchGuard("balances")).subscribe(e=>{this.store.update(i=>this.updateBalances(i,e))})}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:i})=>t.type==="XYK"?i>0n&&!!e:!!e)}updateBalances=(t,e)=>{let i=[],s=new Map(t.map(n=>[n.address,n]));for(let[n,a]of e){let r=s.get(n);if(r){let l=r.tokens.map(c=>{let u=a.find(p=>p.id===c.id);return u&&c.id!==r.id?{...c,balance:u.balance.transferable}:c});i.push({...r,tokens:l})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<xs||(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,g.pairwise)(),(0,g.filter)(([r,l])=>r==="offline"&&l==="online"),(0,g.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,g.catchError)(r=>(this.log.error("watchdog_recovery_error",r),P.EMPTY)),(0,g.repeat)({delay:1e3})),n=this.watcher.finalizedBlock$.pipe((0,g.pairwise)(),(0,g.tap)(([r,l])=>{let c=Number(r.number),u=Number(l.number),p=u-c;p>=3&&(this.log.debug("watchdog_gap",{from:c,to:u,gap:p}),this.requestResync())}),(0,g.catchError)(r=>(this.log.error("watchdog_gap_error",r),P.EMPTY)),(0,g.repeat)({delay:1e3})),a=(0,P.interval)(36e5).pipe((0,g.tap)(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),(0,g.catchError)(r=>(this.log.error("watchdog_periodic_error",r),P.EMPTY)),(0,g.repeat)({delay:1e3}));return(0,P.merge)(s,n,a).subscribe()}watchGuard(t){return e=>e.pipe((0,g.tap)({error:i=>{this.log.error(t,i),this.requestResync(!0)}}),(0,g.finalize)(()=>{this.log.debug(t,"unsub")}),(0,g.catchError)(()=>P.EMPTY))}};var Ft=class extends L{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=Y.calculateLinearWeights(i?i.toString():"0",s?s.toString():"0",n.toString(),a.toString(),e.toString()),l=BigInt(r),c=this.MAX_FINAL_WEIGHT-BigInt(l);return[l,c]}async isSupported(){return(await this.api.getStaticApis()).compat.query.LBP.PoolData.isCompatible(ui.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,c=l.toString(),u=await this.getPoolDelta(c,r,s);return{address:c,type:"LBP",fee:r.fee,...u,...i}});return Promise.all(n)}async getPoolDelta(t,e,i){let{assets:s,repay_target:n,fee_collector:a}=e,[r,l]=this.getPoolWeights(e,i),[c,u]=s,[p,h,m,d,b]=await Promise.all([this.isRepayFeeApplied(c,n,a.toString()),this.balance.getBalance(t,c),this.api.query.AssetRegistry.Assets.getValue(c,{at:this.at}),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u,{at:this.at})]);return{repayFeeApply:p,tokens:[{id:c,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:h.transferable,weight:r,type:m?.asset_type.type},{id:u,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:d.transferable,weight:l,type:b?.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,at.map)(({value:t})=>t),(0,at.filter)(t=>t!==void 0),(0,at.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let i=[];for(let s of e){let n=this.poolsData.get(s.address);if(n){let{assets:a,repay_target:r,fee_collector:l}=n,[c]=a,[u,p]=this.getPoolWeights(n,t),[h,m]=s.tokens,d=[{...h,weight:u},{...m,weight:p}],b=await this.isRepayFeeApplied(c,r,l.toString());i.push({...s,tokens:d,repayFeeApply:b})}}return i})})}subscribeUpdates(){let t=new at.Subscription;return t.add(this.subscribeValidationData()),t}};var Fe={};W(Fe,{OmniMath:()=>x,OmniPool:()=>Ct,OmniPoolClient:()=>Mt,OmniPoolFee:()=>pt,getEmaKey:()=>me,getEmaPair:()=>St});var y=require("@galacticcouncil/math-omnipool"),ut=_t(require("big.js")),x=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,c,u){return(0,y.calculate_in_given_out)(t,e,i,s,n,a,r,l,c,u)}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,c,u){return(0,y.calculate_out_given_in)(t,e,i,s,n,a,r,l,c,u)}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,ut.default)(e),a=(0,ut.default)(t),r=(0,ut.default)(s),l=(0,ut.default)(i),c=(0,ut.default)(10).pow(18),u=l.div(c);if(n.div(r).lt(u)){let h=u.times(r).minus(n).times(a),m=n.times((0,ut.default)(1).minus(u));return h.div(m).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,c,u,p){return(0,y.recalculate_asset_fee)(t,e,i,s,n,a,r,l,c,u,p)}static recalculateProtocolFee(t,e,i,s,n,a,r,l,c,u,p){return(0,y.recalculate_protocol_fee)(t,e,i,s,n,a,r,l,c,u,p)}static verifyAssetCap(t,e,i,s){return(0,y.verify_asset_cap)(t,e,i,s)}};var pi=require("@galacticcouncil/common");var{FeeUtils:tt}=T,Ct=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:K.calculateBuyFee(s,n),r=[],l=x.isSellAllowed(t.tradeableIn),c=x.isBuyAllowed(t.tradeableOut);(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&r.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return n>p&&r.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),a=K.calculateSellFee(s,n),r=[],l=x.isSellAllowed(t.tradeableIn),c=x.isBuyAllowed(t.tradeableOut);(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&r.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return n>p&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:n,feePct:a,errors:r}}calculateInGivenOut(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,i);let s=x.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?tt.toRaw(i.assetFee).toString():"0",i?tt.toRaw(i.protocolFee).toString():"0",i?tt.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateLrnaInGivenOut(t,e,i){let s=x.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?tt.toRaw(i.assetFee).toString():"0",i?tt.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=x.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?tt.toRaw(i.assetFee).toString():"0",i?tt.toRaw(i.protocolFee).toString():"0",i?tt.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateOutGivenLrnaIn(t,e,i){let s=x.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?tt.toRaw(i.assetFee).toString():"0",i?tt.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=x.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=x.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=x.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=x.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=pi.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var st=require("polkadot-api"),hi=require("@polkadot-api/utils"),v=require("rxjs"),gi=require("@galacticcouncil/common");var{FeeUtils:C}=T,pt=class o{static compute(t,e,i,s,n,a,r,l){let c=t.assetIn,[u,p,h]=o.getAssetFee(t,e,i,s,a),m=0,d=0,b=0;c!==1&&([m,d,b]=o.getProtocolFee(t,e,i,n,r));let G=u+m,_=h+b;return{assetFee:C.fromPermill(p),protocolFee:C.fromPermill(d),maxSlipFee:C.fromPermill(l),min:C.fromPermill(G),max:C.fromPermill(_)}}static getAssetFee(t,e,i,s,n){let{assetOut:a,balanceOut:r}=t,{min_fee:l,max_fee:c,decay:u,amplification:p}=n;if(!i||!s)return[l,l,c];let h=C.fromPermill(l),m=C.fromPermill(c),[d]=s,{asset_fee:b,timestamp:G}=i,_=Math.max(1,e-G),q=d.volume.b_in.toString(),F=d.volume.b_out.toString(),B=d.liquidity.b.toString();a===0&&(q=d.volume.a_in.toString(),F=d.volume.a_out.toString(),B=d.liquidity.a.toString());let $=C.fromPermill(b),X=x.recalculateAssetFee(q,F,B,"9",r.toString(),C.toRaw($).toString(),_.toString(),C.toRaw(h).toString(),C.toRaw(m).toString(),u.toString(),p.toString());return[l,Number(X)*1e6,c]}static getProtocolFee(t,e,i,s,n){let{assetIn:a,balanceIn:r}=t,{min_fee:l,max_fee:c,decay:u,amplification:p}=n;if(!i||!s)return[l,l,c];let h=C.fromPermill(l),m=C.fromPermill(c),[d]=s,{protocol_fee:b,timestamp:G}=i,_=Math.max(1,e-G),q=d.volume.b_in.toString(),F=d.volume.b_out.toString(),B=d.liquidity.b.toString();a===0&&(q=d.volume.a_in.toString(),F=d.volume.a_out.toString(),B=d.liquidity.a.toString());let $=C.fromPermill(b),X=x.recalculateProtocolFee(q,F,B,"9",r.toString(),C.toRaw($).toString(),_.toString(),C.toRaw(h).toString(),C.toRaw(m).toString(),u.toString(),p.toString());return[l,Number(X)*1e6,c]}};var St=o=>o===0?[0,1]:[1,o],me=o=>St(o).join(":");var{FeeUtils:Re}=T,mi=st.Binary.toHex(st.Binary.fromText("omnipool")),di=(0,st.Enum)("Short"),Mt=class extends L{queryBus=new bt;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(mi,t,di,{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,hi.toHex)(e);return(0,st.AccountId)(gi.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(st.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 c=i.map(async({keyArgs:p,value:h})=>{let[m]=p,{hub_reserve:d,shares:b,tradable:G,cap:_,protocol_shares:q}=h,[F,B]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m,{at:this.at}),this.balance.getBalance(e,m)]);return{id:m,decimals:F?.decimals,existentialDeposit:F?.existential_deposit,balance:B.transferable,cap:_,hubReserves:d,protocolShares:q,shares:b,tradeable:G,type:F?.asset_type.type}}),u=await Promise.all(c);return u.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:u,...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:h,protocol_fee:m}=a.value;return{assetFee:Re.fromPermill(h),protocolFee:Re.fromPermill(m),maxSlipFee:Re.fromPermill(n)}}let[r,l,c,u,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(St(e)),this.emaOracles.get(St(i)),a?a.value.asset_fee_params:this.api.constants.DynamicFees.AssetFeeParameters(),a?a.value.protocol_fee_params:this.api.constants.DynamicFees.ProtocolFeeParameters()]);return pt.compute(t,this.block,r,l,c,u,p,n)}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(s=>s.id).map(s=>St(s)).map(s=>this.api.query.EmaOracle.Oracles.watchValue(mi,s,di,{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 Le={};W(Le,{StableMath:()=>E,StableSwap:()=>mt,StableSwapClient:()=>Gt});var I=require("@galacticcouncil/math-stableswap"),E=class{static getPoolAddress(t){return(0,I.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,I.calculate_amplification)(t,e,i,s,n)}static calculateInGivenOut(t,e,i,s,n,a,r){return(0,I.calculate_in_given_out)(t,e,i,s,n,a,r)}static calculateAddOneAsset(t,e,i,s,n,a,r){return(0,I.calculate_add_one_asset)(t,e,i,s,n,a,r)}static calculateSharesForAmount(t,e,i,s,n,a,r){return(0,I.calculate_shares_for_amount)(t,e,i,s,n,a,r)}static calculateOutGivenIn(t,e,i,s,n,a,r){return(0,I.calculate_out_given_in)(t,e,i,s,n,a,r)}static calculateLiquidityOutOneAsset(t,e,i,s,n,a,r){return(0,I.calculate_liquidity_out_one_asset)(t,e,i,s,n,a,r)}static calculateShares(t,e,i,s,n,a){return(0,I.calculate_shares)(t,e,i,s,n,a)}static calculateSpotPriceWithFee(t,e,i,s,n,a,r,l){return(0,I.calculate_spot_price_with_fee)(t,e,i,s,n,a,r,l)}static recalculatePegs(t,e,i,s,n,a){let r=(0,I.recalculate_peg)(t,e,i,s,n,a);return JSON.parse(r)}};var Lt=require("@galacticcouncil/common");var{FeeUtils:xt}=T,mt=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:K.calculateBuyFee(s,n),r=[],l=x.isSellAllowed(t.tradeableIn),c=x.isBuyAllowed(t.tradeableOut);return(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),a=K.calculateSellFee(s,n),r=[],l=x.isSellAllowed(t.tradeableIn),c=x.isBuyAllowed(t.tradeableOut);return(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:n,feePct:a,errors:r}}calculateIn(t,e,i){let s=E.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?xt.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateAddOneAsset(t,e,i){let s=E.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?xt.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateSharesForAmount(t,e,i){let s=E.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?xt.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=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=E.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?xt.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateWithdrawOneAsset(t,e,i){let s=E.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?xt.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateShares(t,e,i){let s=E.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?xt.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=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,Bt.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],Bt.jsonFormatter)}normalizeSpot(t,e,i,s,n){return e?t*Lt.big.pow10(Lt.RUNTIME_DECIMALS-n):i?t/Lt.big.pow10(n-s):t}};var he=require("polkadot-api"),Ti=require("@polkadot-api/utils"),wi=require("@noble/hashes/blake2b"),A=require("rxjs"),ge=require("@galacticcouncil/common");var yi=require("polkadot-api"),Me=require("viem");var Ce=[{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"}],bi=[{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"}],fi=[{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 Dt=class{static parse(t){let{address:e,topics:i,data:s}=t.log,n=e.toLowerCase(),a=yi.Binary.toHex(s);try{let{eventName:r,args:l}=(0,Me.decodeEventLog)({abi:fi,topics:i,data:a});return{eventName:`ManagedOracle.${r}`,emitter:n,value:l.answer,timestamp:l.timestamp}}catch{}try{let{eventName:r,args:l}=(0,Me.decodeEventLog)({abi:bi,topics:i,data:a});return{eventName:`DIA.${r}`,emitter:n,key:l.key,value:l.value,timestamp:l.timestamp}}catch{}}};var qt=class{adapter;constructor(t){this.adapter=t.getRPCAdapter()}async getData(t,e=6){let[i,s,n]=await Promise.all([this.adapter.readContract({abi:Ce,address:t,functionName:"latestRoundData"}),this.adapter.readContract({abi:Ce,address:t,functionName:"decimals"}),this.adapter.getBlock()]),[a,r,l,c]=i,u=n.number-(n.timestamp-c)/BigInt(e),p=Number(u);return{price:r,decimals:s,updatedAt:p<0?0:p}}};var Pi={"EUR/USD":"0xaa47a5662269270d3df33ae08f806e383611575c","sUSDs/USD":"0x4b32bffc6acd751446e79e8687ef3815fd7924fd","sUSDe/USD":"0x22cdea305cee63d082e79f8c5db939eecd0265d0"},vi={"0xcfab6a4031c70da0f0cf6f31a252c16119db3611":"0xaafd758688cefd0a7b7770a825f1aad551e16185"},Si={"bifrosto:5:15:LastBlock":"0xaafd758688cefd0a7b7770a825f1aad551e16185"};function xi(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:Tt}=T,Nt=class o{static compute(t,e,i,s){let n=o.getRecent(e),a=Tt.fromPermill(t.fee),r=Tt.fromPerbill(e.max_peg_update),l=i.map(({pair:d,updatedAt:b})=>[d,b]),c=i.find(d=>d.source),u=e.updated_at?e.updated_at.toString():c?.updatedAt;if(!u)throw new Error("Current peg unknown!");let[p,h]=E.recalculatePegs(JSON.stringify(n),u,JSON.stringify(l),s.toString(),Tt.toRaw(r).toString(),Tt.toRaw(a).toString()),m=Number(p)*1e6;return{pegsFee:Tt.fromPermill(m),pegs:h}}static getDefault(t){return{pegsFee:Tt.fromPermill(t.fee),pegs:E.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:Ts}=T,ws=["ManagedOracle.PriceUpdated","DIA.OracleUpdate"],Gt=class extends L{poolsData=new Map([]);mmOracle=new qt(this.evm);mmAddresses=new Set;mmRouting={byEmitter:new Map,byDiaKey:new Map,byEma:new Map};queryBus=new bt;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=E.getPoolAddress(t),i=(0,wi.blake2b)(e,{dkLen:32}),s=(0,Ti.toHex)(i);return(0,he.AccountId)(ge.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=E.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(vi)){let i=t.toLowerCase(),s=e.toLowerCase();this.mmAddresses.has(s)&&this.mmRouting.byEmitter.set(i,s)}for(let[t,e]of Object.entries(Pi)){let i=e.toLowerCase();this.mmAddresses.has(i)&&this.mmRouting.byDiaKey.set(t,i)}for(let[t,e]of Object.entries(Si)){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(he.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 c of r.source)c.type==="MMOracle"&&this.mmAddresses.add(c.value.toString().toLowerCase())}this.buildRouting();let n=t.map(async({keyArgs:a,value:r})=>{let[l]=a,c=this.getPoolAddress(l),[u,p,h,m]=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 u.push({id:l,tradeable:15,balance:m,decimals:ge.RUNTIME_DECIMALS}),this.poolsData.set(l,r),{address:c,id:l,type:"Stableswap",fee:Ts.fromPermill(r.fee),tokens:u,totalIssuance:m,...h,...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 Nt.getDefault(e);let n=await this.getLatestPegs(e,s,i);return Nt.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[c,u,p]=r.value,h=[p,n[l]].sort((_,q)=>_-q),m=await this.emaOracles.get(c,h,u);if(!m)throw new Error("EmaOracle missing for "+c+" / "+h);let[{price:d,updated_at:b}]=m;return{pair:p===h[0]?[d.n.toString(),d.d.toString()]:[d.d.toString(),d.n.toString()],updatedAt:b.toString(),source:r.type}}if(r.type==="MMOracle"){let c=r.value.toString(),{price:u,decimals:p,updatedAt:h}=await this.mmOracles.get(c),m=(10n**BigInt(p)).toString();return{pair:[u.toString(),m],updatedAt:h.toString(),source:r.type}}if(r.type==="Value")return{pair:r.value.map(u=>u.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,A.map)(({value:s})=>s),(0,A.map)((s,n)=>({value:s,index:n})),(0,A.tap)(({index:s,value:n})=>{s>0&&this.log.trace("tokens.TotalIssuance",i,n)}),(0,A.map)(({value:s})=>({id:i,value:s}))));return(0,A.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:s,value:n}=i;this.store.update(a=>{let r=[];return a.filter(l=>l.id===s).forEach(l=>{let c=l.tokens.map(u=>u.id===s?{...u,balance:n}:u);r.push({...l,tokens:c,totalIssuance:n})}),r})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,A.distinctUntilChanged)((t,e)=>!e.deltas),(0,A.map)((t,e)=>({value:t,index:e})),(0,A.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,A.distinctUntilChanged)((t,e)=>!e.deltas),(0,A.map)((t,e)=>({value:t,index:e})),(0,A.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=xi(n,a,r.type),c=this.mmRouting.byEma.get(l);c&&e.add(c)}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,A.map)(({events:t})=>t.map(e=>Dt.parse(e.payload)).filter(e=>!!e).filter(({eventName:e})=>ws.includes(e))),(0,A.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 A.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeMMOracles()),t.add(this.subscribeIssuance()),t.add(this.subscribeBlock()),t}};var De={};W(De,{XykMath:()=>nt,XykPool:()=>Vt,XykPoolClient:()=>Ht});var O=require("@galacticcouncil/math-xyk"),nt=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 Ai=require("@galacticcouncil/common");var{FeeUtils:Ii}=T,Vt=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=Ii.toPct(i.exchangeFee),r=s+n,l=[];(e<this.minTradingLimit||s<t.assetInEd)&&l.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&l.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return r>u&&l.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:a,errors:l}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateTradeFee(s,i),a=Ii.toPct(i.exchangeFee),r=s-n,l=[];(e<this.minTradingLimit||s<t.assetOutEd)&&l.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&l.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return r>u&&l.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:a,errors:l}}calculateInGivenOut(t,e){let i=nt.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e){let i=nt.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){let e=nt.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=nt.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=nt.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=Ai.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var Oi=require("polkadot-api"),_i=require("rxjs");var Ht=class extends L{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(Oi.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,[c,u,p,h]=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:u?.decimals||this.decimals.get(r),existentialDeposit:u?.existential_deposit,balance:c.transferable,type:u?.asset_type.type},{id:l,decimals:h?.decimals||this.decimals.get(l),existentialDeposit:h?.existential_deposit,balance:p.transferable,type:h?.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 _i.Subscription.EMPTY}};var Ne={};W(Ne,{AavePool:()=>Ut,AavePoolClient:()=>Wt});var wt=require("@galacticcouncil/common");var Ut=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 wt.big.toBigInt(1,wt.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return wt.big.toBigInt(1,wt.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var Ei=require("polkadot-api"),Ri=require("@polkadot-api/utils"),H=require("rxjs"),fe=require("@galacticcouncil/common");var qe=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{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 ll=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Bi=require("polkadot-api"),ki=require("viem");var be=class{static parse(t){let{topics:e,data:i}=t.log,s=Bi.Binary.toHex(i);try{let{eventName:n,args:a}=(0,ki.decodeEventLog)({abi:qe,topics:e,data:s}),r=a.reserve.toLowerCase();return{eventName:n,reserve:r,key:`${n}:${r}`}}catch{return}}};var Is=_t(require("big.js")),$t=require("@galacticcouncil/common");var{ERC20:Sl}=$t.erc20,{H160:xl}=$t.h160;var Tl=10n**27n;var{ERC20:As}=fe.erc20,Os=["Supply","Withdraw","Repay","Borrow"],Wt=class extends L{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,s=new TextEncoder().encode(i.padEnd(32,"\0")),n=(0,Ri.toHex)(s);return(0,Ei.AccountId)(fe.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,c,u]=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:c?.decimals,existentialDeposit:c?.existential_deposit,balance:a,location:u,type:c?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:s,liqudity_out:n}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at: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 As.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,H.mergeMap)(({events:i})=>i),(0,H.map)(({payload:i})=>this.parseRouterLog(i)),(0,H.filter)(({assetIn:i,assetOut:s})=>e.includes(i)||e.includes(s)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:s,key:n})=>{this.log.trace("router.Executed",n),this.store.update(async a=>{let r=[];for(let l of a){let[c,u]=l.tokens;if(u.id===i||u.id===s){let h=await this.getPoolDelta(l);r.push({...l,tokens:h})}}return r})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,H.mergeMap)(({events:t})=>t),(0,H.map)(({payload:t})=>be.parse(t)),(0,H.filter)(t=>t!==void 0),(0,H.filter)(({eventName:t})=>Os.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 H.Subscription.EMPTY}subscribeUpdates(){let t=new H.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var Ve={};W(Ve,{HsmMath:()=>z,HsmPool:()=>zt,HsmPoolClient:()=>Xt});var D=require("@galacticcouncil/math-hsm"),z=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,D.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,D.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,D.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,D.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,D.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,D.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,D.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,D.calculate_max_price)(t,e)}};var N=require("@galacticcouncil/common");var{FeeUtils:It}=T,zt=class o extends mt{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=z.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),It.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=z.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),It.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=z.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),It.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=z.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),It.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=z.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=z.calculateBuybackLimit(e.toString(),It.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let s=z.calculateBuybackPriceWithFee(i.toString(),e.toString(),It.toRaw(this.buyBackFee).toString()),[n,a]=JSON.parse(s),r=N.big.pow10(t.decimalsIn+N.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(n)*r/BigInt(a)}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=z.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[s,n]=JSON.parse(i),a=N.big.pow10(N.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(s)*a/BigInt(n)}spotPriceInGivenOut(t){let e=N.big.toBigInt(1,t.decimalsOut),s=this.calculateInGivenOut(t,e)*N.big.pow10(N.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(s,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=N.big.toBigInt(1,t.decimalsIn),s=this.calculateOutGivenIn(t,e)*N.big.pow10(N.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)?[N.big.toBigInt(1,18).toString(),N.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=N.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var Se=require("polkadot-api"),Li=require("@polkadot-api/utils"),M=require("rxjs"),xe=require("@galacticcouncil/common");var Fi=require("polkadot-api"),Ci=require("viem");var ye=[{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 Pe=class{static parse(t){let{topics:e,data:i}=t.log,s=Fi.Binary.toHex(i);try{let{eventName:n,args:a}=(0,Ci.decodeEventLog)({abi:ye,topics:e,data:s}),r=a.facilitatorAddress.toLowerCase();return{eventName:n,facilitator:r,key:`${n}:${r}`}}catch{return}}};var ve=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,s]=await this.client.readContract({abi:ye,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-s}};var{FeeUtils:Ge}=T,{H160:Mi}=xe.h160,_s=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Xt=class extends L{ghoClient;stableClient;constructor(t,e,i,s){super(t,e,s),this.stableClient=i,this.ghoClient=new ve(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,Li.toHex)(i);return(0,Se.AccountId)(xe.HYDRATION_SS58_PREFIX).dec(s)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(Se.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=Mi.fromAny(n),r=this.getHollarAddress(e),l=await this.ghoClient.getFacilitatorCapacity(r,a),c=i.map(async({keyArgs:p,value:h})=>{let[m]=p,{pool_id:d,max_buy_price_coefficient:b,max_in_holding:G,purchase_fee:_,buy_back_fee:q,buyback_rate:F}=h,B=s.find($=>$.id===d);if(B){let $=this.getPoolId(d),X=await this.balance.getBalance(n,m);return{...B,address:$,type:"HSM",tokens:B.tokens.filter(lt=>lt.id!==d),hsmAddress:n,hsmMintCapacity:l,hollarId:t,hollarH160:r,collateralId:m,collateralBalance:X.transferable,maxBuyPriceCoefficient:b,maxInHolding:G,purchaseFee:Ge.fromPermill(_),buyBackFee:Ge.fromPermill(q),buyBackRate:Ge.fromPerbill(F)}}});return(await Promise.all(c)).filter(p=>p!==null)}async getPoolFees(){return{}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,M.mergeMap)(({events:t})=>t),(0,M.map)(({payload:t})=>Pe.parse(t)),(0,M.filter)(t=>t!==void 0),(0,M.filter)(({eventName:t})=>_s.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=Mi.fromAny(n);if(r.toLowerCase()===e){let c=await this.ghoClient.getFacilitatorCapacity(a,r);for(let u of i)s.push({...u,hsmMintCapacity:c})}return s})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(n=>{let{tokens:a,collateralId:r}=n;a.find(c=>c.id===r).type==="Erc20"?e.push(r):t.push(r)});let[{hsmAddress:i}]=this.store.pools,s=[];if(t.length>0){let n=this.balance.watchTokensBalance(i);s.push(n)}if(e.length>0){let n=this.balance.watchErc20Balance(i,e);s.push(n)}return s.length>0?(0,M.combineLatest)(s).pipe((0,M.map)(n=>n.flat()),(0,M.pairwise)(),(0,M.map)(([n,a])=>this.balance.getDeltas(n,a)),this.watchGuard("balances")).subscribe(n=>{this.store.update(a=>{let r=[],l=new Map(a.map(c=>[c.collateralId,c]));return n.forEach(({id:c,balance:u})=>{let p=l.get(c);p&&(this.log.trace("balances",{id:c,balance:u}),r.push({...p,collateralBalance:u.transferable}))}),r})}):M.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 M.Subscription.EMPTY}subscribeUpdates(){let t=new M.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var ze={};W(ze,{UNISWAP_V3_FACTORY:()=>He,UniswapV3Math:()=>At,UniswapV3Pool:()=>Yt,UniswapV3PoolClient:()=>jt,V3_POOLS:()=>Ue,ticksInWord:()=>$i});var He="0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0",Ue=[{assetA:16,assetB:9,fee:3e3},{assetA:16,assetB:9,fee:500}];var S=_t(require("jsbi")),R=require("@uniswap/v3-sdk"),$e=S.default.BigInt(0),Di=S.default.BigInt(1),We=S.default.BigInt(-1),At=class o{static calculateOutGivenIn(t,e,i){if(i<=0n||t.liquidity<=0n)return 0n;let s=o.computeSwap(t,e,S.default.BigInt(i.toString())),n=S.default.multiply(s.amountCalculated,We);return BigInt(n.toString())}static calculateInGivenOut(t,e,i){if(i<=0n||t.liquidity<=0n)return 0n;let s=o.computeSwap(t,e,S.default.multiply(S.default.BigInt(i.toString()),We));return BigInt(s.amountCalculated.toString())}static computeSwap(t,e,i){let s=o.buildTicks(t.ticks),n=t.tickSpacing,a=t.fee,r=e?S.default.add(R.TickMath.MIN_SQRT_RATIO,Di):S.default.subtract(R.TickMath.MAX_SQRT_RATIO,Di),l=S.default.greaterThanOrEqual(i,$e),c=i,u=$e,p=S.default.BigInt(t.sqrtPriceX96.toString()),h=t.tick,m=S.default.BigInt(t.liquidity.toString());for(;S.default.notEqual(c,$e)&&S.default.notEqual(p,r);){let d=p,[b,G]=R.TickList.nextInitializedTickWithinOneWord(s,h,e,n);b<R.TickMath.MIN_TICK?b=R.TickMath.MIN_TICK:b>R.TickMath.MAX_TICK&&(b=R.TickMath.MAX_TICK);let _=R.TickMath.getSqrtRatioAtTick(b),q=(e?S.default.lessThan(_,r):S.default.greaterThan(_,r))?r:_,[F,B,$,X]=R.SwapMath.computeSwapStep(p,q,m,c,a);if(p=F,l?(c=S.default.subtract(c,S.default.add(B,X)),u=S.default.subtract(u,$)):(c=S.default.add(c,$),u=S.default.add(u,S.default.add(B,X))),S.default.equal(p,_)){if(G){let lt=R.TickList.getTick(s,b).liquidityNet;e&&(lt=S.default.multiply(lt,We)),m=R.LiquidityMath.addDelta(m,lt)}h=e?b-1:b}else S.default.notEqual(p,d)&&(h=R.TickMath.getTickAtSqrtRatio(p))}return{amountCalculated:u,sqrtPriceX96:p,liquidity:m,tick:h}}static buildTicks(t){return t.map(e=>new R.Tick({index:e.index,liquidityGross:e.liquidityGross.toString(),liquidityNet:e.liquidityNet.toString()})).sort((e,i)=>e.index-i.index)}};var Gi=require("@galacticcouncil/common");var Bs=1e6,qi=10n**BigInt(Gi.RUNTIME_DECIMALS),Ni=192n,Yt=class o{type;address;id;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;token0;token1;sqrtPriceX96;tick;liquidity;tickSpacing;ticks;static fromPool(t){return new o(t)}constructor(t){this.type="UniswapV3",this.address=t.address,this.id=t.id,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.token0=t.token0,this.token1=t.token1,this.sqrtPriceX96=t.sqrtPriceX96,this.tick=t.tick,this.liquidity=t.liquidity,this.tickSpacing=t.tickSpacing,this.ticks=t.ticks}validatePair(t,e){let i=s=>s===this.token0||s===this.token1;return i(t)&&i(e)&&t!==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,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:s.balance,balanceOut:n.balance,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}calculateInGivenOut(t,e,i){return At.calculateInGivenOut(this.toState(i!=null),this.isZeroForOne(t.assetIn),e)}calculateOutGivenIn(t,e,i){return At.calculateOutGivenIn(this.toState(i!=null),this.isZeroForOne(t.assetIn),e)}spotPriceOutGivenIn(t){let e=this.spotOutPerIn(this.isZeroForOne(t.assetIn));return this.normalizeSpot(e,t.decimalsIn,t.decimalsOut)}spotPriceInGivenOut(t){let e=this.spotOutPerIn(!this.isZeroForOne(t.assetIn));return this.normalizeSpot(e,t.decimalsOut,t.decimalsIn)}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,this.fees()),a=K.calculateSellFee(s,n),r=[];(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&r.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return n>c&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:n,feePct:a,errors:r}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,this.fees()),a=K.calculateBuyFee(s,n),r=[];(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&r.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return n>c&&r.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:a,errors:r}}fees(){return{fee:[this.fee,Bs]}}isZeroForOne(t){return t===this.token0}toState(t){return{fee:t?this.fee:0,sqrtPriceX96:this.sqrtPriceX96,tick:this.tick,liquidity:this.liquidity,tickSpacing:this.tickSpacing,ticks:this.ticks}}spotOutPerIn(t){let e=this.sqrtPriceX96*this.sqrtPriceX96;if(e===0n)return 0n;let i=e*qi>>Ni;return t?i:(qi<<Ni)/e}normalizeSpot(t,e,i){let s=e-i;if(s===0)return t;let n=10n**BigInt(Math.abs(s));return s>0?t*n:t/n}};var ot=require("rxjs"),Ui=require("@galacticcouncil/common"),rt=require("@uniswap/v3-sdk");var Te=require("viem"),Vi=(0,Te.parseAbi)(["function getPool(address tokenA, address tokenB, uint24 fee) view returns (address pool)"]),dt=(0,Te.parseAbi)(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)","function liquidity() view returns (uint128)","function tickBitmap(int16 wordPosition) view returns (uint256)","function ticks(int24 tick) view returns (uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized)"]),Kt=(0,Te.parseAbi)(["function balanceOf(address account) view returns (uint256)"]);var{ERC20:we}=Ui.erc20,ks="0x0000000000000000000000000000000000000000",Es=1e6,Hi=5;function $i(o,t,e){let i=[];for(let s=0;s<256;s++)o>>BigInt(s)&1n&&i.push((t*256+s)*e);return i}var jt=class extends L{getPoolType(){return"UniswapV3"}async isSupported(){return!0}async getPoolFees(t,e){let i=this.store.pools.find(n=>n.address===e);return{fee:[i?i.fee:0,Es]}}async loadPools(){let t=this.evm.getWsProvider();return(await Promise.all(Ue.map(i=>this.loadPool(t,i)))).filter(i=>i!==void 0)}async loadPool(t,e){try{let{assetA:i,assetB:s,fee:n}=e,a=rt.TICK_SPACINGS[n];if(a===void 0)return;let r=we.fromAssetId(i).toLowerCase(),l=we.fromAssetId(s).toLowerCase(),c=r<l,u=c?i:s,p=c?s:i,h=c?r:l,m=c?l:r,d=await t.readContract({abi:Vi,address:He,functionName:"getPool",args:[h,m,n]});if(d.toLowerCase()===ks)return;let[b,G,_,q,F,B]=await Promise.all([t.readContract({abi:dt,address:d,functionName:"slot0"}),t.readContract({abi:dt,address:d,functionName:"liquidity"}),t.readContract({abi:Kt,address:h,functionName:"balanceOf",args:[d]}),t.readContract({abi:Kt,address:m,functionName:"balanceOf",args:[d]}),this.api.query.AssetRegistry.Assets.getValue(u,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(p,{at:this.at})]),$=b[0],X=b[1],lt=await this.loadTicks(t,d,X,a);return{address:d,type:"UniswapV3",token0:u,token1:p,fee:n,sqrtPriceX96:$,tick:X,liquidity:G,tickSpacing:a,ticks:lt,tokens:[{id:u,decimals:F?.decimals,existentialDeposit:F?.existential_deposit??0n,balance:_,type:F?.asset_type.type},{id:p,decimals:B?.decimals,existentialDeposit:B?.existential_deposit??0n,balance:q,type:B?.asset_type.type}],maxInRatio:3n,maxOutRatio:3n,minTradingLimit:0n}}catch(i){this.log.error("v3_load_pool",e,i);return}}async loadTicks(t,e,i,s){let n=Math.floor(i/s)>>8,a=[];for(let m=n-Hi;m<=n+Hi;m++)a.push(m);let r=await Promise.all(a.map(m=>t.readContract({abi:dt,address:e,functionName:"tickBitmap",args:[m]}))),l=a.flatMap((m,d)=>$i(r[d],m,s)),c=await Promise.all(l.map(m=>t.readContract({abi:dt,address:e,functionName:"ticks",args:[m]}))),u=l.map((m,d)=>({index:m,liquidityGross:c[d][0],liquidityNet:c[d][1]})),p=(0,rt.nearestUsableTick)(rt.TickMath.MIN_TICK,s),h=(0,rt.nearestUsableTick)(rt.TickMath.MAX_TICK,s);return u.some(m=>m.index===p)||u.push({index:p,liquidityNet:0n,liquidityGross:0n}),u.some(m=>m.index===h)||u.push({index:h,liquidityNet:0n,liquidityGross:0n}),u.sort((m,d)=>m.index-d.index),u}async refreshPool(t,e){let i=e.address,s=we.fromAssetId(e.token0).toLowerCase(),n=we.fromAssetId(e.token1).toLowerCase(),[a,r,l,c]=await Promise.all([t.readContract({abi:dt,address:i,functionName:"slot0"}),t.readContract({abi:dt,address:i,functionName:"liquidity"}),t.readContract({abi:Kt,address:s,functionName:"balanceOf",args:[i]}),t.readContract({abi:Kt,address:n,functionName:"balanceOf",args:[i]})]),u=a[1],p=await this.loadTicks(t,i,u,e.tickSpacing),h=e.tokens.map(m=>m.id===e.token0?{...m,balance:l}:{...m,balance:c});return{...e,sqrtPriceX96:a[0],tick:u,liquidity:r,ticks:p,tokens:h}}subscribeBalances(){return ot.Subscription.EMPTY}subscribeUpdates(){let t=new Set(this.store.pools.map(e=>e.address.toLowerCase()));return this.api.event.EVM.Log.watch().pipe((0,ot.mergeMap)(({events:e})=>e),(0,ot.map)(({payload:e})=>e.log.address.toLowerCase()),(0,ot.filter)(e=>t.has(e)),this.watchGuard("evm.Log")).subscribe(e=>{this.log.trace("evm.Log",e),this.store.update(async i=>{let s=this.evm.getWsProvider(),n=[];for(let a of i)a.address.toLowerCase()===e&&n.push(await this.refreshPool(s,a));return n})})}};var Ie=class{static get(t){switch(t.type){case"Aave":return Ut.fromPool(t);case"XYK":return Vt.fromPool(t);case"Omnipool":return Ct.fromPool(t);case"LBP":return Et.fromPool(t);case"Stableswap":return mt.fromPool(t);case"HSM":return zt.fromPool(t);case"UniswapV3":return Yt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var Wi=require("@galacticcouncil/common"),U=require("rxjs");var Ot=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}};var{logger:Rs}=Wi.log,Ae=class extends Q{evm;aave;omnipool;stableswap;hsm;xyk;lbp;uniswapv3;active=new Set([]);pools=new Map([]);clients=[];aaveSub=U.Subscription.EMPTY;omniSub=U.Subscription.EMPTY;stableSub=U.Subscription.EMPTY;hsmSub=U.Subscription.EMPTY;xykSub=U.Subscription.EMPTY;lbpSub=U.Subscription.EMPTY;v3Sub=U.Subscription.EMPTY;isReady=!1;isDestroyed=new U.Subject;constructor(t,e,i){super(t,i),this.evm=e,this.aave=new Wt(t,e,i),this.omnipool=new Mt(t,e,i),this.stableswap=new Gt(t,e,i),this.hsm=new Xt(t,e,this.stableswap,i),this.xyk=new Ht(t,e,i),this.lbp=new Ft(t,e,i),this.uniswapv3=new jt(t,e,i),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp,this.uniswapv3]}get isHistorical(){return this.at!=="best"&&this.at!=="finalized"}subscribe(t){return this.isHistorical?U.Subscription.EMPTY:t.getSubscriber().pipe((0,U.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")||(Rs.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}withV3(){return this.v3Sub.unsubscribe(),this.v3Sub=this.subscribe(this.uniswapv3),this.active.add("UniswapV3"),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 Ot(e.type)}};var Oe=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:c,protocolFeeParams:u,maxSlipFee:p}=s.omni,h=r.find(({asset:b})=>b===n)?.fee,m=l.find(({pair:b})=>b.join(":")===me(n))?.oracle,d=l.find(({pair:b})=>b.join(":")===me(a))?.oracle;return pt.compute(t,i,h,m,d,c,u,p)}default:throw new Ot(e.type)}}};0&&(module.exports={PoolContextProvider,PoolError,PoolFactory,PoolType,SnapshotPoolCtxProvider,aave,hsm,lbp,omni,stable,uniswapv3,xyk});
@@ -7,4 +7,5 @@ export * as stable from './stable';
7
7
  export * as hsm from './hsm';
8
8
  export * as xyk from './xyk';
9
9
  export * as lbp from './lbp';
10
+ export * as uniswapv3 from './uniswapv3';
10
11
  export * from './types';