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