@galacticcouncil/sdk-next 1.0.0-beta.0 → 1.0.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.
Files changed (151) hide show
  1. package/README.md +131 -78
  2. package/build/aave/AaveClient.d.ts +77 -0
  3. package/build/aave/AaveUtils.d.ts +78 -0
  4. package/build/aave/abi/AavePool.d.ts +208 -0
  5. package/build/aave/abi/AavePoolDataProvider.d.ts +384 -0
  6. package/build/aave/abi/index.d.ts +2 -0
  7. package/build/aave/const.d.ts +6 -0
  8. package/build/aave/index.cjs +1 -0
  9. package/build/aave/index.d.ts +4 -0
  10. package/build/aave/index.mjs +1 -0
  11. package/build/aave/types.d.ts +17 -0
  12. package/build/api/Papi.d.ts +10 -0
  13. package/build/api/Watcher.d.ts +11 -0
  14. package/build/api/index.d.ts +3 -0
  15. package/build/api/probe.d.ts +26 -0
  16. package/build/api/provider/index.d.ts +2 -0
  17. package/build/api/provider/smoldot.d.ts +1 -0
  18. package/build/api/provider/websocket.d.ts +4 -0
  19. package/build/{types/client → client}/AssetClient.d.ts +1 -1
  20. package/build/client/BalanceClient.d.ts +20 -0
  21. package/build/client/ChainParams.d.ts +9 -0
  22. package/build/client/index.cjs +1 -0
  23. package/build/{types/client → client}/index.d.ts +1 -0
  24. package/build/client/index.mjs +1 -0
  25. package/build/{types/consts.d.ts → consts.d.ts} +2 -2
  26. package/build/evm/adapter.d.ts +11 -0
  27. package/build/evm/chain.d.ts +2 -0
  28. package/build/evm/client.d.ts +15 -0
  29. package/build/evm/index.cjs +1 -0
  30. package/build/evm/index.d.ts +4 -0
  31. package/build/evm/index.mjs +1 -0
  32. package/build/evm/types.d.ts +7 -0
  33. package/build/factory.d.ts +29 -0
  34. package/build/farm/LiquidityMiningApi.d.ts +29 -0
  35. package/build/farm/LiquidityMiningClient.d.ts +146 -0
  36. package/build/farm/MultiCurrencyContainer.d.ts +8 -0
  37. package/build/farm/RewardClaimSimulator.d.ts +16 -0
  38. package/build/farm/const.d.ts +4 -0
  39. package/build/farm/index.cjs +1 -0
  40. package/build/farm/index.d.ts +3 -0
  41. package/build/farm/index.mjs +1 -0
  42. package/build/farm/types.d.ts +46 -0
  43. package/build/gho/GhoTokenClient.d.ts +6 -0
  44. package/build/gho/abi.d.ts +124 -0
  45. package/build/gho/index.d.ts +2 -0
  46. package/build/index.cjs +1 -1
  47. package/build/{types/index.d.ts → index.d.ts} +6 -0
  48. package/build/index.mjs +1 -1
  49. package/build/oracle/MmOracleClient.d.ts +7 -0
  50. package/build/oracle/abi.d.ts +196 -0
  51. package/build/oracle/index.d.ts +3 -0
  52. package/build/oracle/types.d.ts +5 -0
  53. package/build/pool/PoolClient.d.ts +75 -0
  54. package/build/pool/PoolContextProvider.d.ts +41 -0
  55. package/build/pool/PoolLog.d.ts +11 -0
  56. package/build/pool/PoolStore.d.ts +20 -0
  57. package/build/pool/aave/AaveAbi.d.ts +126 -0
  58. package/build/pool/aave/AavePool.d.ts +24 -0
  59. package/build/pool/aave/AavePoolClient.d.ts +19 -0
  60. package/build/pool/aave/index.d.ts +2 -0
  61. package/build/pool/aave/types.d.ts +13 -0
  62. package/build/pool/hsm/HsmMath.d.ts +21 -0
  63. package/build/pool/hsm/HsmPool.d.ts +63 -0
  64. package/build/pool/hsm/HsmPoolClient.d.ts +26 -0
  65. package/build/pool/hsm/index.d.ts +3 -0
  66. package/build/pool/hsm/types.d.ts +7 -0
  67. package/build/pool/index.cjs +1 -0
  68. package/build/{types/pool → pool}/index.d.ts +4 -2
  69. package/build/pool/index.mjs +1 -0
  70. package/build/{types/pool → pool}/lbp/LbpPool.d.ts +1 -1
  71. package/build/{types/pool → pool}/lbp/LbpPoolClient.d.ts +9 -7
  72. package/build/{types/pool → pool}/omni/OmniMath.d.ts +7 -6
  73. package/build/{types/pool → pool}/omni/OmniPool.d.ts +14 -1
  74. package/build/pool/omni/OmniPoolClient.d.ts +29 -0
  75. package/build/pool/omni/types.d.ts +11 -0
  76. package/build/{types/pool → pool}/stable/StableMath.d.ts +1 -2
  77. package/build/{types/pool → pool}/stable/StableSwap.d.ts +21 -4
  78. package/build/pool/stable/StableSwapClient.d.ts +23 -0
  79. package/build/pool/stable/types.d.ts +15 -0
  80. package/build/{types/pool → pool}/types.d.ts +14 -3
  81. package/build/{types/pool → pool}/xyk/XykPool.d.ts +13 -1
  82. package/build/pool/xyk/XykPoolClient.d.ts +14 -0
  83. package/build/{types/sor → sor}/Router.d.ts +26 -8
  84. package/build/sor/TradeRouteBuilder.d.ts +4 -0
  85. package/build/sor/TradeRouter.d.ts +207 -0
  86. package/build/sor/TradeScheduler.d.ts +111 -0
  87. package/build/sor/const.d.ts +8 -0
  88. package/build/sor/index.cjs +1 -0
  89. package/build/sor/index.d.ts +6 -0
  90. package/build/sor/index.mjs +1 -0
  91. package/build/{types/sor → sor}/route/bfs.d.ts +11 -2
  92. package/build/{types/sor → sor}/route/index.d.ts +1 -1
  93. package/build/sor/route/suggester.d.ts +33 -0
  94. package/build/sor/types.d.ts +68 -0
  95. package/build/staking/StakingApi.d.ts +66 -0
  96. package/build/staking/StakingClient.d.ts +132 -0
  97. package/build/staking/index.cjs +1 -0
  98. package/build/staking/index.d.ts +2 -0
  99. package/build/staking/index.mjs +1 -0
  100. package/build/staking/types.d.ts +16 -0
  101. package/build/staking/utils.d.ts +1 -0
  102. package/build/tx/OrderTxBuilder.d.ts +21 -0
  103. package/build/tx/TradeTxBuilder.d.ts +18 -0
  104. package/build/tx/TxBuilder.d.ts +19 -0
  105. package/build/tx/TxBuilderFactory.d.ts +12 -0
  106. package/build/tx/index.cjs +1 -0
  107. package/build/tx/index.d.ts +2 -0
  108. package/build/tx/index.mjs +1 -0
  109. package/build/tx/types.d.ts +10 -0
  110. package/build/tx/utils.d.ts +5 -0
  111. package/build/{types/types.d.ts → types.d.ts} +9 -2
  112. package/build/utils/QueryBus.d.ts +10 -0
  113. package/build/utils/async.d.ts +1 -0
  114. package/build/utils/calc.d.ts +52 -0
  115. package/build/utils/format.d.ts +11 -0
  116. package/build/utils/index.cjs +1 -0
  117. package/build/{types/utils → utils}/index.d.ts +3 -3
  118. package/build/utils/index.mjs +1 -0
  119. package/build/{types/utils → utils}/math.d.ts +0 -9
  120. package/package.json +70 -15
  121. package/build/types/api/Papi.d.ts +0 -375
  122. package/build/types/api/client.d.ts +0 -2
  123. package/build/types/api/index.d.ts +0 -2
  124. package/build/types/client/BalanceClient.d.ts +0 -17
  125. package/build/types/pool/PoolClient.d.ts +0 -25
  126. package/build/types/pool/PoolContextProvider.d.ts +0 -26
  127. package/build/types/pool/omni/OmniPoolClient.d.ts +0 -13
  128. package/build/types/pool/stable/StableSwapClient.d.ts +0 -16
  129. package/build/types/pool/xyk/XykPoolClient.d.ts +0 -12
  130. package/build/types/sor/TradeRouter.d.ts +0 -155
  131. package/build/types/sor/TradeUtils.d.ts +0 -12
  132. package/build/types/sor/index.d.ts +0 -4
  133. package/build/types/sor/route/suggester.d.ts +0 -24
  134. package/build/types/sor/types.d.ts +0 -31
  135. package/build/types/utils/big.d.ts +0 -3
  136. package/build/types/utils/evm.d.ts +0 -3
  137. package/build/types/utils/format.d.ts +0 -4
  138. package/build/types/utils/xc.d.ts +0 -1
  139. /package/build/{types/errors.d.ts → errors.d.ts} +0 -0
  140. /package/build/{types/pool → pool}/PoolFactory.d.ts +0 -0
  141. /package/build/{types/pool → pool}/lbp/LbpMath.d.ts +0 -0
  142. /package/build/{types/pool → pool}/lbp/index.d.ts +0 -0
  143. /package/build/{types/pool → pool}/omni/index.d.ts +0 -0
  144. /package/build/{types/pool → pool}/stable/index.d.ts +0 -0
  145. /package/build/{types/pool → pool}/xyk/XykMath.d.ts +0 -0
  146. /package/build/{types/pool → pool}/xyk/index.d.ts +0 -0
  147. /package/build/{types/sor → sor}/route/graph.d.ts +0 -0
  148. /package/build/{types/utils → utils}/Queue.d.ts +0 -0
  149. /package/build/{types/utils → utils}/Stack.d.ts +0 -0
  150. /package/build/{types/utils → utils}/json.d.ts +0 -0
  151. /package/build/{types/utils → utils}/traversal/bfs.d.ts +0 -0
