@galacticcouncil/sdk-next 0.40.1 → 0.41.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 (130) hide show
  1. package/build/aave/index.cjs +1 -0
  2. package/build/aave/index.mjs +1 -0
  3. package/build/client/index.cjs +1 -0
  4. package/build/client/index.mjs +1 -0
  5. package/build/evm/index.cjs +1 -0
  6. package/build/evm/index.mjs +1 -0
  7. package/build/farm/index.cjs +1 -0
  8. package/build/farm/index.mjs +1 -0
  9. package/build/pool/index.cjs +1 -0
  10. package/build/pool/index.mjs +1 -0
  11. package/build/sor/index.cjs +1 -0
  12. package/build/sor/index.mjs +1 -0
  13. package/build/staking/index.cjs +1 -0
  14. package/build/staking/index.mjs +1 -0
  15. package/build/tx/index.cjs +1 -0
  16. package/build/tx/index.mjs +1 -0
  17. package/build/utils/index.cjs +1 -0
  18. package/build/utils/index.mjs +1 -0
  19. package/package.json +57 -5
  20. /package/build/{types/aave → aave}/AaveClient.d.ts +0 -0
  21. /package/build/{types/aave → aave}/AaveUtils.d.ts +0 -0
  22. /package/build/{types/aave → aave}/abi/AavePool.d.ts +0 -0
  23. /package/build/{types/aave → aave}/abi/AavePoolDataProvider.d.ts +0 -0
  24. /package/build/{types/aave → aave}/abi/index.d.ts +0 -0
  25. /package/build/{types/aave → aave}/const.d.ts +0 -0
  26. /package/build/{types/aave → aave}/index.d.ts +0 -0
  27. /package/build/{types/aave → aave}/types.d.ts +0 -0
  28. /package/build/{types/api → api}/Papi.d.ts +0 -0
  29. /package/build/{types/api → api}/Watcher.d.ts +0 -0
  30. /package/build/{types/api → api}/index.d.ts +0 -0
  31. /package/build/{types/api → api}/probe.d.ts +0 -0
  32. /package/build/{types/api → api}/provider/index.d.ts +0 -0
  33. /package/build/{types/api → api}/provider/smoldot.d.ts +0 -0
  34. /package/build/{types/api → api}/provider/websocket.d.ts +0 -0
  35. /package/build/{types/client → client}/AssetClient.d.ts +0 -0
  36. /package/build/{types/client → client}/BalanceClient.d.ts +0 -0
  37. /package/build/{types/client → client}/ChainParams.d.ts +0 -0
  38. /package/build/{types/client → client}/index.d.ts +0 -0
  39. /package/build/{types/consts.d.ts → consts.d.ts} +0 -0
  40. /package/build/{types/errors.d.ts → errors.d.ts} +0 -0
  41. /package/build/{types/evm → evm}/adapter.d.ts +0 -0
  42. /package/build/{types/evm → evm}/chain.d.ts +0 -0
  43. /package/build/{types/evm → evm}/client.d.ts +0 -0
  44. /package/build/{types/evm → evm}/index.d.ts +0 -0
  45. /package/build/{types/evm → evm}/types.d.ts +0 -0
  46. /package/build/{types/factory.d.ts → factory.d.ts} +0 -0
  47. /package/build/{types/farm → farm}/LiquidityMiningApi.d.ts +0 -0
  48. /package/build/{types/farm → farm}/LiquidityMiningClient.d.ts +0 -0
  49. /package/build/{types/farm → farm}/MultiCurrencyContainer.d.ts +0 -0
  50. /package/build/{types/farm → farm}/RewardClaimSimulator.d.ts +0 -0
  51. /package/build/{types/farm → farm}/const.d.ts +0 -0
  52. /package/build/{types/farm → farm}/index.d.ts +0 -0
  53. /package/build/{types/farm → farm}/types.d.ts +0 -0
  54. /package/build/{types/gho → gho}/GhoTokenClient.d.ts +0 -0
  55. /package/build/{types/gho → gho}/abi.d.ts +0 -0
  56. /package/build/{types/gho → gho}/index.d.ts +0 -0
  57. /package/build/{types/index.d.ts → index.d.ts} +0 -0
  58. /package/build/{types/oracle → oracle}/MmOracleClient.d.ts +0 -0
  59. /package/build/{types/oracle → oracle}/abi.d.ts +0 -0
  60. /package/build/{types/oracle → oracle}/index.d.ts +0 -0
  61. /package/build/{types/oracle → oracle}/types.d.ts +0 -0
  62. /package/build/{types/pool → pool}/PoolClient.d.ts +0 -0
  63. /package/build/{types/pool → pool}/PoolContextProvider.d.ts +0 -0
  64. /package/build/{types/pool → pool}/PoolFactory.d.ts +0 -0
  65. /package/build/{types/pool → pool}/PoolLog.d.ts +0 -0
  66. /package/build/{types/pool → pool}/PoolStore.d.ts +0 -0
  67. /package/build/{types/pool → pool}/aave/AaveAbi.d.ts +0 -0
  68. /package/build/{types/pool → pool}/aave/AavePool.d.ts +0 -0
  69. /package/build/{types/pool → pool}/aave/AavePoolClient.d.ts +0 -0
  70. /package/build/{types/pool → pool}/aave/index.d.ts +0 -0
  71. /package/build/{types/pool → pool}/aave/types.d.ts +0 -0
  72. /package/build/{types/pool → pool}/hsm/HsmMath.d.ts +0 -0
  73. /package/build/{types/pool → pool}/hsm/HsmPool.d.ts +0 -0
  74. /package/build/{types/pool → pool}/hsm/HsmPoolClient.d.ts +0 -0
  75. /package/build/{types/pool → pool}/hsm/index.d.ts +0 -0
  76. /package/build/{types/pool → pool}/hsm/types.d.ts +0 -0
  77. /package/build/{types/pool → pool}/index.d.ts +0 -0
  78. /package/build/{types/pool → pool}/lbp/LbpMath.d.ts +0 -0
  79. /package/build/{types/pool → pool}/lbp/LbpPool.d.ts +0 -0
  80. /package/build/{types/pool → pool}/lbp/LbpPoolClient.d.ts +0 -0
  81. /package/build/{types/pool → pool}/lbp/index.d.ts +0 -0
  82. /package/build/{types/pool → pool}/omni/OmniMath.d.ts +0 -0
  83. /package/build/{types/pool → pool}/omni/OmniPool.d.ts +0 -0
  84. /package/build/{types/pool → pool}/omni/OmniPoolClient.d.ts +0 -0
  85. /package/build/{types/pool → pool}/omni/index.d.ts +0 -0
  86. /package/build/{types/pool → pool}/omni/types.d.ts +0 -0
  87. /package/build/{types/pool → pool}/stable/StableMath.d.ts +0 -0
  88. /package/build/{types/pool → pool}/stable/StableSwap.d.ts +0 -0
  89. /package/build/{types/pool → pool}/stable/StableSwapClient.d.ts +0 -0
  90. /package/build/{types/pool → pool}/stable/index.d.ts +0 -0
  91. /package/build/{types/pool → pool}/stable/types.d.ts +0 -0
  92. /package/build/{types/pool → pool}/types.d.ts +0 -0
  93. /package/build/{types/pool → pool}/xyk/XykMath.d.ts +0 -0
  94. /package/build/{types/pool → pool}/xyk/XykPool.d.ts +0 -0
  95. /package/build/{types/pool → pool}/xyk/XykPoolClient.d.ts +0 -0
  96. /package/build/{types/pool → pool}/xyk/index.d.ts +0 -0
  97. /package/build/{types/sor → sor}/Router.d.ts +0 -0
  98. /package/build/{types/sor → sor}/TradeRouteBuilder.d.ts +0 -0
  99. /package/build/{types/sor → sor}/TradeRouter.d.ts +0 -0
  100. /package/build/{types/sor → sor}/TradeScheduler.d.ts +0 -0
  101. /package/build/{types/sor → sor}/const.d.ts +0 -0
  102. /package/build/{types/sor → sor}/index.d.ts +0 -0
  103. /package/build/{types/sor → sor}/route/bfs.d.ts +0 -0
  104. /package/build/{types/sor → sor}/route/graph.d.ts +0 -0
  105. /package/build/{types/sor → sor}/route/index.d.ts +0 -0
  106. /package/build/{types/sor → sor}/route/suggester.d.ts +0 -0
  107. /package/build/{types/sor → sor}/types.d.ts +0 -0
  108. /package/build/{types/staking → staking}/StakingApi.d.ts +0 -0
  109. /package/build/{types/staking → staking}/StakingClient.d.ts +0 -0
  110. /package/build/{types/staking → staking}/index.d.ts +0 -0
  111. /package/build/{types/staking → staking}/types.d.ts +0 -0
  112. /package/build/{types/staking → staking}/utils.d.ts +0 -0
  113. /package/build/{types/tx → tx}/OrderTxBuilder.d.ts +0 -0
  114. /package/build/{types/tx → tx}/TradeTxBuilder.d.ts +0 -0
  115. /package/build/{types/tx → tx}/TxBuilder.d.ts +0 -0
  116. /package/build/{types/tx → tx}/TxBuilderFactory.d.ts +0 -0
  117. /package/build/{types/tx → tx}/index.d.ts +0 -0
  118. /package/build/{types/tx → tx}/types.d.ts +0 -0
  119. /package/build/{types/tx → tx}/utils.d.ts +0 -0
  120. /package/build/{types/types.d.ts → types.d.ts} +0 -0
  121. /package/build/{types/utils → utils}/QueryBus.d.ts +0 -0
  122. /package/build/{types/utils → utils}/Queue.d.ts +0 -0
  123. /package/build/{types/utils → utils}/Stack.d.ts +0 -0
  124. /package/build/{types/utils → utils}/async.d.ts +0 -0
  125. /package/build/{types/utils → utils}/calc.d.ts +0 -0
  126. /package/build/{types/utils → utils}/format.d.ts +0 -0
  127. /package/build/{types/utils → utils}/index.d.ts +0 -0
  128. /package/build/{types/utils → utils}/json.d.ts +0 -0
  129. /package/build/{types/utils → utils}/math.d.ts +0 -0
  130. /package/build/{types/utils → utils}/traversal/bfs.d.ts +0 -0
