@galacticcouncil/sdk-next 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.cjs +1 -1
- package/build/index.mjs +1 -1
- package/build/types/api/ChainWatcher.d.ts +11 -0
- package/build/types/api/Papi.d.ts +2 -1
- package/build/types/api/index.d.ts +1 -0
- package/build/types/api/probe.d.ts +19 -0
- package/build/types/pool/PoolClient.d.ts +45 -1
- package/build/types/pool/PoolLog.d.ts +11 -0
- package/build/types/sor/TradeScheduler.d.ts +1 -1
- package/build/types/utils/async.d.ts +1 -0
- package/build/types/utils/calc.d.ts +38 -0
- package/build/types/utils/index.d.ts +2 -0
- package/build/types/utils/math.d.ts +0 -9
- package/package.json +3 -3
- package/build/types/api/utils.d.ts +0 -1
- package/build/types/sor/TradeRouter.utils.d.ts +0 -1
package/build/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Qn=Object.create;var we=Object.defineProperty;var Jn=Object.getOwnPropertyDescriptor;var Zn=Object.getOwnPropertyNames;var ts=Object.getPrototypeOf,es=Object.prototype.hasOwnProperty;var R=(u,t)=>{for(var e in t)we(u,e,{get:t[e],enumerable:!0})},zi=(u,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Zn(t))!es.call(u,n)&&n!==e&&we(u,n,{get:()=>t[n],enumerable:!(i=Jn(t,n))||i.enumerable});return u};var dt=(u,t,e)=>(e=u!=null?Qn(ts(u)):{},zi(t||!u||!u.__esModule?we(e,"default",{value:u,enumerable:!0}):e,u)),is=u=>zi(we({},"__esModule",{value:!0}),u);var ks={};R(ks,{QueryBus:()=>jt,aave:()=>li,api:()=>ni,client:()=>mi,const:()=>pi,createSdkContext:()=>Es,error:()=>gi,evm:()=>bi,farm:()=>xi,fmt:()=>_,json:()=>Ot,math:()=>O,pool:()=>Ci,sor:()=>Ni,staking:()=>Gi,tx:()=>Vi});module.exports=is(ks);var ni={};R(ni,{Papi:()=>N,getWs:()=>ns});var Ki=require("@galacticcouncil/descriptors");function Xi(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var N=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(Ki.hydration)}log(t,...e){let i=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Xi(i)&&console.log(t,...e)}};var $i=require("polkadot-api/logs-provider"),ji=require("@polkadot-api/legacy-provider"),Qi=require("polkadot-api/ws-provider"),ns=(u,t={})=>{let e=typeof u=="string"?u.split(","):u,i=(0,Qi.getWsProvider)(e,{innerEnhancer:(0,ji.withLegacy)(),...t});return(0,$i.withLogsRecorder)(n=>console.log(n),i),i};var li={};R(li,{AAVE_GAS_LIMIT:()=>ai,AAVE_LENDING_POOL_ADDRESS:()=>Ae,AAVE_POOL_ABI:()=>si,AAVE_POOL_DATA_PROVIDER:()=>_e,AAVE_POOL_DATA_PROVIDER_ABI:()=>Ie,AAVE_POOL_PROXY:()=>ri,AAVE_ROUNDING_THRESHOLD:()=>Xs,AAVE_UINT_256_MAX:()=>ss,AaveClient:()=>Vt,AaveUtils:()=>Pt});var si=[{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 Ie=[{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 ri="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",_e="0x112b087b60C1a166130d59266363C45F8aa99db0",Ae="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ai=1000000n,Xs=5,ss=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Vt=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:Ie,address:_e,args:[Ae],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:Ie,address:_e,args:[Ae,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:si,address:ri,args:[t],functionName:"getUserAccountData"})}};var L=dt(require("big.js")),J=require("@galacticcouncil/common");var{ERC20:xt}=J.erc20,{H160:oi}=J.h160,rs=1.01,as=31536000n,Ji=4,Oe=-1,Be=10n**27n,Pt=class{client;constructor(t){this.client=new Vt(t)}async getSummary(t){let e=oi.fromAny(t),[i,n,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[a]=i,[o,l]=n,[c,p,m,d,g,b]=s,h=J.big.toDecimal(b,18),f=[];for(let y of o){let S=y.underlyingAsset.toLowerCase(),v=a.find(({underlyingAsset:ii})=>ii.toLowerCase()===S);if(!v)throw new Error("Missing pool reserve for "+S);let x=y.scaledATokenBalance,A=v.liquidityIndex,D=v.liquidityRate,G=v.availableLiquidity,rt=v.priceInMarketReferenceCurrency,ut=r+6,K=this.calculateLinearInterest(D,v.lastUpdateTimestamp,ut),Q=A*K/Be,Ut=x*Q/Be,Se=Number(l!==0&&l===v.eModeCategoryId?v.eModeLiquidationThreshold:v.reserveLiquidationThreshold)/1e4,Te=v.usageAsCollateralEnabled&&y.usageAsCollateralEnabledOnUser&&y.scaledATokenBalance>0n,xe=xt.toAssetId(S);f.push({aTokenBalance:Ut,availableLiquidity:G,decimals:Number(v.decimals),isCollateral:Te,priceInRef:rt,reserveId:xe,reserveAsset:S,reserveLiquidationThreshold:Se})}return{healthFactor:Number(h),currentLiquidationThreshold:Number(J.big.toDecimal(d,Ji)),totalCollateral:c,totalDebt:p,reserves:f}}async hasBorrowPositions(t){let e=oi.fromAny(t),i=await this.client.getUserAccountData(e),[n,s]=i;return s>0n}async getHealthFactor(t){let e=oi.fromAny(t),i=await this.client.getUserAccountData(e),[n,s,r,a,o,l]=i;return this.calculateHealthFactorFromBalances(s,n,a)}async getHealthFactorAfterWithdraw(t,e,i){let{totalCollateral:n,totalDebt:s,reserves:r,currentLiquidationThreshold:a}=await this.getSummary(t);if(s===0n)return Oe;let o=xt.fromAssetId(e),l=r.find(S=>S.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:c,isCollateral:p,priceInRef:m,reserveLiquidationThreshold:d}=l,g=J.big.toBigInt(i,c),b=p?g*m/10n**BigInt(c):0n,h=n-b;if(h<=0n)return 0;let f=(0,L.default)(n.toString()).mul(a).minus((0,L.default)(b.toString()).mul(d)).div(h.toString()),y=(0,L.default)(h.toString()).mul(f).div(s.toString()).toFixed(6,L.default.roundDown);return Number(y)}async getHealthFactorAfterSupply(t,e,i){let{totalCollateral:n,totalDebt:s,reserves:r,currentLiquidationThreshold:a}=await this.getSummary(t);if(s===0n)return Oe;let o=xt.fromAssetId(e),l=r.find(y=>y.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:c,priceInRef:p,reserveLiquidationThreshold:m}=l,g=J.big.toBigInt(i,c)*p/10n**BigInt(c),b=n+g;if(b<=0n)return 0;let h=(0,L.default)(n.toString()).mul(a).plus((0,L.default)(g.toString()).mul(m)).div(b.toString()),f=(0,L.default)(b.toString()).mul(h).div(s.toString()).toFixed(6,L.default.roundDown);return Number(f)}async getHealthFactorAfterSwap(t,e,i,n,s){let{totalDebt:r,reserves:a,healthFactor:o}=await this.getSummary(t);if(r===0n)return Oe;let l=xt.fromAssetId(i),c=xt.fromAssetId(s),p=a.find(A=>A.reserveAsset===l),m=a.find(A=>A.reserveAsset===c);if(!p)throw new Error(`Missing reserve ctx for ${l}`);if(!m)throw new Error(`Missing reserve ctx for ${m}`);let d=J.big.toBigInt(e,p.decimals),g=J.big.toBigInt(n,m.decimals),b=d*p.priceInRef/10n**BigInt(p.decimals),h=g*m.priceInRef/10n**BigInt(m.decimals),f=p.isCollateral?(0,L.default)(b.toString()).mul(p.reserveLiquidationThreshold):(0,L.default)(0),v=(0,L.default)(h.toString()).mul(m.reserveLiquidationThreshold).minus(f).div(r.toString()),x=(0,L.default)(o).plus(v).toFixed(6,L.default.roundDown);return Number(x)}async getMaxWithdraw(t,e){let{totalDebt:i,reserves:n,healthFactor:s}=await this.getSummary(t),r=xt.fromAssetId(e),a=n.find(o=>o.reserveAsset===r);if(!a)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(a,i,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:i,healthFactor:n}=await this.getSummary(t),s={};for(let r of i){let a=this.calculateWithdrawMax(r,e,n);r.reserveId&&(s[r.reserveId]=a)}return s}calculateWithdrawMax(t,e,i){let{aTokenBalance:n,availableLiquidity:s,decimals:r,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=t,c=n;if(l&&e>0n){let m=i-rs;if(m>0){let d=(0,L.default)(m).mul(e.toString()).div(o).toFixed(0,L.default.roundDown),g=(0,L.default)(d).div(a.toString()).mul(10**r).toFixed(0,L.default.roundDown);c=n<BigInt(g)?n:BigInt(g)}else c=0n}return{amount:c<s?c:s,decimals:r}}calculateLinearInterest(t,e,i){let n=i-e;if(n<=0)return Be;let s=t*BigInt(n)/as;return Be+s}calculateHealthFactorFromBalances(t,e,i){if(t===0n)return Oe;let n=e*i/t,s=J.big.toDecimal(n,Ji);return Number(s)}};var mi={};R(mi,{AssetClient:()=>wt,BalanceClient:()=>at,ChainParams:()=>At});var wt=class extends N{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:i,value:n})=>{let[s]=i;return[s,n]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:i,value:n})=>{let[s]=i;return[s,n]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:i})=>{let{asset_type:n}=i;return this.SUPPORTED_TYPES.includes(n.type)}).map(({keyArgs:i,value:n})=>{let[s]=i;return[s,n]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:i,value:n})=>{let[s]=i;return[s,n]}))}async mapToken(t,e,i,n){let{name:s,asset_type:r,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:c}=i.get(t)??{};return{id:t,name:s?.asText(),symbol:l,decimals:c,icon:l,type:r.type,isSufficient:a,location:n,existentialDeposit:o}}async mapBond(t,e,i,n){let[s,r]=n,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:c,decimals:p}=await this.mapToken(s,e,i),m=Number(r),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(m)].join(" ");return{id:t,name:g,symbol:c+"b",decimals:p,icon:c,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:s,maturity:m}}async mapShares(t,e,i,n){let{assets:s}=n,{name:r,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:c}=e,p=await Promise.all(s.map(async g=>{let{symbol:b}=await this.mapToken(g,e,i);return[g,b]})),m=Object.fromEntries(p),d=Object.values(m);return{id:t,name:d.join(", "),symbol:a?.asText()||r?.asText(),decimals:18,icon:d.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:m}}async mapExternal(t,e,i,n){let s=await this.mapToken(t,e,new Map,n),r=i?.find(a=>a.internalId===s.id);return r?{...s,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.isWhiteListed}:s}parseMetadata(t){return new Map(Array.from(t,([e,i])=>[e,{symbol:i.symbol?.asText(),decimals:i.decimals}]))}async getOnChainAssets(t,e){let[i,n,s,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(i),o=[];for(let[l,c]of Array.from(i)){let p=n.get(l),{asset_type:m}=c,d;switch(m.type){case"Bond":let g=r.get(l);d=await this.mapBond(l,c,a,g);break;case"StableSwap":let b=s.get(l);d=await this.mapShares(l,c,a,b);break;case"External":d=await this.mapExternal(l,c,e,p);break;default:d=await this.mapToken(l,c,a,p)}o.push(d)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var w=require("rxjs");var pi={};R(pi,{HUB_ASSET_ID:()=>Wt,HYDRATION_OMNIPOOL_ADDRESS:()=>ls,HYDRATION_PARACHAIN_ID:()=>os,PERBILL_DENOMINATOR:()=>ci,PERMILL_DENOMINATOR:()=>It,SYSTEM_ASSET_DECIMALS:()=>ui,SYSTEM_ASSET_ID:()=>F,TRADEABLE_DEFAULT:()=>_t});var It=1e6,ci=1e9,F=0,ui=12,os=2034,ls="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Wt=1,_t=15;var at=class extends N{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:i}=await e.getValue(t,{at:"best"});return this.calculateBalance(i)}async getTokenBalance(t,e){let n=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.calculateBalance(n)}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),i=this.subscribeTokensBalance(t),n=this.subscribeErc20Balance(t);return(0,w.combineLatest)([e,i,n]).pipe((0,w.debounceTime)(250),(0,w.map)(s=>s.flat()),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([s,r],a)=>a===0?r:this.getDeltas(s,r)))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe((0,w.map)(i=>({id:0,balance:this.calculateBalance(i.data)})))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe((0,w.map)(n=>({id:e,balance:this.calculateBalance(n)})))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe((0,w.distinctUntilChanged)((i,n)=>!n.deltas),(0,w.map)(({deltas:i})=>{let n=[];return i?.deleted.forEach(s=>{let[r,a]=s.args;n.push({id:a,balance:this.calculateBalance({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(s=>{let[r,a]=s.args;n.push({id:a,balance:this.calculateBalance(s.value)})}),n}))}subscribeErc20Balance(t,e){let i=new w.Subject,n=i.pipe((0,w.shareReplay)(1)),s=async()=>(await this.api.query.AssetRegistry.Assets.getEntries({at:"best"})).filter(({value:l})=>{let{asset_type:c}=l;return c.type==="Erc20"}).map(({keyArgs:l})=>{let[c]=l;return c}),r=async()=>{let o=e||await s(),l=async()=>{let m=(await Promise.all(o.map(async d=>{let g=await this.getTokenBalanceData(t,d);return[d,g]}))).map(([d,g])=>({id:d,balance:g}));i.next(m)};await l();let c=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>c.unsubscribe()},a;return r().then(o=>a=o),n.pipe((0,w.finalize)(()=>a?.()),(0,w.pairwise)(),(0,w.map)(([o,l],c)=>c===0?l.filter(p=>p.balance.transferable>0n):this.getDeltas(o,l)),(0,w.distinctUntilChanged)((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.calculateBalance(i)}calculateBalance(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=(s,r)=>s!==void 0&&r!==void 0&&s.transferable===r.transferable&&s.total===r.total,n=t.reduce((s,r)=>(s.set(r.id,r.balance),s),new Map);return e.filter(s=>!i(s.balance,n.get(s.id)))}};var At=class extends N{_minOrderBudget;_blockTime;constructor(t){super(t)}async getBlockTime(){if(this._blockTime===void 0){let t=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(t)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var gi={};R(gi,{AssetNotFound:()=>di,PoolNotFound:()=>Yt,RouteNotFound:()=>zt});var di=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},Yt=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},zt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var bi={};R(bi,{EvmClient:()=>Kt,EvmRpcAdapter:()=>Xt,createChain:()=>hi});var vt=require("polkadot-api"),Zi=require("@galacticcouncil/descriptors"),Re=require("viem"),cs=10000000n,Xt=class{api;constructor(t){this.api=t.getTypedApi(Zi.hydration)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,i=e.timestamp/1000n,[n]=e.number;return{timestamp:i,number:n}}readContract=(async t=>{let{abi:e,address:i,functionName:n,args:s}=t,r=(0,Re.encodeFunctionData)({abi:e,functionName:n,args:s}),a=this.api.apis.EthereumRuntimeRPCApi.call,o=await this.api.compatibilityToken,l=a.isCompatible(vt.CompatibilityLevel.BackwardsCompatible,o);console.log(l);let c=await this.api.apis.EthereumRuntimeRPCApi.call(vt.FixedSizeBinary.fromText(""),vt.FixedSizeBinary.fromHex(i),vt.Binary.fromHex(r),[0n,0n,0n,0n],[cs,0n,0n,0n],void 0,void 0,void 0,!1,[]);if(console.log(c),!c.success)throw console.error(n,c.value.type),new Error("Contract read failure");let{exit_reason:p,value:m,used_gas:d}=c.value;if(console.log(d),p.type==="Succeed")return(0,Re.decodeFunctionResult)({abi:e,functionName:n,data:m.asHex()});throw console.log(n,p.type,p.value.type),new Error("Contract read error")})};var tn=require("viem"),us=["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"],hi=()=>(0,tn.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:us}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var ot=require("viem");var Kt=class{client;chain;constructor(t){this.client=t,this.chain=hi()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,ot.createPublicClient)({chain:this.chain,transport:(0,ot.http)()})}getWsProvider(){return(0,ot.createPublicClient)({transport:(0,ot.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,ot.createWalletClient)({account:t,chain:this.chain,transport:(0,ot.custom)(window.ethereum)})}getRPCAdapter(){return new Xt(this.client)}};var xi={};R(xi,{LiquidityMiningApi:()=>Qt,LiquidityMiningClient:()=>Jt});var dn=require("polkadot-api"),U=dt(require("big.js")),ht=require("@galacticcouncil/common"),Ti=require("@galacticcouncil/math-liquidity-mining");var _={};R(_,{FeeUtils:()=>yi,shiftNeg:()=>ps});var en=dt(require("big.js"));var yi=class u{static toPct(t){let[e,i]=t;return u.safeDivide(e*100,i)}static toRaw(t){let[e,i]=t;return u.safeDivide(e,i)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,i=12){let n=10**i;return Math.round(t*n/e)/n}static safeRound(t){return parseFloat(t.toPrecision(15))}};function ps(u,t){let e=(0,en.default)(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Ot={};R(Ot,{findNestedKey:()=>ms,findNestedObj:()=>ds,jsonFormatter:()=>gs});var ms=(u,t)=>{let e=[];return JSON.stringify(u,(i,n)=>(n&&n[t]&&e.push(n),n)),e[0]},ds=(u,t,e)=>{let i;return JSON.stringify(u,(n,s)=>(s&&s[t]===e&&(i=s),s)),i},gs=(u,t)=>typeof t=="bigint"?t.toString():t;var O={};R(O,{calculateBuyFee:()=>fs,calculateDiffToAvg:()=>hs,calculateDiffToRef:()=>bs,calculateSellFee:()=>ys,getFraction:()=>Ps});var lt=dt(require("big.js"));function hs(u,t){let e=(0,lt.default)(u.toString()),i=(0,lt.default)(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function bs(u,t){if(t===0n)return 0;let e=(0,lt.default)(u.toString()),i=(0,lt.default)(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function ys(u,t){if(u===0n)return 0;let e=(0,lt.default)(u.toString()),i=(0,lt.default)(t.toString());return(0,lt.default)(1).minus(i.div(e)).mul(100).round(2).toNumber()}function fs(u,t){if(u===0n)return 0;let e=(0,lt.default)(u.toString());return(0,lt.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function Ps(u,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let i=Math.pow(10,e),n=BigInt(t*i);return u*n/BigInt(100*i)}var $t=(u,t)=>u===t?0:u==null?t==null?0:-1:t==null?u==null?0:1:typeof u.compare=="function"?u.compare(t):typeof t.compare=="function"?-t.compare(u):u<t?-1:u>t?1:0;var Fe=(u,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(u(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var vs=Fe(()=>"illegal argument(s)"),nn=u=>{throw new vs(u)};var Ss=Fe(()=>"index out of bounds"),fi=u=>{throw new Ss(u)},Ce=(u,t,e)=>(u<t||u>=e)&&fi(u);var sn=23283064365386963e-26,Ee=class{float(t=1){return this.int()*sn*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*sn-.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 ke=class extends Ee{constructor(t){super(),this.rnd=t}float(t=1){return this.rnd()*t}norm(t=1){return(this.rnd()-.5)*2*t}int(){return this.rnd()*4294967296>>>0}};var rn=new ke(Math.random);var an=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var on=Object.getPrototypeOf({}),Me="function",ln="string",Bt=(u,t)=>{let e;if(u===t)return!0;if(u!=null){if(typeof u.equiv===Me)return u.equiv(t)}else return u==t;if(t!=null){if(typeof t.equiv===Me)return t.equiv(u)}else return u==t;return typeof u===ln||typeof t===ln?!1:(e=Object.getPrototypeOf(u),(e==null||e===on)&&(e=Object.getPrototypeOf(t),e==null||e===on)?Is(u,t):typeof u!==Me&&u.length!==void 0&&typeof t!==Me&&t.length!==void 0?Ts(u,t):u instanceof Set&&t instanceof Set?xs(u,t):u instanceof Map&&t instanceof Map?ws(u,t):u instanceof Date&&t instanceof Date?u.getTime()===t.getTime():u instanceof RegExp&&t instanceof RegExp?u.toString()===t.toString():u!==u&&t!==t)},Ts=(u,t,e=Bt)=>{let i=u.length;if(i===t.length)for(;i-- >0&&e(u[i],t[i]););return i<0},xs=(u,t,e=Bt)=>u.size===t.size&&e([...u.keys()].sort(),[...t.keys()].sort()),ws=(u,t,e=Bt)=>u.size===t.size&&e([...u].sort(),[...t].sort()),Is=(u,t,e=Bt)=>{if(Object.keys(u).length!==Object.keys(t).length)return!1;for(let i in u)if(!t.hasOwnProperty(i)||!e(u[i],t[i]))return!1;return!0};var Pi=class{value;constructor(t){this.value=t}deref(){return this.value}};var cn=u=>u instanceof Pi;var De=class u{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return un("next",this._head)}reverseIterator(){return un("prev",this.tail)}clear(){this.release()}compare(t,e=$t){let i=this._length;if(i<t._length)return-1;if(i>t._length)return 1;if(i===0)return 0;{let n=this._head,s=t._head,r=0;for(;i-- >0&&r===0;)r=e(n.value,s.value),n=n.next,s=s.next;return r}}concat(...t){let e=this.copy();for(let i of t)e.into(i);return e}equiv(t){if(!(t instanceof u||an(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),i=this._head;for(let n=this._length;n-- >0;){if(!Bt(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||$t;for(let i=this._head,n=this._length;n-- >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 n=this._length;n-- >0&&!cn(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 n=t.value;t.value=e.value,e.value=n,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&&fi(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 n=e;do{if(!t(n))break;n=n.next}while(n!==i);return n}_map(t,e){return this.traverse(i=>(t.append(e(i.value)),!0)),t}};function*un(u,t){for(;t;)yield t.value,t=t[u]}var Le=class u extends De{_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 u(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 u}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):(Ce(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):(Ce(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new u,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),n=this.nthCell(e-1),s=r=>({first(){return r.value},next(){return r!==n&&r.next?s(r.next):void 0}});return i?s(i):void 0}shuffle(t,e=rn){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 n=i.next;e.probability(.5)?this.asHead(i):this.asTail(i),i=n}}return this}slice(t=0,e=this.length){let i=t<0?t+this._length:t,n=e<0?e+this._length:e;(i<0||n<0)&&nn("invalid indices: ${from} / ${to}");let s=new u,r=this.nthCell(i);for(;r&&++i<=n;)s.push(r.value),r=r.next;return s}sort(t=$t){if(!this._length)return this;let e=1;for(;;){let i=this._head;this._head=void 0,this._tail=void 0;let n=0;for(;i;){n++;let s=i,r=0;for(let o=0;o<e&&(r++,s=s.next,!!s);o++);let a=e;for(;r>0||a>0&&s;){let o;r===0?(o=s,s=s.next,a--):!s||a===0||t(i.value,s.value)<=0?(o=i,i=i.next,r--):(o=s,s=s.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}i=s}if(this._tail.next=void 0,n<=1)return this;e*=2}}splice(t,e=0,i){let n;typeof t=="number"?(t<0&&(t+=this._length),Ce(t,0,this._length),n=this.nthCellUnsafe(t)):n=t;let s=new u;if(e>0)for(;n&&e-- >0;)this.remove(n),s.push(n.value),n=n.next;else n&&(n=n.next);if(i)if(n)for(let r of i)this.insertBefore(n,r);else for(let r of i)this.push(r);return s}};var qe=class u{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 Le,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 u(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),n=this.map.get(t),s=Math.max(0,i-(n?n.value.s:0));return this._size+=s,this.ensureSize()?this.doSetEntry(n,t,e,i):this._size-=s,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 n=this.items.drop();if(!n)return!1;this.map.delete(n.k),t?.(n.k,n.v),this._size-=n.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,n){t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=n,this.items.asTail(t)):(this.items.push({k:e,v:i,s:n}),this.map.set(e,this.items.tail))}};var St=class u extends qe{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new u(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 n=this.opts.ksize(t)+this.opts.vsize(e),s=this.map.get(t),r=Math.max(0,n-(s?s.value.s:0));return this._size+=r,this.ensureSize()?this.doSetEntry(s,t,e,n,i):this._size-=r,e}async getSet(t,e,i=this.opts.ttl){let n=this.get(t);return n!==void 0?n: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(),n=this.items.head;for(;n&&(this._size>e||this.length>=t);)n.value.t<i&&this.removeEntry(n),n=n.next;return super.ensureSize()}doSetEntry(t,e,i,n,s=this.opts.ttl){let r=Date.now()+s;t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=n,t.value.t=r,this.items.asTail(t)):(this.items.push({k:e,v:i,s:n,t:r,ttl:s}),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 jt=class{debug;constructor(t){this.debug=t||!1}log(t,e,i){this.debug&&console.log(t,e,i)}scope(t,e,i,n){let s=new Map,r=n!==void 0?new St(null,{ttl:n}):new St;return{get:(...c)=>{let p=i(...c);if(s.has(p)){this.log("[live]",t,p);let d=s.get(p);return Promise.resolve(d)}if(r.has(p))return this.log("[memo]",t,p),r.get(p);this.log("[fetch]",t,p);let m=e(...c).catch(d=>{throw r.delete(p),d});return r.set(p,m),m},set:(c,...p)=>{let m=i(...p);this.log("[set-live]",t,m),s.set(m,c)},clear:()=>{this.log("[clear]",t),s.clear(),r.release()}}}};var Ne=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let i=0;i<t.length;++i){let[n,s]=t[i];this.result.set(this.getKey(s,n),e[i].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,i,n){let s=this.getKey(t,e),r=this.getKey(t,i),a=this.result.get(s)??0n,o=this.result.get(r)??0n;if(a<n)throw new Error("Attempting to transfer more than is present");this.result.set(s,a+n),this.result.set(r,o+n)}};var gt=dt(require("big.js")),et=require("@galacticcouncil/math-liquidity-mining");var vi=dt(require("big.js")),Si=(0,vi.default)(10).pow(18),pn=BigInt((0,vi.default)(1).pow(18).toString()),mn=6e3;var _s="1000000000000000000",He=class{constructor(t,e,i){this.getAccount=t;this.getAsset=e;this.multiCurrency=i}async syncGlobalFarm(t,e,i){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),s=e-t.updated_at,r=this.getAccount(t.id),a=n?.existential_deposit;if(!a)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,r),l=(0,gt.default)(a.toString()),c=(0,gt.default)(o.toString()).minus(l.lt(o.toString())?a.toString():o.toString()),p=(0,gt.default)((0,et.calculate_global_farm_rewards)(t.total_shares_z.toString(),i.toString(),(0,gt.default)(t.yield_per_period.toString()).mul(Si).round(0,gt.default.roundDown).toFixed(),t.max_reward_per_period.toString(),s.toFixed()));if(c.lt(p)&&(p=c),p.eq(0))return t;let m=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,r,m,BigInt(p.toFixed())),{...t,accumulated_rpz:BigInt((0,et.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),p.toFixed()))}}syncYieldFarm(t,e,i){if(t.state.type!=="Active"||t.updated_at===i)return null;if(t.total_valued_shares===0n)return{...t,updated_at:i};let n=(0,et.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(n),updated_at:i}}getLoyaltyMultiplier(t,e){let i=(0,gt.default)(1).mul(Si).round(0,gt.default.roundDown).toString();if(!e)return i;let{initial_reward_percentage:n,scale_coef:s}=e;return(0,et.calculate_loyalty_multiplier)(t.toFixed(),n.toString(),s.toFixed())}async claimRewards(t,e,i,n,s){if(e.state.type==="Terminated")return null;let r=Math.floor(n/t.blocks_per_period);if(i.updated_at===r)return null;let a=await this.syncGlobalFarm(t,r,s);if(!a)return null;let o=this.syncYieldFarm(e,a,r);if(!o)return null;let l=o.total_stopped-i.stopped_at_creation,c=o.updated_at-i.entered_at-l,p=this.getLoyaltyMultiplier(c,o.loyalty_curve),m=BigInt((0,et.calculate_user_reward)(i.accumulated_rpvs.toString(),i.valued_shares.toString(),i.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),d=BigInt((0,et.calculate_user_reward)(i.accumulated_rpvs.toString(),i.valued_shares.toString(),i.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),_s));return{reward:m,maxReward:d,assetId:a.reward_currency,yieldFarmId:o.id,isActiveFarm:o.state.type==="Active"}}};var As=(0,U.default)(365.2425).times(24).times(60).times(60),Qt=class{client;balanceClient;options;constructor(t,e,i={}){this.client=t,this.balanceClient=e,this.options=Object.freeze({blockTime:i.blockTime??mn})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let i=[t,e].sort((s,r)=>s-r);if(t===e)return pn;let n=await this.client.getOraclePrice(i);if(n){let{n:s,d:r}=n[0].price,a;return t<e?a=(0,Ti.fixed_from_rational)(s.toString(),r.toString()):a=(0,Ti.fixed_from_rational)(r.toString(),s.toString()),BigInt(a)}}getFarmAddress=(t,e)=>{let i=Buffer.from("modl","utf-8"),n=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),s=Buffer.from([t]),r=Buffer.concat([i,n,s]),o="0x"+Buffer.concat([r,Buffer.alloc(32-r.length)]).toString("hex");return(0,dn.AccountId)(ht.HYDRATION_SS58_PREFIX).dec(o)};getGlobalRewardPerPeriod(t,e,i,n){let s=(0,U.default)(n).times(t.toString()).times(e.toString()).div(Math.pow(10,ht.RUNTIME_DECIMALS));return s.gte(i.toString())?i.toString():s.toString()}getPoolYieldPerPeriod(t,e,i,n){let s=(0,U.default)(t.toString()).times(e),r=(0,U.default)(i.toString()).times(n);return s.div(r.toString()).toString()}farmData(t,e,i){let{yieldFarm:n,globalFarm:s,priceAdjustment:r,balance:a,id:o}=t,{multiplier:l,loyalty_curve:c}=n,{blocks_per_period:p,yield_per_period:m,total_shares_z:d,max_reward_per_period:g,pending_rewards:b,accumulated_paid_rewards:h,planned_yielding_periods:f,updated_at:y,incentivized_asset:S,reward_currency:v,price_adjustment:x,min_deposit:A}=s,D=_.shiftNeg(r??x,ht.RUNTIME_DECIMALS),G=_.shiftNeg(l,ht.RUNTIME_DECIMALS),rt=_.shiftNeg(c?.initial_reward_percentage??0,ht.RUNTIME_DECIMALS),ut=As.div((0,U.default)(this.blockTime).div(1e3).times(p)).toString(),K;if(d<=0)K=(0,U.default)(G).times(m.toString()).times(ut).toString();else{let $n=this.getGlobalRewardPerPeriod(d,m,g,D),jn=this.getPoolYieldPerPeriod($n,G,d,D);K=(0,U.default)(jn).times(ut).toString()}let Q=b+h,Ut=g*BigInt(f),ve=a.transferable+Q,Wi=ve-Q,Se=(0,U.default)(Wi.toString()).div(g.toString()),Te=(0,U.default)(e).div(p.toString()).toString(),xe=(d>=0?Se.plus(y):Se.plus(Te)).toString(),ii=(0,U.default)(xe).times(p).toString(),Xn=(0,U.default)(d.toString()).div((0,U.default)(g.toString()).div(m.toString())).div(Math.pow(10,ht.RUNTIME_DECIMALS)).times(100).times(D).toFixed(2),Yi=(0,U.default)(Q.toString()).div(ve.toString()).gte(.999);K=Yi?"0":(0,U.default)(K).div(i?2:1).times(100).toString();let Kn=rt?(0,U.default)(K).times(rt).toString():void 0;return{apr:K,minApr:Kn,isDistributed:Yi,estimatedEndPeriod:xe,estimatedEndBlock:ii,maxRewards:Ut,incentivizedAsset:S,rewardCurrency:v,loyaltyCurve:c,currentPeriod:Te,potMaxRewards:ve,fullness:Xn,yieldFarmId:n.id,globalFarmId:s.id,poolId:o,distributedRewards:Q,plannedYieldingPeriods:f,minDeposit:A,blocksPerPeriod:p}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((n,s)=>n.includes(s.keyArgs[0].toString())?n:[...n,s.keyArgs[0].toString()],[]),i=await Promise.all(e.map(async n=>{let s=await this.getOmnipoolFarms(n);if(s)return[n,s]}));return Object.fromEntries(i.filter(n=>!!n))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),i=await this.client.getRelayBlockNumber(),n=await Promise.all(e.map(async({keyArgs:s,value:r})=>{let[,a]=s,o=r,l=await this.client.getOmnipoolGlobalFarm(a),c=await this.client.getOmnipoolYieldFarm(Number(t),a,o);if(!l||!c)return;let p=l.reward_currency,m=l.incentivized_asset,d=this.getFarmAddress(a),g=await this.getOraclePrice(p,m),b=await this.balanceClient.getBalance(d,p);return{id:t,globalFarm:l,yieldFarm:c,priceAdjustment:g,balance:b}}));return i?n.map(s=>s?this.farmData(s,i):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((n,s)=>n.includes(s.keyArgs[0].toString())?n:[...n,s.keyArgs[0].toString()],[]),i=await Promise.all(e.map(async n=>{let s=await this.getIsolatedFarms(n);if(s)return[n,s]}));return Object.fromEntries(i.filter(n=>!!n))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),i=await this.client.getRelayBlockNumber(),n=await Promise.all(e.map(async({keyArgs:s,value:r})=>{let[,a]=s,o=r,l=await this.client.getIsolatedGlobalFarm(a),c=await this.client.getIsolatedYieldFarm(t,a,o);if(!l||!c)return;let p=l.reward_currency,m=l.incentivized_asset,d=this.getFarmAddress(a,!0),g=await this.getOraclePrice(p,m),b=await this.balanceClient.getBalance(d,p);return{id:t,globalFarm:l,yieldFarm:c,priceAdjustment:g,balance:b,farmAddress:d}}));return i?n.map(s=>s?this.farmData(s,i,!0):void 0):[]}async getDepositReward(t,e,i,n){let s=e.global_farm_id,r=e.yield_farm_id,a=i?await this.client.getIsolatedYieldFarm(t,s,r):await this.client.getOmnipoolYieldFarm(Number(t),s,r),o=i?await this.client.getIsolatedGlobalFarm(s):await this.client.getOmnipoolGlobalFarm(s);if(!o||!a)return;let l=o.reward_currency,c=o.incentivized_asset,p=[[this.getFarmAddress(0,i),o.reward_currency],[this.getFarmAddress(o.id,i),o.reward_currency]],m=await this.getAccountAssetBalances(p),d=await this.getOraclePrice(l,c),g=new Ne(p,m),h=await new He(y=>this.getFarmAddress(y),y=>this.client.getAsset(y),g).claimRewards(o,a,e,n,d??o.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,i]=await Promise.all([Promise.all(t.filter(([s,r])=>r!==0).map(([s,r])=>this.balanceClient.getTokenBalance(s,r))),Promise.all(t.filter(([s,r])=>r===0).map(([s])=>this.balanceClient.getSystemBalance(s)))]),n=[];for(let s=0,r=0;s+r<t.length;){let a=s+r,[,o]=t[a];o===0?(n.push(i[r]),r+=1):(n.push(e[s]),s+=1)}return n}};var Ge=require("polkadot-api"),Jt=class extends N{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(Ge.Binary.fromText("omnipool"),t,(0,Ge.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)}async getOmnipoolYieldFarm(t,e,i){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,i)}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)}async getIsolatedYieldFarm(t,e,i){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,i)}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};var Ci={};R(Ci,{PoolContextProvider:()=>Dt,PoolError:()=>bt,PoolFactory:()=>Mt,PoolType:()=>C,aave:()=>Oi,hsm:()=>Fi,lbp:()=>wi,omni:()=>Ii,stable:()=>_i,xyk:()=>Ai});var wi={};R(wi,{LbpMath:()=>it,LbpPool:()=>Zt,LbpPoolClient:()=>te});var ct=require("@galacticcouncil/math-lbp"),it=class{static getSpotPrice(t,e,i,n,s){return(0,ct.get_spot_price)(t,e,i,n,s)}static calculateInGivenOut(t,e,i,n,s){return(0,ct.calculate_in_given_out)(t,e,i,n,s)}static calculateOutGivenIn(t,e,i,n,s){return(0,ct.calculate_out_given_in)(t,e,i,n,s)}static calculateLinearWeights(t,e,i,n,s){return(0,ct.calculate_linear_weights)(t,e,i,n,s)}static calculatePoolTradeFee(t,e,i){return(0,ct.calculate_pool_trade_fee)(t,e,i)}};var Rt=require("@galacticcouncil/common");var C=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r.HSM="HSM",r))(C||{}),bt=(c=>(c.UnknownError="UnknownError",c.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",c.InsufficientTradingAmount="InsufficientTradingAmount",c.InsufficientCollateral="InsufficientCollateral",c.MaxHoldingExceeded="MaxHoldingExceeded",c.MaxInRatioExceeded="MaxInRatioExceeded",c.MaxOutRatioExceeded="MaxOutRatioExceeded",c.TradeNotAllowed="TradeNotAllowed",c.MaxBuyBackExceeded="MaxBuyBackExceeded",c.MaxBuyPriceExceeded="MaxBuyPriceExceeded",c))(bt||{});var{FeeUtils:gn}=_,Zt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new u(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(r=>[r.id,r])),n=i.get(t),s=i.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:n.balance,balanceOut:s.balance,decimalsIn:n.decimals,decimalsOut:s.decimals,weightIn:n.weight,weightOut:s.weight}}validateAndBuy(t,e,i){let n=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let r=t.balanceOut/this.maxOutRatio;if(e>r&&s.push("MaxOutRatioExceeded"),n===t.assetOut){let a=this.calculateTradeFee(e,i),o=gn.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),l=e+a,c=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return c>p&&s.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:s}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&s.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:s}}}validateAndSell(t,e,i){let n=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let r=t.balanceIn/this.maxInRatio;if(e>r&&s.push("MaxInRatioExceeded"),n===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:s}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,i),l=gn.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),c=a-o,p=t.balanceOut/this.maxOutRatio;return c>p&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:c,feePct:l,errors:s}}}calculateInGivenOut(t,e){let i=it.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),n=BigInt(i);return n<0n?0n:n}calculateOutGivenIn(t,e){let i=it.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),n=BigInt(i);return n<0n?0n:n}spotPriceInGivenOut(t){let e=it.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=it.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=it.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var yn=require("polkadot-api"),Ft=require("rxjs");var hn=(u,t=new Map)=>e=>{let i;return t.has(e)?t.get(e):(t.set(e,i=u(e)),i)};var P=require("rxjs");var bn=require("rxjs"),Ue=class{store$=new bn.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((a,o)=>[a.address,o])),n=await t(e),s=e.slice(),r=new Set;for(let a of n){let o=i.get(a.address);o===void 0?(i.set(a.address,s.length),s.push(a)):s[o]=a,r.add(a.address)}this.changeset=r,this.store$.next(s)}).catch(console.error)}destroy(){this.store$.complete()}};var X=class extends at{evm;store=new Ue;shared$;mem=0;memPoolsCache=new St(null,{ttl:6*1e3});memPools=hn(t=>(this.log(this.getPoolType(),"sync mem pools",t),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e}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,P.startWith)([]),(0,P.bufferCount)(2,1),(0,P.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,P.filter)(t=>t.length>0),(0,P.throttleTime)(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return(0,P.defer)(()=>{let t=new P.Subscription;return(0,P.from)(this.getMemPools()).pipe((0,P.map)(i=>i.filter(n=>this.hasValidAssets(n))),(0,P.tap)(i=>this.store.set(i))).pipe((0,P.tap)(()=>{t.add(this.subscribeBalances()),t.add(this.subscribeUpdates())}),(0,P.switchMap)(i=>(0,P.merge)((0,P.of)(i),this.store.asObservable().pipe((0,P.skip)(1)))),(0,P.finalize)(()=>{t.unsubscribe()}))}).pipe((0,P.share)({connector:()=>new P.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:i}=e,n=[this.subscribeTokensBalance(i)];if(this.hasSystemAsset(e)){let s=this.subscribeSystemBalance(i);n.push(s)}if(this.hasErc20Asset(e)){let s=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),r=this.subscribeErc20Balance(i,s);n.push(r)}return(0,P.combineLatest)(n).pipe((0,P.map)(s=>s.flat()),(0,P.pairwise)(),(0,P.map)(([s,r])=>this.getDeltas(s,r)),(0,P.map)(s=>[i,s]))});return(0,P.combineLatest)(t).pipe((0,P.debounceTime)(250),(0,P.map)(e=>new Map(e))).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})=>i>0n&&!!e)}updateBalances=(t,e)=>{let i=[],n=new Map(t.map(s=>[s.address,s]));for(let[s,r]of e){let a=n.get(s);if(a){let o=a.tokens.map(l=>{let c=r.find(p=>p.id===l.id);return c&&l.id!==a.id?{...l,balance:c.balance.transferable}:l});i.push({...a,tokens:o})}}return i}};var te=class extends X{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:n,initial_weight:s,final_weight:r}=t,a=it.calculateLinearWeights(i?i.toString():"0",n?n.toString():"0",s.toString(),r.toString(),e.toString()),o=BigInt(a),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(yn.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()]),n=e?.relay_parent_number||0,s=t.filter(({value:r})=>e&&this.isActivePool(r,n)).map(async({keyArgs:r,value:a})=>{let[o]=r,l=o.toString(),c=await this.getPoolDelta(l,a,n);return{address:l,type:"LBP",fee:a.fee,...c,...i}});return Promise.all(s)}async getPoolDelta(t,e,i){let{assets:n,repay_target:s,fee_collector:r}=e,[a,o]=this.getPoolWeights(e,i),[l,c]=n,[p,m,d,g,b]=await Promise.all([this.isRepayFeeApplied(l,s,r.toString()),this.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l),this.getBalance(t,c),this.api.query.AssetRegistry.Assets.getValue(c)]);return{repayFeeApply:p,tokens:[{id:l,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:m.transferable,weight:a,type:d?.asset_type.type},{id:c,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:g.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(t,e){let{start:i,end:n}=t;return i&&n?e>=i&&e<n:!1}async isRepayFeeApplied(t,e,i){if(e===0n)return!1;try{return(await this.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(s=>s.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:i.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue("best").pipe((0,Ft.filter)(t=>t!==void 0),(0,Ft.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number)).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let i=[];for(let n of e){let s=this.poolsData.get(n.address);if(s){let{assets:r,repay_target:a,fee_collector:o}=s,[l]=r,[c,p]=this.getPoolWeights(s,t),[m,d]=n.tokens,g=[{...m,weight:c},{...d,weight:p}],b=await this.isRepayFeeApplied(l,a,o.toString());i.push({...n,tokens:g,repayFeeApply:b})}}return i})})}subscribeUpdates(){let t=new Ft.Subscription;return t.add(this.subscribeValidationData()),t}};var Ii={};R(Ii,{OmniMath:()=>B,OmniPool:()=>ee,OmniPoolClient:()=>ie});var T=require("@galacticcouncil/math-omnipool"),Tt=dt(require("big.js")),B=class{static calculateSpotPrice(t,e,i,n){return(0,T.calculate_spot_price)(t,e,i,n)}static calculateLrnaSpotPrice(t,e){return(0,T.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,i,n,s,r,a,o,l){return(0,T.calculate_in_given_out)(t,e,i,n,s,r,a,o,l)}static calculateLrnaInGivenOut(t,e,i,n,s){return(0,T.calculate_lrna_in_given_out)(t,e,i,n,s)}static calculateOutGivenIn(t,e,i,n,s,r,a,o,l){return(0,T.calculate_out_given_in)(t,e,i,n,s,r,a,o,l)}static calculateOutGivenLrnaIn(t,e,i,n,s){return(0,T.calculate_out_given_lrna_in)(t,e,i,n,s)}static calculateShares(t,e,i,n){return(0,T.calculate_shares)(t,e,i,n)}static calculateLiquidityOut(t,e,i,n,s,r,a,o){return(0,T.calculate_liquidity_out)(t,e,i,n,s,r,a,o)}static calculateLiquidityLRNAOut(t,e,i,n,s,r,a,o){return(0,T.calculate_liquidity_lrna_out)(t,e,i,n,s,r,a,o)}static calculateCapDifference(t,e,i,n){let s=(0,Tt.default)(e),r=(0,Tt.default)(t),a=(0,Tt.default)(n),o=(0,Tt.default)(i),l=(0,Tt.default)(10).pow(18),c=o.div(l);if(s.div(a).lt(c)){let m=c.times(a).minus(s).times(r),d=s.times((0,Tt.default)(1).minus(c));return m.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,n){return(0,T.calculate_liquidity_hub_in)(t,e,i,n)}static isSellAllowed(t){return(0,T.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,T.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,T.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,T.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,i,n,s,r,a,o,l,c,p){return(0,T.recalculate_asset_fee)(t,e,i,n,s,r,a,o,l,c,p)}static recalculateProtocolFee(t,e,i,n,s,r,a,o,l,c,p){return(0,T.recalculate_protocol_fee)(t,e,i,n,s,r,a,o,l,c,p)}static verifyAssetCap(t,e,i,n){return(0,T.verify_asset_cap)(t,e,i,n)}};var fn=require("@galacticcouncil/common");var{FeeUtils:Ct}=_,ee=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new u(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let i=new Map(this.tokens.map(r=>[r.id,r])),n=i.get(t),s=i.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:n.hubReserves,hubReservesOut:s.hubReserves,sharesIn:n.shares,sharesOut:s.shares,decimalsIn:n.decimals,decimalsOut:s.decimals,balanceIn:n.balance,balanceOut:s.balance,tradeableIn:n.tradeable,tradeableOut:s.tradeable,assetInEd:n.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,i){let n=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,i),r=n===0n?0:O.calculateDiffToRef(s,n),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetInEd)&&a.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&a.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return s>p&&a.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:n,amountOut:e,feePct:r,errors:a}}validateAndSell(t,e,i){let n=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,i),r=O.calculateDiffToRef(n,s),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetOutEd)&&a.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&a.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return s>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:n,amountOut:s,feePct:r,errors:a}}calculateInGivenOut(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,i);let n=B.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?Ct.toRaw(i.assetFee).toString():"0",i?Ct.toRaw(i.protocolFee).toString():"0"),s=BigInt(n);return s<0n?0n:s}calculateLrnaInGivenOut(t,e,i){let n=B.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?Ct.toRaw(i.assetFee).toString():"0"),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,i);let n=B.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?Ct.toRaw(i.assetFee).toString():"0",i?Ct.toRaw(i.protocolFee).toString():"0"),s=BigInt(n);return s<0n?0n:s}calculateOutGivenLrnaIn(t,e,i){let n=B.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?Ct.toRaw(i.assetFee).toString():"0"),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=B.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceLrnaInGivenOut(t){let e=B.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=B.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}spotPriceOutGivenLrnaIn(t){let e=B.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,i){let n=e-i;if(n===0)return t;let s=fn.big.pow10(Math.abs(n));return n>0?t*s:t/s}};var yt=require("polkadot-api"),Sn=require("@polkadot-api/utils"),M=require("rxjs"),Tn=require("@galacticcouncil/common");var{FeeUtils:q}=_,Pn=yt.Binary.fromText("omnipool"),vn=(0,yt.Enum)("Short"),ie=class extends X{queryBus=new jt;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);emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(Pn,t,vn,{at:"best"}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,Sn.toHex)(e);return(0,yt.AccountId)(Tn.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(yt.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,n,s,r,a]=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.getBalance(e,t),this.getPoolLimits()]),o=i.map(async({keyArgs:c,value:p})=>{let[m]=c,{hub_reserve:d,shares:g,tradable:b,cap:h,protocol_shares:f}=p,[y,S]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,m)]);return{id:m,decimals:y?.decimals,existentialDeposit:y?.existential_deposit,balance:S.transferable,cap:h,hubReserves:d,protocolShares:f,shares:g,tradeable:b,type:y?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:r.transferable,tradeable:n,type:s?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...a}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,n=await this.dynamicFeesConfig.get(e);if(n?.type==="Fixed"){let{asset_fee:y,protocol_fee:S}=n.value;return{assetFee:q.fromPermill(y),protocolFee:q.fromPermill(S)}}let s=this.getOraclePair(e),r=this.getOraclePair(i),[a,o,l]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(s),this.emaOracles.get(r)]),[c,p,m]=await this.getAssetFee(t,this.block,a,o,n?.value.asset_fee_params),[d,g,b]=i===1?[0,0,0]:await this.getProtocolFee(t,this.block,a,l,n?.value.protocol_fee_params),h=c+d,f=m+b;return{assetFee:q.fromPermill(p),protocolFee:q.fromPermill(g),min:q.fromPermill(h),max:q.fromPermill(f)}}async getAssetFee(t,e,i,n,s){let{assetOut:r,balanceOut:a}=t,{min_fee:o,max_fee:l,decay:c,amplification:p}=s||await this.api.constants.DynamicFees.AssetFeeParameters();if(!i||!n)return[o,o,l];let m=q.fromPermill(o),d=q.fromPermill(l),[g]=n,{asset_fee:b,timestamp:h}=i,f=Math.max(1,e-h),y=g.volume.b_in.toString(),S=g.volume.b_out.toString(),v=g.liquidity.b.toString();r===0&&(y=g.volume.a_in.toString(),S=g.volume.a_out.toString(),v=g.liquidity.a.toString());let x=q.fromPermill(b),A=B.recalculateAssetFee(y,S,v,"9",a.toString(),q.toRaw(x).toString(),f.toString(),q.toRaw(m).toString(),q.toRaw(d).toString(),c.toString(),p.toString());return[o,Number(A)*1e6,l]}async getProtocolFee(t,e,i,n,s){let{assetIn:r,balanceIn:a}=t,{min_fee:o,max_fee:l,decay:c,amplification:p}=s||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!i||!n)return[o,o,l];let m=q.fromPermill(o),d=q.fromPermill(l),[g]=n,{protocol_fee:b,timestamp:h}=i,f=Math.max(1,e-h),y=g.volume.b_in.toString(),S=g.volume.b_out.toString(),v=g.liquidity.b.toString();r===0&&(y=g.volume.a_in.toString(),S=g.volume.a_out.toString(),v=g.liquidity.a.toString());let x=q.fromPermill(b),A=B.recalculateProtocolFee(y,S,v,"9",a.toString(),q.toRaw(x).toString(),f.toString(),q.toRaw(m).toString(),q.toRaw(d).toString(),c.toString(),p.toString());return[o,Number(A)*1e6,l]}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(n=>n.id).map(n=>this.getOraclePair(n)).map(n=>this.api.query.EmaOracle.Oracles.watchValue(Pn,n,vn,"best").pipe((0,M.filter)(s=>s!==void 0),(0,M.map)(s=>({pair:n,value:s}))));return(0,M.merge)(...i).pipe((0,M.finalize)(()=>{this.log(this.getPoolType(),"unsub ema oracles"),this.emaOracles.clear()})).subscribe(n=>{let{pair:s,value:r}=n;this.emaOracles.set(r,s)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,M.distinctUntilChanged)((t,e)=>!e.deltas),(0,M.finalize)(()=>{(0,M.finalize)(()=>{this.log(this.getPoolType(),"unsub dyn fees"),this.dynamicFees.clear()})})).subscribe(({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,M.distinctUntilChanged)((t,e)=>!e.deltas),(0,M.finalize)(()=>{this.log(this.getPoolType(),"unsub dyn fees config"),this.dynamicFeesConfig.clear()})).subscribe(({deltas:t})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFeesConfig.set(e.value,i)})})}subscribeBlock(){return this.api.query.System.Number.watchValue("best").pipe((0,M.finalize)(()=>{this.log(this.getPoolType(),"unsub block change")})).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,M.distinctUntilChanged)((t,e)=>!e.deltas),(0,M.finalize)(()=>{this.log(this.getPoolType(),"unsub assets")})).subscribe(({deltas:t})=>{this.store.update(([e])=>{let i=t?.upserted.reduce((s,r)=>{let[a]=r.args;return s.set(a,r.value),s},new Map),n=e.tokens.map(s=>{let r=i?.get(s.id);return r?this.updateTokenState(s,r):s});return[{...e,tokens:n}]})})}subscribeUpdates(){let t=new M.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:n,tradable:s,cap:r,protocol_shares:a}=e;return{...t,cap:r,hubReserves:i,protocolShares:a,shares:n,tradeable:s}}};var _i={};R(_i,{StableMath:()=>V,StableSwap:()=>ft,StableSwapClient:()=>se});var E=require("@galacticcouncil/math-stableswap"),V=class{static getPoolAddress(t){return(0,E.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,n,s){return(0,E.calculate_amplification)(t,e,i,n,s)}static calculateInGivenOut(t,e,i,n,s,r,a){return(0,E.calculate_in_given_out)(t,e,i,n,s,r,a)}static calculateAddOneAsset(t,e,i,n,s,r,a){return(0,E.calculate_add_one_asset)(t,e,i,n,s,r,a)}static calculateSharesForAmount(t,e,i,n,s,r,a){return(0,E.calculate_shares_for_amount)(t,e,i,n,s,r,a)}static calculateOutGivenIn(t,e,i,n,s,r,a){return(0,E.calculate_out_given_in)(t,e,i,n,s,r,a)}static calculateLiquidityOutOneAsset(t,e,i,n,s,r,a){return(0,E.calculate_liquidity_out_one_asset)(t,e,i,n,s,r,a)}static calculateShares(t,e,i,n,s,r){return(0,E.calculate_shares)(t,e,i,n,s,r)}static calculateSpotPriceWithFee(t,e,i,n,s,r,a,o){return(0,E.calculate_spot_price_with_fee)(t,e,i,n,s,r,a,o)}static recalculatePegs(t,e,i,n,s,r){let a=(0,E.recalculate_peg)(t,e,i,n,s,r);return JSON.parse(a)}};var ne=require("@galacticcouncil/common");var{FeeUtils:Et}=_,ft=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new u(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(r=>[r.id,r])),n=i.get(t),s=i.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:n.balance,balanceOut:s.balance,decimalsIn:n.decimals,decimalsOut:s.decimals,tradeableIn:this.id===t?15:n.tradeable,tradeableOut:this.id===e?15:s.tradeable,assetInEd:n.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,i){let n=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,i),r=n===0n?0:O.calculateDiffToRef(s,n),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:s,calculatedIn:n,amountOut:e,feePct:r,errors:a}}validateAndSell(t,e,i){let n=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,i),r=O.calculateDiffToRef(n,s),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:n,amountOut:s,feePct:r,errors:a}}calculateIn(t,e,i){let n=V.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?Et.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(n);return s<0n?0n:s}calculateAddOneAsset(t,e,i){let n=V.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?Et.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(n);return s<0n?0n:s}calculateSharesForAmount(t,e,i){let n=V.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?Et.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(n);return s<0n?0n:s}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=V.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 n=V.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?Et.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(n);return s<0n?0n:s}calculateWithdrawOneAsset(t,e,i){let n=V.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?Et.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(n);return s<0n?0n:s}calculateShares(t,e,i){let n=V.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?Et.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(n);return s<0n?0n:s}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=V.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:n})=>({asset_id:e,amount:i,decimals:n}));return JSON.stringify(t,Ot.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],Ot.jsonFormatter)}normalizeSpot(t,e,i,n,s){return e?t*ne.big.pow10(ne.RUNTIME_DECIMALS-s):i?t/ne.big.pow10(s-n):t}};var Ve=require("polkadot-api"),xn=require("@polkadot-api/utils"),wn=require("@noble/hashes/blake2b"),Z=require("rxjs"),We=require("@galacticcouncil/common");var{FeeUtils:Os}=_,se=class extends X{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=V.getPoolAddress(t),i=(0,wn.blake2b)(e,{dkLen:32}),n=(0,xn.toHex)(i);return(0,Ve.AccountId)(We.HYDRATION_SS58_PREFIX).dec(n)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:i,final_amplification:n,initial_block:s,final_block:r}=t,a=V.calculateAmplification(i.toString(),n.toString(),s.toString(),r.toString(),e.toString()),o=Number(a)<n;return{amplification:BigInt(a),isRampPeriod:o}}async getPoolTokens(t,e){let i=this.getPoolAddress(t),n=e.assets.map(async s=>{let[r,a,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,s),this.api.query.AssetRegistry.Assets.getValue(s),this.getBalance(i,s)]);return{id:s,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:o.transferable,tradeable:r,type:a?.asset_type.type}});return Promise.all(n)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(Ve.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()]),n=t.map(async({keyArgs:s,value:r})=>{let[a]=s,o=this.getPoolAddress(a),[l,c,p]=await Promise.all([this.getPoolTokens(a,r),this.api.query.Stableswap.PoolPegs.getValue(a,{at:"best"}),this.api.query.Tokens.TotalIssuance.getValue(a,{at:"best"})]),m=this.getPoolAmplification(r,e),d=c?this.getRecentPegs(c):this.getDefaultPegs(r);return l.push({id:a,tradeable:15,balance:p,decimals:We.RUNTIME_DECIMALS}),this.poolsData.set(a,r),{address:o,id:a,type:"Stableswap",fee:Os.fromPermill(r.fee),tokens:l,totalIssuance:p,pegs:d,...i,...m}});return Promise.all(n)}async getPoolFees(t,e){return{fee:this.store.pools.find(n=>n.address===e).fee}}getDefaultPegs(t){return V.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([i,n])=>n.map(s=>s.toString()))}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,"best").pipe((0,Z.map)(n=>({id:i,value:n}))));return(0,Z.merge)(...e).pipe((0,Z.finalize)(()=>{this.log(this.getPoolType(),"unsub total issuance")})).subscribe(i=>{let{id:n,value:s}=i;this.store.update(r=>{let a=[];return r.filter(o=>o.id===n).forEach(o=>{let l=o.tokens.map(c=>c.id===n?{...c,balance:s}:c);a.push({...o,tokens:l,totalIssuance:s})}),a})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,Z.distinctUntilChanged)((t,e)=>!e.deltas),(0,Z.finalize)(()=>{this.log(this.getPoolType(),"unsub pool pegs")})).subscribe(({deltas:t})=>{this.store.update(e=>{let i=[],n=new Map(e.map(s=>[s.id,s]));return t?.upserted.forEach(({args:s,value:r})=>{let[a]=s,o=n.get(a);if(o){let l=this.getRecentPegs(r);i.push({...o,pegs:l})}}),i})})}subscribeBlock(){return this.api.query.System.Number.watchValue("best").pipe((0,Z.finalize)(()=>{this.log(this.getPoolType(),"unsub block change")})).subscribe(t=>{this.store.update(e=>{let i=[];return e.filter(n=>n.isRampPeriod).forEach(n=>{let s=this.poolsData.get(n.id);if(s){let r=this.getPoolAmplification(s,t);i.push({...n,...r})}}),i})})}subscribeUpdates(){let t=new Z.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 Ai={};R(Ai,{XykMath:()=>pt,XykPool:()=>re,XykPoolClient:()=>ae});var k=require("@galacticcouncil/math-xyk"),pt=class{static getSpotPrice(t,e,i){return(0,k.get_spot_price)(t,e,i)}static calculateInGivenOut(t,e,i){return(0,k.calculate_in_given_out)(t,e,i)}static calculateOutGivenIn(t,e,i){return(0,k.calculate_out_given_in)(t,e,i)}static calculatePoolTradeFee(t,e,i){return(0,k.calculate_pool_trade_fee)(t,e,i)}static calculateLiquidityIn(t,e,i){return(0,k.calculate_liquidity_in)(t,e,i)}static calculateSpotPrice(t,e){return(0,k.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,i,n){return(0,k.calculate_spot_price_with_fee)(t,e,i,n)}static calculateShares(t,e,i){return(0,k.calculate_shares)(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,n){return(0,k.calculate_liquidity_out_asset_a)(t,e,i,n)}static calculateLiquidityOutAssetB(t,e,i,n){return(0,k.calculate_liquidity_out_asset_b)(t,e,i,n)}};var _n=require("@galacticcouncil/common");var{FeeUtils:In}=_,re=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(r=>[r.id,r])),n=i.get(t),s=i.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:n.decimals,decimalsOut:s.decimals,balanceIn:n.balance,balanceOut:s.balance,assetInEd:n.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,i){let n=this.calculateInGivenOut(t,e),s=this.calculateTradeFee(n,i),r=In.toPct(i.exchangeFee),a=n+s,o=[];(e<this.minTradingLimit||n<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return a>c&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:n,amountOut:e,feePct:r,errors:o}}validateAndSell(t,e,i){let n=this.calculateOutGivenIn(t,e),s=this.calculateTradeFee(n,i),r=In.toPct(i.exchangeFee),a=n-s,o=[];(e<this.minTradingLimit||n<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return a>c&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:n,amountOut:a,feePct:r,errors:o}}calculateInGivenOut(t,e){let i=pt.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),n=BigInt(i);return n<0n?0n:n}calculateOutGivenIn(t,e){let i=pt.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),n=BigInt(i);return n<0n?0n:n}spotPriceInGivenOut(t){let e=pt.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=pt.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=pt.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(i)}normalizeSpot(t,e,i){let n=e-i;if(n===0)return t;let s=_n.big.pow10(Math.abs(n));return n>0?t*s:t/s}};var An=require("polkadot-api"),On=require("rxjs");var ae=class extends X{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(An.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries(),this.getPoolLimits()]),i=t.map(async({keyArgs:n,value:s})=>{let[r]=n,[a,o]=s,[l,c,p,m]=await Promise.all([this.getBalance(r,a),this.api.query.AssetRegistry.Assets.getValue(a),this.getBalance(r,o),this.api.query.AssetRegistry.Assets.getValue(o)]);return{address:r,type:"XYK",tokens:[{id:a,decimals:c?.decimals||this.decimals.get(a),existentialDeposit:c?.existential_deposit,balance:l.transferable,type:c?.asset_type.type},{id:o,decimals:m?.decimals||this.decimals.get(o),existentialDeposit:m?.existential_deposit,balance:p.transferable,type:m?.asset_type.type}],...e}});return Promise.all(i)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return On.Subscription.EMPTY}};var Oi={};R(Oi,{AavePool:()=>oe,AavePoolClient:()=>le});var kt=require("@galacticcouncil/common");var oe=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(r=>[r.id,r])),n=i.get(t),s=i.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:n.balance,balanceOut:s.balance,decimalsIn:n.decimals,decimalsOut:s.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,i){let n=this.calculateInGivenOut(t,e),s=[];return e>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:n,calculatedIn:n,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e,i){let n=this.calculateOutGivenIn(t,e),s=[];return n>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:e,calculatedOut:n,amountOut:n,feePct:0,errors:s}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return kt.big.toBigInt(1,kt.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return kt.big.toBigInt(1,kt.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var Rn=require("polkadot-api"),Fn=require("@polkadot-api/utils"),$=require("rxjs"),Cn=require("viem"),Ye=require("@galacticcouncil/common");var Bn=[{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:Bs}=Ye.erc20,Rs=["Supply","Withdraw","Repay","Borrow"],le=class extends X{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,n=new TextEncoder().encode(i.padEnd(32,"\0")),s=(0,Fn.toHex)(n);return(0,Rn.AccountId)(Ye.HYDRATION_SS58_PREFIX).dec(s)}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:n,liqudity_in:s,liqudity_out:r})=>{let[a,o,l,c]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i),this.api.query.AssetRegistry.AssetLocations.getValue(i),this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n)]);return{address:this.getPoolId(i,n),type:"Aave",tokens:[{id:i,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:s,location:o,type:a?.asset_type.type},{id:n,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:r,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:n,liqudity_out:s}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:"best"});return t.tokens.map(r=>{let a=r.id===e.id?n:s;return{...r,balance:a}})}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 Bs.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,n=e.map(r=>r.asHex()),s=i.asHex();try{let{eventName:r,args:a}=(0,Cn.decodeEventLog)({abi:Bn,topics:n,data:s}),o=a.reserve.toLowerCase();return{eventName:r,reserve:o,key:`${r}:${o}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(i=>i.tokens).map(([i,n])=>n).map(i=>i.id);return this.api.event.Router.Executed.watch().pipe((0,$.map)(({payload:i})=>this.parseRouterLog(i)),(0,$.filter)(({assetIn:i,assetOut:n})=>e.includes(i)||e.includes(n)),(0,$.finalize)(()=>{this.log(this.getPoolType(),"unsub router executed")})).subscribe(({assetIn:i,assetOut:n,key:s})=>{this.log(this.getPoolType(),"[router:Executed]",s),this.store.update(async r=>{let a=[];for(let o of r){let[l,c]=o.tokens;if(c.id===i||c.id===n){let m=await this.getPoolDelta(o);a.push({...o,tokens:m})}}return a})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,$.map)(({payload:t})=>this.parseEvmLog(t)),(0,$.filter)(t=>t!==void 0),(0,$.filter)(({eventName:t})=>Rs.includes(t)),(0,$.finalize)(()=>{this.log(this.getPoolType(),"unsub evm log")})).subscribe(({reserve:t,key:e})=>{this.log(this.getPoolType(),"[evm:Log]",e),this.store.update(async i=>{let n=[];for(let s of i){let[r]=s.tokens;if(this.getReserveH160Id(r).toLowerCase()===t){let o=await this.getPoolDelta(s);n.push({...s,tokens:o})}}return n})})}subscribeBalances(){return $.Subscription.EMPTY}subscribeUpdates(){let t=new $.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var Mt=class{static get(t){switch(t.type){case"Aave":return oe.fromPool(t);case"XYK":return re.fromPool(t);case"Omnipool":return ee.fromPool(t);case"LBP":return Zt.fromPool(t);case"Stableswap":return ft.fromPool(t);case"HSM":return ft.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var st=require("rxjs");var Fi={};R(Fi,{HsmMath:()=>nt,HsmPool:()=>Bi,HsmPoolClient:()=>me});var W=require("@galacticcouncil/math-hsm"),nt=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,W.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,W.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,W.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,W.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,W.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,W.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,W.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,W.calculate_max_price)(t,e)}};var mt=require("@galacticcouncil/common");var{FeeUtils:ce}=_,Bi=class u extends ft{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new u(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,i,n){let s=this.calculateBuybackLimit(t);e>s&&n.push("MaxBuyBackExceeded");let r=this.calculateBuyPrice(t,e,i),a=this.calculateMaxPrice(t);return r>a&&n.push("MaxBuyPriceExceeded"),i>this.collateralBalance&&n.push("InsufficientCollateral"),n}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 n=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,i,n):this.validateTradeHollarOut(e,i,n)}validateAndBuy(t,e){let i=this.calculateInGivenOut(t,e),n=this.validateTradeConstraints(t,i,e);return{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:n}}validateAndSell(t,e){let i=this.calculateOutGivenIn(t,e),n=this.validateTradeConstraints(t,e,i);return{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:n}}calculateHollarInGivenCollateralOut(t,e){let i=super.calculateInGivenOut(t,e,{fee:this.fee}),n=nt.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),ce.toRaw(this.buyBackFee).toString());return BigInt(n)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=nt.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),ce.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}),n=nt.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),ce.toRaw(this.buyBackFee).toString());return BigInt(n)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=nt.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),ce.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=nt.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=nt.calculateBuybackLimit(e.toString(),ce.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let n=i*10n**BigInt(t.decimalsIn);return e*10n**BigInt(t.decimalsOut)/n}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=nt.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[n,s]=JSON.parse(i),r=10n**BigInt(mt.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(n)*r/BigInt(s)}spotPriceInGivenOut(t){let e=mt.big.toBigInt(1,mt.RUNTIME_DECIMALS);return this.calculateInGivenOut(t,e)}spotPriceOutGivenIn(t){let e=mt.big.toBigInt(1,mt.RUNTIME_DECIMALS);return this.calculateOutGivenIn(t,e)}getCollateralPeg(){let t=this.tokens.findIndex(n=>n.id!==this.hollarId),e=this.pegs[t],i=this.tokens[t].decimals;return this.isDefaultPeg(e)?[mt.big.toBigInt(1,18).toString(),mt.big.toBigInt(1,i).toString()]:e}isDefaultPeg(t){let[e,i]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&i==="1"}};var ze=require("polkadot-api"),kn=require("@polkadot-api/utils"),H=require("rxjs"),Mn=require("viem"),Xe=require("@galacticcouncil/common");var ue=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var pe=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,n]=await this.client.readContract({abi:ue,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-n}};var{FeeUtils:Ri}=_,{H160:En}=Xe.h160,Fs=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],me=class extends X{ghoClient;stableClient;constructor(t,e,i){super(t,e),this.stableClient=i,this.ghoClient=new pe(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),n=(0,kn.toHex)(i);return(0,ze.AccountId)(Xe.HYDRATION_SS58_PREFIX).dec(n)}async isSupported(){let t=this.api.query.HSM.Collaterals,e=await this.api.compatibilityToken;return t.isCompatible(ze.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,n]=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 s=this.getFacilitatorAddress(),r=En.fromAny(s),a=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(a,r),l=i.map(async({keyArgs:p,value:m})=>{let[d]=p,{pool_id:g,max_buy_price_coefficient:b,max_in_holding:h,purchase_fee:f,buy_back_fee:y,buyback_rate:S}=m,v=n.find(x=>x.id===g);if(v){let x=this.getPoolId(g),A=await this.getBalance(s,d);return{...v,address:x,type:"HSM",tokens:v.tokens.filter(D=>D.id!==g),hsmAddress:s,hsmMintCapacity:o,hollarId:t,hollarH160:a,collateralId:d,collateralBalance:A.transferable,maxBuyPriceCoefficient:b,maxInHolding:h,purchaseFee:Ri.fromPermill(f),buyBackFee:Ri.fromPermill(y),buyBackRate:Ri.fromPerbill(S)}}});return(await Promise.all(l)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:i}=t.log,n=e.map(r=>r.asHex()),s=i.asHex();try{let{eventName:r,args:a}=(0,Mn.decodeEventLog)({abi:ue,topics:n,data:s}),o=a.facilitatorAddress.toLowerCase();return{eventName:r,facilitator:o,key:`${r}:${o}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,H.map)(({payload:t})=>this.parseEvmLog(t)),(0,H.filter)(t=>t!==void 0),(0,H.filter)(({eventName:t})=>Fs.includes(t)),(0,H.finalize)(()=>{this.log(this.getPoolType(),"unsub evm log")})).subscribe(({facilitator:t,key:e})=>{this.log(this.getPoolType(),"[evm:Log]",e),this.store.update(async i=>{let n=[],[{hsmAddress:s,hollarH160:r}]=i,a=En.fromAny(s);if(a.toLowerCase()===t){let l=await this.ghoClient.getFacilitatorCapacity(r,a);for(let c of i)n.push({...c,hsmMintCapacity:l})}return n})})}subscribeBalances(){let t=[],e=[];this.store.pools.forEach(s=>{let{tokens:r,collateralId:a}=s;r.find(l=>l.id===a).type==="Erc20"?e.push(a):t.push(a)});let[{hsmAddress:i}]=this.store.pools,n=[];if(t.length>0){let s=this.subscribeTokensBalance(i);n.push(s)}if(e.length>0){let s=this.subscribeErc20Balance(i,e);n.push(s)}return n.length>0?(0,H.combineLatest)(n).pipe((0,H.map)(s=>s.flat()),(0,H.pairwise)(),(0,H.map)(([s,r])=>this.getDeltas(s,r)),(0,H.finalize)(()=>{this.log(this.getPoolType(),"unsub collateral balance")})).subscribe(s=>{this.store.update(r=>{let a=[],o=new Map(r.map(l=>[l.collateralId,l]));return s.forEach(({id:l,balance:c})=>{let p=o.get(l);p&&(this.log(this.getPoolType(),"[collateral:Balance]",l,c.transferable),a.push({...p,collateralBalance:c.transferable}))}),a})}):H.Subscription.EMPTY}subscribeUpdates(){let t=new H.Subscription;return t.add(this.subscribeEvmLog()),t}};var Dt=class extends N{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=st.Subscription.EMPTY;omniSub=st.Subscription.EMPTY;stableSub=st.Subscription.EMPTY;hsmSub=st.Subscription.EMPTY;xykSub=st.Subscription.EMPTY;lbpSub=st.Subscription.EMPTY;isReady=!1;isDestroyed=new st.Subject;constructor(t,e){super(t),this.evm=e,this.aave=new le(t,e),this.omnipool=new ie(t,e),this.stableswap=new se(t,e),this.hsm=new me(t,e,this.stableswap),this.xyk=new ae(t,e),this.lbp=new te(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe((0,st.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.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(n=>n.getPoolType()===e.type);if(i)return i.getPoolFees(t,e.address);throw new Yt(e.type)}};var Ni={};R(Ni,{DEFAULT_BLOCK_TIME:()=>qn,DEFAULT_MIN_BUDGET:()=>Mi,ORDER_MIN_BLOCK_PERIOD:()=>Nn,Router:()=>Lt,TWAP_BLOCK_PERIOD:()=>ye,TWAP_MAX_DURATION:()=>Li,TWAP_MAX_PRICE_IMPACT:()=>Di,TWAP_TX_MULTIPLIER:()=>ep,TradeOrderError:()=>ki,TradeOrderType:()=>$e,TradeRouteBuilder:()=>tt,TradeRouter:()=>qt,TradeScheduler:()=>Nt,TradeType:()=>Ke});var de=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Cs=10,ge=class{isNotVisited(t,e){let i=!0;return e.forEach(n=>{(n[0]===t[0]||n[1]===t[1])&&(i=!1)}),i}findPaths(t,e,i){let n=[],s=new de,r=[];for(r.push([e,""]),s.enqueue(r);s.size()>0;){let a=s.dequeue();if(!a||a.length>Cs)continue;let o=a[a.length-1];(i===null||o[0]===i)&&n.push(a),t.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,a)){let p=[...a];p.push(c),s.enqueue(p)}})}return n}findShortestPaths(t,e,i){let n=[],s=new de,r=[];r.push([e,""]),s.enqueue(r);let a=1/0;for(;s.size()>0;){let o=s.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===i){o.length<a?(a=o.length,n.length=0,n.push(o)):o.length===a&&n.push(o);continue}let c=t.get(l[0]);for(let p of c??[])this.isNotVisited(p,o)&&s.enqueue([...o,p])}return n}buildAndPopulateGraph(t,e){let i=new Map;for(let n of t)i.set(parseInt(n),[]);for(let[n,s,r]of e)i.get(s)?.push([r,n]);return i}};function Ei(u){let t={};for(let e of u){let i=e.tokens.length;for(let n=0;n<i;n++){t[e.tokens[n].id]||(t[e.tokens[n].id]=[]);for(let s=0;s<i;s++){if(n==s)continue;let r=[e.address,e.tokens[n].id,e.tokens[s].id];t[e.tokens[n].id].push(r)}}}return t}var he=class{getProposals(t,e,i){let n=i.filter(h=>h.type==="XYK"),s=i.filter(h=>h.type!=="XYK"),r=new Set(s.map(h=>h.tokens).flat().map(h=>h.id)),a=r.has(t),o=r.has(e),l=new ge,c=h=>{let f=Ei(h),y=Object.keys(f),S=y.flatMap(v=>f[v]);return l.buildAndPopulateGraph(y,S)};if(!a&&!o){let h=n.filter(S=>S.tokens.find(v=>v.id===t)||S.tokens.find(v=>v.id===e)),f=c(h),y=l.findPaths(f,t,e);return this.parsePaths(y)}if(a&&o){let h=c(s),f=l.findPaths(h,t,e);return this.parsePaths(f)}let p=a?e:t,m=n.filter(h=>h.tokens.some(f=>f.id===p));if(m.length===0)return[];let d=[...s,...m],g=c(d),b=l.findPaths(g,t,e);return this.parsePaths(b)}parsePaths(t){let e=[];for(let i of t){let n=[];for(let s=0;s<i.length;s++){let r=i[s],a=i[s+1];if(a==null)break;n.push(this.toEdge(r,a))}e.push(n)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var Lt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new he,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,i){return`${t}->${e}::${i.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:i=[]}=this.filter,n=new Set(e),s=new Set(i);return t.filter(r=>s.has(r.type)?!1:n.size>0?n.has(r.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let i=await this.getPools();return this.validateInput(t,e,i),this.getPaths(t,e,i)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(n=>n!==t).map(n=>this.getRoutes(n,t)))).filter(n=>n.length>0).map(([n])=>n[0].assetIn).sort()}validateInput(t,e,i){if(i.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let n=this.getAssets(i);if(!n.has(t))throw new Error(t+" is not supported asset");if(!n.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(i)}getAssets(t){let e=t.map(i=>i.tokens.map(n=>n.id)).flat().sort((i,n)=>i>n?1:-1);return new Set(e)}getPaths(t,e,i){let n=this.toPoolsMap(i);return this.getProposals(t,e,i).filter(r=>this.validPath(r,n)).map(r=>this.toHops(r,n))}getProposals(t,e,i){let n=this.buildRouteKey(t,e,i);if(this.routeProposals.has(n))return this.routeProposals.get(n);let s=this.routeSuggester.getProposals(t,e,i);return this.routeProposals.set(n,s),s}validPath(t,e){return t.length>0&&t.map(i=>this.validEdge(i,e)).reduce((i,n)=>i&&n)}validEdge([t,e,i],n){return n.get(t)?.validatePair(e,i)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Mt.get(e)]))}toHops(t,e){return t.map(([i,n,s])=>{let r=e.get(i);return{poolAddress:i,poolId:r?.id,pool:r?.type,assetIn:n,assetOut:s}})}};var I=require("@galacticcouncil/common");var Dn=require("@galacticcouncil/common");function be(u,t,e,i){let n=Math.pow(10,e+Dn.RUNTIME_DECIMALS-i);return u*t/BigInt(n)}var Ke=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Ke||{}),$e=(i=>(i.Dca="Dca",i.TwapSell="TwapSell",i.TwapBuy="TwapBuy",i))($e||{}),ki=(i=>(i.OrderTooSmall="OrderTooSmall",i.OrderTooBig="OrderTooBig",i.OrderImpactTooBig="OrderImpactTooBig",i))(ki||{});var{FeeUtils:Ln}=_,qt=class extends Lt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,i){let n=super.validateInput(t,e,i),s=super.getPaths(t,e,i);if(!s.length)throw new zt(t,e);return{paths:s,pools:i,poolsMap:n}}async withCtx(t,e,i){let n=await super.getPools(),s=this.buildCtxSync(t,e,n);return i(s)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((i,n)=>{let s=i[i.length-1].amountOut,r=n[n.length-1].amountOut;return s>r?-1:1});return e.find(i=>i.every(n=>n.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(i=>i.tradeFeeRange).length>0){let i=t.map(s=>s.tradeFeeRange?.[0]??s.tradeFeePct).reduce((s,r)=>s+r),n=t.map(s=>s.tradeFeeRange?.[1]??s.tradeFeePct).reduce((s,r)=>s+r);return[i,n]}}getPoolFeeRange(t){let e=t.min?Ln.toPct(t.min):void 0,i=t.max?Ln.toPct(t.max):void 0;if(e&&i)return[e,i]}async getBestSell(t,e,i){return this.getSell(t,e,i)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,i,n){return this.withCtx(t,e,async({paths:s,poolsMap:r})=>{let a;if(n)a=await this.toSellSwaps(i,n,r);else{let o=s.map(c=>this.toSellSwaps(i,c,r)),l=await Promise.all(o);a=this.findBestSellRoute(l)}return this.buildSell(r,a)})}async getSells(t,e,i){return this.withCtx(t,e,async({paths:n,poolsMap:s})=>{let r=n.map(o=>this.toSellSwaps(i,o,s));return(await Promise.all(r)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(s,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let i=e[0],n=e[e.length-1],s=this.isDirectTrade(e),r=this.getSellSpot(e),a=n.amountOut,o=s?n.calculatedOut:this.calculateDelta0Y(i.amountIn,e,t),l=o-a,c=this.getRouteFeeRange(e),p=s?n.tradeFeePct:O.calculateSellFee(o,a),m=be(i.amountIn,r,i.assetInDecimals,n.assetOutDecimals),d=O.calculateDiffToRef(o,m);return{type:"Sell",amountIn:i.amountIn,amountOut:n.amountOut,spotPrice:r,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Sell",amountIn:I.big.toDecimal(i.amountIn,i.assetInDecimals),amountOut:I.big.toDecimal(n.amountOut,n.assetOutDecimals),spotPrice:I.big.toDecimal(r,I.RUNTIME_DECIMALS),tradeFee:I.big.toDecimal(l,n.assetOutDecimals),tradeFeePct:p,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(g=>g.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,i)=>e*i/10n**BigInt(I.RUNTIME_DECIMALS))}calculateDelta0Y(t,e,i){let n=[];for(let s=0;s<e.length;s++){let r=e[s],a=i.get(r.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(r.assetIn,r.assetOut),l;s>0?l=n[s-1]:l=t;let c=a.calculateOutGivenIn(o,l);n.push(c)}return n[n.length-1]}async calculateMostLiquidRoute(t,e,i){let{paths:n,pools:s,poolsMap:r}=i,l=s.filter(b=>b.tokens.some(h=>h.id===t)).map(b=>b.type==="Aave"?b.tokens:b.tokens.filter(h=>h.id===t)).map(b=>b.map(h=>h.balance).reduce((h,f)=>h+f)).sort((b,h)=>h<b?-1:1)[0],c=O.getFraction(l,.1),p=await Promise.all(n.map(b=>this.toSellSwaps(c,b,r))),d=this.findBestSellRoute(p).map(b=>({poolAddress:b.poolAddress,poolId:b?.poolId,pool:b.pool,assetIn:b.assetIn,assetOut:b.assetOut})),g=this.buildRouteKey(t,e,s);return this.mlr.set(g,d),d}async toSellSwaps(t,e,i){let n=[];for(let s=0;s<e.length;s++){let r=e[s],a=i.get(r.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(r.assetIn,r.assetOut),l;s>0?l=n[s-1].amountOut:l=typeof t=="string"?I.big.toBigInt(t,o.decimalsIn):t;let c=await this.ctx.getPoolFees(o,a),{amountOut:p,calculatedOut:m,feePct:d,errors:g}=a.validateAndSell(o,l,c),b=this.getPoolFeeRange(c),h=a.spotPriceOutGivenIn(o),f=be(l,h,o.decimalsIn,o.decimalsOut),y=O.calculateDiffToRef(m,f);n.push({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:m,spotPrice:h,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===r.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===r.assetIn},toHuman(){return{...r,amountIn:I.big.toDecimal(l,o.decimalsIn),amountOut:I.big.toDecimal(p,o.decimalsOut),calculatedOut:I.big.toDecimal(m,o.decimalsOut),spotPrice:I.big.toDecimal(h,I.RUNTIME_DECIMALS),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y,errors:g}}})}return n}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async i=>{let n=this.buildRouteKey(t,e,i.pools),s=this.mlr.get(n);return s||this.calculateMostLiquidRoute(t,e,i)})}async getSpotPrice(t,e){return this.withCtx(t,e,async i=>{let{pools:n,poolsMap:s}=i,r=this.buildRouteKey(t,e,n),a=this.mlr.get(r);a||(a=await this.calculateMostLiquidRoute(t,e,i));let o=await this.toSellSwaps("1",a,s);return{amount:this.getSellSpot(o),decimals:I.RUNTIME_DECIMALS}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((i,n)=>{let s=i[0].amountIn,r=n[0].amountIn;return s>r?1:-1});return e.find(i=>i.every(n=>n.errors.length==0))||e[0]}async getBestBuy(t,e,i){return this.getBuy(t,e,i)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,i,n){return this.withCtx(t,e,async({paths:s,poolsMap:r})=>{let a;if(n)a=await this.toBuySwaps(i,n,r);else{let o=s.map(c=>this.toBuySwaps(i,c,r)),l=await Promise.all(o);a=this.findBestBuyRoute(l)}return this.buildBuy(r,a)})}async getBuys(t,e,i){return this.withCtx(t,e,async({paths:n,poolsMap:s})=>{let r=n.map(o=>this.toBuySwaps(i,o,s));return(await Promise.all(r)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(s,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let i=e[e.length-1],n=e[0],s=this.isDirectTrade(e),r=this.getBuySpot(e),a=n.amountIn,o=s?n.calculatedIn:this.calculateDelta0X(i.amountOut,e,t),l=a-o,c=this.getRouteFeeRange(e),p=s?n.tradeFeePct:O.calculateBuyFee(o,a),m=be(i.amountOut,r,i.assetOutDecimals,n.assetInDecimals),d;return o===0n?d=-100:d=O.calculateDiffToRef(m,o),{type:"Buy",amountOut:i.amountOut,amountIn:n.amountIn,spotPrice:r,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Buy",amountOut:I.big.toDecimal(i.amountOut,i.assetOutDecimals),amountIn:I.big.toDecimal(n.amountIn,n.assetInDecimals),spotPrice:I.big.toDecimal(r,I.RUNTIME_DECIMALS),tradeFee:I.big.toDecimal(l,n.assetInDecimals),tradeFeePct:p,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(g=>g.toHuman())}}}}calculateDelta0X(t,e,i){let n=[];for(let s=e.length-1;s>=0;s--){let r=e[s],a=i.get(r.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(r.assetIn,r.assetOut),l;s==e.length-1?l=t:l=n[0];let c=a.calculateInGivenOut(o,l);n.unshift(c)}return n[0]}async toBuySwaps(t,e,i){let n=[];for(let s=e.length-1;s>=0;s--){let r=e[s],a=i.get(r.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(r.assetIn,r.assetOut),l;s==e.length-1?l=typeof t=="string"?I.big.toBigInt(t,o.decimalsOut):t:l=n[0].amountIn;let c=await this.ctx.getPoolFees(o,a),{amountIn:p,calculatedIn:m,feePct:d,errors:g}=a.validateAndBuy(o,l,c),b=this.getPoolFeeRange(c),h=a.spotPriceInGivenOut(o),f=be(l,h,o.decimalsOut,o.decimalsIn),y;m===0n?y=-100:y=O.calculateDiffToRef(f,m),n.unshift({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:m,spotPrice:h,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===r.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===r.assetIn},toHuman(){return{...r,amountOut:I.big.toDecimal(l,o.decimalsOut),amountIn:I.big.toDecimal(p,o.decimalsIn),calculatedIn:I.big.toDecimal(m,o.decimalsIn),spotPrice:I.big.toDecimal(h,I.RUNTIME_DECIMALS),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:y,errors:g}}})}return n}};var Y=require("@galacticcouncil/common");var qn=6e3,Mi=1000000000000000n,ye=6,Di=-5,Li=216e5,ep=3,Nn=6;var qi=require("polkadot-api");var tt=class{static build(t){return t.map(({assetIn:e,assetOut:i,pool:n,poolId:s})=>n==="Stableswap"?{pool:(0,qi.Enum)("Stableswap",s),asset_in:e,asset_out:i}:{pool:(0,qi.Enum)(n),asset_in:e,asset_out:i})}};var Nt=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Mi})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,i,n,s){let[r,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,i)]),{amountIn:o,swaps:l,priceImpactPct:c}=a,p=l[0],m=l[l.length-1],{assetInDecimals:d}=p,{assetOutDecimals:g}=m,b=Math.abs(c),h=this.getMaximumTradeCount(o,r),f=this.getOptimalTradeCount(b),y=s||f,S=Math.round(n/y),v=o/BigInt(y),x=await this.router.getBestSell(t,e,v),A=o<r,D=[];A&&D.push("OrderTooSmall");let G=x.amountOut*BigInt(y),rt=this.toBlockPeriod(S),ut=x.tradeFee*BigInt(y),K=tt.build(l),Q={assetIn:t,assetOut:e,errors:D,maxTradeCount:h,optTradeCount:f,tradeCount:y,tradeFee:ut,tradeImpactPct:x.priceImpactPct,tradePeriod:rt,tradeRoute:K,type:"Dca"};return{...Q,amountIn:o,amountOut:G,tradeAmountIn:x.amountIn,tradeAmountOut:x.amountOut,toHuman(){return{...Q,amountIn:Y.big.toDecimal(o,d),amountOut:Y.big.toDecimal(G,g),tradeAmountIn:Y.big.toDecimal(x.amountIn,d),tradeAmountOut:Y.big.toDecimal(x.amountOut,g)}}}}async getMinimumOrderBudget(t){if(0===t)return this.minOrderBudget;let e=await this.router.getSpotPrice(0,t),i=10n**BigInt(12);if(e)return this.minOrderBudget*e.amount/i;throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e){let i=e*2n/10n;if(i===0n)return 0;let n=t+i/2n;return Number(n/i)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,i){let[n,s]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,i)]),{amountIn:r,swaps:a,priceImpactPct:o}=s,l=a[0],c=a[a.length-1],{assetInDecimals:p}=l,{assetOutDecimals:m}=c,d=Math.abs(o),g=this.getTwapTradeCount(d),b=r/BigInt(g),h=await this.router.getBestSell(l.assetIn,c.assetOut,b),f=g===1,y=r<n,S=h.priceImpactPct<-5,v=[];y||f?v.push("OrderTooSmall"):S&&v.push("OrderImpactTooBig");let x=h.amountOut*BigInt(g),A=h.tradeFee*BigInt(g),D=tt.build(a),G={assetIn:t,assetOut:e,errors:v,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:D,type:"TwapSell"};return{...G,amountIn:r,amountOut:x,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:A,toHuman(){return{...G,amountIn:Y.big.toDecimal(r,p),amountOut:Y.big.toDecimal(x,m),tradeAmountIn:Y.big.toDecimal(h.amountIn,p),tradeAmountOut:Y.big.toDecimal(h.amountOut,m),tradeFee:Y.big.toDecimal(A,m)}}}}async getTwapBuyOrder(t,e,i){let[n,s]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,i)]),{amountOut:r,swaps:a,priceImpactPct:o}=s,l=a[0],c=a[a.length-1],{assetInDecimals:p}=l,{assetOutDecimals:m}=c,d=Math.abs(o),g=this.getTwapTradeCount(d),b=r/BigInt(g),h=await this.router.getBestBuy(l.assetIn,c.assetOut,b),f=h.amountIn*BigInt(g),y=g===1,S=f<n,v=h.priceImpactPct<-5,x=[];S||y?x.push("OrderTooSmall"):v&&x.push("OrderImpactTooBig");let A=h.tradeFee*BigInt(g),D=tt.build(a),G={assetIn:t,assetOut:e,errors:x,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:D,type:"TwapBuy"};return{...G,amountIn:f,amountOut:r,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:A,toHuman(){return{...G,amountIn:Y.big.toDecimal(f,p),amountOut:Y.big.toDecimal(r,m),tradeAmountIn:Y.big.toDecimal(h.amountIn,p),tradeAmountOut:Y.big.toDecimal(h.amountOut,m),tradeFee:Y.big.toDecimal(A,p)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let n=216e5/(this.blockTime*6);return Math.round(n)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,i=Math.round(e);return Math.max(i,6)}};var Gi={};R(Gi,{BIG_10:()=>Yn,BIG_BILL:()=>Hi,StakingApi:()=>fe,StakingClient:()=>Pe});var z=require("@galacticcouncil/math-staking"),j=dt(require("big.js"));var je={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},Hn=u=>Object.keys(je).includes(u);var Gn=require("polkadot-api"),Un=require("@polkadot-api/utils"),Vn=require("@galacticcouncil/common");function Wn(u){let t=("modl"+u).padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,Un.toHex)(e);return(0,Gn.AccountId)(Vn.HYDRATION_SS58_PREFIX).dec(i)}var Qe="20000000000000000",Je="2000",Yn=(0,j.default)(10),Hi=(0,j.default)(Yn.pow(12)),fe=class{client;balanceClient;constructor(t,e){this.client=t,this.balanceClient=e}async getPotBalance(){let t=await this.client.getPalletId(),e=Wn(t);return await this.balanceClient.getBalance(e,0)}async getStakingPosition(t){let[e,i]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let n=e.created_at,s=await i.reduce(async(r,[a,o])=>{let l=await r,c=a,p=o.amount,m=o.conviction.type.toLowerCase(),d=await this.client.getReferendumInfo(c);return d&&(d.type==="Approved"||d.type==="Rejected")&&Hn(m)&&l.push({id:c,amount:p,conviction:m}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:n,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:s}}async getStake(t){let e=await this.client.getNFTCollectionId(),[i,n]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),s=n.find(r=>r)?.itemId;return{totalStake:i?.total_stake,accumulatedRewardPerStake:i?.accumulated_reward_per_stake,potReservedBalance:i?.pot_reserved_balance,positionId:s,stakePosition:s?await this.getStakingPosition(s):void 0}}getCurrentActionPoints(t,e,i,n){let s=(0,j.default)(0),r=(0,j.default)(0),a=je.locked6x,o=(0,j.default)(i.toString()).mul(a),l=100,c=[];t.forEach(d=>{let g=je[d.conviction],b=n.includes(d.id.toString());b&&c.push(d.id.toString());let h=(0,j.default)(d.amount.toString()).mul(l).div(o);s=s.plus(Math.floor(h.mul(g).toNumber())),r=r.plus(Math.floor(h.mul(b?a:g).toNumber()))});let p=Math.floor((0,j.default)(i.toString()).mul(a).mul(l).div(o).toNumber());n.forEach(d=>{c.includes(d)||(r=r.plus(p))});let m={democracyVote:1};return s=s.mul(m.democracyVote),s=s.plus(e.toString()||"0"),r=r.mul(m.democracyVote),r=r.plus(e.toString()||"0"),{currentActionPoints:s.toString(),maxActionPoints:r.toString()}}async getRewards(t,e,i){let n=await this.getStake(t),{potReservedBalance:s,accumulatedRewardPerStake:r,totalStake:a,stakePosition:o}=n;if(!o)return;let[l,c,p,m,d,g,b]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),h=(0,j.default)(l.transferable.toString()).minus(s.toString()),f=h.gt(0)&&a>0?(0,z.calculate_accumulated_rps)(r.toString(),h.toString(),a.toString()):r.toString(),y=(0,z.calculate_period_number)(c.toString(),i,b),S=(0,z.calculate_period_number)(c.toString(),o.createdAt.toString(),b),v=(0,z.calculate_rewards)(f,o.rewardPerStake.toString(),o.stake.toString()),x=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),A=(0,z.calculate_points)(S,y,m.toString(),d.toString(),x.currentActionPoints,g.toString(),o.accumulatedSlashPoints.toString()),D=(0,z.sigmoid)(A,Qe,Je),G=(()=>{if(!e.length)return;let Ut=(0,z.calculate_points)(S,y,m.toString(),d.toString(),x.maxActionPoints.toString(),g.toString(),o.accumulatedSlashPoints.toString());return(0,z.sigmoid)(Ut,Qe,Je)})(),rt=(0,j.default)(v).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if((0,j.default)(y).minus(S).lte(p.toString()))return{rewards:"0",payablePercentage:D,extraPayablePercentage:G,constants:{a:Qe,b:Je}};let ut=(0,z.calculate_percentage_amount)(rt.toString(),D),K=(0,j.default)(o.accumulatedLockedRewards.toString()),Q=K.gt(ut)?K:(0,j.default)(ut);return{rewards:Q.div(Hi).toString(),maxRewards:rt.div(Hi).toString(),allocatedRewardsPercentage:Q.div(rt).mul(100).toNumber(),points:A,payablePercentage:D,extraPayablePercentage:G,constants:{a:Qe,b:Je}}}};var Pe=class extends N{async getPalletId(){let t=this.api.constants.Staking.PalletId;return(await t()).asText()}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:r})=>{let[a,o,l]=r;return{address:a,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var Vi={};R(Vi,{TxBuilderFactory:()=>Gt});var Ui=require("polkadot-api");function zn(u){let t=[],e=u;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var Ht=class extends N{evm;evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balanceClient=new at(t),this.aaveUtils=new Pt(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:i=>this.dryRun(i,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:ai})}async dryRun(t,e){let i=(0,Ui.Enum)("Signed",t),n=(0,Ui.Enum)("system",i),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(n,e.decodedCall),a=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(a){let o=zn(a.value);throw new Error("Dry run execution error!",{cause:o})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var Ze=class extends Ht{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:i}=this.trade;if(i==="Buy")return this.buildBuyTx();let{assetIn:n}=e[0],s=await this.balanceClient.getBalance(this.beneficiary,n);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,n=i[0],s=i[i.length-1],r=O.getFraction(t,this.slippagePct),a=n.assetIn,o=s.assetOut,l=t+r,c;return this.isDirectOmnipoolTrade(i)?c=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):c=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:tt.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,n=i[0],s=i[i.length-1],r=O.getFraction(e,this.slippagePct),a=n.assetIn,o=s.assetOut,l=e-r,c;return this.isDirectOmnipoolTrade(i)?c=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):c=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:tt.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,i=e[0],n=e[e.length-1],s=O.getFraction(t,this.slippagePct),r=i.assetIn,a=n.assetOut,o=t-s,l=this.api.tx.Router.sell_all({asset_in:r,asset_out:a,min_amount_out:o,route:tt.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var ti=require("polkadot-api");var ei=class extends Ht{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:n,tradePeriod:s,tradeRoute:r}=this.order,a=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ti.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:n,min_amount_out:0n,route:r})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:n,tradeAmountOut:s,tradePeriod:r,tradeRoute:a}=this.order,o=O.getFraction(s,this.slippagePct),l=s-o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ti.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:n,min_amount_out:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:n,tradeAmountOut:s,tradePeriod:r,tradeRoute:a}=this.order,o=O.getFraction(n,this.slippagePct),l=n+o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ti.Enum)("Buy",{asset_in:e,asset_out:i,amount_out:s,max_amount_in:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",c)}};var Gt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new Ze(this.client,this.evmClient).setTrade(t)}order(t){return new ei(this.client,this.evmClient).setOrder(t)}};async function Es(u){let t=new At(u),e=new Kt(u),[i,n]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),s=new Dt(u,e).withAave().withOmnipool().withStableswap().withXyk(),r=new at(u),a=new Pe(u),o=new Jt(u),l=new Pt(e),c=new qt(s),p=new Nt(c,{blockTime:i,minBudgetInNative:n}),m=new fe(a,r),d=new Qt(o,r,{blockTime:i});return{api:{aave:l,router:c,scheduler:p,staking:m,farm:d},client:{asset:new wt(u),balance:r,evm:e},ctx:{pool:s},tx:new Gt(u,e),destroy:()=>{s.destroy()}}}0&&(module.exports={QueryBus,aave,api,client,const:null,createSdkContext,error,evm,farm,fmt,json,math,pool,sor,staking,tx});
|
|
1
|
+
"use strict";var pr=Object.create;var Ce=Object.defineProperty;var mr=Object.getOwnPropertyDescriptor;var dr=Object.getOwnPropertyNames;var gr=Object.getPrototypeOf,hr=Object.prototype.hasOwnProperty;var B=(c,t)=>{for(var e in t)Ce(c,e,{get:t[e],enumerable:!0})},nn=(c,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of dr(t))!hr.call(c,n)&&n!==e&&Ce(c,n,{get:()=>t[n],enumerable:!(i=mr(t,n))||i.enumerable});return c};var yt=(c,t,e)=>(e=c!=null?pr(gr(c)):{},nn(t||!c||!c.__esModule?Ce(e,"default",{value:c,enumerable:!0}):e,c)),br=c=>nn(Ce({},"__esModule",{value:!0}),c);var ts={};B(ts,{QueryBus:()=>re,aave:()=>fi,api:()=>di,async:()=>ie,calc:()=>q,client:()=>wi,const:()=>Si,createSdkContext:()=>Zr,error:()=>xi,evm:()=>_i,farm:()=>Ei,fmt:()=>I,json:()=>kt,math:()=>U,pool:()=>Ui,sor:()=>Ki,staking:()=>Qi,tx:()=>Zi});module.exports=br(ts);var di={};B(di,{ChainWatcher:()=>Kt,Papi:()=>H,getWs:()=>fr});var an=require("@galacticcouncil/descriptors");var sn=require("@galacticcouncil/common"),Fe=require("rxjs");var ft=require("rxjs"),et=require("rxjs/operators");function rn(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1500}={}){return(0,ft.timer)(0,t).pipe((0,et.switchMap)(()=>(0,ft.defer)(()=>(0,ft.from)(c._request("system_health",[]))).pipe((0,et.timeout)({first:e}),(0,et.map)(()=>"online"),(0,et.catchError)(()=>(0,ft.of)("offline")))),(0,et.distinctUntilChanged)(),(0,et.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:yr}=sn.log,Kt=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)",rn(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe((0,Fe.tap)({error:i=>yr.error(t,i)}),(0,Fe.shareReplay)({bufferSize:1,refCount:!0}))}};var H=class{client;api;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(an.hydration),this.watcher=Kt.getInstance(this.client)}};var on=require("polkadot-api/logs-provider"),ln=require("@polkadot-api/legacy-provider"),cn=require("polkadot-api/ws-provider"),fr=(c,t={})=>{let e=typeof c=="string"?c.split(","):c,i=(0,cn.getWsProvider)(e,{innerEnhancer:(0,ln.withLegacy)(),...t});return(0,on.withLogsRecorder)(n=>console.log(n),i),i};var fi={};B(fi,{AAVE_GAS_LIMIT:()=>bi,AAVE_LENDING_POOL_ADDRESS:()=>Me,AAVE_POOL_ABI:()=>gi,AAVE_POOL_DATA_PROVIDER:()=>ke,AAVE_POOL_DATA_PROVIDER_ABI:()=>Ee,AAVE_POOL_PROXY:()=>hi,AAVE_ROUNDING_THRESHOLD:()=>fs,AAVE_UINT_256_MAX:()=>Pr,AaveClient:()=>jt,AaveUtils:()=>xt});var gi=[{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 Ee=[{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 hi="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",ke="0x112b087b60C1a166130d59266363C45F8aa99db0",Me="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",bi=1000000n,fs=5,Pr=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var jt=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:Ee,address:ke,args:[Me],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:Ee,address:ke,args:[Me,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:gi,address:hi,args:[t],functionName:"getUserAccountData"})}};var L=yt(require("big.js")),it=require("@galacticcouncil/common");var{ERC20:Ot}=it.erc20,{H160:yi}=it.h160,vr=1.01,Sr=31536000n,un=4,De=-1,Le=10n**27n,xt=class{client;constructor(t){this.client=new jt(t)}async getSummary(t){let e=yi.fromAny(t),[i,n,r,s]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[a]=i,[o,l]=n,[u,p,d,m,h,b]=r,g=it.big.toDecimal(b,18),f=[];for(let y of o){let S=y.underlyingAsset.toLowerCase(),v=a.find(({underlyingAsset:mi})=>mi.toLowerCase()===S);if(!v)throw new Error("Missing pool reserve for "+S);let T=y.scaledATokenBalance,A=v.liquidityIndex,D=v.liquidityRate,G=v.availableLiquidity,lt=v.priceInMarketReferenceCurrency,gt=s+6,j=this.calculateLinearInterest(D,v.lastUpdateTimestamp,gt),tt=A*j/Le,Xt=T*tt/Le,Oe=Number(l!==0&&l===v.eModeCategoryId?v.eModeLiquidationThreshold:v.reserveLiquidationThreshold)/1e4,Be=v.usageAsCollateralEnabled&&y.usageAsCollateralEnabledOnUser&&y.scaledATokenBalance>0n,Re=Ot.toAssetId(S);f.push({aTokenBalance:Xt,availableLiquidity:G,decimals:Number(v.decimals),isCollateral:Be,priceInRef:lt,reserveId:Re,reserveAsset:S,reserveLiquidationThreshold:Oe})}return{healthFactor:Number(g),currentLiquidationThreshold:Number(it.big.toDecimal(m,un)),totalCollateral:u,totalDebt:p,reserves:f}}async hasBorrowPositions(t){let e=yi.fromAny(t),i=await this.client.getUserAccountData(e),[n,r]=i;return r>0n}async getHealthFactor(t){let e=yi.fromAny(t),i=await this.client.getUserAccountData(e),[n,r,s,a,o,l]=i;return this.calculateHealthFactorFromBalances(r,n,a)}async getHealthFactorAfterWithdraw(t,e,i){let{totalCollateral:n,totalDebt:r,reserves:s,currentLiquidationThreshold:a}=await this.getSummary(t);if(r===0n)return De;let o=Ot.fromAssetId(e),l=s.find(S=>S.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:u,isCollateral:p,priceInRef:d,reserveLiquidationThreshold:m}=l,h=it.big.toBigInt(i,u),b=p?h*d/10n**BigInt(u):0n,g=n-b;if(g<=0n)return 0;let f=(0,L.default)(n.toString()).mul(a).minus((0,L.default)(b.toString()).mul(m)).div(g.toString()),y=(0,L.default)(g.toString()).mul(f).div(r.toString()).toFixed(6,L.default.roundDown);return Number(y)}async getHealthFactorAfterSupply(t,e,i){let{totalCollateral:n,totalDebt:r,reserves:s,currentLiquidationThreshold:a}=await this.getSummary(t);if(r===0n)return De;let o=Ot.fromAssetId(e),l=s.find(y=>y.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:u,priceInRef:p,reserveLiquidationThreshold:d}=l,h=it.big.toBigInt(i,u)*p/10n**BigInt(u),b=n+h;if(b<=0n)return 0;let g=(0,L.default)(n.toString()).mul(a).plus((0,L.default)(h.toString()).mul(d)).div(b.toString()),f=(0,L.default)(b.toString()).mul(g).div(r.toString()).toFixed(6,L.default.roundDown);return Number(f)}async getHealthFactorAfterSwap(t,e,i,n,r){let{totalDebt:s,reserves:a,healthFactor:o}=await this.getSummary(t);if(s===0n)return De;let l=Ot.fromAssetId(i),u=Ot.fromAssetId(r),p=a.find(A=>A.reserveAsset===l),d=a.find(A=>A.reserveAsset===u);if(!p)throw new Error(`Missing reserve ctx for ${l}`);if(!d)throw new Error(`Missing reserve ctx for ${d}`);let m=it.big.toBigInt(e,p.decimals),h=it.big.toBigInt(n,d.decimals),b=m*p.priceInRef/10n**BigInt(p.decimals),g=h*d.priceInRef/10n**BigInt(d.decimals),f=p.isCollateral?(0,L.default)(b.toString()).mul(p.reserveLiquidationThreshold):(0,L.default)(0),v=(0,L.default)(g.toString()).mul(d.reserveLiquidationThreshold).minus(f).div(s.toString()),T=(0,L.default)(o).plus(v).toFixed(6,L.default.roundDown);return Number(T)}async getMaxWithdraw(t,e){let{totalDebt:i,reserves:n,healthFactor:r}=await this.getSummary(t),s=Ot.fromAssetId(e),a=n.find(o=>o.reserveAsset===s);if(!a)throw new Error("Missing reserve ctx for "+s);return this.calculateWithdrawMax(a,i,r)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:i,healthFactor:n}=await this.getSummary(t),r={};for(let s of i){let a=this.calculateWithdrawMax(s,e,n);s.reserveId&&(r[s.reserveId]=a)}return r}calculateWithdrawMax(t,e,i){let{aTokenBalance:n,availableLiquidity:r,decimals:s,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=t,u=n;if(l&&e>0n){let d=i-vr;if(d>0){let m=(0,L.default)(d).mul(e.toString()).div(o).toFixed(0,L.default.roundDown),h=(0,L.default)(m).div(a.toString()).mul(10**s).toFixed(0,L.default.roundDown);u=n<BigInt(h)?n:BigInt(h)}else u=0n}return{amount:u<r?u:r,decimals:s}}calculateLinearInterest(t,e,i){let n=i-e;if(n<=0)return Le;let r=t*BigInt(n)/Sr;return Le+r}calculateHealthFactorFromBalances(t,e,i){if(t===0n)return De;let n=e*i/t,r=it.big.toDecimal(n,un);return Number(r)}};var wi={};B(wi,{AssetClient:()=>Bt,BalanceClient:()=>ct,ChainParams:()=>Et});var Bt=class extends H{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:i,value:n})=>{let[r]=i;return[r,n]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:i,value:n})=>{let[r]=i;return[r,n]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:i})=>{let{asset_type:n}=i;return this.SUPPORTED_TYPES.includes(n.type)}).map(({keyArgs:i,value:n})=>{let[r]=i;return[r,n]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:i,value:n})=>{let[r]=i;return[r,n]}))}async mapToken(t,e,i,n){let{name:r,asset_type:s,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=i.get(t)??{};return{id:t,name:r?.asText(),symbol:l,decimals:u,icon:l,type:s.type,isSufficient:a,location:n,existentialDeposit:o}}async mapBond(t,e,i,n){let[r,s]=n,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:p}=await this.mapToken(r,e,i),d=Number(s),m=new Intl.DateTimeFormat("en-GB"),h=[u,"Bond",m.format(d)].join(" ");return{id:t,name:h,symbol:u+"b",decimals:p,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:r,maturity:d}}async mapShares(t,e,i,n){let{assets:r}=n,{name:s,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,p=await Promise.all(r.map(async h=>{let{symbol:b}=await this.mapToken(h,e,i);return[h,b]})),d=Object.fromEntries(p),m=Object.values(d);return{id:t,name:m.join(", "),symbol:a?.asText()||s?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:d}}async mapExternal(t,e,i,n){let r=await this.mapToken(t,e,new Map,n),s=i?.find(a=>a.internalId===r.id);return s?{...r,decimals:s.decimals,name:s.name,symbol:s.symbol,icon:s.symbol,isWhiteListed:s.isWhiteListed}:r}parseMetadata(t){return new Map(Array.from(t,([e,i])=>[e,{symbol:i.symbol?.asText(),decimals:i.decimals}]))}async getOnChainAssets(t,e){let[i,n,r,s]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(i),o=[];for(let[l,u]of Array.from(i)){let p=n.get(l),{asset_type:d}=u,m;switch(d.type){case"Bond":let h=s.get(l);m=await this.mapBond(l,u,a,h);break;case"StableSwap":let b=r.get(l);m=await this.mapShares(l,u,a,b);break;case"External":m=await this.mapExternal(l,u,e,p);break;default:m=await this.mapToken(l,u,a,p)}o.push(m)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var pn=require("@galacticcouncil/common"),Q=require("rxjs"),C=require("rxjs/operators");var Si={};B(Si,{HUB_ASSET_ID:()=>Qt,HYDRATION_OMNIPOOL_ADDRESS:()=>Tr,HYDRATION_PARACHAIN_ID:()=>wr,PERBILL_DENOMINATOR:()=>Pi,PERMILL_DENOMINATOR:()=>Rt,SYSTEM_ASSET_DECIMALS:()=>vi,SYSTEM_ASSET_ID:()=>E,TRADEABLE_DEFAULT:()=>Ct});var Rt=1e6,Pi=1e9,E=0,vi=12,wr=2034,Tr="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Qt=1,Ct=15;var{logger:Ft}=pn.log,ct=class extends H{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:i}=await e.getValue(t,{at:"best"});return this.calculateBalance(i)}async getTokenBalance(t,e){let n=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.calculateBalance(n)}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),i=this.subscribeTokensBalance(t),n=this.subscribeErc20Balance(t);return(0,Q.combineLatest)([e,i,n]).pipe((0,C.tap)({error:r=>Ft.error("balance",r)}),(0,Q.retry)({delay:1e3}),(0,Q.debounceTime)(250),(0,C.map)(r=>r.flat()),(0,C.startWith)([]),(0,C.bufferCount)(2,1),(0,C.map)(([r,s],a)=>a===0?s:this.getDeltas(r,s)))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe((0,C.tap)({error:i=>Ft.error("balance(system)",i)}),(0,C.map)(i=>({id:0,balance:this.calculateBalance(i.data)})))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe((0,C.tap)({error:n=>Ft.error("balance(token)",n)}),(0,C.map)(n=>({id:e,balance:this.calculateBalance(n)})))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe((0,C.tap)({error:i=>Ft.error("balance(tokens)",i)}),(0,Q.distinctUntilChanged)((i,n)=>!n.deltas),(0,C.map)(({deltas:i})=>{let n=[];return i?.deleted.forEach(r=>{let[s,a]=r.args;n.push({id:a,balance:this.calculateBalance({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(r=>{let[s,a]=r.args;n.push({id:a,balance:this.calculateBalance(r.value)})}),n}))}subscribeErc20Balance(t,e){let i=new Q.Subject,n=i.pipe((0,Q.shareReplay)(1)),r=async()=>(await this.api.query.AssetRegistry.Assets.getEntries({at:"best"})).filter(({value:l})=>{let{asset_type:u}=l;return u.type==="Erc20"}).map(({keyArgs:l})=>{let[u]=l;return u}),s=async()=>{let o=e||await r(),l=async()=>{let d=(await Promise.all(o.map(async m=>{let h=await this.getTokenBalanceData(t,m);return[m,h]}))).map(([m,h])=>({id:m,balance:h}));i.next(d)};await l();let u=this.watcher.bestBlock$.subscribe({error:p=>Ft.error("balance(erc20) watcher.bestBlock",p),next:l});return()=>u.unsubscribe()},a;return s().then(o=>a=o),n.pipe((0,C.tap)({error:o=>Ft.error("balance(erc20)",o)}),(0,C.finalize)(()=>a?.()),(0,C.pairwise)(),(0,C.map)(([o,l],u)=>u===0?l.filter(p=>p.balance.transferable>0n):this.getDeltas(o,l)),(0,Q.distinctUntilChanged)((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.calculateBalance(i)}calculateBalance(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=(r,s)=>r!==void 0&&s!==void 0&&r.transferable===s.transferable&&r.total===s.total,n=t.reduce((r,s)=>(r.set(s.id,s.balance),r),new Map);return e.filter(r=>!i(r.balance,n.get(r.id)))}};var Et=class extends H{_minOrderBudget;_blockTime;constructor(t){super(t)}async getBlockTime(){if(this._blockTime===void 0){let t=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(t)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var xi={};B(xi,{AssetNotFound:()=>Ti,PoolNotFound:()=>Jt,RouteNotFound:()=>Zt});var Ti=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},Jt=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},Zt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var _i={};B(_i,{EvmClient:()=>ee,EvmRpcAdapter:()=>te,createChain:()=>Ii});var It=require("polkadot-api"),mn=require("@galacticcouncil/descriptors"),qe=require("viem"),xr=10000000n,te=class{api;constructor(t){this.api=t.getTypedApi(mn.hydration)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,i=e.timestamp/1000n,[n]=e.number;return{timestamp:i,number:n}}readContract=(async t=>{let{abi:e,address:i,functionName:n,args:r}=t,s=(0,qe.encodeFunctionData)({abi:e,functionName:n,args:r}),a=this.api.apis.EthereumRuntimeRPCApi.call,o=await this.api.compatibilityToken,l=a.isCompatible(It.CompatibilityLevel.BackwardsCompatible,o);console.log(l);let u=await this.api.apis.EthereumRuntimeRPCApi.call(It.FixedSizeBinary.fromText(""),It.FixedSizeBinary.fromHex(i),It.Binary.fromHex(s),[0n,0n,0n,0n],[xr,0n,0n,0n],void 0,void 0,void 0,!1,[]);if(console.log(u),!u.success)throw console.error(n,u.value.type),new Error("Contract read failure");let{exit_reason:p,value:d,used_gas:m}=u.value;if(console.log(m),p.type==="Succeed")return(0,qe.decodeFunctionResult)({abi:e,functionName:n,data:d.asHex()});throw console.log(n,p.type,p.value.type),new Error("Contract read error")})};var dn=require("viem"),Ir=["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"],Ii=()=>(0,dn.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:Ir}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var ut=require("viem");var ee=class{client;chain;constructor(t){this.client=t,this.chain=Ii()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,ut.createPublicClient)({chain:this.chain,transport:(0,ut.http)()})}getWsProvider(){return(0,ut.createPublicClient)({transport:(0,ut.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,ut.createWalletClient)({account:t,chain:this.chain,transport:(0,ut.custom)(window.ethereum)})}getRPCAdapter(){return new te(this.client)}};var Ei={};B(Ei,{LiquidityMiningApi:()=>se,LiquidityMiningClient:()=>ae});var An=require("polkadot-api"),V=yt(require("big.js")),vt=require("@galacticcouncil/common"),Fi=require("@galacticcouncil/math-liquidity-mining");var ie={};B(ie,{withTimeout:()=>_r});function _r(c,t,e="timeout"){return new Promise((i,n)=>{let r=setTimeout(()=>n(new Error(e)),t);c.then(s=>{clearTimeout(r),i(s)},s=>{clearTimeout(r),n(s)})})}var q={};B(q,{getFraction:()=>Or,mulScaled:()=>hn,mulSpot:()=>Ar});var gn=require("@galacticcouncil/common");function hn(c,t,e,i,n){let r=e+i-n,s=c*t;return r>0?s/BigInt(10)**BigInt(r):r<0?s*BigInt(10)**BigInt(-r):s}function Ar(c,t,e,i){return hn(c,t,e,gn.RUNTIME_DECIMALS,i)}function Or(c,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let i=BigInt(10)**BigInt(e),n=BigInt(Math.round(t*Number(i)));return c*n/(BigInt(100)*i)}var I={};B(I,{FeeUtils:()=>Ai,shiftNeg:()=>Br});var bn=yt(require("big.js"));var Ai=class c{static toPct(t){let[e,i]=t;return c.safeDivide(e*100,i)}static toRaw(t){let[e,i]=t;return c.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 n=10**i;return Math.round(t*n/e)/n}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Br(c,t){let e=(0,bn.default)(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var kt={};B(kt,{findNestedKey:()=>Rr,findNestedObj:()=>Cr,jsonFormatter:()=>Fr});var Rr=(c,t)=>{let e=[];return JSON.stringify(c,(i,n)=>(n&&n[t]&&e.push(n),n)),e[0]},Cr=(c,t,e)=>{let i;return JSON.stringify(c,(n,r)=>(r&&r[t]===e&&(i=r),r)),i},Fr=(c,t)=>typeof t=="bigint"?t.toString():t;var U={};B(U,{calculateBuyFee:()=>Dr,calculateDiffToAvg:()=>Er,calculateDiffToRef:()=>kr,calculateSellFee:()=>Mr});var pt=yt(require("big.js"));function Er(c,t){let e=(0,pt.default)(c.toString()),i=(0,pt.default)(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function kr(c,t){if(t===0n)return 0;let e=(0,pt.default)(c.toString()),i=(0,pt.default)(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function Mr(c,t){if(c===0n)return 0;let e=(0,pt.default)(c.toString()),i=(0,pt.default)(t.toString());return(0,pt.default)(1).minus(i.div(e)).mul(100).round(2).toNumber()}function Dr(c,t){if(c===0n)return 0;let e=(0,pt.default)(c.toString());return(0,pt.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var ne=(c,t)=>c===t?0:c==null?t==null?0:-1:t==null?c==null?0:1:typeof c.compare=="function"?c.compare(t):typeof t.compare=="function"?-t.compare(c):c<t?-1:c>t?1:0;var Ne=(c,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(c(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var Lr=Ne(()=>"illegal argument(s)"),yn=c=>{throw new Lr(c)};var qr=Ne(()=>"index out of bounds"),Oi=c=>{throw new qr(c)},He=(c,t,e)=>(c<t||c>=e)&&Oi(c);var fn=23283064365386963e-26,Ge=class{float(t=1){return this.int()*fn*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*fn-.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 Ue=class extends Ge{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 Pn=new Ue(Math.random);var vn=c=>c!=null&&typeof c!="function"&&c.length!==void 0;var Sn=Object.getPrototypeOf({}),Ve="function",wn="string",Mt=(c,t)=>{let e;if(c===t)return!0;if(c!=null){if(typeof c.equiv===Ve)return c.equiv(t)}else return c==t;if(t!=null){if(typeof t.equiv===Ve)return t.equiv(c)}else return c==t;return typeof c===wn||typeof t===wn?!1:(e=Object.getPrototypeOf(c),(e==null||e===Sn)&&(e=Object.getPrototypeOf(t),e==null||e===Sn)?Ur(c,t):typeof c!==Ve&&c.length!==void 0&&typeof t!==Ve&&t.length!==void 0?Nr(c,t):c instanceof Set&&t instanceof Set?Hr(c,t):c instanceof Map&&t instanceof Map?Gr(c,t):c instanceof Date&&t instanceof Date?c.getTime()===t.getTime():c instanceof RegExp&&t instanceof RegExp?c.toString()===t.toString():c!==c&&t!==t)},Nr=(c,t,e=Mt)=>{let i=c.length;if(i===t.length)for(;i-- >0&&e(c[i],t[i]););return i<0},Hr=(c,t,e=Mt)=>c.size===t.size&&e([...c.keys()].sort(),[...t.keys()].sort()),Gr=(c,t,e=Mt)=>c.size===t.size&&e([...c].sort(),[...t].sort()),Ur=(c,t,e=Mt)=>{if(Object.keys(c).length!==Object.keys(t).length)return!1;for(let i in c)if(!t.hasOwnProperty(i)||!e(c[i],t[i]))return!1;return!0};var Bi=class{value;constructor(t){this.value=t}deref(){return this.value}};var Tn=c=>c instanceof Bi;var We=class c{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return xn("next",this._head)}reverseIterator(){return xn("prev",this.tail)}clear(){this.release()}compare(t,e=ne){let i=this._length;if(i<t._length)return-1;if(i>t._length)return 1;if(i===0)return 0;{let n=this._head,r=t._head,s=0;for(;i-- >0&&s===0;)s=e(n.value,r.value),n=n.next,r=r.next;return s}}concat(...t){let e=this.copy();for(let i of t)e.into(i);return e}equiv(t){if(!(t instanceof c||vn(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),i=this._head;for(let n=this._length;n-- >0;){if(!Mt(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||ne;for(let i=this._head,n=this._length;n-- >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 n=this._length;n-- >0&&!Tn(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 n=t.value;t.value=e.value,e.value=n,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&&Oi(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 n=e;do{if(!t(n))break;n=n.next}while(n!==i);return n}_map(t,e){return this.traverse(i=>(t.append(e(i.value)),!0)),t}};function*xn(c,t){for(;t;)yield t.value,t=t[c]}var Ye=class c extends We{_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 c(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 c}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):(He(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):(He(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new c,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),n=this.nthCell(e-1),r=s=>({first(){return s.value},next(){return s!==n&&s.next?r(s.next):void 0}});return i?r(i):void 0}shuffle(t,e=Pn){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 n=i.next;e.probability(.5)?this.asHead(i):this.asTail(i),i=n}}return this}slice(t=0,e=this.length){let i=t<0?t+this._length:t,n=e<0?e+this._length:e;(i<0||n<0)&&yn("invalid indices: ${from} / ${to}");let r=new c,s=this.nthCell(i);for(;s&&++i<=n;)r.push(s.value),s=s.next;return r}sort(t=ne){if(!this._length)return this;let e=1;for(;;){let i=this._head;this._head=void 0,this._tail=void 0;let n=0;for(;i;){n++;let r=i,s=0;for(let o=0;o<e&&(s++,r=r.next,!!r);o++);let a=e;for(;s>0||a>0&&r;){let o;s===0?(o=r,r=r.next,a--):!r||a===0||t(i.value,r.value)<=0?(o=i,i=i.next,s--):(o=r,r=r.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}i=r}if(this._tail.next=void 0,n<=1)return this;e*=2}}splice(t,e=0,i){let n;typeof t=="number"?(t<0&&(t+=this._length),He(t,0,this._length),n=this.nthCellUnsafe(t)):n=t;let r=new c;if(e>0)for(;n&&e-- >0;)this.remove(n),r.push(n.value),n=n.next;else n&&(n=n.next);if(i)if(n)for(let s of i)this.insertBefore(n,s);else for(let s of i)this.push(s);return r}};var ze=class c{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 Ye,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 c(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),n=this.map.get(t),r=Math.max(0,i-(n?n.value.s:0));return this._size+=r,this.ensureSize()?this.doSetEntry(n,t,e,i):this._size-=r,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 n=this.items.drop();if(!n)return!1;this.map.delete(n.k),t?.(n.k,n.v),this._size-=n.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,n){t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=n,this.items.asTail(t)):(this.items.push({k:e,v:i,s:n}),this.map.set(e,this.items.tail))}};var _t=class c extends ze{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new c(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 n=this.opts.ksize(t)+this.opts.vsize(e),r=this.map.get(t),s=Math.max(0,n-(r?r.value.s:0));return this._size+=s,this.ensureSize()?this.doSetEntry(r,t,e,n,i):this._size-=s,e}async getSet(t,e,i=this.opts.ttl){let n=this.get(t);return n!==void 0?n: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(),n=this.items.head;for(;n&&(this._size>e||this.length>=t);)n.value.t<i&&this.removeEntry(n),n=n.next;return super.ensureSize()}doSetEntry(t,e,i,n,r=this.opts.ttl){let s=Date.now()+r;t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=n,t.value.t=s,this.items.asTail(t)):(this.items.push({k:e,v:i,s:n,t:s,ttl:r}),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 re=class{debug;constructor(t){this.debug=t||!1}log(t,e,i){this.debug&&console.log(t,e,i)}scope(t,e,i,n){let r=new Map,s=n!==void 0?new _t(null,{ttl:n}):new _t;return{get:(...u)=>{let p=i(...u);if(r.has(p)){this.log("[live]",t,p);let m=r.get(p);return Promise.resolve(m)}if(s.has(p))return this.log("[memo]",t,p),s.get(p);this.log("[fetch]",t,p);let d=e(...u).catch(m=>{throw s.delete(p),m});return s.set(p,d),d},set:(u,...p)=>{let d=i(...p);this.log("[set-live]",t,d),r.set(d,u)},clear:()=>{this.log("[clear]",t),r.clear(),s.release()}}}};var $e=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let i=0;i<t.length;++i){let[n,r]=t[i];this.result.set(this.getKey(r,n),e[i].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,i,n){let r=this.getKey(t,e),s=this.getKey(t,i),a=this.result.get(r)??0n,o=this.result.get(s)??0n;if(a<n)throw new Error("Attempting to transfer more than is present");this.result.set(r,a+n),this.result.set(s,o+n)}};var Pt=yt(require("big.js")),rt=require("@galacticcouncil/math-liquidity-mining");var Ri=yt(require("big.js")),Ci=(0,Ri.default)(10).pow(18),In=BigInt((0,Ri.default)(1).pow(18).toString()),_n=6e3;var Vr="1000000000000000000",Xe=class{constructor(t,e,i){this.getAccount=t;this.getAsset=e;this.multiCurrency=i}async syncGlobalFarm(t,e,i){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),r=e-t.updated_at,s=this.getAccount(t.id),a=n?.existential_deposit;if(!a)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,s),l=(0,Pt.default)(a.toString()),u=(0,Pt.default)(o.toString()).minus(l.lt(o.toString())?a.toString():o.toString()),p=(0,Pt.default)((0,rt.calculate_global_farm_rewards)(t.total_shares_z.toString(),i.toString(),(0,Pt.default)(t.yield_per_period.toString()).mul(Ci).round(0,Pt.default.roundDown).toFixed(),t.max_reward_per_period.toString(),r.toFixed()));if(u.lt(p)&&(p=u),p.eq(0))return t;let d=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,s,d,BigInt(p.toFixed())),{...t,accumulated_rpz:BigInt((0,rt.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),p.toFixed()))}}syncYieldFarm(t,e,i){if(t.state.type!=="Active"||t.updated_at===i)return null;if(t.total_valued_shares===0n)return{...t,updated_at:i};let n=(0,rt.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(n),updated_at:i}}getLoyaltyMultiplier(t,e){let i=(0,Pt.default)(1).mul(Ci).round(0,Pt.default.roundDown).toString();if(!e)return i;let{initial_reward_percentage:n,scale_coef:r}=e;return(0,rt.calculate_loyalty_multiplier)(t.toFixed(),n.toString(),r.toFixed())}async claimRewards(t,e,i,n,r){if(e.state.type==="Terminated")return null;let s=Math.floor(n/t.blocks_per_period);if(i.updated_at===s)return null;let a=await this.syncGlobalFarm(t,s,r);if(!a)return null;let o=this.syncYieldFarm(e,a,s);if(!o)return null;let l=o.total_stopped-i.stopped_at_creation,u=o.updated_at-i.entered_at-l,p=this.getLoyaltyMultiplier(u,o.loyalty_curve),d=BigInt((0,rt.calculate_user_reward)(i.accumulated_rpvs.toString(),i.valued_shares.toString(),i.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),m=BigInt((0,rt.calculate_user_reward)(i.accumulated_rpvs.toString(),i.valued_shares.toString(),i.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),Vr));return{reward:d,maxReward:m,assetId:a.reward_currency,yieldFarmId:o.id,isActiveFarm:o.state.type==="Active"}}};var Wr=(0,V.default)(365.2425).times(24).times(60).times(60),se=class{client;balanceClient;options;constructor(t,e,i={}){this.client=t,this.balanceClient=e,this.options=Object.freeze({blockTime:i.blockTime??_n})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let i=[t,e].sort((r,s)=>r-s);if(t===e)return In;let n=await this.client.getOraclePrice(i);if(n){let{n:r,d:s}=n[0].price,a;return t<e?a=(0,Fi.fixed_from_rational)(r.toString(),s.toString()):a=(0,Fi.fixed_from_rational)(s.toString(),r.toString()),BigInt(a)}}getFarmAddress=(t,e)=>{let i=Buffer.from("modl","utf-8"),n=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),r=Buffer.from([t]),s=Buffer.concat([i,n,r]),o="0x"+Buffer.concat([s,Buffer.alloc(32-s.length)]).toString("hex");return(0,An.AccountId)(vt.HYDRATION_SS58_PREFIX).dec(o)};getGlobalRewardPerPeriod(t,e,i,n){let r=(0,V.default)(n).times(t.toString()).times(e.toString()).div(Math.pow(10,vt.RUNTIME_DECIMALS));return r.gte(i.toString())?i.toString():r.toString()}getPoolYieldPerPeriod(t,e,i,n){let r=(0,V.default)(t.toString()).times(e),s=(0,V.default)(i.toString()).times(n);return r.div(s.toString()).toString()}farmData(t,e,i){let{yieldFarm:n,globalFarm:r,priceAdjustment:s,balance:a,id:o}=t,{multiplier:l,loyalty_curve:u}=n,{blocks_per_period:p,yield_per_period:d,total_shares_z:m,max_reward_per_period:h,pending_rewards:b,accumulated_paid_rewards:g,planned_yielding_periods:f,updated_at:y,incentivized_asset:S,reward_currency:v,price_adjustment:T,min_deposit:A}=r,D=I.shiftNeg(s??T,vt.RUNTIME_DECIMALS),G=I.shiftNeg(l,vt.RUNTIME_DECIMALS),lt=I.shiftNeg(u?.initial_reward_percentage??0,vt.RUNTIME_DECIMALS),gt=Wr.div((0,V.default)(this.blockTime).div(1e3).times(p)).toString(),j;if(m<=0)j=(0,V.default)(G).times(d.toString()).times(gt).toString();else{let cr=this.getGlobalRewardPerPeriod(m,d,h,D),ur=this.getPoolYieldPerPeriod(cr,G,m,D);j=(0,V.default)(ur).times(gt).toString()}let tt=b+g,Xt=h*BigInt(f),Ae=a.transferable+tt,tn=Ae-tt,Oe=(0,V.default)(tn.toString()).div(h.toString()),Be=(0,V.default)(e).div(p.toString()).toString(),Re=(m>=0?Oe.plus(y):Oe.plus(Be)).toString(),mi=(0,V.default)(Re).times(p).toString(),or=(0,V.default)(m.toString()).div((0,V.default)(h.toString()).div(d.toString())).div(Math.pow(10,vt.RUNTIME_DECIMALS)).times(100).times(D).toFixed(2),en=(0,V.default)(tt.toString()).div(Ae.toString()).gte(.999);j=en?"0":(0,V.default)(j).div(i?2:1).times(100).toString();let lr=lt?(0,V.default)(j).times(lt).toString():void 0;return{apr:j,minApr:lr,isDistributed:en,estimatedEndPeriod:Re,estimatedEndBlock:mi,maxRewards:Xt,incentivizedAsset:S,rewardCurrency:v,loyaltyCurve:u,currentPeriod:Be,potMaxRewards:Ae,fullness:or,yieldFarmId:n.id,globalFarmId:r.id,poolId:o,distributedRewards:tt,plannedYieldingPeriods:f,minDeposit:A,blocksPerPeriod:p}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((n,r)=>n.includes(r.keyArgs[0].toString())?n:[...n,r.keyArgs[0].toString()],[]),i=await Promise.all(e.map(async n=>{let r=await this.getOmnipoolFarms(n);if(r)return[n,r]}));return Object.fromEntries(i.filter(n=>!!n))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),i=await this.client.getRelayBlockNumber(),n=await Promise.all(e.map(async({keyArgs:r,value:s})=>{let[,a]=r,o=s,l=await this.client.getOmnipoolGlobalFarm(a),u=await this.client.getOmnipoolYieldFarm(Number(t),a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a),h=await this.getOraclePrice(p,d),b=await this.balanceClient.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:h,balance:b}}));return i?n.map(r=>r?this.farmData(r,i):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((n,r)=>n.includes(r.keyArgs[0].toString())?n:[...n,r.keyArgs[0].toString()],[]),i=await Promise.all(e.map(async n=>{let r=await this.getIsolatedFarms(n);if(r)return[n,r]}));return Object.fromEntries(i.filter(n=>!!n))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),i=await this.client.getRelayBlockNumber(),n=await Promise.all(e.map(async({keyArgs:r,value:s})=>{let[,a]=r,o=s,l=await this.client.getIsolatedGlobalFarm(a),u=await this.client.getIsolatedYieldFarm(t,a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a,!0),h=await this.getOraclePrice(p,d),b=await this.balanceClient.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:h,balance:b,farmAddress:m}}));return i?n.map(r=>r?this.farmData(r,i,!0):void 0):[]}async getDepositReward(t,e,i,n){let r=e.global_farm_id,s=e.yield_farm_id,a=i?await this.client.getIsolatedYieldFarm(t,r,s):await this.client.getOmnipoolYieldFarm(Number(t),r,s),o=i?await this.client.getIsolatedGlobalFarm(r):await this.client.getOmnipoolGlobalFarm(r);if(!o||!a)return;let l=o.reward_currency,u=o.incentivized_asset,p=[[this.getFarmAddress(0,i),o.reward_currency],[this.getFarmAddress(o.id,i),o.reward_currency]],d=await this.getAccountAssetBalances(p),m=await this.getOraclePrice(l,u),h=new $e(p,d),g=await new Xe(y=>this.getFarmAddress(y),y=>this.client.getAsset(y),h).claimRewards(o,a,e,n,m??o.price_adjustment);if(!g)return;let f=await this.client.getAsset(g.assetId);if(f&&!(g.reward<=f.existential_deposit))return g}async getAccountAssetBalances(t){let[e,i]=await Promise.all([Promise.all(t.filter(([r,s])=>s!==0).map(([r,s])=>this.balanceClient.getTokenBalance(r,s))),Promise.all(t.filter(([r,s])=>s===0).map(([r])=>this.balanceClient.getSystemBalance(r)))]),n=[];for(let r=0,s=0;r+s<t.length;){let a=r+s,[,o]=t[a];o===0?(n.push(i[s]),s+=1):(n.push(e[r]),r+=1)}return n}};var Ke=require("polkadot-api"),ae=class extends H{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(Ke.Binary.fromText("omnipool"),t,(0,Ke.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)}async getOmnipoolYieldFarm(t,e,i){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,i)}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)}async getIsolatedYieldFarm(t,e,i){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,i)}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};var Ui={};B(Ui,{PoolContextProvider:()=>Ut,PoolError:()=>St,PoolFactory:()=>Gt,PoolType:()=>F,aave:()=>qi,hsm:()=>Gi,lbp:()=>ki,omni:()=>Mi,stable:()=>Di,xyk:()=>Li});var ki={};B(ki,{LbpMath:()=>st,LbpPool:()=>oe,LbpPoolClient:()=>le});var mt=require("@galacticcouncil/math-lbp"),st=class{static getSpotPrice(t,e,i,n,r){return(0,mt.get_spot_price)(t,e,i,n,r)}static calculateInGivenOut(t,e,i,n,r){return(0,mt.calculate_in_given_out)(t,e,i,n,r)}static calculateOutGivenIn(t,e,i,n,r){return(0,mt.calculate_out_given_in)(t,e,i,n,r)}static calculateLinearWeights(t,e,i,n,r){return(0,mt.calculate_linear_weights)(t,e,i,n,r)}static calculatePoolTradeFee(t,e,i){return(0,mt.calculate_pool_trade_fee)(t,e,i)}};var Dt=require("@galacticcouncil/common");var F=(s=>(s.Aave="Aave",s.LBP="LBP",s.Omni="Omnipool",s.Stable="Stableswap",s.XYK="XYK",s.HSM="HSM",s))(F||{}),St=(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))(St||{});var{FeeUtils:On}=I,oe=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(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(s=>[s.id,s])),n=i.get(t),r=i.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:n.balance,balanceOut:r.balance,decimalsIn:n.decimals,decimalsOut:r.decimals,weightIn:n.weight,weightOut:r.weight}}validateAndBuy(t,e,i){let n=this.tokens[0].id,r=[];e<this.minTradingLimit&&r.push("InsufficientTradingAmount");let s=t.balanceOut/this.maxOutRatio;if(e>s&&r.push("MaxOutRatioExceeded"),n===t.assetOut){let a=this.calculateTradeFee(e,i),o=On.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return u>p&&r.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:r}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&r.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:r}}}validateAndSell(t,e,i){let n=this.tokens[0].id,r=[];e<this.minTradingLimit&&r.push("InsufficientTradingAmount");let s=t.balanceIn/this.maxInRatio;if(e>s&&r.push("MaxInRatioExceeded"),n===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:r}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,i),l=On.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),u=a-o,p=t.balanceOut/this.maxOutRatio;return u>p&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:r}}}calculateInGivenOut(t,e){let i=st.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),n=BigInt(i);return n<0n?0n:n}calculateOutGivenIn(t,e){let i=st.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),n=BigInt(i);return n<0n?0n:n}spotPriceInGivenOut(t){let e=st.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),Dt.big.toBigInt(1,Dt.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=st.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),Dt.big.toBigInt(1,Dt.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let i=st.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var Fn=require("polkadot-api"),Lt=require("rxjs");var Bn=(c,t=new Map)=>e=>{let i;return t.has(e)?t.get(e):(t.set(e,i=c(e)),i)};var R=require("rxjs"),P=require("rxjs/operators");var Rn=require("rxjs"),je=class{store$=new Rn.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((a,o)=>[a.address,o])),n=await t(e),r=e.slice(),s=new Set;for(let a of n){let o=i.get(a.address);o===void 0?(i.set(a.address,r.length),r.push(a)):r[o]=a,s.add(a.address)}this.changeset=s,this.store$.next(r)}).catch(console.error)}destroy(){this.store$.complete()}};var Cn=require("@galacticcouncil/common");var Yr={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Qe}=Cn.log,Je=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${Yr[this.type]})`,10)}trace(t,...e){Qe.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){Qe.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){Qe.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){Qe.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:zr}=ie,$r=3e3,X=class extends ct{evm;store=new je;log;shared$;resync$=new R.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new _t(null,{ttl:6*1e3});memPools=Bn(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e,this.log=new Je(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,P.startWith)([]),(0,P.bufferCount)(2,1),(0,P.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,P.filter)(t=>t.length>0),(0,P.throttleTime)(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return(0,R.defer)(()=>{let t=new R.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,P.switchMap)(()=>{let e=new R.Subscription;return(0,R.from)(zr(this.getMemPools(),3e4,"getMemPools stalled")).pipe((0,P.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,P.map)(n=>n.filter(r=>this.hasValidAssets(r))),(0,P.tap)(n=>this.store.set(n)),(0,P.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(!0),R.EMPTY))).pipe((0,P.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,P.switchMap)(n=>(0,R.merge)((0,R.of)(n),this.store.asObservable().pipe((0,P.skip)(1)))),(0,P.finalize)(()=>{e.unsubscribe()}))}),(0,P.finalize)(()=>t.unsubscribe()),(0,P.share)({connector:()=>new R.ReplaySubject(1),resetOnRefCountZero:!0}))})}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:i}=e,n=[this.subscribeTokensBalance(i)];if(this.hasSystemAsset(e)){let r=this.subscribeSystemBalance(i);n.push(r)}if(this.hasErc20Asset(e)){let r=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),s=this.subscribeErc20Balance(i,r);n.push(s)}return(0,R.combineLatest)(n).pipe((0,P.map)(r=>r.flat()),(0,P.pairwise)(),(0,P.map)(([r,s])=>this.getDeltas(r,s)),(0,P.filter)(r=>r.length>0),(0,P.map)(r=>[i,r]))});return(0,R.merge)(...t).pipe((0,P.bufferTime)(250),(0,P.filter)(e=>e.length>0),(0,P.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})=>i>0n&&!!e)}updateBalances=(t,e)=>{let i=[],n=new Map(t.map(r=>[r.address,r]));for(let[r,s]of e){let a=n.get(r);if(a){let o=a.tokens.map(l=>{let u=s.find(p=>p.id===l.id);return u&&l.id!==a.id?{...l,balance:u.balance.transferable}:l});i.push({...a,tokens:o})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<$r||(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,P.pairwise)(),(0,P.filter)(([r,s])=>r==="offline"&&s==="online"),(0,P.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,P.catchError)(r=>(this.log.error("watchdog_recovery_error",r),R.EMPTY)),(0,P.repeat)({delay:1e3})),n=this.watcher.finalizedBlock$.pipe((0,P.pairwise)(),(0,P.tap)(([r,s])=>{let a=Number(r.number),o=Number(s.number),l=o-a;l>=3&&(this.log.debug("watchdog_gap",{from:a,to:o,gap:l}),this.requestResync())}),(0,P.catchError)(r=>(this.log.error("watchdog_gap_error",r),R.EMPTY)),(0,P.repeat)({delay:1e3}));return(0,R.merge)(i,n).subscribe()}watchGuard(t){return e=>e.pipe((0,P.tap)({error:i=>{this.log.error(t,i),this.requestResync(!0)}}),(0,P.finalize)(()=>{this.log.debug(t,"unsub")}),(0,P.catchError)(()=>R.EMPTY))}};var le=class extends X{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:n,initial_weight:r,final_weight:s}=t,a=st.calculateLinearWeights(i?i.toString():"0",n?n.toString():"0",r.toString(),s.toString(),e.toString()),o=BigInt(a),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Fn.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()]),n=e?.relay_parent_number||0,r=t.filter(({value:s})=>e&&this.isActivePool(s,n)).map(async({keyArgs:s,value:a})=>{let[o]=s,l=o.toString(),u=await this.getPoolDelta(l,a,n);return{address:l,type:"LBP",fee:a.fee,...u,...i}});return Promise.all(r)}async getPoolDelta(t,e,i){let{assets:n,repay_target:r,fee_collector:s}=e,[a,o]=this.getPoolWeights(e,i),[l,u]=n,[p,d,m,h,b]=await Promise.all([this.isRepayFeeApplied(l,r,s.toString()),this.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l),this.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u)]);return{repayFeeApply:p,tokens:[{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,weight:a,type:m?.asset_type.type},{id:u,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:h.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(t,e){let{start:i,end:n}=t;return i&&n?e>=i&&e<n:!1}async isRepayFeeApplied(t,e,i){if(e===0n)return!1;try{return(await this.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(r=>r.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 n of e){let r=this.poolsData.get(n.address);if(r){let{assets:s,repay_target:a,fee_collector:o}=r,[l]=s,[u,p]=this.getPoolWeights(r,t),[d,m]=n.tokens,h=[{...d,weight:u},{...m,weight:p}],b=await this.isRepayFeeApplied(l,a,o.toString());i.push({...n,tokens:h,repayFeeApply:b})}}return i})})}subscribeUpdates(){let t=new Lt.Subscription;return t.add(this.subscribeValidationData()),t}};var Mi={};B(Mi,{OmniMath:()=>O,OmniPool:()=>ce,OmniPoolClient:()=>ue});var w=require("@galacticcouncil/math-omnipool"),At=yt(require("big.js")),O=class{static calculateSpotPrice(t,e,i,n){return(0,w.calculate_spot_price)(t,e,i,n)}static calculateLrnaSpotPrice(t,e){return(0,w.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,i,n,r,s,a,o,l){return(0,w.calculate_in_given_out)(t,e,i,n,r,s,a,o,l)}static calculateLrnaInGivenOut(t,e,i,n,r){return(0,w.calculate_lrna_in_given_out)(t,e,i,n,r)}static calculateOutGivenIn(t,e,i,n,r,s,a,o,l){return(0,w.calculate_out_given_in)(t,e,i,n,r,s,a,o,l)}static calculateOutGivenLrnaIn(t,e,i,n,r){return(0,w.calculate_out_given_lrna_in)(t,e,i,n,r)}static calculateShares(t,e,i,n){return(0,w.calculate_shares)(t,e,i,n)}static calculateLiquidityOut(t,e,i,n,r,s,a,o){return(0,w.calculate_liquidity_out)(t,e,i,n,r,s,a,o)}static calculateLiquidityLRNAOut(t,e,i,n,r,s,a,o){return(0,w.calculate_liquidity_lrna_out)(t,e,i,n,r,s,a,o)}static calculateCapDifference(t,e,i,n){let r=(0,At.default)(e),s=(0,At.default)(t),a=(0,At.default)(n),o=(0,At.default)(i),l=(0,At.default)(10).pow(18),u=o.div(l);if(r.div(a).lt(u)){let d=u.times(a).minus(r).times(s),m=r.times((0,At.default)(1).minus(u));return d.div(m).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,n){return(0,w.calculate_liquidity_hub_in)(t,e,i,n)}static isSellAllowed(t){return(0,w.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,w.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,w.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,w.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,i,n,r,s,a,o,l,u,p){return(0,w.recalculate_asset_fee)(t,e,i,n,r,s,a,o,l,u,p)}static recalculateProtocolFee(t,e,i,n,r,s,a,o,l,u,p){return(0,w.recalculate_protocol_fee)(t,e,i,n,r,s,a,o,l,u,p)}static verifyAssetCap(t,e,i,n){return(0,w.verify_asset_cap)(t,e,i,n)}};var En=require("@galacticcouncil/common");var{FeeUtils:qt}=I,ce=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(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(s=>[s.id,s])),n=i.get(t),r=i.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:n.hubReserves,hubReservesOut:r.hubReserves,sharesIn:n.shares,sharesOut:r.shares,decimalsIn:n.decimals,decimalsOut:r.decimals,balanceIn:n.balance,balanceOut:r.balance,tradeableIn:n.tradeable,tradeableOut:r.tradeable,assetInEd:n.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,i){let n=this.calculateInGivenOut(t,e),r=this.calculateInGivenOut(t,e,i),s=n===0n?0:U.calculateDiffToRef(r,n),a=[],o=O.isSellAllowed(t.tradeableIn),l=O.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return r>p&&a.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:n,amountOut:e,feePct:s,errors:a}}validateAndSell(t,e,i){let n=this.calculateOutGivenIn(t,e),r=this.calculateOutGivenIn(t,e,i),s=U.calculateDiffToRef(n,r),a=[],o=O.isSellAllowed(t.tradeableIn),l=O.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return r>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:n,amountOut:r,feePct:s,errors:a}}calculateInGivenOut(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,i);let n=O.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?qt.toRaw(i.assetFee).toString():"0",i?qt.toRaw(i.protocolFee).toString():"0"),r=BigInt(n);return r<0n?0n:r}calculateLrnaInGivenOut(t,e,i){let n=O.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?qt.toRaw(i.assetFee).toString():"0"),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,i);let n=O.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?qt.toRaw(i.assetFee).toString():"0",i?qt.toRaw(i.protocolFee).toString():"0"),r=BigInt(n);return r<0n?0n:r}calculateOutGivenLrnaIn(t,e,i){let n=O.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?qt.toRaw(i.assetFee).toString():"0"),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=O.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=O.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=O.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=O.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,i){let n=e-i;if(n===0)return t;let r=En.big.pow10(Math.abs(n));return n>0?t*r:t/r}};var wt=require("polkadot-api"),Dn=require("@polkadot-api/utils"),_=require("rxjs"),Ln=require("@galacticcouncil/common");var{FeeUtils:N}=I,kn=wt.Binary.fromText("omnipool"),Mn=(0,wt.Enum)("Short"),ue=class extends X{queryBus=new re;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);emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(kn,t,Mn,{at:"best"}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,Dn.toHex)(e);return(0,wt.AccountId)(Ln.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(wt.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,n,r,s,a]=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.getBalance(e,t),this.getPoolLimits()]),o=i.map(async({keyArgs:u,value:p})=>{let[d]=u,{hub_reserve:m,shares:h,tradable:b,cap:g,protocol_shares:f}=p,[y,S]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(e,d)]);return{id:d,decimals:y?.decimals,existentialDeposit:y?.existential_deposit,balance:S.transferable,cap:g,hubReserves:m,protocolShares:f,shares:h,tradeable:b,type:y?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:s.transferable,tradeable:n,type:r?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...a}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,n=await this.dynamicFeesConfig.get(e);if(n?.type==="Fixed"){let{asset_fee:y,protocol_fee:S}=n.value;return{assetFee:N.fromPermill(y),protocolFee:N.fromPermill(S)}}let r=this.getOraclePair(e),s=this.getOraclePair(i),[a,o,l]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(r),this.emaOracles.get(s)]),[u,p,d]=await this.getAssetFee(t,this.block,a,o,n?.value.asset_fee_params),[m,h,b]=i===1?[0,0,0]:await this.getProtocolFee(t,this.block,a,l,n?.value.protocol_fee_params),g=u+m,f=d+b;return{assetFee:N.fromPermill(p),protocolFee:N.fromPermill(h),min:N.fromPermill(g),max:N.fromPermill(f)}}async getAssetFee(t,e,i,n,r){let{assetOut:s,balanceOut:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=r||await this.api.constants.DynamicFees.AssetFeeParameters();if(!i||!n)return[o,o,l];let d=N.fromPermill(o),m=N.fromPermill(l),[h]=n,{asset_fee:b,timestamp:g}=i,f=Math.max(1,e-g),y=h.volume.b_in.toString(),S=h.volume.b_out.toString(),v=h.liquidity.b.toString();s===0&&(y=h.volume.a_in.toString(),S=h.volume.a_out.toString(),v=h.liquidity.a.toString());let T=N.fromPermill(b),A=O.recalculateAssetFee(y,S,v,"9",a.toString(),N.toRaw(T).toString(),f.toString(),N.toRaw(d).toString(),N.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(A)*1e6,l]}async getProtocolFee(t,e,i,n,r){let{assetIn:s,balanceIn:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=r||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!i||!n)return[o,o,l];let d=N.fromPermill(o),m=N.fromPermill(l),[h]=n,{protocol_fee:b,timestamp:g}=i,f=Math.max(1,e-g),y=h.volume.b_in.toString(),S=h.volume.b_out.toString(),v=h.liquidity.b.toString();s===0&&(y=h.volume.a_in.toString(),S=h.volume.a_out.toString(),v=h.liquidity.a.toString());let T=N.fromPermill(b),A=O.recalculateProtocolFee(y,S,v,"9",a.toString(),N.toRaw(T).toString(),f.toString(),N.toRaw(d).toString(),N.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(A)*1e6,l]}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(n=>n.id).map(n=>this.getOraclePair(n)).map(n=>this.api.query.EmaOracle.Oracles.watchValue(kn,n,Mn,"best").pipe((0,_.filter)(r=>r!==void 0),(0,_.map)((r,s)=>({value:r,index:s})),(0,_.tap)(({index:r})=>{r>0&&this.log.trace("emaOracle.Oracles",n.join(":"))}),(0,_.map)(({value:r})=>({pair:n,value:r}))));return(0,_.merge)(...i).pipe((0,_.finalize)(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(n=>{let{pair:r,value:s}=n;this.emaOracles.set(s,r)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,_.distinctUntilChanged)((t,e)=>!e.deltas),(0,_.map)((t,e)=>({value:t,index:e})),(0,_.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),(0,_.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,_.distinctUntilChanged)((t,e)=>!e.deltas),(0,_.map)((t,e)=>({value:t,index:e})),(0,_.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),(0,_.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,_.distinctUntilChanged)((t,e)=>!e.deltas),(0,_.map)((t,e)=>({value:t,index:e})),(0,_.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((r,s)=>{let[a]=s.args;return r.set(a,s.value),r},new Map),n=e.tokens.map(r=>{let s=i?.get(r.id);return s?this.updateTokenState(r,s):r});return[{...e,tokens:n}]})})}subscribeUpdates(){let t=new _.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:n,tradable:r,cap:s,protocol_shares:a}=e;return{...t,cap:s,hubReserves:i,protocolShares:a,shares:n,tradeable:r}}};var Di={};B(Di,{StableMath:()=>W,StableSwap:()=>Tt,StableSwapClient:()=>me});var k=require("@galacticcouncil/math-stableswap"),W=class{static getPoolAddress(t){return(0,k.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,n,r){return(0,k.calculate_amplification)(t,e,i,n,r)}static calculateInGivenOut(t,e,i,n,r,s,a){return(0,k.calculate_in_given_out)(t,e,i,n,r,s,a)}static calculateAddOneAsset(t,e,i,n,r,s,a){return(0,k.calculate_add_one_asset)(t,e,i,n,r,s,a)}static calculateSharesForAmount(t,e,i,n,r,s,a){return(0,k.calculate_shares_for_amount)(t,e,i,n,r,s,a)}static calculateOutGivenIn(t,e,i,n,r,s,a){return(0,k.calculate_out_given_in)(t,e,i,n,r,s,a)}static calculateLiquidityOutOneAsset(t,e,i,n,r,s,a){return(0,k.calculate_liquidity_out_one_asset)(t,e,i,n,r,s,a)}static calculateShares(t,e,i,n,r,s){return(0,k.calculate_shares)(t,e,i,n,r,s)}static calculateSpotPriceWithFee(t,e,i,n,r,s,a,o){return(0,k.calculate_spot_price_with_fee)(t,e,i,n,r,s,a,o)}static recalculatePegs(t,e,i,n,r,s){let a=(0,k.recalculate_peg)(t,e,i,n,r,s);return JSON.parse(a)}};var pe=require("@galacticcouncil/common");var{FeeUtils:Nt}=I,Tt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new c(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(s=>[s.id,s])),n=i.get(t),r=i.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:n.balance,balanceOut:r.balance,decimalsIn:n.decimals,decimalsOut:r.decimals,tradeableIn:this.id===t?15:n.tradeable,tradeableOut:this.id===e?15:r.tradeable,assetInEd:n.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,i){let n=this.calculateInGivenOut(t,e),r=this.calculateInGivenOut(t,e,i),s=n===0n?0:U.calculateDiffToRef(r,n),a=[],o=O.isSellAllowed(t.tradeableIn),l=O.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:r,calculatedIn:n,amountOut:e,feePct:s,errors:a}}validateAndSell(t,e,i){let n=this.calculateOutGivenIn(t,e),r=this.calculateOutGivenIn(t,e,i),s=U.calculateDiffToRef(n,r),a=[],o=O.isSellAllowed(t.tradeableIn),l=O.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:n,amountOut:r,feePct:s,errors:a}}calculateIn(t,e,i){let n=W.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?Nt.toRaw(i.fee).toString():"0",this.getPegs()),r=BigInt(n);return r<0n?0n:r}calculateAddOneAsset(t,e,i){let n=W.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?Nt.toRaw(i.fee).toString():"0",this.getPegs()),r=BigInt(n);return r<0n?0n:r}calculateSharesForAmount(t,e,i){let n=W.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?Nt.toRaw(i.fee).toString():"0",this.getPegs()),r=BigInt(n);return r<0n?0n:r}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=W.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 n=W.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?Nt.toRaw(i.fee).toString():"0",this.getPegs()),r=BigInt(n);return r<0n?0n:r}calculateWithdrawOneAsset(t,e,i){let n=W.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?Nt.toRaw(i.fee).toString():"0",this.getPegs()),r=BigInt(n);return r<0n?0n:r}calculateShares(t,e,i){let n=W.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?Nt.toRaw(i.fee).toString():"0",this.getPegs()),r=BigInt(n);return r<0n?0n:r}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=W.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:n})=>({asset_id:e,amount:i,decimals:n}));return JSON.stringify(t,kt.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],kt.jsonFormatter)}normalizeSpot(t,e,i,n,r){return e?t*pe.big.pow10(pe.RUNTIME_DECIMALS-r):i?t/pe.big.pow10(r-n):t}};var Ze=require("polkadot-api"),qn=require("@polkadot-api/utils"),Nn=require("@noble/hashes/blake2b"),J=require("rxjs"),ti=require("@galacticcouncil/common");var{FeeUtils:Xr}=I,me=class extends X{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=W.getPoolAddress(t),i=(0,Nn.blake2b)(e,{dkLen:32}),n=(0,qn.toHex)(i);return(0,Ze.AccountId)(ti.HYDRATION_SS58_PREFIX).dec(n)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:i,final_amplification:n,initial_block:r,final_block:s}=t,a=W.calculateAmplification(i.toString(),n.toString(),r.toString(),s.toString(),e.toString()),o=Number(a)<n;return{amplification:BigInt(a),isRampPeriod:o}}async getPoolTokens(t,e){let i=this.getPoolAddress(t),n=e.assets.map(async r=>{let[s,a,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,r),this.api.query.AssetRegistry.Assets.getValue(r),this.getBalance(i,r)]);return{id:r,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:o.transferable,tradeable:s,type:a?.asset_type.type}});return Promise.all(n)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(Ze.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()]),n=t.map(async({keyArgs:r,value:s})=>{let[a]=r,o=this.getPoolAddress(a),[l,u,p]=await Promise.all([this.getPoolTokens(a,s),this.api.query.Stableswap.PoolPegs.getValue(a,{at:"best"}),this.api.query.Tokens.TotalIssuance.getValue(a,{at:"best"})]),d=this.getPoolAmplification(s,e),m=u?this.getRecentPegs(u):this.getDefaultPegs(s);return l.push({id:a,tradeable:15,balance:p,decimals:ti.RUNTIME_DECIMALS}),this.poolsData.set(a,s),{address:o,id:a,type:"Stableswap",fee:Xr.fromPermill(s.fee),tokens:l,totalIssuance:p,pegs:m,...i,...d}});return Promise.all(n)}async getPoolFees(t,e){return{fee:this.store.pools.find(n=>n.address===e).fee}}getDefaultPegs(t){return W.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([i,n])=>n.map(r=>r.toString()))}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,"best").pipe((0,J.map)((n,r)=>({value:n,index:r})),(0,J.tap)(({index:n,value:r})=>{n>0&&this.log.trace("tokens.TotalIssuance",i,r)}),(0,J.map)(({value:n})=>({id:i,value:n}))));return(0,J.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:n,value:r}=i;this.store.update(s=>{let a=[];return s.filter(o=>o.id===n).forEach(o=>{let l=o.tokens.map(u=>u.id===n?{...u,balance:r}:u);a.push({...o,tokens:l,totalIssuance:r})}),a})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,J.distinctUntilChanged)((t,e)=>!e.deltas),(0,J.map)((t,e)=>({value:t,index:e})),(0,J.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=[],n=new Map(e.map(r=>[r.id,r]));return t?.upserted.forEach(({args:r,value:s})=>{let[a]=r,o=n.get(a);if(o){let l=this.getRecentPegs(s);i.push({...o,pegs:l})}}),i})}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(e=>{let i=[];return e.filter(n=>n.isRampPeriod).forEach(n=>{let r=this.poolsData.get(n.id);if(r){let s=this.getPoolAmplification(r,t);i.push({...n,...s})}}),i})})}subscribeUpdates(){let t=new J.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 Li={};B(Li,{XykMath:()=>ht,XykPool:()=>de,XykPoolClient:()=>ge});var M=require("@galacticcouncil/math-xyk"),ht=class{static getSpotPrice(t,e,i){return(0,M.get_spot_price)(t,e,i)}static calculateInGivenOut(t,e,i){return(0,M.calculate_in_given_out)(t,e,i)}static calculateOutGivenIn(t,e,i){return(0,M.calculate_out_given_in)(t,e,i)}static calculatePoolTradeFee(t,e,i){return(0,M.calculate_pool_trade_fee)(t,e,i)}static calculateLiquidityIn(t,e,i){return(0,M.calculate_liquidity_in)(t,e,i)}static calculateSpotPrice(t,e){return(0,M.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,i,n){return(0,M.calculate_spot_price_with_fee)(t,e,i,n)}static calculateShares(t,e,i){return(0,M.calculate_shares)(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,n){return(0,M.calculate_liquidity_out_asset_a)(t,e,i,n)}static calculateLiquidityOutAssetB(t,e,i,n){return(0,M.calculate_liquidity_out_asset_b)(t,e,i,n)}};var Gn=require("@galacticcouncil/common");var{FeeUtils:Hn}=I,de=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(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(s=>[s.id,s])),n=i.get(t),r=i.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:n.decimals,decimalsOut:r.decimals,balanceIn:n.balance,balanceOut:r.balance,assetInEd:n.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,i){let n=this.calculateInGivenOut(t,e),r=this.calculateTradeFee(n,i),s=Hn.toPct(i.exchangeFee),a=n+r,o=[];(e<this.minTradingLimit||n<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:n,amountOut:e,feePct:s,errors:o}}validateAndSell(t,e,i){let n=this.calculateOutGivenIn(t,e),r=this.calculateTradeFee(n,i),s=Hn.toPct(i.exchangeFee),a=n-r,o=[];(e<this.minTradingLimit||n<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:n,amountOut:a,feePct:s,errors:o}}calculateInGivenOut(t,e){let i=ht.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),n=BigInt(i);return n<0n?0n:n}calculateOutGivenIn(t,e){let i=ht.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),n=BigInt(i);return n<0n?0n:n}spotPriceInGivenOut(t){let e=ht.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=ht.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=ht.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(i)}normalizeSpot(t,e,i){let n=e-i;if(n===0)return t;let r=Gn.big.pow10(Math.abs(n));return n>0?t*r:t/r}};var Un=require("polkadot-api"),Vn=require("rxjs");var ge=class extends X{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(Un.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries(),this.getPoolLimits()]),i=t.map(async({keyArgs:n,value:r})=>{let[s]=n,[a,o]=r,[l,u,p,d]=await Promise.all([this.getBalance(s,a),this.api.query.AssetRegistry.Assets.getValue(a),this.getBalance(s,o),this.api.query.AssetRegistry.Assets.getValue(o)]);return{address:s,type:"XYK",tokens:[{id:a,decimals:u?.decimals||this.decimals.get(a),existentialDeposit:u?.existential_deposit,balance:l.transferable,type:u?.asset_type.type},{id:o,decimals:d?.decimals||this.decimals.get(o),existentialDeposit:d?.existential_deposit,balance:p.transferable,type:d?.asset_type.type}],...e}});return Promise.all(i)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return Vn.Subscription.EMPTY}};var qi={};B(qi,{AavePool:()=>he,AavePoolClient:()=>be});var Ht=require("@galacticcouncil/common");var he=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(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(s=>[s.id,s])),n=i.get(t),r=i.get(e);if(n==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:n.balance,balanceOut:r.balance,decimalsIn:n.decimals,decimalsOut:r.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,i){let n=this.calculateInGivenOut(t,e),r=[];return e>t.balanceOut&&r.push("TradeNotAllowed"),{amountIn:n,calculatedIn:n,amountOut:e,feePct:0,errors:r}}validateAndSell(t,e,i){let n=this.calculateOutGivenIn(t,e),r=[];return n>t.balanceOut&&r.push("TradeNotAllowed"),{amountIn:e,calculatedOut:n,amountOut:n,feePct:0,errors:r}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return Ht.big.toBigInt(1,Ht.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return Ht.big.toBigInt(1,Ht.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var Yn=require("polkadot-api"),zn=require("@polkadot-api/utils"),dt=require("rxjs"),$n=require("viem"),ei=require("@galacticcouncil/common");var Wn=[{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:Kr}=ei.erc20,jr=["Supply","Withdraw","Repay","Borrow"],be=class extends X{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,n=new TextEncoder().encode(i.padEnd(32,"\0")),r=(0,zn.toHex)(n);return(0,Yn.AccountId)(ei.HYDRATION_SS58_PREFIX).dec(r)}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:n,liqudity_in:r,liqudity_out:s})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i),this.api.query.AssetRegistry.AssetLocations.getValue(i),this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n)]);return{address:this.getPoolId(i,n),type:"Aave",tokens:[{id:i,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:r,location:o,type:a?.asset_type.type},{id:n,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:s,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:n,liqudity_out:r}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:"best"});return t.tokens.map(s=>{let a=s.id===e.id?n:r;return{...s,balance:a}})}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 Kr.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,n=e.map(s=>s.asHex()),r=i.asHex();try{let{eventName:s,args:a}=(0,$n.decodeEventLog)({abi:Wn,topics:n,data:r}),o=a.reserve.toLowerCase();return{eventName:s,reserve:o,key:`${s}:${o}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(i=>i.tokens).map(([i,n])=>n).map(i=>i.id);return this.api.event.Router.Executed.watch().pipe((0,dt.map)(({payload:i})=>this.parseRouterLog(i)),(0,dt.filter)(({assetIn:i,assetOut:n})=>e.includes(i)||e.includes(n)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:n,key:r})=>{this.log.trace("router.Executed",r),this.store.update(async s=>{let a=[];for(let o of s){let[l,u]=o.tokens;if(u.id===i||u.id===n){let d=await this.getPoolDelta(o);a.push({...o,tokens:d})}}return a})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,dt.map)(({payload:t})=>this.parseEvmLog(t)),(0,dt.filter)(t=>t!==void 0),(0,dt.filter)(({eventName:t})=>jr.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async i=>{let n=[];for(let r of i){let[s]=r.tokens;if(this.getReserveH160Id(s).toLowerCase()===t){let o=await this.getPoolDelta(r);n.push({...r,tokens:o})}}return n})})}subscribeBalances(){return dt.Subscription.EMPTY}subscribeUpdates(){let t=new dt.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var Gt=class{static get(t){switch(t.type){case"Aave":return he.fromPool(t);case"XYK":return de.fromPool(t);case"Omnipool":return ce.fromPool(t);case"LBP":return oe.fromPool(t);case"Stableswap":return Tt.fromPool(t);case"HSM":return Tt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var ot=require("rxjs");var Gi={};B(Gi,{HsmMath:()=>at,HsmPool:()=>Ni,HsmPoolClient:()=>ve});var Y=require("@galacticcouncil/math-hsm"),at=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,Y.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,Y.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,Y.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,Y.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,Y.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,Y.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,Y.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,Y.calculate_max_price)(t,e)}};var bt=require("@galacticcouncil/common");var{FeeUtils:ye}=I,Ni=class c extends Tt{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new c(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,n){let r=this.calculateBuybackLimit(t);e>r&&n.push("MaxBuyBackExceeded");let s=this.calculateBuyPrice(t,e,i),a=this.calculateMaxPrice(t);return s>a&&n.push("MaxBuyPriceExceeded"),i>this.collateralBalance&&n.push("InsufficientCollateral"),n}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 n=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,i,n):this.validateTradeHollarOut(e,i,n)}validateAndBuy(t,e){let i=this.calculateInGivenOut(t,e),n=this.validateTradeConstraints(t,i,e);return{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:n}}validateAndSell(t,e){let i=this.calculateOutGivenIn(t,e),n=this.validateTradeConstraints(t,e,i);return{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:n}}calculateHollarInGivenCollateralOut(t,e){let i=super.calculateInGivenOut(t,e,{fee:this.fee}),n=at.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),ye.toRaw(this.buyBackFee).toString());return BigInt(n)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=at.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),ye.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}),n=at.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),ye.toRaw(this.buyBackFee).toString());return BigInt(n)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=at.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),ye.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=at.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=at.calculateBuybackLimit(e.toString(),ye.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let n=i*10n**BigInt(t.decimalsIn);return e*10n**BigInt(t.decimalsOut)/n}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=at.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[n,r]=JSON.parse(i),s=10n**BigInt(bt.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(n)*s/BigInt(r)}spotPriceInGivenOut(t){let e=bt.big.toBigInt(1,bt.RUNTIME_DECIMALS);return this.calculateInGivenOut(t,e)}spotPriceOutGivenIn(t){let e=bt.big.toBigInt(1,bt.RUNTIME_DECIMALS);return this.calculateOutGivenIn(t,e)}getCollateralPeg(){let t=this.tokens.findIndex(n=>n.id!==this.hollarId),e=this.pegs[t],i=this.tokens[t].decimals;return this.isDefaultPeg(e)?[bt.big.toBigInt(1,18).toString(),bt.big.toBigInt(1,i).toString()]:e}isDefaultPeg(t){let[e,i]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&i==="1"}};var ii=require("polkadot-api"),Kn=require("@polkadot-api/utils"),K=require("rxjs"),jn=require("viem"),ni=require("@galacticcouncil/common");var fe=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var Pe=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,n]=await this.client.readContract({abi:fe,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-n}};var{FeeUtils:Hi}=I,{H160:Xn}=ni.h160,Qr=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],ve=class extends X{ghoClient;stableClient;constructor(t,e,i){super(t,e),this.stableClient=i,this.ghoClient=new Pe(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),n=(0,Kn.toHex)(i);return(0,ii.AccountId)(ni.HYDRATION_SS58_PREFIX).dec(n)}async isSupported(){let t=this.api.query.HSM.Collaterals,e=await this.api.compatibilityToken;return t.isCompatible(ii.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,n]=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 r=this.getFacilitatorAddress(),s=Xn.fromAny(r),a=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(a,s),l=i.map(async({keyArgs:p,value:d})=>{let[m]=p,{pool_id:h,max_buy_price_coefficient:b,max_in_holding:g,purchase_fee:f,buy_back_fee:y,buyback_rate:S}=d,v=n.find(T=>T.id===h);if(v){let T=this.getPoolId(h),A=await this.getBalance(r,m);return{...v,address:T,type:"HSM",tokens:v.tokens.filter(D=>D.id!==h),hsmAddress:r,hsmMintCapacity:o,hollarId:t,hollarH160:a,collateralId:m,collateralBalance:A.transferable,maxBuyPriceCoefficient:b,maxInHolding:g,purchaseFee:Hi.fromPermill(f),buyBackFee:Hi.fromPermill(y),buyBackRate:Hi.fromPerbill(S)}}});return(await Promise.all(l)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:i}=t.log,n=e.map(s=>s.asHex()),r=i.asHex();try{let{eventName:s,args:a}=(0,jn.decodeEventLog)({abi:fe,topics:n,data:r}),o=a.facilitatorAddress.toLowerCase();return{eventName:s,facilitator:o,key:`${s}:${o}`}}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})=>Qr.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async i=>{let n=[],[{hsmAddress:r,hollarH160:s}]=i,a=Xn.fromAny(r);if(a.toLowerCase()===e){let l=await this.ghoClient.getFacilitatorCapacity(s,a);for(let u of i)n.push({...u,hsmMintCapacity:l})}return n})})}subscribeBalances(){let t=[],e=[];this.store.pools.forEach(r=>{let{tokens:s,collateralId:a}=r;s.find(l=>l.id===a).type==="Erc20"?e.push(a):t.push(a)});let[{hsmAddress:i}]=this.store.pools,n=[];if(t.length>0){let r=this.subscribeTokensBalance(i);n.push(r)}if(e.length>0){let r=this.subscribeErc20Balance(i,e);n.push(r)}return n.length>0?(0,K.combineLatest)(n).pipe((0,K.map)(r=>r.flat()),(0,K.pairwise)(),(0,K.map)(([r,s])=>this.getDeltas(r,s)),this.watchGuard("balances")).subscribe(r=>{this.store.update(s=>{let a=[],o=new Map(s.map(l=>[l.collateralId,l]));return r.forEach(({id:l,balance:u})=>{let p=o.get(l);p&&(this.log.trace("balances",{id:l,balance:u}),a.push({...p,collateralBalance:u.transferable}))}),a})}):K.Subscription.EMPTY}subscribeUpdates(){let t=new K.Subscription;return t.add(this.subscribeEvmLog()),t}};var Ut=class extends H{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=ot.Subscription.EMPTY;omniSub=ot.Subscription.EMPTY;stableSub=ot.Subscription.EMPTY;hsmSub=ot.Subscription.EMPTY;xykSub=ot.Subscription.EMPTY;lbpSub=ot.Subscription.EMPTY;isReady=!1;isDestroyed=new ot.Subject;constructor(t,e){super(t),this.evm=e,this.aave=new be(t,e),this.omnipool=new ue(t,e),this.stableswap=new me(t,e),this.hsm=new ve(t,e,this.stableswap),this.xyk=new ge(t,e),this.lbp=new le(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe((0,ot.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.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(n=>n.getPoolType()===e.type);if(i)return i.getPoolFees(t,e.address);throw new Jt(e.type)}};var Ki={};B(Ki,{DEFAULT_BLOCK_TIME:()=>Jn,DEFAULT_MIN_BUDGET:()=>Yi,ORDER_MIN_BLOCK_PERIOD:()=>Zn,Router:()=>Vt,TWAP_BLOCK_PERIOD:()=>xe,TWAP_MAX_DURATION:()=>$i,TWAP_MAX_PRICE_IMPACT:()=>zi,TWAP_TX_MULTIPLIER:()=>Bp,TradeOrderError:()=>Wi,TradeOrderType:()=>si,TradeRouteBuilder:()=>nt,TradeRouter:()=>Wt,TradeScheduler:()=>Yt,TradeType:()=>ri});var Se=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Jr=10,we=class{isNotVisited(t,e){let i=!0;return e.forEach(n=>{(n[0]===t[0]||n[1]===t[1])&&(i=!1)}),i}findPaths(t,e,i){let n=[],r=new Se,s=[];for(s.push([e,""]),r.enqueue(s);r.size()>0;){let a=r.dequeue();if(!a||a.length>Jr)continue;let o=a[a.length-1];(i===null||o[0]===i)&&n.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let p=[...a];p.push(u),r.enqueue(p)}})}return n}findShortestPaths(t,e,i){let n=[],r=new Se,s=[];s.push([e,""]),r.enqueue(s);let a=1/0;for(;r.size()>0;){let o=r.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===i){o.length<a?(a=o.length,n.length=0,n.push(o)):o.length===a&&n.push(o);continue}let u=t.get(l[0]);for(let p of u??[])this.isNotVisited(p,o)&&r.enqueue([...o,p])}return n}buildAndPopulateGraph(t,e){let i=new Map;for(let n of t)i.set(parseInt(n),[]);for(let[n,r,s]of e)i.get(r)?.push([s,n]);return i}};function Vi(c){let t={};for(let e of c){let i=e.tokens.length;for(let n=0;n<i;n++){t[e.tokens[n].id]||(t[e.tokens[n].id]=[]);for(let r=0;r<i;r++){if(n==r)continue;let s=[e.address,e.tokens[n].id,e.tokens[r].id];t[e.tokens[n].id].push(s)}}}return t}var Te=class{getProposals(t,e,i){let n=i.filter(g=>g.type==="XYK"),r=i.filter(g=>g.type!=="XYK"),s=new Set(r.map(g=>g.tokens).flat().map(g=>g.id)),a=s.has(t),o=s.has(e),l=new we,u=g=>{let f=Vi(g),y=Object.keys(f),S=y.flatMap(v=>f[v]);return l.buildAndPopulateGraph(y,S)};if(!a&&!o){let g=n.filter(S=>S.tokens.find(v=>v.id===t)||S.tokens.find(v=>v.id===e)),f=u(g),y=l.findPaths(f,t,e);return this.parsePaths(y)}if(a&&o){let g=u(r),f=l.findPaths(g,t,e);return this.parsePaths(f)}let p=a?e:t,d=n.filter(g=>g.tokens.some(f=>f.id===p));if(d.length===0)return[];let m=[...r,...d],h=u(m),b=l.findPaths(h,t,e);return this.parsePaths(b)}parsePaths(t){let e=[];for(let i of t){let n=[];for(let r=0;r<i.length;r++){let s=i[r],a=i[r+1];if(a==null)break;n.push(this.toEdge(s,a))}e.push(n)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var Vt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new Te,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,i){return`${t}->${e}::${i.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:i=[]}=this.filter,n=new Set(e),r=new Set(i);return t.filter(s=>r.has(s.type)?!1:n.size>0?n.has(s.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let i=await this.getPools();return this.validateInput(t,e,i),this.getPaths(t,e,i)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(n=>n!==t).map(n=>this.getRoutes(n,t)))).filter(n=>n.length>0).map(([n])=>n[0].assetIn).sort()}validateInput(t,e,i){if(i.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let n=this.getAssets(i);if(!n.has(t))throw new Error(t+" is not supported asset");if(!n.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(i)}getAssets(t){let e=t.map(i=>i.tokens.map(n=>n.id)).flat().sort((i,n)=>i>n?1:-1);return new Set(e)}getPaths(t,e,i){let n=this.toPoolsMap(i);return this.getProposals(t,e,i).filter(s=>this.validPath(s,n)).map(s=>this.toHops(s,n))}getProposals(t,e,i){let n=this.buildRouteKey(t,e,i);if(this.routeProposals.has(n))return this.routeProposals.get(n);let r=this.routeSuggester.getProposals(t,e,i);return this.routeProposals.set(n,r),r}validPath(t,e){return t.length>0&&t.map(i=>this.validEdge(i,e)).reduce((i,n)=>i&&n)}validEdge([t,e,i],n){return n.get(t)?.validatePair(e,i)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Gt.get(e)]))}toHops(t,e){return t.map(([i,n,r])=>{let s=e.get(i);return{poolAddress:i,poolId:s?.id,pool:s?.type,assetIn:n,assetOut:r}})}};var x=require("@galacticcouncil/common");var ri=(e=>(e.Buy="Buy",e.Sell="Sell",e))(ri||{}),si=(i=>(i.Dca="Dca",i.TwapSell="TwapSell",i.TwapBuy="TwapBuy",i))(si||{}),Wi=(i=>(i.OrderTooSmall="OrderTooSmall",i.OrderTooBig="OrderTooBig",i.OrderImpactTooBig="OrderImpactTooBig",i))(Wi||{});var{FeeUtils:Qn}=I,Wt=class extends Vt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,i){let n=super.validateInput(t,e,i),r=super.getPaths(t,e,i);if(!r.length)throw new Zt(t,e);return{paths:r,pools:i,poolsMap:n}}async withCtx(t,e,i){let n=await super.getPools(),r=this.buildCtxSync(t,e,n);return i(r)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((i,n)=>{let r=i[i.length-1].amountOut,s=n[n.length-1].amountOut;return r>s?-1:1});return e.find(i=>i.every(n=>n.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(i=>i.tradeFeeRange).length>0){let i=t.map(r=>r.tradeFeeRange?.[0]??r.tradeFeePct).reduce((r,s)=>r+s),n=t.map(r=>r.tradeFeeRange?.[1]??r.tradeFeePct).reduce((r,s)=>r+s);return[i,n]}}getPoolFeeRange(t){let e=t.min?Qn.toPct(t.min):void 0,i=t.max?Qn.toPct(t.max):void 0;if(e&&i)return[e,i]}async getBestSell(t,e,i){return this.getSell(t,e,i)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,i,n){return this.withCtx(t,e,async({paths:r,poolsMap:s})=>{let a;if(n)a=await this.toSellSwaps(i,n,s);else{let o=r.map(u=>this.toSellSwaps(i,u,s)),l=await Promise.all(o);a=this.findBestSellRoute(l)}return this.buildSell(s,a)})}async getSells(t,e,i){return this.withCtx(t,e,async({paths:n,poolsMap:r})=>{let s=n.map(o=>this.toSellSwaps(i,o,r));return(await Promise.all(s)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(r,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let i=e[0],n=e[e.length-1],r=this.isDirectTrade(e),s=this.getSellSpot(e),a=n.amountOut,o=r?n.calculatedOut:this.calculateDelta0Y(i.amountIn,e,t),l=o-a,u=this.getRouteFeeRange(e),p=r?n.tradeFeePct:U.calculateSellFee(o,a),d=q.mulSpot(i.amountIn,s,i.assetInDecimals,n.assetOutDecimals),m=U.calculateDiffToRef(o,d);return{type:"Sell",amountIn:i.amountIn,amountOut:n.amountOut,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Sell",amountIn:x.big.toDecimal(i.amountIn,i.assetInDecimals),amountOut:x.big.toDecimal(n.amountOut,n.assetOutDecimals),spotPrice:x.big.toDecimal(s,x.RUNTIME_DECIMALS),tradeFee:x.big.toDecimal(l,n.assetOutDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e.map(h=>h.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,i)=>e*i/10n**BigInt(x.RUNTIME_DECIMALS))}calculateDelta0Y(t,e,i){let n=[];for(let r=0;r<e.length;r++){let s=e[r],a=i.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;r>0?l=n[r-1]:l=t;let u=a.calculateOutGivenIn(o,l);n.push(u)}return n[n.length-1]}async calculateMostLiquidRoute(t,e,i){let{paths:n,pools:r,poolsMap:s}=i,l=r.filter(b=>b.tokens.some(g=>g.id===t)).map(b=>b.type==="Aave"?b.tokens:b.tokens.filter(g=>g.id===t)).map(b=>b.map(g=>g.balance).reduce((g,f)=>g+f)).sort((b,g)=>g<b?-1:1)[0],u=q.getFraction(l,.1),p=await Promise.all(n.map(b=>this.toSellSwaps(u,b,s))),m=this.findBestSellRoute(p).map(b=>({poolAddress:b.poolAddress,poolId:b?.poolId,pool:b.pool,assetIn:b.assetIn,assetOut:b.assetOut})),h=this.buildRouteKey(t,e,r);return this.mlr.set(h,m),m}async toSellSwaps(t,e,i){let n=[];for(let r=0;r<e.length;r++){let s=e[r],a=i.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;r>0?l=n[r-1].amountOut:l=typeof t=="string"?x.big.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(o,a),{amountOut:p,calculatedOut:d,feePct:m,errors:h}=a.validateAndSell(o,l,u),b=this.getPoolFeeRange(u),g=a.spotPriceOutGivenIn(o),f=q.mulSpot(l,g,o.decimalsIn,o.decimalsOut),y=U.calculateDiffToRef(d,f);n.push({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===s.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===s.assetIn},toHuman(){return{...s,amountIn:x.big.toDecimal(l,o.decimalsIn),amountOut:x.big.toDecimal(p,o.decimalsOut),calculatedOut:x.big.toDecimal(d,o.decimalsOut),spotPrice:x.big.toDecimal(g,x.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h}}})}return n}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async i=>{let n=this.buildRouteKey(t,e,i.pools),r=this.mlr.get(n);return r||this.calculateMostLiquidRoute(t,e,i)})}async getSpotPrice(t,e){return this.withCtx(t,e,async i=>{let{pools:n,poolsMap:r}=i,s=this.buildRouteKey(t,e,n),a=this.mlr.get(s);a||(a=await this.calculateMostLiquidRoute(t,e,i));let o=await this.toSellSwaps("1",a,r);return{amount:this.getSellSpot(o),decimals:x.RUNTIME_DECIMALS}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((i,n)=>{let r=i[0].amountIn,s=n[0].amountIn;return r>s?1:-1});return e.find(i=>i.every(n=>n.errors.length==0))||e[0]}async getBestBuy(t,e,i){return this.getBuy(t,e,i)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,i,n){return this.withCtx(t,e,async({paths:r,poolsMap:s})=>{let a;if(n)a=await this.toBuySwaps(i,n,s);else{let o=r.map(u=>this.toBuySwaps(i,u,s)),l=await Promise.all(o);a=this.findBestBuyRoute(l)}return this.buildBuy(s,a)})}async getBuys(t,e,i){return this.withCtx(t,e,async({paths:n,poolsMap:r})=>{let s=n.map(o=>this.toBuySwaps(i,o,r));return(await Promise.all(s)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(r,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let i=e[e.length-1],n=e[0],r=this.isDirectTrade(e),s=this.getBuySpot(e),a=n.amountIn,o=r?n.calculatedIn:this.calculateDelta0X(i.amountOut,e,t),l=a-o,u=this.getRouteFeeRange(e),p=r?n.tradeFeePct:U.calculateBuyFee(o,a),d=q.mulSpot(i.amountOut,s,i.assetOutDecimals,n.assetInDecimals),m;return o===0n?m=-100:m=U.calculateDiffToRef(d,o),{type:"Buy",amountOut:i.amountOut,amountIn:n.amountIn,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Buy",amountOut:x.big.toDecimal(i.amountOut,i.assetOutDecimals),amountIn:x.big.toDecimal(n.amountIn,n.assetInDecimals),spotPrice:x.big.toDecimal(s,x.RUNTIME_DECIMALS),tradeFee:x.big.toDecimal(l,n.assetInDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e.map(h=>h.toHuman())}}}}calculateDelta0X(t,e,i){let n=[];for(let r=e.length-1;r>=0;r--){let s=e[r],a=i.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;r==e.length-1?l=t:l=n[0];let u=a.calculateInGivenOut(o,l);n.unshift(u)}return n[0]}async toBuySwaps(t,e,i){let n=[];for(let r=e.length-1;r>=0;r--){let s=e[r],a=i.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;r==e.length-1?l=typeof t=="string"?x.big.toBigInt(t,o.decimalsOut):t:l=n[0].amountIn;let u=await this.ctx.getPoolFees(o,a),{amountIn:p,calculatedIn:d,feePct:m,errors:h}=a.validateAndBuy(o,l,u),b=this.getPoolFeeRange(u),g=a.spotPriceInGivenOut(o),f=q.mulSpot(l,g,o.decimalsOut,o.decimalsIn),y;d===0n?y=-100:y=U.calculateDiffToRef(f,d),n.unshift({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===s.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===s.assetIn},toHuman(){return{...s,amountOut:x.big.toDecimal(l,o.decimalsOut),amountIn:x.big.toDecimal(p,o.decimalsIn),calculatedIn:x.big.toDecimal(d,o.decimalsIn),spotPrice:x.big.toDecimal(g,x.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h}}})}return n}};var z=require("@galacticcouncil/common");var Jn=6e3,Yi=1000000000000000n,xe=6,zi=-5,$i=216e5,Bp=3,Zn=6;var Xi=require("polkadot-api");var nt=class{static build(t){return t.map(({assetIn:e,assetOut:i,pool:n,poolId:r})=>n==="Stableswap"?{pool:(0,Xi.Enum)("Stableswap",r),asset_in:e,asset_out:i}:{pool:(0,Xi.Enum)(n),asset_in:e,asset_out:i})}};var Yt=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Yi})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,i,n,r){let s=await this.router.getBestSell(t,e,i),{amountIn:a,swaps:o,priceImpactPct:l}=s,u=o[0],p=o[o.length-1],{assetInDecimals:d}=u,{assetOutDecimals:m}=p,h=Math.abs(l),b=await this.getMinimumOrderBudget(t,d),g=this.getMaximumTradeCount(a,b),f=this.getOptimalTradeCount(h),y=r||f,S=Math.round(n/y),v=a/BigInt(y),T=await this.router.getBestSell(t,e,v),A=a<b,D=[];A&&D.push("OrderTooSmall");let G=T.amountOut*BigInt(y),lt=this.toBlockPeriod(S),gt=T.tradeFee*BigInt(y),j=nt.build(o),tt={assetIn:t,assetOut:e,errors:D,maxTradeCount:g,optTradeCount:f,tradeCount:y,tradeFee:gt,tradeImpactPct:T.priceImpactPct,tradePeriod:lt,tradeRoute:j,type:"Dca"};return{...tt,amountIn:a,amountOut:G,tradeAmountIn:T.amountIn,tradeAmountOut:T.amountOut,toHuman(){return{...tt,amountIn:z.big.toDecimal(a,d),amountOut:z.big.toDecimal(G,m),tradeAmountIn:z.big.toDecimal(T.amountIn,d),tradeAmountOut:z.big.toDecimal(T.amountOut,m)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let i=await this.router.getSpotPrice(0,t);if(i)return q.mulSpot(this.minOrderBudget,i.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e){let i=e*2n/10n;if(i===0n)return 0;let n=t+i/2n;return Number(n/i)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,i){let n=await this.router.getBestSell(t,e,i),{amountIn:r,swaps:s,priceImpactPct:a}=n,o=s[0],l=s[s.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),h=r/BigInt(m),[b,g]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestSell(o.assetIn,l.assetOut,h)]),f=m===1,y=r<b,S=g.priceImpactPct<-5,v=[];y||f?v.push("OrderTooSmall"):S&&v.push("OrderImpactTooBig");let T=g.amountOut*BigInt(m),A=g.tradeFee*BigInt(m),D=nt.build(s),G={assetIn:t,assetOut:e,errors:v,tradeCount:m,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:D,type:"TwapSell"};return{...G,amountIn:r,amountOut:T,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:A,toHuman(){return{...G,amountIn:z.big.toDecimal(r,u),amountOut:z.big.toDecimal(T,p),tradeAmountIn:z.big.toDecimal(g.amountIn,u),tradeAmountOut:z.big.toDecimal(g.amountOut,p),tradeFee:z.big.toDecimal(A,p)}}}}async getTwapBuyOrder(t,e,i){let n=await this.router.getBestBuy(t,e,i),{amountOut:r,swaps:s,priceImpactPct:a}=n,o=s[0],l=s[s.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),h=r/BigInt(m),[b,g]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestBuy(o.assetIn,l.assetOut,h)]),f=g.amountIn*BigInt(m),y=m===1,S=f<b,v=g.priceImpactPct<-5,T=[];S||y?T.push("OrderTooSmall"):v&&T.push("OrderImpactTooBig");let A=g.tradeFee*BigInt(m),D=nt.build(s),G={assetIn:t,assetOut:e,errors:T,tradeCount:m,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:D,type:"TwapBuy"};return{...G,amountIn:f,amountOut:r,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:A,toHuman(){return{...G,amountIn:z.big.toDecimal(f,u),amountOut:z.big.toDecimal(r,p),tradeAmountIn:z.big.toDecimal(g.amountIn,u),tradeAmountOut:z.big.toDecimal(g.amountOut,p),tradeFee:z.big.toDecimal(A,u)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let n=216e5/(this.blockTime*6);return Math.round(n)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,i=Math.round(e);return Math.max(i,6)}};var Qi={};B(Qi,{BIG_10:()=>sr,BIG_BILL:()=>ji,StakingApi:()=>Ie,StakingClient:()=>_e});var $=require("@galacticcouncil/math-staking"),Z=yt(require("big.js"));var ai={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},tr=c=>Object.keys(ai).includes(c);var er=require("polkadot-api"),ir=require("@polkadot-api/utils"),nr=require("@galacticcouncil/common");function rr(c){let t=("modl"+c).padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,ir.toHex)(e);return(0,er.AccountId)(nr.HYDRATION_SS58_PREFIX).dec(i)}var oi="20000000000000000",li="2000",sr=(0,Z.default)(10),ji=(0,Z.default)(sr.pow(12)),Ie=class{client;balanceClient;constructor(t,e){this.client=t,this.balanceClient=e}async getPotBalance(){let t=await this.client.getPalletId(),e=rr(t);return await this.balanceClient.getBalance(e,0)}async getStakingPosition(t){let[e,i]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let n=e.created_at,r=await i.reduce(async(s,[a,o])=>{let l=await s,u=a,p=o.amount,d=o.conviction.type.toLowerCase(),m=await this.client.getReferendumInfo(u);return m&&(m.type==="Approved"||m.type==="Rejected")&&tr(d)&&l.push({id:u,amount:p,conviction:d}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:n,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:r}}async getStake(t){let e=await this.client.getNFTCollectionId(),[i,n]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),r=n.find(s=>s)?.itemId;return{totalStake:i?.total_stake,accumulatedRewardPerStake:i?.accumulated_reward_per_stake,potReservedBalance:i?.pot_reserved_balance,positionId:r,stakePosition:r?await this.getStakingPosition(r):void 0}}getCurrentActionPoints(t,e,i,n){let r=(0,Z.default)(0),s=(0,Z.default)(0),a=ai.locked6x,o=(0,Z.default)(i.toString()).mul(a),l=100,u=[];t.forEach(m=>{let h=ai[m.conviction],b=n.includes(m.id.toString());b&&u.push(m.id.toString());let g=(0,Z.default)(m.amount.toString()).mul(l).div(o);r=r.plus(Math.floor(g.mul(h).toNumber())),s=s.plus(Math.floor(g.mul(b?a:h).toNumber()))});let p=Math.floor((0,Z.default)(i.toString()).mul(a).mul(l).div(o).toNumber());n.forEach(m=>{u.includes(m)||(s=s.plus(p))});let d={democracyVote:1};return r=r.mul(d.democracyVote),r=r.plus(e.toString()||"0"),s=s.mul(d.democracyVote),s=s.plus(e.toString()||"0"),{currentActionPoints:r.toString(),maxActionPoints:s.toString()}}async getRewards(t,e,i){let n=await this.getStake(t),{potReservedBalance:r,accumulatedRewardPerStake:s,totalStake:a,stakePosition:o}=n;if(!o)return;let[l,u,p,d,m,h,b]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),g=(0,Z.default)(l.transferable.toString()).minus(r.toString()),f=g.gt(0)&&a>0?(0,$.calculate_accumulated_rps)(s.toString(),g.toString(),a.toString()):s.toString(),y=(0,$.calculate_period_number)(u.toString(),i,b),S=(0,$.calculate_period_number)(u.toString(),o.createdAt.toString(),b),v=(0,$.calculate_rewards)(f,o.rewardPerStake.toString(),o.stake.toString()),T=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),A=(0,$.calculate_points)(S,y,d.toString(),m.toString(),T.currentActionPoints,h.toString(),o.accumulatedSlashPoints.toString()),D=(0,$.sigmoid)(A,oi,li),G=(()=>{if(!e.length)return;let Xt=(0,$.calculate_points)(S,y,d.toString(),m.toString(),T.maxActionPoints.toString(),h.toString(),o.accumulatedSlashPoints.toString());return(0,$.sigmoid)(Xt,oi,li)})(),lt=(0,Z.default)(v).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if((0,Z.default)(y).minus(S).lte(p.toString()))return{rewards:"0",payablePercentage:D,extraPayablePercentage:G,constants:{a:oi,b:li}};let gt=(0,$.calculate_percentage_amount)(lt.toString(),D),j=(0,Z.default)(o.accumulatedLockedRewards.toString()),tt=j.gt(gt)?j:(0,Z.default)(gt);return{rewards:tt.div(ji).toString(),maxRewards:lt.div(ji).toString(),allocatedRewardsPercentage:tt.div(lt).mul(100).toNumber(),points:A,payablePercentage:D,extraPayablePercentage:G,constants:{a:oi,b:li}}}};var _e=class extends H{async getPalletId(){let t=this.api.constants.Staking.PalletId;return(await t()).asText()}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:s})=>{let[a,o,l]=s;return{address:a,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var Zi={};B(Zi,{TxBuilderFactory:()=>$t});var Ji=require("polkadot-api");function ar(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var zt=class extends H{evm;evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balanceClient=new ct(t),this.aaveUtils=new xt(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:i=>this.dryRun(i,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:bi})}async dryRun(t,e){let i=(0,Ji.Enum)("Signed",t),n=(0,Ji.Enum)("system",i),s=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(n,e.decodedCall),a=s.success&&!s.value.execution_result.success?s.value.execution_result.value.error:null;if(a){let o=ar(a.value);throw new Error("Dry run execution error!",{cause:o})}return s}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var ci=class extends zt{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:i}=this.trade;if(i==="Buy")return this.buildBuyTx();let{assetIn:n}=e[0],r=await this.balanceClient.getBalance(this.beneficiary,n);return t>=r.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,n=i[0],r=i[i.length-1],s=q.getFraction(t,this.slippagePct),a=n.assetIn,o=r.assetOut,l=t+s,u;return this.isDirectOmnipoolTrade(i)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:nt.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,n=i[0],r=i[i.length-1],s=q.getFraction(e,this.slippagePct),a=n.assetIn,o=r.assetOut,l=e-s,u;return this.isDirectOmnipoolTrade(i)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:nt.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,i=e[0],n=e[e.length-1],r=q.getFraction(t,this.slippagePct),s=i.assetIn,a=n.assetOut,o=t-r,l=this.api.tx.Router.sell_all({asset_in:s,asset_out:a,min_amount_out:o,route:nt.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var ui=require("polkadot-api");var pi=class extends zt{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:n,tradePeriod:r,tradeRoute:s}=this.order,a=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ui.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:n,min_amount_out:0n,route:s})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:n,tradeAmountOut:r,tradePeriod:s,tradeRoute:a}=this.order,o=q.getFraction(r,this.slippagePct),l=r-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ui.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:n,min_amount_out:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:n,tradeAmountOut:r,tradePeriod:s,tradeRoute:a}=this.order,o=q.getFraction(n,this.slippagePct),l=n+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ui.Enum)("Buy",{asset_in:e,asset_out:i,amount_out:r,max_amount_in:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var $t=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new ci(this.client,this.evmClient).setTrade(t)}order(t){return new pi(this.client,this.evmClient).setOrder(t)}};async function Zr(c){let t=new Et(c),e=new ee(c),[i,n]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),r=new Ut(c,e).withAave().withOmnipool().withStableswap().withXyk(),s=new ct(c),a=new _e(c),o=new ae(c),l=new xt(e),u=new Wt(r),p=new Yt(u,{blockTime:i,minBudgetInNative:n}),d=new Ie(a,s),m=new se(o,s,{blockTime:i});return{api:{aave:l,router:u,scheduler:p,staking:d,farm:m},client:{asset:new Bt(c),balance:s,evm:e},ctx:{pool:r},tx:new $t(c,e),destroy:()=>{r.destroy()}}}0&&(module.exports={QueryBus,aave,api,async,calc,client,const:null,createSdkContext,error,evm,farm,fmt,json,math,pool,sor,staking,tx});
|