@@ -0,0 +1 @@
1
+ "use strict";var Ze=Object.create;var Et=Object.defineProperty;var ti=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ii=Object.getPrototypeOf,si=Object.prototype.hasOwnProperty;var G=(o,t)=>{for(var e in t)Et(o,e,{get:t[e],enumerable:!0})},be=(o,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ei(t))!si.call(o,s)&&s!==e&&Et(o,s,{get:()=>t[s],enumerable:!(i=ti(t,s))||i.enumerable});return o};var ne=(o,t,e)=>(e=o!=null?Ze(ii(o)):{},be(t||!o||!o.__esModule?Et(e,"default",{value:o,enumerable:!0}):e,o)),ni=o=>be(Et({},"__esModule",{value:!0}),o);var Li={};G(Li,{PoolContextProvider:()=>se,PoolError:()=>tt,PoolFactory:()=>ee,PoolType:()=>O,aave:()=>de,hsm:()=>ge,lbp:()=>le,omni:()=>ue,stable:()=>pe,xyk:()=>me});module.exports=ni(Li);var le={};G(le,{LbpMath:()=>N,LbpPool:()=>ft,LbpPoolClient:()=>Pt});var V=require("@galacticcouncil/math-lbp"),N=class{static getSpotPrice(t,e,i,s,n){return(0,V.get_spot_price)(t,e,i,s,n)}static calculateInGivenOut(t,e,i,s,n){return(0,V.calculate_in_given_out)(t,e,i,s,n)}static calculateOutGivenIn(t,e,i,s,n){return(0,V.calculate_out_given_in)(t,e,i,s,n)}static calculateLinearWeights(t,e,i,s,n){return(0,V.calculate_linear_weights)(t,e,i,s,n)}static calculatePoolTradeFee(t,e,i){return(0,V.calculate_pool_trade_fee)(t,e,i)}};var ot=require("@galacticcouncil/common");var O=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a.HSM="HSM",a))(O||{}),tt=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(tt||{});var Rt={};G(Rt,{withTimeout:()=>ai});function ai(o,t,e="timeout"){return new Promise((i,s)=>{let n=setTimeout(()=>s(new Error(e)),t);o.then(a=>{clearTimeout(n),i(a)},a=>{clearTimeout(n),s(a)})})}var ri=require("@galacticcouncil/common");var I={};G(I,{FeeUtils:()=>ae,shiftNeg:()=>ci});var fe=ne(require("big.js"));var ae=class o{static toPct(t){let[e,i]=t;return o.safeDivide(e*100,i)}static toRaw(t){let[e,i]=t;return o.safeDivide(e,i)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,i=12){let s=10**i;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function ci(o,t){let e=(0,fe.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var gt={};G(gt,{findNestedKey:()=>ui,findNestedObj:()=>pi,jsonFormatter:()=>mi});var ui=(o,t)=>{let e=[];return JSON.stringify(o,(i,s)=>(s&&s[t]&&e.push(s),s)),e[0]},pi=(o,t,e)=>{let i;return JSON.stringify(o,(s,n)=>(n&&n[t]===e&&(i=n),n)),i},mi=(o,t)=>typeof t=="bigint"?t.toString():t;var et={};G(et,{calculateBuyFee:()=>bi,calculateDiffToAvg:()=>di,calculateDiffToRef:()=>hi,calculateSellFee:()=>gi});var $=ne(require("big.js"));function di(o,t){let e=(0,$.default)(o.toString()),i=(0,$.default)(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function hi(o,t){if(t===0n)return 0;let e=(0,$.default)(o.toString()),i=(0,$.default)(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function gi(o,t){if(o===0n)return 0;let e=(0,$.default)(o.toString()),i=(0,$.default)(t.toString());return(0,$.default)(1).minus(i.div(e)).mul(100).round(2).toNumber()}function bi(o,t){if(o===0n)return 0;let e=(0,$.default)(o.toString());return(0,$.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var bt=(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 Mt=(o,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(o(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var fi=Mt(()=>"illegal argument(s)"),ye=o=>{throw new fi(o)};var yi=Mt(()=>"index out of bounds"),re=o=>{throw new yi(o)},Lt=(o,t,e)=>(o<t||o>=e)&&re(o);var Pe=23283064365386963e-26,Dt=class{float(t=1){return this.int()*Pe*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*Pe-.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 qt=class extends Dt{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 ve=new qt(Math.random);var Se=o=>o!=null&&typeof o!="function"&&o.length!==void 0;var xe=Object.getPrototypeOf({}),Ht="function",we="string",rt=(o,t)=>{let e;if(o===t)return!0;if(o!=null){if(typeof o.equiv===Ht)return o.equiv(t)}else return o==t;if(t!=null){if(typeof t.equiv===Ht)return t.equiv(o)}else return o==t;return typeof o===we||typeof t===we?!1:(e=Object.getPrototypeOf(o),(e==null||e===xe)&&(e=Object.getPrototypeOf(t),e==null||e===xe)?xi(o,t):typeof o!==Ht&&o.length!==void 0&&typeof t!==Ht&&t.length!==void 0?Pi(o,t):o instanceof Set&&t instanceof Set?vi(o,t):o instanceof Map&&t instanceof Map?Si(o,t):o instanceof Date&&t instanceof Date?o.getTime()===t.getTime():o instanceof RegExp&&t instanceof RegExp?o.toString()===t.toString():o!==o&&t!==t)},Pi=(o,t,e=rt)=>{let i=o.length;if(i===t.length)for(;i-- >0&&e(o[i],t[i]););return i<0},vi=(o,t,e=rt)=>o.size===t.size&&e([...o.keys()].sort(),[...t.keys()].sort()),Si=(o,t,e=rt)=>o.size===t.size&&e([...o].sort(),[...t].sort()),xi=(o,t,e=rt)=>{if(Object.keys(o).length!==Object.keys(t).length)return!1;for(let i in o)if(!t.hasOwnProperty(i)||!e(o[i],t[i]))return!1;return!0};var oe=class{value;constructor(t){this.value=t}deref(){return this.value}};var Oe=o=>o instanceof oe;var Gt=class o{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Ie("next",this._head)}reverseIterator(){return Ie("prev",this.tail)}clear(){this.release()}compare(t,e=bt){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||Se(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),i=this._head;for(let s=this._length;s-- >0;){if(!rt(i.value,e.next().value))return!1;i=i.next}return!0}filter(t){let e=this.empty();return this.traverse(i=>(t(i.value)&&e.append(i.value),!0)),e}find(t){return this.traverse(e=>e.value!==t)}findWith(t){return this.traverse(e=>!t(e.value))}first(){return this._head?.value}insertSorted(t,e){e=e||bt;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&&!Oe(e);)e=t(e,i.value),i=i.next;return e}reduce(t,e){return this.$reduce(t,e)}release(){let t=this._head;if(!t)return!0;let e;for(let i=this._length;i-- >0;)e=t.next,delete t.value,delete t.prev,delete t.next,t=e;return this._head=void 0,this._length=0,!0}reverse(){let t=this._head,e=this.tail,i=(this._length>>>1)+(this._length&1);for(;t&&e&&i>0;){let s=t.value;t.value=e.value,e.value=s,t=t.next,e=e.prev,i--}return this}setHead(t){let e=this._head;return e?(e.value=t,e):this.prepend(t)}setNth(t,e){let i=this.nthCell(t);return!i&&re(t),i.value=e,i}setTail(t){let e=this.tail;return e?(e.value=t,e):this.append(t)}swap(t,e){if(t!==e){let i=t.value;t.value=e.value,e.value=i}return this}toArray(t=[]){return this.traverse(e=>(t.push(e.value),!0)),t}toJSON(){return this.toArray()}toString(){let t=[];return this.traverse(e=>(t.push(String(e.value)),!0)),t.join(", ")}traverse(t,e=this._head,i){if(!this._head)return;let s=e;do{if(!t(s))break;s=s.next}while(s!==i);return s}_map(t,e){return this.traverse(i=>(t.append(e(i.value)),!0)),t}};function*Ie(o,t){for(;t;)yield t.value,t=t[o]}var Nt=class o extends Gt{_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):(Lt(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):(Lt(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=ve){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)&&ye("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=bt){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),Lt(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 zt=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 Nt,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 zt{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 Vt=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:(...u)=>{let p=i(...u);if(n.has(p)){this.log("[live]",t,p);let P=n.get(p);return Promise.resolve(P)}if(a.has(p))return this.log("[memo]",t,p),a.get(p);this.log("[fetch]",t,p);let g=e(...u).catch(P=>{throw a.delete(p),P});return a.set(p,g),g},set:(u,...p)=>{let g=i(...p);this.log("[set-live]",t,g),n.set(g,u)},clear:()=>{this.log("[clear]",t),n.clear(),a.release()}}}};var{FeeUtils:Te}=I,ft=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=Te.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=Te.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=N.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e){let i=N.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){let e=N.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),ot.big.toBigInt(1,ot.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=N.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),ot.big.toBigInt(1,ot.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let i=N.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var Re=require("polkadot-api"),it=require("rxjs");var _e=(o,t=new Map)=>e=>{let i;return t.has(e)?t.get(e):(t.set(e,i=o(e)),i)};var b=require("rxjs"),m=require("rxjs/operators");var Wt=require("@galacticcouncil/descriptors");var Be=require("@galacticcouncil/common"),lt=require("rxjs");var J=require("rxjs"),T=require("rxjs/operators");function Ae(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>(0,J.defer)(()=>(0,J.from)(o._request("system_health",[]))).pipe((0,T.timeout)({first:e}),(0,T.map)(()=>"online"),(0,T.catchError)(()=>(0,J.of)("offline")));return(0,J.of)({state:"offline",delayMs:0}).pipe((0,T.expand)(n=>(0,J.timer)(n.delayMs).pipe((0,T.switchMap)(i),(0,T.map)(a=>({state:a,delayMs:t})))),(0,T.skip)(1),(0,T.map)(n=>n.state),(0,T.distinctUntilChanged)(),(0,T.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:wi}=Be.log,$t=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,lt.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Ae(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,lt.tap)({error:i=>wi.error(t,i)}),(0,lt.shareReplay)({bufferSize:1,refCount:!0}))}};var W=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(Wt.hydration),this.apiNext=this.client.getTypedApi(Wt.hydrationNext),this.watcher=$t.getInstance(this.client)}};var Oi=require("polkadot-api/ws"),Ii=require("polkadot-api/logs-provider");var Ti=require("polkadot-api/sm-provider");var _i=require("polkadot-api");var Fe=require("@galacticcouncil/common"),M=require("rxjs"),d=require("rxjs/operators");var{logger:ct}=Fe.log,yt=class extends W{erc20Ids=null;constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:i}=await e.getValue(t,{at:"best"});return this.getBreakdown(i)}async getTokenBalance(t,e){let s=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(s)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,M.defer)(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return(0,M.combineLatest)([e,i,s]).pipe((0,d.connect)(n=>(0,M.concat)(n.pipe((0,d.take)(1)),n.pipe((0,d.skip)(1),(0,d.debounceTime)(250)))))}).pipe((0,d.map)(e=>e.flat()),(0,d.startWith)([]),(0,d.bufferCount)(2,1),(0,d.map)(([e,i],s)=>s===0?i:this.getDeltas(e,i))).pipe((0,d.tap)({subscribe:()=>ct.debug("balance: subscribe",t),error:e=>ct.error("balance",e)}),(0,d.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,M.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,d.map)(({value:i})=>({id:0,balance:this.getBreakdown(i.data)})),(0,d.tap)({error:i=>ct.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return(0,M.defer)(()=>i.watchValue(t,e,{at:"best"})).pipe((0,d.map)(({value:s})=>({id:e,balance:this.getBreakdown(s)})),(0,d.tap)({error:s=>ct.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,M.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,d.distinctUntilChanged)((i,s)=>!s.deltas),(0,d.map)(({deltas:i})=>{let s=[];return i?.deleted.forEach(n=>{let[a,r]=n.args;s.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(n=>{let[a,r]=n.args;s.push({id:r,balance:this.getBreakdown(n.value)})}),s}),(0,d.tap)({error:i=>ct.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,M.defer)(()=>(0,M.from)(e?Promise.resolve(e):i()).pipe((0,d.switchMap)(n=>this.watcher.bestBlock$.pipe((0,d.switchMap)(()=>(0,M.from)(s(n))))),(0,d.startWith)([]),(0,d.bufferCount)(2,1),(0,d.map)(([n,a],r)=>r===0?a.filter(l=>l.balance.total>0n):this.getDeltas(n,a)),(0,d.distinctUntilChanged)((n,a)=>a.length===0),(0,d.tap)({error:n=>ct.error("balance(erc20)",n)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.getBreakdown(i)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,i=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:i,transferable:e}}getDeltas(t,e){let i=(n,a)=>n!==void 0&&a!==void 0&&n.transferable===a.transferable&&n.total===a.total,s=t.reduce((n,a)=>(n.set(a.id,a.balance),n),new Map);return e.filter(n=>!i(n.balance,s.get(n.id)))}};var ke=require("rxjs"),Ut=class{store$=new ke.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 Ee=require("@galacticcouncil/common");var Ai={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Yt}=Ee.log,Xt=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${Ai[this.type]})`,10)}trace(t,...e){Yt.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){Yt.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){Yt.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){Yt.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:Bi}=Rt,Fi=3e3,E=class extends W{evm;balance;store=new Ut;log;shared$;resync$=new b.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new st(null,{ttl:6*1e3});memPools=_e(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e,this.balance=new yt(t),this.log=new Xt(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){return(await this.getMemPools()).filter(e=>this.hasValidAssets(e))}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe((0,m.startWith)([]),(0,m.bufferCount)(2,1),(0,m.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,m.filter)(t=>t.length>0),(0,m.throttleTime)(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return(0,b.defer)(()=>{let t=new b.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,m.switchMap)(()=>{let e=new b.Subscription;return(0,b.from)(Bi(this.getMemPools(),6e4,"getMemPools stalled")).pipe((0,m.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,m.map)(s=>s.filter(n=>this.hasValidAssets(n))),(0,m.tap)(s=>this.store.set(s)),(0,m.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),b.EMPTY))).pipe((0,m.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,m.switchMap)(s=>(0,b.merge)((0,b.of)(s),this.store.asObservable().pipe((0,m.skip)(1)))),(0,m.finalize)(()=>{e.unsubscribe()}))}),(0,m.finalize)(()=>t.unsubscribe()))}).pipe((0,m.share)({connector:()=>new b.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:i}=e,s=[this.balance.watchTokensBalance(i)];if(this.hasSystemAsset(e)){let n=this.balance.watchSystemBalance(i);s.push(n)}if(this.hasErc20Asset(e)){let n=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),a=this.balance.watchErc20Balance(i,n);s.push(a)}return(0,b.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,b.merge)(...t).pipe((0,m.bufferTime)(250),(0,m.filter)(e=>e.length>0),(0,m.map)(e=>new Map(e)),this.watchGuard("balances")).subscribe(e=>{this.store.update(i=>this.updateBalances(i,e))})}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:i})=>t.type==="XYK"?i>0n&&!!e:!!e)}updateBalances=(t,e)=>{let i=[],s=new Map(t.map(n=>[n.address,n]));for(let[n,a]of e){let r=s.get(n);if(r){let l=r.tokens.map(c=>{let u=a.find(p=>p.id===c.id);return u&&c.id!==r.id?{...c,balance:u.balance.transferable}:c});i.push({...r,tokens:l})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<Fi||(this.resyncAt=e,this.mem++,this.resync$.next())}requestResync(t=!1){this.resyncPending||(this.resyncPending=!0,setTimeout(()=>{this.resyncPending=!1,this.resync(t)},0))}startWatchdog(){let 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),b.EMPTY)),(0,m.repeat)({delay:1e3})),n=this.watcher.finalizedBlock$.pipe((0,m.pairwise)(),(0,m.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,m.catchError)(r=>(this.log.error("watchdog_gap_error",r),b.EMPTY)),(0,m.repeat)({delay:1e3})),a=(0,b.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),b.EMPTY)),(0,m.repeat)({delay:1e3}));return(0,b.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)(()=>b.EMPTY))}};var Pt=class extends E{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}getPoolWeights(t,e){let{start:i,end:s,initial_weight:n,final_weight:a}=t,r=N.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(Re.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:"best"}),this.api.query.ParachainSystem.ValidationData.getValue({at:"best"}),this.getPoolLimits()]),s=e?.relay_parent_number||0,n=t.filter(({value:a})=>e&&this.isActivePool(a,s)).map(async({keyArgs:a,value:r})=>{let[l]=a,c=l.toString(),u=await this.getPoolDelta(c,r,s);return{address:c,type:"LBP",fee:r.fee,...u,...i}});return Promise.all(n)}async getPoolDelta(t,e,i){let{assets:s,repay_target:n,fee_collector:a}=e,[r,l]=this.getPoolWeights(e,i),[c,u]=s,[p,g,P,y,F]=await Promise.all([this.isRepayFeeApplied(c,n,a.toString()),this.balance.getBalance(t,c),this.api.query.AssetRegistry.Assets.getValue(c),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u)]);return{repayFeeApply:p,tokens:[{id:c,decimals:P?.decimals,existentialDeposit:P?.existential_deposit,balance:g.transferable,weight:r,type:P?.asset_type.type},{id:u,decimals:F?.decimals,existentialDeposit:F?.existential_deposit,balance:y.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,it.map)(({value:t})=>t),(0,it.filter)(t=>t!==void 0),(0,it.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let i=[];for(let s of e){let n=this.poolsData.get(s.address);if(n){let{assets:a,repay_target:r,fee_collector:l}=n,[c]=a,[u,p]=this.getPoolWeights(n,t),[g,P]=s.tokens,y=[{...g,weight:u},{...P,weight:p}],F=await this.isRepayFeeApplied(c,r,l.toString());i.push({...s,tokens:y,repayFeeApply:F})}}return i})})}subscribeUpdates(){let t=new it.Subscription;return t.add(this.subscribeValidationData()),t}};var ue={};G(ue,{OmniMath:()=>v,OmniPool:()=>vt,OmniPoolClient:()=>St});var h=require("@galacticcouncil/math-omnipool"),nt=ne(require("big.js")),v=class{static calculateSpotPrice(t,e,i,s){return(0,h.calculate_spot_price)(t,e,i,s)}static calculateLrnaSpotPrice(t,e){return(0,h.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,i,s,n,a,r,l,c,u){return(0,h.calculate_in_given_out)(t,e,i,s,n,a,r,l,c,u)}static calculateLrnaInGivenOut(t,e,i,s,n,a){return(0,h.calculate_lrna_in_given_out)(t,e,i,s,n,a)}static calculateOutGivenIn(t,e,i,s,n,a,r,l,c,u){return(0,h.calculate_out_given_in)(t,e,i,s,n,a,r,l,c,u)}static calculateOutGivenLrnaIn(t,e,i,s,n,a){return(0,h.calculate_out_given_lrna_in)(t,e,i,s,n,a)}static calculateShares(t,e,i,s){return(0,h.calculate_shares)(t,e,i,s)}static calculateLiquidityOut(t,e,i,s,n,a,r,l){return(0,h.calculate_liquidity_out)(t,e,i,s,n,a,r,l)}static calculateLiquidityLRNAOut(t,e,i,s,n,a,r,l){return(0,h.calculate_liquidity_lrna_out)(t,e,i,s,n,a,r,l)}static calculateCapDifference(t,e,i,s){let n=(0,nt.default)(e),a=(0,nt.default)(t),r=(0,nt.default)(s),l=(0,nt.default)(i),c=(0,nt.default)(10).pow(18),u=l.div(c);if(n.div(r).lt(u)){let g=u.times(r).minus(n).times(a),P=n.times((0,nt.default)(1).minus(u));return g.div(P).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,s){return(0,h.calculate_liquidity_hub_in)(t,e,i,s)}static isSellAllowed(t){return(0,h.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,h.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,h.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,h.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,i,s,n,a,r,l,c,u,p){return(0,h.recalculate_asset_fee)(t,e,i,s,n,a,r,l,c,u,p)}static recalculateProtocolFee(t,e,i,s,n,a,r,l,c,u,p){return(0,h.recalculate_protocol_fee)(t,e,i,s,n,a,r,l,c,u,p)}static verifyAssetCap(t,e,i,s){return(0,h.verify_asset_cap)(t,e,i,s)}};var Ce=require("@galacticcouncil/common");var{FeeUtils:U}=I,vt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new o(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let i=new Map(this.tokens.map(a=>[a.id,a])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:s.hubReserves,hubReservesOut:n.hubReserves,sharesIn:s.shares,sharesOut:n.shares,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:s.balance,balanceOut:n.balance,tradeableIn:s.tradeable,tradeableOut:n.tradeable,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,i),a=s===0n?0:et.calculateBuyFee(s,n),r=[],l=v.isSellAllowed(t.tradeableIn),c=v.isBuyAllowed(t.tradeableOut);(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&r.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return n>p&&r.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),a=et.calculateSellFee(s,n),r=[],l=v.isSellAllowed(t.tradeableIn),c=v.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=v.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?U.toRaw(i.assetFee).toString():"0",i?U.toRaw(i.protocolFee).toString():"0",i?U.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateLrnaInGivenOut(t,e,i){let s=v.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?U.toRaw(i.assetFee).toString():"0",i?U.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,i);let s=v.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?U.toRaw(i.assetFee).toString():"0",i?U.toRaw(i.protocolFee).toString():"0",i?U.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateOutGivenLrnaIn(t,e,i){let s=v.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?U.toRaw(i.assetFee).toString():"0",i?U.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=v.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceLrnaInGivenOut(t){let e=v.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=v.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}spotPriceOutGivenLrnaIn(t){let e=v.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,i){let s=e-i;if(s===0)return t;let n=Ce.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var Y=require("polkadot-api"),De=require("@polkadot-api/utils"),f=require("rxjs"),qe=require("@galacticcouncil/common");var{FeeUtils:S}=I,Me=Y.Binary.toHex(Y.Binary.fromText("omnipool")),Le=(0,Y.Enum)("Short"),St=class extends E{queryBus=new Vt;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:"best"}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:"best"}),t=>String(t),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:"best"}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(Me,t,Le,{at:"best"}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,De.toHex)(e);return(0,Y.AccountId)(qe.HYDRATION_SS58_PREFIX).dec(i)}getOraclePair(t){return t===0?[0,1]:[1,t]}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Omnipool.Assets.isCompatible(Y.CompatibilityLevel.BackwardsCompatible)}async isSlipFeeSupported(){return(await this.apiNext.getStaticApis()).compat.query.Omnipool.SlipFee.isCompatible(Y.CompatibilityLevel.Partial)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,s,n,a,r]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:"best"}),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.balance.getBalance(e,t),this.getPoolLimits()]),l=i.map(async({keyArgs:u,value:p})=>{let[g]=u,{hub_reserve:P,shares:y,tradable:F,cap:X,protocol_shares:K}=p,[C,H]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(g),this.balance.getBalance(e,g)]);return{id:g,decimals:C?.decimals,existentialDeposit:C?.existential_deposit,balance:H.transferable,cap:X,hubReserves:P,protocolShares:K,shares:y,tradeable:F,type:C?.asset_type.type}}),c=await Promise.all(l);return c.push({id:t,decimals:n?.decimals,existentialDeposit:n?.existential_deposit,balance:a.transferable,tradeable:s,type:n?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:c,...r}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,s=0;await this.isSlipFeeSupported()&&(s=await this.maxSlipFee.get()??0);let a=await this.dynamicFeesConfig.get(e);if(a?.type==="Fixed"){let{asset_fee:D,protocol_fee:j}=a.value;return{assetFee:S.fromPermill(D),protocolFee:S.fromPermill(j),maxSlipFee:S.fromPermill(s)}}let r=this.getOraclePair(e),l=this.getOraclePair(i),[c,u,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(r),this.emaOracles.get(l)]),[g,P,y]=await this.getAssetFee(t,this.block,c,u,a?.value.asset_fee_params),[F,X,K]=i===1?[0,0,0]:await this.getProtocolFee(t,this.block,c,p,a?.value.protocol_fee_params),C=g+F,H=y+K;return{assetFee:S.fromPermill(P),protocolFee:S.fromPermill(X),maxSlipFee:S.fromPermill(s),min:S.fromPermill(C),max:S.fromPermill(H)}}async getAssetFee(t,e,i,s,n){let{assetOut:a,balanceOut:r}=t,{min_fee:l,max_fee:c,decay:u,amplification:p}=n||await this.api.constants.DynamicFees.AssetFeeParameters();if(!i||!s)return[l,l,c];let g=S.fromPermill(l),P=S.fromPermill(c),[y]=s,{asset_fee:F,timestamp:X}=i,K=Math.max(1,e-X),C=y.volume.b_in.toString(),H=y.volume.b_out.toString(),D=y.liquidity.b.toString();a===0&&(C=y.volume.a_in.toString(),H=y.volume.a_out.toString(),D=y.liquidity.a.toString());let j=S.fromPermill(F),ht=v.recalculateAssetFee(C,H,D,"9",r.toString(),S.toRaw(j).toString(),K.toString(),S.toRaw(g).toString(),S.toRaw(P).toString(),u.toString(),p.toString());return[l,Number(ht)*1e6,c]}async getProtocolFee(t,e,i,s,n){let{assetIn:a,balanceIn:r}=t,{min_fee:l,max_fee:c,decay:u,amplification:p}=n||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!i||!s)return[l,l,c];let g=S.fromPermill(l),P=S.fromPermill(c),[y]=s,{protocol_fee:F,timestamp:X}=i,K=Math.max(1,e-X),C=y.volume.b_in.toString(),H=y.volume.b_out.toString(),D=y.liquidity.b.toString();a===0&&(C=y.volume.a_in.toString(),H=y.volume.a_out.toString(),D=y.liquidity.a.toString());let j=S.fromPermill(F),ht=v.recalculateProtocolFee(C,H,D,"9",r.toString(),S.toRaw(j).toString(),K.toString(),S.toRaw(g).toString(),S.toRaw(P).toString(),u.toString(),p.toString());return[l,Number(ht)*1e6,c]}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(s=>s.id).map(s=>this.getOraclePair(s)).map(s=>this.api.query.EmaOracle.Oracles.watchValue(Me,s,Le,{at:"best"}).pipe((0,f.map)(({value:n})=>n),(0,f.filter)(n=>n!==void 0),(0,f.map)((n,a)=>({value:n,index:a})),(0,f.tap)(({index:n})=>{n>0&&this.log.trace("emaOracle.Oracles",s.join(":"))}),(0,f.map)(({value:n})=>({pair:s,value:n}))));return(0,f.merge)(...i).pipe((0,f.finalize)(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(s=>{let{pair:n,value:a}=s;this.emaOracles.set(a,n)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,f.distinctUntilChanged)((t,e)=>!e.deltas),(0,f.map)((t,e)=>({value:t,index:e})),(0,f.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),(0,f.finalize)(()=>this.dynamicFees.clear()),this.watchGuard("dynamicFees.AssetFee")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFees.set(e.value,i)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe((0,f.distinctUntilChanged)((t,e)=>!e.deltas),(0,f.map)((t,e)=>({value:t,index:e})),(0,f.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),(0,f.finalize)(()=>this.dynamicFeesConfig.clear()),this.watchGuard("dynamicFees.AssetFeeConfiguration")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFeesConfig.set(e.value,i)})})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,f.distinctUntilChanged)((t,e)=>!e.deltas),(0,f.map)((t,e)=>({value:t,index:e})),(0,f.tap)(({value:t,index:e})=>{e>0&&this.log.trace("omnipool.Assets",t.deltas?.upserted)}),this.watchGuard("omnipool.Assets")).subscribe(({value:{deltas:t}})=>{this.store.update(([e])=>{let i=t?.upserted.reduce((n,a)=>{let[r]=a.args;return n.set(r,a.value),n},new Map),s=e.tokens.map(n=>{let a=i?.get(n.id);return a?this.updateTokenState(n,a):n});return[{...e,tokens:s}]})})}subscribeUpdates(){let t=new f.Subscription;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:i,shares:s,tradable:n,cap:a,protocol_shares:r}=e;return{...t,cap:a,hubReserves:i,protocolShares:r,shares:s,tradeable:n}}};var pe={};G(pe,{StableMath:()=>A,StableSwap:()=>at,StableSwapClient:()=>wt});var x=require("@galacticcouncil/math-stableswap"),A=class{static getPoolAddress(t){return(0,x.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let i=0;i<t;i++)e.push(["1","1"]);return e}static calculateAmplification(t,e,i,s,n){return(0,x.calculate_amplification)(t,e,i,s,n)}static calculateInGivenOut(t,e,i,s,n,a,r){return(0,x.calculate_in_given_out)(t,e,i,s,n,a,r)}static calculateAddOneAsset(t,e,i,s,n,a,r){return(0,x.calculate_add_one_asset)(t,e,i,s,n,a,r)}static calculateSharesForAmount(t,e,i,s,n,a,r){return(0,x.calculate_shares_for_amount)(t,e,i,s,n,a,r)}static calculateOutGivenIn(t,e,i,s,n,a,r){return(0,x.calculate_out_given_in)(t,e,i,s,n,a,r)}static calculateLiquidityOutOneAsset(t,e,i,s,n,a,r){return(0,x.calculate_liquidity_out_one_asset)(t,e,i,s,n,a,r)}static calculateShares(t,e,i,s,n,a){return(0,x.calculate_shares)(t,e,i,s,n,a)}static calculateSpotPriceWithFee(t,e,i,s,n,a,r,l){return(0,x.calculate_spot_price_with_fee)(t,e,i,s,n,a,r,l)}static recalculatePegs(t,e,i,s,n,a){let r=(0,x.recalculate_peg)(t,e,i,s,n,a);return JSON.parse(r)}};var xt=require("@galacticcouncil/common");var{FeeUtils:ut}=I,at=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new o(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(a=>[a.id,a])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:n.tradeable,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,i),a=s===0n?0:et.calculateBuyFee(s,n),r=[],l=v.isSellAllowed(t.tradeableIn),c=v.isBuyAllowed(t.tradeableOut);return(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),a=et.calculateSellFee(s,n),r=[],l=v.isSellAllowed(t.tradeableIn),c=v.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=A.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?ut.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateAddOneAsset(t,e,i){let s=A.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?ut.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateSharesForAmount(t,e,i){let s=A.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?ut.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=A.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=A.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?ut.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateWithdrawOneAsset(t,e,i){let s=A.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?ut.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateShares(t,e,i){let s=A.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?ut.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=A.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,gt.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],gt.jsonFormatter)}normalizeSpot(t,e,i,s,n){return e?t*xt.big.pow10(xt.RUNTIME_DECIMALS-n):i?t/xt.big.pow10(n-s):t}};var jt=require("polkadot-api"),He=require("@polkadot-api/utils"),Ge=require("@noble/hashes/blake2b"),R=require("rxjs"),Jt=require("@galacticcouncil/common");var{FeeUtils:ki}=I,wt=class extends E{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=A.getPoolAddress(t),i=(0,Ge.blake2b)(e,{dkLen:32}),s=(0,He.toHex)(i);return(0,jt.AccountId)(Jt.HYDRATION_SS58_PREFIX).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:i,final_amplification:s,initial_block:n,final_block:a}=t,r=A.calculateAmplification(i.toString(),s.toString(),n.toString(),a.toString(),e.toString()),l=Number(r)<s;return{amplification:BigInt(r),isRampPeriod:l}}async getPoolTokens(t,e){let i=this.getPoolAddress(t),s=e.assets.map(async n=>{let[a,r,l]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,n),this.api.query.AssetRegistry.Assets.getValue(n),this.balance.getBalance(i,n)]);return{id:n,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:l.transferable,tradeable:a,type:r?.asset_type.type}});return Promise.all(s)}async isSupported(){return(await this.api.getStaticApis()).compat.query.Stableswap.Pools.isCompatible(jt.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:"best"}),this.api.query.System.Number.getValue({at:"best"}),this.getPoolLimits()]),s=t.map(async({keyArgs:n,value:a})=>{let[r]=n,l=this.getPoolAddress(r),[c,u,p]=await Promise.all([this.getPoolTokens(r,a),this.api.query.Stableswap.PoolPegs.getValue(r,{at:"best"}),this.api.query.Tokens.TotalIssuance.getValue(r,{at:"best"})]),g=this.getPoolAmplification(a,e),P=u?this.getRecentPegs(u):this.getDefaultPegs(a);return c.push({id:r,tradeable:15,balance:p,decimals:Jt.RUNTIME_DECIMALS}),this.poolsData.set(r,a),{address:l,id:r,type:"Stableswap",fee:ki.fromPermill(a.fee),tokens:c,totalIssuance:p,pegs:P,...i,...g}});return Promise.all(s)}async getPoolFees(t,e){return{fee:this.store.pools.find(s=>s.address===e).fee}}getDefaultPegs(t){return A.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([i,s])=>s.map(n=>n.toString()))}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,{at:"best"}).pipe((0,R.map)(({value:s})=>s),(0,R.map)((s,n)=>({value:s,index:n})),(0,R.tap)(({index:s,value:n})=>{s>0&&this.log.trace("tokens.TotalIssuance",i,n)}),(0,R.map)(({value:s})=>({id:i,value:s}))));return(0,R.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:s,value: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,R.distinctUntilChanged)((t,e)=>!e.deltas),(0,R.map)((t,e)=>({value:t,index:e})),(0,R.tap)(({value:t,index:e})=>{e>0&&this.log.trace("stableswap.PoolPegs",t.deltas?.upserted)}),this.watchGuard("stableswap.PoolPegs")).subscribe({error:t=>this.log.error("stableswap.PoolPegs",t),next:({value:{deltas:t}})=>{this.store.update(e=>{let i=[],s=new Map(e.map(n=>[n.id,n]));return t?.upserted.forEach(({args:n,value:a})=>{let[r]=n,l=s.get(r);if(l){let c=this.getRecentPegs(a);i.push({...l,pegs:c})}}),i})}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(e=>{let i=[];return e.filter(s=>s.isRampPeriod).forEach(s=>{let n=this.poolsData.get(s.id);if(n){let a=this.getPoolAmplification(n,t);i.push({...s,...a})}}),i})})}subscribeUpdates(){let t=new R.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var me={};G(me,{XykMath:()=>Z,XykPool:()=>Ot,XykPoolClient:()=>It});var w=require("@galacticcouncil/math-xyk"),Z=class{static getSpotPrice(t,e,i){return(0,w.get_spot_price)(t,e,i)}static calculateInGivenOut(t,e,i){return(0,w.calculate_in_given_out)(t,e,i)}static calculateOutGivenIn(t,e,i){return(0,w.calculate_out_given_in)(t,e,i)}static calculatePoolTradeFee(t,e,i){return(0,w.calculate_pool_trade_fee)(t,e,i)}static calculateLiquidityIn(t,e,i){return(0,w.calculate_liquidity_in)(t,e,i)}static calculateSpotPrice(t,e){return(0,w.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,i,s){return(0,w.calculate_spot_price_with_fee)(t,e,i,s)}static calculateShares(t,e,i){return(0,w.calculate_shares)(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,s){return(0,w.calculate_liquidity_out_asset_a)(t,e,i,s)}static calculateLiquidityOutAssetB(t,e,i,s){return(0,w.calculate_liquidity_out_asset_b)(t,e,i,s)}};var ze=require("@galacticcouncil/common");var{FeeUtils:Ne}=I,Ot=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=Ne.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=Ne.toPct(i.exchangeFee),r=s-n,l=[];(e<this.minTradingLimit||s<t.assetOutEd)&&l.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&l.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return r>u&&l.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:a,errors:l}}calculateInGivenOut(t,e){let i=Z.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e){let i=Z.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){let e=Z.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=Z.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=Z.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(i)}normalizeSpot(t,e,i){let s=e-i;if(s===0)return t;let n=ze.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var Ve=require("polkadot-api"),$e=require("rxjs");var It=class extends E{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){return(await this.api.getStaticApis()).compat.query.XYK.PoolAssets.isCompatible(Ve.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries(),this.getPoolLimits()]),i=t.map(async({keyArgs:s,value:n})=>{let[a]=s,[r,l]=n,[c,u,p,g]=await Promise.all([this.balance.getBalance(a,r),this.api.query.AssetRegistry.Assets.getValue(r),this.balance.getBalance(a,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:a,type:"XYK",tokens:[{id:r,decimals:u?.decimals||this.decimals.get(r),existentialDeposit:u?.existential_deposit,balance:c.transferable,type:u?.asset_type.type},{id:l,decimals:g?.decimals||this.decimals.get(l),existentialDeposit:g?.existential_deposit,balance:p.transferable,type:g?.asset_type.type}],...e}});return Promise.all(i)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return $e.Subscription.EMPTY}};var de={};G(de,{AavePool:()=>Tt,AavePoolClient:()=>_t});var pt=require("@galacticcouncil/common");var Tt=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 pt.big.toBigInt(1,pt.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return pt.big.toBigInt(1,pt.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var Qt=require("polkadot-api"),Ue=require("@polkadot-api/utils"),L=require("rxjs"),Ye=require("viem"),Zt=require("@galacticcouncil/common");var We=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"}];var{ERC20:Ei}=Zt.erc20,Ri=["Supply","Withdraw","Repay","Borrow"],_t=class extends E{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,s=new TextEncoder().encode(i.padEnd(32,"\0")),n=(0,Ue.toHex)(s);return(0,Qt.AccountId)(Zt.HYDRATION_SS58_PREFIX).dec(n)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:"best"})).map(async({reserve:i,atoken:s,liqudity_in:n,liqudity_out:a})=>{let[r,l,c,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i),this.api.query.AssetRegistry.AssetLocations.getValue(i),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(i,s),type:"Aave",tokens:[{id:i,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:n,location:l,type:r?.asset_type.type},{id:s,decimals:c?.decimals,existentialDeposit:c?.existential_deposit,balance:a,location:u,type:c?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:s,liqudity_out:n}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:"best"});return t.tokens.map(a=>{let r=a.id===e.id?s:n;return{...a,balance:r}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key}throw new Error("Invalid aave reserve multilocation")}return Ei.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:i}=t;return{assetIn:e,assetOut:i,key:`${e}:${i}`}}parseEvmLog(t){let{topics:e,data:i}=t.log,s=e,n=Qt.Binary.toHex(i);try{let{eventName:a,args:r}=(0,Ye.decodeEventLog)({abi:We,topics:s,data:n}),l=r.reserve.toLowerCase();return{eventName:a,reserve:l,key:`${a}:${l}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(i=>i.tokens).map(([i,s])=>s).map(i=>i.id);return this.api.event.Router.Executed.watch().pipe((0,L.mergeMap)(({events:i})=>i),(0,L.map)(({payload:i})=>this.parseRouterLog(i)),(0,L.filter)(({assetIn:i,assetOut:s})=>e.includes(i)||e.includes(s)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:s,key:n})=>{this.log.trace("router.Executed",n),this.store.update(async a=>{let r=[];for(let l of a){let[c,u]=l.tokens;if(u.id===i||u.id===s){let g=await this.getPoolDelta(l);r.push({...l,tokens:g})}}return r})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,L.mergeMap)(({events:t})=>t),(0,L.map)(({payload:t})=>this.parseEvmLog(t)),(0,L.filter)(t=>t!==void 0),(0,L.filter)(({eventName:t})=>Ri.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async i=>{let s=[];for(let n of i){let[a]=n.tokens;if(this.getReserveH160Id(a).toLowerCase()===t){let l=await this.getPoolDelta(n);s.push({...n,tokens:l})}}return s})})}subscribeBalances(){return L.Subscription.EMPTY}subscribeUpdates(){let t=new L.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var ge={};G(ge,{HsmMath:()=>q,HsmPool:()=>At,HsmPoolClient:()=>kt});var B=require("@galacticcouncil/math-hsm"),q=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,B.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,B.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,B.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,B.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,B.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,B.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,B.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,B.calculate_max_price)(t,e)}};var k=require("@galacticcouncil/common");var{FeeUtils:mt}=I,At=class o extends at{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=q.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),mt.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=q.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),mt.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=q.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),mt.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=q.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),mt.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=q.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=q.calculateBuybackLimit(e.toString(),mt.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let s=q.calculateBuybackPriceWithFee(i.toString(),e.toString(),mt.toRaw(this.buyBackFee).toString()),[n,a]=JSON.parse(s),r=k.big.pow10(t.decimalsIn+k.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(n)*r/BigInt(a)}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=q.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[s,n]=JSON.parse(i),a=k.big.pow10(k.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(s)*a/BigInt(n)}spotPriceInGivenOut(t){let e=k.big.toBigInt(1,t.decimalsOut),s=this.calculateInGivenOut(t,e)*k.big.pow10(k.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(s,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=k.big.toBigInt(1,t.decimalsIn),s=this.calculateOutGivenIn(t,e)*k.big.pow10(k.RUNTIME_DECIMALS-t.decimalsIn);return this.normalizeSpotPrice(s,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(s=>s.id!==this.hollarId),e=this.pegs[t],i=this.tokens[t].decimals;return this.isDefaultPeg(e)?[k.big.toBigInt(1,18).toString(),k.big.toBigInt(1,i).toString()]:e}isDefaultPeg(t){let[e,i]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&i==="1"}normalizeSpotPrice(t,e,i){let s=e-i;if(s===0)return t;let n=k.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var dt=require("polkadot-api"),Ke=require("@polkadot-api/utils"),_=require("rxjs"),je=require("viem"),te=require("@galacticcouncil/common");var Bt=[{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 Ft=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,s]=await this.client.readContract({abi:Bt,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-s}};var{FeeUtils:he}=I,{H160:Xe}=te.h160,Ci=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],kt=class extends E{ghoClient;stableClient;constructor(t,e,i){super(t,e),this.stableClient=i,this.ghoClient=new Ft(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,Ke.toHex)(i);return(0,dt.AccountId)(te.HYDRATION_SS58_PREFIX).dec(s)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(dt.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),this.api.query.HSM.Collaterals.getEntries({at:"best"}),this.stableClient.getPools()]);if(i.length===0)return[];let n=this.getFacilitatorAddress(),a=Xe.fromAny(n),r=this.getHollarAddress(e),l=await this.ghoClient.getFacilitatorCapacity(r,a),c=i.map(async({keyArgs:p,value:g})=>{let[P]=p,{pool_id:y,max_buy_price_coefficient:F,max_in_holding:X,purchase_fee:K,buy_back_fee:C,buyback_rate:H}=g,D=s.find(j=>j.id===y);if(D){let j=this.getPoolId(y),ht=await this.balance.getBalance(n,P);return{...D,address:j,type:"HSM",tokens:D.tokens.filter(Qe=>Qe.id!==y),hsmAddress:n,hsmMintCapacity:l,hollarId:t,hollarH160:r,collateralId:P,collateralBalance:ht.transferable,maxBuyPriceCoefficient:F,maxInHolding:X,purchaseFee:he.fromPermill(K),buyBackFee:he.fromPermill(C),buyBackRate:he.fromPerbill(H)}}});return(await Promise.all(c)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:i}=t.log,s=e,n=dt.Binary.toHex(i);try{let{eventName:a,args:r}=(0,je.decodeEventLog)({abi:Bt,topics:s,data:n}),l=r.facilitatorAddress.toLowerCase();return{eventName:a,facilitator:l,key:`${a}:${l}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,_.mergeMap)(({events:t})=>t),(0,_.map)(({payload:t})=>this.parseEvmLog(t)),(0,_.filter)(t=>t!==void 0),(0,_.filter)(({eventName:t})=>Ci.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async i=>{let s=[],[{hsmAddress:n,hollarH160:a}]=i,r=Xe.fromAny(n);if(r.toLowerCase()===e){let c=await this.ghoClient.getFacilitatorCapacity(a,r);for(let u of i)s.push({...u,hsmMintCapacity:c})}return s})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(n=>{let{tokens:a,collateralId:r}=n;a.find(c=>c.id===r).type==="Erc20"?e.push(r):t.push(r)});let[{hsmAddress:i}]=this.store.pools,s=[];if(t.length>0){let n=this.balance.watchTokensBalance(i);s.push(n)}if(e.length>0){let n=this.balance.watchErc20Balance(i,e);s.push(n)}return s.length>0?(0,_.combineLatest)(s).pipe((0,_.map)(n=>n.flat()),(0,_.pairwise)(),(0,_.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})}):_.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 _.Subscription.EMPTY}subscribeUpdates(){let t=new _.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var ee=class{static get(t){switch(t.type){case"Aave":return Tt.fromPool(t);case"XYK":return Ot.fromPool(t);case"Omnipool":return vt.fromPool(t);case"LBP":return ft.fromPool(t);case"Stableswap":return at.fromPool(t);case"HSM":return At.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var Je=require("@galacticcouncil/common"),z=require("rxjs");var ie=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}};var{logger:Mi}=Je.log,se=class extends W{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=z.Subscription.EMPTY;omniSub=z.Subscription.EMPTY;stableSub=z.Subscription.EMPTY;hsmSub=z.Subscription.EMPTY;xykSub=z.Subscription.EMPTY;lbpSub=z.Subscription.EMPTY;isReady=!1;isDestroyed=new z.Subject;constructor(t,e){super(t),this.evm=e,this.aave=new _t(t,e),this.omnipool=new St(t,e),this.stableswap=new wt(t,e),this.hsm=new kt(t,e,this.stableswap),this.xyk=new It(t,e),this.lbp=new Pt(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe((0,z.takeUntil)(this.isDestroyed)).subscribe(e=>{e.forEach(i=>{this.pools.set(i.address,i)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.active.has("Stableswap")||(Mi.info("[PoolContextProvider] auto-activating stableswap"),this.withStableswap()),this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let i=this.clients.find(s=>s.getPoolType()===e.type);if(i)return i.getPoolFees(t,e.address);throw new ie(e.type)}};0&&(module.exports={PoolContextProvider,PoolError,PoolFactory,PoolType,aave,hsm,lbp,omni,stable,xyk});
@@ -1,7 +1,9 @@
1
1
  export { PoolFactory } from './PoolFactory';
2
2
  export { PoolContextProvider } from './PoolContextProvider';
3
- export * as xyk from './xyk';
3
+ export * as aave from './aave';
4
4
  export * as omni from './omni';
5
- export * as lbp from './lbp';
6
5
  export * as stable from './stable';
6
+ export * as hsm from './hsm';
7
+ export * as xyk from './xyk';
8
+ export * as lbp from './lbp';
7
9
  export * from './types';
@@ -0,0 +1 @@
1
+ var we=Object.defineProperty;var A=(u,t)=>{for(var e in t)we(u,e,{get:t[e],enumerable:!0})};import Te from"buffer";typeof window<"u"&&(window.Buffer=Te.Buffer);var se={};A(se,{LbpMath:()=>T,LbpPool:()=>Q,LbpPoolClient:()=>st});import{calculate_in_given_out as Ae,calculate_out_given_in as Be,calculate_linear_weights as Fe,calculate_pool_trade_fee as _e,get_spot_price as ke}from"@galacticcouncil/math-lbp";var T=class{static getSpotPrice(t,e,i,s,a){return ke(t,e,i,s,a)}static calculateInGivenOut(t,e,i,s,a){return Ae(t,e,i,s,a)}static calculateOutGivenIn(t,e,i,s,a){return Be(t,e,i,s,a)}static calculateLinearWeights(t,e,i,s,a){return Fe(t,e,i,s,a)}static calculatePoolTradeFee(t,e,i){return _e(t,e,i)}};import{big as $t,RUNTIME_DECIMALS as Ut}from"@galacticcouncil/common";var y=(n=>(n.Aave="Aave",n.LBP="LBP",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="XYK",n.HSM="HSM",n))(y||{}),H=(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))(H||{});var bt={};A(bt,{withTimeout:()=>Re});function Re(u,t,e="timeout"){return new Promise((i,s)=>{let a=setTimeout(()=>s(new Error(e)),t);u.then(n=>{clearTimeout(a),i(n)},n=>{clearTimeout(a),s(n)})})}import{RUNTIME_DECIMALS as Fa}from"@galacticcouncil/common";var P={};A(P,{FeeUtils:()=>Bt,shiftNeg:()=>Me});import Le from"big.js";var Bt=class u{static toPct(t){let[e,i]=t;return u.safeDivide(e*100,i)}static toRaw(t){let[e,i]=t;return u.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 Me(u,t){let e=Le(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var j={};A(j,{findNestedKey:()=>De,findNestedObj:()=>He,jsonFormatter:()=>Ge});var De=(u,t)=>{let e=[];return JSON.stringify(u,(i,s)=>(s&&s[t]&&e.push(s),s)),e[0]},He=(u,t,e)=>{let i;return JSON.stringify(u,(s,a)=>(a&&a[t]===e&&(i=a),a)),i},Ge=(u,t)=>typeof t=="bigint"?t.toString():t;var D={};A(D,{calculateBuyFee:()=>We,calculateDiffToAvg:()=>qe,calculateDiffToRef:()=>Ne,calculateSellFee:()=>Ve});import E from"big.js";function qe(u,t){let e=E(u.toString()),i=E(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function Ne(u,t){if(t===0n)return 0;let e=E(u.toString()),i=E(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function Ve(u,t){if(u===0n)return 0;let e=E(u.toString()),i=E(t.toString());return E(1).minus(i.div(e)).mul(100).round(2).toNumber()}function We(u,t){if(u===0n)return 0;let e=E(u.toString());return E(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}import{TLRUCache as Wt}from"@thi.ng/cache";var Pt=class{debug;constructor(t){this.debug=t||!1}log(t,e,i){this.debug&&console.log(t,e,i)}scope(t,e,i,s){let a=new Map,n=s!==void 0?new Wt(null,{ttl:s}):new Wt;return{get:(...c)=>{let p=i(...c);if(a.has(p)){this.log("[live]",t,p);let g=a.get(p);return Promise.resolve(g)}if(n.has(p))return this.log("[memo]",t,p),n.get(p);this.log("[fetch]",t,p);let m=e(...c).catch(g=>{throw n.delete(p),g});return n.set(p,m),m},set:(c,...p)=>{let m=i(...p);this.log("[set-live]",t,m),a.set(m,c)},clear:()=>{this.log("[clear]",t),a.clear(),n.release()}}}};var{FeeUtils:Yt}=P,Q=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new u(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),s=i.get(t),a=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,weightIn:s.weight,weightOut:a.weight}}validateAndBuy(t,e,i){let s=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let n=t.balanceOut/this.maxOutRatio;if(e>n&&a.push("MaxOutRatioExceeded"),s===t.assetOut){let r=this.calculateTradeFee(e,i),o=Yt.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),l=e+r,c=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return c>p&&a.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:a}}else{let r=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return r>o&&a.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:a}}}validateAndSell(t,e,i){let s=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let n=t.balanceIn/this.maxInRatio;if(e>n&&a.push("MaxInRatioExceeded"),s===t.assetIn){let r=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return r>o&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:a}}else{let r=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(r,i),l=Yt.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),c=r-o,p=t.balanceOut/this.maxOutRatio;return c>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:c,feePct:l,errors:a}}}calculateInGivenOut(t,e){let i=T.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=T.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=T.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),$t.toBigInt(1,Ut).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=T.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),$t.toBigInt(1,Ut).toString());return BigInt(e)}calculateTradeFee(t,e){let i=T.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};import{CompatibilityLevel as Ei}from"polkadot-api";import{Subscription as Ci,distinctUntilChanged as Li,filter as Mi,map as Di}from"rxjs";import{memoize1 as yi}from"@thi.ng/memoize";import{TLRUCache as fi}from"@thi.ng/cache";import{ReplaySubject as te,Subscription as ee,combineLatest as Si,defer as vi,from as xi,interval as Ii,merge as _t,of as Oi,EMPTY as et}from"rxjs";import{bufferCount as wi,bufferTime as Ti,catchError as it,filter as xt,finalize as kt,map as W,pairwise as Rt,repeat as Et,skip as Ai,share as Bi,startWith as Fi,switchMap as ie,tap as G,throttleTime as _i}from"rxjs/operators";import{hydration as ni,hydrationNext as ri}from"@galacticcouncil/descriptors";import{log as ti}from"@galacticcouncil/common";import{map as ei,shareReplay as ii,tap as si}from"rxjs";import{defer as $e,from as Ue,of as Xt,timer as Ye}from"rxjs";import{catchError as Xe,distinctUntilChanged as ze,expand as Ke,map as Ft,shareReplay as je,skip as Qe,switchMap as Je,timeout as Ze}from"rxjs/operators";function zt(u,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>$e(()=>Ue(u._request("system_health",[]))).pipe(Ze({first:e}),Ft(()=>"online"),Xe(()=>Xt("offline")));return Xt({state:"offline",delayMs:0}).pipe(Ke(a=>Ye(a.delayMs).pipe(Je(i),Ft(n=>({state:n,delayMs:t})))),Qe(1),Ft(a=>a.state),ze(),je({bufferSize:1,refCount:!0}))}var{logger:ai}=ti,yt=class u{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(ei(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",zt(t))}static getInstance(t){return this.instance||(this.instance=new u(t)),this.instance}watched(t,e){return e.pipe(si({error:i=>ai.error(t,i)}),ii({bufferSize:1,refCount:!0}))}};var B=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(ni),this.apiNext=this.client.getTypedApi(ri),this.watcher=yt.getInstance(this.client)}};import{getWsProvider as xn}from"polkadot-api/ws";import{withLogsRecorder as On}from"polkadot-api/logs-provider";import{getSmProvider as Bn}from"polkadot-api/sm-provider";import{Binary as Nn}from"polkadot-api";import{log as oi}from"@galacticcouncil/common";import{combineLatest as li,concat as ci,defer as J,from as Kt}from"rxjs";import{bufferCount as jt,distinctUntilChanged as Qt,debounceTime as ui,map as N,retry as pi,startWith as Jt,switchMap as Zt,tap as Z,take as mi,skip as di,connect as gi}from"rxjs/operators";var{logger:V}=oi,tt=class extends B{erc20Ids=null;constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:i}=await e.getValue(t,{at:"best"});return this.getBreakdown(i)}async getTokenBalance(t,e){let s=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(s)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return J(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return li([e,i,s]).pipe(gi(a=>ci(a.pipe(mi(1)),a.pipe(di(1),ui(250)))))}).pipe(N(e=>e.flat()),Jt([]),jt(2,1),N(([e,i],s)=>s===0?i:this.getDeltas(e,i))).pipe(Z({subscribe:()=>V.debug("balance: subscribe",t),error:e=>V.error("balance",e)}),pi({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return J(()=>e.watchValue(t,{at:"best"})).pipe(N(({value:i})=>({id:0,balance:this.getBreakdown(i.data)})),Z({error:i=>V.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return J(()=>i.watchValue(t,e,{at:"best"})).pipe(N(({value:s})=>({id:e,balance:this.getBreakdown(s)})),Z({error:s=>V.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return J(()=>e.watchEntries(t,{at:"best"})).pipe(Qt((i,s)=>!s.deltas),N(({deltas:i})=>{let s=[];return i?.deleted.forEach(a=>{let[n,r]=a.args;s.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(a=>{let[n,r]=a.args;s.push({id:r,balance:this.getBreakdown(a.value)})}),s}),Z({error:i=>V.error("balance(tokens)",i)}))}watchErc20Balance(t,e){let i=async()=>{if(this.erc20Ids)return this.erc20Ids;let a=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=a.filter(({value:n})=>n.asset_type.type==="Erc20").map(({keyArgs:n})=>{let[r]=n;return r}),this.erc20Ids},s=async a=>(await Promise.all(a.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,o])=>({id:r,balance:o}));return J(()=>Kt(e?Promise.resolve(e):i()).pipe(Zt(a=>this.watcher.bestBlock$.pipe(Zt(()=>Kt(s(a))))),Jt([]),jt(2,1),N(([a,n],r)=>r===0?n.filter(o=>o.balance.total>0n):this.getDeltas(a,n)),Qt((a,n)=>n.length===0),Z({error:a=>V.error("balance(erc20)",a)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.getBreakdown(i)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,i=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:i,transferable:e}}getDeltas(t,e){let i=(a,n)=>a!==void 0&&n!==void 0&&a.transferable===n.transferable&&a.total===n.total,s=t.reduce((a,n)=>(a.set(n.id,n.balance),a),new Map);return e.filter(a=>!i(a.balance,s.get(a.id)))}};import{BehaviorSubject as bi}from"rxjs";var ft=class{store$=new bi([]);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,o)=>[r.address,o])),s=await t(e),a=e.slice(),n=new Set;for(let r of s){let o=i.get(r.address);o===void 0?(i.set(r.address,a.length),a.push(r)):a[o]=r,n.add(r.address)}this.changeset=n,this.store$.next(a)}).catch(console.error)}destroy(){this.store$.complete()}};import{log as hi}from"@galacticcouncil/common";var Pi={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:St}=hi,vt=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${Pi[this.type]})`,10)}trace(t,...e){St.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){St.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){St.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){St.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:ki}=bt,Ri=3e3,v=class extends B{evm;balance;store=new ft;log;shared$;resync$=new te(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new fi(null,{ttl:6*1e3});memPools=yi(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e,this.balance=new tt(t),this.log=new vt(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){return(await this.getMemPools()).filter(e=>this.hasValidAssets(e))}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe(Fi([]),wi(2,1),W(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),xt(t=>t.length>0),_i(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return vi(()=>{let t=new ee;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe(ie(()=>{let e=new ee;return xi(ki(this.getMemPools(),6e4,"getMemPools stalled")).pipe(G(()=>this.log.info("pool_synced",{mem:this.mem})),W(s=>s.filter(a=>this.hasValidAssets(a))),G(s=>this.store.set(s)),it(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),et))).pipe(G(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),ie(s=>_t(Oi(s),this.store.asObservable().pipe(Ai(1)))),kt(()=>{e.unsubscribe()}))}),kt(()=>t.unsubscribe()))}).pipe(Bi({connector:()=>new te(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:i}=e,s=[this.balance.watchTokensBalance(i)];if(this.hasSystemAsset(e)){let a=this.balance.watchSystemBalance(i);s.push(a)}if(this.hasErc20Asset(e)){let a=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),n=this.balance.watchErc20Balance(i,a);s.push(n)}return Si(s).pipe(W(a=>a.flat()),Rt(),W(([a,n])=>this.balance.getDeltas(a,n)),xt(a=>a.length>0),W(a=>[i,a]))});return _t(...t).pipe(Ti(250),xt(e=>e.length>0),W(e=>new Map(e)),this.watchGuard("balances")).subscribe(e=>{this.store.update(i=>this.updateBalances(i,e))})}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:i})=>t.type==="XYK"?i>0n&&!!e:!!e)}updateBalances=(t,e)=>{let i=[],s=new Map(t.map(a=>[a.address,a]));for(let[a,n]of e){let r=s.get(a);if(r){let o=r.tokens.map(l=>{let c=n.find(p=>p.id===l.id);return c&&l.id!==r.id?{...l,balance:c.balance.transferable}:l});i.push({...r,tokens:o})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<Ri||(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(Rt(),xt(([r,o])=>r==="offline"&&o==="online"),G(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),it(r=>(this.log.error("watchdog_recovery_error",r),et)),Et({delay:1e3})),a=this.watcher.finalizedBlock$.pipe(Rt(),G(([r,o])=>{let l=Number(r.number),c=Number(o.number),p=c-l;p>=3&&(this.log.debug("watchdog_gap",{from:l,to:c,gap:p}),this.requestResync())}),it(r=>(this.log.error("watchdog_gap_error",r),et)),Et({delay:1e3})),n=Ii(36e5).pipe(G(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),it(r=>(this.log.error("watchdog_periodic_error",r),et)),Et({delay:1e3}));return _t(s,a,n).subscribe()}watchGuard(t){return e=>e.pipe(G({error:i=>{this.log.error(t,i),this.requestResync(!0)}}),kt(()=>{this.log.debug(t,"unsub")}),it(()=>et))}};var st=class extends v{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}getPoolWeights(t,e){let{start:i,end:s,initial_weight:a,final_weight:n}=t,r=T.calculateLinearWeights(i?i.toString():"0",s?s.toString():"0",a.toString(),n.toString(),e.toString()),o=BigInt(r),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){return(await this.api.getStaticApis()).compat.query.LBP.PoolData.isCompatible(Ei.BackwardsCompatible)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:"best"}),this.api.query.ParachainSystem.ValidationData.getValue({at:"best"}),this.getPoolLimits()]),s=e?.relay_parent_number||0,a=t.filter(({value:n})=>e&&this.isActivePool(n,s)).map(async({keyArgs:n,value:r})=>{let[o]=n,l=o.toString(),c=await this.getPoolDelta(l,r,s);return{address:l,type:"LBP",fee:r.fee,...c,...i}});return Promise.all(a)}async getPoolDelta(t,e,i){let{assets:s,repay_target:a,fee_collector:n}=e,[r,o]=this.getPoolWeights(e,i),[l,c]=s,[p,m,g,d,S]=await Promise.all([this.isRepayFeeApplied(l,a,n.toString()),this.balance.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l),this.balance.getBalance(t,c),this.api.query.AssetRegistry.Assets.getValue(c)]);return{repayFeeApply:p,tokens:[{id:l,decimals:g?.decimals,existentialDeposit:g?.existential_deposit,balance:m.transferable,weight:r,type:g?.asset_type.type},{id:c,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:d.transferable,weight:o,type:S?.asset_type.type}]}}isActivePool(t,e){let{start:i,end:s}=t;return i&&s?e>=i&&e<s:!1}async isRepayFeeApplied(t,e,i){if(e===0n)return!1;try{return(await this.balance.getBalance(i,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let i=this.store.pools.find(a=>a.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:i.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue({at:"best"}).pipe(Di(({value:t})=>t),Mi(t=>t!==void 0),Li((t,e)=>t.relay_parent_number===e.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let i=[];for(let s of e){let a=this.poolsData.get(s.address);if(a){let{assets:n,repay_target:r,fee_collector:o}=a,[l]=n,[c,p]=this.getPoolWeights(a,t),[m,g]=s.tokens,d=[{...m,weight:c},{...g,weight:p}],S=await this.isRepayFeeApplied(l,r,o.toString());i.push({...s,tokens:d,repayFeeApply:S})}}return i})})}subscribeUpdates(){let t=new Ci;return t.add(this.subscribeValidationData()),t}};var le={};A(le,{OmniMath:()=>b,OmniPool:()=>at,OmniPoolClient:()=>nt});import{calculate_in_given_out as Hi,calculate_lrna_in_given_out as Gi,calculate_out_given_in as qi,calculate_out_given_lrna_in as Ni,calculate_spot_price as Vi,calculate_lrna_spot_price as Wi,calculate_shares as $i,calculate_liquidity_out as Ui,calculate_liquidity_lrna_out as Yi,verify_asset_cap as Xi,calculate_liquidity_hub_in as zi,is_sell_allowed as Ki,is_buy_allowed as ji,is_add_liquidity_allowed as Qi,is_remove_liquidity_allowed as Ji,recalculate_asset_fee as Zi,recalculate_protocol_fee as ts}from"@galacticcouncil/math-omnipool";import $ from"big.js";var b=class{static calculateSpotPrice(t,e,i,s){return Vi(t,e,i,s)}static calculateLrnaSpotPrice(t,e){return Wi(t,e)}static calculateInGivenOut(t,e,i,s,a,n,r,o,l,c){return Hi(t,e,i,s,a,n,r,o,l,c)}static calculateLrnaInGivenOut(t,e,i,s,a,n){return Gi(t,e,i,s,a,n)}static calculateOutGivenIn(t,e,i,s,a,n,r,o,l,c){return qi(t,e,i,s,a,n,r,o,l,c)}static calculateOutGivenLrnaIn(t,e,i,s,a,n){return Ni(t,e,i,s,a,n)}static calculateShares(t,e,i,s){return $i(t,e,i,s)}static calculateLiquidityOut(t,e,i,s,a,n,r,o){return Ui(t,e,i,s,a,n,r,o)}static calculateLiquidityLRNAOut(t,e,i,s,a,n,r,o){return Yi(t,e,i,s,a,n,r,o)}static calculateCapDifference(t,e,i,s){let a=$(e),n=$(t),r=$(s),o=$(i),l=$(10).pow(18),c=o.div(l);if(a.div(r).lt(c)){let m=c.times(r).minus(a).times(n),g=a.times($(1).minus(c));return m.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,s){return zi(t,e,i,s)}static isSellAllowed(t){return Ki(t)}static isBuyAllowed(t){return ji(t)}static isAddLiquidityAllowed(t){return Qi(t)}static isRemoveLiquidityAllowed(t){return Ji(t)}static recalculateAssetFee(t,e,i,s,a,n,r,o,l,c,p){return Zi(t,e,i,s,a,n,r,o,l,c,p)}static recalculateProtocolFee(t,e,i,s,a,n,r,o,l,c,p){return ts(t,e,i,s,a,n,r,o,l,c,p)}static verifyAssetCap(t,e,i,s){return Xi(t,e,i,s)}};import{big as es}from"@galacticcouncil/common";var{FeeUtils:F}=P,at=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new u(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),s=i.get(t),a=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:s.hubReserves,hubReservesOut:a.hubReserves,sharesIn:s.shares,sharesOut:a.shares,decimalsIn:s.decimals,decimalsOut:a.decimals,balanceIn:s.balance,balanceOut:a.balance,tradeableIn:s.tradeable,tradeableOut:a.tradeable,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,i),n=s===0n?0:D.calculateBuyFee(s,a),r=[],o=b.isSellAllowed(t.tradeableIn),l=b.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&r.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return a>p&&r.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:n,errors:r}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,i),n=D.calculateSellFee(s,a),r=[],o=b.isSellAllowed(t.tradeableIn),l=b.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&r.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return a>p&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:n,errors:r}}calculateInGivenOut(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,i);let s=b.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?F.toRaw(i.assetFee).toString():"0",i?F.toRaw(i.protocolFee).toString():"0",i?F.toRaw(i.maxSlipFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateLrnaInGivenOut(t,e,i){let s=b.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?F.toRaw(i.assetFee).toString():"0",i?F.toRaw(i.maxSlipFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,i);let s=b.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?F.toRaw(i.assetFee).toString():"0",i?F.toRaw(i.protocolFee).toString():"0",i?F.toRaw(i.maxSlipFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateOutGivenLrnaIn(t,e,i){let s=b.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?F.toRaw(i.assetFee).toString():"0",i?F.toRaw(i.maxSlipFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=b.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=b.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=b.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=b.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,i){let s=e-i;if(s===0)return t;let a=es.pow10(Math.abs(s));return s>0?t*a:t/a}};import{AccountId as is,Binary as ae,CompatibilityLevel as ne,Enum as ss}from"polkadot-api";import{toHex as as}from"@polkadot-api/utils";import{Subscription as ns,distinctUntilChanged as Lt,filter as rs,finalize as Mt,map as U,merge as os,tap as It}from"rxjs";import{HYDRATION_SS58_PREFIX as ls}from"@galacticcouncil/common";var{FeeUtils:h}=P,re=ae.toHex(ae.fromText("omnipool")),oe=ss("Short"),nt=class extends v{queryBus=new Pt;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:"best"}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:"best"}),t=>String(t),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:"best"}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(re,t,oe,{at:"best"}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=as(e);return is(ls).dec(i)}getOraclePair(t){return t===0?[0,1]:[1,t]}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Omnipool.Assets.isCompatible(ne.BackwardsCompatible)}async isSlipFeeSupported(){return(await this.apiNext.getStaticApis()).compat.query.Omnipool.SlipFee.isCompatible(ne.Partial)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,s,a,n,r]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:"best"}),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.balance.getBalance(e,t),this.getPoolLimits()]),o=i.map(async({keyArgs:c,value:p})=>{let[m]=c,{hub_reserve:g,shares:d,tradable:S,cap:_,protocol_shares:k}=p,[x,w]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.balance.getBalance(e,m)]);return{id:m,decimals:x?.decimals,existentialDeposit:x?.existential_deposit,balance:w.transferable,cap:_,hubReserves:g,protocolShares:k,shares:d,tradeable:S,type:x?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:n.transferable,tradeable:s,type:a?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...r}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,s=0;await this.isSlipFeeSupported()&&(s=await this.maxSlipFee.get()??0);let n=await this.dynamicFeesConfig.get(e);if(n?.type==="Fixed"){let{asset_fee:I,protocol_fee:R}=n.value;return{assetFee:h.fromPermill(I),protocolFee:h.fromPermill(R),maxSlipFee:h.fromPermill(s)}}let r=this.getOraclePair(e),o=this.getOraclePair(i),[l,c,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(r),this.emaOracles.get(o)]),[m,g,d]=await this.getAssetFee(t,this.block,l,c,n?.value.asset_fee_params),[S,_,k]=i===1?[0,0,0]:await this.getProtocolFee(t,this.block,l,p,n?.value.protocol_fee_params),x=m+S,w=d+k;return{assetFee:h.fromPermill(g),protocolFee:h.fromPermill(_),maxSlipFee:h.fromPermill(s),min:h.fromPermill(x),max:h.fromPermill(w)}}async getAssetFee(t,e,i,s,a){let{assetOut:n,balanceOut:r}=t,{min_fee:o,max_fee:l,decay:c,amplification:p}=a||await this.api.constants.DynamicFees.AssetFeeParameters();if(!i||!s)return[o,o,l];let m=h.fromPermill(o),g=h.fromPermill(l),[d]=s,{asset_fee:S,timestamp:_}=i,k=Math.max(1,e-_),x=d.volume.b_in.toString(),w=d.volume.b_out.toString(),I=d.liquidity.b.toString();n===0&&(x=d.volume.a_in.toString(),w=d.volume.a_out.toString(),I=d.liquidity.a.toString());let R=h.fromPermill(S),K=b.recalculateAssetFee(x,w,I,"9",r.toString(),h.toRaw(R).toString(),k.toString(),h.toRaw(m).toString(),h.toRaw(g).toString(),c.toString(),p.toString());return[o,Number(K)*1e6,l]}async getProtocolFee(t,e,i,s,a){let{assetIn:n,balanceIn:r}=t,{min_fee:o,max_fee:l,decay:c,amplification:p}=a||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!i||!s)return[o,o,l];let m=h.fromPermill(o),g=h.fromPermill(l),[d]=s,{protocol_fee:S,timestamp:_}=i,k=Math.max(1,e-_),x=d.volume.b_in.toString(),w=d.volume.b_out.toString(),I=d.liquidity.b.toString();n===0&&(x=d.volume.a_in.toString(),w=d.volume.a_out.toString(),I=d.liquidity.a.toString());let R=h.fromPermill(S),K=b.recalculateProtocolFee(x,w,I,"9",r.toString(),h.toRaw(R).toString(),k.toString(),h.toRaw(m).toString(),h.toRaw(g).toString(),c.toString(),p.toString());return[o,Number(K)*1e6,l]}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(s=>s.id).map(s=>this.getOraclePair(s)).map(s=>this.api.query.EmaOracle.Oracles.watchValue(re,s,oe,{at:"best"}).pipe(U(({value:a})=>a),rs(a=>a!==void 0),U((a,n)=>({value:a,index:n})),It(({index:a})=>{a>0&&this.log.trace("emaOracle.Oracles",s.join(":"))}),U(({value:a})=>({pair:s,value:a}))));return os(...i).pipe(Mt(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(s=>{let{pair:a,value:n}=s;this.emaOracles.set(n,a)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe(Lt((t,e)=>!e.deltas),U((t,e)=>({value:t,index:e})),It(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),Mt(()=>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(Lt((t,e)=>!e.deltas),U((t,e)=>({value:t,index:e})),It(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),Mt(()=>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(Lt((t,e)=>!e.deltas),U((t,e)=>({value:t,index:e})),It(({value:t,index:e})=>{e>0&&this.log.trace("omnipool.Assets",t.deltas?.upserted)}),this.watchGuard("omnipool.Assets")).subscribe(({value:{deltas:t}})=>{this.store.update(([e])=>{let i=t?.upserted.reduce((a,n)=>{let[r]=n.args;return a.set(r,n.value),a},new Map),s=e.tokens.map(a=>{let n=i?.get(a.id);return n?this.updateTokenState(a,n):a});return[{...e,tokens:s}]})})}subscribeUpdates(){let t=new ns;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:i,shares:s,tradable:a,cap:n,protocol_shares:r}=e;return{...t,cap:n,hubReserves:i,protocolShares:r,shares:s,tradeable:a}}};var pe={};A(pe,{StableMath:()=>f,StableSwap:()=>q,StableSwapClient:()=>rt});import{calculate_in_given_out as cs,calculate_out_given_in as us,calculate_amplification as ps,calculate_add_one_asset as ms,calculate_liquidity_out_one_asset as ds,calculate_shares as gs,calculate_shares_for_amount as bs,calculate_spot_price_with_fee as hs,pool_account_name as Ps,recalculate_peg as ys}from"@galacticcouncil/math-stableswap";var f=class{static getPoolAddress(t){return Ps(t)}static defaultPegs(t){let e=[];for(let i=0;i<t;i++)e.push(["1","1"]);return e}static calculateAmplification(t,e,i,s,a){return ps(t,e,i,s,a)}static calculateInGivenOut(t,e,i,s,a,n,r){return cs(t,e,i,s,a,n,r)}static calculateAddOneAsset(t,e,i,s,a,n,r){return ms(t,e,i,s,a,n,r)}static calculateSharesForAmount(t,e,i,s,a,n,r){return bs(t,e,i,s,a,n,r)}static calculateOutGivenIn(t,e,i,s,a,n,r){return us(t,e,i,s,a,n,r)}static calculateLiquidityOutOneAsset(t,e,i,s,a,n,r){return ds(t,e,i,s,a,n,r)}static calculateShares(t,e,i,s,a,n){return gs(t,e,i,s,a,n)}static calculateSpotPriceWithFee(t,e,i,s,a,n,r,o){return hs(t,e,i,s,a,n,r,o)}static recalculatePegs(t,e,i,s,a,n){let r=ys(t,e,i,s,a,n);return JSON.parse(r)}};import{RUNTIME_DECIMALS as fs,big as ce}from"@galacticcouncil/common";var{FeeUtils:Y}=P,q=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new u(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),s=i.get(t),a=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:a.tradeable,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,i),n=s===0n?0:D.calculateBuyFee(s,a),r=[],o=b.isSellAllowed(t.tradeableIn),l=b.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:n,errors:r}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,i),n=D.calculateSellFee(s,a),r=[],o=b.isSellAllowed(t.tradeableIn),l=b.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:n,errors:r}}calculateIn(t,e,i){let s=f.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?Y.toRaw(i.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateAddOneAsset(t,e,i){let s=f.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?Y.toRaw(i.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateSharesForAmount(t,e,i){let s=f.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?Y.toRaw(i.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateInGivenOut(t,e,i){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,i):t.assetIn==this.id?this.calculateSharesForAmount(t,e,i):this.calculateIn(t,e,i)}spotPriceInGivenOut(t){let e=f.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=f.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?Y.toRaw(i.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateWithdrawOneAsset(t,e,i){let s=f.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?Y.toRaw(i.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateShares(t,e,i){let s=f.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?Y.toRaw(i.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e,i){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,i):t.assetOut==this.id?this.calculateShares(t,e,i):this.calculateOut(t,e,i)}spotPriceOutGivenIn(t){let e=f.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,j.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],j.jsonFormatter)}normalizeSpot(t,e,i,s,a){return e?t*ce.pow10(fs-a):i?t/ce.pow10(a-s):t}};import{AccountId as Ss,CompatibilityLevel as vs}from"polkadot-api";import{toHex as xs}from"@polkadot-api/utils";import{blake2b as Is}from"@noble/hashes/blake2b";import{Subscription as Os,distinctUntilChanged as ws,map as wt,merge as Ts,tap as ue}from"rxjs";import{HYDRATION_SS58_PREFIX as As,RUNTIME_DECIMALS as Bs}from"@galacticcouncil/common";var{FeeUtils:Fs}=P,rt=class extends v{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=f.getPoolAddress(t),i=Is(e,{dkLen:32}),s=xs(i);return Ss(As).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:i,final_amplification:s,initial_block:a,final_block:n}=t,r=f.calculateAmplification(i.toString(),s.toString(),a.toString(),n.toString(),e.toString()),o=Number(r)<s;return{amplification:BigInt(r),isRampPeriod:o}}async getPoolTokens(t,e){let i=this.getPoolAddress(t),s=e.assets.map(async a=>{let[n,r,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,a),this.api.query.AssetRegistry.Assets.getValue(a),this.balance.getBalance(i,a)]);return{id:a,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:o.transferable,tradeable:n,type:r?.asset_type.type}});return Promise.all(s)}async isSupported(){return(await this.api.getStaticApis()).compat.query.Stableswap.Pools.isCompatible(vs.BackwardsCompatible)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:"best"}),this.api.query.System.Number.getValue({at:"best"}),this.getPoolLimits()]),s=t.map(async({keyArgs:a,value:n})=>{let[r]=a,o=this.getPoolAddress(r),[l,c,p]=await Promise.all([this.getPoolTokens(r,n),this.api.query.Stableswap.PoolPegs.getValue(r,{at:"best"}),this.api.query.Tokens.TotalIssuance.getValue(r,{at:"best"})]),m=this.getPoolAmplification(n,e),g=c?this.getRecentPegs(c):this.getDefaultPegs(n);return l.push({id:r,tradeable:15,balance:p,decimals:Bs}),this.poolsData.set(r,n),{address:o,id:r,type:"Stableswap",fee:Fs.fromPermill(n.fee),tokens:l,totalIssuance:p,pegs:g,...i,...m}});return Promise.all(s)}async getPoolFees(t,e){return{fee:this.store.pools.find(s=>s.address===e).fee}}getDefaultPegs(t){return f.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([i,s])=>s.map(a=>a.toString()))}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,{at:"best"}).pipe(wt(({value:s})=>s),wt((s,a)=>({value:s,index:a})),ue(({index:s,value:a})=>{s>0&&this.log.trace("tokens.TotalIssuance",i,a)}),wt(({value:s})=>({id:i,value:s}))));return Ts(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:s,value:a}=i;this.store.update(n=>{let r=[];return n.filter(o=>o.id===s).forEach(o=>{let l=o.tokens.map(c=>c.id===s?{...c,balance:a}:c);r.push({...o,tokens:l,totalIssuance:a})}),r})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe(ws((t,e)=>!e.deltas),wt((t,e)=>({value:t,index:e})),ue(({value:t,index:e})=>{e>0&&this.log.trace("stableswap.PoolPegs",t.deltas?.upserted)}),this.watchGuard("stableswap.PoolPegs")).subscribe({error:t=>this.log.error("stableswap.PoolPegs",t),next:({value:{deltas:t}})=>{this.store.update(e=>{let i=[],s=new Map(e.map(a=>[a.id,a]));return t?.upserted.forEach(({args:a,value:n})=>{let[r]=a,o=s.get(r);if(o){let l=this.getRecentPegs(n);i.push({...o,pegs:l})}}),i})}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(e=>{let i=[];return e.filter(s=>s.isRampPeriod).forEach(s=>{let a=this.poolsData.get(s.id);if(a){let n=this.getPoolAmplification(a,t);i.push({...s,...n})}}),i})})}subscribeUpdates(){let t=new Os;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var de={};A(de,{XykMath:()=>L,XykPool:()=>ot,XykPoolClient:()=>lt});import{calculate_in_given_out as _s,calculate_out_given_in as ks,calculate_pool_trade_fee as Rs,get_spot_price as Es,calculate_liquidity_in as Cs,calculate_shares as Ls,calculate_spot_price as Ms,calculate_spot_price_with_fee as Ds,calculate_liquidity_out_asset_a as Hs,calculate_liquidity_out_asset_b as Gs}from"@galacticcouncil/math-xyk";var L=class{static getSpotPrice(t,e,i){return Es(t,e,i)}static calculateInGivenOut(t,e,i){return _s(t,e,i)}static calculateOutGivenIn(t,e,i){return ks(t,e,i)}static calculatePoolTradeFee(t,e,i){return Rs(t,e,i)}static calculateLiquidityIn(t,e,i){return Cs(t,e,i)}static calculateSpotPrice(t,e){return Ms(t,e)}static calculateSpotPriceWithFee(t,e,i,s){return Ds(t,e,i,s)}static calculateShares(t,e,i){return Ls(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,s){return Hs(t,e,i,s)}static calculateLiquidityOutAssetB(t,e,i,s){return Gs(t,e,i,s)}};import{big as qs}from"@galacticcouncil/common";var{FeeUtils:me}=P,ot=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),s=i.get(t),a=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:s.decimals,decimalsOut:a.decimals,balanceIn:s.balance,balanceOut:a.balance,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),a=this.calculateTradeFee(s,i),n=me.toPct(i.exchangeFee),r=s+a,o=[];(e<this.minTradingLimit||s<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return r>c&&o.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:n,errors:o}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),a=this.calculateTradeFee(s,i),n=me.toPct(i.exchangeFee),r=s-a,o=[];(e<this.minTradingLimit||s<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return r>c&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:n,errors:o}}calculateInGivenOut(t,e){let i=L.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e){let i=L.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){let e=L.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=L.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=L.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(i)}normalizeSpot(t,e,i){let s=e-i;if(s===0)return t;let a=qs.pow10(Math.abs(s));return s>0?t*a:t/a}};import{CompatibilityLevel as Ns}from"polkadot-api";import{Subscription as Vs}from"rxjs";var lt=class extends v{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(Ns.BackwardsCompatible)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries(),this.getPoolLimits()]),i=t.map(async({keyArgs:s,value:a})=>{let[n]=s,[r,o]=a,[l,c,p,m]=await Promise.all([this.balance.getBalance(n,r),this.api.query.AssetRegistry.Assets.getValue(r),this.balance.getBalance(n,o),this.api.query.AssetRegistry.Assets.getValue(o)]);return{address:n,type:"XYK",tokens:[{id:r,decimals:c?.decimals||this.decimals.get(r),existentialDeposit:c?.existential_deposit,balance:l.transferable,type:c?.asset_type.type},{id:o,decimals:m?.decimals||this.decimals.get(o),existentialDeposit:m?.existential_deposit,balance:p.transferable,type:m?.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 Vs.EMPTY}};var Se={};A(Se,{AavePool:()=>ct,AavePoolClient:()=>ut});import{big as ge,RUNTIME_DECIMALS as be}from"@galacticcouncil/common";var ct=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),s=i.get(t),a=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),a=[];return e>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:a}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),a=[];return s>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:a}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return ge.toBigInt(1,be)}spotPriceOutGivenIn(t){return ge.toBigInt(1,be)}calculateTradeFee(t,e){return 0n}};import{AccountId as Ws,Binary as $s}from"polkadot-api";import{toHex as Us}from"@polkadot-api/utils";import{Subscription as Pe,filter as Dt,map as ye,mergeMap as fe}from"rxjs";import{decodeEventLog as Ys}from"viem";import{erc20 as Xs,HYDRATION_SS58_PREFIX as zs}from"@galacticcouncil/common";var he=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"}];var{ERC20:Ks}=Xs,js=["Supply","Withdraw","Repay","Borrow"],ut=class extends v{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,s=new TextEncoder().encode(i.padEnd(32,"\0")),a=Us(s);return Ws(zs).dec(a)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:"best"})).map(async({reserve:i,atoken:s,liqudity_in:a,liqudity_out:n})=>{let[r,o,l,c]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i),this.api.query.AssetRegistry.AssetLocations.getValue(i),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(i,s),type:"Aave",tokens:[{id:i,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:a,location:o,type:r?.asset_type.type},{id:s,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:n,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:s,liqudity_out:a}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:"best"});return t.tokens.map(n=>{let r=n.id===e.id?s:a;return{...n,balance:r}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key}throw new Error("Invalid aave reserve multilocation")}return Ks.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:i}=t;return{assetIn:e,assetOut:i,key:`${e}:${i}`}}parseEvmLog(t){let{topics:e,data:i}=t.log,s=e,a=$s.toHex(i);try{let{eventName:n,args:r}=Ys({abi:he,topics:s,data:a}),o=r.reserve.toLowerCase();return{eventName:n,reserve:o,key:`${n}:${o}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(i=>i.tokens).map(([i,s])=>s).map(i=>i.id);return this.api.event.Router.Executed.watch().pipe(fe(({events:i})=>i),ye(({payload:i})=>this.parseRouterLog(i)),Dt(({assetIn:i,assetOut:s})=>e.includes(i)||e.includes(s)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:s,key:a})=>{this.log.trace("router.Executed",a),this.store.update(async n=>{let r=[];for(let o of n){let[l,c]=o.tokens;if(c.id===i||c.id===s){let m=await this.getPoolDelta(o);r.push({...o,tokens:m})}}return r})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(fe(({events:t})=>t),ye(({payload:t})=>this.parseEvmLog(t)),Dt(t=>t!==void 0),Dt(({eventName:t})=>js.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async i=>{let s=[];for(let a of i){let[n]=a.tokens;if(this.getReserveH160Id(n).toLowerCase()===t){let o=await this.getPoolDelta(a);s.push({...a,tokens:o})}}return s})})}subscribeBalances(){return Pe.EMPTY}subscribeUpdates(){let t=new Pe;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var Ie={};A(Ie,{HsmMath:()=>O,HsmPool:()=>pt,HsmPoolClient:()=>gt});import{calculate_collateral_in_given_hollar_out as Qs,calculate_collateral_out_given_hollar_in as Js,calculate_hollar_in_given_collateral_out as Zs,calculate_hollar_out_given_collateral_in as ta,calculate_imbalance as ea,calculate_max_price as ia,calculate_buyback_limit as sa,calculate_buyback_price_with_fee as aa}from"@galacticcouncil/math-hsm";var O=class{static calculateCollateralInGivenHollarOut(t,e,i){return Qs(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return Js(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return ta(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return Zs(t,e,i)}static calculateImbalance(t,e,i){return ea(t,e,i)}static calculateBuybackLimit(t,e){return sa(t,e)}static calculateBuybackPriceWithFee(t,e,i){return aa(t,e,i)}static calculateMaxPrice(t,e){return ia(t,e)}};import{big as M,RUNTIME_DECIMALS as Tt}from"@galacticcouncil/common";var{FeeUtils:X}=P,pt=class u extends q{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new u(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,i){let s=this.parsePair(t.assetOut,t.assetIn),a=super.calculateInGivenOut(s,e,{fee:this.fee}),n=this.calculateBuybackLimit(t);e>n&&i.push("MaxBuyBackExceeded");let r=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,a)>r&&i.push("MaxBuyPriceExceeded"),a>this.collateralBalance&&i.push("InsufficientCollateral"),i}validateTradeHollarOut(t,e,i){return this.collateralBalance+t>this.maxInHolding&&i.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&i.push("FacilitatorCapacityExceeded"),i}validateTradeConstraints(t,e,i){let s=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,s):this.validateTradeHollarOut(e,i,s)}validateAndBuy(t,e){let i=this.calculateInGivenOut(t,e),s=this.validateTradeConstraints(t,i,e);return{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e){let i=this.calculateOutGivenIn(t,e),s=this.validateTradeConstraints(t,e,i);return{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(t,e){let i=super.calculateInGivenOut(t,e,{fee:this.fee}),s=O.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),X.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=O.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),X.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=O.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),X.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=O.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),X.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=O.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=O.calculateBuybackLimit(e.toString(),X.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let s=O.calculateBuybackPriceWithFee(i.toString(),e.toString(),X.toRaw(this.buyBackFee).toString()),[a,n]=JSON.parse(s),r=M.pow10(t.decimalsIn+Tt-t.decimalsOut);return BigInt(a)*r/BigInt(n)}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=O.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[s,a]=JSON.parse(i),n=M.pow10(Tt-t.decimalsOut);return BigInt(s)*n/BigInt(a)}spotPriceInGivenOut(t){let e=M.toBigInt(1,t.decimalsOut),s=this.calculateInGivenOut(t,e)*M.pow10(Tt-t.decimalsOut);return this.normalizeSpotPrice(s,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=M.toBigInt(1,t.decimalsIn),s=this.calculateOutGivenIn(t,e)*M.pow10(Tt-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)?[M.toBigInt(1,18).toString(),M.toBigInt(1,i).toString()]:e}isDefaultPeg(t){let[e,i]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&i==="1"}normalizeSpotPrice(t,e,i){let s=e-i;if(s===0)return t;let a=M.pow10(Math.abs(s));return s>0?t*a:t/a}};import{AccountId as na,Binary as ra,CompatibilityLevel as oa}from"polkadot-api";import{toHex as la}from"@polkadot-api/utils";import{Subscription as Ht,combineLatest as ca,filter as ve,map as Gt,mergeMap as ua,pairwise as pa}from"rxjs";import{decodeEventLog as ma}from"viem";import{h160 as da,HYDRATION_SS58_PREFIX as ga}from"@galacticcouncil/common";var mt=[{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 dt=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,s]=await this.client.readContract({abi:mt,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-s}};var{FeeUtils:qt}=P,{H160:xe}=da,ba=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],gt=class extends v{ghoClient;stableClient;constructor(t,e,i){super(t,e),this.stableClient=i,this.ghoClient=new dt(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=la(i);return na(ga).dec(s)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(oa.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,s]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t),this.api.query.HSM.Collaterals.getEntries({at:"best"}),this.stableClient.getPools()]);if(i.length===0)return[];let a=this.getFacilitatorAddress(),n=xe.fromAny(a),r=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(r,n),l=i.map(async({keyArgs:p,value:m})=>{let[g]=p,{pool_id:d,max_buy_price_coefficient:S,max_in_holding:_,purchase_fee:k,buy_back_fee:x,buyback_rate:w}=m,I=s.find(R=>R.id===d);if(I){let R=this.getPoolId(d),K=await this.balance.getBalance(a,g);return{...I,address:R,type:"HSM",tokens:I.tokens.filter(Oe=>Oe.id!==d),hsmAddress:a,hsmMintCapacity:o,hollarId:t,hollarH160:r,collateralId:g,collateralBalance:K.transferable,maxBuyPriceCoefficient:S,maxInHolding:_,purchaseFee:qt.fromPermill(k),buyBackFee:qt.fromPermill(x),buyBackRate:qt.fromPerbill(w)}}});return(await Promise.all(l)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:i}=t.log,s=e,a=ra.toHex(i);try{let{eventName:n,args:r}=ma({abi:mt,topics:s,data:a}),o=r.facilitatorAddress.toLowerCase();return{eventName:n,facilitator:o,key:`${n}:${o}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(ua(({events:t})=>t),Gt(({payload:t})=>this.parseEvmLog(t)),ve(t=>t!==void 0),ve(({eventName:t})=>ba.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async i=>{let s=[],[{hsmAddress:a,hollarH160:n}]=i,r=xe.fromAny(a);if(r.toLowerCase()===e){let l=await this.ghoClient.getFacilitatorCapacity(n,r);for(let c of i)s.push({...c,hsmMintCapacity:l})}return s})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(a=>{let{tokens:n,collateralId:r}=a;n.find(l=>l.id===r).type==="Erc20"?e.push(r):t.push(r)});let[{hsmAddress:i}]=this.store.pools,s=[];if(t.length>0){let a=this.balance.watchTokensBalance(i);s.push(a)}if(e.length>0){let a=this.balance.watchErc20Balance(i,e);s.push(a)}return s.length>0?ca(s).pipe(Gt(a=>a.flat()),pa(),Gt(([a,n])=>this.balance.getDeltas(a,n)),this.watchGuard("balances")).subscribe(a=>{this.store.update(n=>{let r=[],o=new Map(n.map(l=>[l.collateralId,l]));return a.forEach(({id:l,balance:c})=>{let p=o.get(l);p&&(this.log.trace("balances",{id:l,balance:c}),r.push({...p,collateralBalance:c.transferable}))}),r})}):Ht.EMPTY}subscribeStableswapUpdates(){return this.stableClient.getSubscriber().pipe(this.watchGuard("stableswap.updates")).subscribe(t=>{let e=new Map(t.map(i=>[i.id,i]));this.store.update(i=>{let s=[];for(let a of i){let n=e.get(a.id);n&&s.push({...a,fee:n.fee,tokens:n.tokens.filter(r=>r.id!==a.id),totalIssuance:n.totalIssuance,pegs:n.pegs,amplification:n.amplification,isRampPeriod:n.isRampPeriod})}return s})})}subscribeBalances(){return Ht.EMPTY}subscribeUpdates(){let t=new Ht;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var Nt=class{static get(t){switch(t.type){case"Aave":return ct.fromPool(t);case"XYK":return ot.fromPool(t);case"Omnipool":return at.fromPool(t);case"LBP":return Q.fromPool(t);case"Stableswap":return q.fromPool(t);case"HSM":return pt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{log as ha}from"@galacticcouncil/common";import{Subject as Pa,Subscription as z,takeUntil as ya}from"rxjs";var At=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}};var{logger:fa}=ha,Vt=class extends B{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=z.EMPTY;omniSub=z.EMPTY;stableSub=z.EMPTY;hsmSub=z.EMPTY;xykSub=z.EMPTY;lbpSub=z.EMPTY;isReady=!1;isDestroyed=new Pa;constructor(t,e){super(t),this.evm=e,this.aave=new ut(t,e),this.omnipool=new nt(t,e),this.stableswap=new rt(t,e),this.hsm=new gt(t,e,this.stableswap),this.xyk=new lt(t,e),this.lbp=new st(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe(ya(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")||(fa.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 At(e.type)}};export{Vt as PoolContextProvider,H as PoolError,Nt as PoolFactory,y as PoolType,Se as aave,Ie as hsm,se as lbp,le as omni,pe as stable,de as xyk};
@@ -24,7 +24,7 @@ export declare class LbpPool implements Pool {
24
24
  fee: PoolFee;
25
25
  repayFeeApply: boolean;
26
26
  static fromPool(pool: LbpPoolBase): LbpPool;
27
- constructor(address: string, tokens: WeightedPoolToken[], maxInRatio: bigint, maxOutRatio: bigint, minTradingLimit: bigint, fee: PoolFee, repayFeeApply: boolean);
27
+ constructor(pool: LbpPoolBase);
28
28
  validatePair(_tokenIn: number, _tokenOut: number): boolean;
29
29
  parsePair(tokenIn: number, tokenOut: number): WeightedPoolPair;
30
30
  /**
@@ -1,18 +1,20 @@
1
- import { type Observable } from 'rxjs';
2
- import { PoolType, PoolFees } from '../types';
1
+ import { Subscription } from 'rxjs';
2
+ import { PoolType, PoolFees, PoolPair } from '../types';
3
3
  import { PoolClient } from '../PoolClient';
4
4
  import { LbpPoolBase } from './LbpPool';
5
5
  export declare class LbpPoolClient extends PoolClient<LbpPoolBase> {
6
6
  private readonly MAX_FINAL_WEIGHT;
7
7
  private poolsData;
8
+ getPoolType(): PoolType;
9
+ private getPoolLimits;
10
+ private getPoolWeights;
11
+ isSupported(): Promise<boolean>;
8
12
  protected loadPools(): Promise<LbpPoolBase[]>;
9
13
  private getPoolDelta;
10
14
  private isActivePool;
11
15
  private isRepayFeeApplied;
12
16
  private getRepayFee;
13
- private getPoolLimits;
14
- getPoolFees(pool: LbpPoolBase): Promise<PoolFees>;
15
- getPoolType(): PoolType;
16
- isSupported(): Promise<boolean>;
17
- subscribePoolChange(pool: LbpPoolBase): Observable<LbpPoolBase>;
17
+ getPoolFees(_pair: PoolPair, address: string): Promise<PoolFees>;
18
+ private subscribeValidationData;
19
+ protected subscribeUpdates(): Subscription;
18
20
  }
@@ -1,19 +1,20 @@
1
1
  export declare class OmniMath {
2
2
  static calculateSpotPrice(assetInBalance: string, assetInHubReserve: string, assetOutBalance: string, assetOutHubReserve: string): string;
3
3
  static calculateLrnaSpotPrice(assetBalance: string, assetHubReserve: string): string;
4
- static calculateInGivenOut(assetInBalance: string, assetInHubReserve: string, assetInShares: string, assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string, protocolFee: string): string;
5
- static calculateLrnaInGivenOut(assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string): string;
6
- static calculateOutGivenIn(assetInBalance: string, assetInHubReserve: string, assetInShares: string, assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountIn: string, assetFee: string, protocolFee: string): string;
7
- static calculateOutGivenLrnaIn(assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string): string;
8
- static calculatePoolTradeFee(amount: string, feeNumerator: number, feeDenominator: number): string;
4
+ static calculateInGivenOut(assetInBalance: string, assetInHubReserve: string, assetInShares: string, assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string, protocolFee: string, maxSlipFee: string): string;
5
+ static calculateLrnaInGivenOut(assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string, maxSlipFee: string): string;
6
+ static calculateOutGivenIn(assetInBalance: string, assetInHubReserve: string, assetInShares: string, assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountIn: string, assetFee: string, protocolFee: string, maxSlipFee: string): string;
7
+ static calculateOutGivenLrnaIn(assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string, maxSlipFee: string): string;
9
8
  static calculateShares(assetReserve: string, assetHubReserve: string, assetShares: string, amountIn: string): string;
10
9
  static calculateLiquidityOut(assetReserve: string, assetHubReserve: string, assetShares: string, positionAmount: string, positionShares: string, positionPrice: string, sharesToRemove: string, withdrawalFee: string): string;
11
10
  static calculateLiquidityLRNAOut(assetReserve: string, assetHubReserve: string, assetShares: string, positionAmount: string, positionShares: string, positionPrice: string, sharesToRemove: string, withdrawalFee: string): string;
12
11
  static calculateCapDifference(assetReserve: string, assetHubReserve: string, assetCap: string, totalHubReserve: string): string;
13
- static verifyAssetCap(assetReserve: string, assetCap: string, hubAdded: string, totalHubReserve: string): boolean;
14
12
  static calculateLimitHubIn(assetReserve: string, assetHubReserve: string, assetShares: string, amountIn: string): string;
15
13
  static isSellAllowed(bits: number): boolean;
16
14
  static isBuyAllowed(bits: number): boolean;
17
15
  static isAddLiquidityAllowed(bits: number): boolean;
18
16
  static isRemoveLiquidityAllowed(bits: number): boolean;
17
+ static recalculateAssetFee(oracleAmountIn: string, oracleAmountOut: string, oracleLiquidity: string, oraclePeriod: string, currentAssetLiquidity: string, previousFee: string, blocDifference: string, minFee: string, maxFee: string, decay: string, amplification: string): string;
18
+ static recalculateProtocolFee(oracleAmountIn: string, oracleAmountOut: string, oracleLiquidity: string, oraclePeriod: string, currentAssetLiquidity: string, previousFee: string, blocDifference: string, minFee: string, maxFee: string, decay: string, amplification: string): string;
19
+ static verifyAssetCap(assetReserve: string, assetCap: string, hubAdded: string, totalHubReserve: string): boolean;
19
20
  }
@@ -16,6 +16,7 @@ export type OmniPoolToken = PoolToken & {
16
16
  export type OmniPoolFees = PoolFees & {
17
17
  assetFee: PoolFee;
18
18
  protocolFee: PoolFee;
19
+ maxSlipFee: PoolFee;
19
20
  };
20
21
  export type OmniPoolBase = PoolBase & {
21
22
  hubAssetId: number;
@@ -29,7 +30,7 @@ export declare class OmniPool implements Pool {
29
30
  minTradingLimit: bigint;
30
31
  hubAssetId: number;
31
32
  static fromPool(pool: OmniPoolBase): OmniPool;
32
- constructor(address: string, tokens: OmniPoolToken[], maxInRation: bigint, maxOutRatio: bigint, minTradeLimit: bigint, hubAssetId: number);
33
+ constructor(pool: OmniPoolBase);
33
34
  validatePair(_tokenIn: number, tokenOut: number): boolean;
34
35
  parsePair(tokenIn: number, tokenOut: number): OmniPoolPair;
35
36
  validateAndBuy(poolPair: OmniPoolPair, amountOut: bigint, fees: OmniPoolFees): BuyCtx;
@@ -42,4 +43,16 @@ export declare class OmniPool implements Pool {
42
43
  spotPriceLrnaInGivenOut(poolPair: OmniPoolPair): bigint;
43
44
  spotPriceOutGivenIn(poolPair: OmniPoolPair): bigint;
44
45
  spotPriceOutGivenLrnaIn(poolPair: OmniPoolPair): bigint;
46
+ /**
47
+ * Normalize OmniMath spot to runtime decimals.
48
+ *
49
+ * - if `decimalsIn === decimalsOut`: spot already 18dp
50
+ * - if `decimalsIn > decimalsOut`: spot in 18 - (decimalsIn - decimalsOut)
51
+ * - if `decimalsIn < decimalsOut`: spot in 18 + (decimalsOut - decimalsIn)
52
+ *
53
+ * @param spotRaw - raw spot
54
+ * @param decimalsIn - asset in decimals
55
+ * @param decimalsOut - asset out decimals
56
+ */
57
+ private normalizeSpot;
45
58
  }
@@ -0,0 +1,29 @@
1
+ import { Subscription } from 'rxjs';
2
+ import { PoolClient } from '../PoolClient';
3
+ import { PoolType, PoolPair } from '../types';
4
+ import { OmniPoolBase, OmniPoolFees } from './OmniPool';
5
+ export declare class OmniPoolClient extends PoolClient<OmniPoolBase> {
6
+ private queryBus;
7
+ private block;
8
+ private dynamicFeesConfig;
9
+ private dynamicFees;
10
+ private maxSlipFee;
11
+ private emaOracles;
12
+ getPoolType(): PoolType;
13
+ private getPoolAddress;
14
+ private getOraclePair;
15
+ private getPoolLimits;
16
+ isSupported(): Promise<boolean>;
17
+ isSlipFeeSupported(): Promise<boolean>;
18
+ protected loadPools(): Promise<OmniPoolBase[]>;
19
+ getPoolFees(pair: PoolPair): Promise<OmniPoolFees>;
20
+ private getAssetFee;
21
+ private getProtocolFee;
22
+ private subscribeEmaOracles;
23
+ private subscribeDynamicFees;
24
+ private subscribeDynamicFeesConfig;
25
+ private subscribeBlock;
26
+ private subscribeAssets;
27
+ protected subscribeUpdates(): Subscription;
28
+ private updateTokenState;
29
+ }
@@ -0,0 +1,11 @@
1
+ import { FixedSizeArray } from 'polkadot-api';
2
+ import { HydrationNextQueries, HydrationConstants, HydrationQueries } from '@galacticcouncil/descriptors';
3
+ export type TDynamicFees = HydrationQueries['DynamicFees']['AssetFee']['Value'];
4
+ export type TDynamicFeesConfig = HydrationQueries['DynamicFees']['AssetFeeConfiguration']['Value'];
5
+ export type TDynamicFeeRange = [number, number, number];
6
+ export type TSlipFee = HydrationNextQueries['Omnipool']['SlipFee']['Value'];
7
+ export type TAssetFeeParams = HydrationConstants['DynamicFees']['AssetFeeParameters'];
8
+ export type TProtocolFeeParams = HydrationConstants['DynamicFees']['ProtocolFeeParameters'];
9
+ export type TEmaOracle = HydrationQueries['EmaOracle']['Oracles']['Value'];
10
+ export type TEmaPair = FixedSizeArray<2, number>;
11
+ export type TOmnipoolAsset = HydrationQueries['Omnipool']['Assets']['Value'];
@@ -9,6 +9,5 @@ export declare class StableMath {
9
9
  static calculateLiquidityOutOneAsset(reserves: string, shares: string, assetOut: number, amplification: string, shareIssuance: string, withdrawFee: string, pegs: string): string;
10
10
  static calculateShares(reserves: string, assets: string, amplification: string, shareIssuance: string, fee: string, pegs: string): string;
11
11
  static calculateSpotPriceWithFee(poolId: string, reserves: string, amplification: string, assetIn: string, assetOut: string, shareIssuance: string, fee: string, pegs: string): string;
12
- static calculatePoolTradeFee(amount: string, feeNumerator: number, feeDenominator: number): string;
13
- static recalculatePegs(currentPegs: string, targetPegs: string, currentBlock: string, maxPegUpdate: string, poolFee: string): string;
12
+ static recalculatePegs(currentPegs: string, currentPegsUpdatedAt: string, targetPegs: string, currentBlock: string, maxPegUpdate: string, poolFee: string): [string, string[][]];
14
13
  }
@@ -1,4 +1,4 @@
1
- import { BuyCtx, Pool, PoolBase, PoolFee, PoolFees, PoolPair, PoolToken, PoolType, SellCtx } from '../types';
1
+ import { BuyCtx, Pool, PoolBase, PoolFee, PoolFees, PoolPair, PoolPegs, PoolToken, PoolType, SellCtx } from '../types';
2
2
  export type StableSwapPair = PoolPair & {
3
3
  tradeableIn: number;
4
4
  tradeableOut: number;
@@ -8,9 +8,11 @@ export type StableSwapFees = PoolFees & {
8
8
  };
9
9
  export type StableSwapBase = PoolBase & {
10
10
  amplification: bigint;
11
- id: string;
11
+ isRampPeriod: boolean;
12
+ id: number;
12
13
  fee: PoolFee;
13
14
  totalIssuance: bigint;
15
+ pegs: PoolPegs;
14
16
  };
15
17
  export declare class StableSwap implements Pool {
16
18
  type: PoolType;
@@ -20,11 +22,13 @@ export declare class StableSwap implements Pool {
20
22
  maxOutRatio: bigint;
21
23
  minTradingLimit: bigint;
22
24
  amplification: bigint;
25
+ isRampPeriod: boolean;
23
26
  id: number;
24
27
  fee: PoolFee;
25
28
  totalIssuance: bigint;
29
+ pegs: string[][];
26
30
  static fromPool(pool: StableSwapBase): StableSwap;
27
- constructor(address: string, tokens: PoolToken[], maxInRation: bigint, maxOutRatio: bigint, minTradeLimit: bigint, amplification: bigint, id: number, fee: PoolFee, totalIssuance: bigint);
31
+ constructor(pool: StableSwapBase);
28
32
  validatePair(_tokenIn: number, _tokenOut: number): boolean;
29
33
  parsePair(tokenIn: number, tokenOut: number): StableSwapPair;
30
34
  validateAndBuy(poolPair: StableSwapPair, amountOut: bigint, fees: StableSwapFees): BuyCtx;
@@ -39,8 +43,21 @@ export declare class StableSwap implements Pool {
39
43
  private calculateShares;
40
44
  calculateOutGivenIn(poolPair: PoolPair, amountIn: bigint, fees?: StableSwapFees): bigint;
41
45
  spotPriceOutGivenIn(poolPair: PoolPair): bigint;
42
- calculateTradeFee(amount: bigint, fees: StableSwapFees): bigint;
43
46
  private getPegs;
44
47
  private getReserves;
45
48
  private getAssets;
49
+ /**
50
+ * Normalize spot to runtime decimals.
51
+ *
52
+ * - if `neither arg is share`: spot already 18dp
53
+ * - if `argIn is share`: spot in decimalsIn
54
+ * - if `argOut is share`: spot in 18 + (decimalsOut - decimalsIn)
55
+ *
56
+ * @param spotRaw - raw spot
57
+ * @param isInShare - whether the first arg is share
58
+ * @param isOutShare - whether the second arg is share
59
+ * @param decimalsIn - asset in decimals
60
+ * @param decimalsOut - asset out decimals
61
+ */
62
+ private normalizeSpot;
46
63
  }