@@ -0,0 +1 @@
1
+ "use strict";var K=Object.create;var D=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty;var te=(l,e)=>{for(var t in e)D(l,t,{get:e[t],enumerable:!0})},U=(l,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Q(e))!ee.call(l,n)&&n!==t&&D(l,n,{get:()=>e[n],enumerable:!(r=J(e,n))||r.enumerable});return l};var ne=(l,e,t)=>(t=l!=null?K(Z(l)):{},U(e||!l||!l.__esModule?D(t,"default",{value:l,enumerable:!0}):t,l)),ae=l=>U(D({},"__esModule",{value:!0}),l);var le={};te(le,{AAVE_GAS_LIMIT:()=>re,AAVE_LENDING_POOL_ADDRESS:()=>P,AAVE_POOL_ABI:()=>S,AAVE_POOL_DATA_PROVIDER:()=>B,AAVE_POOL_DATA_PROVIDER_ABI:()=>C,AAVE_POOL_PROXY:()=>M,AAVE_ROUNDING_THRESHOLD:()=>ge,AAVE_UINT_256_MAX:()=>ie,AaveClient:()=>I,AaveUtils:()=>k});module.exports=ae(le);var S=[{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 C=[{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 M="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",B="0x112b087b60C1a166130d59266363C45F8aa99db0",P="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",re=1000000n,ge=5,ie=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var I=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:C,address:B,args:[P],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:C,address:B,args:[P,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:S,address:M,args:[e],functionName:"getUserAccountData"})}};var s=ne(require("big.js")),f=require("@galacticcouncil/common");var{ERC20:w}=f.erc20,{H160:O}=f.h160,se=1.01,oe=31536000n,F=4,E=-1,_=10n**27n,k=class{client;constructor(e){this.client=new I(e)}async getSummary(e){let t=O.fromAny(e),[r,n,a,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[o]=r,[p,d]=n,[y,m,u,A,T,g]=a,b=f.big.toDecimal(g,18),h=[];for(let v of p){let R=v.underlyingAsset.toLowerCase(),c=o.find(({underlyingAsset:z})=>z.toLowerCase()===R);if(!c)throw new Error("Missing pool reserve for "+R);let L=v.scaledATokenBalance,x=c.liquidityIndex,q=c.liquidityRate,N=c.availableLiquidity,V=c.priceInMarketReferenceCurrency,W=i+6,H=this.calculateLinearInterest(q,c.lastUpdateTimestamp,W),$=x*H/_,G=L*$/_,Y=Number(d!==0&&d===c.eModeCategoryId?c.eModeLiquidationThreshold:c.reserveLiquidationThreshold)/1e4,X=c.usageAsCollateralEnabled&&v.usageAsCollateralEnabledOnUser&&v.scaledATokenBalance>0n,j=w.toAssetId(R);h.push({aTokenBalance:G,availableLiquidity:N,decimals:Number(c.decimals),isCollateral:X,priceInRef:V,reserveId:j,reserveAsset:R,reserveLiquidationThreshold:Y})}return{healthFactor:Number(b),currentLiquidationThreshold:Number(f.big.toDecimal(A,F)),totalCollateral:y,totalDebt:m,reserves:h}}async hasBorrowPositions(e){let t=O.fromAny(e),r=await this.client.getUserAccountData(t),[n,a]=r;return a>0n}async getHealthFactor(e){let t=O.fromAny(e),r=await this.client.getUserAccountData(t),[n,a,i,o,p,d]=r;return this.calculateHealthFactorFromBalances(a,n,o)}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:n,totalDebt:a,reserves:i,currentLiquidationThreshold:o}=await this.getSummary(e);if(a===0n)return E;let p=w.fromAssetId(t),d=i.find(R=>R.reserveAsset===p);if(!d)throw new Error("Missing reserve ctx for "+p);let{decimals:y,isCollateral:m,priceInRef:u,reserveLiquidationThreshold:A}=d,T=f.big.toBigInt(r,y),g=m?T*u/10n**BigInt(y):0n,b=n-g;if(b<=0n)return 0;let h=(0,s.default)(n.toString()).mul(o).minus((0,s.default)(g.toString()).mul(A)).div(b.toString()),v=(0,s.default)(b.toString()).mul(h).div(a.toString()).toFixed(6,s.default.roundDown);return Number(v)}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:n,totalDebt:a,reserves:i,currentLiquidationThreshold:o}=await this.getSummary(e);if(a===0n)return E;let p=w.fromAssetId(t),d=i.find(v=>v.reserveAsset===p);if(!d)throw new Error("Missing reserve ctx for "+p);let{decimals:y,priceInRef:m,reserveLiquidationThreshold:u}=d,T=f.big.toBigInt(r,y)*m/10n**BigInt(y),g=n+T;if(g<=0n)return 0;let b=(0,s.default)(n.toString()).mul(o).plus((0,s.default)(T.toString()).mul(u)).div(g.toString()),h=(0,s.default)(g.toString()).mul(b).div(a.toString()).toFixed(6,s.default.roundDown);return Number(h)}async getHealthFactorAfterSwap(e,t,r,n,a){let{totalDebt:i,reserves:o,healthFactor:p}=await this.getSummary(e);if(i===0n)return E;let d=w.fromAssetId(r),y=w.fromAssetId(a),m=o.find(x=>x.reserveAsset===d),u=o.find(x=>x.reserveAsset===y);if(!m)throw new Error(`Missing reserve ctx for ${d}`);if(!u)throw new Error(`Missing reserve ctx for ${u}`);let A=f.big.toBigInt(t,m.decimals),T=f.big.toBigInt(n,u.decimals),g=A*m.priceInRef/10n**BigInt(m.decimals),b=T*u.priceInRef/10n**BigInt(u.decimals),h=m.isCollateral?(0,s.default)(g.toString()).mul(m.reserveLiquidationThreshold):(0,s.default)(0),c=(u.isCollateral?(0,s.default)(b.toString()).mul(u.reserveLiquidationThreshold):(0,s.default)(0)).minus(h).div(i.toString()),L=(0,s.default)(p).plus(c).toFixed(6,s.default.roundDown);return Number(L)}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:n,healthFactor:a}=await this.getSummary(e),i=w.fromAssetId(t),o=n.find(p=>p.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(o,r,a)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:n}=await this.getSummary(e),a={};for(let i of r){let o=this.calculateWithdrawMax(i,t,n);i.reserveId&&(a[i.reserveId]=o)}return a}calculateWithdrawMax(e,t,r){let{aTokenBalance:n,availableLiquidity:a,decimals:i,priceInRef:o,reserveLiquidationThreshold:p,isCollateral:d}=e,y=n;if(d&&t>0n){let u=r-se;if(u>0){let A=(0,s.default)(u).mul(t.toString()).div(p).toFixed(0,s.default.roundDown),T=(0,s.default)(A).div(o.toString()).mul(10**i).toFixed(0,s.default.roundDown);y=n<BigInt(T)?n:BigInt(T)}else y=0n}return{amount:y<a?y:a,decimals:i}}calculateLinearInterest(e,t,r){let n=r-t;if(n<=0)return _;let a=e*BigInt(n)/oe;return _+a}calculateHealthFactorFromBalances(e,t,r){if(e===0n)return E;let n=t*r/e,a=f.big.toDecimal(n,F);return Number(a)}};0&&(module.exports={AAVE_GAS_LIMIT,AAVE_LENDING_POOL_ADDRESS,AAVE_POOL_ABI,AAVE_POOL_DATA_PROVIDER,AAVE_POOL_DATA_PROVIDER_ABI,AAVE_POOL_PROXY,AAVE_ROUNDING_THRESHOLD,AAVE_UINT_256_MAX,AaveClient,AaveUtils});
@@ -0,0 +1 @@
1
+ import j from"buffer";typeof window<"u"&&(window.Buffer=j.Buffer);var L=[{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 B=[{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 S="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",P="0x112b087b60C1a166130d59266363C45F8aa99db0",E="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",pe=1000000n,de=5,ye=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var x=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:B,address:P,args:[E],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:B,address:P,args:[E,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:L,address:S,args:[e],functionName:"getUserAccountData"})}};import s from"big.js";import{big as h,erc20 as z,h160 as K}from"@galacticcouncil/common";var{ERC20:w}=z,{H160:_}=K,J=1.01,Q=31536000n,M=4,I=-1,D=10n**27n,O=class{client;constructor(e){this.client=new x(e)}async getSummary(e){let t=_.fromAny(e),[r,n,a,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[o]=r,[u,p]=n,[d,y,l,b,c,f]=a,T=h.toDecimal(f,18),v=[];for(let g of u){let A=g.underlyingAsset.toLowerCase(),m=o.find(({underlyingAsset:X})=>X.toLowerCase()===A);if(!m)throw new Error("Missing pool reserve for "+A);let C=g.scaledATokenBalance,R=m.liquidityIndex,U=m.liquidityRate,F=m.availableLiquidity,q=m.priceInMarketReferenceCurrency,N=i+6,V=this.calculateLinearInterest(U,m.lastUpdateTimestamp,N),W=R*V/D,H=C*W/D,$=Number(p!==0&&p===m.eModeCategoryId?m.eModeLiquidationThreshold:m.reserveLiquidationThreshold)/1e4,G=m.usageAsCollateralEnabled&&g.usageAsCollateralEnabledOnUser&&g.scaledATokenBalance>0n,Y=w.toAssetId(A);v.push({aTokenBalance:H,availableLiquidity:F,decimals:Number(m.decimals),isCollateral:G,priceInRef:q,reserveId:Y,reserveAsset:A,reserveLiquidationThreshold:$})}return{healthFactor:Number(T),currentLiquidationThreshold:Number(h.toDecimal(b,M)),totalCollateral:d,totalDebt:y,reserves:v}}async hasBorrowPositions(e){let t=_.fromAny(e),r=await this.client.getUserAccountData(t),[n,a]=r;return a>0n}async getHealthFactor(e){let t=_.fromAny(e),r=await this.client.getUserAccountData(t),[n,a,i,o,u,p]=r;return this.calculateHealthFactorFromBalances(a,n,o)}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:n,totalDebt:a,reserves:i,currentLiquidationThreshold:o}=await this.getSummary(e);if(a===0n)return I;let u=w.fromAssetId(t),p=i.find(A=>A.reserveAsset===u);if(!p)throw new Error("Missing reserve ctx for "+u);let{decimals:d,isCollateral:y,priceInRef:l,reserveLiquidationThreshold:b}=p,c=h.toBigInt(r,d),f=y?c*l/10n**BigInt(d):0n,T=n-f;if(T<=0n)return 0;let v=s(n.toString()).mul(o).minus(s(f.toString()).mul(b)).div(T.toString()),g=s(T.toString()).mul(v).div(a.toString()).toFixed(6,s.roundDown);return Number(g)}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:n,totalDebt:a,reserves:i,currentLiquidationThreshold:o}=await this.getSummary(e);if(a===0n)return I;let u=w.fromAssetId(t),p=i.find(g=>g.reserveAsset===u);if(!p)throw new Error("Missing reserve ctx for "+u);let{decimals:d,priceInRef:y,reserveLiquidationThreshold:l}=p,c=h.toBigInt(r,d)*y/10n**BigInt(d),f=n+c;if(f<=0n)return 0;let T=s(n.toString()).mul(o).plus(s(c.toString()).mul(l)).div(f.toString()),v=s(f.toString()).mul(T).div(a.toString()).toFixed(6,s.roundDown);return Number(v)}async getHealthFactorAfterSwap(e,t,r,n,a){let{totalDebt:i,reserves:o,healthFactor:u}=await this.getSummary(e);if(i===0n)return I;let p=w.fromAssetId(r),d=w.fromAssetId(a),y=o.find(R=>R.reserveAsset===p),l=o.find(R=>R.reserveAsset===d);if(!y)throw new Error(`Missing reserve ctx for ${p}`);if(!l)throw new Error(`Missing reserve ctx for ${l}`);let b=h.toBigInt(t,y.decimals),c=h.toBigInt(n,l.decimals),f=b*y.priceInRef/10n**BigInt(y.decimals),T=c*l.priceInRef/10n**BigInt(l.decimals),v=y.isCollateral?s(f.toString()).mul(y.reserveLiquidationThreshold):s(0),m=(l.isCollateral?s(T.toString()).mul(l.reserveLiquidationThreshold):s(0)).minus(v).div(i.toString()),C=s(u).plus(m).toFixed(6,s.roundDown);return Number(C)}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:n,healthFactor:a}=await this.getSummary(e),i=w.fromAssetId(t),o=n.find(u=>u.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(o,r,a)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:n}=await this.getSummary(e),a={};for(let i of r){let o=this.calculateWithdrawMax(i,t,n);i.reserveId&&(a[i.reserveId]=o)}return a}calculateWithdrawMax(e,t,r){let{aTokenBalance:n,availableLiquidity:a,decimals:i,priceInRef:o,reserveLiquidationThreshold:u,isCollateral:p}=e,d=n;if(p&&t>0n){let l=r-J;if(l>0){let b=s(l).mul(t.toString()).div(u).toFixed(0,s.roundDown),c=s(b).div(o.toString()).mul(10**i).toFixed(0,s.roundDown);d=n<BigInt(c)?n:BigInt(c)}else d=0n}return{amount:d<a?d:a,decimals:i}}calculateLinearInterest(e,t,r){let n=r-t;if(n<=0)return D;let a=e*BigInt(n)/Q;return D+a}calculateHealthFactorFromBalances(e,t,r){if(e===0n)return I;let n=t*r/e,a=h.toDecimal(n,M);return Number(a)}};export{pe as AAVE_GAS_LIMIT,E as AAVE_LENDING_POOL_ADDRESS,L as AAVE_POOL_ABI,P as AAVE_POOL_DATA_PROVIDER,B as AAVE_POOL_DATA_PROVIDER_ABI,S as AAVE_POOL_PROXY,de as AAVE_ROUNDING_THRESHOLD,ye as AAVE_UINT_256_MAX,x as AaveClient,O as AaveUtils};
@@ -0,0 +1 @@
1
+ "use strict";var E=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var L=Object.prototype.hasOwnProperty;var I=(p,e)=>{for(var t in e)E(p,t,{get:e[t],enumerable:!0})},R=(p,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of O(e))!L.call(p,n)&&n!==t&&E(p,n,{get:()=>e[n],enumerable:!(s=D(e,n))||s.enumerable});return p};var N=p=>R(E({},"__esModule",{value:!0}),p);var Q={};I(Q,{AssetClient:()=>S,BalanceClient:()=>k,ChainParams:()=>x});module.exports=N(Q);var P=require("@galacticcouncil/descriptors");var v=require("@galacticcouncil/common"),w=require("rxjs");var b=require("rxjs"),c=require("rxjs/operators");function M(p,{intervalMs:e=5e3,rpcTimeoutMs:t=1e4}={}){let s=()=>(0,b.defer)(()=>(0,b.from)(p._request("system_health",[]))).pipe((0,c.timeout)({first:t}),(0,c.map)(()=>"online"),(0,c.catchError)(()=>(0,b.of)("offline")));return(0,b.of)({state:"offline",delayMs:0}).pipe((0,c.expand)(a=>(0,b.timer)(a.delayMs).pipe((0,c.switchMap)(s),(0,c.map)(r=>({state:r,delayMs:e})))),(0,c.skip)(1),(0,c.map)(a=>a.state),(0,c.distinctUntilChanged)(),(0,c.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:H}=v.log,T=class p{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(e){this.bestBlock$=this.watched("watcher(bestBlock)",e.getUnsafeApi().query.System.Number.watchValue("best")),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",e.finalizedBlock$),this.connection$=this.watched("watcher(connection)",M(e))}static getInstance(e){return this.instance||(this.instance=new p(e)),this.instance}watched(e,t){return t.pipe((0,w.tap)({error:s=>H.error(e,s)}),(0,w.shareReplay)({bufferSize:1,refCount:!0}))}};var h=class{client;api;apiNext;watcher;constructor(e){this.client=e,this.api=this.client.getTypedApi(P.hydration),this.apiNext=this.client.getTypedApi(P.hydrationNext),this.watcher=T.getInstance(this.client)}};var V=require("polkadot-api/ws-provider"),W=require("polkadot-api/logs-provider"),z=require("@polkadot-api/legacy-provider");var $=require("polkadot-api/sm-provider");var S=class extends h{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async queryShares(){let t=await this.api.query.Stableswap.Pools.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryBonds(){let t=await this.api.query.Bonds.Bonds.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryAssets(){let t=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(t.filter(({value:s})=>{let{asset_type:n}=s;return this.SUPPORTED_TYPES.includes(n.type)}).map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryAssetLocations(){let t=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async mapToken(e,t,s,n){let{name:a,asset_type:r,is_sufficient:i,existential_deposit:m}=t,{symbol:l,decimals:u}=s.get(e)??{};return{id:e,name:a?.asText(),symbol:l,decimals:u,icon:l,type:r.type,isSufficient:i,location:n,existentialDeposit:m}}async mapBond(e,t,s,n){let[a,r]=n,{asset_type:i,is_sufficient:m,existential_deposit:l}=t,{symbol:u,decimals:A}=await this.mapToken(a,t,s),f=Number(r),y=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",y.format(f)].join(" ");return{id:e,name:g,symbol:u+"b",decimals:A,icon:u,type:i.type,isSufficient:m,existentialDeposit:l,underlyingAssetId:a,maturity:f}}async mapShares(e,t,s,n){let{assets:a}=n,{name:r,symbol:i,asset_type:m,is_sufficient:l,existential_deposit:u}=t,A=await Promise.all(a.map(async g=>{let{symbol:_}=await this.mapToken(g,t,s);return[g,_]})),f=Object.fromEntries(A),y=Object.values(f);return{id:e,name:y.join(", "),symbol:i?.asText()||r?.asText(),decimals:18,icon:y.join("/"),type:m.type,isSufficient:l,existentialDeposit:u,meta:f}}async mapExternal(e,t,s,n){let a=await this.mapToken(e,t,new Map,n),r=s?.find(i=>i.internalId===a.id);return r?{...a,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.isWhiteListed}:a}parseMetadata(e){return new Map(Array.from(e,([t,s])=>[t,{symbol:s.symbol?.asText(),decimals:s.decimals}]))}async getSupported(e,t){let[s,n,a,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),i=this.parseMetadata(s),m=[];for(let[l,u]of Array.from(s)){let A=n.get(l),{asset_type:f}=u,y;switch(f.type){case"Bond":let g=r.get(l);y=await this.mapBond(l,u,i,g);break;case"StableSwap":let _=a.get(l);y=await this.mapShares(l,u,i,_);break;case"External":y=await this.mapExternal(l,u,t,A);break;default:y=await this.mapToken(l,u,i,A)}m.push(y)}return e?m:m.filter(l=>this.isValidAsset(l))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};var q=require("@galacticcouncil/common"),d=require("rxjs"),o=require("rxjs/operators");var{logger:B}=q.log,k=class extends h{erc20Ids=null;constructor(e){super(e)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:s}=await t.getValue(e,{at:"best"});return this.getBreakdown(s)}async getTokenBalance(e,t){let n=await this.api.query.Tokens.Accounts.getValue(e,t,{at:"best"});return this.getBreakdown(n)}async getErc20Balance(e,t){return this.getBalanceData(e,t)}watchBalance(e){return(0,d.defer)(()=>{let t=this.watchSystemBalance(e),s=this.watchTokensBalance(e),n=this.watchErc20Balance(e);return(0,d.combineLatest)([t,s,n]).pipe((0,o.connect)(a=>(0,d.concat)(a.pipe((0,o.take)(1)),a.pipe((0,o.skip)(1),(0,o.debounceTime)(250)))))}).pipe((0,o.map)(t=>t.flat()),(0,o.startWith)([]),(0,o.bufferCount)(2,1),(0,o.map)(([t,s],n)=>n===0?s:this.getDeltas(t,s))).pipe((0,o.tap)({subscribe:()=>B.debug("balance: subscribe",e),error:t=>B.error("balance",t)}),(0,o.retry)({delay:1e3}))}watchSystemBalance(e){let t=this.api.query.System.Account;return(0,d.defer)(()=>t.watchValue(e,"best")).pipe((0,o.map)(s=>({id:0,balance:this.getBreakdown(s.data)})),(0,o.tap)({error:s=>B.error("balance(system)",s)}))}watchTokenBalance(e,t){let s=this.api.query.Tokens.Accounts;return(0,d.defer)(()=>s.watchValue(e,t,"best")).pipe((0,o.map)(n=>({id:t,balance:this.getBreakdown(n)})),(0,o.tap)({error:n=>B.error("balance(token)",n)}))}watchTokensBalance(e){let t=this.api.query.Tokens.Accounts;return(0,d.defer)(()=>t.watchEntries(e,{at:"best"})).pipe((0,o.distinctUntilChanged)((s,n)=>!n.deltas),(0,o.map)(({deltas:s})=>{let n=[];return s?.deleted.forEach(a=>{let[r,i]=a.args;n.push({id:i,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),s?.upserted.forEach(a=>{let[r,i]=a.args;n.push({id:i,balance:this.getBreakdown(a.value)})}),n}),(0,o.tap)({error:s=>B.error("balance(tokens)",s)}))}watchErc20Balance(e,t){let s=async()=>{if(this.erc20Ids)return this.erc20Ids;let a=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=a.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[i]=r;return i}),this.erc20Ids},n=async a=>(await Promise.all(a.map(async i=>[i,await this.getBalanceData(e,i)]))).map(([i,m])=>({id:i,balance:m}));return(0,d.defer)(()=>(0,d.from)(t?Promise.resolve(t):s()).pipe((0,o.switchMap)(a=>this.watcher.bestBlock$.pipe((0,o.switchMap)(()=>(0,d.from)(n(a))))),(0,o.startWith)([]),(0,o.bufferCount)(2,1),(0,o.map)(([a,r],i)=>i===0?r.filter(m=>m.balance.total>0n):this.getDeltas(a,r)),(0,o.distinctUntilChanged)((a,r)=>r.length===0),(0,o.tap)({error:a=>B.error("balance(erc20)",a)})))}async getBalanceData(e,t){let s=await this.api.apis.CurrenciesApi.account(t,e,{at:"best"});return this.getBreakdown(s)}getBreakdown(e){let t=e.free>=e.frozen?e.free-e.frozen:0n,s=e.free+e.reserved;return{free:e.free,reserved:e.reserved,frozen:e.frozen,total:s,transferable:t}}getDeltas(e,t){let s=(a,r)=>a!==void 0&&r!==void 0&&a.transferable===r.transferable&&a.total===r.total,n=e.reduce((a,r)=>(a.set(r.id,r.balance),a),new Map);return t.filter(a=>!s(a.balance,n.get(a.id)))}};var x=class extends h{_minOrderBudget;_blockTime;constructor(e){super(e)}async getBlockTime(){if(this._blockTime===void 0){let e=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(e)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};0&&(module.exports={AssetClient,BalanceClient,ChainParams});
@@ -0,0 +1 @@
1
+ import O from"buffer";typeof window<"u"&&(window.Buffer=O.Buffer);import{hydration as G,hydrationNext as X}from"@galacticcouncil/descriptors";import{log as U}from"@galacticcouncil/common";import{shareReplay as Y,tap as j}from"rxjs";import{defer as L,from as I,of as x,timer as R}from"rxjs";import{catchError as N,distinctUntilChanged as H,expand as V,map as T,shareReplay as W,skip as z,switchMap as $,timeout as Q}from"rxjs/operators";function _(u,{intervalMs:e=5e3,rpcTimeoutMs:t=1e4}={}){let s=()=>L(()=>I(u._request("system_health",[]))).pipe(Q({first:t}),T(()=>"online"),N(()=>x("offline")));return x({state:"offline",delayMs:0}).pipe(V(a=>R(a.delayMs).pipe($(s),T(r=>({state:r,delayMs:e})))),z(1),T(a=>a.state),H(),W({bufferSize:1,refCount:!0}))}var{logger:F}=U,B=class u{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(e){this.bestBlock$=this.watched("watcher(bestBlock)",e.getUnsafeApi().query.System.Number.watchValue("best")),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",e.finalizedBlock$),this.connection$=this.watched("watcher(connection)",_(e))}static getInstance(e){return this.instance||(this.instance=new u(e)),this.instance}watched(e,t){return t.pipe(j({error:s=>F.error(e,s)}),Y({bufferSize:1,refCount:!0}))}};var m=class{client;api;apiNext;watcher;constructor(e){this.client=e,this.api=this.client.getTypedApi(G),this.apiNext=this.client.getTypedApi(X),this.watcher=B.getInstance(this.client)}};import{getWsProvider as Te}from"polkadot-api/ws-provider";import{withLogsRecorder as Se}from"polkadot-api/logs-provider";import{withLegacy as xe}from"@polkadot-api/legacy-provider";import{getSmProvider as ve}from"polkadot-api/sm-provider";var P=class extends m{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async queryShares(){let t=await this.api.query.Stableswap.Pools.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryBonds(){let t=await this.api.query.Bonds.Bonds.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryAssets(){let t=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(t.filter(({value:s})=>{let{asset_type:n}=s;return this.SUPPORTED_TYPES.includes(n.type)}).map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async queryAssetLocations(){let t=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(t.map(({keyArgs:s,value:n})=>{let[a]=s;return[a,n]}))}async mapToken(e,t,s,n){let{name:a,asset_type:r,is_sufficient:o,existential_deposit:c}=t,{symbol:i,decimals:l}=s.get(e)??{};return{id:e,name:a?.asText(),symbol:i,decimals:l,icon:i,type:r.type,isSufficient:o,location:n,existentialDeposit:c}}async mapBond(e,t,s,n){let[a,r]=n,{asset_type:o,is_sufficient:c,existential_deposit:i}=t,{symbol:l,decimals:y}=await this.mapToken(a,t,s),d=Number(r),p=new Intl.DateTimeFormat("en-GB"),b=[l,"Bond",p.format(d)].join(" ");return{id:e,name:b,symbol:l+"b",decimals:y,icon:l,type:o.type,isSufficient:c,existentialDeposit:i,underlyingAssetId:a,maturity:d}}async mapShares(e,t,s,n){let{assets:a}=n,{name:r,symbol:o,asset_type:c,is_sufficient:i,existential_deposit:l}=t,y=await Promise.all(a.map(async b=>{let{symbol:w}=await this.mapToken(b,t,s);return[b,w]})),d=Object.fromEntries(y),p=Object.values(d);return{id:e,name:p.join(", "),symbol:o?.asText()||r?.asText(),decimals:18,icon:p.join("/"),type:c.type,isSufficient:i,existentialDeposit:l,meta:d}}async mapExternal(e,t,s,n){let a=await this.mapToken(e,t,new Map,n),r=s?.find(o=>o.internalId===a.id);return r?{...a,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.isWhiteListed}:a}parseMetadata(e){return new Map(Array.from(e,([t,s])=>[t,{symbol:s.symbol?.asText(),decimals:s.decimals}]))}async getSupported(e,t){let[s,n,a,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),o=this.parseMetadata(s),c=[];for(let[i,l]of Array.from(s)){let y=n.get(i),{asset_type:d}=l,p;switch(d.type){case"Bond":let b=r.get(i);p=await this.mapBond(i,l,o,b);break;case"StableSwap":let w=a.get(i);p=await this.mapShares(i,l,o,w);break;case"External":p=await this.mapExternal(i,l,t,y);break;default:p=await this.mapToken(i,l,o,y)}c.push(p)}return e?c:c.filter(i=>this.isValidAsset(i))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};import{log as J}from"@galacticcouncil/common";import{combineLatest as K,concat as Z,defer as A,from as M}from"rxjs";import{bufferCount as v,distinctUntilChanged as C,debounceTime as ee,map as h,retry as te,startWith as q,switchMap as D,tap as g,take as se,skip as ae,connect as ne}from"rxjs/operators";var{logger:f}=J,S=class extends m{erc20Ids=null;constructor(e){super(e)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:s}=await t.getValue(e,{at:"best"});return this.getBreakdown(s)}async getTokenBalance(e,t){let n=await this.api.query.Tokens.Accounts.getValue(e,t,{at:"best"});return this.getBreakdown(n)}async getErc20Balance(e,t){return this.getBalanceData(e,t)}watchBalance(e){return A(()=>{let t=this.watchSystemBalance(e),s=this.watchTokensBalance(e),n=this.watchErc20Balance(e);return K([t,s,n]).pipe(ne(a=>Z(a.pipe(se(1)),a.pipe(ae(1),ee(250)))))}).pipe(h(t=>t.flat()),q([]),v(2,1),h(([t,s],n)=>n===0?s:this.getDeltas(t,s))).pipe(g({subscribe:()=>f.debug("balance: subscribe",e),error:t=>f.error("balance",t)}),te({delay:1e3}))}watchSystemBalance(e){let t=this.api.query.System.Account;return A(()=>t.watchValue(e,"best")).pipe(h(s=>({id:0,balance:this.getBreakdown(s.data)})),g({error:s=>f.error("balance(system)",s)}))}watchTokenBalance(e,t){let s=this.api.query.Tokens.Accounts;return A(()=>s.watchValue(e,t,"best")).pipe(h(n=>({id:t,balance:this.getBreakdown(n)})),g({error:n=>f.error("balance(token)",n)}))}watchTokensBalance(e){let t=this.api.query.Tokens.Accounts;return A(()=>t.watchEntries(e,{at:"best"})).pipe(C((s,n)=>!n.deltas),h(({deltas:s})=>{let n=[];return s?.deleted.forEach(a=>{let[r,o]=a.args;n.push({id:o,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),s?.upserted.forEach(a=>{let[r,o]=a.args;n.push({id:o,balance:this.getBreakdown(a.value)})}),n}),g({error:s=>f.error("balance(tokens)",s)}))}watchErc20Balance(e,t){let s=async()=>{if(this.erc20Ids)return this.erc20Ids;let a=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=a.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[o]=r;return o}),this.erc20Ids},n=async a=>(await Promise.all(a.map(async o=>[o,await this.getBalanceData(e,o)]))).map(([o,c])=>({id:o,balance:c}));return A(()=>M(t?Promise.resolve(t):s()).pipe(D(a=>this.watcher.bestBlock$.pipe(D(()=>M(n(a))))),q([]),v(2,1),h(([a,r],o)=>o===0?r.filter(c=>c.balance.total>0n):this.getDeltas(a,r)),C((a,r)=>r.length===0),g({error:a=>f.error("balance(erc20)",a)})))}async getBalanceData(e,t){let s=await this.api.apis.CurrenciesApi.account(t,e,{at:"best"});return this.getBreakdown(s)}getBreakdown(e){let t=e.free>=e.frozen?e.free-e.frozen:0n,s=e.free+e.reserved;return{free:e.free,reserved:e.reserved,frozen:e.frozen,total:s,transferable:t}}getDeltas(e,t){let s=(a,r)=>a!==void 0&&r!==void 0&&a.transferable===r.transferable&&a.total===r.total,n=e.reduce((a,r)=>(a.set(r.id,r.balance),a),new Map);return t.filter(a=>!s(a.balance,n.get(a.id)))}};var k=class extends m{_minOrderBudget;_blockTime;constructor(e){super(e)}async getBlockTime(){if(this._blockTime===void 0){let e=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(e)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};export{P as AssetClient,S as BalanceClient,k as ChainParams};
@@ -0,0 +1 @@
1
+ "use strict";var d=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var P=Object.getOwnPropertyNames;var k=Object.prototype.hasOwnProperty;var w=(i,t)=>{for(var e in t)d(i,e,{get:t[e],enumerable:!0})},v=(i,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of P(t))!k.call(i,r)&&r!==e&&d(i,r,{get:()=>t[r],enumerable:!(a=x(t,r))||a.enumerable});return i};var E=i=>v(d({},"__esModule",{value:!0}),i);var R={};w(R,{EvmClient:()=>h,EvmRpcAdapter:()=>c,createChain:()=>u});module.exports=E(R);var o=require("polkadot-api"),m=require("@galacticcouncil/descriptors"),s=require("viem"),A=10000000n,c=class{api;constructor(t){this.api=t.getTypedApi(m.hydration)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,a=e.timestamp/1000n,[r]=e.number;return{timestamp:a,number:r}}readContract=(async t=>{let{abi:e,address:a,functionName:r,args:C}=t,f=(0,s.encodeFunctionData)({abi:e,functionName:r,args:C}),l=await this.api.apis.EthereumRuntimeRPCApi.call(o.FixedSizeBinary.fromText(""),o.FixedSizeBinary.fromHex(a),o.Binary.fromHex(f),[0n,0n,0n,0n],[A,0n,0n,0n],void 0,void 0,void 0,!1,[],[]);if(!l.success)throw console.error(r,l.value.type),new Error("Contract read failure");let{exit_reason:p,value:b,used_gas:g}=l.value;if(console.log(g),p.type==="Succeed")return(0,s.decodeFunctionResult)({abi:e,functionName:r,data:b.asHex()});throw console.log(r,p.type,p.value.type),new Error("Contract read error")})};var y=require("viem"),H=["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"],u=()=>(0,y.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:H}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var n=require("viem");var h=class{client;chain;constructor(t){this.client=t,this.chain=u()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,n.createPublicClient)({chain:this.chain,transport:(0,n.http)()})}getWsProvider(){return(0,n.createPublicClient)({transport:(0,n.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,n.createWalletClient)({account:t,chain:this.chain,transport:(0,n.custom)(window.ethereum)})}getRPCAdapter(){return new c(this.client)}};0&&(module.exports={EvmClient,EvmRpcAdapter,createChain});
@@ -0,0 +1 @@
1
+ import C from"buffer";typeof window<"u"&&(window.Buffer=C.Buffer);import{Binary as g,FixedSizeBinary as s}from"polkadot-api";import{hydration as b}from"@galacticcouncil/descriptors";import{encodeFunctionData as x,decodeFunctionResult as P}from"viem";var w=10000000n,n=class{api;constructor(t){this.api=t.getTypedApi(b)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,i=e.timestamp/1000n,[r]=e.number;return{timestamp:i,number:r}}readContract=(async t=>{let{abi:e,address:i,functionName:r,args:h}=t,m=x({abi:e,functionName:r,args:h}),a=await this.api.apis.EthereumRuntimeRPCApi.call(s.fromText(""),s.fromHex(i),g.fromHex(m),[0n,0n,0n,0n],[w,0n,0n,0n],void 0,void 0,void 0,!1,[],[]);if(!a.success)throw console.error(r,a.value.type),new Error("Contract read failure");let{exit_reason:o,value:f,used_gas:y}=a.value;if(console.log(y),o.type==="Succeed")return P({abi:e,functionName:r,data:f.asHex()});throw console.log(r,o.type,o.value.type),new Error("Contract read error")})};import{defineChain as k}from"viem";var v=["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"],c=()=>k({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:v}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});import{createPublicClient as l,createWalletClient as E,custom as p,http as A}from"viem";var d=class{client;chain;constructor(t){this.client=t,this.chain=c()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return l({chain:this.chain,transport:A()})}getWsProvider(){return l({transport:p({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return E({account:t,chain:this.chain,transport:p(window.ethereum)})}getRPCAdapter(){return new n(this.client)}};export{d as EvmClient,n as EvmRpcAdapter,c as createChain};
@@ -0,0 +1 @@
1
+ "use strict";var ht=Object.create;var O=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,vt=Object.prototype.hasOwnProperty;var Z=(a,t)=>{for(var e in t)O(a,e,{get:t[e],enumerable:!0})},tt=(a,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of St(t))!vt.call(a,i)&&i!==e&&O(a,i,{get:()=>t[i],enumerable:!(r=_t(t,i))||r.enumerable});return a};var x=(a,t,e)=>(e=a!=null?ht(wt(a)):{},tt(t||!a||!a.__esModule?O(e,"default",{value:a,enumerable:!0}):e,a)),Ft=a=>tt(O({},"__esModule",{value:!0}),a);var kt={};Z(kt,{LiquidityMiningApi:()=>W,LiquidityMiningClient:()=>j});module.exports=Ft(kt);var it=require("polkadot-api"),d=x(require("big.js")),h=require("@galacticcouncil/common"),K=require("@galacticcouncil/math-liquidity-mining");var It=require("@galacticcouncil/common");var A={};Z(A,{FeeUtils:()=>q,shiftNeg:()=>Ot});var et=x(require("big.js"));var q=class a{static toPct(t){let[e,r]=t;return a.safeDivide(e*100,r)}static toRaw(t){let[e,r]=t;return a.safeDivide(e,r)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,r=12){let i=10**r;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Ot(a,t){let e=(0,et.default)(typeof a=="bigint"?a.toString():a);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Mt=x(require("big.js"));var T=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let r=0;r<t.length;++r){let[i,n]=t[r];this.result.set(this.getKey(n,i),e[r].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,r,i){let n=this.getKey(t,e),o=this.getKey(t,r),c=this.result.get(n)??0n,s=this.result.get(o)??0n;if(c<i)throw new Error("Attempting to transfer more than is present");this.result.set(n,c+i),this.result.set(o,s+i)}};var S=x(require("big.js")),b=require("@galacticcouncil/math-liquidity-mining");var k=x(require("big.js")),z=(0,k.default)(10).pow(18),rt=BigInt((0,k.default)(1).pow(18).toString()),nt=6e3;var Et="1000000000000000000",M=class{constructor(t,e,r){this.getAccount=t;this.getAsset=e;this.multiCurrency=r}async syncGlobalFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let i=await this.getAsset(t.reward_currency),n=e-t.updated_at,o=this.getAccount(t.id),c=i?.existential_deposit;if(!c)throw new Error("Missing reward currency asset list");let s=this.multiCurrency.freeBalance(t.reward_currency,o),m=(0,S.default)(c.toString()),g=(0,S.default)(s.toString()).minus(m.lt(s.toString())?c.toString():s.toString()),l=(0,S.default)((0,b.calculate_global_farm_rewards)(t.total_shares_z.toString(),r.toString(),(0,S.default)(t.yield_per_period.toString()).mul(z).round(0,S.default.roundDown).toFixed(),t.max_reward_per_period.toString(),n.toFixed()));if(g.lt(l)&&(l=g),l.eq(0))return t;let f=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,o,f,BigInt(l.toFixed())),{...t,accumulated_rpz:BigInt((0,b.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),l.toFixed()))}}syncYieldFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===r)return null;if(t.total_valued_shares===0n)return{...t,updated_at:r};let i=(0,b.calculate_yield_farm_delta_rpvs)(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(i),updated_at:r}}getLoyaltyMultiplier(t,e){let r=(0,S.default)(1).mul(z).round(0,S.default.roundDown).toString();if(!e)return r;let{initial_reward_percentage:i,scale_coef:n}=e;return(0,b.calculate_loyalty_multiplier)(t.toFixed(),i.toString(),n.toFixed())}async claimRewards(t,e,r,i,n){if(e.state.type==="Terminated")return null;let o=Math.floor(i/t.blocks_per_period);if(r.updated_at===o)return null;let c=await this.syncGlobalFarm(t,o,n);if(!c)return null;let s=this.syncYieldFarm(e,c,o);if(!s)return null;let m=s.total_stopped-r.stopped_at_creation,g=s.updated_at-r.entered_at-m,l=this.getLoyaltyMultiplier(g,s.loyalty_curve),f=BigInt((0,b.calculate_user_reward)(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),s.accumulated_rpvs.toString(),l)),p=BigInt((0,b.calculate_user_reward)(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),s.accumulated_rpvs.toString(),Et));return{reward:f,maxReward:p,assetId:c.reward_currency,yieldFarmId:s.id,isActiveFarm:s.state.type==="Active"}}};var Lt=(0,d.default)(365.2425).times(24).times(60).times(60),W=class{balance;client;options;constructor(t,e,r={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:r.blockTime??nt})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let r=[t,e].sort((n,o)=>n-o);if(t===e)return rt;let i=await this.client.getOraclePrice(r);if(i){let{n,d:o}=i[0].price,c;return t<e?c=(0,K.fixed_from_rational)(n.toString(),o.toString()):c=(0,K.fixed_from_rational)(o.toString(),n.toString()),BigInt(c)}}getFarmAddress=(t,e)=>{let r=Buffer.from("modl","utf-8"),i=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),n=Buffer.from([t]),o=Buffer.concat([r,i,n]),s="0x"+Buffer.concat([o,Buffer.alloc(32-o.length)]).toString("hex");return(0,it.AccountId)(h.HYDRATION_SS58_PREFIX).dec(s)};getGlobalRewardPerPeriod(t,e,r,i){let n=(0,d.default)(i).times(t.toString()).times(e.toString()).div(Math.pow(10,h.RUNTIME_DECIMALS));return n.gte(r.toString())?r.toString():n.toString()}getPoolYieldPerPeriod(t,e,r,i){let n=(0,d.default)(t.toString()).times(e),o=(0,d.default)(r.toString()).times(i);return n.div(o.toString()).toString()}farmData(t,e,r){let{yieldFarm:i,globalFarm:n,priceAdjustment:o,balance:c,id:s}=t,{multiplier:m,loyalty_curve:g}=i,{blocks_per_period:l,yield_per_period:f,total_shares_z:p,max_reward_per_period:y,pending_rewards:w,accumulated_paid_rewards:v,planned_yielding_periods:I,updated_at:P,incentivized_asset:at,reward_currency:ct,price_adjustment:lt,min_deposit:ut}=n,N=A.shiftNeg(o??lt,h.RUNTIME_DECIMALS),U=A.shiftNeg(m,h.RUNTIME_DECIMALS),V=A.shiftNeg(g?.initial_reward_percentage??0,h.RUNTIME_DECIMALS),$=Lt.div((0,d.default)(this.blockTime).div(1e3).times(l)).toString(),F;if(p<=0)F=(0,d.default)(U).times(f.toString()).times($).div(Math.pow(10,h.RUNTIME_DECIMALS)).toString();else{let bt=this.getGlobalRewardPerPeriod(p,f,y,N),yt=this.getPoolYieldPerPeriod(bt,U,p,N);F=(0,d.default)(yt).times($).toString()}let B=w+v,mt=y*BigInt(I),D=c.transferable+B,dt=D-B,H=(0,d.default)(dt.toString()).div(y.toString()),X=(0,d.default)(e).div(l.toString()).toString(),J=(p>=0?H.plus(P):H.plus(X)).toString(),gt=(0,d.default)(J).times(l).toString(),pt=(0,d.default)(p.toString()).div((0,d.default)(y.toString()).div(f.toString())).div(Math.pow(10,h.RUNTIME_DECIMALS)).times(100).times(N).toFixed(2),Q=(0,d.default)(B.toString()).div(D.toString()).gte(.999);F=Q?"0":(0,d.default)(F).div(r?2:1).times(100).toString();let ft=V?(0,d.default)(F).times(V).toString():void 0;return{apr:F,minApr:ft,isDistributed:Q,estimatedEndPeriod:J,estimatedEndBlock:gt,maxRewards:mt,incentivizedAsset:at,rewardCurrency:ct,loyaltyCurve:g,currentPeriod:X,potMaxRewards:D,fullness:pt,yieldFarmId:i.id,globalFarmId:n.id,poolId:s,distributedRewards:B,plannedYieldingPeriods:I,minDeposit:ut,blocksPerPeriod:l}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((i,n)=>i.includes(n.keyArgs[0].toString())?i:[...i,n.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async i=>{let n=await this.getOmnipoolFarms(i);if(n)return[i,n]}));return Object.fromEntries(r.filter(i=>!!i))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),r=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:n,value:o})=>{let[,c]=n,s=o,m=await this.client.getOmnipoolGlobalFarm(c),g=await this.client.getOmnipoolYieldFarm(Number(t),c,s);if(!m||!g)return;let l=m.reward_currency,f=m.incentivized_asset,p=this.getFarmAddress(c),y=await this.getOraclePrice(l,f),w=await this.balance.getBalance(p,l);return{id:t,globalFarm:m,yieldFarm:g,priceAdjustment:y,balance:w}}));return r?i.map(n=>n?this.farmData(n,r):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((i,n)=>i.includes(n.keyArgs[0].toString())?i:[...i,n.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async i=>{let n=await this.getIsolatedFarms(i);if(n)return[i,n]}));return Object.fromEntries(r.filter(i=>!!i))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),r=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:n,value:o})=>{let[,c]=n,s=o,m=await this.client.getIsolatedGlobalFarm(c),g=await this.client.getIsolatedYieldFarm(t,c,s);if(!m||!g)return;let l=m.reward_currency,f=m.incentivized_asset,p=this.getFarmAddress(c,!0),y=await this.getOraclePrice(l,f),w=await this.balance.getBalance(p,l);return{id:t,globalFarm:m,yieldFarm:g,priceAdjustment:y,balance:w,farmAddress:p}}));return r?i.map(n=>n?this.farmData(n,r,!0):void 0):[]}async getDepositReward(t,e,r,i){let n=e.global_farm_id,o=e.yield_farm_id,c=r?await this.client.getIsolatedYieldFarm(t,n,o):await this.client.getOmnipoolYieldFarm(Number(t),n,o),s=r?await this.client.getIsolatedGlobalFarm(n):await this.client.getOmnipoolGlobalFarm(n);if(!s||!c)return;let m=s.reward_currency,g=s.incentivized_asset,l=[[this.getFarmAddress(0,r),s.reward_currency],[this.getFarmAddress(s.id,r),s.reward_currency]],f=await this.getAccountAssetBalances(l),p=await this.getOraclePrice(m,g),y=new T(l,f),v=await new M(P=>this.getFarmAddress(P),P=>this.client.getAsset(P),y).claimRewards(s,c,e,i,p??s.price_adjustment);if(!v)return;let I=await this.client.getAsset(v.assetId);if(I&&!(v.reward<=I.existential_deposit))return v}async getAccountAssetBalances(t){let[e,r]=await Promise.all([Promise.all(t.filter(([n,o])=>o!==0).map(([n,o])=>this.balance.getTokenBalance(n,o))),Promise.all(t.filter(([n,o])=>o===0).map(([n])=>this.balance.getSystemBalance(n)))]),i=[];for(let n=0,o=0;n+o<t.length;){let c=n+o,[,s]=t[c];s===0?(i.push(r[o]),o+=1):(i.push(e[n]),n+=1)}return i}};var R=require("@galacticcouncil/descriptors");var st=require("@galacticcouncil/common"),E=require("rxjs");var _=require("rxjs"),u=require("rxjs/operators");function ot(a,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let r=()=>(0,_.defer)(()=>(0,_.from)(a._request("system_health",[]))).pipe((0,u.timeout)({first:e}),(0,u.map)(()=>"online"),(0,u.catchError)(()=>(0,_.of)("offline")));return(0,_.of)({state:"offline",delayMs:0}).pipe((0,u.expand)(n=>(0,_.timer)(n.delayMs).pipe((0,u.switchMap)(r),(0,u.map)(o=>({state:o,delayMs:t})))),(0,u.skip)(1),(0,u.map)(n=>n.state),(0,u.distinctUntilChanged)(),(0,u.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Rt}=st.log,C=class a{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue("best")),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",ot(t))}static getInstance(t){return this.instance||(this.instance=new a(t)),this.instance}watched(t,e){return e.pipe((0,E.tap)({error:r=>Rt.error(t,r)}),(0,E.shareReplay)({bufferSize:1,refCount:!0}))}};var L=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(R.hydration),this.apiNext=this.client.getTypedApi(R.hydrationNext),this.watcher=C.getInstance(this.client)}};var Yt=require("polkadot-api/ws-provider"),Nt=require("polkadot-api/logs-provider"),Dt=require("@polkadot-api/legacy-provider");var qt=require("polkadot-api/sm-provider");var Y=require("polkadot-api"),j=class extends L{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(Y.Binary.fromText("omnipool"),t,(0,Y.Enum)("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,r){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,r,{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,r){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,r,{at:"best"})}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};0&&(module.exports={LiquidityMiningApi,LiquidityMiningClient});
@@ -0,0 +1 @@
1
+ var lt=Object.defineProperty;var ct=(c,t)=>{for(var e in t)lt(c,e,{get:t[e],enumerable:!0})};import ut from"buffer";typeof window<"u"&&(window.Buffer=ut.Buffer);import{AccountId as It}from"polkadot-api";import m from"big.js";import{HYDRATION_SS58_PREFIX as At,RUNTIME_DECIMALS as w}from"@galacticcouncil/common";import{fixed_from_rational as j}from"@galacticcouncil/math-liquidity-mining";import{RUNTIME_DECIMALS as Qt}from"@galacticcouncil/common";var S={};ct(S,{FeeUtils:()=>T,shiftNeg:()=>bt});import ft from"big.js";var T=class c{static toPct(t){let[e,r]=t;return c.safeDivide(e*100,r)}static toRaw(t){let[e,r]=t;return c.safeDivide(e,r)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,r=12){let n=10**r;return Math.round(t*n/e)/n}static safeRound(t){return parseFloat(t.toPrecision(15))}};function bt(c,t){let e=ft(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import ne from"big.js";import{TLRUCache as se}from"@thi.ng/cache";var A=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let r=0;r<t.length;++r){let[n,i]=t[r];this.result.set(this.getKey(i,n),e[r].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,r,n){let i=this.getKey(t,e),o=this.getKey(t,r),s=this.result.get(i)??0n,a=this.result.get(o)??0n;if(s<n)throw new Error("Attempting to transfer more than is present");this.result.set(i,s+n),this.result.set(o,a+n)}};import b from"big.js";import{calculate_accumulated_rps as _t,calculate_global_farm_rewards as St,calculate_loyalty_multiplier as wt,calculate_user_reward as V,calculate_yield_farm_delta_rpvs as Ft}from"@galacticcouncil/math-liquidity-mining";import W from"big.js";var Y=W(10).pow(18),z=BigInt(W(1).pow(18).toString()),K=6e3;var vt="1000000000000000000",x=class{constructor(t,e,r){this.getAccount=t;this.getAsset=e;this.multiCurrency=r}async syncGlobalFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let n=await this.getAsset(t.reward_currency),i=e-t.updated_at,o=this.getAccount(t.id),s=n?.existential_deposit;if(!s)throw new Error("Missing reward currency asset list");let a=this.multiCurrency.freeBalance(t.reward_currency,o),u=b(s.toString()),d=b(a.toString()).minus(u.lt(a.toString())?s.toString():a.toString()),l=b(St(t.total_shares_z.toString(),r.toString(),b(t.yield_per_period.toString()).mul(Y).round(0,b.roundDown).toFixed(),t.max_reward_per_period.toString(),i.toFixed()));if(d.lt(l)&&(l=d),l.eq(0))return t;let g=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,o,g,BigInt(l.toFixed())),{...t,accumulated_rpz:BigInt(_t(t.accumulated_rpz.toString(),t.total_shares_z.toString(),l.toFixed()))}}syncYieldFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===r)return null;if(t.total_valued_shares===0n)return{...t,updated_at:r};let n=Ft(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(n),updated_at:r}}getLoyaltyMultiplier(t,e){let r=b(1).mul(Y).round(0,b.roundDown).toString();if(!e)return r;let{initial_reward_percentage:n,scale_coef:i}=e;return wt(t.toFixed(),n.toString(),i.toFixed())}async claimRewards(t,e,r,n,i){if(e.state.type==="Terminated")return null;let o=Math.floor(n/t.blocks_per_period);if(r.updated_at===o)return null;let s=await this.syncGlobalFarm(t,o,i);if(!s)return null;let a=this.syncYieldFarm(e,s,o);if(!a)return null;let u=a.total_stopped-r.stopped_at_creation,d=a.updated_at-r.entered_at-u,l=this.getLoyaltyMultiplier(d,a.loyalty_curve),g=BigInt(V(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),a.accumulated_rpvs.toString(),l)),p=BigInt(V(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),a.accumulated_rpvs.toString(),vt));return{reward:g,maxReward:p,assetId:s.reward_currency,yieldFarmId:a.id,isActiveFarm:a.state.type==="Active"}}};var xt=m(365.2425).times(24).times(60).times(60),H=class{balance;client;options;constructor(t,e,r={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:r.blockTime??K})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let r=[t,e].sort((i,o)=>i-o);if(t===e)return z;let n=await this.client.getOraclePrice(r);if(n){let{n:i,d:o}=n[0].price,s;return t<e?s=j(i.toString(),o.toString()):s=j(o.toString(),i.toString()),BigInt(s)}}getFarmAddress=(t,e)=>{let r=Buffer.from("modl","utf-8"),n=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),i=Buffer.from([t]),o=Buffer.concat([r,n,i]),a="0x"+Buffer.concat([o,Buffer.alloc(32-o.length)]).toString("hex");return It(At).dec(a)};getGlobalRewardPerPeriod(t,e,r,n){let i=m(n).times(t.toString()).times(e.toString()).div(Math.pow(10,w));return i.gte(r.toString())?r.toString():i.toString()}getPoolYieldPerPeriod(t,e,r,n){let i=m(t.toString()).times(e),o=m(r.toString()).times(n);return i.div(o.toString()).toString()}farmData(t,e,r){let{yieldFarm:n,globalFarm:i,priceAdjustment:o,balance:s,id:a}=t,{multiplier:u,loyalty_curve:d}=n,{blocks_per_period:l,yield_per_period:g,total_shares_z:p,max_reward_per_period:f,pending_rewards:y,accumulated_paid_rewards:h,planned_yielding_periods:F,updated_at:v,incentivized_asset:Q,reward_currency:J,price_adjustment:Z,min_deposit:tt}=i,B=S.shiftNeg(o??Z,w),E=S.shiftNeg(u,w),R=S.shiftNeg(d?.initial_reward_percentage??0,w),D=xt.div(m(this.blockTime).div(1e3).times(l)).toString(),_;if(p<=0)_=m(E).times(g.toString()).times(D).div(Math.pow(10,w)).toString();else{let at=this.getGlobalRewardPerPeriod(p,g,f,B),st=this.getPoolYieldPerPeriod(at,E,p,B);_=m(st).times(D).toString()}let I=y+h,et=f*BigInt(F),M=s.transferable+I,rt=M-I,N=m(rt.toString()).div(f.toString()),k=m(e).div(l.toString()).toString(),q=(p>=0?N.plus(v):N.plus(k)).toString(),it=m(q).times(l).toString(),nt=m(p.toString()).div(m(f.toString()).div(g.toString())).div(Math.pow(10,w)).times(100).times(B).toFixed(2),G=m(I.toString()).div(M.toString()).gte(.999);_=G?"0":m(_).div(r?2:1).times(100).toString();let ot=R?m(_).times(R).toString():void 0;return{apr:_,minApr:ot,isDistributed:G,estimatedEndPeriod:q,estimatedEndBlock:it,maxRewards:et,incentivizedAsset:Q,rewardCurrency:J,loyaltyCurve:d,currentPeriod:k,potMaxRewards:M,fullness:nt,yieldFarmId:n.id,globalFarmId:i.id,poolId:a,distributedRewards:I,plannedYieldingPeriods:F,minDeposit:tt,blocksPerPeriod:l}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((n,i)=>n.includes(i.keyArgs[0].toString())?n:[...n,i.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async n=>{let i=await this.getOmnipoolFarms(n);if(i)return[n,i]}));return Object.fromEntries(r.filter(n=>!!n))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),r=await this.client.getRelayBlockNumber(),n=await Promise.all(e.map(async({keyArgs:i,value:o})=>{let[,s]=i,a=o,u=await this.client.getOmnipoolGlobalFarm(s),d=await this.client.getOmnipoolYieldFarm(Number(t),s,a);if(!u||!d)return;let l=u.reward_currency,g=u.incentivized_asset,p=this.getFarmAddress(s),f=await this.getOraclePrice(l,g),y=await this.balance.getBalance(p,l);return{id:t,globalFarm:u,yieldFarm:d,priceAdjustment:f,balance:y}}));return r?n.map(i=>i?this.farmData(i,r):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((n,i)=>n.includes(i.keyArgs[0].toString())?n:[...n,i.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async n=>{let i=await this.getIsolatedFarms(n);if(i)return[n,i]}));return Object.fromEntries(r.filter(n=>!!n))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),r=await this.client.getRelayBlockNumber(),n=await Promise.all(e.map(async({keyArgs:i,value:o})=>{let[,s]=i,a=o,u=await this.client.getIsolatedGlobalFarm(s),d=await this.client.getIsolatedYieldFarm(t,s,a);if(!u||!d)return;let l=u.reward_currency,g=u.incentivized_asset,p=this.getFarmAddress(s,!0),f=await this.getOraclePrice(l,g),y=await this.balance.getBalance(p,l);return{id:t,globalFarm:u,yieldFarm:d,priceAdjustment:f,balance:y,farmAddress:p}}));return r?n.map(i=>i?this.farmData(i,r,!0):void 0):[]}async getDepositReward(t,e,r,n){let i=e.global_farm_id,o=e.yield_farm_id,s=r?await this.client.getIsolatedYieldFarm(t,i,o):await this.client.getOmnipoolYieldFarm(Number(t),i,o),a=r?await this.client.getIsolatedGlobalFarm(i):await this.client.getOmnipoolGlobalFarm(i);if(!a||!s)return;let u=a.reward_currency,d=a.incentivized_asset,l=[[this.getFarmAddress(0,r),a.reward_currency],[this.getFarmAddress(a.id,r),a.reward_currency]],g=await this.getAccountAssetBalances(l),p=await this.getOraclePrice(u,d),f=new A(l,g),h=await new x(v=>this.getFarmAddress(v),v=>this.client.getAsset(v),f).claimRewards(a,s,e,n,p??a.price_adjustment);if(!h)return;let F=await this.client.getAsset(h.assetId);if(F&&!(h.reward<=F.existential_deposit))return h}async getAccountAssetBalances(t){let[e,r]=await Promise.all([Promise.all(t.filter(([i,o])=>o!==0).map(([i,o])=>this.balance.getTokenBalance(i,o))),Promise.all(t.filter(([i,o])=>o===0).map(([i])=>this.balance.getSystemBalance(i)))]),n=[];for(let i=0,o=0;i+o<t.length;){let s=i+o,[,a]=t[s];a===0?(n.push(r[o]),o+=1):(n.push(e[i]),i+=1)}return n}};import{hydration as Gt,hydrationNext as Wt}from"@galacticcouncil/descriptors";import{log as Dt}from"@galacticcouncil/common";import{shareReplay as Nt,tap as kt}from"rxjs";import{defer as Pt,from as Ot,of as U,timer as Bt}from"rxjs";import{catchError as Mt,distinctUntilChanged as Tt,expand as Yt,map as C,shareReplay as Lt,skip as Ct,switchMap as Et,timeout as Rt}from"rxjs/operators";function $(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let r=()=>Pt(()=>Ot(c._request("system_health",[]))).pipe(Rt({first:e}),C(()=>"online"),Mt(()=>U("offline")));return U({state:"offline",delayMs:0}).pipe(Yt(i=>Bt(i.delayMs).pipe(Et(r),C(o=>({state:o,delayMs:t})))),Ct(1),C(i=>i.state),Tt(),Lt({bufferSize:1,refCount:!0}))}var{logger:qt}=Dt,P=class c{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue("best")),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",$(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe(kt({error:r=>qt.error(t,r)}),Nt({bufferSize:1,refCount:!0}))}};var O=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(Gt),this.apiNext=this.client.getTypedApi(Wt),this.watcher=P.getInstance(this.client)}};import{getWsProvider as Qe}from"polkadot-api/ws-provider";import{withLogsRecorder as Ze}from"polkadot-api/logs-provider";import{withLegacy as er}from"@polkadot-api/legacy-provider";import{getSmProvider as or}from"polkadot-api/sm-provider";import{Binary as zt,Enum as Kt}from"polkadot-api";var X=class extends O{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(zt.fromText("omnipool"),t,Kt("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,r){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,r,{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,r){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,r,{at:"best"})}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};export{H as LiquidityMiningApi,X as LiquidityMiningClient};
@@ -0,0 +1 @@
1
+ "use strict";var Ze=Object.create;var Ft=Object.defineProperty;var ti=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ii=Object.getPrototypeOf,si=Object.prototype.hasOwnProperty;var H=(o,t)=>{for(var e in t)Ft(o,e,{get:t[e],enumerable:!0})},ge=(o,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ei(t))!si.call(o,s)&&s!==e&&Ft(o,s,{get:()=>t[s],enumerable:!(i=ti(t,s))||i.enumerable});return o};var se=(o,t,e)=>(e=o!=null?Ze(ii(o)):{},ge(t||!o||!o.__esModule?Ft(e,"default",{value:o,enumerable:!0}):e,o)),ni=o=>ge(Ft({},"__esModule",{value:!0}),o);var Li={};H(Li,{PoolContextProvider:()=>ie,PoolError:()=>tt,PoolFactory:()=>te,PoolType:()=>O,aave:()=>me,hsm:()=>he,lbp:()=>oe,omni:()=>ce,stable:()=>ue,xyk:()=>pe});module.exports=ni(Li);var oe={};H(oe,{LbpMath:()=>G,LbpPool:()=>gt,LbpPoolClient:()=>ft});var z=require("@galacticcouncil/math-lbp"),G=class{static getSpotPrice(t,e,i,s,n){return(0,z.get_spot_price)(t,e,i,s,n)}static calculateInGivenOut(t,e,i,s,n){return(0,z.calculate_in_given_out)(t,e,i,s,n)}static calculateOutGivenIn(t,e,i,s,n){return(0,z.calculate_out_given_in)(t,e,i,s,n)}static calculateLinearWeights(t,e,i,s,n){return(0,z.calculate_linear_weights)(t,e,i,s,n)}static calculatePoolTradeFee(t,e,i){return(0,z.calculate_pool_trade_fee)(t,e,i)}};var rt=require("@galacticcouncil/common");var O=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a.HSM="HSM",a))(O||{}),tt=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(tt||{});var kt={};H(kt,{withTimeout:()=>ai});function ai(o,t,e="timeout"){return new Promise((i,s)=>{let n=setTimeout(()=>s(new Error(e)),t);o.then(a=>{clearTimeout(n),i(a)},a=>{clearTimeout(n),s(a)})})}var ri=require("@galacticcouncil/common");var I={};H(I,{FeeUtils:()=>ne,shiftNeg:()=>ci});var be=se(require("big.js"));var ne=class o{static toPct(t){let[e,i]=t;return o.safeDivide(e*100,i)}static toRaw(t){let[e,i]=t;return o.safeDivide(e,i)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,i=12){let s=10**i;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function ci(o,t){let e=(0,be.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var dt={};H(dt,{findNestedKey:()=>ui,findNestedObj:()=>pi,jsonFormatter:()=>mi});var ui=(o,t)=>{let e=[];return JSON.stringify(o,(i,s)=>(s&&s[t]&&e.push(s),s)),e[0]},pi=(o,t,e)=>{let i;return JSON.stringify(o,(s,n)=>(n&&n[t]===e&&(i=n),n)),i},mi=(o,t)=>typeof t=="bigint"?t.toString():t;var et={};H(et,{calculateBuyFee:()=>bi,calculateDiffToAvg:()=>di,calculateDiffToRef:()=>hi,calculateSellFee:()=>gi});var V=se(require("big.js"));function di(o,t){let e=(0,V.default)(o.toString()),i=(0,V.default)(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function hi(o,t){if(t===0n)return 0;let e=(0,V.default)(o.toString()),i=(0,V.default)(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function gi(o,t){if(o===0n)return 0;let e=(0,V.default)(o.toString()),i=(0,V.default)(t.toString());return(0,V.default)(1).minus(i.div(e)).mul(100).round(2).toNumber()}function bi(o,t){if(o===0n)return 0;let e=(0,V.default)(o.toString());return(0,V.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var ht=(o,t)=>o===t?0:o==null?t==null?0:-1:t==null?o==null?0:1:typeof o.compare=="function"?o.compare(t):typeof t.compare=="function"?-t.compare(o):o<t?-1:o>t?1:0;var Rt=(o,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(o(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var fi=Rt(()=>"illegal argument(s)"),fe=o=>{throw new fi(o)};var yi=Rt(()=>"index out of bounds"),ae=o=>{throw new yi(o)},Ct=(o,t,e)=>(o<t||o>=e)&&ae(o);var ye=23283064365386963e-26,Mt=class{float(t=1){return this.int()*ye*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*ye-.5)*2*t}normMinMax(t,e){let i=this.minmax(t,e);return this.float()<.5?i:-i}minmax(t,e){return this.float()*(e-t)+t}minmaxInt(t,e){t|=0;let i=(e|0)-t;return i?t+this.int()%i:t}minmaxUint(t,e){t>>>=0;let i=(e>>>0)-t;return i?t+this.int()%i:t}};var Lt=class extends Mt{constructor(t){super(),this.rnd=t}float(t=1){return this.rnd()*t}norm(t=1){return(this.rnd()-.5)*2*t}int(){return this.rnd()*4294967296>>>0}};var Pe=new Lt(Math.random);var ve=o=>o!=null&&typeof o!="function"&&o.length!==void 0;var Se=Object.getPrototypeOf({}),Dt="function",xe="string",at=(o,t)=>{let e;if(o===t)return!0;if(o!=null){if(typeof o.equiv===Dt)return o.equiv(t)}else return o==t;if(t!=null){if(typeof t.equiv===Dt)return t.equiv(o)}else return o==t;return typeof o===xe||typeof t===xe?!1:(e=Object.getPrototypeOf(o),(e==null||e===Se)&&(e=Object.getPrototypeOf(t),e==null||e===Se)?xi(o,t):typeof o!==Dt&&o.length!==void 0&&typeof t!==Dt&&t.length!==void 0?Pi(o,t):o instanceof Set&&t instanceof Set?vi(o,t):o instanceof Map&&t instanceof Map?Si(o,t):o instanceof Date&&t instanceof Date?o.getTime()===t.getTime():o instanceof RegExp&&t instanceof RegExp?o.toString()===t.toString():o!==o&&t!==t)},Pi=(o,t,e=at)=>{let i=o.length;if(i===t.length)for(;i-- >0&&e(o[i],t[i]););return i<0},vi=(o,t,e=at)=>o.size===t.size&&e([...o.keys()].sort(),[...t.keys()].sort()),Si=(o,t,e=at)=>o.size===t.size&&e([...o].sort(),[...t].sort()),xi=(o,t,e=at)=>{if(Object.keys(o).length!==Object.keys(t).length)return!1;for(let i in o)if(!t.hasOwnProperty(i)||!e(o[i],t[i]))return!1;return!0};var re=class{value;constructor(t){this.value=t}deref(){return this.value}};var we=o=>o instanceof re;var qt=class o{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Oe("next",this._head)}reverseIterator(){return Oe("prev",this.tail)}clear(){this.release()}compare(t,e=ht){let i=this._length;if(i<t._length)return-1;if(i>t._length)return 1;if(i===0)return 0;{let s=this._head,n=t._head,a=0;for(;i-- >0&&a===0;)a=e(s.value,n.value),s=s.next,n=n.next;return a}}concat(...t){let e=this.copy();for(let i of t)e.into(i);return e}equiv(t){if(!(t instanceof o||ve(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),i=this._head;for(let s=this._length;s-- >0;){if(!at(i.value,e.next().value))return!1;i=i.next}return!0}filter(t){let e=this.empty();return this.traverse(i=>(t(i.value)&&e.append(i.value),!0)),e}find(t){return this.traverse(e=>e.value!==t)}findWith(t){return this.traverse(e=>!t(e.value))}first(){return this._head?.value}insertSorted(t,e){e=e||ht;for(let i=this._head,s=this._length;s-- >0;){if(e(t,i.value)<=0)return this.insertBefore(i,t);i=i.next}return this.append(t)}into(t){for(let e of t)this.append(e);return this}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCellUnsafe(t){let e,i;for(t<=this._length>>>1?(e=this._head,i="next"):(e=this.tail,i="prev",t=this._length-t-1);t-- >0&&e;)e=e[i];return e}peek(){return this.tail?.value}$reduce(t,e){let i=this._head;for(let s=this._length;s-- >0&&!we(e);)e=t(e,i.value),i=i.next;return e}reduce(t,e){return this.$reduce(t,e)}release(){let t=this._head;if(!t)return!0;let e;for(let i=this._length;i-- >0;)e=t.next,delete t.value,delete t.prev,delete t.next,t=e;return this._head=void 0,this._length=0,!0}reverse(){let t=this._head,e=this.tail,i=(this._length>>>1)+(this._length&1);for(;t&&e&&i>0;){let s=t.value;t.value=e.value,e.value=s,t=t.next,e=e.prev,i--}return this}setHead(t){let e=this._head;return e?(e.value=t,e):this.prepend(t)}setNth(t,e){let i=this.nthCell(t);return!i&&ae(t),i.value=e,i}setTail(t){let e=this.tail;return e?(e.value=t,e):this.append(t)}swap(t,e){if(t!==e){let i=t.value;t.value=e.value,e.value=i}return this}toArray(t=[]){return this.traverse(e=>(t.push(e.value),!0)),t}toJSON(){return this.toArray()}toString(){let t=[];return this.traverse(e=>(t.push(String(e.value)),!0)),t.join(", ")}traverse(t,e=this._head,i){if(!this._head)return;let s=e;do{if(!t(s))break;s=s.next}while(s!==i);return s}_map(t,e){return this.traverse(i=>(t.append(e(i.value)),!0)),t}};function*Oe(o,t){for(;t;)yield t.value,t=t[o]}var Ht=class o extends qt{_tail;constructor(t){super(),t&&this.into(t)}get tail(){return this._tail}append(t){if(this._tail){let e={value:t,prev:this._tail};return this._tail.next=e,this._tail=e,this._length++,e}else return this.prepend(t)}asHead(t){return t===this._head?this:(this.remove(t),this._head.prev=t,t.next=this._head,t.prev=void 0,this._head=t,this._length++,this)}asTail(t){return t===this._tail?this:(this.remove(t),this._tail.next=t,t.prev=this._tail,t.next=void 0,this._tail=t,this._length++,this)}cons(t){return this.prepend(t),this}copy(){return new o(this)}*cycle(){for(;;)yield*this}drop(){let t=this._head;if(t)return this._head=t.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,t.value}empty(){return new o}insertAfter(t,e){let i={value:e,next:t.next,prev:t};return t.next?t.next.prev=i:this._tail=i,t.next=i,this._length++,i}insertAfterNth(t,e){return t<0&&(t+=this._length),t>=this._length-1?this.append(e):(Ct(t,0,this._length),this.insertAfter(this.nthCellUnsafe(t),e))}insertBefore(t,e){let i={value:e,next:t,prev:t.prev};return t.prev?t.prev.next=i:this._head=i,t.prev=i,this._length++,i}insertBeforeNth(t,e){return t<0&&(t+=this._length),t<=0?this.prepend(e):(Ct(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new o,t)}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCell(t){if(t<0&&(t+=this._length),!(t<0||t>=this._length))return this.nthCellUnsafe(t)}pop(){let t=this._tail;if(t)return this._tail=t.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,t.value}prepend(t){let e={value:t,next:this._head};return this._head?this._head.prev=e:this._tail=e,this._head=e,this._length++,e}push(t){return this.append(t),this}release(){return this._tail=void 0,super.release()}remove(t){return t.prev?t.prev.next=t.next:this._head=t.next,t.next?t.next.prev=t.prev:this._tail=t.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let t=this.peek();return this.pop(),this.prepend(t),this}}seq(t=0,e=this.length){if(t>=e||t<0)return;let i=this.nthCell(t),s=this.nthCell(e-1),n=a=>({first(){return a.value},next(){return a!==s&&a.next?n(a.next):void 0}});return i?n(i):void 0}shuffle(t,e=Pe){if(this._length<2)return this;for(t=t!==void 0?t:Math.ceil(1.5*Math.log2(this._length));t>0;t--){let i=this._head;for(;i;){let s=i.next;e.probability(.5)?this.asHead(i):this.asTail(i),i=s}}return this}slice(t=0,e=this.length){let i=t<0?t+this._length:t,s=e<0?e+this._length:e;(i<0||s<0)&&fe("invalid indices: ${from} / ${to}");let n=new o,a=this.nthCell(i);for(;a&&++i<=s;)n.push(a.value),a=a.next;return n}sort(t=ht){if(!this._length)return this;let e=1;for(;;){let i=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;i;){s++;let n=i,a=0;for(let l=0;l<e&&(a++,n=n.next,!!n);l++);let r=e;for(;a>0||r>0&&n;){let l;a===0?(l=n,n=n.next,r--):!n||r===0||t(i.value,n.value)<=0?(l=i,i=i.next,a--):(l=n,n=n.next,r--),this._tail?this._tail.next=l:this._head=l,l.prev=this._tail,this._tail=l}i=n}if(this._tail.next=void 0,s<=1)return this;e*=2}}splice(t,e=0,i){let s;typeof t=="number"?(t<0&&(t+=this._length),Ct(t,0,this._length),s=this.nthCellUnsafe(t)):s=t;let n=new o;if(e>0)for(;s&&e-- >0;)this.remove(s),n.push(s.value),s=s.next;else s&&(s=s.next);if(i)if(s)for(let a of i)this.insertBefore(s,a);else for(let a of i)this.push(a);return n}};var Gt=class o{map;items;opts;_size;constructor(t,e){let i={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...e};this.map=i.map(),this.items=new Ht,this._size=0,this.opts=i,t&&this.into(t)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let t of this.items)yield[t.k,t]}*keys(){for(let t of this.items)yield t.k}*values(){for(let t of this.items)yield t.v}copy(){let t=this.empty();t.items=this.items.copy();let e=t.items.head;for(;e;)t.map.set(e.value.k,e),e=e.next;return t}empty(){return new o(null,this.opts)}release(){this._size=0,this.map.clear();let t=this.opts.release;if(t){let e;for(;e=this.items.drop();)t(e.k,e.v);return!0}return this.items.release()}has(t){return this.map.has(t)}get(t,e){let i=this.map.get(t);return i?this.resetEntry(i):e}set(t,e){let i=this.opts.ksize(t)+this.opts.vsize(e),s=this.map.get(t),n=Math.max(0,i-(s?s.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(s,t,e,i):this._size-=n,e}into(t){for(let e of t)this.set(e[0],e[1]);return this}async getSet(t,e){let i=this.map.get(t);return i?this.resetEntry(i):this.set(t,await e())}delete(t){let e=this.map.get(t);return e?(this.removeEntry(e),!0):!1}resetEntry(t){return this.items.asTail(t),t.value.v}ensureSize(){let{release:t,maxsize:e,maxlen:i}=this.opts;for(;this._size>e||this.length>=i;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),t?.(s.k,s.v),this._size-=s.s}return!0}removeEntry(t){let e=t.value;this.map.delete(e.k),this.items.remove(t),this.opts.release?.(e.k,e.v),this._size-=e.s}doSetEntry(t,e,i,s){t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=s,this.items.asTail(t)):(this.items.push({k:e,v:i,s}),this.map.set(e,this.items.tail))}};var it=class o extends Gt{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new o(null,this.opts)}has(t){return this.get(t)!==void 0}get(t,e){let i=this.map.get(t);if(i){if(i.value.t>=Date.now())return this.resetEntry(i);this.removeEntry(i)}return e}set(t,e,i=this.opts.ttl){let s=this.opts.ksize(t)+this.opts.vsize(e),n=this.map.get(t),a=Math.max(0,s-(n?n.value.s:0));return this._size+=a,this.ensureSize()?this.doSetEntry(n,t,e,s,i):this._size-=a,e}async getSet(t,e,i=this.opts.ttl){let s=this.get(t);return s!==void 0?s:this.set(t,await e(),i)}prune(){let t=Date.now(),e=this.items.head,i=0;for(;e;)e.value.t<t&&(this.removeEntry(e),i++),e=e.next;return i}ensureSize(){let{maxlen:t,maxsize:e}=this.opts,i=Date.now(),s=this.items.head;for(;s&&(this._size>e||this.length>=t);)s.value.t<i&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(t,e,i,s,n=this.opts.ttl){let a=Date.now()+n;t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=s,t.value.t=a,this.items.asTail(t)):(this.items.push({k:e,v:i,s,t:a,ttl:n}),this.map.set(e,this.items.tail))}resetEntry(t){return this.opts.autoExtend&&(t.value.t=Date.now()+t.value.ttl),super.resetEntry(t)}};var Nt=class{debug;constructor(t){this.debug=t||!1}log(t,e,i){this.debug&&console.log(t,e,i)}scope(t,e,i,s){let n=new Map,a=s!==void 0?new it(null,{ttl:s}):new it;return{get:(...u)=>{let p=i(...u);if(n.has(p)){this.log("[live]",t,p);let y=n.get(p);return Promise.resolve(y)}if(a.has(p))return this.log("[memo]",t,p),a.get(p);this.log("[fetch]",t,p);let g=e(...u).catch(y=>{throw a.delete(p),y});return a.set(p,g),g},set:(u,...p)=>{let g=i(...p);this.log("[set-live]",t,g),n.set(g,u)},clear:()=>{this.log("[clear]",t),n.clear(),a.release()}}}};var{FeeUtils:Ie}=I,gt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new o(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(a=>[a.id,a])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,weightIn:s.weight,weightOut:n.weight}}validateAndBuy(t,e,i){let s=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let a=t.balanceOut/this.maxOutRatio;if(e>a&&n.push("MaxOutRatioExceeded"),s===t.assetOut){let r=this.calculateTradeFee(e,i),l=Ie.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),c=e+r,u=this.calculateInGivenOut(t,c),p=t.balanceIn/this.maxInRatio;return u>p&&n.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:l,errors:n}}else{let r=this.calculateInGivenOut(t,e),l=t.balanceIn/this.maxInRatio;return r>l&&n.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:n}}}validateAndSell(t,e,i){let s=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let a=t.balanceIn/this.maxInRatio;if(e>a&&n.push("MaxInRatioExceeded"),s===t.assetIn){let r=this.calculateOutGivenIn(t,e),l=t.balanceOut/this.maxOutRatio;return r>l&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:n}}else{let r=this.calculateOutGivenIn(t,e),l=this.calculateTradeFee(r,i),c=Ie.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),u=r-l,p=t.balanceOut/this.maxOutRatio;return u>p&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:u,feePct:c,errors:n}}}calculateInGivenOut(t,e){let i=G.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e){let i=G.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){let e=G.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),rt.big.toBigInt(1,rt.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=G.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),rt.big.toBigInt(1,rt.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let i=G.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var Ee=require("polkadot-api"),lt=require("rxjs");var Te=(o,t=new Map)=>e=>{let i;return t.has(e)?t.get(e):(t.set(e,i=o(e)),i)};var v=require("rxjs"),m=require("rxjs/operators");var $t=require("@galacticcouncil/descriptors");var Be=require("@galacticcouncil/common"),Vt=require("rxjs");var j=require("rxjs"),T=require("rxjs/operators");function _e(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>(0,j.defer)(()=>(0,j.from)(o._request("system_health",[]))).pipe((0,T.timeout)({first:e}),(0,T.map)(()=>"online"),(0,T.catchError)(()=>(0,j.of)("offline")));return(0,j.of)({state:"offline",delayMs:0}).pipe((0,T.expand)(n=>(0,j.timer)(n.delayMs).pipe((0,T.switchMap)(i),(0,T.map)(a=>({state:a,delayMs:t})))),(0,T.skip)(1),(0,T.map)(n=>n.state),(0,T.distinctUntilChanged)(),(0,T.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:wi}=Be.log,zt=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue("best")),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",_e(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,Vt.tap)({error:i=>wi.error(t,i)}),(0,Vt.shareReplay)({bufferSize:1,refCount:!0}))}};var $=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi($t.hydration),this.apiNext=this.client.getTypedApi($t.hydrationNext),this.watcher=zt.getInstance(this.client)}};var Oi=require("polkadot-api/ws-provider"),Ii=require("polkadot-api/logs-provider"),Ti=require("@polkadot-api/legacy-provider");var _i=require("polkadot-api/sm-provider");var Ae=require("@galacticcouncil/common"),C=require("rxjs"),d=require("rxjs/operators");var{logger:ot}=Ae.log,bt=class extends ${erc20Ids=null;constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:i}=await e.getValue(t,{at:"best"});return this.getBreakdown(i)}async getTokenBalance(t,e){let s=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(s)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,C.defer)(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return(0,C.combineLatest)([e,i,s]).pipe((0,d.connect)(n=>(0,C.concat)(n.pipe((0,d.take)(1)),n.pipe((0,d.skip)(1),(0,d.debounceTime)(250)))))}).pipe((0,d.map)(e=>e.flat()),(0,d.startWith)([]),(0,d.bufferCount)(2,1),(0,d.map)(([e,i],s)=>s===0?i:this.getDeltas(e,i))).pipe((0,d.tap)({subscribe:()=>ot.debug("balance: subscribe",t),error:e=>ot.error("balance",e)}),(0,d.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,C.defer)(()=>e.watchValue(t,"best")).pipe((0,d.map)(i=>({id:0,balance:this.getBreakdown(i.data)})),(0,d.tap)({error:i=>ot.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return(0,C.defer)(()=>i.watchValue(t,e,"best")).pipe((0,d.map)(s=>({id:e,balance:this.getBreakdown(s)})),(0,d.tap)({error:s=>ot.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,C.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,d.distinctUntilChanged)((i,s)=>!s.deltas),(0,d.map)(({deltas:i})=>{let s=[];return i?.deleted.forEach(n=>{let[a,r]=n.args;s.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(n=>{let[a,r]=n.args;s.push({id:r,balance:this.getBreakdown(n.value)})}),s}),(0,d.tap)({error:i=>ot.error("balance(tokens)",i)}))}watchErc20Balance(t,e){let i=async()=>{if(this.erc20Ids)return this.erc20Ids;let n=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=n.filter(({value:a})=>a.asset_type.type==="Erc20").map(({keyArgs:a})=>{let[r]=a;return r}),this.erc20Ids},s=async n=>(await Promise.all(n.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,l])=>({id:r,balance:l}));return(0,C.defer)(()=>(0,C.from)(e?Promise.resolve(e):i()).pipe((0,d.switchMap)(n=>this.watcher.bestBlock$.pipe((0,d.switchMap)(()=>(0,C.from)(s(n))))),(0,d.startWith)([]),(0,d.bufferCount)(2,1),(0,d.map)(([n,a],r)=>r===0?a.filter(l=>l.balance.total>0n):this.getDeltas(n,a)),(0,d.distinctUntilChanged)((n,a)=>a.length===0),(0,d.tap)({error:n=>ot.error("balance(erc20)",n)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.getBreakdown(i)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,i=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:i,transferable:e}}getDeltas(t,e){let i=(n,a)=>n!==void 0&&a!==void 0&&n.transferable===a.transferable&&n.total===a.total,s=t.reduce((n,a)=>(n.set(a.id,a.balance),n),new Map);return e.filter(n=>!i(n.balance,s.get(n.id)))}};var Fe=require("rxjs"),Wt=class{store$=new Fe.BehaviorSubject([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(t){return this.changeset.size===0?[]:t.filter(e=>this.changeset.has(e.address))}set(t){this.changeset=new Set(t.map(e=>e.address)),this.store$.next(t)}update(t){this.updateQueue=this.updateQueue.then(async()=>{let e=this.store$.value,i=new Map(e.map((r,l)=>[r.address,l])),s=await t(e),n=e.slice(),a=new Set;for(let r of s){let l=i.get(r.address);l===void 0?(i.set(r.address,n.length),n.push(r)):n[l]=r,a.add(r.address)}this.changeset=a,this.store$.next(n)}).catch(console.error)}destroy(){this.store$.complete()}};var ke=require("@galacticcouncil/common");var Bi={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Ut}=ke.log,Yt=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${Bi[this.type]})`,10)}trace(t,...e){Ut.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){Ut.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){Ut.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){Ut.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:Ai}=kt,Fi=3e3,E=class extends ${evm;balance;store=new Wt;log;shared$;resync$=new v.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new it(null,{ttl:6*1e3});memPools=Te(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e,this.balance=new bt(t),this.log=new Yt(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){return(await this.getMemPools()).filter(e=>this.hasValidAssets(e))}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe((0,m.startWith)([]),(0,m.bufferCount)(2,1),(0,m.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,m.filter)(t=>t.length>0),(0,m.throttleTime)(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return(0,v.defer)(()=>{let t=new v.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,m.switchMap)(()=>{let e=new v.Subscription;return(0,v.from)(Ai(this.getMemPools(),6e4,"getMemPools stalled")).pipe((0,m.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,m.map)(s=>s.filter(n=>this.hasValidAssets(n))),(0,m.tap)(s=>this.store.set(s)),(0,m.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),v.EMPTY))).pipe((0,m.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,m.switchMap)(s=>(0,v.merge)((0,v.of)(s),this.store.asObservable().pipe((0,m.skip)(1)))),(0,m.finalize)(()=>{e.unsubscribe()}))}),(0,m.finalize)(()=>t.unsubscribe()))}).pipe((0,m.share)({connector:()=>new v.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:i}=e,s=[this.balance.watchTokensBalance(i)];if(this.hasSystemAsset(e)){let n=this.balance.watchSystemBalance(i);s.push(n)}if(this.hasErc20Asset(e)){let n=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),a=this.balance.watchErc20Balance(i,n);s.push(a)}return(0,v.combineLatest)(s).pipe((0,m.map)(n=>n.flat()),(0,m.pairwise)(),(0,m.map)(([n,a])=>this.balance.getDeltas(n,a)),(0,m.filter)(n=>n.length>0),(0,m.map)(n=>[i,n]))});return(0,v.merge)(...t).pipe((0,m.bufferTime)(250),(0,m.filter)(e=>e.length>0),(0,m.map)(e=>new Map(e)),this.watchGuard("balances")).subscribe(e=>{this.store.update(i=>this.updateBalances(i,e))})}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:i})=>t.type==="XYK"?i>0n&&!!e:!!e)}updateBalances=(t,e)=>{let i=[],s=new Map(t.map(n=>[n.address,n]));for(let[n,a]of e){let r=s.get(n);if(r){let l=r.tokens.map(c=>{let u=a.find(p=>p.id===c.id);return u&&c.id!==r.id?{...c,balance:u.balance.transferable}:c});i.push({...r,tokens:l})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<Fi||(this.resyncAt=e,this.mem++,this.resync$.next())}requestResync(t=!1){this.resyncPending||(this.resyncPending=!0,setTimeout(()=>{this.resyncPending=!1,this.resync(t)},0))}startWatchdog(){let i=this.watcher.connection$.pipe((0,m.pairwise)(),(0,m.filter)(([n,a])=>n==="offline"&&a==="online"),(0,m.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,m.catchError)(n=>(this.log.error("watchdog_recovery_error",n),v.EMPTY)),(0,m.repeat)({delay:1e3})),s=this.watcher.finalizedBlock$.pipe((0,m.pairwise)(),(0,m.tap)(([n,a])=>{let r=Number(n.number),l=Number(a.number),c=l-r;c>=3&&(this.log.debug("watchdog_gap",{from:r,to:l,gap:c}),this.requestResync())}),(0,m.catchError)(n=>(this.log.error("watchdog_gap_error",n),v.EMPTY)),(0,m.repeat)({delay:1e3}));return(0,v.merge)(i,s).subscribe()}watchGuard(t){return e=>e.pipe((0,m.tap)({error:i=>{this.log.error(t,i),this.requestResync(!0)}}),(0,m.finalize)(()=>{this.log.debug(t,"unsub")}),(0,m.catchError)(()=>v.EMPTY))}};var ft=class extends E{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}getPoolWeights(t,e){let{start:i,end:s,initial_weight:n,final_weight:a}=t,r=G.calculateLinearWeights(i?i.toString():"0",s?s.toString():"0",n.toString(),a.toString(),e.toString()),l=BigInt(r),c=this.MAX_FINAL_WEIGHT-BigInt(l);return[l,c]}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Ee.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:"best"}),this.api.query.ParachainSystem.ValidationData.getValue({at:"best"}),this.getPoolLimits()]),s=e?.relay_parent_number||0,n=t.filter(({value:a})=>e&&this.isActivePool(a,s)).map(async({keyArgs:a,value:r})=>{let[l]=a,c=l.toString(),u=await this.getPoolDelta(c,r,s);return{address:c,type:"LBP",fee:r.fee,...u,...i}});return Promise.all(n)}async getPoolDelta(t,e,i){let{assets:s,repay_target:n,fee_collector:a}=e,[r,l]=this.getPoolWeights(e,i),[c,u]=s,[p,g,y,b,A]=await Promise.all([this.isRepayFeeApplied(c,n,a.toString()),this.balance.getBalance(t,c),this.api.query.AssetRegistry.Assets.getValue(c),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u)]);return{repayFeeApply:p,tokens:[{id:c,decimals:y?.decimals,existentialDeposit:y?.existential_deposit,balance:g.transferable,weight:r,type:y?.asset_type.type},{id:u,decimals:A?.decimals,existentialDeposit:A?.existential_deposit,balance:b.transferable,weight:l,type:A?.asset_type.type}]}}isActivePool(t,e){let{start:i,end:s}=t;return i&&s?e>=i&&e<s:!1}async isRepayFeeApplied(t,e,i){if(e===0n)return!1;try{return(await this.balance.getBalance(i,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let i=this.store.pools.find(n=>n.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:i.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue("best").pipe((0,lt.filter)(t=>t!==void 0),(0,lt.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let i=[];for(let s of e){let n=this.poolsData.get(s.address);if(n){let{assets:a,repay_target:r,fee_collector:l}=n,[c]=a,[u,p]=this.getPoolWeights(n,t),[g,y]=s.tokens,b=[{...g,weight:u},{...y,weight:p}],A=await this.isRepayFeeApplied(c,r,l.toString());i.push({...s,tokens:b,repayFeeApply:A})}}return i})})}subscribeUpdates(){let t=new lt.Subscription;return t.add(this.subscribeValidationData()),t}};var ce={};H(ce,{OmniMath:()=>P,OmniPool:()=>yt,OmniPoolClient:()=>Pt});var h=require("@galacticcouncil/math-omnipool"),st=se(require("big.js")),P=class{static calculateSpotPrice(t,e,i,s){return(0,h.calculate_spot_price)(t,e,i,s)}static calculateLrnaSpotPrice(t,e){return(0,h.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,i,s,n,a,r,l,c,u){return(0,h.calculate_in_given_out)(t,e,i,s,n,a,r,l,c,u)}static calculateLrnaInGivenOut(t,e,i,s,n,a){return(0,h.calculate_lrna_in_given_out)(t,e,i,s,n,a)}static calculateOutGivenIn(t,e,i,s,n,a,r,l,c,u){return(0,h.calculate_out_given_in)(t,e,i,s,n,a,r,l,c,u)}static calculateOutGivenLrnaIn(t,e,i,s,n,a){return(0,h.calculate_out_given_lrna_in)(t,e,i,s,n,a)}static calculateShares(t,e,i,s){return(0,h.calculate_shares)(t,e,i,s)}static calculateLiquidityOut(t,e,i,s,n,a,r,l){return(0,h.calculate_liquidity_out)(t,e,i,s,n,a,r,l)}static calculateLiquidityLRNAOut(t,e,i,s,n,a,r,l){return(0,h.calculate_liquidity_lrna_out)(t,e,i,s,n,a,r,l)}static calculateCapDifference(t,e,i,s){let n=(0,st.default)(e),a=(0,st.default)(t),r=(0,st.default)(s),l=(0,st.default)(i),c=(0,st.default)(10).pow(18),u=l.div(c);if(n.div(r).lt(u)){let g=u.times(r).minus(n).times(a),y=n.times((0,st.default)(1).minus(u));return g.div(y).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,s){return(0,h.calculate_liquidity_hub_in)(t,e,i,s)}static isSellAllowed(t){return(0,h.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,h.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,h.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,h.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,i,s,n,a,r,l,c,u,p){return(0,h.recalculate_asset_fee)(t,e,i,s,n,a,r,l,c,u,p)}static recalculateProtocolFee(t,e,i,s,n,a,r,l,c,u,p){return(0,h.recalculate_protocol_fee)(t,e,i,s,n,a,r,l,c,u,p)}static verifyAssetCap(t,e,i,s){return(0,h.verify_asset_cap)(t,e,i,s)}};var Re=require("@galacticcouncil/common");var{FeeUtils:W}=I,yt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new o(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let i=new Map(this.tokens.map(a=>[a.id,a])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:s.hubReserves,hubReservesOut:n.hubReserves,sharesIn:s.shares,sharesOut:n.shares,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:s.balance,balanceOut:n.balance,tradeableIn:s.tradeable,tradeableOut:n.tradeable,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,i),a=s===0n?0:et.calculateBuyFee(s,n),r=[],l=P.isSellAllowed(t.tradeableIn),c=P.isBuyAllowed(t.tradeableOut);(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&r.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return n>p&&r.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),a=et.calculateSellFee(s,n),r=[],l=P.isSellAllowed(t.tradeableIn),c=P.isBuyAllowed(t.tradeableOut);(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&r.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return n>p&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:n,feePct:a,errors:r}}calculateInGivenOut(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,i);let s=P.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?W.toRaw(i.assetFee).toString():"0",i?W.toRaw(i.protocolFee).toString():"0",i?W.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateLrnaInGivenOut(t,e,i){let s=P.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?W.toRaw(i.assetFee).toString():"0",i?W.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,i);let s=P.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?W.toRaw(i.assetFee).toString():"0",i?W.toRaw(i.protocolFee).toString():"0",i?W.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateOutGivenLrnaIn(t,e,i){let s=P.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?W.toRaw(i.assetFee).toString():"0",i?W.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=P.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceLrnaInGivenOut(t){let e=P.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=P.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}spotPriceOutGivenLrnaIn(t){let e=P.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,i){let s=e-i;if(s===0)return t;let n=Re.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var Q=require("polkadot-api"),Le=require("@polkadot-api/utils"),f=require("rxjs"),De=require("@galacticcouncil/common");var{FeeUtils:S}=I,Ce=Q.Binary.fromText("omnipool"),Me=(0,Q.Enum)("Short"),Pt=class extends E{queryBus=new Nt;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:"best"}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:"best"}),t=>String(t),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:"best"}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(Ce,t,Me,{at:"best"}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,Le.toHex)(e);return(0,Q.AccountId)(De.HYDRATION_SS58_PREFIX).dec(i)}getOraclePair(t){return t===0?[0,1]:[1,t]}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Q.CompatibilityLevel.BackwardsCompatible,e)}async isSlipFeeSupported(){return this.apiNext.query.Omnipool.SlipFee.isCompatible(Q.CompatibilityLevel.Partial)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,s,n,a,r]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:"best"}),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.balance.getBalance(e,t),this.getPoolLimits()]),l=i.map(async({keyArgs:u,value:p})=>{let[g]=u,{hub_reserve:y,shares:b,tradable:A,cap:Y,protocol_shares:X}=p,[R,q]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(g),this.balance.getBalance(e,g)]);return{id:g,decimals:R?.decimals,existentialDeposit:R?.existential_deposit,balance:q.transferable,cap:Y,hubReserves:y,protocolShares:X,shares:b,tradeable:A,type:R?.asset_type.type}}),c=await Promise.all(l);return c.push({id:t,decimals:n?.decimals,existentialDeposit:n?.existential_deposit,balance:a.transferable,tradeable:s,type:n?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:c,...r}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,s=0;await this.isSlipFeeSupported()&&(s=await this.maxSlipFee.get()??0);let a=await this.dynamicFeesConfig.get(e);if(a?.type==="Fixed"){let{asset_fee:L,protocol_fee:K}=a.value;return{assetFee:S.fromPermill(L),protocolFee:S.fromPermill(K),maxSlipFee:S.fromPermill(s)}}let r=this.getOraclePair(e),l=this.getOraclePair(i),[c,u,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(r),this.emaOracles.get(l)]),[g,y,b]=await this.getAssetFee(t,this.block,c,u,a?.value.asset_fee_params),[A,Y,X]=i===1?[0,0,0]:await this.getProtocolFee(t,this.block,c,p,a?.value.protocol_fee_params),R=g+A,q=b+X;return{assetFee:S.fromPermill(y),protocolFee:S.fromPermill(Y),maxSlipFee:S.fromPermill(s),min:S.fromPermill(R),max:S.fromPermill(q)}}async getAssetFee(t,e,i,s,n){let{assetOut:a,balanceOut:r}=t,{min_fee:l,max_fee:c,decay:u,amplification:p}=n||await this.api.constants.DynamicFees.AssetFeeParameters();if(!i||!s)return[l,l,c];let g=S.fromPermill(l),y=S.fromPermill(c),[b]=s,{asset_fee:A,timestamp:Y}=i,X=Math.max(1,e-Y),R=b.volume.b_in.toString(),q=b.volume.b_out.toString(),L=b.liquidity.b.toString();a===0&&(R=b.volume.a_in.toString(),q=b.volume.a_out.toString(),L=b.liquidity.a.toString());let K=S.fromPermill(A),mt=P.recalculateAssetFee(R,q,L,"9",r.toString(),S.toRaw(K).toString(),X.toString(),S.toRaw(g).toString(),S.toRaw(y).toString(),u.toString(),p.toString());return[l,Number(mt)*1e6,c]}async getProtocolFee(t,e,i,s,n){let{assetIn:a,balanceIn:r}=t,{min_fee:l,max_fee:c,decay:u,amplification:p}=n||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!i||!s)return[l,l,c];let g=S.fromPermill(l),y=S.fromPermill(c),[b]=s,{protocol_fee:A,timestamp:Y}=i,X=Math.max(1,e-Y),R=b.volume.b_in.toString(),q=b.volume.b_out.toString(),L=b.liquidity.b.toString();a===0&&(R=b.volume.a_in.toString(),q=b.volume.a_out.toString(),L=b.liquidity.a.toString());let K=S.fromPermill(A),mt=P.recalculateProtocolFee(R,q,L,"9",r.toString(),S.toRaw(K).toString(),X.toString(),S.toRaw(g).toString(),S.toRaw(y).toString(),u.toString(),p.toString());return[l,Number(mt)*1e6,c]}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(s=>s.id).map(s=>this.getOraclePair(s)).map(s=>this.api.query.EmaOracle.Oracles.watchValue(Ce,s,Me,"best").pipe((0,f.filter)(n=>n!==void 0),(0,f.map)((n,a)=>({value:n,index:a})),(0,f.tap)(({index:n})=>{n>0&&this.log.trace("emaOracle.Oracles",s.join(":"))}),(0,f.map)(({value:n})=>({pair:s,value:n}))));return(0,f.merge)(...i).pipe((0,f.finalize)(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(s=>{let{pair:n,value:a}=s;this.emaOracles.set(a,n)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,f.distinctUntilChanged)((t,e)=>!e.deltas),(0,f.map)((t,e)=>({value:t,index:e})),(0,f.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),(0,f.finalize)(()=>this.dynamicFees.clear()),this.watchGuard("dynamicFees.AssetFee")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFees.set(e.value,i)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe((0,f.distinctUntilChanged)((t,e)=>!e.deltas),(0,f.map)((t,e)=>({value:t,index:e})),(0,f.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),(0,f.finalize)(()=>this.dynamicFeesConfig.clear()),this.watchGuard("dynamicFees.AssetFeeConfiguration")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFeesConfig.set(e.value,i)})})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,f.distinctUntilChanged)((t,e)=>!e.deltas),(0,f.map)((t,e)=>({value:t,index:e})),(0,f.tap)(({value:t,index:e})=>{e>0&&this.log.trace("omnipool.Assets",t.deltas?.upserted)}),this.watchGuard("omnipool.Assets")).subscribe(({value:{deltas:t}})=>{this.store.update(([e])=>{let i=t?.upserted.reduce((n,a)=>{let[r]=a.args;return n.set(r,a.value),n},new Map),s=e.tokens.map(n=>{let a=i?.get(n.id);return a?this.updateTokenState(n,a):n});return[{...e,tokens:s}]})})}subscribeUpdates(){let t=new f.Subscription;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:i,shares:s,tradable:n,cap:a,protocol_shares:r}=e;return{...t,cap:a,hubReserves:i,protocolShares:r,shares:s,tradeable:n}}};var ue={};H(ue,{StableMath:()=>_,StableSwap:()=>nt,StableSwapClient:()=>St});var x=require("@galacticcouncil/math-stableswap"),_=class{static getPoolAddress(t){return(0,x.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let i=0;i<t;i++)e.push(["1","1"]);return e}static calculateAmplification(t,e,i,s,n){return(0,x.calculate_amplification)(t,e,i,s,n)}static calculateInGivenOut(t,e,i,s,n,a,r){return(0,x.calculate_in_given_out)(t,e,i,s,n,a,r)}static calculateAddOneAsset(t,e,i,s,n,a,r){return(0,x.calculate_add_one_asset)(t,e,i,s,n,a,r)}static calculateSharesForAmount(t,e,i,s,n,a,r){return(0,x.calculate_shares_for_amount)(t,e,i,s,n,a,r)}static calculateOutGivenIn(t,e,i,s,n,a,r){return(0,x.calculate_out_given_in)(t,e,i,s,n,a,r)}static calculateLiquidityOutOneAsset(t,e,i,s,n,a,r){return(0,x.calculate_liquidity_out_one_asset)(t,e,i,s,n,a,r)}static calculateShares(t,e,i,s,n,a){return(0,x.calculate_shares)(t,e,i,s,n,a)}static calculateSpotPriceWithFee(t,e,i,s,n,a,r,l){return(0,x.calculate_spot_price_with_fee)(t,e,i,s,n,a,r,l)}static recalculatePegs(t,e,i,s,n,a){let r=(0,x.recalculate_peg)(t,e,i,s,n,a);return JSON.parse(r)}};var vt=require("@galacticcouncil/common");var{FeeUtils:ct}=I,nt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new o(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(a=>[a.id,a])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:n.tradeable,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,i),a=s===0n?0:et.calculateBuyFee(s,n),r=[],l=P.isSellAllowed(t.tradeableIn),c=P.isBuyAllowed(t.tradeableOut);return(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:a,errors:r}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),a=et.calculateSellFee(s,n),r=[],l=P.isSellAllowed(t.tradeableIn),c=P.isBuyAllowed(t.tradeableOut);return(!l||!c)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:n,feePct:a,errors:r}}calculateIn(t,e,i){let s=_.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateAddOneAsset(t,e,i){let s=_.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateSharesForAmount(t,e,i){let s=_.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateInGivenOut(t,e,i){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,i):t.assetIn==this.id?this.calculateSharesForAmount(t,e,i):this.calculateIn(t,e,i)}spotPriceInGivenOut(t){let e=_.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetOut===this.id,t.assetIn===this.id,t.decimalsOut,t.decimalsIn)}calculateOut(t,e,i){let s=_.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateWithdrawOneAsset(t,e,i){let s=_.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateShares(t,e,i){let s=_.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?ct.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e,i){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,i):t.assetOut==this.id?this.calculateShares(t,e,i):this.calculateOut(t,e,i)}spotPriceOutGivenIn(t){let e=_.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetIn===this.id,t.assetOut===this.id,t.decimalsIn,t.decimalsOut)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:i,decimals:s})=>({asset_id:e,amount:i,decimals:s}));return JSON.stringify(t,dt.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],dt.jsonFormatter)}normalizeSpot(t,e,i,s,n){return e?t*vt.big.pow10(vt.RUNTIME_DECIMALS-n):i?t/vt.big.pow10(n-s):t}};var Kt=require("polkadot-api"),qe=require("@polkadot-api/utils"),He=require("@noble/hashes/blake2b"),M=require("rxjs"),jt=require("@galacticcouncil/common");var{FeeUtils:ki}=I,St=class extends E{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=_.getPoolAddress(t),i=(0,He.blake2b)(e,{dkLen:32}),s=(0,qe.toHex)(i);return(0,Kt.AccountId)(jt.HYDRATION_SS58_PREFIX).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:i,final_amplification:s,initial_block:n,final_block:a}=t,r=_.calculateAmplification(i.toString(),s.toString(),n.toString(),a.toString(),e.toString()),l=Number(r)<s;return{amplification:BigInt(r),isRampPeriod:l}}async getPoolTokens(t,e){let i=this.getPoolAddress(t),s=e.assets.map(async n=>{let[a,r,l]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,n),this.api.query.AssetRegistry.Assets.getValue(n),this.balance.getBalance(i,n)]);return{id:n,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:l.transferable,tradeable:a,type:r?.asset_type.type}});return Promise.all(s)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(Kt.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:"best"}),this.api.query.System.Number.getValue({at:"best"}),this.getPoolLimits()]),s=t.map(async({keyArgs:n,value:a})=>{let[r]=n,l=this.getPoolAddress(r),[c,u,p]=await Promise.all([this.getPoolTokens(r,a),this.api.query.Stableswap.PoolPegs.getValue(r,{at:"best"}),this.api.query.Tokens.TotalIssuance.getValue(r,{at:"best"})]),g=this.getPoolAmplification(a,e),y=u?this.getRecentPegs(u):this.getDefaultPegs(a);return c.push({id:r,tradeable:15,balance:p,decimals:jt.RUNTIME_DECIMALS}),this.poolsData.set(r,a),{address:l,id:r,type:"Stableswap",fee:ki.fromPermill(a.fee),tokens:c,totalIssuance:p,pegs:y,...i,...g}});return Promise.all(s)}async getPoolFees(t,e){return{fee:this.store.pools.find(s=>s.address===e).fee}}getDefaultPegs(t){return _.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([i,s])=>s.map(n=>n.toString()))}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,"best").pipe((0,M.map)((s,n)=>({value:s,index:n})),(0,M.tap)(({index:s,value:n})=>{s>0&&this.log.trace("tokens.TotalIssuance",i,n)}),(0,M.map)(({value:s})=>({id:i,value:s}))));return(0,M.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:s,value:n}=i;this.store.update(a=>{let r=[];return a.filter(l=>l.id===s).forEach(l=>{let c=l.tokens.map(u=>u.id===s?{...u,balance:n}:u);r.push({...l,tokens:c,totalIssuance:n})}),r})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,M.distinctUntilChanged)((t,e)=>!e.deltas),(0,M.map)((t,e)=>({value:t,index:e})),(0,M.tap)(({value:t,index:e})=>{e>0&&this.log.trace("stableswap.PoolPegs",t.deltas?.upserted)}),this.watchGuard("stableswap.PoolPegs")).subscribe({error:t=>this.log.error("stableswap.PoolPegs",t),next:({value:{deltas:t}})=>{this.store.update(e=>{let i=[],s=new Map(e.map(n=>[n.id,n]));return t?.upserted.forEach(({args:n,value:a})=>{let[r]=n,l=s.get(r);if(l){let c=this.getRecentPegs(a);i.push({...l,pegs:c})}}),i})}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(e=>{let i=[];return e.filter(s=>s.isRampPeriod).forEach(s=>{let n=this.poolsData.get(s.id);if(n){let a=this.getPoolAmplification(n,t);i.push({...s,...a})}}),i})})}subscribeUpdates(){let t=new M.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var pe={};H(pe,{XykMath:()=>Z,XykPool:()=>xt,XykPoolClient:()=>wt});var w=require("@galacticcouncil/math-xyk"),Z=class{static getSpotPrice(t,e,i){return(0,w.get_spot_price)(t,e,i)}static calculateInGivenOut(t,e,i){return(0,w.calculate_in_given_out)(t,e,i)}static calculateOutGivenIn(t,e,i){return(0,w.calculate_out_given_in)(t,e,i)}static calculatePoolTradeFee(t,e,i){return(0,w.calculate_pool_trade_fee)(t,e,i)}static calculateLiquidityIn(t,e,i){return(0,w.calculate_liquidity_in)(t,e,i)}static calculateSpotPrice(t,e){return(0,w.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,i,s){return(0,w.calculate_spot_price_with_fee)(t,e,i,s)}static calculateShares(t,e,i){return(0,w.calculate_shares)(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,s){return(0,w.calculate_liquidity_out_asset_a)(t,e,i,s)}static calculateLiquidityOutAssetB(t,e,i,s){return(0,w.calculate_liquidity_out_asset_b)(t,e,i,s)}};var Ne=require("@galacticcouncil/common");var{FeeUtils:Ge}=I,xt=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new o(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(a=>[a.id,a])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:s.balance,balanceOut:n.balance,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=this.calculateTradeFee(s,i),a=Ge.toPct(i.exchangeFee),r=s+n,l=[];(e<this.minTradingLimit||s<t.assetInEd)&&l.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&l.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return r>u&&l.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:a,errors:l}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=this.calculateTradeFee(s,i),a=Ge.toPct(i.exchangeFee),r=s-n,l=[];(e<this.minTradingLimit||s<t.assetOutEd)&&l.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&l.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return r>u&&l.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:a,errors:l}}calculateInGivenOut(t,e){let i=Z.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e){let i=Z.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){let e=Z.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=Z.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=Z.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(i)}normalizeSpot(t,e,i){let s=e-i;if(s===0)return t;let n=Ne.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var ze=require("polkadot-api"),Ve=require("rxjs");var wt=class extends E{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(ze.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries(),this.getPoolLimits()]),i=t.map(async({keyArgs:s,value:n})=>{let[a]=s,[r,l]=n,[c,u,p,g]=await Promise.all([this.balance.getBalance(a,r),this.api.query.AssetRegistry.Assets.getValue(r),this.balance.getBalance(a,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:a,type:"XYK",tokens:[{id:r,decimals:u?.decimals||this.decimals.get(r),existentialDeposit:u?.existential_deposit,balance:c.transferable,type:u?.asset_type.type},{id:l,decimals:g?.decimals||this.decimals.get(l),existentialDeposit:g?.existential_deposit,balance:p.transferable,type:g?.asset_type.type}],...e}});return Promise.all(i)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return Ve.Subscription.EMPTY}};var me={};H(me,{AavePool:()=>Ot,AavePoolClient:()=>It});var ut=require("@galacticcouncil/common");var Ot=class o{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new o(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(a=>[a.id,a])),s=i.get(t),n=i.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,i){let s=this.calculateInGivenOut(t,e),n=[];return e>t.balanceOut&&n.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:n}}validateAndSell(t,e,i){let s=this.calculateOutGivenIn(t,e),n=[];return s>t.balanceOut&&n.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:n}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return ut.big.toBigInt(1,ut.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return ut.big.toBigInt(1,ut.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var We=require("polkadot-api"),Ue=require("@polkadot-api/utils"),U=require("rxjs"),Ye=require("viem"),Jt=require("@galacticcouncil/common");var $e=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"}];var{ERC20:Ei}=Jt.erc20,Ri=["Supply","Withdraw","Repay","Borrow"],It=class extends E{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,s=new TextEncoder().encode(i.padEnd(32,"\0")),n=(0,Ue.toHex)(s);return(0,We.AccountId)(Jt.HYDRATION_SS58_PREFIX).dec(n)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:"best"})).map(async({reserve:i,atoken:s,liqudity_in:n,liqudity_out:a})=>{let[r,l,c,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i),this.api.query.AssetRegistry.AssetLocations.getValue(i),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(i,s),type:"Aave",tokens:[{id:i,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:n,location:l,type:r?.asset_type.type},{id:s,decimals:c?.decimals,existentialDeposit:c?.existential_deposit,balance:a,location:u,type:c?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:s,liqudity_out:n}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:"best"});return t.tokens.map(a=>{let r=a.id===e.id?s:n;return{...a,balance:r}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key.asHex()}throw new Error("Invalid aave reserve multilocation")}return Ei.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:i}=t;return{assetIn:e,assetOut:i,key:`${e}:${i}`}}parseEvmLog(t){let{topics:e,data:i}=t.log,s=e.map(a=>a.asHex()),n=i.asHex();try{let{eventName:a,args:r}=(0,Ye.decodeEventLog)({abi:$e,topics:s,data:n}),l=r.reserve.toLowerCase();return{eventName:a,reserve:l,key:`${a}:${l}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(i=>i.tokens).map(([i,s])=>s).map(i=>i.id);return this.api.event.Router.Executed.watch().pipe((0,U.map)(({payload:i})=>this.parseRouterLog(i)),(0,U.filter)(({assetIn:i,assetOut:s})=>e.includes(i)||e.includes(s)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:s,key:n})=>{this.log.trace("router.Executed",n),this.store.update(async a=>{let r=[];for(let l of a){let[c,u]=l.tokens;if(u.id===i||u.id===s){let g=await this.getPoolDelta(l);r.push({...l,tokens:g})}}return r})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,U.map)(({payload:t})=>this.parseEvmLog(t)),(0,U.filter)(t=>t!==void 0),(0,U.filter)(({eventName:t})=>Ri.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async i=>{let s=[];for(let n of i){let[a]=n.tokens;if(this.getReserveH160Id(a).toLowerCase()===t){let l=await this.getPoolDelta(n);s.push({...n,tokens:l})}}return s})})}subscribeBalances(){return U.Subscription.EMPTY}subscribeUpdates(){let t=new U.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var he={};H(he,{HsmMath:()=>D,HsmPool:()=>Tt,HsmPoolClient:()=>At});var B=require("@galacticcouncil/math-hsm"),D=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,B.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,B.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,B.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,B.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,B.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,B.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,B.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,B.calculate_max_price)(t,e)}};var F=require("@galacticcouncil/common");var{FeeUtils:pt}=I,Tt=class o extends nt{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new o(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,i){let s=this.parsePair(t.assetOut,t.assetIn),n=super.calculateInGivenOut(s,e,{fee:this.fee}),a=this.calculateBuybackLimit(t);e>a&&i.push("MaxBuyBackExceeded");let r=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,n)>r&&i.push("MaxBuyPriceExceeded"),n>this.collateralBalance&&i.push("InsufficientCollateral"),i}validateTradeHollarOut(t,e,i){return this.collateralBalance+t>this.maxInHolding&&i.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&i.push("FacilitatorCapacityExceeded"),i}validateTradeConstraints(t,e,i){let s=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,s):this.validateTradeHollarOut(e,i,s)}validateAndBuy(t,e){let i=this.calculateInGivenOut(t,e),s=this.validateTradeConstraints(t,i,e);return{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e){let i=this.calculateOutGivenIn(t,e),s=this.validateTradeConstraints(t,e,i);return{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(t,e){let i=super.calculateInGivenOut(t,e,{fee:this.fee}),s=D.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),pt.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=D.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),pt.toRaw(this.purchaseFee).toString());return BigInt(i)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let i=super.calculateOutGivenIn(t,e,{fee:this.fee}),s=D.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),pt.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=D.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),pt.toRaw(this.purchaseFee).toString());return BigInt(i)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),i=D.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=D.calculateBuybackLimit(e.toString(),pt.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let s=D.calculateBuybackPriceWithFee(i.toString(),e.toString(),pt.toRaw(this.buyBackFee).toString()),[n,a]=JSON.parse(s),r=F.big.pow10(t.decimalsIn+F.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(n)*r/BigInt(a)}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=D.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[s,n]=JSON.parse(i),a=F.big.pow10(F.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(s)*a/BigInt(n)}spotPriceInGivenOut(t){let e=F.big.toBigInt(1,t.decimalsOut),s=this.calculateInGivenOut(t,e)*F.big.pow10(F.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(s,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=F.big.toBigInt(1,t.decimalsIn),s=this.calculateOutGivenIn(t,e)*F.big.pow10(F.RUNTIME_DECIMALS-t.decimalsIn);return this.normalizeSpotPrice(s,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(s=>s.id!==this.hollarId),e=this.pegs[t],i=this.tokens[t].decimals;return this.isDefaultPeg(e)?[F.big.toBigInt(1,18).toString(),F.big.toBigInt(1,i).toString()]:e}isDefaultPeg(t){let[e,i]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&i==="1"}normalizeSpotPrice(t,e,i){let s=e-i;if(s===0)return t;let n=F.big.pow10(Math.abs(s));return s>0?t*n:t/n}};var Qt=require("polkadot-api"),Ke=require("@polkadot-api/utils"),k=require("rxjs"),je=require("viem"),Zt=require("@galacticcouncil/common");var _t=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var Bt=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,s]=await this.client.readContract({abi:_t,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-s}};var{FeeUtils:de}=I,{H160:Xe}=Zt.h160,Ci=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],At=class extends E{ghoClient;stableClient;constructor(t,e,i){super(t,e),this.stableClient=i,this.ghoClient=new Bt(e)}getPoolType(){return"HSM"}getPoolId(t){return this.getPoolAddress("hsm:"+t)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(t){if(t){let e=t.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key.asHex()}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),i=new TextEncoder().encode(e),s=(0,Ke.toHex)(i);return(0,Qt.AccountId)(Zt.HYDRATION_SS58_PREFIX).dec(s)}async isSupported(){let t=this.api.query.HSM.Collaterals,e=await this.api.compatibilityToken;return t.isCompatible(Qt.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,s]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t),this.api.query.HSM.Collaterals.getEntries({at:"best"}),this.stableClient.getPools()]);if(i.length===0)return[];let n=this.getFacilitatorAddress(),a=Xe.fromAny(n),r=this.getHollarAddress(e),l=await this.ghoClient.getFacilitatorCapacity(r,a),c=i.map(async({keyArgs:p,value:g})=>{let[y]=p,{pool_id:b,max_buy_price_coefficient:A,max_in_holding:Y,purchase_fee:X,buy_back_fee:R,buyback_rate:q}=g,L=s.find(K=>K.id===b);if(L){let K=this.getPoolId(b),mt=await this.balance.getBalance(n,y);return{...L,address:K,type:"HSM",tokens:L.tokens.filter(Qe=>Qe.id!==b),hsmAddress:n,hsmMintCapacity:l,hollarId:t,hollarH160:r,collateralId:y,collateralBalance:mt.transferable,maxBuyPriceCoefficient:A,maxInHolding:Y,purchaseFee:de.fromPermill(X),buyBackFee:de.fromPermill(R),buyBackRate:de.fromPerbill(q)}}});return(await Promise.all(c)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:i}=t.log,s=e.map(a=>a.asHex()),n=i.asHex();try{let{eventName:a,args:r}=(0,je.decodeEventLog)({abi:_t,topics:s,data:n}),l=r.facilitatorAddress.toLowerCase();return{eventName:a,facilitator:l,key:`${a}:${l}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,k.map)(({payload:t})=>this.parseEvmLog(t)),(0,k.filter)(t=>t!==void 0),(0,k.filter)(({eventName:t})=>Ci.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async i=>{let s=[],[{hsmAddress:n,hollarH160:a}]=i,r=Xe.fromAny(n);if(r.toLowerCase()===e){let c=await this.ghoClient.getFacilitatorCapacity(a,r);for(let u of i)s.push({...u,hsmMintCapacity:c})}return s})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(n=>{let{tokens:a,collateralId:r}=n;a.find(c=>c.id===r).type==="Erc20"?e.push(r):t.push(r)});let[{hsmAddress:i}]=this.store.pools,s=[];if(t.length>0){let n=this.balance.watchTokensBalance(i);s.push(n)}if(e.length>0){let n=this.balance.watchErc20Balance(i,e);s.push(n)}return s.length>0?(0,k.combineLatest)(s).pipe((0,k.map)(n=>n.flat()),(0,k.pairwise)(),(0,k.map)(([n,a])=>this.balance.getDeltas(n,a)),this.watchGuard("balances")).subscribe(n=>{this.store.update(a=>{let r=[],l=new Map(a.map(c=>[c.collateralId,c]));return n.forEach(({id:c,balance:u})=>{let p=l.get(c);p&&(this.log.trace("balances",{id:c,balance:u}),r.push({...p,collateralBalance:u.transferable}))}),r})}):k.Subscription.EMPTY}subscribeStableswapUpdates(){return this.stableClient.getSubscriber().pipe(this.watchGuard("stableswap.updates")).subscribe(t=>{let e=new Map(t.map(i=>[i.id,i]));this.store.update(i=>{let s=[];for(let n of i){let a=e.get(n.id);a&&s.push({...n,fee:a.fee,tokens:a.tokens.filter(r=>r.id!==n.id),totalIssuance:a.totalIssuance,pegs:a.pegs,amplification:a.amplification,isRampPeriod:a.isRampPeriod})}return s})})}subscribeBalances(){return k.Subscription.EMPTY}subscribeUpdates(){let t=new k.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var te=class{static get(t){switch(t.type){case"Aave":return Ot.fromPool(t);case"XYK":return xt.fromPool(t);case"Omnipool":return yt.fromPool(t);case"LBP":return gt.fromPool(t);case"Stableswap":return nt.fromPool(t);case"HSM":return Tt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var Je=require("@galacticcouncil/common"),N=require("rxjs");var ee=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}};var{logger:Mi}=Je.log,ie=class extends ${evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=N.Subscription.EMPTY;omniSub=N.Subscription.EMPTY;stableSub=N.Subscription.EMPTY;hsmSub=N.Subscription.EMPTY;xykSub=N.Subscription.EMPTY;lbpSub=N.Subscription.EMPTY;isReady=!1;isDestroyed=new N.Subject;constructor(t,e){super(t),this.evm=e,this.aave=new It(t,e),this.omnipool=new Pt(t,e),this.stableswap=new St(t,e),this.hsm=new At(t,e,this.stableswap),this.xyk=new wt(t,e),this.lbp=new ft(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe((0,N.takeUntil)(this.isDestroyed)).subscribe(e=>{e.forEach(i=>{this.pools.set(i.address,i)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.active.has("Stableswap")||(Mi.info("[PoolContextProvider] auto-activating stableswap"),this.withStableswap()),this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let i=this.clients.find(s=>s.getPoolType()===e.type);if(i)return i.getPoolFees(t,e.address);throw new ee(e.type)}};0&&(module.exports={PoolContextProvider,PoolError,PoolFactory,PoolType,aave,hsm,lbp,omni,stable,xyk});