@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
package/build/index.mjs CHANGED
@@ -1 +1 @@
1
- var Gt=Object.defineProperty;var O=(u,t)=>{for(var e in t)Gt(u,e,{get:t[e],enumerable:!0})};var xt={};O(xt,{Papi:()=>F,getWs:()=>Xt});import{createClient as Ht}from"polkadot-api";import{withPolkadotSdkCompat as Wt}from"polkadot-api/polkadot-sdk-compat";var Xt=async u=>{let t=typeof u=="string"?u.split(","):u,i=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(t);return Ht(Wt(i))};import{hydration as Yt}from"@galacticcouncil/descriptors";var F=class{client;constructor(t){this.client=t}get api(){return this.client.getTypedApi(Yt)}logSync(t,e,s){let i=t.substring(0,10).concat("..."),n=["\u{1F504} Sync",e,"[",i,"]",s].join(" ");console.log(n)}};var Tt={};O(Tt,{AssetClient:()=>at,BalanceClient:()=>G});var at=class extends F{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:s,value:i})=>{let[n]=s;return[n,i]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:s,value:i})=>{let[n]=s;return[n,i]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:s})=>{let{asset_type:i}=s;return this.SUPPORTED_TYPES.includes(i.type)}).map(({keyArgs:s,value:i})=>{let[n]=s;return[n,i]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:s,value:i})=>{let[n]=s;return[n,i]}))}async mapToken(t,e,s,i){let{name:n,asset_type:a,is_sufficient:o,existential_deposit:r}=e,{symbol:l,decimals:c}=s.get(t)??{};return{id:t,name:n?.asText(),symbol:l,decimals:c,icon:l,type:a.type,isSufficient:o,location:i,existentialDeposit:r}}async mapBond(t,e,s,i){let[n,a]=i,{asset_type:o,is_sufficient:r,existential_deposit:l}=e,{symbol:c,decimals:g}=await this.mapToken(n,e,s),m=Number(a),p=new Intl.DateTimeFormat("en-GB"),b=[c,"Bond",p.format(m)].join(" ");return{id:t,name:b,symbol:c+"b",decimals:g,icon:c,type:o.type,isSufficient:r,existentialDeposit:l,underlyingAssetId:n,maturity:m}}async mapShares(t,e,s,i){let{assets:n}=i,{name:a,symbol:o,asset_type:r,is_sufficient:l,existential_deposit:c}=e,g=await Promise.all(n.map(async b=>{let{symbol:y}=await this.mapToken(b,e,s);return[b,y]})),m=Object.fromEntries(g),p=Object.values(m);return{id:t,name:p.join(", "),symbol:o?.asText()||a?.asText(),decimals:18,icon:p.join("/"),type:r.type,isSufficient:l,existentialDeposit:c,meta:m}}async mapExternal(t,e,s,i){let n=await this.mapToken(t,e,new Map,i),a=s?.find(o=>o.internalId===n.id);return a?{...n,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:n}parseMetadata(t){return new Map(Array.from(t,([e,s])=>[e,{symbol:s.symbol?.asText(),decimals:s.decimals}]))}async getOnChainAssets(t,e){let[s,i,n,a]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),o=this.parseMetadata(s),r=[];for(let[l,c]of Array.from(s)){let g=i.get(l),{asset_type:m}=c,p;switch(m.type){case"Bond":let b=a.get(l);p=await this.mapBond(l,c,o,b);break;case"StableSwap":let y=n.get(l);p=await this.mapShares(l,c,o,y);break;case"External":p=await this.mapExternal(l,c,e,g);break;default:p=await this.mapToken(l,c,o,g)}r.push(p)}return t?r:r.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};import{Subject as zt,combineLatest as Kt,debounceTime as Qt,distinctUntilChanged as At,finalize as Jt,map as z,pairwise as $t,shareReplay as Zt}from"rxjs";var wt={};O(wt,{HUB_ASSET_ID:()=>bt,HYDRATION_OMNIPOOL_ADDRESS:()=>Ut,HYDRATION_PARACHAIN_ID:()=>jt,HYDRATION_SS58_PREFIX:()=>M,RUNTIME_DECIMALS:()=>T,SYSTEM_ASSET_DECIMALS:()=>Vt,SYSTEM_ASSET_ID:()=>C,TRADEABLE_DEFAULT:()=>q});var T=18,C=0,Vt=12,jt=2034,M=63,Ut="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",bt=1,q=15;var vt={};O(vt,{AssetNotFound:()=>j,PoolNotFound:()=>U,RouteNotFound:()=>N});var j=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},U=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},N=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var G=class extends F{constructor(t){super(t)}async getBalance(t,e){let i=await this.api.query.AssetRegistry.Assets.getValue(e);if(!i)throw new j(e);return i.asset_type.type==="Erc20"?this.getErc20Balance(t,e):e===0?this.getSystemBalance(t):this.getTokenBalance(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:{free:s,frozen:i}}=await e.getValue(t);return s-i}async getTokenBalance(t,e){let s=this.api.query.Tokens.Accounts,{free:i,frozen:n}=await s.getValue(t,e);return i-n}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),s=this.subscribeTokensBalance(t),i=this.subscribeErc20Balance(t);return Kt([e,s,i]).pipe(Qt(250),z(n=>n.flat()))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe(z(s=>{let{free:i,frozen:n}=s.data;return{id:0,amount:i-n}}))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe(z(i=>{let{free:n,frozen:a}=i;return{id:e,amount:n-a}}))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe(At((s,i)=>!i.deltas),z(({deltas:s})=>{let i=[];return s?.deleted.forEach(n=>{let[a,o]=n.args;i.push({id:o,amount:0n})}),s?.upserted.forEach(n=>{let[a,o]=n.args,{free:r,frozen:l}=n.value;i.push({id:o,amount:r-l})}),i}))}subscribeErc20Balance(t,e){let s=new zt,i=s.pipe(Zt(1)),n=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:c}=l;return c.type==="Erc20"}).map(({keyArgs:l})=>{let[c]=l;return c}),a=async()=>{let r=e||await n(),l=async()=>{let m=(await Promise.all(r.map(async p=>{let b=await this.getTokenBalanceData(t,p);return[p,b]}))).map(([p,b])=>({id:p,amount:b}));s.next(m)};await l();let c=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>c.unsubscribe()},o;return a().then(r=>o=r),i.pipe(Jt(()=>o?.()),$t(),z(([r,l],c)=>{if(c===0)return l;let g=r.reduce((p,b)=>(p.set(b.id,b.amount),p),new Map);return l.filter(p=>p.amount!==g.get(p.id))}),At((r,l)=>l.length===0))}async getTokenBalanceData(t,e){let{free:s,frozen:i}=await this.api.apis.CurrenciesApi.account(e,t);return s-i}};var Ct={};O(Ct,{PoolContextProvider:()=>ct,PoolError:()=>H,PoolFactory:()=>Y,PoolType:()=>v,lbp:()=>yt,omni:()=>ft,stable:()=>St,xyk:()=>It});var yt={};O(yt,{LbpMath:()=>_,LbpPool:()=>Q,LbpPoolClient:()=>J});import{calculate_in_given_out as te,calculate_out_given_in as ee,calculate_linear_weights as se,calculate_pool_trade_fee as ie,get_spot_price as ne}from"@galacticcouncil/math-lbp";var _=class{static getSpotPrice(t,e,s,i,n){return ne(t,e,s,i,n)}static calculateInGivenOut(t,e,s,i,n){return te(t,e,s,i,n)}static calculateOutGivenIn(t,e,s,i,n){return ee(t,e,s,i,n)}static calculateLinearWeights(t,e,s,i,n){return se(t,e,s,i,n)}static calculatePoolTradeFee(t,e,s){return ie(t,e,s)}};var v=(n=>(n.Aave="Aave",n.LBP="LBP",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="XYK",n))(v||{}),H=(n=>(n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n.UnknownError="UnknownError",n))(H||{});var P={};O(P,{toBigInt:()=>ae,toDecimal:()=>oe});import W from"big.js";W.NE=-18;function oe(u,t,e=6,s){let i=W(u.toString()),n=W(10).pow(t);return i.div(n).round(e,s).toString()}function ae(u,t){let e=W(10).pow(t),i=W(u).mul(e).toFixed(0,W.roundDown);return BigInt(i)}var Bt={};O(Bt,{convertFromH160:()=>le,convertToH160:()=>ce,isEvmAccount:()=>ue});import{AccountId as Pt}from"polkadot-api";import{toHex as re}from"@polkadot-api/utils";import{Buffer as D}from"buffer";var ht="ETH\0";function le(u,t=63){let e=D.from(u.slice(2),"hex"),s=D.from(ht),i=Uint8Array.from(D.concat([s,e,D.alloc(8)])),n=re(i);return Pt(t).dec(n)}function ce(u){let t=Pt().enc(u),e=D.from(ht),s=t.slice(e.length,-8);return"0x"+D.from(s).toString("hex")}function ue(u){if(!u)return!1;try{let t=Pt().enc(u),e=D.from(ht);return D.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}var d={};O(d,{fromPermill:()=>ge,toDecimals:()=>pe,toPct:()=>me});var Ft=1e3;function me(u){let[t,e]=u;return t/e*100}function pe(u){let[t,e]=u;return t/e}function ge(u){return[u/Ft,Ft]}var K={};O(K,{findNestedKey:()=>de,findNestedObj:()=>be,jsonFormatter:()=>Pe});var de=(u,t)=>{let e=[];return JSON.stringify(u,(s,i)=>(i&&i[t]&&e.push(i),i)),e[0]},be=(u,t,e)=>{let s;return JSON.stringify(u,(i,n)=>(n&&n[t]===e&&(s=n),n)),s},Pe=(u,t)=>typeof t=="bigint"?t.toString():t;var S={};O(S,{calculateBuyFee:()=>Se,calculateDiffToAvg:()=>he,calculateDiffToRef:()=>ye,calculateSellFee:()=>fe,getFraction:()=>Ie});import k from"big.js";function he(u,t){let e=k(u.toString()),s=k(t.toString());return e.minus(s).abs().div(e.plus(s).div(2)).mul(100).round(2).toNumber()}function ye(u,t){let e=k(u.toString()),s=k(t.toString());return e.minus(s).div(s).mul(100).round(2).toNumber()}function fe(u,t){let e=k(u.toString()),s=k(t.toString());return k(1).minus(s.div(e)).mul(100).round(2).toNumber()}function Se(u,t){let e=k(u.toString());return k(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function Ie(u,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let s=Math.pow(10,e),i=BigInt(t*s);return u*i/BigInt(100*s)}var _t={};O(_t,{convertToId:()=>xe});import{Buffer as Oe}from"buffer";function xe(u){let e=Oe.from(u.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var Q=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,s,i,n,a,o){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=i,this.minTradingLimit=n,this.fee=a,this.repayFeeApply=o}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),i=s.get(t),n=s.get(e);if(i==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:i.balance,balanceOut:n.balance,decimalsIn:i.decimals,decimalsOut:n.decimals,weightIn:i.weight,weightOut:n.weight}}validateAndBuy(t,e,s){let i=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let a=t.balanceOut/this.maxOutRatio;if(e>a&&n.push("MaxOutRatioExceeded"),i===t.assetOut){let o=this.calculateTradeFee(e,s),r=d.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),l=e+o,c=this.calculateInGivenOut(t,l),g=t.balanceIn/this.maxInRatio;return c>g&&n.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:r,errors:n}}else{let o=this.calculateInGivenOut(t,e),r=t.balanceIn/this.maxInRatio;return o>r&&n.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:e,feePct:0,errors:n}}}validateAndSell(t,e,s){let i=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let a=t.balanceIn/this.maxInRatio;if(e>a&&n.push("MaxInRatioExceeded"),i===t.assetIn){let o=this.calculateOutGivenIn(t,e),r=t.balanceOut/this.maxOutRatio;return o>r&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:o,amountOut:o,feePct:0,errors:n}}else{let o=this.calculateOutGivenIn(t,e),r=this.calculateTradeFee(o,s),l=d.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o-r,g=t.balanceOut/this.maxOutRatio;return c>g&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:o,amountOut:c,feePct:l,errors:n}}}calculateInGivenOut(t,e){let s=_.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(s);return i<0n?0n:i}calculateOutGivenIn(t,e){let s=_.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(s);return i<0n?0n:i}spotPriceInGivenOut(t){let e=_.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=_.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let s=_.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(s)}};import{CompatibilityLevel as Fe}from"polkadot-api";import{map as _e,of as Lt,switchMap as Re}from"rxjs";import{memoize1 as we}from"@thi.ng/memoize";import{combineLatest as Rt,combineLatestAll as ve,debounceTime as Ae,firstValueFrom as Te,from as kt,map as Et,mergeAll as Be,switchMap as Dt}from"rxjs";var R=class extends G{override=[];mem=0;memPools=we(t=>(console.log(this.getPoolType(),"mem pools",t,"\u2705"),this.loadPools()));constructor(t){super(t)}async withOverride(t){this.override=t||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let t=kt(this.getPoolsMem()).pipe(Dt(e=>this.subscribe(e)),ve());return Te(t)}getSubscriber(){return kt(this.getPoolsMem()).pipe(Dt(t=>this.subscribe(t)),Be())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>Rt([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe(Ae(250),Et(([s,i])=>this.updatePool(s,i))))}subscribePoolBalance(t){let e=[this.subscribeTokensBalance(t.address)];if(this.hasSystemAsset(t)){let s=this.subscribeSystemBalance(t.address);e.push(s)}if(this.hasErc20Asset(t)){let s=t.tokens.filter(n=>n.type==="Erc20").map(n=>n.id),i=this.subscribeErc20Balance(t.address,s);e.push(i)}return Rt(e).pipe(Et(s=>s.map(i=>Array.isArray(i)?i:[i]).flat()))}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(({id:e,decimals:s,balance:i})=>{let n=this.override.find(o=>o.id===e),a=!!s||!!n?.decimals;return i>0n&&a})}updatePool=(t,e)=>{let s=t.tokens.map(i=>{let n=e.find(o=>o.id===i.id),a=this.override.find(o=>o.id===i.id);return n?{...i,balance:n.amount,decimals:i.decimals||a?.decimals}:{...i,decimals:i.decimals||a?.decimals}});return{...t,tokens:s}}};var J=class extends R{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[t,e,s]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),i=e?.relay_parent_number||0,n=t.filter(({value:a})=>e&&this.isActivePool(a,i)).map(async({keyArgs:a,value:o})=>{let[r]=a,l=r.toString(),c=await this.getPoolDelta(l,o,i);return{address:l,type:"LBP",fee:o.fee,...c,...s}});return Promise.all(n)}async getPoolDelta(t,e,s){let{start:i,end:n,assets:a,initial_weight:o,final_weight:r,repay_target:l,fee_collector:c}=e,g=_.calculateLinearWeights(i?i.toString():"0",n?n.toString():"0",o.toString(),r.toString(),s.toString()),[m,p]=a,b=BigInt(g),y=this.MAX_FINAL_WEIGHT-BigInt(b),[f,A,x,w,B]=await Promise.all([this.isRepayFeeApplied(m,l,c.toString()),this.getBalance(t,m),this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(t,p),this.api.query.AssetRegistry.Assets.getValue(p)]);return{repayFeeApply:f,tokens:[{id:m,decimals:x?.decimals,existentialDeposit:x?.existential_deposit,balance:A,weight:b,type:x?.asset_type.type},{id:p,decimals:B?.decimals,existentialDeposit:B?.existential_deposit,balance:w,weight:y,type:B?.asset_type.type}]}}isActivePool(t,e){let{start:s,end:i}=t;return s&&i?e>=s&&e<i:!1}async isRepayFeeApplied(t,e,s){if(e===0n)return!1;try{return await this.getBalance(s,t)<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[t,e,s]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:s}}async getPoolFees(t){return{repayFee:await this.getRepayFee(),exchangeFee:t.fee}}getPoolType(){return"LBP"}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Fe.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,s=this.poolsData.get(t.address);return s?e.watchValue("best").pipe(Re(i=>i?this.getPoolDelta(t.address,s,i.relay_parent_number):Lt(t)),_e(i=>Object.assign({},t,i))):Lt(t)}};var ft={};O(ft,{OmniMath:()=>h,OmniPool:()=>$,OmniPoolClient:()=>Z});import{calculate_in_given_out as ke,calculate_lrna_in_given_out as Ee,calculate_out_given_in as De,calculate_out_given_lrna_in as Le,calculate_pool_trade_fee as Me,calculate_spot_price as Ce,calculate_lrna_spot_price as qe,calculate_shares as Ne,calculate_liquidity_out as Ge,calculate_liquidity_lrna_out as He,verify_asset_cap as We,calculate_liquidity_hub_in as Xe,is_sell_allowed as Ye,is_buy_allowed as Ve,is_add_liquidity_allowed as je,is_remove_liquidity_allowed as Ue}from"@galacticcouncil/math-omnipool";import X from"big.js";var h=class{static calculateSpotPrice(t,e,s,i){return Ce(t,e,s,i)}static calculateLrnaSpotPrice(t,e){return qe(t,e)}static calculateInGivenOut(t,e,s,i,n,a,o,r,l){return ke(t,e,s,i,n,a,o,r,l)}static calculateLrnaInGivenOut(t,e,s,i,n){return Ee(t,e,s,i,n)}static calculateOutGivenIn(t,e,s,i,n,a,o,r,l){return De(t,e,s,i,n,a,o,r,l)}static calculateOutGivenLrnaIn(t,e,s,i,n){return Le(t,e,s,i,n)}static calculatePoolTradeFee(t,e,s){return Me(t,e,s)}static calculateShares(t,e,s,i){return Ne(t,e,s,i)}static calculateLiquidityOut(t,e,s,i,n,a,o,r){return Ge(t,e,s,i,n,a,o,r)}static calculateLiquidityLRNAOut(t,e,s,i,n,a,o,r){return He(t,e,s,i,n,a,o,r)}static calculateCapDifference(t,e,s,i){let n=X(e),a=X(t),o=X(i),r=X(s),l=X(10).pow(18),c=r.div(l);if(n.div(o).lt(c)){let m=c.times(o).minus(n).times(a),p=n.times(X(1).minus(c));return m.div(p).toFixed(0)}else return"0"}static verifyAssetCap(t,e,s,i){return We(t,e,s,i)}static calculateLimitHubIn(t,e,s,i){return Xe(t,e,s,i)}static isSellAllowed(t){return Ye(t)}static isBuyAllowed(t){return Ve(t)}static isAddLiquidityAllowed(t){return je(t)}static isRemoveLiquidityAllowed(t){return Ue(t)}};var $=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,s,i,n,a){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=i,this.minTradingLimit=n,this.hubAssetId=a}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),i=s.get(t),n=s.get(e);if(i==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:i.hubReserves,hubReservesOut:n.hubReserves,sharesIn:i.shares,sharesOut:n.shares,decimalsIn:i.decimals,decimalsOut:n.decimals,balanceIn:i.balance,balanceOut:n.balance,tradeableIn:i.tradeable,tradeableOut:n.tradeable,assetInEd:i.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,s){let i=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,s),a=i===0n?0:S.calculateDiffToRef(n,i),o=[],r=h.isSellAllowed(t.tradeableIn),l=h.isBuyAllowed(t.tradeableOut);(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&o.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&o.push("MaxOutRatioExceeded");let g=t.balanceIn/this.maxInRatio;return n>g&&o.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:i,amountOut:e,feePct:a,errors:o}}validateAndSell(t,e,s){let i=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,s),a=S.calculateDiffToRef(i,n),o=[],r=h.isSellAllowed(t.tradeableIn),l=h.isBuyAllowed(t.tradeableOut);(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&o.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&o.push("MaxInRatioExceeded");let g=t.balanceOut/this.maxOutRatio;return n>g&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:n,feePct:a,errors:o}}calculateInGivenOut(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,s);let i=h.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?d.toDecimals(s.assetFee).toString():"0",s?d.toDecimals(s.protocolFee).toString():"0"),n=BigInt(i);return n<0n?0n:n}calculateLrnaInGivenOut(t,e,s){let i=h.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?d.toDecimals(s.assetFee).toString():"0"),n=BigInt(i);return n<0n?0n:n}calculateOutGivenIn(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,s);let i=h.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?d.toDecimals(s.assetFee).toString():"0",s?d.toDecimals(s.protocolFee).toString():"0"),n=BigInt(i);return n<0n?0n:n}calculateOutGivenLrnaIn(t,e,s){let i=h.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?d.toDecimals(s.assetFee).toString():"0"),n=BigInt(i);return n<0n?0n:n}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=h.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString()),s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}spotPriceLrnaInGivenOut(t){let e=h.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString()),s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=h.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString()),s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}spotPriceOutGivenLrnaIn(t){let e=h.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}};import{AccountId as ze,CompatibilityLevel as Ke}from"polkadot-api";import{toHex as Qe}from"@polkadot-api/utils";import{distinctUntilChanged as Je,map as Mt}from"rxjs";var Z=class extends R{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[s,i,n,a,o]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.getBalance(e,t),this.getPoolLimits()]),r=s.map(async({keyArgs:c,value:g})=>{let[m]=c,{hub_reserve:p,shares:b,tradable:y,cap:f,protocol_shares:A}=g,[x,w]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,m)]);return{id:m,decimals:x?.decimals,existentialDeposit:x?.existential_deposit,balance:w,cap:f,hubReserves:p,protocolShares:A,shares:b,tradeable:y,type:x?.asset_type.type}}),l=await Promise.all(r);return l.push({id:t,decimals:n?.decimals,existentialDeposit:n?.existential_deposit,balance:a,tradeable:i,type:n?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...o}]}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),s=Qe(e);return ze(63).dec(s)}async getPoolLimits(){let[t,e,s]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:s}}async getPoolFees(t,e){let[s,i,n]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),a=s.min_fee+i.min_fee,o=s.max_fee+i.max_fee;if(n){let{asset_fee:r,protocol_fee:l}=n;return{assetFee:d.fromPermill(r),protocolFee:d.fromPermill(l),min:d.fromPermill(a),max:d.fromPermill(o)}}else return{assetFee:d.fromPermill(s.min_fee),protocolFee:d.fromPermill(i.min_fee),min:d.fromPermill(a),max:d.fromPermill(o)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Ke.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(Je((s,i)=>!i.deltas),Mt(({entries:s})=>s.map(i=>{let[n]=i.args,{hub_reserve:a,shares:o,tradable:r,cap:l,protocol_shares:c}=i.value,g=t.tokens.findIndex(p=>p.id===n);return{...t.tokens[g],cap:l,hubReserves:a,protocolShares:c,shares:o,tradeable:r}})),Mt(s=>{let i=t.tokens.find(n=>n.id===1);return{...t,tokens:[...s,i]}}))}};var St={};O(St,{StableMath:()=>I,StableSwap:()=>tt,StableSwapClient:()=>et});import{calculate_in_given_out as $e,calculate_out_given_in as Ze,calculate_amplification as ts,calculate_add_one_asset as es,calculate_liquidity_out_one_asset as ss,calculate_pool_trade_fee as is,calculate_shares as ns,calculate_shares_for_amount as os,calculate_spot_price_with_fee as as,pool_account_name as rs,recalculate_peg as ls}from"@galacticcouncil/math-stableswap";var I=class{static getPoolAddress(t){return rs(t)}static defaultPegs(t){let e=[];for(let s=0;s<t;s++)e.push(["1","1"]);return e}static calculateAmplification(t,e,s,i,n){return ts(t,e,s,i,n)}static calculateInGivenOut(t,e,s,i,n,a,o){return $e(t,e,s,i,n,a,o)}static calculateAddOneAsset(t,e,s,i,n,a,o){return es(t,e,s,i,n,a,o)}static calculateSharesForAmount(t,e,s,i,n,a,o){return os(t,e,s,i,n,a,o)}static calculateOutGivenIn(t,e,s,i,n,a,o){return Ze(t,e,s,i,n,a,o)}static calculateLiquidityOutOneAsset(t,e,s,i,n,a,o){return ss(t,e,s,i,n,a,o)}static calculateShares(t,e,s,i,n,a){return ns(t,e,s,i,n,a)}static calculateSpotPriceWithFee(t,e,s,i,n,a,o,r){return as(t,e,s,i,n,a,o,r)}static calculatePoolTradeFee(t,e,s){return is(t,e,s)}static recalculatePegs(t,e,s,i,n){return ls(t,e,s,i,n)}};var tt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.id,t.fee,t.totalIssuance)}constructor(t,e,s,i,n,a,o,r,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=i,this.minTradingLimit=n,this.amplification=a,this.id=o,this.fee=r,this.totalIssuance=l}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),i=s.get(t),n=s.get(e);if(i==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:i.balance,balanceOut:n.balance,decimalsIn:i.decimals,decimalsOut:n.decimals,tradeableIn:this.id===t?15:i.tradeable,tradeableOut:this.id===e?15:n.tradeable,assetInEd:i.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,s){let i=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,s),a=d.toPct(s.fee),o=[],r=h.isSellAllowed(t.tradeableIn),l=h.isBuyAllowed(t.tradeableOut);return(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&o.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:i,amountOut:e,feePct:a,errors:o}}validateAndSell(t,e,s){let i=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,s),a=d.toPct(s.fee),o=[],r=h.isSellAllowed(t.tradeableIn),l=h.isBuyAllowed(t.tradeableOut);return(!r||!l)&&o.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&o.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:i,amountOut:n,feePct:a,errors:o}}calculateIn(t,e,s){let i=I.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateAddOneAsset(t,e,s){let i=I.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateSharesForAmount(t,e,s){let i=I.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateInGivenOut(t,e,s){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,s):t.assetIn==this.id?this.calculateSharesForAmount(t,e,s):this.calculateIn(t,e,s)}spotPriceInGivenOut(t){let e=I.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetOut==this.id)return BigInt(e);if(t.assetIn==this.id){let i=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(i)}let s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}calculateOut(t,e,s){let i=I.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateWithdrawOneAsset(t,e,s){let i=I.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateShares(t,e,s){let i=I.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),s?d.toDecimals(s.fee).toString():"0",this.getPegs()),n=BigInt(i);return n<0n?0n:n}calculateOutGivenIn(t,e,s){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,s):t.assetOut==this.id?this.calculateShares(t,e,s):this.calculateOut(t,e,s)}spotPriceOutGivenIn(t){let e=I.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetIn==this.id)return BigInt(e);if(t.assetOut==this.id){let i=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(i)}let s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}calculateTradeFee(t,e){let[s,i]=e.fee,n=I.calculatePoolTradeFee(t.toString(),s,i);return BigInt(n)}getPegs(){let t=I.defaultPegs(this.tokens.length-1);return JSON.stringify(t)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:s,decimals:i})=>({asset_id:e,amount:s,decimals:i}));return JSON.stringify(t,K.jsonFormatter)}getAssets(t,e){let s={asset_id:Number(t),amount:e.toString()};return JSON.stringify([s],K.jsonFormatter)}};import{AccountId as cs,CompatibilityLevel as us}from"polkadot-api";import{toHex as ms}from"@polkadot-api/utils";import{blake2b as ps}from"@noble/hashes/blake2b";import{map as gs,of as ds,switchMap as bs}from"rxjs";var Ps=340282366920938463463374607431768211455n,et=class extends R{poolsData=new Map([]);async loadPools(){let[t,e,s]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),i=t.map(async({keyArgs:n,value:a})=>{let[o]=n,r=this.getPoolAddress(o),[l,c]=await Promise.all([this.getPoolDelta(o,a,e),this.getPoolTokens(o,a)]);return this.poolsData.set(r,a),{address:r,id:o,type:"Stableswap",fee:d.fromPermill(a.fee),tokens:c,...l,...s}});return Promise.all(i)}async getPoolDelta(t,e,s){let{initial_amplification:i,final_amplification:n,initial_block:a,final_block:o}=e,r=I.calculateAmplification(i.toString(),n.toString(),a.toString(),o.toString(),s.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(t);return{amplification:BigInt(r),totalIssuance:l}}async getPoolTokens(t,e){let s=this.getPoolAddress(t),i=e.assets.map(async o=>{let[r,l,c]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(s,o)]);return{id:o,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:c,tradeable:r,type:l?.asset_type.type}}),n=await Promise.all(i),a=await this.api.query.AssetRegistry.Assets.getValue(t);return n.push({id:t,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:Ps,tradeable:15,type:a?.asset_type.type}),n}getPoolAddress(t){let e=I.getPoolAddress(t),s=ps(e,{dkLen:32}),i=ms(s);return cs(63).dec(i)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(t){return{fee:t.fee}}getPoolType(){return"Stableswap"}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(us.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.System.Number,s=this.poolsData.get(t.address);return!s||!t.id?ds(t):e.watchValue("best").pipe(bs(i=>this.getPoolDelta(t.id,s,i)),gs(i=>Object.assign({},t,i)))}};var It={};O(It,{XykMath:()=>E,XykPool:()=>st,XykPoolClient:()=>it});import{calculate_in_given_out as hs,calculate_out_given_in as ys,calculate_pool_trade_fee as fs,get_spot_price as Ss,calculate_liquidity_in as Is,calculate_shares as Os,calculate_spot_price as xs,calculate_spot_price_with_fee as ws,calculate_liquidity_out_asset_a as vs,calculate_liquidity_out_asset_b as As}from"@galacticcouncil/math-xyk";var E=class{static getSpotPrice(t,e,s){return Ss(t,e,s)}static calculateInGivenOut(t,e,s){return hs(t,e,s)}static calculateOutGivenIn(t,e,s){return ys(t,e,s)}static calculatePoolTradeFee(t,e,s){return fs(t,e,s)}static calculateLiquidityIn(t,e,s){return Is(t,e,s)}static calculateSpotPrice(t,e){return xs(t,e)}static calculateSpotPriceWithFee(t,e,s,i){return ws(t,e,s,i)}static calculateShares(t,e,s){return Os(t,e,s)}static calculateLiquidityOutAssetA(t,e,s,i){return vs(t,e,s,i)}static calculateLiquidityOutAssetB(t,e,s,i){return As(t,e,s,i)}};var st=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,s,i,n){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=s,this.maxOutRatio=i,this.minTradingLimit=n}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(a=>[a.id,a])),i=s.get(t),n=s.get(e);if(i==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:i.decimals,decimalsOut:n.decimals,balanceIn:i.balance,balanceOut:n.balance,assetInEd:i.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,s){let i=this.calculateInGivenOut(t,e),n=this.calculateTradeFee(i,s),a=d.toPct(s.exchangeFee),o=i+n,r=[];(e<this.minTradingLimit||i<t.assetInEd)&&r.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&r.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return o>c&&r.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:i,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,s){let i=this.calculateOutGivenIn(t,e),n=this.calculateTradeFee(i,s),a=d.toPct(s.exchangeFee),o=i-n,r=[];(e<this.minTradingLimit||i<t.assetOutEd)&&r.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&r.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return o>c&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:o,feePct:a,errors:r}}calculateInGivenOut(t,e){let s=E.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(s);return i<0n?0n:i}calculateOutGivenIn(t,e){let s=E.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(s);return i<0n?0n:i}spotPriceInGivenOut(t){let e=E.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),s=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(s)}spotPriceOutGivenIn(t){let e=E.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),s=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(s)}calculateTradeFee(t,e){let s=E.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(s)}};import{CompatibilityLevel as Ts}from"polkadot-api";import{of as Bs}from"rxjs";var it=class extends R{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,s]=await Promise.all([t.getEntries(),this.getPoolLimits()]),i=e.map(async({keyArgs:n,value:a})=>{let[o]=n,[r,l]=a,[c,g,m,p]=await Promise.all([this.getBalance(o,r),this.api.query.AssetRegistry.Assets.getValue(r),this.getBalance(o,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:o,type:"XYK",tokens:[{id:r,decimals:g?.decimals,existentialDeposit:g?.existential_deposit,balance:c,type:g?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:m,type:p?.asset_type.type}],...s}});return Promise.all(i)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[t,e,s]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:s}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(Ts.BackwardsCompatible,e)}subscribePoolChange(t){return Bs(t)}};var Y=class{static get(t){switch(t.type){case"XYK":return st.fromPool(t);case"Omnipool":return $.fromPool(t);case"LBP":return Q.fromPool(t);case"Stableswap":return tt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{Subject as Fs,Subscription as rt,takeUntil as lt}from"rxjs";var ct=class extends F{lbpClient;omniClient;stableClient;xykClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=rt.EMPTY;omniSub=rt.EMPTY;stableSub=rt.EMPTY;xykSub=rt.EMPTY;isReady=!1;isDestroyed=new Fs;constructor(t){super(t),this.lbpClient=new J(t),this.omniClient=new Z(t),this.stableClient=new et(t),this.xykClient=new it(t),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient]}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.omniClient.getSubscriber().pipe(lt(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)}),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.stableClient.getSubscriber().pipe(lt(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)}),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.lbpClient.getSubscriber().pipe(lt(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)}),this.active.add("LBP"),this}withXyk(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.xykClient.getSubscriber().pipe(lt(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)}),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());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 s=this.clients.find(i=>i.getPoolType()===t.type);if(s)return s.getPoolFees(t,e);throw new U(t.type)}};var Nt={};O(Nt,{Router:()=>V,TradeRouter:()=>pt,TradeType:()=>mt,TradeUtils:()=>gt});var ut=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var _s=5,nt=class{isNotVisited(t,e){let s=!0;return e.forEach(i=>{(i[0]===t[0]||i[1]===t[1])&&(s=!1)}),s}findPaths(t,e,s){let i=[],n=new ut,a=[];for(a.push([e,""]),n.enqueue(a);n.size()>0;){let o=n.dequeue();if(o==null||o.length>_s)return i;let r=o[o.length-1];(s===null||r[0]===s)&&i.push(o),t.get(r[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let g=[...o];g.push(c),n.enqueue(g)}})}return i}buildAndPopulateGraph(t,e){let s=new Map;for(let i of t)s.set(parseInt(i),[]);for(let[i,n,a]of e)s.get(n)?.push([a,i]);return s}};function Ot(u){let t={};for(let e of u){let s=e.tokens.length;for(let i=0;i<s;i++){t[e.tokens[i].id]||(t[e.tokens[i].id]=[]);for(let n=0;n<s;n++){if(i==n)continue;let a=[e.address,e.tokens[i].id,e.tokens[n].id];t[e.tokens[i].id].push(a)}}}return t}var ot=class{getProposals(t,e,s){let i=Ot(s),n=Object.keys(i),a=n.map(c=>i[c]).flat(),o=new nt,r=o.buildAndPopulateGraph(n,a),l=o.findPaths(r,t,e);return this.parsePaths(l)}parsePaths(t){let e=[];for(let s of t){let i=[];for(let n=0;n<s.length;n++){let a=s[n],o=s[n+1];if(o==null)break;i.push(this.toEdge(a,o))}e.push(i)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var V=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(t,e){this.ctx=t,this.routeSuggester=new ot,this.routerOptions={...this.defaultRouterOptions,...e}}async getPools(){let t=await this.ctx.getPools(),e=this.routerOptions.useOnly;return e.length===0?t:t.filter(s=>e.includes(s.type))}async getRoutes(t,e){let s=await this.getPools();return this.validateInput(t,e,s),this.getPaths(t,e,s)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}validateInput(t,e,s){if(s.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let i=this.getAssets(s);if(!i.has(t))throw new Error(t+" is not supported asset");if(!i.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(s)}getAssets(t){let e=t.map(s=>s.tokens.map(i=>i.id)).flat().sort((s,i)=>s>i?1:-1);return new Set(e)}getPaths(t,e,s){let i=this.toPoolsMap(s);return this.routeSuggester.getProposals(t,e,s).filter(a=>this.validPath(a,i)).map(a=>this.toHops(a,i))}validPath(t,e){return t.length>0&&t.map(s=>this.validEdge(s,e)).reduce((s,i)=>s&&i)}validEdge([t,e,s],i){return i.get(t)?.validatePair(e,s)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Y.get(e)]))}toHops(t,e){return t.map(([s,i,n])=>{let a=e.get(s);return{poolAddress:s,poolId:a?.id,pool:a?.type,assetIn:i,assetOut:n}})}};var mt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(mt||{});var pt=class extends V{isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((s,i)=>{let n=s[s.length-1].amountOut,a=i[i.length-1].amountOut;return n>a?-1:1});return e.find(s=>s.every(i=>i.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(s=>s.tradeFeeRange).length>0){let s=t.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,a)=>n+a),i=t.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,a)=>n+a);return[s,i]}}getPoolFeeRange(t){let e=t.min?d.toPct(t.min):void 0,s=t.max?d.toPct(t.max):void 0;if(e&&s)return[e,s]}async getBestSell(t,e,s){return this.getSell(t,e,s)}async getSellSpot(t){let e=t[t.length-1];if(t.length===1)return e.spotPrice;let s=t.map(o=>o.assetOutDecimals).reduce((o,r)=>o+r),i=t.map(o=>o.spotPrice).reduce((o,r)=>o*r),n=s-e.assetOutDecimals,a=Math.pow(10,n);return i/BigInt(a)}async getSell(t,e,s,i){let n=await super.getPools(),a=super.validateInput(t,e,n),o=super.getPaths(t,e,n);if(o.length===0)throw new N(t,e);let r;if(i)r=await this.toSellSwaps(s,i,a);else{let L=await Promise.all(o.map(dt=>this.toSellSwaps(s,dt,a)));r=this.findBestSellRoute(L)}let l=r[0],c=r[r.length-1],g=this.isDirectTrade(r),m=await this.getSellSpot(r),p=c.amountOut,b=g?c.calculatedOut:this.calculateDelta0Y(l.amountIn,r,a),y=b-p,f=this.getRouteFeeRange(r),A=g?c.tradeFeePct:S.calculateSellFee(b,p),x=Math.pow(10,l.assetInDecimals),w=l.amountIn*m/BigInt(x),B=S.calculateDiffToRef(b,w);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:m,tradeFee:y,tradeFeePct:A,tradeFeeRange:f,priceImpactPct:B,swaps:r,toHuman(){return{type:"Sell",amountIn:P.toDecimal(l.amountIn,l.assetInDecimals),amountOut:P.toDecimal(c.amountOut,c.assetOutDecimals),spotPrice:P.toDecimal(m,c.assetOutDecimals),tradeFee:P.toDecimal(y,c.assetOutDecimals),tradeFeePct:A,tradeFeeRange:f,priceImpactPct:B,swaps:r.map(L=>L.toHuman())}}}}calculateDelta0Y(t,e,s){let i=[];for(let n=0;n<e.length;n++){let a=e[n],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;n>0?l=i[n-1]:l=t;let c=o.calculateOutGivenIn(r,l);i.push(c)}return i[i.length-1]}async toSellSwaps(t,e,s){let i=[];for(let n=0;n<e.length;n++){let a=e[n],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;n>0?l=i[n-1].amountOut:l=typeof t=="string"?P.toBigInt(t,r.decimalsIn):t;let c=await this.ctx.getPoolFees(o,r.assetOut),{amountOut:g,calculatedOut:m,feePct:p,errors:b}=o.validateAndSell(r,l,c),y=this.getPoolFeeRange(c),f=o.spotPriceOutGivenIn(r),A=Math.pow(10,r.decimalsIn),x=l*f/BigInt(A),w=S.calculateDiffToRef(m,x);i.push({...a,assetInDecimals:r.decimalsIn,assetOutDecimals:r.decimalsOut,amountIn:l,amountOut:g,calculatedOut:m,spotPrice:f,tradeFeePct:p,tradeFeeRange:y,priceImpactPct:w,errors:b,toHuman(){return{...a,amountIn:P.toDecimal(l,r.decimalsIn),amountOut:P.toDecimal(g,r.decimalsOut),calculatedOut:P.toDecimal(m,r.decimalsOut),spotPrice:P.toDecimal(f,r.decimalsOut),tradeFeePct:p,tradeFeeRange:y,priceImpactPct:w,errors:b}}})}return i}async getMostLiquidRoute(t,e){let s=await super.getPools(),i=super.validateInput(t,e,s),n=super.getPaths(t,e,s),r=s.filter(m=>m.tokens.some(p=>p.id===t&&p.id!==m.id)).map(m=>m.type==="Aave"?m.tokens:m.tokens.filter(p=>p.id===t)).map(m=>m.map(p=>p.balance).reduce((p,b)=>p+b)).sort((m,p)=>p<m?-1:1)[0],l=S.getFraction(r,.1),c=await Promise.all(n.map(m=>this.toSellSwaps(l,m,i)));return this.findBestSellRoute(c).map(m=>({poolAddress:m.poolAddress,poolId:m?.poolId,pool:m.pool,assetIn:m.assetIn,assetOut:m.assetOut}))}async getSpotPrice(t,e){let s=await super.getPools(),i=super.validateInput(t,e,s),n=await this.getMostLiquidRoute(t,e),a=await this.toSellSwaps("1",n,i),o=await this.getSellSpot(a),r=a[a.length-1].assetOutDecimals;return{amount:o,decimals:r}}findBestBuyRoute(t){let e=t.sort((s,i)=>{let n=s[0].amountIn,a=i[0].amountIn;return n>a?1:-1});return e.find(s=>s.every(i=>i.errors.length==0))||e[0]}async getBestBuy(t,e,s){return this.getBuy(t,e,s)}async getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let s=t.map(o=>o.assetInDecimals).reduce((o,r)=>o+r),i=t.map(o=>o.spotPrice).reduce((o,r)=>o*r),n=s-e.assetInDecimals,a=Math.pow(10,n);return i/BigInt(a)}async getBuy(t,e,s,i){let n=await super.getPools(),a=super.validateInput(t,e,n),o=super.getPaths(t,e,n);if(o.length===0)throw new N(t,e);let r;if(i)r=await this.toBuySwaps(s,i,a);else{let L=await Promise.all(o.map(dt=>this.toBuySwaps(s,dt,a)));r=this.findBestBuyRoute(L)}let l=r[r.length-1],c=r[0],g=this.isDirectTrade(r),m=await this.getBuySpot(r),p=c.amountIn,b=g?c.calculatedIn:this.calculateDelta0X(l.amountOut,r,a),y=p-b,f=this.getRouteFeeRange(r),A=g?c.tradeFeePct:S.calculateBuyFee(b,p),x=Math.pow(10,l.assetOutDecimals),w=l.amountOut*m/BigInt(x),B;return b===0n?B=-100:B=S.calculateDiffToRef(w,b),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:m,tradeFee:y,tradeFeePct:A,tradeFeeRange:f,priceImpactPct:B,swaps:r,toHuman(){return{type:"Buy",amountOut:P.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:P.toDecimal(c.amountIn,c.assetInDecimals),spotPrice:P.toDecimal(m,c.assetInDecimals),tradeFee:P.toDecimal(y,c.assetInDecimals),tradeFeePct:A,tradeFeeRange:f,priceImpactPct:B,swaps:r.map(L=>L.toHuman())}}}}calculateDelta0X(t,e,s){let i=[];for(let n=e.length-1;n>=0;n--){let a=e[n],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;n==e.length-1?l=t:l=i[0];let c=o.calculateInGivenOut(r,l);i.unshift(c)}return i[0]}async toBuySwaps(t,e,s){let i=[];for(let n=e.length-1;n>=0;n--){let a=e[n],o=s.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let r=o.parsePair(a.assetIn,a.assetOut),l;n==e.length-1?l=typeof t=="string"?P.toBigInt(t,r.decimalsOut):t:l=i[0].amountIn;let c=await this.ctx.getPoolFees(o,r.assetOut),{amountIn:g,calculatedIn:m,feePct:p,errors:b}=o.validateAndBuy(r,l,c),y=this.getPoolFeeRange(c),f=o.spotPriceInGivenOut(r),A=Math.pow(10,r.decimalsOut),x=l*f/BigInt(A),w;m===0n?w=-100:w=S.calculateDiffToRef(x,m),i.unshift({...a,assetInDecimals:r.decimalsIn,assetOutDecimals:r.decimalsOut,amountOut:l,amountIn:g,calculatedIn:m,spotPrice:f,tradeFeePct:p,tradeFeeRange:y,priceImpactPct:w,errors:b,toHuman(){return{...a,amountOut:P.toDecimal(l,r.decimalsOut),amountIn:P.toDecimal(g,r.decimalsIn),calculatedIn:P.toDecimal(m,r.decimalsIn),spotPrice:P.toDecimal(f,r.decimalsIn),tradeFeePct:p,tradeFeeRange:y,priceImpactPct:w,errors:b}}})}return i}};import{Enum as qt}from"polkadot-api";var gt=class extends F{constructor(t){super(t)}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}tradeCheck(t,e){if(e!==t.type)throw new Error("Not permitted")}async buildBuyTx(t,e=1){this.tradeCheck(t,"Buy");let{amountIn:s,amountOut:i,swaps:n}=t,a=n[0],o=n[n.length-1],r=S.getFraction(s,e),l=a.assetIn,c=o.assetOut,g=s+r;return this.isDirectOmnipoolTrade(n)?this.api.tx.Omnipool.buy({asset_in:l,asset_out:c,amount:i,max_sell_amount:g}).getEncodedData():this.api.tx.Router.buy({asset_in:l,asset_out:c,amount_out:i,max_amount_in:g,route:this.buildRoute(n)}).getEncodedData()}async buildSellTx(t,e=1){this.tradeCheck(t,"Sell");let{amountIn:s,amountOut:i,swaps:n}=t,a=n[0],o=n[n.length-1],r=S.getFraction(i,e),l=a.assetIn,c=o.assetOut,g=i-r;return this.isDirectOmnipoolTrade(n)?this.api.tx.Omnipool.sell({asset_in:l,asset_out:c,amount:s,min_buy_amount:g}).getEncodedData():this.api.tx.Router.sell({asset_in:l,asset_out:c,amount_in:s,min_amount_out:g,route:this.buildRoute(n)}).getEncodedData()}async buildSellAllTx(t,e=1){this.tradeCheck(t,"Sell");let{amountOut:s,swaps:i}=t,n=i[0],a=i[i.length-1],o=S.getFraction(s,e),r=n.assetIn,l=a.assetOut,c=s-o;return this.api.tx.Router.sell_all({asset_in:r,asset_out:l,min_amount_out:c,route:this.buildRoute(i)}).getEncodedData()}buildRoute(t){return t.map(({assetIn:e,assetOut:s,pool:i,poolId:n})=>i==="Stableswap"?{pool:qt("Stableswap",n),asset_in:e,asset_out:s}:{pool:qt(i),asset_in:e,asset_out:s})}};export{xt as api,P as big,Tt as client,wt as const,vt as error,Bt as evm,d as fmt,K as json,S as math,Ct as pool,Nt as sor,_t as xc};
1
+ var Mr=Object.defineProperty;var A=(p,t)=>{for(var e in t)Mr(p,e,{get:t[e],enumerable:!0})};import Dr from"buffer";typeof window<"u"&&(window.Buffer=Dr.Buffer);var wn={};A(wn,{Papi:()=>_,Watcher:()=>Bt,getSm:()=>ii,getWs:()=>ni});import{hydration as Jr,hydrationNext as Zr}from"@galacticcouncil/descriptors";import{log as Xr}from"@galacticcouncil/common";import{map as zr,shareReplay as Kr,tap as jr}from"rxjs";import{defer as Lr,from as qr,of as Pn,timer as Nr}from"rxjs";import{catchError as Hr,distinctUntilChanged as Gr,expand as Vr,map as Le,shareReplay as Ur,skip as Wr,switchMap as Yr,timeout as $r}from"rxjs/operators";function Sn(p,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let n=()=>Lr(()=>qr(p._request("system_health",[]))).pipe($r({first:e}),Le(()=>"online"),Hr(()=>Pn("offline")));return Pn({state:"offline",delayMs:0}).pipe(Vr(i=>Nr(i.delayMs).pipe(Yr(n),Le(a=>({state:a,delayMs:t})))),Wr(1),Le(i=>i.state),Gr(),Ur({bufferSize:1,refCount:!0}))}var{logger:Qr}=Xr,Bt=class p{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(zr(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Sn(t))}static getInstance(t){return this.instance||(this.instance=new p(t)),this.instance}watched(t,e){return e.pipe(jr({error:n=>Qr.error(t,n)}),Kr({bufferSize:1,refCount:!0}))}};var _=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(Jr),this.apiNext=this.client.getTypedApi(Zr),this.watcher=Bt.getInstance(this.client)}};import{getWsProvider as ti}from"polkadot-api/ws";import{withLogsRecorder as ei}from"polkadot-api/logs-provider";var ni=(p,t={})=>{let e=typeof p=="string"?p.split(","):p,n=ti(e,t);return ei(r=>console.log(r),n),n};import{getSmProvider as ri}from"polkadot-api/sm-provider";async function ii(p){let{start:t}=await import("polkadot-api/smoldot"),{chainSpec:e}=await import("polkadot-api/chains/polkadot"),n=t(),r=await n.addChain({chainSpec:e}),i=await n.addChain({chainSpec:p,potentialRelayChains:[r]});return ri(()=>i)}var xn={};A(xn,{AAVE_GAS_LIMIT:()=>He,AAVE_LENDING_POOL_ADDRESS:()=>de,AAVE_POOL_ABI:()=>qe,AAVE_POOL_DATA_PROVIDER:()=>me,AAVE_POOL_DATA_PROVIDER_ABI:()=>pe,AAVE_POOL_PROXY:()=>Ne,AAVE_ROUNDING_THRESHOLD:()=>el,AAVE_UINT_256_MAX:()=>ai,AaveClient:()=>_t,AaveUtils:()=>nt});var qe=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var pe=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Ne="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",me="0x112b087b60C1a166130d59266363C45F8aa99db0",de="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",He=1000000n,el=5,ai=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var _t=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:pe,address:me,args:[de],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:pe,address:me,args:[de,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:qe,address:Ne,args:[t],functionName:"getUserAccountData"})}};import R from"big.js";import{big as et,erc20 as si,h160 as oi}from"@galacticcouncil/common";var{ERC20:st}=si,{H160:Ge}=oi,li=1.01,ci=31536000n,vn=4,ge=-1,he=10n**27n,nt=class{client;constructor(t){this.client=new _t(t)}async getSummary(t){let e=Ge.fromAny(t),[n,r,i,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[s]=n,[o,l]=r,[c,u,d,m,h,b]=i,g=et.toDecimal(b,18),f=[];for(let y of o){let S=y.underlyingAsset.toLowerCase(),P=s.find(({underlyingAsset:De})=>De.toLowerCase()===S);if(!P)throw new Error("Missing pool reserve for "+S);let w=y.scaledATokenBalance,v=P.liquidityIndex,F=P.liquidityRate,k=P.availableLiquidity,$=P.priceInMarketReferenceCurrency,K=a+6,H=this.calculateLinearInterest(F,P.lastUpdateTimestamp,K),V=v*H/he,Ot=w*V/he,le=Number(l!==0&&l===P.eModeCategoryId?P.eModeLiquidationThreshold:P.reserveLiquidationThreshold)/1e4,ce=P.usageAsCollateralEnabled&&y.usageAsCollateralEnabledOnUser&&y.scaledATokenBalance>0n,ue=st.toAssetId(S);f.push({aTokenBalance:Ot,availableLiquidity:k,decimals:Number(P.decimals),isCollateral:ce,priceInRef:$,reserveId:ue,reserveAsset:S,reserveLiquidationThreshold:le})}return{healthFactor:Number(g),currentLiquidationThreshold:Number(et.toDecimal(m,vn)),totalCollateral:c,totalDebt:u,reserves:f}}async hasBorrowPositions(t){let e=Ge.fromAny(t),n=await this.client.getUserAccountData(e),[r,i]=n;return i>0n}async getHealthFactor(t){let e=Ge.fromAny(t),n=await this.client.getUserAccountData(e),[r,i,a,s,o,l]=n;return this.calculateHealthFactorFromBalances(i,r,s)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:r,totalDebt:i,reserves:a,currentLiquidationThreshold:s}=await this.getSummary(t);if(i===0n)return ge;let o=st.fromAssetId(e),l=a.find(S=>S.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:c,isCollateral:u,priceInRef:d,reserveLiquidationThreshold:m}=l,h=et.toBigInt(n,c),b=u?h*d/10n**BigInt(c):0n,g=r-b;if(g<=0n)return 0;let f=R(r.toString()).mul(s).minus(R(b.toString()).mul(m)).div(g.toString()),y=R(g.toString()).mul(f).div(i.toString()).toFixed(6,R.roundDown);return Number(y)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:r,totalDebt:i,reserves:a,currentLiquidationThreshold:s}=await this.getSummary(t);if(i===0n)return ge;let o=st.fromAssetId(e),l=a.find(y=>y.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:c,priceInRef:u,reserveLiquidationThreshold:d}=l,h=et.toBigInt(n,c)*u/10n**BigInt(c),b=r+h;if(b<=0n)return 0;let g=R(r.toString()).mul(s).plus(R(h.toString()).mul(d)).div(b.toString()),f=R(b.toString()).mul(g).div(i.toString()).toFixed(6,R.roundDown);return Number(f)}async getHealthFactorAfterSwap(t,e,n,r,i){let{totalDebt:a,reserves:s,healthFactor:o}=await this.getSummary(t);if(a===0n)return ge;let l=st.fromAssetId(n),c=st.fromAssetId(i),u=s.find(v=>v.reserveAsset===l),d=s.find(v=>v.reserveAsset===c);if(!u)throw new Error(`Missing reserve ctx for ${l}`);if(!d)throw new Error(`Missing reserve ctx for ${d}`);let m=et.toBigInt(e,u.decimals),h=et.toBigInt(r,d.decimals),b=m*u.priceInRef/10n**BigInt(u.decimals),g=h*d.priceInRef/10n**BigInt(d.decimals),f=u.isCollateral?R(b.toString()).mul(u.reserveLiquidationThreshold):R(0),P=(d.isCollateral?R(g.toString()).mul(d.reserveLiquidationThreshold):R(0)).minus(f).div(a.toString()),w=R(o).plus(P).toFixed(6,R.roundDown);return Number(w)}async getMaxWithdraw(t,e){let{totalDebt:n,reserves:r,healthFactor:i}=await this.getSummary(t),a=st.fromAssetId(e),s=r.find(o=>o.reserveAsset===a);if(!s)throw new Error("Missing reserve ctx for "+a);return this.calculateWithdrawMax(s,n,i)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:n,healthFactor:r}=await this.getSummary(t),i={};for(let a of n){let s=this.calculateWithdrawMax(a,e,r);a.reserveId&&(i[a.reserveId]=s)}return i}calculateWithdrawMax(t,e,n){let{aTokenBalance:r,availableLiquidity:i,decimals:a,priceInRef:s,reserveLiquidationThreshold:o,isCollateral:l}=t,c=r;if(l&&e>0n){let d=n-li;if(d>0){let m=R(d).mul(e.toString()).div(o).toFixed(0,R.roundDown),h=R(m).div(s.toString()).mul(10**a).toFixed(0,R.roundDown);c=r<BigInt(h)?r:BigInt(h)}else c=0n}return{amount:c<i?c:i,decimals:a}}calculateLinearInterest(t,e,n){let r=n-e;if(r<=0)return he;let i=t*BigInt(r)/ci;return he+i}calculateHealthFactorFromBalances(t,e,n){if(t===0n)return ge;let r=e*n/t,i=et.toDecimal(r,vn);return Number(i)}};var Fn={};A(Fn,{AssetClient:()=>ot,BalanceClient:()=>X,ChainParams:()=>mt});import{Binary as be}from"polkadot-api";var ot=class extends _{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:n,value:r})=>{let[i]=n;return[i,r]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:r})=>{let[i]=n;return[i,r]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:r}=n;return this.SUPPORTED_TYPES.includes(r.type)}).map(({keyArgs:n,value:r})=>{let[i]=n;return[i,r]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:r})=>{let[i]=n;return[i,r]}))}async mapToken(t,e,n,r){let{name:i,asset_type:a,is_sufficient:s,existential_deposit:o}=e,{symbol:l,decimals:c}=n.get(t)??{};return{id:t,name:i?be.toText(i):void 0,symbol:l,decimals:c,icon:l,type:a.type,isSufficient:s,location:r,existentialDeposit:o}}async mapBond(t,e,n,r){let[i,a]=r,{asset_type:s,is_sufficient:o,existential_deposit:l}=e,{symbol:c,decimals:u}=await this.mapToken(i,e,n),d=Number(a),m=new Intl.DateTimeFormat("en-GB"),h=[c,"Bond",m.format(d)].join(" ");return{id:t,name:h,symbol:c+"b",decimals:u,icon:c,type:s.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:i,maturity:d}}async mapShares(t,e,n,r){let{assets:i}=r,{name:a,symbol:s,asset_type:o,is_sufficient:l,existential_deposit:c}=e,u=await Promise.all(i.map(async h=>{let{symbol:b}=await this.mapToken(h,e,n);return[h,b]})),d=Object.fromEntries(u),m=Object.values(d);return{id:t,name:m.join(", "),symbol:s&&be.toText(s)||a&&be.toText(a),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:d}}async mapExternal(t,e,n,r){let i=await this.mapToken(t,e,new Map,r),a=n?.find(s=>s.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:i}parseMetadata(t){return new Map(Array.from(t,([e,n])=>[e,{symbol:n.symbol?be.toText(n.symbol):void 0,decimals:n.decimals}]))}async getSupported(t,e){let[n,r,i,a]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),s=this.parseMetadata(n),o=[];for(let[l,c]of Array.from(n)){let u=r.get(l),{asset_type:d}=c,m;switch(d.type){case"Bond":let h=a.get(l);m=await this.mapBond(l,c,s,h);break;case"StableSwap":let b=i.get(l);m=await this.mapShares(l,c,s,b);break;case"External":m=await this.mapExternal(l,c,e,u);break;default:m=await this.mapToken(l,c,s,u)}o.push(m)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};import{log as mi}from"@galacticcouncil/common";import{combineLatest as di,concat as gi,defer as Rt,from as In}from"rxjs";import{bufferCount as An,distinctUntilChanged as On,debounceTime as hi,map as ut,retry as bi,startWith as Bn,switchMap as _n,tap as Ct,take as yi,skip as fi,connect as Pi}from"rxjs/operators";var Tn={};A(Tn,{HUB_ASSET_ID:()=>Ft,HYDRATION_OMNIPOOL_ADDRESS:()=>pi,HYDRATION_PARACHAIN_ID:()=>ui,PERBILL_DENOMINATOR:()=>Ve,PERMILL_DENOMINATOR:()=>lt,SYSTEM_ASSET_DECIMALS:()=>ye,SYSTEM_ASSET_ID:()=>O,TRADEABLE_DEFAULT:()=>ct});var lt=1e6,Ve=1e9,O=0,ye=12,ui=2034,pi="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Ft=1,ct=15;var{logger:pt}=mi,X=class extends _{erc20Ids=null;constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:n}=await e.getValue(t,{at:"best"});return this.getBreakdown(n)}async getTokenBalance(t,e){let r=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(r)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return Rt(()=>{let e=this.watchSystemBalance(t),n=this.watchTokensBalance(t),r=this.watchErc20Balance(t);return di([e,n,r]).pipe(Pi(i=>gi(i.pipe(yi(1)),i.pipe(fi(1),hi(250)))))}).pipe(ut(e=>e.flat()),Bn([]),An(2,1),ut(([e,n],r)=>r===0?n:this.getDeltas(e,n))).pipe(Ct({subscribe:()=>pt.debug("balance: subscribe",t),error:e=>pt.error("balance",e)}),bi({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return Rt(()=>e.watchValue(t,{at:"best"})).pipe(ut(({value:n})=>({id:0,balance:this.getBreakdown(n.data)})),Ct({error:n=>pt.error("balance(system)",n)}))}watchTokenBalance(t,e){let n=this.api.query.Tokens.Accounts;return Rt(()=>n.watchValue(t,e,{at:"best"})).pipe(ut(({value:r})=>({id:e,balance:this.getBreakdown(r)})),Ct({error:r=>pt.error("balance(token)",r)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return Rt(()=>e.watchEntries(t,{at:"best"})).pipe(On((n,r)=>!r.deltas),ut(({deltas:n})=>{let r=[];return n?.deleted.forEach(i=>{let[a,s]=i.args;r.push({id:s,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),n?.upserted.forEach(i=>{let[a,s]=i.args;r.push({id:s,balance:this.getBreakdown(i.value)})}),r}),Ct({error:n=>pt.error("balance(tokens)",n)}))}watchErc20Balance(t,e){let n=async()=>{if(this.erc20Ids)return this.erc20Ids;let i=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=i.filter(({value:a})=>a.asset_type.type==="Erc20").map(({keyArgs:a})=>{let[s]=a;return s}),this.erc20Ids},r=async i=>(await Promise.all(i.map(async s=>[s,await this.getBalanceData(t,s)]))).map(([s,o])=>({id:s,balance:o}));return Rt(()=>In(e?Promise.resolve(e):n()).pipe(_n(i=>this.watcher.bestBlock$.pipe(_n(()=>In(r(i))))),Bn([]),An(2,1),ut(([i,a],s)=>s===0?a.filter(o=>o.balance.total>0n):this.getDeltas(i,a)),On((i,a)=>a.length===0),Ct({error:i=>pt.error("balance(erc20)",i)})))}async getBalanceData(t,e){let n=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.getBreakdown(n)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,n=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:n,transferable:e}}getDeltas(t,e){let n=(i,a)=>i!==void 0&&a!==void 0&&i.transferable===a.transferable&&i.total===a.total,r=t.reduce((i,a)=>(i.set(a.id,a.balance),i),new Map);return e.filter(i=>!n(i.balance,r.get(i.id)))}};var mt=class extends _{_minOrderBudget;_blockTime;constructor(t){super(t)}async getBlockTime(){if(this._blockTime===void 0){let t=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(t)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var Rn={};A(Rn,{AssetNotFound:()=>Ue,PoolNotFound:()=>Et,RouteNotFound:()=>kt});var Ue=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},Et=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},kt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Mn={};A(Mn,{EvmClient:()=>Dt,EvmRpcAdapter:()=>Mt,createChain:()=>We});import{Binary as Cn}from"polkadot-api";import{hydration as Si}from"@galacticcouncil/descriptors";import{encodeFunctionData as wi,decodeFunctionResult as vi}from"viem";var xi=10000000n,Mt=class{api;constructor(t){this.api=t.getTypedApi(Si)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,n=e.timestamp/1000n,[r]=e.number;return{timestamp:n,number:r}}readContract=(async t=>{let{abi:e,address:n,functionName:r,args:i}=t,a=wi({abi:e,functionName:r,args:i}),s=await this.api.apis.EthereumRuntimeRPCApi.call("0x0000000000000000000000000000000000000000",n,Cn.fromHex(a),[0n,0n,0n,0n],[xi,0n,0n,0n],void 0,void 0,void 0,!1,[],[]);if(!s.success)throw console.error(r,s.value.type),new Error("Contract read failure");let{exit_reason:o,value:l,used_gas:c}=s.value;if(console.log(c),o.type==="Succeed")return vi({abi:e,functionName:r,data:Cn.toHex(l)});throw console.log(r,o.type,o.value.type),new Error("Contract read error")})};import{defineChain as Ti}from"viem";var Ii=["https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],We=()=>Ti({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:Ii}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});import{createPublicClient as En,createWalletClient as Ai,custom as kn,http as Oi}from"viem";var Dt=class{client;chain;constructor(t){this.client=t,this.chain=We()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return En({chain:this.chain,transport:Oi()})}getWsProvider(){return En({transport:kn({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return Ai({account:t,chain:this.chain,transport:kn(window.ethereum)})}getRPCAdapter(){return new Mt(this.client)}};var Yn={};A(Yn,{LiquidityMiningApi:()=>qt,LiquidityMiningClient:()=>Nt});import{AccountId as $i}from"polkadot-api";import q from"big.js";import{HYDRATION_SS58_PREFIX as Xi,RUNTIME_DECIMALS as dt}from"@galacticcouncil/common";import{fixed_from_rational as Un}from"@galacticcouncil/math-liquidity-mining";var fe={};A(fe,{withTimeout:()=>Bi});function Bi(p,t,e="timeout"){return new Promise((n,r)=>{let i=setTimeout(()=>r(new Error(e)),t);p.then(a=>{clearTimeout(i),n(a)},a=>{clearTimeout(i),r(a)})})}var C={};A(C,{divSpot:()=>Fi,getFraction:()=>Ri,mulScaled:()=>Ln,mulSpot:()=>_i});import{RUNTIME_DECIMALS as Dn}from"@galacticcouncil/common";function Ln(p,t,e,n,r){let i=e+n-r,a=p*t;return i>0?a/BigInt(10)**BigInt(i):i<0?a*BigInt(10)**BigInt(-i):a}function _i(p,t,e,n){return Ln(p,t,e,Dn,n)}function Fi(p,t,e,n){if(t===0n)return 0n;let r=BigInt(10)**BigInt(Dn+n-e);return p*r/t}function Ri(p,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let n=BigInt(10)**BigInt(e),r=BigInt(Math.round(t*Number(n)));return p*r/(BigInt(100)*n)}var x={};A(x,{FeeUtils:()=>Ye,shiftNeg:()=>Ei});import Ci from"big.js";var Ye=class p{static toPct(t){let[e,n]=t;return p.safeDivide(e*100,n)}static toRaw(t){let[e,n]=t;return p.safeDivide(e,n)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,n=12){let r=10**n;return Math.round(t*r/e)/r}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Ei(p,t){let e=Ci(typeof p=="bigint"?p.toString():p);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Lt={};A(Lt,{findNestedKey:()=>ki,findNestedObj:()=>Mi,jsonFormatter:()=>Di});var ki=(p,t)=>{let e=[];return JSON.stringify(p,(n,r)=>(r&&r[t]&&e.push(r),r)),e[0]},Mi=(p,t,e)=>{let n;return JSON.stringify(p,(r,i)=>(i&&i[t]===e&&(n=i),i)),n},Di=(p,t)=>typeof t=="bigint"?t.toString():t;var L={};A(L,{calculateBuyFee:()=>Hi,calculateDiffToAvg:()=>Li,calculateDiffToRef:()=>qi,calculateSellFee:()=>Ni});import j from"big.js";function Li(p,t){let e=j(p.toString()),n=j(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function qi(p,t){if(t===0n)return 0;let e=j(p.toString()),n=j(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function Ni(p,t){if(p===0n)return 0;let e=j(p.toString()),n=j(t.toString());return j(1).minus(n.div(e)).mul(100).round(2).toNumber()}function Hi(p,t){if(p===0n)return 0;let e=j(p.toString());return j(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}import{TLRUCache as qn}from"@thi.ng/cache";var Pe=class{debug;constructor(t){this.debug=t||!1}log(t,e,n){this.debug&&console.log(t,e,n)}scope(t,e,n,r){let i=new Map,a=r!==void 0?new qn(null,{ttl:r}):new qn;return{get:(...c)=>{let u=n(...c);if(i.has(u)){this.log("[live]",t,u);let m=i.get(u);return Promise.resolve(m)}if(a.has(u))return this.log("[memo]",t,u),a.get(u);this.log("[fetch]",t,u);let d=e(...c).catch(m=>{throw a.delete(u),m});return a.set(u,d),d},set:(c,...u)=>{let d=n(...u);this.log("[set-live]",t,d),i.set(d,c)},clear:()=>{this.log("[clear]",t),i.clear(),a.release()}}}};var Se=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let n=0;n<t.length;++n){let[r,i]=t[n];this.result.set(this.getKey(i,r),e[n].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,n,r){let i=this.getKey(t,e),a=this.getKey(t,n),s=this.result.get(i)??0n,o=this.result.get(a)??0n;if(s<r)throw new Error("Attempting to transfer more than is present");this.result.set(i,s+r),this.result.set(a,o+r)}};import rt from"big.js";import{calculate_accumulated_rps as Gi,calculate_global_farm_rewards as Vi,calculate_loyalty_multiplier as Ui,calculate_user_reward as Vn,calculate_yield_farm_delta_rpvs as Wi}from"@galacticcouncil/math-liquidity-mining";import Nn from"big.js";var $e=Nn(10).pow(18),Hn=BigInt(Nn(1).pow(18).toString()),Gn=6e3;var Yi="1000000000000000000",we=class{constructor(t,e,n){this.getAccount=t;this.getAsset=e;this.multiCurrency=n}async syncGlobalFarm(t,e,n){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let r=await this.getAsset(t.reward_currency),i=e-t.updated_at,a=this.getAccount(t.id),s=r?.existential_deposit;if(!s)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,a),l=rt(s.toString()),c=rt(o.toString()).minus(l.lt(o.toString())?s.toString():o.toString()),u=rt(Vi(t.total_shares_z.toString(),n.toString(),rt(t.yield_per_period.toString()).mul($e).round(0,rt.roundDown).toFixed(),t.max_reward_per_period.toString(),i.toFixed()));if(c.lt(u)&&(u=c),u.eq(0))return t;let d=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,a,d,BigInt(u.toFixed())),{...t,accumulated_rpz:BigInt(Gi(t.accumulated_rpz.toString(),t.total_shares_z.toString(),u.toFixed()))}}syncYieldFarm(t,e,n){if(t.state.type!=="Active"||t.updated_at===n)return t;if(t.total_valued_shares===0n)return{...t,updated_at:n};let r=Wi(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(r),updated_at:n}}getLoyaltyMultiplier(t,e){let n=rt(1).mul($e).round(0,rt.roundDown).toString();if(!e)return n;let{initial_reward_percentage:r,scale_coef:i}=e;return Ui(t.toFixed(),r.toString(),i.toFixed())}async claimRewards(t,e,n,r,i){if(e.state.type==="Terminated")return null;let a=Math.floor(r/t.blocks_per_period);if(n.updated_at===a)return null;let s=await this.syncGlobalFarm(t,a,i);if(!s)return null;let o=this.syncYieldFarm(e,s,a);if(!o)return null;let l=o.total_stopped-n.stopped_at_creation,c=o.updated_at-n.entered_at-l,u=this.getLoyaltyMultiplier(c,o.loyalty_curve),d=BigInt(Vn(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),u)),m=BigInt(Vn(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),Yi));return{reward:d,maxReward:m,assetId:s.reward_currency,yieldFarmId:o.id,isActiveFarm:o.state.type==="Active"}}};var zi=q(365.2425).times(24).times(60).times(60),qt=class{balance;client;options;constructor(t,e,n={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:n.blockTime??Gn})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let n=[t,e].sort((i,a)=>i-a);if(t===e)return Hn;let r=await this.client.getOraclePrice(n);if(r){let{n:i,d:a}=r[0].price,s;return t<e?s=Un(i.toString(),a.toString()):s=Un(a.toString(),i.toString()),BigInt(s)}}getFarmAddress=(t,e)=>{let n=Buffer.from("modl","utf-8"),r=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),i=Buffer.from([t]),a=Buffer.concat([n,r,i]),o="0x"+Buffer.concat([a,Buffer.alloc(32-a.length)]).toString("hex");return $i(Xi).dec(o)};getGlobalRewardPerPeriod(t,e,n,r){let i=q(r).times(t.toString()).times(e.toString()).div(Math.pow(10,dt));return i.gte(n.toString())?n.toString():i.toString()}getPoolYieldPerPeriod(t,e,n,r){let i=q(t.toString()).times(e),a=q(n.toString()).times(r);return i.div(a.toString()).toString()}farmData(t,e,n){let{yieldFarm:r,globalFarm:i,priceAdjustment:a,balance:s,id:o}=t,{multiplier:l,loyalty_curve:c}=r,{blocks_per_period:u,yield_per_period:d,total_shares_z:m,max_reward_per_period:h,pending_rewards:b,accumulated_paid_rewards:g,planned_yielding_periods:f,updated_at:y,incentivized_asset:S,reward_currency:P,price_adjustment:w,min_deposit:v}=i,F=x.shiftNeg(a??w,dt),k=x.shiftNeg(l,dt),$=x.shiftNeg(c?.initial_reward_percentage??0,dt),K=zi.div(q(this.blockTime).div(1e3).times(u)).toString(),H;if(m<=0)H=q(k).times(d.toString()).times(K).div(Math.pow(10,dt)).toString();else{let Er=this.getGlobalRewardPerPeriod(m,d,h,F),kr=this.getPoolYieldPerPeriod(Er,k,m,F);H=q(kr).times(K).toString()}let V=b+g,Ot=h*BigInt(f),oe=s.transferable+V,yn=oe-V,le=q(yn.toString()).div(h.toString()),ce=q(e).div(u.toString()).toString(),ue=(m>=0?le.plus(y):le.plus(ce)).toString(),De=q(ue).times(u).toString(),Rr=q(m.toString()).div(q(h.toString()).div(d.toString())).div(Math.pow(10,dt)).times(100).times(F).toFixed(2),fn=q(V.toString()).div(oe.toString()).gte(.999);H=fn?"0":q(H).div(n?2:1).times(100).toString();let Cr=$?q(H).times($).toString():void 0;return{apr:H,minApr:Cr,isDistributed:fn,estimatedEndPeriod:ue,estimatedEndBlock:De,maxRewards:Ot,incentivizedAsset:S,rewardCurrency:P,loyaltyCurve:c,currentPeriod:ce,potMaxRewards:oe,fullness:Rr,yieldFarmId:r.id,globalFarmId:i.id,poolId:o,distributedRewards:V,plannedYieldingPeriods:f,minDeposit:v,blocksPerPeriod:u}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((r,i)=>r.includes(i.keyArgs[0].toString())?r:[...r,i.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async r=>{let i=await this.getOmnipoolFarms(r);if(i)return[r,i]}));return Object.fromEntries(n.filter(r=>!!r))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),n=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:i,value:a})=>{let[,s]=i,o=a,l=await this.client.getOmnipoolGlobalFarm(s),c=await this.client.getOmnipoolYieldFarm(Number(t),s,o);if(!l||!c)return;let u=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(s),h=await this.getOraclePrice(u,d),b=await this.balance.getBalance(m,u);return{id:t,globalFarm:l,yieldFarm:c,priceAdjustment:h,balance:b}}));return n?r.map(i=>i?this.farmData(i,n):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((r,i)=>r.includes(i.keyArgs[0].toString())?r:[...r,i.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async r=>{let i=await this.getIsolatedFarms(r);if(i)return[r,i]}));return Object.fromEntries(n.filter(r=>!!r))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),n=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:i,value:a})=>{let[,s]=i,o=a,l=await this.client.getIsolatedGlobalFarm(s),c=await this.client.getIsolatedYieldFarm(t,s,o);if(!l||!c)return;let u=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(s,!0),h=await this.getOraclePrice(u,d),b=await this.balance.getBalance(m,u);return{id:t,globalFarm:l,yieldFarm:c,priceAdjustment:h,balance:b,farmAddress:m}}));return n?r.map(i=>i?this.farmData(i,n,!0):void 0):[]}async getDepositReward(t,e,n,r){let i=e.global_farm_id,a=e.yield_farm_id,s=n?await this.client.getIsolatedYieldFarm(t,i,a):await this.client.getOmnipoolYieldFarm(Number(t),i,a),o=n?await this.client.getIsolatedGlobalFarm(i):await this.client.getOmnipoolGlobalFarm(i);if(!o||!s)return;let l=o.reward_currency,c=o.incentivized_asset,u=[[this.getFarmAddress(0,n),o.reward_currency],[this.getFarmAddress(o.id,n),o.reward_currency]],d=await this.getAccountAssetBalances(u),m=await this.getOraclePrice(l,c),h=new Se(u,d),g=await new we(y=>this.getFarmAddress(y),y=>this.client.getAsset(y),h).claimRewards(o,s,e,r,m??o.price_adjustment);if(!g)return;let f=await this.client.getAsset(g.assetId);if(f&&!(g.reward<=f.existential_deposit))return g}async getAccountAssetBalances(t){let[e,n]=await Promise.all([Promise.all(t.filter(([i,a])=>a!==0).map(([i,a])=>this.balance.getTokenBalance(i,a))),Promise.all(t.filter(([i,a])=>a===0).map(([i])=>this.balance.getSystemBalance(i)))]),r=[];for(let i=0,a=0;i+a<t.length;){let s=i+a,[,o]=t[s];o===0?(r.push(n[a]),a+=1):(r.push(e[i]),i+=1)}return r}};import{Binary as Wn,Enum as Ki}from"polkadot-api";var ji=Wn.toHex(Wn.fromText("omnipool")),Nt=class extends _{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(ji,t,Ki("TenMinutes"))}async getRelayBlockNumber(){return(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number}async getAllOmnipooFarms(){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries()}async getOmnipooFarms(t){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries(t)}async getOmnipoolGlobalFarm(t){return this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getOmnipoolYieldFarm(t,e,n){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,n,{at:"best"})}async getAllIsolatedFarms(){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries()}async getIsolatedFarms(t){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries(t)}async getIsolatedGlobalFarm(t){return this.api.query.XYKWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getIsolatedYieldFarm(t,e,n){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,n,{at:"best"})}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};var dr={};A(dr,{PoolContextProvider:()=>wt,PoolError:()=>Z,PoolFactory:()=>Pt,PoolType:()=>I,aave:()=>an,hsm:()=>cn,lbp:()=>Qe,omni:()=>tn,stable:()=>en,xyk:()=>nn});var Qe={};A(Qe,{LbpMath:()=>Y,LbpPool:()=>Ht,LbpPoolClient:()=>Ut});import{calculate_in_given_out as Qi,calculate_out_given_in as Ji,calculate_linear_weights as Zi,calculate_pool_trade_fee as ta,get_spot_price as ea}from"@galacticcouncil/math-lbp";var Y=class{static getSpotPrice(t,e,n,r,i){return ea(t,e,n,r,i)}static calculateInGivenOut(t,e,n,r,i){return Qi(t,e,n,r,i)}static calculateOutGivenIn(t,e,n,r,i){return Ji(t,e,n,r,i)}static calculateLinearWeights(t,e,n,r,i){return Zi(t,e,n,r,i)}static calculatePoolTradeFee(t,e,n){return ta(t,e,n)}};import{big as $n,RUNTIME_DECIMALS as Xn}from"@galacticcouncil/common";var I=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a.HSM="HSM",a))(I||{}),Z=(c=>(c.UnknownError="UnknownError",c.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",c.InsufficientTradingAmount="InsufficientTradingAmount",c.InsufficientCollateral="InsufficientCollateral",c.MaxHoldingExceeded="MaxHoldingExceeded",c.MaxInRatioExceeded="MaxInRatioExceeded",c.MaxOutRatioExceeded="MaxOutRatioExceeded",c.TradeNotAllowed="TradeNotAllowed",c.MaxBuyBackExceeded="MaxBuyBackExceeded",c.MaxBuyPriceExceeded="MaxBuyPriceExceeded",c))(Z||{});var{FeeUtils:zn}=x,Ht=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new p(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 n=new Map(this.tokens.map(a=>[a.id,a])),r=n.get(t),i=n.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:i.balance,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(t,e,n){let r=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let a=t.balanceOut/this.maxOutRatio;if(e>a&&i.push("MaxOutRatioExceeded"),r===t.assetOut){let s=this.calculateTradeFee(e,n),o=zn.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+s,c=this.calculateInGivenOut(t,l),u=t.balanceIn/this.maxInRatio;return c>u&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:i}}else{let s=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return s>o&&i.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:i}}}validateAndSell(t,e,n){let r=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let a=t.balanceIn/this.maxInRatio;if(e>a&&i.push("MaxInRatioExceeded"),r===t.assetIn){let s=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return s>o&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:i}}else{let s=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(s,n),l=zn.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),c=s-o,u=t.balanceOut/this.maxOutRatio;return c>u&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(t,e){let n=Y.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(t,e){let n=Y.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(t){let e=Y.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),$n.toBigInt(1,Xn).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=Y.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),$n.toBigInt(1,Xn).toString());return BigInt(e)}calculateTradeFee(t,e){let n=Y.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as Sa}from"polkadot-api";import{Subscription as wa,distinctUntilChanged as va,filter as xa,map as Ta}from"rxjs";import{memoize1 as aa}from"@thi.ng/memoize";import{TLRUCache as sa}from"@thi.ng/cache";import{ReplaySubject as Kn,Subscription as jn,combineLatest as oa,defer as la,from as ca,interval as ua,merge as Xe,of as pa,EMPTY as Gt}from"rxjs";import{bufferCount as ma,bufferTime as da,catchError as Vt,filter as Ie,finalize as ze,map as gt,pairwise as Ke,repeat as je,skip as ga,share as ha,startWith as ba,switchMap as Qn,tap as it,throttleTime as ya}from"rxjs/operators";import{BehaviorSubject as na}from"rxjs";var ve=class{store$=new na([]);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,n=new Map(e.map((s,o)=>[s.address,o])),r=await t(e),i=e.slice(),a=new Set;for(let s of r){let o=n.get(s.address);o===void 0?(n.set(s.address,i.length),i.push(s)):i[o]=s,a.add(s.address)}this.changeset=a,this.store$.next(i)}).catch(console.error)}destroy(){this.store$.complete()}};import{log as ra}from"@galacticcouncil/common";var ia={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:xe}=ra,Te=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${ia[this.type]})`,10)}trace(t,...e){xe.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){xe.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){xe.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){xe.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:fa}=fe,Pa=3e3,N=class extends _{evm;balance;store=new ve;log;shared$;resync$=new Kn(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new sa(null,{ttl:6*1e3});memPools=aa(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e,this.balance=new X(t),this.log=new Te(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(ba([]),ma(2,1),gt(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),Ie(t=>t.length>0),ya(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return la(()=>{let t=new jn;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe(Qn(()=>{let e=new jn;return ca(fa(this.getMemPools(),6e4,"getMemPools stalled")).pipe(it(()=>this.log.info("pool_synced",{mem:this.mem})),gt(r=>r.filter(i=>this.hasValidAssets(i))),it(r=>this.store.set(r)),Vt(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),Gt))).pipe(it(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),Qn(r=>Xe(pa(r),this.store.asObservable().pipe(ga(1)))),ze(()=>{e.unsubscribe()}))}),ze(()=>t.unsubscribe()))}).pipe(ha({connector:()=>new Kn(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:n}=e,r=[this.balance.watchTokensBalance(n)];if(this.hasSystemAsset(e)){let i=this.balance.watchSystemBalance(n);r.push(i)}if(this.hasErc20Asset(e)){let i=e.tokens.filter(s=>s.type==="Erc20").map(s=>s.id),a=this.balance.watchErc20Balance(n,i);r.push(a)}return oa(r).pipe(gt(i=>i.flat()),Ke(),gt(([i,a])=>this.balance.getDeltas(i,a)),Ie(i=>i.length>0),gt(i=>[n,i]))});return Xe(...t).pipe(da(250),Ie(e=>e.length>0),gt(e=>new Map(e)),this.watchGuard("balances")).subscribe(e=>{this.store.update(n=>this.updateBalances(n,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:n})=>t.type==="XYK"?n>0n&&!!e:!!e)}updateBalances=(t,e)=>{let n=[],r=new Map(t.map(i=>[i.address,i]));for(let[i,a]of e){let s=r.get(i);if(s){let o=s.tokens.map(l=>{let c=a.find(u=>u.id===l.id);return c&&l.id!==s.id?{...l,balance:c.balance.transferable}:l});n.push({...s,tokens:o})}}return n};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<Pa||(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 r=this.watcher.connection$.pipe(Ke(),Ie(([s,o])=>s==="offline"&&o==="online"),it(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),Vt(s=>(this.log.error("watchdog_recovery_error",s),Gt)),je({delay:1e3})),i=this.watcher.finalizedBlock$.pipe(Ke(),it(([s,o])=>{let l=Number(s.number),c=Number(o.number),u=c-l;u>=3&&(this.log.debug("watchdog_gap",{from:l,to:c,gap:u}),this.requestResync())}),Vt(s=>(this.log.error("watchdog_gap_error",s),Gt)),je({delay:1e3})),a=ua(36e5).pipe(it(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),Vt(s=>(this.log.error("watchdog_periodic_error",s),Gt)),je({delay:1e3}));return Xe(r,i,a).subscribe()}watchGuard(t){return e=>e.pipe(it({error:n=>{this.log.error(t,n),this.requestResync(!0)}}),ze(()=>{this.log.debug(t,"unsub")}),Vt(()=>Gt))}};var Ut=class extends N{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}getPoolWeights(t,e){let{start:n,end:r,initial_weight:i,final_weight:a}=t,s=Y.calculateLinearWeights(n?n.toString():"0",r?r.toString():"0",i.toString(),a.toString(),e.toString()),o=BigInt(s),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){return(await this.api.getStaticApis()).compat.query.LBP.PoolData.isCompatible(Sa.BackwardsCompatible)}async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:"best"}),this.api.query.ParachainSystem.ValidationData.getValue({at:"best"}),this.getPoolLimits()]),r=e?.relay_parent_number||0,i=t.filter(({value:a})=>e&&this.isActivePool(a,r)).map(async({keyArgs:a,value:s})=>{let[o]=a,l=o.toString(),c=await this.getPoolDelta(l,s,r);return{address:l,type:"LBP",fee:s.fee,...c,...n}});return Promise.all(i)}async getPoolDelta(t,e,n){let{assets:r,repay_target:i,fee_collector:a}=e,[s,o]=this.getPoolWeights(e,n),[l,c]=r,[u,d,m,h,b]=await Promise.all([this.isRepayFeeApplied(l,i,a.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:u,tokens:[{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,weight:s,type:m?.asset_type.type},{id:c,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:h.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:r}=t;return n&&r?e>=n&&e<r:!1}async isRepayFeeApplied(t,e,n){if(e===0n)return!1;try{return(await this.balance.getBalance(n,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let n=this.store.pools.find(i=>i.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:n.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue({at:"best"}).pipe(Ta(({value:t})=>t),xa(t=>t!==void 0),va((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 n=[];for(let r of e){let i=this.poolsData.get(r.address);if(i){let{assets:a,repay_target:s,fee_collector:o}=i,[l]=a,[c,u]=this.getPoolWeights(i,t),[d,m]=r.tokens,h=[{...d,weight:c},{...m,weight:u}],b=await this.isRepayFeeApplied(l,s,o.toString());n.push({...r,tokens:h,repayFeeApply:b})}}return n})})}subscribeUpdates(){let t=new wa;return t.add(this.subscribeValidationData()),t}};var tn={};A(tn,{OmniMath:()=>T,OmniPool:()=>Wt,OmniPoolClient:()=>Yt});import{calculate_in_given_out as Ia,calculate_lrna_in_given_out as Aa,calculate_out_given_in as Oa,calculate_out_given_lrna_in as Ba,calculate_spot_price as _a,calculate_lrna_spot_price as Fa,calculate_shares as Ra,calculate_liquidity_out as Ca,calculate_liquidity_lrna_out as Ea,verify_asset_cap as ka,calculate_liquidity_hub_in as Ma,is_sell_allowed as Da,is_buy_allowed as La,is_add_liquidity_allowed as qa,is_remove_liquidity_allowed as Na,recalculate_asset_fee as Ha,recalculate_protocol_fee as Ga}from"@galacticcouncil/math-omnipool";import ht from"big.js";var T=class{static calculateSpotPrice(t,e,n,r){return _a(t,e,n,r)}static calculateLrnaSpotPrice(t,e){return Fa(t,e)}static calculateInGivenOut(t,e,n,r,i,a,s,o,l,c){return Ia(t,e,n,r,i,a,s,o,l,c)}static calculateLrnaInGivenOut(t,e,n,r,i,a){return Aa(t,e,n,r,i,a)}static calculateOutGivenIn(t,e,n,r,i,a,s,o,l,c){return Oa(t,e,n,r,i,a,s,o,l,c)}static calculateOutGivenLrnaIn(t,e,n,r,i,a){return Ba(t,e,n,r,i,a)}static calculateShares(t,e,n,r){return Ra(t,e,n,r)}static calculateLiquidityOut(t,e,n,r,i,a,s,o){return Ca(t,e,n,r,i,a,s,o)}static calculateLiquidityLRNAOut(t,e,n,r,i,a,s,o){return Ea(t,e,n,r,i,a,s,o)}static calculateCapDifference(t,e,n,r){let i=ht(e),a=ht(t),s=ht(r),o=ht(n),l=ht(10).pow(18),c=o.div(l);if(i.div(s).lt(c)){let d=c.times(s).minus(i).times(a),m=i.times(ht(1).minus(c));return d.div(m).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,n,r){return Ma(t,e,n,r)}static isSellAllowed(t){return Da(t)}static isBuyAllowed(t){return La(t)}static isAddLiquidityAllowed(t){return qa(t)}static isRemoveLiquidityAllowed(t){return Na(t)}static recalculateAssetFee(t,e,n,r,i,a,s,o,l,c,u){return Ha(t,e,n,r,i,a,s,o,l,c,u)}static recalculateProtocolFee(t,e,n,r,i,a,s,o,l,c,u){return Ga(t,e,n,r,i,a,s,o,l,c,u)}static verifyAssetCap(t,e,n,r){return ka(t,e,n,r)}};import{big as Va}from"@galacticcouncil/common";var{FeeUtils:z}=x,Wt=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new p(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 n=new Map(this.tokens.map(a=>[a.id,a])),r=n.get(t),i=n.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:r.balance,balanceOut:i.balance,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInEd:r.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,n){let r=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,n),a=r===0n?0:L.calculateBuyFee(r,i),s=[],o=T.isSellAllowed(t.tradeableIn),l=T.isBuyAllowed(t.tradeableOut);(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&s.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&s.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return i>u&&s.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:e,feePct:a,errors:s}}validateAndSell(t,e,n){let r=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,n),a=L.calculateSellFee(r,i),s=[],o=T.isSellAllowed(t.tradeableIn),l=T.isBuyAllowed(t.tradeableOut);(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&s.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&s.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return i>u&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:i,feePct:a,errors:s}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let r=T.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?z.toRaw(n.assetFee).toString():"0",n?z.toRaw(n.protocolFee).toString():"0",n?z.toRaw(n.maxSlipFee).toString():"0"),i=BigInt(r);return i<0n?0n:i}calculateLrnaInGivenOut(t,e,n){let r=T.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?z.toRaw(n.assetFee).toString():"0",n?z.toRaw(n.maxSlipFee).toString():"0"),i=BigInt(r);return i<0n?0n:i}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let r=T.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?z.toRaw(n.assetFee).toString():"0",n?z.toRaw(n.protocolFee).toString():"0",n?z.toRaw(n.maxSlipFee).toString():"0"),i=BigInt(r);return i<0n?0n:i}calculateOutGivenLrnaIn(t,e,n){let r=T.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?z.toRaw(n.assetFee).toString():"0",n?z.toRaw(n.maxSlipFee).toString():"0"),i=BigInt(r);return i<0n?0n:i}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=T.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=T.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=T.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=T.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,n){let r=e-n;if(r===0)return t;let i=Va.pow10(Math.abs(r));return r>0?t*i:t/i}};import{AccountId as Ua,Binary as Jn,CompatibilityLevel as Zn,Enum as Wa}from"polkadot-api";import{toHex as Ya}from"@polkadot-api/utils";import{Subscription as $a,distinctUntilChanged as Je,filter as Xa,finalize as Ze,map as bt,merge as za,tap as Ae}from"rxjs";import{HYDRATION_SS58_PREFIX as Ka}from"@galacticcouncil/common";var{FeeUtils:B}=x,tr=Jn.toHex(Jn.fromText("omnipool")),er=Wa("Short"),Yt=class extends N{queryBus=new Pe;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(tr,t,er,{at:"best"}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=Ya(e);return Ua(Ka).dec(n)}getOraclePair(t){return t===0?[0,1]:[1,t]}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Omnipool.Assets.isCompatible(Zn.BackwardsCompatible)}async isSlipFeeSupported(){return(await this.apiNext.getStaticApis()).compat.query.Omnipool.SlipFee.isCompatible(Zn.Partial)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,r,i,a,s]=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=n.map(async({keyArgs:c,value:u})=>{let[d]=c,{hub_reserve:m,shares:h,tradable:b,cap:g,protocol_shares:f}=u,[y,S]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d),this.balance.getBalance(e,d)]);return{id:d,decimals:y?.decimals,existentialDeposit:y?.existential_deposit,balance:S.transferable,cap:g,hubReserves:m,protocolShares:f,shares:h,tradeable:b,type:y?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:a.transferable,tradeable:r,type:i?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...s}]}async getPoolFees(t){let e=t.assetOut,n=t.assetIn,r=0;await this.isSlipFeeSupported()&&(r=await this.maxSlipFee.get()??0);let a=await this.dynamicFeesConfig.get(e);if(a?.type==="Fixed"){let{asset_fee:P,protocol_fee:w}=a.value;return{assetFee:B.fromPermill(P),protocolFee:B.fromPermill(w),maxSlipFee:B.fromPermill(r)}}let s=this.getOraclePair(e),o=this.getOraclePair(n),[l,c,u]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(s),this.emaOracles.get(o)]),[d,m,h]=await this.getAssetFee(t,this.block,l,c,a?.value.asset_fee_params),[b,g,f]=n===1?[0,0,0]:await this.getProtocolFee(t,this.block,l,u,a?.value.protocol_fee_params),y=d+b,S=h+f;return{assetFee:B.fromPermill(m),protocolFee:B.fromPermill(g),maxSlipFee:B.fromPermill(r),min:B.fromPermill(y),max:B.fromPermill(S)}}async getAssetFee(t,e,n,r,i){let{assetOut:a,balanceOut:s}=t,{min_fee:o,max_fee:l,decay:c,amplification:u}=i||await this.api.constants.DynamicFees.AssetFeeParameters();if(!n||!r)return[o,o,l];let d=B.fromPermill(o),m=B.fromPermill(l),[h]=r,{asset_fee:b,timestamp:g}=n,f=Math.max(1,e-g),y=h.volume.b_in.toString(),S=h.volume.b_out.toString(),P=h.liquidity.b.toString();a===0&&(y=h.volume.a_in.toString(),S=h.volume.a_out.toString(),P=h.liquidity.a.toString());let w=B.fromPermill(b),v=T.recalculateAssetFee(y,S,P,"9",s.toString(),B.toRaw(w).toString(),f.toString(),B.toRaw(d).toString(),B.toRaw(m).toString(),c.toString(),u.toString());return[o,Number(v)*1e6,l]}async getProtocolFee(t,e,n,r,i){let{assetIn:a,balanceIn:s}=t,{min_fee:o,max_fee:l,decay:c,amplification:u}=i||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!n||!r)return[o,o,l];let d=B.fromPermill(o),m=B.fromPermill(l),[h]=r,{protocol_fee:b,timestamp:g}=n,f=Math.max(1,e-g),y=h.volume.b_in.toString(),S=h.volume.b_out.toString(),P=h.liquidity.b.toString();a===0&&(y=h.volume.a_in.toString(),S=h.volume.a_out.toString(),P=h.liquidity.a.toString());let w=B.fromPermill(b),v=T.recalculateProtocolFee(y,S,P,"9",s.toString(),B.toRaw(w).toString(),f.toString(),B.toRaw(d).toString(),B.toRaw(m).toString(),c.toString(),u.toString());return[o,Number(v)*1e6,l]}subscribeEmaOracles(){let[t]=this.store.pools,n=t.tokens.map(r=>r.id).map(r=>this.getOraclePair(r)).map(r=>this.api.query.EmaOracle.Oracles.watchValue(tr,r,er,{at:"best"}).pipe(bt(({value:i})=>i),Xa(i=>i!==void 0),bt((i,a)=>({value:i,index:a})),Ae(({index:i})=>{i>0&&this.log.trace("emaOracle.Oracles",r.join(":"))}),bt(({value:i})=>({pair:r,value:i}))));return za(...n).pipe(Ze(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(r=>{let{pair:i,value:a}=r;this.emaOracles.set(a,i)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe(Je((t,e)=>!e.deltas),bt((t,e)=>({value:t,index:e})),Ae(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),Ze(()=>this.dynamicFees.clear()),this.watchGuard("dynamicFees.AssetFee")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[n]=e.args;this.dynamicFees.set(e.value,n)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe(Je((t,e)=>!e.deltas),bt((t,e)=>({value:t,index:e})),Ae(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),Ze(()=>this.dynamicFeesConfig.clear()),this.watchGuard("dynamicFees.AssetFeeConfiguration")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[n]=e.args;this.dynamicFeesConfig.set(e.value,n)})})}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(Je((t,e)=>!e.deltas),bt((t,e)=>({value:t,index:e})),Ae(({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 n=t?.upserted.reduce((i,a)=>{let[s]=a.args;return i.set(s,a.value),i},new Map),r=e.tokens.map(i=>{let a=n?.get(i.id);return a?this.updateTokenState(i,a):i});return[{...e,tokens:r}]})})}subscribeUpdates(){let t=new $a;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:n,shares:r,tradable:i,cap:a,protocol_shares:s}=e;return{...t,cap:a,hubReserves:n,protocolShares:s,shares:r,tradeable:i}}};var en={};A(en,{StableMath:()=>M,StableSwap:()=>at,StableSwapClient:()=>$t});import{calculate_in_given_out as ja,calculate_out_given_in as Qa,calculate_amplification as Ja,calculate_add_one_asset as Za,calculate_liquidity_out_one_asset as ts,calculate_shares as es,calculate_shares_for_amount as ns,calculate_spot_price_with_fee as rs,pool_account_name as is,recalculate_peg as as}from"@galacticcouncil/math-stableswap";var M=class{static getPoolAddress(t){return is(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,r,i){return Ja(t,e,n,r,i)}static calculateInGivenOut(t,e,n,r,i,a,s){return ja(t,e,n,r,i,a,s)}static calculateAddOneAsset(t,e,n,r,i,a,s){return Za(t,e,n,r,i,a,s)}static calculateSharesForAmount(t,e,n,r,i,a,s){return ns(t,e,n,r,i,a,s)}static calculateOutGivenIn(t,e,n,r,i,a,s){return Qa(t,e,n,r,i,a,s)}static calculateLiquidityOutOneAsset(t,e,n,r,i,a,s){return ts(t,e,n,r,i,a,s)}static calculateShares(t,e,n,r,i,a){return es(t,e,n,r,i,a)}static calculateSpotPriceWithFee(t,e,n,r,i,a,s,o){return rs(t,e,n,r,i,a,s,o)}static recalculatePegs(t,e,n,r,i,a){let s=as(t,e,n,r,i,a);return JSON.parse(s)}};import{RUNTIME_DECIMALS as ss,big as nr}from"@galacticcouncil/common";var{FeeUtils:yt}=x,at=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new p(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 n=new Map(this.tokens.map(a=>[a.id,a])),r=n.get(t),i=n.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:i.balance,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===t?15:r.tradeable,tradeableOut:this.id===e?15:i.tradeable,assetInEd:r.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,n){let r=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,n),a=r===0n?0:L.calculateBuyFee(r,i),s=[],o=T.isSellAllowed(t.tradeableIn),l=T.isBuyAllowed(t.tradeableOut);return(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&s.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:e,feePct:a,errors:s}}validateAndSell(t,e,n){let r=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,n),a=L.calculateSellFee(r,i),s=[],o=T.isSellAllowed(t.tradeableIn),l=T.isBuyAllowed(t.tradeableOut);return(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&s.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:r,amountOut:i,feePct:a,errors:s}}calculateIn(t,e,n){let r=M.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(r);return i<0n?0n:i}calculateAddOneAsset(t,e,n){let r=M.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(r);return i<0n?0n:i}calculateSharesForAmount(t,e,n){let r=M.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(r);return i<0n?0n:i}calculateInGivenOut(t,e,n){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,n):t.assetIn==this.id?this.calculateSharesForAmount(t,e,n):this.calculateIn(t,e,n)}spotPriceInGivenOut(t){let e=M.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,n){let r=M.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(r);return i<0n?0n:i}calculateWithdrawOneAsset(t,e,n){let r=M.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(r);return i<0n?0n:i}calculateShares(t,e,n){let r=M.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(r);return i<0n?0n:i}calculateOutGivenIn(t,e,n){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,n):t.assetOut==this.id?this.calculateShares(t,e,n):this.calculateOut(t,e,n)}spotPriceOutGivenIn(t){let e=M.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:n,decimals:r})=>({asset_id:e,amount:n,decimals:r}));return JSON.stringify(t,Lt.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],Lt.jsonFormatter)}normalizeSpot(t,e,n,r,i){return e?t*nr.pow10(ss-i):n?t/nr.pow10(i-r):t}};import{AccountId as os,CompatibilityLevel as ls}from"polkadot-api";import{toHex as cs}from"@polkadot-api/utils";import{blake2b as us}from"@noble/hashes/blake2b";import{Subscription as ps,distinctUntilChanged as ms,map as Oe,merge as ds,tap as rr}from"rxjs";import{HYDRATION_SS58_PREFIX as gs,RUNTIME_DECIMALS as hs}from"@galacticcouncil/common";var{FeeUtils:bs}=x,$t=class extends N{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=M.getPoolAddress(t),n=us(e,{dkLen:32}),r=cs(n);return os(gs).dec(r)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:n,final_amplification:r,initial_block:i,final_block:a}=t,s=M.calculateAmplification(n.toString(),r.toString(),i.toString(),a.toString(),e.toString()),o=Number(s)<r;return{amplification:BigInt(s),isRampPeriod:o}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),r=e.assets.map(async i=>{let[a,s,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,i),this.api.query.AssetRegistry.Assets.getValue(i),this.balance.getBalance(n,i)]);return{id:i,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:o.transferable,tradeable:a,type:s?.asset_type.type}});return Promise.all(r)}async isSupported(){return(await this.api.getStaticApis()).compat.query.Stableswap.Pools.isCompatible(ls.BackwardsCompatible)}async loadPools(){let[t,e,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:"best"}),this.api.query.System.Number.getValue({at:"best"}),this.getPoolLimits()]),r=t.map(async({keyArgs:i,value:a})=>{let[s]=i,o=this.getPoolAddress(s),[l,c,u]=await Promise.all([this.getPoolTokens(s,a),this.api.query.Stableswap.PoolPegs.getValue(s,{at:"best"}),this.api.query.Tokens.TotalIssuance.getValue(s,{at:"best"})]),d=this.getPoolAmplification(a,e),m=c?this.getRecentPegs(c):this.getDefaultPegs(a);return l.push({id:s,tradeable:15,balance:u,decimals:hs}),this.poolsData.set(s,a),{address:o,id:s,type:"Stableswap",fee:bs.fromPermill(a.fee),tokens:l,totalIssuance:u,pegs:m,...n,...d}});return Promise.all(r)}async getPoolFees(t,e){return{fee:this.store.pools.find(r=>r.address===e).fee}}getDefaultPegs(t){return M.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([n,r])=>r.map(i=>i.toString()))}subscribeIssuance(){let e=this.store.pools.map(n=>n.id).map(n=>this.api.query.Tokens.TotalIssuance.watchValue(n,{at:"best"}).pipe(Oe(({value:r})=>r),Oe((r,i)=>({value:r,index:i})),rr(({index:r,value:i})=>{r>0&&this.log.trace("tokens.TotalIssuance",n,i)}),Oe(({value:r})=>({id:n,value:r}))));return ds(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(n=>{let{id:r,value:i}=n;this.store.update(a=>{let s=[];return a.filter(o=>o.id===r).forEach(o=>{let l=o.tokens.map(c=>c.id===r?{...c,balance:i}:c);s.push({...o,tokens:l,totalIssuance:i})}),s})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe(ms((t,e)=>!e.deltas),Oe((t,e)=>({value:t,index:e})),rr(({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 n=[],r=new Map(e.map(i=>[i.id,i]));return t?.upserted.forEach(({args:i,value:a})=>{let[s]=i,o=r.get(s);if(o){let l=this.getRecentPegs(a);n.push({...o,pegs:l})}}),n})}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(e=>{let n=[];return e.filter(r=>r.isRampPeriod).forEach(r=>{let i=this.poolsData.get(r.id);if(i){let a=this.getPoolAmplification(i,t);n.push({...r,...a})}}),n})})}subscribeUpdates(){let t=new ps;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 nn={};A(nn,{XykMath:()=>Q,XykPool:()=>Xt,XykPoolClient:()=>zt});import{calculate_in_given_out as ys,calculate_out_given_in as fs,calculate_pool_trade_fee as Ps,get_spot_price as Ss,calculate_liquidity_in as ws,calculate_shares as vs,calculate_spot_price as xs,calculate_spot_price_with_fee as Ts,calculate_liquidity_out_asset_a as Is,calculate_liquidity_out_asset_b as As}from"@galacticcouncil/math-xyk";var Q=class{static getSpotPrice(t,e,n){return Ss(t,e,n)}static calculateInGivenOut(t,e,n){return ys(t,e,n)}static calculateOutGivenIn(t,e,n){return fs(t,e,n)}static calculatePoolTradeFee(t,e,n){return Ps(t,e,n)}static calculateLiquidityIn(t,e,n){return ws(t,e,n)}static calculateSpotPrice(t,e){return xs(t,e)}static calculateSpotPriceWithFee(t,e,n,r){return Ts(t,e,n,r)}static calculateShares(t,e,n){return vs(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,r){return Is(t,e,n,r)}static calculateLiquidityOutAssetB(t,e,n,r){return As(t,e,n,r)}};import{big as Os}from"@galacticcouncil/common";var{FeeUtils:ir}=x,Xt=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new p(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 n=new Map(this.tokens.map(a=>[a.id,a])),r=n.get(t),i=n.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:r.balance,balanceOut:i.balance,assetInEd:r.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,n){let r=this.calculateInGivenOut(t,e),i=this.calculateTradeFee(r,n),a=ir.toPct(n.exchangeFee),s=r+i,o=[];(e<this.minTradingLimit||r<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return s>c&&o.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:r,amountOut:e,feePct:a,errors:o}}validateAndSell(t,e,n){let r=this.calculateOutGivenIn(t,e),i=this.calculateTradeFee(r,n),a=ir.toPct(n.exchangeFee),s=r-i,o=[];(e<this.minTradingLimit||r<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return s>c&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:s,feePct:a,errors:o}}calculateInGivenOut(t,e){let n=Q.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(t,e){let n=Q.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(t){let e=Q.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=Q.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let n=Q.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}normalizeSpot(t,e,n){let r=e-n;if(r===0)return t;let i=Os.pow10(Math.abs(r));return r>0?t*i:t/i}};import{CompatibilityLevel as Bs}from"polkadot-api";import{Subscription as _s}from"rxjs";var zt=class extends N{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,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async isSupported(){return(await this.api.getStaticApis()).compat.query.XYK.PoolAssets.isCompatible(Bs.BackwardsCompatible)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries(),this.getPoolLimits()]),n=t.map(async({keyArgs:r,value:i})=>{let[a]=r,[s,o]=i,[l,c,u,d]=await Promise.all([this.balance.getBalance(a,s),this.api.query.AssetRegistry.Assets.getValue(s),this.balance.getBalance(a,o),this.api.query.AssetRegistry.Assets.getValue(o)]);return{address:a,type:"XYK",tokens:[{id:s,decimals:c?.decimals||this.decimals.get(s),existentialDeposit:c?.existential_deposit,balance:l.transferable,type:c?.asset_type.type},{id:o,decimals:d?.decimals||this.decimals.get(o),existentialDeposit:d?.existential_deposit,balance:u.transferable,type:d?.asset_type.type}],...e}});return Promise.all(n)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return _s.EMPTY}};var an={};A(an,{AavePool:()=>Kt,AavePoolClient:()=>jt});import{big as ar,RUNTIME_DECIMALS as sr}from"@galacticcouncil/common";var Kt=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new p(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 n=new Map(this.tokens.map(a=>[a.id,a])),r=n.get(t),i=n.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:i.balance,decimalsIn:r.decimals,decimalsOut:i.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let r=this.calculateInGivenOut(t,e),i=[];return e>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e,n){let r=this.calculateOutGivenIn(t,e),i=[];return r>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:i}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return ar.toBigInt(1,sr)}spotPriceOutGivenIn(t){return ar.toBigInt(1,sr)}calculateTradeFee(t,e){return 0n}};import{AccountId as Fs,Binary as Rs}from"polkadot-api";import{toHex as Cs}from"@polkadot-api/utils";import{Subscription as lr,filter as rn,map as cr,mergeMap as ur}from"rxjs";import{decodeEventLog as Es}from"viem";import{erc20 as ks,HYDRATION_SS58_PREFIX as Ms}from"@galacticcouncil/common";var or=[{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:Ds}=ks,Ls=["Supply","Withdraw","Repay","Borrow"],jt=class extends N{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let n=t+"/"+e,r=new TextEncoder().encode(n.padEnd(32,"\0")),i=Cs(r);return Fs(Ms).dec(i)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:"best"})).map(async({reserve:n,atoken:r,liqudity_in:i,liqudity_out:a})=>{let[s,o,l,c]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(r),this.api.query.AssetRegistry.AssetLocations.getValue(r)]);return{address:this.getPoolId(n,r),type:"Aave",tokens:[{id:n,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:i,location:o,type:s?.asset_type.type},{id:r,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:a,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:r,liqudity_out:i}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id,{at:"best"});return t.tokens.map(a=>{let s=a.id===e.id?r:i;return{...a,balance:s}})}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:n}=e.value;return n.key}throw new Error("Invalid aave reserve multilocation")}return Ds.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:n}=t;return{assetIn:e,assetOut:n,key:`${e}:${n}`}}parseEvmLog(t){let{topics:e,data:n}=t.log,r=e,i=Rs.toHex(n);try{let{eventName:a,args:s}=Es({abi:or,topics:r,data:i}),o=s.reserve.toLowerCase();return{eventName:a,reserve:o,key:`${a}:${o}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(n=>n.tokens).map(([n,r])=>r).map(n=>n.id);return this.api.event.Router.Executed.watch().pipe(ur(({events:n})=>n),cr(({payload:n})=>this.parseRouterLog(n)),rn(({assetIn:n,assetOut:r})=>e.includes(n)||e.includes(r)),this.watchGuard("router.Execute")).subscribe(({assetIn:n,assetOut:r,key:i})=>{this.log.trace("router.Executed",i),this.store.update(async a=>{let s=[];for(let o of a){let[l,c]=o.tokens;if(c.id===n||c.id===r){let d=await this.getPoolDelta(o);s.push({...o,tokens:d})}}return s})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(ur(({events:t})=>t),cr(({payload:t})=>this.parseEvmLog(t)),rn(t=>t!==void 0),rn(({eventName:t})=>Ls.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async n=>{let r=[];for(let i of n){let[a]=i.tokens;if(this.getReserveH160Id(a).toLowerCase()===t){let o=await this.getPoolDelta(i);r.push({...i,tokens:o})}}return r})})}subscribeBalances(){return lr.EMPTY}subscribeUpdates(){let t=new lr;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var cn={};A(cn,{HsmMath:()=>U,HsmPool:()=>Qt,HsmPoolClient:()=>te});import{calculate_collateral_in_given_hollar_out as qs,calculate_collateral_out_given_hollar_in as Ns,calculate_hollar_in_given_collateral_out as Hs,calculate_hollar_out_given_collateral_in as Gs,calculate_imbalance as Vs,calculate_max_price as Us,calculate_buyback_limit as Ws,calculate_buyback_price_with_fee as Ys}from"@galacticcouncil/math-hsm";var U=class{static calculateCollateralInGivenHollarOut(t,e,n){return qs(t,e,n)}static calculateCollateralOutGivenHollarIn(t,e,n){return Ns(t,e,n)}static calculateHollarOutGivenCollateralIn(t,e,n){return Gs(t,e,n)}static calculateHollarInGivenCollateralOut(t,e,n){return Hs(t,e,n)}static calculateImbalance(t,e,n){return Vs(t,e,n)}static calculateBuybackLimit(t,e){return Ws(t,e)}static calculateBuybackPriceWithFee(t,e,n){return Ys(t,e,n)}static calculateMaxPrice(t,e){return Us(t,e)}};import{big as J,RUNTIME_DECIMALS as Be}from"@galacticcouncil/common";var{FeeUtils:ft}=x,Qt=class p extends at{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new p(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,n){let r=this.parsePair(t.assetOut,t.assetIn),i=super.calculateInGivenOut(r,e,{fee:this.fee}),a=this.calculateBuybackLimit(t);e>a&&n.push("MaxBuyBackExceeded");let s=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,i)>s&&n.push("MaxBuyPriceExceeded"),i>this.collateralBalance&&n.push("InsufficientCollateral"),n}validateTradeHollarOut(t,e,n){return this.collateralBalance+t>this.maxInHolding&&n.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&n.push("FacilitatorCapacityExceeded"),n}validateTradeConstraints(t,e,n){let r=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,r):this.validateTradeHollarOut(e,n,r)}validateAndBuy(t,e){let n=this.calculateInGivenOut(t,e),r=this.validateTradeConstraints(t,n,e);return{amountIn:n,calculatedIn:n,amountOut:e,feePct:0,errors:r}}validateAndSell(t,e){let n=this.calculateOutGivenIn(t,e),r=this.validateTradeConstraints(t,e,n);return{amountIn:e,calculatedOut:n,amountOut:n,feePct:0,errors:r}}calculateHollarInGivenCollateralOut(t,e){let n=super.calculateInGivenOut(t,e,{fee:this.fee}),r=U.calculateHollarInGivenCollateralOut(e.toString(),n.toString(),ft.toRaw(this.buyBackFee).toString());return BigInt(r)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),n=U.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),ft.toRaw(this.purchaseFee).toString());return BigInt(n)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let n=super.calculateOutGivenIn(t,e,{fee:this.fee}),r=U.calculateCollateralOutGivenHollarIn(e.toString(),n.toString(),ft.toRaw(this.buyBackFee).toString());return BigInt(r)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),n=U.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),ft.toRaw(this.purchaseFee).toString());return BigInt(n)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),n=U.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(n)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),n=U.calculateBuybackLimit(e.toString(),ft.toRaw(this.buyBackRate).toString());return BigInt(n)}calculateBuyPrice(t,e,n){let r=U.calculateBuybackPriceWithFee(n.toString(),e.toString(),ft.toRaw(this.buyBackFee).toString()),[i,a]=JSON.parse(r),s=J.pow10(t.decimalsIn+Be-t.decimalsOut);return BigInt(i)*s/BigInt(a)}calculateMaxPrice(t){let e=this.getCollateralPeg(),n=U.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[r,i]=JSON.parse(n),a=J.pow10(Be-t.decimalsOut);return BigInt(r)*a/BigInt(i)}spotPriceInGivenOut(t){let e=J.toBigInt(1,t.decimalsOut),r=this.calculateInGivenOut(t,e)*J.pow10(Be-t.decimalsOut);return this.normalizeSpotPrice(r,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=J.toBigInt(1,t.decimalsIn),r=this.calculateOutGivenIn(t,e)*J.pow10(Be-t.decimalsIn);return this.normalizeSpotPrice(r,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(r=>r.id!==this.hollarId),e=this.pegs[t],n=this.tokens[t].decimals;return this.isDefaultPeg(e)?[J.toBigInt(1,18).toString(),J.toBigInt(1,n).toString()]:e}isDefaultPeg(t){let[e,n]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&n==="1"}normalizeSpotPrice(t,e,n){let r=e-n;if(r===0)return t;let i=J.pow10(Math.abs(r));return r>0?t*i:t/i}};import{AccountId as $s,Binary as Xs,CompatibilityLevel as zs}from"polkadot-api";import{toHex as Ks}from"@polkadot-api/utils";import{Subscription as sn,combineLatest as js,filter as pr,map as on,mergeMap as Qs,pairwise as Js}from"rxjs";import{decodeEventLog as Zs}from"viem";import{h160 as to,HYDRATION_SS58_PREFIX as eo}from"@galacticcouncil/common";var Jt=[{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 Zt=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[n,r]=await this.client.readContract({abi:Jt,address:t,functionName:"getFacilitatorBucket",args:[e]});return n-r}};var{FeeUtils:ln}=x,{H160:mr}=to,no=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],te=class extends N{ghoClient;stableClient;constructor(t,e,n){super(t,e),this.stableClient=n,this.ghoClient=new Zt(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:n}=e.value;return n.key}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),n=new TextEncoder().encode(e),r=Ks(n);return $s(eo).dec(r)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(zs.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,n,r]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t),this.api.query.HSM.Collaterals.getEntries({at:"best"}),this.stableClient.getPools()]);if(n.length===0)return[];let i=this.getFacilitatorAddress(),a=mr.fromAny(i),s=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(s,a),l=n.map(async({keyArgs:u,value:d})=>{let[m]=u,{pool_id:h,max_buy_price_coefficient:b,max_in_holding:g,purchase_fee:f,buy_back_fee:y,buyback_rate:S}=d,P=r.find(w=>w.id===h);if(P){let w=this.getPoolId(h),v=await this.balance.getBalance(i,m);return{...P,address:w,type:"HSM",tokens:P.tokens.filter(F=>F.id!==h),hsmAddress:i,hsmMintCapacity:o,hollarId:t,hollarH160:s,collateralId:m,collateralBalance:v.transferable,maxBuyPriceCoefficient:b,maxInHolding:g,purchaseFee:ln.fromPermill(f),buyBackFee:ln.fromPermill(y),buyBackRate:ln.fromPerbill(S)}}});return(await Promise.all(l)).filter(u=>u!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:n}=t.log,r=e,i=Xs.toHex(n);try{let{eventName:a,args:s}=Zs({abi:Jt,topics:r,data:i}),o=s.facilitatorAddress.toLowerCase();return{eventName:a,facilitator:o,key:`${a}:${o}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(Qs(({events:t})=>t),on(({payload:t})=>this.parseEvmLog(t)),pr(t=>t!==void 0),pr(({eventName:t})=>no.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async n=>{let r=[],[{hsmAddress:i,hollarH160:a}]=n,s=mr.fromAny(i);if(s.toLowerCase()===e){let l=await this.ghoClient.getFacilitatorCapacity(a,s);for(let c of n)r.push({...c,hsmMintCapacity:l})}return r})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(i=>{let{tokens:a,collateralId:s}=i;a.find(l=>l.id===s).type==="Erc20"?e.push(s):t.push(s)});let[{hsmAddress:n}]=this.store.pools,r=[];if(t.length>0){let i=this.balance.watchTokensBalance(n);r.push(i)}if(e.length>0){let i=this.balance.watchErc20Balance(n,e);r.push(i)}return r.length>0?js(r).pipe(on(i=>i.flat()),Js(),on(([i,a])=>this.balance.getDeltas(i,a)),this.watchGuard("balances")).subscribe(i=>{this.store.update(a=>{let s=[],o=new Map(a.map(l=>[l.collateralId,l]));return i.forEach(({id:l,balance:c})=>{let u=o.get(l);u&&(this.log.trace("balances",{id:l,balance:c}),s.push({...u,collateralBalance:c.transferable}))}),s})}):sn.EMPTY}subscribeStableswapUpdates(){return this.stableClient.getSubscriber().pipe(this.watchGuard("stableswap.updates")).subscribe(t=>{let e=new Map(t.map(n=>[n.id,n]));this.store.update(n=>{let r=[];for(let i of n){let a=e.get(i.id);a&&r.push({...i,fee:a.fee,tokens:a.tokens.filter(s=>s.id!==i.id),totalIssuance:a.totalIssuance,pegs:a.pegs,amplification:a.amplification,isRampPeriod:a.isRampPeriod})}return r})})}subscribeBalances(){return sn.EMPTY}subscribeUpdates(){let t=new sn;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var Pt=class{static get(t){switch(t.type){case"Aave":return Kt.fromPool(t);case"XYK":return Xt.fromPool(t);case"Omnipool":return Wt.fromPool(t);case"LBP":return Ht.fromPool(t);case"Stableswap":return at.fromPool(t);case"HSM":return Qt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{log as ro}from"@galacticcouncil/common";import{Subject as io,Subscription as St,takeUntil as ao}from"rxjs";var{logger:so}=ro,wt=class extends _{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=St.EMPTY;omniSub=St.EMPTY;stableSub=St.EMPTY;hsmSub=St.EMPTY;xykSub=St.EMPTY;lbpSub=St.EMPTY;isReady=!1;isDestroyed=new io;constructor(t,e){super(t),this.evm=e,this.aave=new jt(t,e),this.omnipool=new Yt(t,e),this.stableswap=new $t(t,e),this.hsm=new te(t,e,this.stableswap),this.xyk=new zt(t,e),this.lbp=new Ut(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe(ao(this.isDestroyed)).subscribe(e=>{e.forEach(n=>{this.pools.set(n.address,n)})})}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")||(so.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 n=this.clients.find(r=>r.getPoolType()===e.type);if(n)return n.getPoolFees(t,e.address);throw new Et(e.type)}};var Pr={};A(Pr,{DCA_TIME_RESERVE:()=>br,DEFAULT_BLOCK_TIME:()=>hr,DEFAULT_MIN_BUDGET:()=>mn,ORDER_MIN_BLOCK_PERIOD:()=>yr,Router:()=>vt,TWAP_EXECUTION_INTERVAL:()=>ie,TWAP_MAX_DURATION:()=>gn,TWAP_MAX_PRICE_IMPACT:()=>dn,TWAP_TX_MULTIPLIER:()=>yb,TradeOrderError:()=>pn,TradeOrderType:()=>Fe,TradeRouteBuilder:()=>G,TradeRouter:()=>tt,TradeScheduler:()=>Tt,TradeType:()=>_e});var ee=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var oo=10,ne=class{isNotVisited(t,e){let n=!0;return e.forEach(r=>{(r[0]===t[0]||r[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let r=[],i=new ee,a=[];for(a.push([e,""]),i.enqueue(a);i.size()>0;){let s=i.dequeue();if(!s||s.length>oo)continue;let o=s[s.length-1];(n===null||o[0]===n)&&r.push(s),t.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,s)){let u=[...s];u.push(c),i.enqueue(u)}})}return r}findShortestPaths(t,e,n){let r=[],i=new ee,a=[];a.push([e,""]),i.enqueue(a);let s=1/0;for(;i.size()>0;){let o=i.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===n){o.length<s?(s=o.length,r.length=0,r.push(o)):o.length===s&&r.push(o);continue}let c=t.get(l[0]);for(let u of c??[])this.isNotVisited(u,o)&&i.enqueue([...o,u])}return r}buildAndPopulateGraph(t,e){let n=new Map;for(let r of t)n.set(parseInt(r),[]);for(let[r,i,a]of e)n.get(i)?.push([a,r]);return n}};function un(p){let t={};for(let e of p){let n=e.tokens.length;for(let r=0;r<n;r++){t[e.tokens[r].id]||(t[e.tokens[r].id]=[]);for(let i=0;i<n;i++){if(r==i)continue;let a=[e.address,e.tokens[r].id,e.tokens[i].id];t[e.tokens[r].id].push(a)}}}return t}var re=class{getProposals(t,e,n){let r=n.filter(g=>g.type==="XYK"),i=n.filter(g=>g.type!=="XYK"),a=new Set(i.map(g=>g.tokens).flat().map(g=>g.id)),s=a.has(t),o=a.has(e),l=new ne,c=g=>{let f=un(g),y=Object.keys(f),S=y.flatMap(P=>f[P]);return l.buildAndPopulateGraph(y,S)};if(!s&&!o){let g=r.filter(S=>S.tokens.find(P=>P.id===t)||S.tokens.find(P=>P.id===e)),f=c(g),y=l.findPaths(f,t,e);return this.parsePaths(y)}if(s&&o){let g=c(i),f=l.findPaths(g,t,e);return this.parsePaths(f)}let u=s?e:t,d=r.filter(g=>g.tokens.some(f=>f.id===u));if(d.length===0)return[];let m=[...i,...d],h=c(m),b=l.findPaths(h,t,e);return this.parsePaths(b)}parsePaths(t){let e=[];for(let n of t){let r=[];for(let i=0;i<n.length;i++){let a=n[i],s=n[i+1];if(s==null)break;r.push(this.toEdge(a,s))}e.push(r)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var vt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new re,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,n){return`${t}->${e}::${n.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:n=[]}=this.filter,r=new Set(e),i=new Set(n);return t.filter(a=>i.has(a.type)?!1:r.size>0?r.has(a.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let n=await this.getPools();return this.validateInput(t,e,n),this.getPaths(t,e,n)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(r=>r!==t).map(r=>this.getRoutes(r,t)))).filter(r=>r.length>0).map(([r])=>r[0].assetIn).sort()}validateInput(t,e,n){if(n.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let r=this.getAssets(n);if(!r.has(t))throw new Error(t+" is not supported asset");if(!r.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(r=>r.id)).flat().sort((n,r)=>n>r?1:-1);return new Set(e)}getPaths(t,e,n){let r=this.toPoolsMap(n);return this.getProposals(t,e,n).filter(a=>this.validPath(a,r)).map(a=>this.toHops(a,r))}getProposals(t,e,n){let r=this.buildRouteKey(t,e,n);if(this.routeProposals.has(r))return this.routeProposals.get(r);let i=this.routeSuggester.getProposals(t,e,n);return this.routeProposals.set(r,i),i}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,r)=>n&&r)}validEdge([t,e,n],r){return r.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Pt.get(e)]))}toHops(t,e){return t.map(([n,r,i])=>{let a=e.get(n);return{poolAddress:n,poolId:a?.id,pool:a?.type,assetIn:r,assetOut:i}})}};import{big as E,RUNTIME_DECIMALS as xt}from"@galacticcouncil/common";var _e=(e=>(e.Buy="Buy",e.Sell="Sell",e))(_e||{}),Fe=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Fe||{}),pn=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(pn||{});var{FeeUtils:gr}=x,tt=class extends vt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,n){let r=super.validateInput(t,e,n),i=super.getPaths(t,e,n);if(!i.length)throw new kt(t,e);return{paths:i,pools:n,poolsMap:r}}async withCtx(t,e,n){let r=await super.getPools(),i=this.buildCtxSync(t,e,r);return n(i)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,r)=>{let i=n[n.length-1].amountOut,a=r[r.length-1].amountOut;return i>a?-1:1});return e.find(n=>n.every(r=>r.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(n=>n.tradeFeeRange).length>0){let n=t.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),r=t.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[n,r]}}getPoolFeeRange(t,e){let n=t.min?gr.toPct(t.min):void 0,r=t.max?gr.toPct(t.max):void 0;if(n&&r)return[n,Math.max(r,e)]}async getBestSell(t,e,n){return this.getSell(t,e,n)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,n,r){return this.withCtx(t,e,async({paths:i,poolsMap:a})=>{let s;if(r)s=await this.toSellSwaps(n,r,a);else{let o=i.map(c=>this.toSellSwaps(n,c,a)),l=await Promise.all(o);s=this.findBestSellRoute(l)}return this.buildSell(a,s)})}async getSells(t,e,n){return this.withCtx(t,e,async({paths:r,poolsMap:i})=>{let a=r.map(o=>this.toSellSwaps(n,o,i));return(await Promise.all(a)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(i,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let n=e[0],r=e[e.length-1],i=this.isDirectTrade(e),a=this.getSellSpot(e),s=r.amountOut,o=i?r.calculatedOut:this.calculateDelta0Y(n.amountIn,e,t),l=o-s,c=this.getRouteFeeRange(e),u=i?r.tradeFeePct:L.calculateSellFee(o,s),d=C.mulSpot(n.amountIn,a,n.assetInDecimals,r.assetOutDecimals),m=L.calculateDiffToRef(o,d);return{type:"Sell",amountIn:n.amountIn,amountOut:r.amountOut,spotPrice:a,tradeFee:l,tradeFeePct:u,tradeFeeRange:c,priceImpactPct:m,swaps:e,toHuman(){return{type:"Sell",amountIn:E.toDecimal(n.amountIn,n.assetInDecimals),amountOut:E.toDecimal(r.amountOut,r.assetOutDecimals),spotPrice:E.toDecimal(a,xt),tradeFee:E.toDecimal(l,r.assetOutDecimals),tradeFeePct:u,tradeFeeRange:c,priceImpactPct:m,swaps:e.map(h=>h.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,n)=>e*n/10n**BigInt(xt))}calculateDelta0Y(t,e,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],s=n.get(a.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(a.assetIn,a.assetOut),l;i>0?l=r[i-1]:l=t;let c=s.calculateOutGivenIn(o,l);r.push(c)}return r[r.length-1]}async calculateMostLiquidRoute(t,e,n){let{paths:r,pools:i,poolsMap:a}=n,l=i.filter(b=>b.tokens.some(g=>g.id===t)).map(b=>b.type==="Aave"?b.tokens:b.tokens.filter(g=>g.id===t)).map(b=>b.map(g=>g.balance).reduce((g,f)=>g+f)).sort((b,g)=>g<b?-1:1)[0],c=C.getFraction(l,.1),u=await Promise.all(r.map(b=>this.toSellSwaps(c,b,a))),m=this.findBestSellRoute(u).map(b=>({poolAddress:b.poolAddress,poolId:b?.poolId,pool:b.pool,assetIn:b.assetIn,assetOut:b.assetOut})),h=this.buildRouteKey(t,e,i);return this.mlr.set(h,m),m}async toSellSwaps(t,e,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],s=n.get(a.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(a.assetIn,a.assetOut),l;i>0?l=r[i-1].amountOut:l=typeof t=="string"?E.toBigInt(t,o.decimalsIn):t;let c=await this.ctx.getPoolFees(o,s),{amountOut:u,calculatedOut:d,feePct:m,errors:h}=s.validateAndSell(o,l,c),b=this.getPoolFeeRange(c,m),g=s.spotPriceOutGivenIn(o),f=C.mulSpot(l,g,o.decimalsIn,o.decimalsOut),y=L.calculateDiffToRef(d,f);r.push({...a,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:u,calculatedOut:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h,isSupply(){return s.type==="Aave"&&s.tokens[0].id===a.assetIn},isWithdraw(){return s.type==="Aave"&&s.tokens[1].id===a.assetIn},toHuman(){return{...a,amountIn:E.toDecimal(l,o.decimalsIn),amountOut:E.toDecimal(u,o.decimalsOut),calculatedOut:E.toDecimal(d,o.decimalsOut),spotPrice:E.toDecimal(g,xt),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h}}})}return r}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async n=>{let r=this.buildRouteKey(t,e,n.pools),i=this.mlr.get(r);return i||this.calculateMostLiquidRoute(t,e,n)})}async getSpotPrice(t,e){return this.withCtx(t,e,async n=>{let{pools:r,poolsMap:i}=n,a=this.buildRouteKey(t,e,r),s=this.mlr.get(a);s||(s=await this.calculateMostLiquidRoute(t,e,n));let o=await this.toSellSwaps("1",s,i);return{amount:this.getSellSpot(o),decimals:xt}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((n,r)=>{let i=n[0].amountIn,a=r[0].amountIn;return i>a?1:-1});return e.find(n=>n.every(r=>r.errors.length==0))||e[0]}async getBestBuy(t,e,n){return this.getBuy(t,e,n)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,n,r){return this.withCtx(t,e,async({paths:i,poolsMap:a})=>{let s;if(r)s=await this.toBuySwaps(n,r,a);else{let o=i.map(c=>this.toBuySwaps(n,c,a)),l=await Promise.all(o);s=this.findBestBuyRoute(l)}return this.buildBuy(a,s)})}async getBuys(t,e,n){return this.withCtx(t,e,async({paths:r,poolsMap:i})=>{let a=r.map(o=>this.toBuySwaps(n,o,i));return(await Promise.all(a)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(i,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let n=e[e.length-1],r=e[0],i=this.isDirectTrade(e),a=this.getBuySpot(e),s=r.amountIn,o=i?r.calculatedIn:this.calculateDelta0X(n.amountOut,e,t),l=s-o,c=this.getRouteFeeRange(e),u=i?r.tradeFeePct:L.calculateBuyFee(o,s),d=C.mulSpot(n.amountOut,a,n.assetOutDecimals,r.assetInDecimals),m;return o===0n?m=-100:m=L.calculateDiffToRef(d,o),{type:"Buy",amountOut:n.amountOut,amountIn:r.amountIn,spotPrice:a,tradeFee:l,tradeFeePct:u,tradeFeeRange:c,priceImpactPct:m,swaps:e,toHuman(){return{type:"Buy",amountOut:E.toDecimal(n.amountOut,n.assetOutDecimals),amountIn:E.toDecimal(r.amountIn,r.assetInDecimals),spotPrice:E.toDecimal(a,xt),tradeFee:E.toDecimal(l,r.assetInDecimals),tradeFeePct:u,tradeFeeRange:c,priceImpactPct:m,swaps:e.map(h=>h.toHuman())}}}}calculateDelta0X(t,e,n){let r=[];for(let i=e.length-1;i>=0;i--){let a=e[i],s=n.get(a.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(a.assetIn,a.assetOut),l;i==e.length-1?l=t:l=r[0];let c=s.calculateInGivenOut(o,l);r.unshift(c)}return r[0]}async toBuySwaps(t,e,n){let r=[];for(let i=e.length-1;i>=0;i--){let a=e[i],s=n.get(a.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(a.assetIn,a.assetOut),l;i==e.length-1?l=typeof t=="string"?E.toBigInt(t,o.decimalsOut):t:l=r[0].amountIn;let c=await this.ctx.getPoolFees(o,s),{amountIn:u,calculatedIn:d,feePct:m,errors:h}=s.validateAndBuy(o,l,c),b=this.getPoolFeeRange(c,m),g=s.spotPriceInGivenOut(o),f=C.mulSpot(l,g,o.decimalsOut,o.decimalsIn),y;d===0n?y=-100:y=L.calculateDiffToRef(f,d),r.unshift({...a,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:u,calculatedIn:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h,isSupply(){return s.type==="Aave"&&s.tokens[0].id===a.assetIn},isWithdraw(){return s.type==="Aave"&&s.tokens[1].id===a.assetIn},toHuman(){return{...a,amountOut:E.toDecimal(l,o.decimalsOut),amountIn:E.toDecimal(u,o.decimalsIn),calculatedIn:E.toDecimal(d,o.decimalsIn),spotPrice:E.toDecimal(g,xt),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h}}})}return r}};import{big as D}from"@galacticcouncil/common";var hr=6e3,mn=1000000000000000n,ie=6,dn=-5,gn=216e5,yb=3,br=.1,yr=6;import{Enum as fr}from"polkadot-api";var G=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:r,poolId:i})=>r==="Stableswap"?{pool:fr("Stableswap",i),asset_in:e,asset_out:n}:{pool:fr(r),asset_in:e,asset_out:n})}};var Tt=class{schedulerOptions;router;constructor(t,e={}){this.router=new tt(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??mn})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,r,i){let a=await this.router.getBestSell(t,e,n),{amountIn:s,swaps:o,priceImpactPct:l}=a,c=o[0],u=o[o.length-1],{assetInDecimals:d}=c,{assetOutDecimals:m}=u,h=Math.abs(l),b=await this.getMinimumOrderBudget(t,d),g=this.getOptimalTradeCount(h),f=this.getMaximumTradeCount(s,b,r),y=i||Math.min(g,f),S=Math.round(r/y),P=s/BigInt(y),w=await this.router.getBestSell(t,e,P),v=s<b,F=[];v&&F.push("OrderTooSmall");let k=w.amountOut*BigInt(y),$=this.toBlockPeriod(S),K=w.tradeFee*BigInt(y),H=G.build(o),V={assetIn:t,assetOut:e,errors:F,maxTradeCount:f,tradeCount:y,tradeFee:K,tradeImpactPct:w.priceImpactPct,tradePeriod:$,tradeRoute:H,type:"Dca"};return{...V,amountIn:s,amountOut:k,tradeAmountIn:w.amountIn,tradeAmountOut:w.amountOut,toHuman(){return{...V,amountIn:D.toDecimal(s,d),amountOut:D.toDecimal(k,m),tradeAmountIn:D.toDecimal(w.amountIn,d),tradeAmountOut:D.toDecimal(w.amountOut,m)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let n=await this.router.getSpotPrice(0,t);if(n)return C.mulSpot(this.minOrderBudget,n.amount,12,e);let r=await this.router.getSpotPrice(t,0);if(r)return C.divSpot(this.minOrderBudget,r.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,n){let r=e*2n/10n;if(r===0n)return 0;let i=Number(t/r),a=Math.floor(n/this.blockTime),s=Math.max(0,Math.floor(a*(1-.1)));return Math.min(i,s)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,n,r){let i=await this.router.getBestSell(t,e,n),{swaps:a}=i,s=a[0],o=a[a.length-1],{assetInDecimals:l}=s,{assetOutDecimals:c}=o,u=await this.getMinimumOrderBudget(t,l),d=i.amountIn<u,m=[];d&&m.push("OrderTooSmall");let h=this.toBlockPeriod(r),b=G.build(a),g={assetIn:t,assetOut:e,errors:m,maxTradeCount:0,tradeCount:0,tradeFee:i.tradeFee,tradeImpactPct:i.priceImpactPct,tradePeriod:h,tradeRoute:b,type:"Dca"};return{...g,amountIn:0n,amountOut:0n,tradeAmountIn:i.amountIn,tradeAmountOut:i.amountOut,toHuman(){return{...g,amountIn:"0",amountOut:"0",tradeAmountIn:D.toDecimal(i.amountIn,l),tradeAmountOut:D.toDecimal(i.amountOut,c)}}}}async getTwapSellOrder(t,e,n){let r=await this.router.getBestSell(t,e,n),{amountIn:i,swaps:a,priceImpactPct:s}=r,o=a[0],l=a[a.length-1],{assetInDecimals:c}=o,{assetOutDecimals:u}=l,d=Math.abs(s),m=this.getTwapTradeCount(d),h=i/BigInt(m),[b,g]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestSell(o.assetIn,l.assetOut,h)]),f=m===1,y=i<b,S=g.priceImpactPct<-5,P=[];y||f?P.push("OrderTooSmall"):S&&P.push("OrderImpactTooBig");let w=g.amountOut*BigInt(m),v=g.tradeFee*BigInt(m),F=G.build(a),k={assetIn:t,assetOut:e,errors:P,tradeCount:m,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:F,type:"TwapSell"};return{...k,amountIn:i,amountOut:w,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:v,toHuman(){return{...k,amountIn:D.toDecimal(i,c),amountOut:D.toDecimal(w,u),tradeAmountIn:D.toDecimal(g.amountIn,c),tradeAmountOut:D.toDecimal(g.amountOut,u),tradeFee:D.toDecimal(v,u)}}}}async getTwapBuyOrder(t,e,n){let r=await this.router.getBestBuy(t,e,n),{amountOut:i,swaps:a,priceImpactPct:s}=r,o=a[0],l=a[a.length-1],{assetInDecimals:c}=o,{assetOutDecimals:u}=l,d=Math.abs(s),m=this.getTwapTradeCount(d),h=i/BigInt(m),[b,g]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestBuy(o.assetIn,l.assetOut,h)]),f=g.amountIn*BigInt(m),y=m===1,S=f<b,P=g.priceImpactPct<-5,w=[];S||y?w.push("OrderTooSmall"):P&&w.push("OrderImpactTooBig");let v=g.tradeFee*BigInt(m),F=G.build(a),k={assetIn:t,assetOut:e,errors:w,tradeCount:m,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:F,type:"TwapBuy"};return{...k,amountIn:f,amountOut:i,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:v,toHuman(){return{...k,amountIn:D.toDecimal(f,c),amountOut:D.toDecimal(i,u),tradeAmountIn:D.toDecimal(g.amountIn,c),tradeAmountOut:D.toDecimal(g.amountOut,u),tradeFee:D.toDecimal(v,c)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let r=216e5/(this.blockTime*6);return Math.round(r)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,n=Math.round(e);return Math.max(n,6)}};var Or={};A(Or,{BIG_10:()=>Ir,BIG_BILL:()=>hn,StakingApi:()=>ae,StakingClient:()=>se});import{calculate_accumulated_rps as po,calculate_percentage_amount as mo,calculate_period_number as vr,calculate_points as xr,calculate_rewards as go,sigmoid as Tr}from"@galacticcouncil/math-staking";import W from"big.js";var Re={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},Sr=p=>Object.keys(Re).includes(p);import{AccountId as lo}from"polkadot-api";import{toHex as co}from"@polkadot-api/utils";import{HYDRATION_SS58_PREFIX as uo}from"@galacticcouncil/common";function wr(p){let t=("modl"+p).padEnd(32,"\0"),e=new TextEncoder().encode(t),n=co(e);return lo(uo).dec(n)}var Ce="20000000000000000",Ee="2000",Ir=W(10),hn=W(Ir.pow(12)),ae=class{client;balance;constructor(t,e){this.client=t,this.balance=e}async getPotBalance(){let t=await this.client.getPalletId(),e=wr(t);return await this.balance.getBalance(e,0)}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let r=e.created_at,i=await n.reduce(async(a,[s,o])=>{let l=await a,c=s,u=o.amount,d=o.conviction.type.toLowerCase(),m=await this.client.getReferendumInfo(c);return m&&(m.type==="Approved"||m.type==="Rejected")&&Sr(d)&&l.push({id:c,amount:u,conviction:d}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:r,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:i}}async getStake(t){let e=await this.client.getNFTCollectionId(),[n,r]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),i=r.find(a=>a)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:i,stakePosition:i?await this.getStakingPosition(i):void 0}}getCurrentActionPoints(t,e,n,r){let i=W(0),a=W(0),s=Re.locked6x,o=W(n.toString()).mul(s),l=100,c=[];t.forEach(m=>{let h=Re[m.conviction],b=r.includes(m.id.toString());b&&c.push(m.id.toString());let g=W(m.amount.toString()).mul(l).div(o);i=i.plus(Math.floor(g.mul(h).toNumber())),a=a.plus(Math.floor(g.mul(b?s:h).toNumber()))});let u=Math.floor(W(n.toString()).mul(s).mul(l).div(o).toNumber());r.forEach(m=>{c.includes(m)||(a=a.plus(u))});let d={democracyVote:1};return i=i.mul(d.democracyVote),i=i.plus(e.toString()||"0"),a=a.mul(d.democracyVote),a=a.plus(e.toString()||"0"),{currentActionPoints:i.toString(),maxActionPoints:a.toString()}}async getRewards(t,e,n){let r=await this.getStake(t),{potReservedBalance:i,accumulatedRewardPerStake:a,totalStake:s,stakePosition:o}=r;if(!o)return;let[l,c,u,d,m,h,b]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),g=W(l.transferable.toString()).minus(i.toString()),f=g.gt(0)&&s>0?po(a.toString(),g.toString(),s.toString()):a.toString(),y=vr(c.toString(),n,b),S=vr(c.toString(),o.createdAt.toString(),b),P=go(f,o.rewardPerStake.toString(),o.stake.toString()),w=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),v=xr(S,y,d.toString(),m.toString(),w.currentActionPoints,h.toString(),o.accumulatedSlashPoints.toString()),F=Tr(v,Ce,Ee),k=(()=>{if(!e.length)return;let Ot=xr(S,y,d.toString(),m.toString(),w.maxActionPoints.toString(),h.toString(),o.accumulatedSlashPoints.toString());return Tr(Ot,Ce,Ee)})(),$=W(P).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if(W(y).minus(S).lte(u.toString()))return{rewards:"0",payablePercentage:F,extraPayablePercentage:k,constants:{a:Ce,b:Ee}};let K=mo($.toString(),F),H=W(o.accumulatedLockedRewards.toString()),V=H.gt(K)?H:W(K);return{rewards:V.div(hn).toString(),maxRewards:$.div(hn).toString(),allocatedRewardsPercentage:V.div($).mul(100).toNumber(),points:v,payablePercentage:F,extraPayablePercentage:k,constants:{a:Ce,b:Ee}}}};import{Binary as Ar}from"polkadot-api";var se=class extends _{async getPalletId(){let t=this.api.constants.Staking.PalletId,e=await t();return Ar.toText(Ar.fromHex(e))}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:a})=>{let[s,o,l]=a;return{address:s,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var Fr={};A(Fr,{TxBuilderFactory:()=>At});import{Enum as _r}from"polkadot-api";function Br(p){let t=[],e=p;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var It=class extends _{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new X(t),this.aaveUtils=new nt(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:n=>this.dryRun(n,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:He})}async dryRun(t,e){let n=_r("Signed",t),r=_r("system",n),a=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(r,e.decodedCall,4),s=a.success&&!a.value.execution_result.success?a.value.execution_result.value.error:null;if(s){let o=s.type==="Module"?Br(s.value):s.type;throw new Error("Dry run execution error!",{cause:o})}return a}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var ke=class extends It{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:r}=e[0],i=await this.balance.getBalance(this.beneficiary,r);return t>=i.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,r=n[0],i=n[n.length-1],a=C.getFraction(t,this.slippagePct),s=r.assetIn,o=i.assetOut,l=t+a,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.buy({asset_in:s,asset_out:o,amount:e,max_sell_amount:l}):c=this.api.tx.Router.buy({asset_in:s,asset_out:o,amount_out:e,max_amount_in:l,route:G.build(n)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,r=n[0],i=n[n.length-1],a=C.getFraction(e,this.slippagePct),s=r.assetIn,o=i.assetOut,l=e-a,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.sell({asset_in:s,asset_out:o,amount:t,min_buy_amount:l}):c=this.api.tx.Router.sell({asset_in:s,asset_out:o,amount_in:t,min_amount_out:l,route:G.build(n)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,n=e[0],r=e[e.length-1],i=C.getFraction(t,this.slippagePct),a=n.assetIn,s=r.assetOut,o=t-i,l=this.api.tx.Router.sell_all({asset_in:a,asset_out:s,min_amount_out:o,route:G.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as bn}from"polkadot-api";var Me=class extends It{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:r,tradePeriod:i,tradeRoute:a}=this.order,s=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:bn("Sell",{asset_in:e,asset_out:n,amount_in:r,min_amount_out:0n,route:a})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(s=await this.dispatchWithExtraGas(s)),this.wrapTx("DcaSchedule",s)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:r,tradeAmountOut:i,tradePeriod:a,tradeRoute:s}=this.order,o=C.getFraction(i,this.slippagePct),l=i-o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:a,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:bn("Sell",{asset_in:e,asset_out:n,amount_in:r,min_amount_out:l,route:s})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapSell",c)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:r,tradeAmountOut:i,tradePeriod:a,tradeRoute:s}=this.order,o=C.getFraction(r,this.slippagePct),l=r+o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:a,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:bn("Buy",{asset_in:e,asset_out:n,amount_out:i,max_amount_in:l,route:s})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapBuy",c)}};var At=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new ke(this.client,this.evmClient).setTrade(t)}order(t){return new Me(this.client,this.evmClient).setOrder(t)}};async function tf(p){let t=new mt(p),e=new Dt(p),[n,r]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),i=new wt(p,e).withAave().withOmnipool().withStableswap().withXyk(),a=new X(p),s=new se(p),o=new Nt(p),l=new nt(e),c=new tt(i),u=new Tt(i,{blockTime:n,minBudgetInNative:r}),d=new ae(s,a),m=new qt(o,a,{blockTime:n});return{api:{aave:l,router:c,scheduler:u,staking:d,farm:m},client:{asset:new ot(p),balance:a,evm:e},ctx:{pool:i},tx:new At(p,e),destroy:()=>{i.destroy()}}}export{Pe as QueryBus,xn as aave,wn as api,fe as async,C as calc,Fn as client,Tn as const,tf as createSdkContext,Rn as error,Mn as evm,Yn as farm,x as fmt,Lt as json,L as math,dr as pool,Pr as sor,Or as staking,Fr as tx};
@@ -0,0 +1,7 @@
1
+ import { EvmClient } from '../evm';
2
+ import { MmOracleEntry } from './types';
3
+ export declare class MmOracleClient {
4
+ private client;
5
+ constructor(evm: EvmClient);
6
+ getData(address: string, blockTimeInSec?: number): Promise<MmOracleEntry>;
7
+ }