@galacticcouncil/sdk-next 1.1.0 → 1.2.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/api/Papi.d.ts +2 -1
- package/build/client/index.cjs +1 -1
- package/build/client/index.mjs +1 -1
- package/build/farm/index.cjs +1 -1
- package/build/farm/index.mjs +1 -1
- package/build/index.cjs +1 -1
- package/build/index.mjs +1 -1
- package/build/pool/index.cjs +1 -1
- package/build/pool/index.mjs +1 -1
- package/build/sor/TradeScheduler.d.ts +10 -0
- package/build/sor/index.cjs +1 -1
- package/build/sor/index.mjs +1 -1
- package/build/sor/types.d.ts +1 -0
- package/build/staking/index.cjs +1 -1
- package/build/staking/index.mjs +1 -1
- package/build/tx/IntentLimitTxBuilder.d.ts +21 -0
- package/build/tx/IntentMarketTxBuilder.d.ts +15 -0
- package/build/tx/IntentOrderTxBuilder.d.ts +17 -0
- package/build/tx/TxBuilderFactory.d.ts +6 -0
- package/build/tx/index.cjs +1 -1
- package/build/tx/index.mjs +1 -1
- package/package.json +2 -2
package/build/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var An=Object.create;var Ue=Object.defineProperty;var On=Object.getOwnPropertyDescriptor;var Bn=Object.getOwnPropertyNames;var Fn=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty;var _i=(c,t)=>()=>(c&&(t=c(c=0)),t);var C=(c,t)=>{for(var e in t)Ue(c,e,{get:t[e],enumerable:!0})},Ge=(c,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Bn(t))!Rn.call(c,r)&&r!==e&&Ue(c,r,{get:()=>t[r],enumerable:!(i=On(t,r))||i.enumerable});return c},yt=(c,t,e)=>(Ge(c,t,"default"),e&&Ge(e,t,"default")),wt=(c,t,e)=>(e=c!=null?An(Fn(c)):{},Ge(t||!c||!c.__esModule?Ue(e,"default",{value:c,enumerable:!0}):e,c)),Cn=c=>Ge(Ue({},"__esModule",{value:!0}),c);var re={};var wr=_i(()=>{yt(re,require("@polkadot-api/sm-provider"))});var ne={};var xr=_i(()=>{yt(ne,require("@polkadot-api/smoldot"))});var se={};var Tr=_i(()=>{yt(se,require("@polkadot-api/known-chains/polkadot"))});var Ss={};C(Ss,{QueryBus:()=>de,aave:()=>Ci,api:()=>Ai,async:()=>pe,calc:()=>q,client:()=>Mi,const:()=>ki,createSdkContext:()=>Ps,error:()=>Li,evm:()=>Hi,farm:()=>Xi,fmt:()=>I,json:()=>Gt,math:()=>z,pool:()=>rr,sor:()=>ur,staking:()=>dr,tx:()=>gr});module.exports=Cn(Ss);var Ai={};C(Ai,{Papi:()=>D,Watcher:()=>ie,getSm:()=>Mn,getWs:()=>kn});var Ve=require("@galacticcouncil/descriptors");var Pr=require("@galacticcouncil/common"),Et=require("rxjs");var ft=require("rxjs"),H=require("rxjs/operators");function fr(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>(0,ft.defer)(()=>(0,ft.from)(c._request("system_health",[]))).pipe((0,H.timeout)({first:e}),(0,H.map)(()=>"online"),(0,H.catchError)(()=>(0,ft.of)("offline")));return(0,ft.of)({state:"offline",delayMs:0}).pipe((0,H.expand)(n=>(0,ft.timer)(n.delayMs).pipe((0,H.switchMap)(i),(0,H.map)(s=>({state:s,delayMs:t})))),(0,H.skip)(1),(0,H.map)(n=>n.state),(0,H.distinctUntilChanged)(),(0,H.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:En}=Pr.log,ie=class c{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,Et.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",fr(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe((0,Et.tap)({error:i=>En.error(t,i)}),(0,Et.shareReplay)({bufferSize:1,refCount:!0}))}};var D=class{client;api;apiNext;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(Ve.hydration),this.apiNext=this.client.getTypedApi(Ve.hydrationNext),this.watcher=ie.getInstance(this.client),this.at=e??"best"}};var Sr=require("polkadot-api/ws"),vr=require("polkadot-api/logs-provider"),kn=(c,t={})=>{let e=typeof c=="string"?c.split(","):c,i=(0,Sr.getWsProvider)(e,t);return(0,vr.withLogsRecorder)(r=>console.log(r),i),i};async function Mn(c){let{getSmProvider:t}=await Promise.resolve().then(()=>(wr(),re)),{start:e}=await Promise.resolve().then(()=>(xr(),ne)),{chainSpec:i}=await Promise.resolve().then(()=>(Tr(),se)),r=e(),n=await r.addChain({chainSpec:i}),s=await r.addChain({chainSpec:c,potentialRelayChains:[n]});return t(()=>s)}var Ci={};C(Ci,{AAVE_GAS_LIMIT:()=>Fi,AAVE_LENDING_POOL_ADDRESS:()=>Ye,AAVE_POOL_ABI:()=>Oi,AAVE_POOL_DATA_PROVIDER:()=>ze,AAVE_POOL_DATA_PROVIDER_ABI:()=>We,AAVE_POOL_PROXY:()=>Bi,AAVE_ROUNDING_THRESHOLD:()=>zs,AAVE_UINT_256_MAX:()=>Dn,AaveClient:()=>ae,AaveUtils:()=>At});var Oi=[{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 Bi="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",ze="0x112b087b60C1a166130d59266363C45F8aa99db0",Ye="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Fi=1000000n,zs=5,Dn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ae=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:ze,args:[Ye],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:We,address:ze,args:[Ye,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:Oi,address:Bi,args:[t],functionName:"getUserAccountData"})}};var L=wt(require("big.js")),st=require("@galacticcouncil/common");var{ERC20:kt}=st.erc20,{H160:Ri}=st.h160,Ln=1.01,qn=31536000n,Ir=4,$e=-1,Xe=10n**27n,At=class{client;constructor(t){this.client=new ae(t)}async getSummary(t){let e=Ri.fromAny(t),[i,r,n,s]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[a]=i,[o,l]=r,[u,p,d,m,g,b]=n,h=st.big.toDecimal(b,18),P=[];for(let f of o){let v=f.underlyingAsset.toLowerCase(),S=a.find(({underlyingAsset:Ii})=>Ii.toLowerCase()===v);if(!S)throw new Error("Missing pool reserve for "+v);let T=f.scaledATokenBalance,B=S.liquidityIndex,N=S.liquidityRate,W=S.availableLiquidity,ut=S.priceInMarketReferenceCurrency,bt=s+6,Z=this.calculateLinearInterest(N,S.lastUpdateTimestamp,bt),nt=B*Z/Xe,ee=T*nt/Xe,qe=Number(l!==0&&l===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,Ne=S.usageAsCollateralEnabled&&f.usageAsCollateralEnabledOnUser&&f.scaledATokenBalance>0n,He=kt.toAssetId(v);P.push({aTokenBalance:ee,availableLiquidity:W,decimals:Number(S.decimals),isCollateral:Ne,priceInRef:ut,reserveId:He,reserveAsset:v,reserveLiquidationThreshold:qe})}return{healthFactor:Number(h),currentLiquidationThreshold:Number(st.big.toDecimal(m,Ir)),totalCollateral:u,totalDebt:p,reserves:P}}async hasBorrowPositions(t){let e=Ri.fromAny(t),i=await this.client.getUserAccountData(e),[r,n]=i;return n>0n}async getHealthFactor(t){let e=Ri.fromAny(t),i=await this.client.getUserAccountData(e),[r,n,s,a,o,l]=i;return this.calculateHealthFactorFromBalances(n,r,a)}async getHealthFactorAfterWithdraw(t,e,i){let{totalCollateral:r,totalDebt:n,reserves:s,currentLiquidationThreshold:a}=await this.getSummary(t);if(n===0n)return $e;let o=kt.fromAssetId(e),l=s.find(v=>v.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:u,isCollateral:p,priceInRef:d,reserveLiquidationThreshold:m}=l,g=st.big.toBigInt(i,u),b=p?g*d/10n**BigInt(u):0n,h=r-b;if(h<=0n)return 0;let P=(0,L.default)(r.toString()).mul(a).minus((0,L.default)(b.toString()).mul(m)).div(h.toString()),f=(0,L.default)(h.toString()).mul(P).div(n.toString()).toFixed(6,L.default.roundDown);return Number(f)}async getHealthFactorAfterSupply(t,e,i){let{totalCollateral:r,totalDebt:n,reserves:s,currentLiquidationThreshold:a}=await this.getSummary(t);if(n===0n)return $e;let o=kt.fromAssetId(e),l=s.find(f=>f.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:u,priceInRef:p,reserveLiquidationThreshold:d}=l,g=st.big.toBigInt(i,u)*p/10n**BigInt(u),b=r+g;if(b<=0n)return 0;let h=(0,L.default)(r.toString()).mul(a).plus((0,L.default)(g.toString()).mul(d)).div(b.toString()),P=(0,L.default)(b.toString()).mul(h).div(n.toString()).toFixed(6,L.default.roundDown);return Number(P)}async getHealthFactorAfterSwap(t,e,i,r,n){let{totalDebt:s,reserves:a,healthFactor:o}=await this.getSummary(t);if(s===0n)return $e;let l=kt.fromAssetId(i),u=kt.fromAssetId(n),p=a.find(B=>B.reserveAsset===l),d=a.find(B=>B.reserveAsset===u);if(!p)throw new Error(`Missing reserve ctx for ${l}`);if(!d)throw new Error(`Missing reserve ctx for ${d}`);let m=st.big.toBigInt(e,p.decimals),g=st.big.toBigInt(r,d.decimals),b=m*p.priceInRef/10n**BigInt(p.decimals),h=g*d.priceInRef/10n**BigInt(d.decimals),P=p.isCollateral?(0,L.default)(b.toString()).mul(p.reserveLiquidationThreshold):(0,L.default)(0),S=(d.isCollateral?(0,L.default)(h.toString()).mul(d.reserveLiquidationThreshold):(0,L.default)(0)).minus(P).div(s.toString()),T=(0,L.default)(o).plus(S).toFixed(6,L.default.roundDown);return Number(T)}async getMaxWithdraw(t,e){let{totalDebt:i,reserves:r,healthFactor:n}=await this.getSummary(t),s=kt.fromAssetId(e),a=r.find(o=>o.reserveAsset===s);if(!a)throw new Error("Missing reserve ctx for "+s);return this.calculateWithdrawMax(a,i,n)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:i,healthFactor:r}=await this.getSummary(t),n={};for(let s of i){let a=this.calculateWithdrawMax(s,e,r);s.reserveId&&(n[s.reserveId]=a)}return n}calculateWithdrawMax(t,e,i){let{aTokenBalance:r,availableLiquidity:n,decimals:s,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=t,u=r;if(l&&e>0n){let d=i-Ln;if(d>0){let m=(0,L.default)(d).mul(e.toString()).div(o).toFixed(0,L.default.roundDown),g=(0,L.default)(m).div(a.toString()).mul(10**s).toFixed(0,L.default.roundDown);u=r<BigInt(g)?r:BigInt(g)}else u=0n}return{amount:u<n?u:n,decimals:s}}calculateLinearInterest(t,e,i){let r=i-e;if(r<=0)return Xe;let n=t*BigInt(r)/qn;return Xe+n}calculateHealthFactorFromBalances(t,e,i){if(t===0n)return $e;let r=e*i/t,n=st.big.toDecimal(r,Ir);return Number(n)}};var Mi={};C(Mi,{AssetClient:()=>Mt,BalanceClient:()=>pt,ChainParams:()=>Ht});var oe=require("polkadot-api");var Mt=class extends D{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:i,value:r})=>{let[n]=i;return[n,r]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:i,value:r})=>{let[n]=i;return[n,r]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:i})=>{let{asset_type:r}=i;return this.SUPPORTED_TYPES.includes(r.type)}).map(({keyArgs:i,value:r})=>{let[n]=i;return[n,r]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:i,value:r})=>{let[n]=i;return[n,r]}))}async mapToken(t,e,i,r){let{name:n,asset_type:s,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=i.get(t)??{};return{id:t,name:n?oe.Binary.toText(n):void 0,symbol:l,decimals:u,icon:l,type:s.type,isSufficient:a,location:r,existentialDeposit:o}}async mapBond(t,e,i,r){let[n,s]=r,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:p}=await this.mapToken(n,e,i),d=Number(s),m=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",m.format(d)].join(" ");return{id:t,name:g,symbol:u+"b",decimals:p,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:n,maturity:d}}async mapShares(t,e,i,r){let{assets:n}=r,{name:s,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,p=await Promise.all(n.map(async g=>{let{symbol:b}=await this.mapToken(g,e,i);return[g,b]})),d=Object.fromEntries(p),m=Object.values(d);return{id:t,name:m.join(", "),symbol:a&&oe.Binary.toText(a)||s&&oe.Binary.toText(s),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:d}}async mapExternal(t,e,i,r){let n=await this.mapToken(t,e,new Map,r),s=i?.find(a=>a.internalId===n.id);return s?{...n,decimals:s.decimals,name:s.name,symbol:s.symbol,icon:s.symbol,isWhiteListed:s.isWhiteListed}:n}parseMetadata(t){return new Map(Array.from(t,([e,i])=>[e,{symbol:i.symbol?oe.Binary.toText(i.symbol):void 0,decimals:i.decimals}]))}async getSupported(t,e){let[i,r,n,s]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(i),o=[];for(let[l,u]of Array.from(i)){let p=r.get(l),{asset_type:d}=u,m;switch(d.type){case"Bond":let g=s.get(l);m=await this.mapBond(l,u,a,g);break;case"StableSwap":let b=n.get(l);m=await this.mapShares(l,u,a,b);break;case"External":m=await this.mapExternal(l,u,e,p);break;default:m=await this.mapToken(l,u,a,p)}o.push(m)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var _r=require("@galacticcouncil/common"),tt=require("rxjs"),w=require("rxjs/operators");var ki={};C(ki,{HUB_ASSET_ID:()=>Lt,HYDRATION_OMNIPOOL_ADDRESS:()=>Hn,HYDRATION_PARACHAIN_ID:()=>Nn,PERBILL_DENOMINATOR:()=>Ei,PERMILL_DENOMINATOR:()=>Dt,SYSTEM_ASSET_DECIMALS:()=>Ke,SYSTEM_ASSET_ID:()=>E,TRADEABLE_DEFAULT:()=>qt});var Dt=1e6,Ei=1e9,E=0,Ke=12,Nn=2034,Hn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Lt=1,qt=15;var{logger:Nt}=_r.log,pt=class extends D{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:i}=await e.getValue(t,{at:this.at});return this.getBreakdown(i)}async getTokenBalance(t,e){let r=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(r)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,tt.defer)(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),r=this.watchErc20Balance(t);return(0,tt.combineLatest)([e,i,r]).pipe((0,w.connect)(n=>(0,tt.concat)(n.pipe((0,w.take)(1)),n.pipe((0,w.skip)(1),(0,w.debounceTime)(250)))))}).pipe((0,w.map)(e=>e.flat()),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([e,i],r)=>r===0?i:this.getDeltas(e,i))).pipe((0,w.tap)({subscribe:()=>Nt.debug("balance: subscribe",t),error:e=>Nt.error("balance",e)}),(0,w.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,tt.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,w.map)(({value:i})=>({id:0,balance:this.getBreakdown(i.data)})),(0,w.tap)({error:i=>Nt.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return(0,tt.defer)(()=>i.watchValue(t,e,{at:"best"})).pipe((0,w.map)(({value:r})=>({id:e,balance:this.getBreakdown(r)})),(0,w.tap)({error:r=>Nt.error("balance(token)",r)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,tt.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,w.distinctUntilChanged)((i,r)=>!r.deltas),(0,w.map)(({deltas:i})=>{let r=[];return i?.deleted.forEach(n=>{let[s,a]=n.args;r.push({id:a,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(n=>{let[s,a]=n.args;r.push({id:a,balance:this.getBreakdown(n.value)})}),r}),(0,w.tap)({error:i=>Nt.error("balance(tokens)",i)}))}watchErc20Balance(t,e){let i=async()=>{if(this.erc20Ids)return this.erc20Ids;let n=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=n.filter(({value:s})=>s.asset_type.type==="Erc20").map(({keyArgs:s})=>{let[a]=s;return a}),this.erc20Ids},r=async n=>(await Promise.all(n.map(async a=>[a,await this.getBalanceData(t,a)]))).map(([a,o])=>({id:a,balance:o}));return(0,tt.defer)(()=>(0,tt.from)(e?Promise.resolve(e):i()).pipe((0,w.switchMap)(n=>this.watcher.bestBlock$.pipe((0,w.switchMap)(()=>(0,tt.from)(r(n))))),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([n,s],a)=>a===0?s.filter(o=>o.balance.total>0n):this.getDeltas(n,s)),(0,w.distinctUntilChanged)((n,s)=>s.length===0),(0,w.tap)({error:n=>Nt.error("balance(erc20)",n)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(i)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,i=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:i,transferable:e}}getDeltas(t,e){let i=(n,s)=>n!==void 0&&s!==void 0&&n.transferable===s.transferable&&n.total===s.total,r=t.reduce((n,s)=>(n.set(s.id,s.balance),n),new Map);return e.filter(n=>!i(n.balance,r.get(n.id)))}};var Ht=class extends D{_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 Li={};C(Li,{AssetNotFound:()=>Di,PoolNotFound:()=>Ot,RouteNotFound:()=>le});var Di=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},Ot=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},le=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Hi={};C(Hi,{EvmClient:()=>ue,EvmRpcAdapter:()=>ce,createChain:()=>Ni});var qi=require("polkadot-api"),Ar=require("@galacticcouncil/descriptors"),je=require("viem"),Gn=10000000n,ce=class{api;constructor(t){this.api=t.getTypedApi(Ar.hydration)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,i=e.timestamp/1000n,[r]=e.number;return{timestamp:i,number:r}}readContract=(async t=>{let{abi:e,address:i,functionName:r,args:n}=t,s=(0,je.encodeFunctionData)({abi:e,functionName:r,args:n}),a=await this.api.apis.EthereumRuntimeRPCApi.call("0x0000000000000000000000000000000000000000",i,qi.Binary.fromHex(s),[0n,0n,0n,0n],[Gn,0n,0n,0n],void 0,void 0,void 0,!1,[],[]);if(!a.success)throw console.error(r,a.value.type),new Error("Contract read failure");let{exit_reason:o,value:l,used_gas:u}=a.value;if(console.log(u),o.type==="Succeed")return(0,je.decodeFunctionResult)({abi:e,functionName:r,data:qi.Binary.toHex(l)});throw console.log(r,o.type,o.value.type),new Error("Contract read error")})};var Or=require("viem"),Un=["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"],Ni=()=>(0,Or.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:Un}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var mt=require("viem");var ue=class{client;chain;constructor(t){this.client=t,this.chain=Ni()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,mt.createPublicClient)({chain:this.chain,transport:(0,mt.http)()})}getWsProvider(){return(0,mt.createPublicClient)({transport:(0,mt.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,mt.createWalletClient)({account:t,chain:this.chain,transport:(0,mt.custom)(window.ethereum)})}getRPCAdapter(){return new ce(this.client)}};var Xi={};C(Xi,{LiquidityMiningApi:()=>he,LiquidityMiningClient:()=>be});var Gr=require("polkadot-api"),Y=wt(require("big.js")),Pt=require("@galacticcouncil/common"),$i=require("@galacticcouncil/math-liquidity-mining");var pe={};C(pe,{withTimeout:()=>Vn});function Vn(c,t,e="timeout"){return new Promise((i,r)=>{let n=setTimeout(()=>r(new Error(e)),t);c.then(s=>{clearTimeout(n),i(s)},s=>{clearTimeout(n),r(s)})})}var q={};C(q,{divSpot:()=>zn,getFraction:()=>Yn,mulScaled:()=>Br,mulSpot:()=>Wn});var Gi=require("@galacticcouncil/common");function Br(c,t,e,i,r){let n=e+i-r,s=c*t;return n>0?s/BigInt(10)**BigInt(n):n<0?s*BigInt(10)**BigInt(-n):s}function Wn(c,t,e,i){return Br(c,t,e,Gi.RUNTIME_DECIMALS,i)}function zn(c,t,e,i){if(t===0n)return 0n;let r=BigInt(10)**BigInt(Gi.RUNTIME_DECIMALS+i-e);return c*r/t}function Yn(c,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let i=BigInt(10)**BigInt(e),r=BigInt(Math.round(t*Number(i)));return c*r/(BigInt(100)*i)}var I={};C(I,{FeeUtils:()=>Ui,shiftNeg:()=>$n});var Fr=wt(require("big.js"));var Ui=class c{static toPct(t){let[e,i]=t;return c.safeDivide(e*100,i)}static toRaw(t){let[e,i]=t;return c.safeDivide(e,i)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,i=12){let r=10**i;return Math.round(t*r/e)/r}static safeRound(t){return parseFloat(t.toPrecision(15))}};function $n(c,t){let e=(0,Fr.default)(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Gt={};C(Gt,{findNestedKey:()=>Xn,findNestedObj:()=>Kn,jsonFormatter:()=>jn});var Xn=(c,t)=>{let e=[];return JSON.stringify(c,(i,r)=>(r&&r[t]&&e.push(r),r)),e[0]},Kn=(c,t,e)=>{let i;return JSON.stringify(c,(r,n)=>(n&&n[t]===e&&(i=n),n)),i},jn=(c,t)=>typeof t=="bigint"?t.toString():t;var z={};C(z,{calculateBuyFee:()=>ts,calculateDiffToAvg:()=>Qn,calculateDiffToRef:()=>Jn,calculateSellFee:()=>Zn});var dt=wt(require("big.js"));function Qn(c,t){let e=(0,dt.default)(c.toString()),i=(0,dt.default)(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function Jn(c,t){if(t===0n)return 0;let e=(0,dt.default)(c.toString()),i=(0,dt.default)(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function Zn(c,t){if(c===0n)return 0;let e=(0,dt.default)(c.toString()),i=(0,dt.default)(t.toString());return(0,dt.default)(1).minus(i.div(e)).mul(100).round(2).toNumber()}function ts(c,t){if(c===0n)return 0;let e=(0,dt.default)(c.toString());return(0,dt.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var me=(c,t)=>c===t?0:c==null?t==null?0:-1:t==null?c==null?0:1:typeof c.compare=="function"?c.compare(t):typeof t.compare=="function"?-t.compare(c):c<t?-1:c>t?1:0;var Qe=(c,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(c(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var es=Qe(()=>"illegal argument(s)"),Rr=c=>{throw new es(c)};var is=Qe(()=>"index out of bounds"),Vi=c=>{throw new is(c)},Je=(c,t,e)=>(c<t||c>=e)&&Vi(c);var Cr=23283064365386963e-26,Ze=class{float(t=1){return this.int()*Cr*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*Cr-.5)*2*t}normMinMax(t,e){let i=this.minmax(t,e);return this.float()<.5?i:-i}minmax(t,e){return this.float()*(e-t)+t}minmaxInt(t,e){t|=0;let i=(e|0)-t;return i?t+this.int()%i:t}minmaxUint(t,e){t>>>=0;let i=(e>>>0)-t;return i?t+this.int()%i:t}};var ti=class extends Ze{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 Er=new ti(Math.random);var kr=c=>c!=null&&typeof c!="function"&&c.length!==void 0;var Mr=Object.getPrototypeOf({}),ei="function",Dr="string",Ut=(c,t)=>{let e;if(c===t)return!0;if(c!=null){if(typeof c.equiv===ei)return c.equiv(t)}else return c==t;if(t!=null){if(typeof t.equiv===ei)return t.equiv(c)}else return c==t;return typeof c===Dr||typeof t===Dr?!1:(e=Object.getPrototypeOf(c),(e==null||e===Mr)&&(e=Object.getPrototypeOf(t),e==null||e===Mr)?as(c,t):typeof c!==ei&&c.length!==void 0&&typeof t!==ei&&t.length!==void 0?rs(c,t):c instanceof Set&&t instanceof Set?ns(c,t):c instanceof Map&&t instanceof Map?ss(c,t):c instanceof Date&&t instanceof Date?c.getTime()===t.getTime():c instanceof RegExp&&t instanceof RegExp?c.toString()===t.toString():c!==c&&t!==t)},rs=(c,t,e=Ut)=>{let i=c.length;if(i===t.length)for(;i-- >0&&e(c[i],t[i]););return i<0},ns=(c,t,e=Ut)=>c.size===t.size&&e([...c.keys()].sort(),[...t.keys()].sort()),ss=(c,t,e=Ut)=>c.size===t.size&&e([...c].sort(),[...t].sort()),as=(c,t,e=Ut)=>{if(Object.keys(c).length!==Object.keys(t).length)return!1;for(let i in c)if(!t.hasOwnProperty(i)||!e(c[i],t[i]))return!1;return!0};var Wi=class{value;constructor(t){this.value=t}deref(){return this.value}};var Lr=c=>c instanceof Wi;var ii=class c{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return qr("next",this._head)}reverseIterator(){return qr("prev",this.tail)}clear(){this.release()}compare(t,e=me){let i=this._length;if(i<t._length)return-1;if(i>t._length)return 1;if(i===0)return 0;{let r=this._head,n=t._head,s=0;for(;i-- >0&&s===0;)s=e(r.value,n.value),r=r.next,n=n.next;return s}}concat(...t){let e=this.copy();for(let i of t)e.into(i);return e}equiv(t){if(!(t instanceof c||kr(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),i=this._head;for(let r=this._length;r-- >0;){if(!Ut(i.value,e.next().value))return!1;i=i.next}return!0}filter(t){let e=this.empty();return this.traverse(i=>(t(i.value)&&e.append(i.value),!0)),e}find(t){return this.traverse(e=>e.value!==t)}findWith(t){return this.traverse(e=>!t(e.value))}first(){return this._head?.value}insertSorted(t,e){e=e||me;for(let i=this._head,r=this._length;r-- >0;){if(e(t,i.value)<=0)return this.insertBefore(i,t);i=i.next}return this.append(t)}into(t){for(let e of t)this.append(e);return this}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCellUnsafe(t){let e,i;for(t<=this._length>>>1?(e=this._head,i="next"):(e=this.tail,i="prev",t=this._length-t-1);t-- >0&&e;)e=e[i];return e}peek(){return this.tail?.value}$reduce(t,e){let i=this._head;for(let r=this._length;r-- >0&&!Lr(e);)e=t(e,i.value),i=i.next;return e}reduce(t,e){return this.$reduce(t,e)}release(){let t=this._head;if(!t)return!0;let e;for(let i=this._length;i-- >0;)e=t.next,delete t.value,delete t.prev,delete t.next,t=e;return this._head=void 0,this._length=0,!0}reverse(){let t=this._head,e=this.tail,i=(this._length>>>1)+(this._length&1);for(;t&&e&&i>0;){let r=t.value;t.value=e.value,e.value=r,t=t.next,e=e.prev,i--}return this}setHead(t){let e=this._head;return e?(e.value=t,e):this.prepend(t)}setNth(t,e){let i=this.nthCell(t);return!i&&Vi(t),i.value=e,i}setTail(t){let e=this.tail;return e?(e.value=t,e):this.append(t)}swap(t,e){if(t!==e){let i=t.value;t.value=e.value,e.value=i}return this}toArray(t=[]){return this.traverse(e=>(t.push(e.value),!0)),t}toJSON(){return this.toArray()}toString(){let t=[];return this.traverse(e=>(t.push(String(e.value)),!0)),t.join(", ")}traverse(t,e=this._head,i){if(!this._head)return;let r=e;do{if(!t(r))break;r=r.next}while(r!==i);return r}_map(t,e){return this.traverse(i=>(t.append(e(i.value)),!0)),t}};function*qr(c,t){for(;t;)yield t.value,t=t[c]}var ri=class c extends ii{_tail;constructor(t){super(),t&&this.into(t)}get tail(){return this._tail}append(t){if(this._tail){let e={value:t,prev:this._tail};return this._tail.next=e,this._tail=e,this._length++,e}else return this.prepend(t)}asHead(t){return t===this._head?this:(this.remove(t),this._head.prev=t,t.next=this._head,t.prev=void 0,this._head=t,this._length++,this)}asTail(t){return t===this._tail?this:(this.remove(t),this._tail.next=t,t.prev=this._tail,t.next=void 0,this._tail=t,this._length++,this)}cons(t){return this.prepend(t),this}copy(){return new c(this)}*cycle(){for(;;)yield*this}drop(){let t=this._head;if(t)return this._head=t.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,t.value}empty(){return new c}insertAfter(t,e){let i={value:e,next:t.next,prev:t};return t.next?t.next.prev=i:this._tail=i,t.next=i,this._length++,i}insertAfterNth(t,e){return t<0&&(t+=this._length),t>=this._length-1?this.append(e):(Je(t,0,this._length),this.insertAfter(this.nthCellUnsafe(t),e))}insertBefore(t,e){let i={value:e,next:t,prev:t.prev};return t.prev?t.prev.next=i:this._head=i,t.prev=i,this._length++,i}insertBeforeNth(t,e){return t<0&&(t+=this._length),t<=0?this.prepend(e):(Je(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new c,t)}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCell(t){if(t<0&&(t+=this._length),!(t<0||t>=this._length))return this.nthCellUnsafe(t)}pop(){let t=this._tail;if(t)return this._tail=t.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,t.value}prepend(t){let e={value:t,next:this._head};return this._head?this._head.prev=e:this._tail=e,this._head=e,this._length++,e}push(t){return this.append(t),this}release(){return this._tail=void 0,super.release()}remove(t){return t.prev?t.prev.next=t.next:this._head=t.next,t.next?t.next.prev=t.prev:this._tail=t.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let t=this.peek();return this.pop(),this.prepend(t),this}}seq(t=0,e=this.length){if(t>=e||t<0)return;let i=this.nthCell(t),r=this.nthCell(e-1),n=s=>({first(){return s.value},next(){return s!==r&&s.next?n(s.next):void 0}});return i?n(i):void 0}shuffle(t,e=Er){if(this._length<2)return this;for(t=t!==void 0?t:Math.ceil(1.5*Math.log2(this._length));t>0;t--){let i=this._head;for(;i;){let r=i.next;e.probability(.5)?this.asHead(i):this.asTail(i),i=r}}return this}slice(t=0,e=this.length){let i=t<0?t+this._length:t,r=e<0?e+this._length:e;(i<0||r<0)&&Rr("invalid indices: ${from} / ${to}");let n=new c,s=this.nthCell(i);for(;s&&++i<=r;)n.push(s.value),s=s.next;return n}sort(t=me){if(!this._length)return this;let e=1;for(;;){let i=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;i;){r++;let n=i,s=0;for(let o=0;o<e&&(s++,n=n.next,!!n);o++);let a=e;for(;s>0||a>0&&n;){let o;s===0?(o=n,n=n.next,a--):!n||a===0||t(i.value,n.value)<=0?(o=i,i=i.next,s--):(o=n,n=n.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}i=n}if(this._tail.next=void 0,r<=1)return this;e*=2}}splice(t,e=0,i){let r;typeof t=="number"?(t<0&&(t+=this._length),Je(t,0,this._length),r=this.nthCellUnsafe(t)):r=t;let n=new c;if(e>0)for(;r&&e-- >0;)this.remove(r),n.push(r.value),r=r.next;else r&&(r=r.next);if(i)if(r)for(let s of i)this.insertBefore(r,s);else for(let s of i)this.push(s);return n}};var ni=class c{map;items;opts;_size;constructor(t,e){let i={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...e};this.map=i.map(),this.items=new ri,this._size=0,this.opts=i,t&&this.into(t)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let t of this.items)yield[t.k,t]}*keys(){for(let t of this.items)yield t.k}*values(){for(let t of this.items)yield t.v}copy(){let t=this.empty();t.items=this.items.copy();let e=t.items.head;for(;e;)t.map.set(e.value.k,e),e=e.next;return t}empty(){return new c(null,this.opts)}release(){this._size=0,this.map.clear();let t=this.opts.release;if(t){let e;for(;e=this.items.drop();)t(e.k,e.v);return!0}return this.items.release()}has(t){return this.map.has(t)}get(t,e){let i=this.map.get(t);return i?this.resetEntry(i):e}set(t,e){let i=this.opts.ksize(t)+this.opts.vsize(e),r=this.map.get(t),n=Math.max(0,i-(r?r.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(r,t,e,i):this._size-=n,e}into(t){for(let e of t)this.set(e[0],e[1]);return this}async getSet(t,e){let i=this.map.get(t);return i?this.resetEntry(i):this.set(t,await e())}delete(t){let e=this.map.get(t);return e?(this.removeEntry(e),!0):!1}resetEntry(t){return this.items.asTail(t),t.value.v}ensureSize(){let{release:t,maxsize:e,maxlen:i}=this.opts;for(;this._size>e||this.length>=i;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),t?.(r.k,r.v),this._size-=r.s}return!0}removeEntry(t){let e=t.value;this.map.delete(e.k),this.items.remove(t),this.opts.release?.(e.k,e.v),this._size-=e.s}doSetEntry(t,e,i,r){t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=r,this.items.asTail(t)):(this.items.push({k:e,v:i,s:r}),this.map.set(e,this.items.tail))}};var Bt=class c extends ni{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new c(null,this.opts)}has(t){return this.get(t)!==void 0}get(t,e){let i=this.map.get(t);if(i){if(i.value.t>=Date.now())return this.resetEntry(i);this.removeEntry(i)}return e}set(t,e,i=this.opts.ttl){let r=this.opts.ksize(t)+this.opts.vsize(e),n=this.map.get(t),s=Math.max(0,r-(n?n.value.s:0));return this._size+=s,this.ensureSize()?this.doSetEntry(n,t,e,r,i):this._size-=s,e}async getSet(t,e,i=this.opts.ttl){let r=this.get(t);return r!==void 0?r:this.set(t,await e(),i)}prune(){let t=Date.now(),e=this.items.head,i=0;for(;e;)e.value.t<t&&(this.removeEntry(e),i++),e=e.next;return i}ensureSize(){let{maxlen:t,maxsize:e}=this.opts,i=Date.now(),r=this.items.head;for(;r&&(this._size>e||this.length>=t);)r.value.t<i&&this.removeEntry(r),r=r.next;return super.ensureSize()}doSetEntry(t,e,i,r,n=this.opts.ttl){let s=Date.now()+n;t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=r,t.value.t=s,this.items.asTail(t)):(this.items.push({k:e,v:i,s:r,t:s,ttl:n}),this.map.set(e,this.items.tail))}resetEntry(t){return this.opts.autoExtend&&(t.value.t=Date.now()+t.value.ttl),super.resetEntry(t)}};var de=class{debug;constructor(t){this.debug=t||!1}log(t,e,i){this.debug&&console.log(t,e,i)}scope(t,e,i,r){let n=new Map,s=r!==void 0?new Bt(null,{ttl:r}):new Bt;return{get:(...u)=>{let p=i(...u);if(n.has(p)){this.log("[live]",t,p);let m=n.get(p);return Promise.resolve(m)}if(s.has(p))return this.log("[memo]",t,p),s.get(p);this.log("[fetch]",t,p);let d=e(...u).catch(m=>{throw s.delete(p),m});return s.set(p,d),d},set:(u,...p)=>{let d=i(...p);this.log("[set-live]",t,d),n.set(d,u)},clear:()=>{this.log("[clear]",t),n.clear(),s.release()}}}};var si=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let i=0;i<t.length;++i){let[r,n]=t[i];this.result.set(this.getKey(n,r),e[i].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,i,r){let n=this.getKey(t,e),s=this.getKey(t,i),a=this.result.get(n)??0n,o=this.result.get(s)??0n;if(a<r)throw new Error("Attempting to transfer more than is present");this.result.set(n,a+r),this.result.set(s,o+r)}};var xt=wt(require("big.js")),lt=require("@galacticcouncil/math-liquidity-mining");var zi=wt(require("big.js")),Yi=(0,zi.default)(10).pow(18),Nr=BigInt((0,zi.default)(1).pow(18).toString()),Hr=6e3;var os="1000000000000000000",ai=class{constructor(t,e,i){this.getAccount=t;this.getAsset=e;this.multiCurrency=i}async syncGlobalFarm(t,e,i){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let r=await this.getAsset(t.reward_currency),n=e-t.updated_at,s=this.getAccount(t.id),a=r?.existential_deposit;if(!a)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,s),l=(0,xt.default)(a.toString()),u=(0,xt.default)(o.toString()).minus(l.lt(o.toString())?a.toString():o.toString()),p=(0,xt.default)((0,lt.calculate_global_farm_rewards)(t.total_shares_z.toString(),i.toString(),(0,xt.default)(t.yield_per_period.toString()).mul(Yi).round(0,xt.default.roundDown).toFixed(),t.max_reward_per_period.toString(),n.toFixed()));if(u.lt(p)&&(p=u),p.eq(0))return t;let d=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,s,d,BigInt(p.toFixed())),{...t,accumulated_rpz:BigInt((0,lt.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),p.toFixed()))}}syncYieldFarm(t,e,i){if(t.state.type!=="Active"||t.updated_at===i)return t;if(t.total_valued_shares===0n)return{...t,updated_at:i};let r=(0,lt.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(r),updated_at:i}}getLoyaltyMultiplier(t,e){let i=(0,xt.default)(1).mul(Yi).round(0,xt.default.roundDown).toString();if(!e)return i;let{initial_reward_percentage:r,scale_coef:n}=e;return(0,lt.calculate_loyalty_multiplier)(t.toFixed(),r.toString(),n.toFixed())}async claimRewards(t,e,i,r,n){if(e.state.type==="Terminated")return null;let s=Math.floor(r/t.blocks_per_period);if(i.updated_at===s)return null;let a=await this.syncGlobalFarm(t,s,n);if(!a)return null;let o=this.syncYieldFarm(e,a,s);if(!o)return null;let l=o.total_stopped-i.stopped_at_creation,u=o.updated_at-i.entered_at-l,p=this.getLoyaltyMultiplier(u,o.loyalty_curve),d=BigInt((0,lt.calculate_user_reward)(i.accumulated_rpvs.toString(),i.valued_shares.toString(),i.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),m=BigInt((0,lt.calculate_user_reward)(i.accumulated_rpvs.toString(),i.valued_shares.toString(),i.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),os));return{reward:d,maxReward:m,assetId:a.reward_currency,yieldFarmId:o.id,isActiveFarm:o.state.type==="Active"}}};var ls=(0,Y.default)(365.2425).times(24).times(60).times(60),he=class{balance;client;options;constructor(t,e,i={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:i.blockTime??Hr})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let i=[t,e].sort((n,s)=>n-s);if(t===e)return Nr;let r=await this.client.getOraclePrice(i);if(r){let{n,d:s}=r[0].price,a;return t<e?a=(0,$i.fixed_from_rational)(n.toString(),s.toString()):a=(0,$i.fixed_from_rational)(s.toString(),n.toString()),BigInt(a)}}getFarmAddress=(t,e)=>{let i=Buffer.from("modl","utf-8"),r=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),n=Buffer.from([t]),s=Buffer.concat([i,r,n]),o="0x"+Buffer.concat([s,Buffer.alloc(32-s.length)]).toString("hex");return(0,Gr.AccountId)(Pt.HYDRATION_SS58_PREFIX).dec(o)};getGlobalRewardPerPeriod(t,e,i,r){let n=(0,Y.default)(r).times(t.toString()).times(e.toString()).div(Math.pow(10,Pt.RUNTIME_DECIMALS));return n.gte(i.toString())?i.toString():n.toString()}getPoolYieldPerPeriod(t,e,i,r){let n=(0,Y.default)(t.toString()).times(e),s=(0,Y.default)(i.toString()).times(r);return n.div(s.toString()).toString()}farmData(t,e,i){let{yieldFarm:r,globalFarm:n,priceAdjustment:s,balance:a,id:o}=t,{multiplier:l,loyalty_curve:u}=r,{blocks_per_period:p,yield_per_period:d,total_shares_z:m,max_reward_per_period:g,pending_rewards:b,accumulated_paid_rewards:h,planned_yielding_periods:P,updated_at:f,incentivized_asset:v,reward_currency:S,price_adjustment:T,min_deposit:B}=n,N=I.shiftNeg(s??T,Pt.RUNTIME_DECIMALS),W=I.shiftNeg(l,Pt.RUNTIME_DECIMALS),ut=I.shiftNeg(u?.initial_reward_percentage??0,Pt.RUNTIME_DECIMALS),bt=ls.div((0,Y.default)(this.blockTime).div(1e3).times(p)).toString(),Z;if(m<=0)Z=(0,Y.default)(W).times(d.toString()).times(bt).div(Math.pow(10,Pt.RUNTIME_DECIMALS)).toString();else{let In=this.getGlobalRewardPerPeriod(m,d,g,N),_n=this.getPoolYieldPerPeriod(In,W,m,N);Z=(0,Y.default)(_n).times(bt).toString()}let nt=b+h,ee=g*BigInt(P),Le=a.transferable+nt,br=Le-nt,qe=(0,Y.default)(br.toString()).div(g.toString()),Ne=(0,Y.default)(e).div(p.toString()).toString(),He=(m>=0?qe.plus(f):qe.plus(Ne)).toString(),Ii=(0,Y.default)(He).times(p).toString(),xn=(0,Y.default)(m.toString()).div((0,Y.default)(g.toString()).div(d.toString())).div(Math.pow(10,Pt.RUNTIME_DECIMALS)).times(100).times(N).toFixed(2),yr=(0,Y.default)(nt.toString()).div(Le.toString()).gte(.999);Z=yr?"0":(0,Y.default)(Z).div(i?2:1).times(100).toString();let Tn=ut?(0,Y.default)(Z).times(ut).toString():void 0;return{apr:Z,minApr:Tn,isDistributed:yr,estimatedEndPeriod:He,estimatedEndBlock:Ii,maxRewards:ee,incentivizedAsset:v,rewardCurrency:S,loyaltyCurve:u,currentPeriod:Ne,potMaxRewards:Le,fullness:xn,yieldFarmId:r.id,globalFarmId:n.id,poolId:o,distributedRewards:nt,plannedYieldingPeriods:P,minDeposit:B,blocksPerPeriod:p}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((r,n)=>r.includes(n.keyArgs[0].toString())?r:[...r,n.keyArgs[0].toString()],[]),i=await Promise.all(e.map(async r=>{let n=await this.getOmnipoolFarms(r);if(n)return[r,n]}));return Object.fromEntries(i.filter(r=>!!r))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),i=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:n,value:s})=>{let[,a]=n,o=s,l=await this.client.getOmnipoolGlobalFarm(a),u=await this.client.getOmnipoolYieldFarm(Number(t),a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a),g=await this.getOraclePrice(p,d),b=await this.balance.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:g,balance:b}}));return i?r.map(n=>n?this.farmData(n,i):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((r,n)=>r.includes(n.keyArgs[0].toString())?r:[...r,n.keyArgs[0].toString()],[]),i=await Promise.all(e.map(async r=>{let n=await this.getIsolatedFarms(r);if(n)return[r,n]}));return Object.fromEntries(i.filter(r=>!!r))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),i=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:n,value:s})=>{let[,a]=n,o=s,l=await this.client.getIsolatedGlobalFarm(a),u=await this.client.getIsolatedYieldFarm(t,a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a,!0),g=await this.getOraclePrice(p,d),b=await this.balance.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:g,balance:b,farmAddress:m}}));return i?r.map(n=>n?this.farmData(n,i,!0):void 0):[]}async getDepositReward(t,e,i,r){let n=e.global_farm_id,s=e.yield_farm_id,a=i?await this.client.getIsolatedYieldFarm(t,n,s):await this.client.getOmnipoolYieldFarm(Number(t),n,s),o=i?await this.client.getIsolatedGlobalFarm(n):await this.client.getOmnipoolGlobalFarm(n);if(!o||!a)return;let l=o.reward_currency,u=o.incentivized_asset,p=[[this.getFarmAddress(0,i),o.reward_currency],[this.getFarmAddress(o.id,i),o.reward_currency]],d=await this.getAccountAssetBalances(p),m=await this.getOraclePrice(l,u),g=new si(p,d),h=await new ai(f=>this.getFarmAddress(f),f=>this.client.getAsset(f),g).claimRewards(o,a,e,r,m??o.price_adjustment);if(!h)return;let P=await this.client.getAsset(h.assetId);if(P&&!(h.reward<=P.existential_deposit))return h}async getAccountAssetBalances(t){let[e,i]=await Promise.all([Promise.all(t.filter(([n,s])=>s!==0).map(([n,s])=>this.balance.getTokenBalance(n,s))),Promise.all(t.filter(([n,s])=>s===0).map(([n])=>this.balance.getSystemBalance(n)))]),r=[];for(let n=0,s=0;n+s<t.length;){let a=n+s,[,o]=t[a];o===0?(r.push(i[s]),s+=1):(r.push(e[n]),n+=1)}return r}};var ge=require("polkadot-api"),cs=ge.Binary.toHex(ge.Binary.fromText("omnipool")),be=class extends D{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(cs,t,(0,ge.Enum)("TenMinutes"))}async getRelayBlockNumber(){return(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number}async getAllOmnipooFarms(){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries()}async getOmnipooFarms(t){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries(t)}async getOmnipoolGlobalFarm(t){return this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getOmnipoolYieldFarm(t,e,i){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,i,{at:"best"})}async getAllIsolatedFarms(){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries()}async getIsolatedFarms(t){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries(t)}async getIsolatedGlobalFarm(t){return this.api.query.XYKWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getIsolatedYieldFarm(t,e,i){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,i,{at:"best"})}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};var rr={};C(rr,{PoolContextProvider:()=>jt,PoolError:()=>Tt,PoolFactory:()=>Kt,PoolType:()=>F,SnapshotPoolCtxProvider:()=>bi,aave:()=>tr,hsm:()=>ir,lbp:()=>Ki,omni:()=>Qi,stable:()=>Ji,xyk:()=>Zi});var Ki={};C(Ki,{LbpMath:()=>ct,LbpPool:()=>ye,LbpPoolClient:()=>fe});var ht=require("@galacticcouncil/math-lbp"),ct=class{static getSpotPrice(t,e,i,r,n){return(0,ht.get_spot_price)(t,e,i,r,n)}static calculateInGivenOut(t,e,i,r,n){return(0,ht.calculate_in_given_out)(t,e,i,r,n)}static calculateOutGivenIn(t,e,i,r,n){return(0,ht.calculate_out_given_in)(t,e,i,r,n)}static calculateLinearWeights(t,e,i,r,n){return(0,ht.calculate_linear_weights)(t,e,i,r,n)}static calculatePoolTradeFee(t,e,i){return(0,ht.calculate_pool_trade_fee)(t,e,i)}};var Vt=require("@galacticcouncil/common");var F=(s=>(s.Aave="Aave",s.LBP="LBP",s.Omni="Omnipool",s.Stable="Stableswap",s.XYK="XYK",s.HSM="HSM",s))(F||{}),Tt=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(Tt||{});var{FeeUtils:Ur}=I,ye=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(s=>[s.id,s])),r=i.get(t),n=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:n.balance,decimalsIn:r.decimals,decimalsOut:n.decimals,weightIn:r.weight,weightOut:n.weight}}validateAndBuy(t,e,i){let r=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let s=t.balanceOut/this.maxOutRatio;if(e>s&&n.push("MaxOutRatioExceeded"),r===t.assetOut){let a=this.calculateTradeFee(e,i),o=Ur.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return u>p&&n.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:n}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&n.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:n}}}validateAndSell(t,e,i){let r=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let s=t.balanceIn/this.maxInRatio;if(e>s&&n.push("MaxInRatioExceeded"),r===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:n}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,i),l=Ur.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),u=a-o,p=t.balanceOut/this.maxOutRatio;return u>p&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:n}}}calculateInGivenOut(t,e){let i=ct.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}calculateOutGivenIn(t,e){let i=ct.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}spotPriceInGivenOut(t){let e=ct.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),Vt.big.toBigInt(1,Vt.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=ct.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),Vt.big.toBigInt(1,Vt.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let i=ct.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var Yr=require("polkadot-api"),It=require("rxjs");var Vr=(c,t=new Map)=>e=>{let i;return t.has(e)?t.get(e):(t.set(e,i=c(e)),i)};var _=require("rxjs"),y=require("rxjs/operators");var Wr=require("rxjs"),oi=class{store$=new Wr.BehaviorSubject([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(t){return this.changeset.size===0?[]:t.filter(e=>this.changeset.has(e.address))}set(t){this.changeset=new Set(t.map(e=>e.address)),this.store$.next(t)}update(t){this.updateQueue=this.updateQueue.then(async()=>{let e=this.store$.value,i=new Map(e.map((a,o)=>[a.address,o])),r=await t(e),n=e.slice(),s=new Set;for(let a of r){let o=i.get(a.address);o===void 0?(i.set(a.address,n.length),n.push(a)):n[o]=a,s.add(a.address)}this.changeset=s,this.store$.next(n)}).catch(console.error)}destroy(){this.store$.complete()}};var zr=require("@galacticcouncil/common");var us={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:li}=zr.log,ci=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${us[this.type]})`,10)}trace(t,...e){li.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){li.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){li.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){li.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:ps}=pe,ms=3e3,Q=class extends D{evm;balance;store=new oi;log;shared$;resync$=new _.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new Bt(null,{ttl:6*1e3});memPools=Vr(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e,i){super(t,i),this.evm=e,this.balance=new pt(t,i),this.log=new ci(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){let e=(await this.getMemPools()).filter(i=>this.hasValidAssets(i));return this.store.set(e),e}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe((0,y.startWith)([]),(0,y.bufferCount)(2,1),(0,y.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,y.filter)(t=>t.length>0),(0,y.throttleTime)(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return(0,_.defer)(()=>{let t=new _.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,y.switchMap)(()=>{let e=new _.Subscription;return(0,_.from)(ps(this.getMemPools(),6e4,"getMemPools stalled")).pipe((0,y.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,y.map)(r=>r.filter(n=>this.hasValidAssets(n))),(0,y.tap)(r=>this.store.set(r)),(0,y.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),_.EMPTY))).pipe((0,y.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,y.switchMap)(r=>(0,_.merge)((0,_.of)(r),this.store.asObservable().pipe((0,y.skip)(1)))),(0,y.finalize)(()=>{e.unsubscribe()}))}),(0,y.finalize)(()=>t.unsubscribe()))}).pipe((0,y.share)({connector:()=>new _.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:i}=e,r=[this.balance.watchTokensBalance(i)];if(this.hasSystemAsset(e)){let n=this.balance.watchSystemBalance(i);r.push(n)}if(this.hasErc20Asset(e)){let n=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),s=this.balance.watchErc20Balance(i,n);r.push(s)}return(0,_.combineLatest)(r).pipe((0,y.map)(n=>n.flat()),(0,y.pairwise)(),(0,y.map)(([n,s])=>this.balance.getDeltas(n,s)),(0,y.filter)(n=>n.length>0),(0,y.map)(n=>[i,n]))});return(0,_.merge)(...t).pipe((0,y.bufferTime)(250),(0,y.filter)(e=>e.length>0),(0,y.map)(e=>new Map(e)),this.watchGuard("balances")).subscribe(e=>{this.store.update(i=>this.updateBalances(i,e))})}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:i})=>t.type==="XYK"?i>0n&&!!e:!!e)}updateBalances=(t,e)=>{let i=[],r=new Map(t.map(n=>[n.address,n]));for(let[n,s]of e){let a=r.get(n);if(a){let o=a.tokens.map(l=>{let u=s.find(p=>p.id===l.id);return u&&l.id!==a.id?{...l,balance:u.balance.transferable}:l});i.push({...a,tokens:o})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<ms||(this.resyncAt=e,this.mem++,this.resync$.next())}requestResync(t=!1){this.resyncPending||(this.resyncPending=!0,setTimeout(()=>{this.resyncPending=!1,this.resync(t)},0))}startWatchdog(){let r=this.watcher.connection$.pipe((0,y.pairwise)(),(0,y.filter)(([a,o])=>a==="offline"&&o==="online"),(0,y.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,y.catchError)(a=>(this.log.error("watchdog_recovery_error",a),_.EMPTY)),(0,y.repeat)({delay:1e3})),n=this.watcher.finalizedBlock$.pipe((0,y.pairwise)(),(0,y.tap)(([a,o])=>{let l=Number(a.number),u=Number(o.number),p=u-l;p>=3&&(this.log.debug("watchdog_gap",{from:l,to:u,gap:p}),this.requestResync())}),(0,y.catchError)(a=>(this.log.error("watchdog_gap_error",a),_.EMPTY)),(0,y.repeat)({delay:1e3})),s=(0,_.interval)(36e5).pipe((0,y.tap)(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),(0,y.catchError)(a=>(this.log.error("watchdog_periodic_error",a),_.EMPTY)),(0,y.repeat)({delay:1e3}));return(0,_.merge)(r,n,s).subscribe()}watchGuard(t){return e=>e.pipe((0,y.tap)({error:i=>{this.log.error(t,i),this.requestResync(!0)}}),(0,y.finalize)(()=>{this.log.debug(t,"unsub")}),(0,y.catchError)(()=>_.EMPTY))}};var fe=class extends Q{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}getPoolWeights(t,e){let{start:i,end:r,initial_weight:n,final_weight:s}=t,a=ct.calculateLinearWeights(i?i.toString():"0",r?r.toString():"0",n.toString(),s.toString(),e.toString()),o=BigInt(a),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){return(await this.api.getStaticApis()).compat.query.LBP.PoolData.isCompatible(Yr.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:this.at}),this.api.query.ParachainSystem.ValidationData.getValue({at:this.at}),this.getPoolLimits()]),r=e?.relay_parent_number||0,n=t.filter(({value:s})=>e&&this.isActivePool(s,r)).map(async({keyArgs:s,value:a})=>{let[o]=s,l=o.toString(),u=await this.getPoolDelta(l,a,r);return{address:l,type:"LBP",fee:a.fee,...u,...i}});return Promise.all(n)}async getPoolDelta(t,e,i){let{assets:r,repay_target:n,fee_collector:s}=e,[a,o]=this.getPoolWeights(e,i),[l,u]=r,[p,d,m,g,b]=await Promise.all([this.isRepayFeeApplied(l,n,s.toString()),this.balance.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l,{at:this.at}),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u,{at:this.at})]);return{repayFeeApply:p,tokens:[{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,weight:a,type:m?.asset_type.type},{id:u,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:g.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(t,e){let{start:i,end:r}=t;return i&&r?e>=i&&e<r:!1}async isRepayFeeApplied(t,e,i){if(e===0n)return!1;try{return(await this.balance.getBalance(i,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let i=this.store.pools.find(n=>n.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:i.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue({at:"best"}).pipe((0,It.map)(({value:t})=>t),(0,It.filter)(t=>t!==void 0),(0,It.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let i=[];for(let r of e){let n=this.poolsData.get(r.address);if(n){let{assets:s,repay_target:a,fee_collector:o}=n,[l]=s,[u,p]=this.getPoolWeights(n,t),[d,m]=r.tokens,g=[{...d,weight:u},{...m,weight:p}],b=await this.isRepayFeeApplied(l,a,o.toString());i.push({...r,tokens:g,repayFeeApply:b})}}return i})})}subscribeUpdates(){let t=new It.Subscription;return t.add(this.subscribeValidationData()),t}};var Qi={};C(Qi,{OmniMath:()=>R,OmniPool:()=>Pe,OmniPoolClient:()=>Se,OmniPoolFee:()=>Rt,getEmaKey:()=>ui,getEmaPair:()=>Wt});var x=require("@galacticcouncil/math-omnipool"),Ft=wt(require("big.js")),R=class{static calculateSpotPrice(t,e,i,r){return(0,x.calculate_spot_price)(t,e,i,r)}static calculateLrnaSpotPrice(t,e){return(0,x.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,i,r,n,s,a,o,l,u){return(0,x.calculate_in_given_out)(t,e,i,r,n,s,a,o,l,u)}static calculateLrnaInGivenOut(t,e,i,r,n,s){return(0,x.calculate_lrna_in_given_out)(t,e,i,r,n,s)}static calculateOutGivenIn(t,e,i,r,n,s,a,o,l,u){return(0,x.calculate_out_given_in)(t,e,i,r,n,s,a,o,l,u)}static calculateOutGivenLrnaIn(t,e,i,r,n,s){return(0,x.calculate_out_given_lrna_in)(t,e,i,r,n,s)}static calculateShares(t,e,i,r){return(0,x.calculate_shares)(t,e,i,r)}static calculateLiquidityOut(t,e,i,r,n,s,a,o){return(0,x.calculate_liquidity_out)(t,e,i,r,n,s,a,o)}static calculateLiquidityLRNAOut(t,e,i,r,n,s,a,o){return(0,x.calculate_liquidity_lrna_out)(t,e,i,r,n,s,a,o)}static calculateCapDifference(t,e,i,r){let n=(0,Ft.default)(e),s=(0,Ft.default)(t),a=(0,Ft.default)(r),o=(0,Ft.default)(i),l=(0,Ft.default)(10).pow(18),u=o.div(l);if(n.div(a).lt(u)){let d=u.times(a).minus(n).times(s),m=n.times((0,Ft.default)(1).minus(u));return d.div(m).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,r){return(0,x.calculate_liquidity_hub_in)(t,e,i,r)}static isSellAllowed(t){return(0,x.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,x.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,x.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,x.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,i,r,n,s,a,o,l,u,p){return(0,x.recalculate_asset_fee)(t,e,i,r,n,s,a,o,l,u,p)}static recalculateProtocolFee(t,e,i,r,n,s,a,o,l,u,p){return(0,x.recalculate_protocol_fee)(t,e,i,r,n,s,a,o,l,u,p)}static verifyAssetCap(t,e,i,r){return(0,x.verify_asset_cap)(t,e,i,r)}};var $r=require("@galacticcouncil/common");var{FeeUtils:gt}=I,Pe=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let i=new Map(this.tokens.map(s=>[s.id,s])),r=i.get(t),n=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:r.hubReserves,hubReservesOut:n.hubReserves,sharesIn:r.shares,sharesOut:n.shares,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:r.balance,balanceOut:n.balance,tradeableIn:r.tradeable,tradeableOut:n.tradeable,assetInEd:r.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,i),s=r===0n?0:z.calculateBuyFee(r,n),a=[],o=R.isSellAllowed(t.tradeableIn),l=R.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return n>p&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:r,amountOut:e,feePct:s,errors:a}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),s=z.calculateSellFee(r,n),a=[],o=R.isSellAllowed(t.tradeableIn),l=R.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return n>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:n,feePct:s,errors:a}}calculateInGivenOut(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,i);let r=R.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?gt.toRaw(i.assetFee).toString():"0",i?gt.toRaw(i.protocolFee).toString():"0",i?gt.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(r);return n<0n?0n:n}calculateLrnaInGivenOut(t,e,i){let r=R.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?gt.toRaw(i.assetFee).toString():"0",i?gt.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(r);return n<0n?0n:n}calculateOutGivenIn(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,i);let r=R.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?gt.toRaw(i.assetFee).toString():"0",i?gt.toRaw(i.protocolFee).toString():"0",i?gt.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(r);return n<0n?0n:n}calculateOutGivenLrnaIn(t,e,i){let r=R.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?gt.toRaw(i.assetFee).toString():"0",i?gt.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(r);return n<0n?0n:n}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=R.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceLrnaInGivenOut(t){let e=R.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=R.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}spotPriceOutGivenLrnaIn(t){let e=R.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,i){let r=e-i;if(r===0)return t;let n=$r.big.pow10(Math.abs(r));return r>0?t*n:t/n}};var St=require("polkadot-api"),jr=require("@polkadot-api/utils"),A=require("rxjs"),Qr=require("@galacticcouncil/common");var{FeeUtils:G}=I,Rt=class c{static compute(t,e,i,r,n,s,a,o){let l=t.assetIn,[u,p,d]=c.getAssetFee(t,e,i,r,s),m=0,g=0,b=0;l!==1&&([m,g,b]=c.getProtocolFee(t,e,i,n,a));let h=u+m,P=d+b;return{assetFee:G.fromPermill(p),protocolFee:G.fromPermill(g),maxSlipFee:G.fromPermill(o),min:G.fromPermill(h),max:G.fromPermill(P)}}static getAssetFee(t,e,i,r,n){let{assetOut:s,balanceOut:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=n;if(!i||!r)return[o,o,l];let d=G.fromPermill(o),m=G.fromPermill(l),[g]=r,{asset_fee:b,timestamp:h}=i,P=Math.max(1,e-h),f=g.volume.b_in.toString(),v=g.volume.b_out.toString(),S=g.liquidity.b.toString();s===0&&(f=g.volume.a_in.toString(),v=g.volume.a_out.toString(),S=g.liquidity.a.toString());let T=G.fromPermill(b),B=R.recalculateAssetFee(f,v,S,"9",a.toString(),G.toRaw(T).toString(),P.toString(),G.toRaw(d).toString(),G.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(B)*1e6,l]}static getProtocolFee(t,e,i,r,n){let{assetIn:s,balanceIn:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=n;if(!i||!r)return[o,o,l];let d=G.fromPermill(o),m=G.fromPermill(l),[g]=r,{protocol_fee:b,timestamp:h}=i,P=Math.max(1,e-h),f=g.volume.b_in.toString(),v=g.volume.b_out.toString(),S=g.liquidity.b.toString();s===0&&(f=g.volume.a_in.toString(),v=g.volume.a_out.toString(),S=g.liquidity.a.toString());let T=G.fromPermill(b),B=R.recalculateProtocolFee(f,v,S,"9",a.toString(),G.toRaw(T).toString(),P.toString(),G.toRaw(d).toString(),G.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(B)*1e6,l]}};var Wt=c=>c===0?[0,1]:[1,c],ui=c=>Wt(c).join(":");var{FeeUtils:ji}=I,Xr=St.Binary.toHex(St.Binary.fromText("omnipool")),Kr=(0,St.Enum)("Short"),Se=class extends Q{queryBus=new de;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:this.at}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:this.at}),t=>String(t),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:this.at}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(Xr,t,Kr,{at:this.at}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,jr.toHex)(e);return(0,St.AccountId)(Qr.HYDRATION_SS58_PREFIX).dec(i)}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Omnipool.Assets.isCompatible(St.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,r,n,s,a,o]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:this.at}),this.api.query.Omnipool.HubAssetTradability.getValue({at:this.at}),this.api.query.AssetRegistry.Assets.getValue(t,{at:this.at}),this.balance.getBalance(e,t),this.getPoolLimits(),this.api.query.System.Number.getValue({at:this.at})]);this.block=o;let l=i.map(async({keyArgs:p,value:d})=>{let[m]=p,{hub_reserve:g,shares:b,tradable:h,cap:P,protocol_shares:f}=d,[v,S]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m,{at:this.at}),this.balance.getBalance(e,m)]);return{id:m,decimals:v?.decimals,existentialDeposit:v?.existential_deposit,balance:S.transferable,cap:P,hubReserves:g,protocolShares:f,shares:b,tradeable:h,type:v?.asset_type.type}}),u=await Promise.all(l);return u.push({id:t,decimals:n?.decimals,existentialDeposit:n?.existential_deposit,balance:s.transferable,tradeable:r,type:n?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:u,...a}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,n=await this.maxSlipFee.get()??0,s=await this.dynamicFeesConfig.get(e);if(s?.type==="Fixed"){let{asset_fee:d,protocol_fee:m}=s.value;return{assetFee:ji.fromPermill(d),protocolFee:ji.fromPermill(m),maxSlipFee:ji.fromPermill(n)}}let[a,o,l,u,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(Wt(e)),this.emaOracles.get(Wt(i)),s?s.value.asset_fee_params:this.api.constants.DynamicFees.AssetFeeParameters(),s?s.value.protocol_fee_params:this.api.constants.DynamicFees.ProtocolFeeParameters()]);return Rt.compute(t,this.block,a,o,l,u,p,n)}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(r=>r.id).map(r=>Wt(r)).map(r=>this.api.query.EmaOracle.Oracles.watchValue(Xr,r,Kr,{at:"best"}).pipe((0,A.map)(({value:n})=>n),(0,A.filter)(n=>n!==void 0),(0,A.map)((n,s)=>({value:n,index:s})),(0,A.tap)(({index:n})=>{n>0&&this.log.trace("emaOracle.Oracles",r.join(":"))}),(0,A.map)(({value:n})=>({pair:r,value:n}))));return(0,A.merge)(...i).pipe((0,A.finalize)(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(r=>{let{pair:n,value:s}=r;this.emaOracles.set(s,n)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,A.distinctUntilChanged)((t,e)=>!e.deltas),(0,A.map)((t,e)=>({value:t,index:e})),(0,A.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),(0,A.finalize)(()=>this.dynamicFees.clear()),this.watchGuard("dynamicFees.AssetFee")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFees.set(e.value,i)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe((0,A.distinctUntilChanged)((t,e)=>!e.deltas),(0,A.map)((t,e)=>({value:t,index:e})),(0,A.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),(0,A.finalize)(()=>this.dynamicFeesConfig.clear()),this.watchGuard("dynamicFees.AssetFeeConfiguration")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFeesConfig.set(e.value,i)})})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,A.distinctUntilChanged)((t,e)=>!e.deltas),(0,A.map)((t,e)=>({value:t,index:e})),(0,A.tap)(({value:t,index:e})=>{e>0&&this.log.trace("omnipool.Assets",t.deltas?.upserted)}),this.watchGuard("omnipool.Assets")).subscribe(({value:{deltas:t}})=>{this.store.update(([e])=>{let i=t?.upserted.reduce((n,s)=>{let[a]=s.args;return n.set(a,s.value),n},new Map),r=e.tokens.map(n=>{let s=i?.get(n.id);return s?this.updateTokenState(n,s):n});return[{...e,tokens:r}]})})}subscribeUpdates(){let t=new A.Subscription;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:i,shares:r,tradable:n,cap:s,protocol_shares:a}=e;return{...t,cap:s,hubReserves:i,protocolShares:a,shares:r,tradeable:n}}};var Ji={};C(Ji,{StableMath:()=>$,StableSwap:()=>Ct,StableSwapClient:()=>we});var k=require("@galacticcouncil/math-stableswap"),$=class{static getPoolAddress(t){return(0,k.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let i=0;i<t;i++)e.push(["1","1"]);return e}static calculateAmplification(t,e,i,r,n){return(0,k.calculate_amplification)(t,e,i,r,n)}static calculateInGivenOut(t,e,i,r,n,s,a){return(0,k.calculate_in_given_out)(t,e,i,r,n,s,a)}static calculateAddOneAsset(t,e,i,r,n,s,a){return(0,k.calculate_add_one_asset)(t,e,i,r,n,s,a)}static calculateSharesForAmount(t,e,i,r,n,s,a){return(0,k.calculate_shares_for_amount)(t,e,i,r,n,s,a)}static calculateOutGivenIn(t,e,i,r,n,s,a){return(0,k.calculate_out_given_in)(t,e,i,r,n,s,a)}static calculateLiquidityOutOneAsset(t,e,i,r,n,s,a){return(0,k.calculate_liquidity_out_one_asset)(t,e,i,r,n,s,a)}static calculateShares(t,e,i,r,n,s){return(0,k.calculate_shares)(t,e,i,r,n,s)}static calculateSpotPriceWithFee(t,e,i,r,n,s,a,o){return(0,k.calculate_spot_price_with_fee)(t,e,i,r,n,s,a,o)}static recalculatePegs(t,e,i,r,n,s){let a=(0,k.recalculate_peg)(t,e,i,r,n,s);return JSON.parse(a)}};var ve=require("@galacticcouncil/common");var{FeeUtils:zt}=I,Ct=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new c(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(s=>[s.id,s])),r=i.get(t),n=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:n.balance,decimalsIn:r.decimals,decimalsOut:n.decimals,tradeableIn:this.id===t?15:r.tradeable,tradeableOut:this.id===e?15:n.tradeable,assetInEd:r.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,i),s=r===0n?0:z.calculateBuyFee(r,n),a=[],o=R.isSellAllowed(t.tradeableIn),l=R.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:r,amountOut:e,feePct:s,errors:a}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),s=z.calculateSellFee(r,n),a=[],o=R.isSellAllowed(t.tradeableIn),l=R.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:r,amountOut:n,feePct:s,errors:a}}calculateIn(t,e,i){let r=$.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?zt.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(r);return n<0n?0n:n}calculateAddOneAsset(t,e,i){let r=$.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?zt.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(r);return n<0n?0n:n}calculateSharesForAmount(t,e,i){let r=$.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?zt.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(r);return n<0n?0n:n}calculateInGivenOut(t,e,i){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,i):t.assetIn==this.id?this.calculateSharesForAmount(t,e,i):this.calculateIn(t,e,i)}spotPriceInGivenOut(t){let e=$.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetOut===this.id,t.assetIn===this.id,t.decimalsOut,t.decimalsIn)}calculateOut(t,e,i){let r=$.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?zt.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(r);return n<0n?0n:n}calculateWithdrawOneAsset(t,e,i){let r=$.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?zt.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(r);return n<0n?0n:n}calculateShares(t,e,i){let r=$.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?zt.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(r);return n<0n?0n:n}calculateOutGivenIn(t,e,i){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,i):t.assetOut==this.id?this.calculateShares(t,e,i):this.calculateOut(t,e,i)}spotPriceOutGivenIn(t){let e=$.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetIn===this.id,t.assetOut===this.id,t.decimalsIn,t.decimalsOut)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:i,decimals:r})=>({asset_id:e,amount:i,decimals:r}));return JSON.stringify(t,Gt.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],Gt.jsonFormatter)}normalizeSpot(t,e,i,r,n){return e?t*ve.big.pow10(ve.RUNTIME_DECIMALS-n):i?t/ve.big.pow10(n-r):t}};var pi=require("polkadot-api"),Jr=require("@polkadot-api/utils"),Zr=require("@noble/hashes/blake2b"),J=require("rxjs"),mi=require("@galacticcouncil/common");var{FeeUtils:ds}=I,we=class extends Q{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=$.getPoolAddress(t),i=(0,Zr.blake2b)(e,{dkLen:32}),r=(0,Jr.toHex)(i);return(0,pi.AccountId)(mi.HYDRATION_SS58_PREFIX).dec(r)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:i,final_amplification:r,initial_block:n,final_block:s}=t,a=$.calculateAmplification(i.toString(),r.toString(),n.toString(),s.toString(),e.toString()),o=Number(a)<r;return{amplification:BigInt(a),isRampPeriod:o}}async getPoolTokens(t,e){let i=this.getPoolAddress(t),r=e.assets.map(async n=>{let[s,a,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,n,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(n,{at:this.at}),this.balance.getBalance(i,n)]);return{id:n,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:o.transferable,tradeable:s,type:a?.asset_type.type}});return Promise.all(r)}async isSupported(){return(await this.api.getStaticApis()).compat.query.Stableswap.Pools.isCompatible(pi.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:this.at}),this.api.query.System.Number.getValue({at:this.at}),this.getPoolLimits()]),r=t.map(async({keyArgs:n,value:s})=>{let[a]=n,o=this.getPoolAddress(a),[l,u,p]=await Promise.all([this.getPoolTokens(a,s),this.api.query.Stableswap.PoolPegs.getValue(a,{at:this.at}),this.api.query.Tokens.TotalIssuance.getValue(a,{at:this.at})]),d=this.getPoolAmplification(s,e),m=u?this.getRecentPegs(u):this.getDefaultPegs(s);return l.push({id:a,tradeable:15,balance:p,decimals:mi.RUNTIME_DECIMALS}),this.poolsData.set(a,s),{address:o,id:a,type:"Stableswap",fee:ds.fromPermill(s.fee),tokens:l,totalIssuance:p,pegs:m,...i,...d}});return Promise.all(r)}async getPoolFees(t,e){return{fee:this.store.pools.find(r=>r.address===e).fee}}getDefaultPegs(t){return $.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([i,r])=>r.map(n=>n.toString()))}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,{at:"best"}).pipe((0,J.map)(({value:r})=>r),(0,J.map)((r,n)=>({value:r,index:n})),(0,J.tap)(({index:r,value:n})=>{r>0&&this.log.trace("tokens.TotalIssuance",i,n)}),(0,J.map)(({value:r})=>({id:i,value:r}))));return(0,J.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:r,value:n}=i;this.store.update(s=>{let a=[];return s.filter(o=>o.id===r).forEach(o=>{let l=o.tokens.map(u=>u.id===r?{...u,balance:n}:u);a.push({...o,tokens:l,totalIssuance:n})}),a})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,J.distinctUntilChanged)((t,e)=>!e.deltas),(0,J.map)((t,e)=>({value:t,index:e})),(0,J.tap)(({value:t,index:e})=>{e>0&&this.log.trace("stableswap.PoolPegs",t.deltas?.upserted)}),this.watchGuard("stableswap.PoolPegs")).subscribe({error:t=>this.log.error("stableswap.PoolPegs",t),next:({value:{deltas:t}})=>{this.store.update(e=>{let i=[],r=new Map(e.map(n=>[n.id,n]));return t?.upserted.forEach(({args:n,value:s})=>{let[a]=n,o=r.get(a);if(o){let l=this.getRecentPegs(s);i.push({...o,pegs:l})}}),i})}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(e=>{let i=[];return e.filter(r=>r.isRampPeriod).forEach(r=>{let n=this.poolsData.get(r.id);if(n){let s=this.getPoolAmplification(n,t);i.push({...r,...s})}}),i})})}subscribeUpdates(){let t=new J.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var Zi={};C(Zi,{XykMath:()=>vt,XykPool:()=>xe,XykPoolClient:()=>Te});var M=require("@galacticcouncil/math-xyk"),vt=class{static getSpotPrice(t,e,i){return(0,M.get_spot_price)(t,e,i)}static calculateInGivenOut(t,e,i){return(0,M.calculate_in_given_out)(t,e,i)}static calculateOutGivenIn(t,e,i){return(0,M.calculate_out_given_in)(t,e,i)}static calculatePoolTradeFee(t,e,i){return(0,M.calculate_pool_trade_fee)(t,e,i)}static calculateLiquidityIn(t,e,i){return(0,M.calculate_liquidity_in)(t,e,i)}static calculateSpotPrice(t,e){return(0,M.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,i,r){return(0,M.calculate_spot_price_with_fee)(t,e,i,r)}static calculateShares(t,e,i){return(0,M.calculate_shares)(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,r){return(0,M.calculate_liquidity_out_asset_a)(t,e,i,r)}static calculateLiquidityOutAssetB(t,e,i,r){return(0,M.calculate_liquidity_out_asset_b)(t,e,i,r)}};var en=require("@galacticcouncil/common");var{FeeUtils:tn}=I,xe=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(s=>[s.id,s])),r=i.get(t),n=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:r.balance,balanceOut:n.balance,assetInEd:r.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),n=this.calculateTradeFee(r,i),s=tn.toPct(i.exchangeFee),a=r+n,o=[];(e<this.minTradingLimit||r<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:r,amountOut:e,feePct:s,errors:o}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),n=this.calculateTradeFee(r,i),s=tn.toPct(i.exchangeFee),a=r-n,o=[];(e<this.minTradingLimit||r<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:a,feePct:s,errors:o}}calculateInGivenOut(t,e){let i=vt.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}calculateOutGivenIn(t,e){let i=vt.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}spotPriceInGivenOut(t){let e=vt.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=vt.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=vt.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(i)}normalizeSpot(t,e,i){let r=e-i;if(r===0)return t;let n=en.big.pow10(Math.abs(r));return r>0?t*n:t/n}};var rn=require("polkadot-api"),nn=require("rxjs");var Te=class extends Q{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){return(await this.api.getStaticApis()).compat.query.XYK.PoolAssets.isCompatible(rn.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries({at:this.at}),this.getPoolLimits()]),i=t.map(async({keyArgs:r,value:n})=>{let[s]=r,[a,o]=n,[l,u,p,d]=await Promise.all([this.balance.getBalance(s,a),this.api.query.AssetRegistry.Assets.getValue(a,{at:this.at}),this.balance.getBalance(s,o),this.api.query.AssetRegistry.Assets.getValue(o,{at:this.at})]);return{address:s,type:"XYK",tokens:[{id:a,decimals:u?.decimals||this.decimals.get(a),existentialDeposit:u?.existential_deposit,balance:l.transferable,type:u?.asset_type.type},{id:o,decimals:d?.decimals||this.decimals.get(o),existentialDeposit:d?.existential_deposit,balance:p.transferable,type:d?.asset_type.type}],...e}});return Promise.all(i)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return nn.Subscription.EMPTY}};var tr={};C(tr,{AavePool:()=>Ie,AavePoolClient:()=>_e});var Yt=require("@galacticcouncil/common");var Ie=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(s=>[s.id,s])),r=i.get(t),n=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:n.balance,decimalsIn:r.decimals,decimalsOut:n.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),n=[];return e>t.balanceOut&&n.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:n}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),n=[];return r>t.balanceOut&&n.push("TradeNotAllowed"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:n}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return Yt.big.toBigInt(1,Yt.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return Yt.big.toBigInt(1,Yt.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var di=require("polkadot-api"),an=require("@polkadot-api/utils"),et=require("rxjs"),on=require("viem"),hi=require("@galacticcouncil/common");var sn=[{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:hs}=hi.erc20,gs=["Supply","Withdraw","Repay","Borrow"],_e=class extends Q{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,r=new TextEncoder().encode(i.padEnd(32,"\0")),n=(0,an.toHex)(r);return(0,di.AccountId)(hi.HYDRATION_SS58_PREFIX).dec(n)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:this.at})).map(async({reserve:i,atoken:r,liqudity_in:n,liqudity_out:s})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(i,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(r,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(r,{at:this.at})]);return{address:this.getPoolId(i,r),type:"Aave",tokens:[{id:i,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:n,location:o,type:a?.asset_type.type},{id:r,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:s,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:r,liqudity_out:n}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:this.at});return t.tokens.map(s=>{let a=s.id===e.id?r:n;return{...s,balance:a}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key}throw new Error("Invalid aave reserve multilocation")}return hs.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:i}=t;return{assetIn:e,assetOut:i,key:`${e}:${i}`}}parseEvmLog(t){let{topics:e,data:i}=t.log,r=e,n=di.Binary.toHex(i);try{let{eventName:s,args:a}=(0,on.decodeEventLog)({abi:sn,topics:r,data:n}),o=a.reserve.toLowerCase();return{eventName:s,reserve:o,key:`${s}:${o}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(i=>i.tokens).map(([i,r])=>r).map(i=>i.id);return this.api.event.Router.Executed.watch().pipe((0,et.mergeMap)(({events:i})=>i),(0,et.map)(({payload:i})=>this.parseRouterLog(i)),(0,et.filter)(({assetIn:i,assetOut:r})=>e.includes(i)||e.includes(r)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:r,key:n})=>{this.log.trace("router.Executed",n),this.store.update(async s=>{let a=[];for(let o of s){let[l,u]=o.tokens;if(u.id===i||u.id===r){let d=await this.getPoolDelta(o);a.push({...o,tokens:d})}}return a})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,et.mergeMap)(({events:t})=>t),(0,et.map)(({payload:t})=>this.parseEvmLog(t)),(0,et.filter)(t=>t!==void 0),(0,et.filter)(({eventName:t})=>gs.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async i=>{let r=[];for(let n of i){let[s]=n.tokens;if(this.getReserveH160Id(s).toLowerCase()===t){let o=await this.getPoolDelta(n);r.push({...n,tokens:o})}}return r})})}subscribeBalances(){return et.Subscription.EMPTY}subscribeUpdates(){let t=new et.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var ir={};C(ir,{HsmMath:()=>at,HsmPool:()=>Ae,HsmPoolClient:()=>Fe});var X=require("@galacticcouncil/math-hsm"),at=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,X.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,X.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,X.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,X.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,X.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,X.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,X.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,X.calculate_max_price)(t,e)}};var K=require("@galacticcouncil/common");var{FeeUtils:$t}=I,Ae=class c extends Ct{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new c(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,i){let r=this.parsePair(t.assetOut,t.assetIn),n=super.calculateInGivenOut(r,e,{fee:this.fee}),s=this.calculateBuybackLimit(t);e>s&&i.push("MaxBuyBackExceeded");let a=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,n)>a&&i.push("MaxBuyPriceExceeded"),n>this.collateralBalance&&i.push("InsufficientCollateral"),i}validateTradeHollarOut(t,e,i){return this.collateralBalance+t>this.maxInHolding&&i.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&i.push("FacilitatorCapacityExceeded"),i}validateTradeConstraints(t,e,i){let r=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,r):this.validateTradeHollarOut(e,i,r)}validateAndBuy(t,e){let i=this.calculateInGivenOut(t,e),r=this.validateTradeConstraints(t,i,e);return{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:r}}validateAndSell(t,e){let i=this.calculateOutGivenIn(t,e),r=this.validateTradeConstraints(t,e,i);return{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:r}}calculateHollarInGivenCollateralOut(t,e){let i=super.calculateInGivenOut(t,e,{fee:this.fee}),r=at.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),$t.toRaw(this.buyBackFee).toString());return BigInt(r)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=at.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),$t.toRaw(this.purchaseFee).toString());return BigInt(i)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let i=super.calculateOutGivenIn(t,e,{fee:this.fee}),r=at.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),$t.toRaw(this.buyBackFee).toString());return BigInt(r)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=at.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),$t.toRaw(this.purchaseFee).toString());return BigInt(i)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),i=at.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=at.calculateBuybackLimit(e.toString(),$t.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let r=at.calculateBuybackPriceWithFee(i.toString(),e.toString(),$t.toRaw(this.buyBackFee).toString()),[n,s]=JSON.parse(r),a=K.big.pow10(t.decimalsIn+K.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(n)*a/BigInt(s)}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=at.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[r,n]=JSON.parse(i),s=K.big.pow10(K.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(r)*s/BigInt(n)}spotPriceInGivenOut(t){let e=K.big.toBigInt(1,t.decimalsOut),r=this.calculateInGivenOut(t,e)*K.big.pow10(K.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(r,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=K.big.toBigInt(1,t.decimalsIn),r=this.calculateOutGivenIn(t,e)*K.big.pow10(K.RUNTIME_DECIMALS-t.decimalsIn);return this.normalizeSpotPrice(r,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(r=>r.id!==this.hollarId),e=this.pegs[t],i=this.tokens[t].decimals;return this.isDefaultPeg(e)?[K.big.toBigInt(1,18).toString(),K.big.toBigInt(1,i).toString()]:e}isDefaultPeg(t){let[e,i]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&i==="1"}normalizeSpotPrice(t,e,i){let r=e-i;if(r===0)return t;let n=K.big.pow10(Math.abs(r));return r>0?t*n:t/n}};var Xt=require("polkadot-api"),cn=require("@polkadot-api/utils"),U=require("rxjs"),un=require("viem"),gi=require("@galacticcouncil/common");var Oe=[{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 Be=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,r]=await this.client.readContract({abi:Oe,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-r}};var{FeeUtils:er}=I,{H160:ln}=gi.h160,bs=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Fe=class extends Q{ghoClient;stableClient;constructor(t,e,i,r){super(t,e,r),this.stableClient=i,this.ghoClient=new Be(e)}getPoolType(){return"HSM"}getPoolId(t){return this.getPoolAddress("hsm:"+t)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(t){if(t){let e=t.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),i=new TextEncoder().encode(e),r=(0,cn.toHex)(i);return(0,Xt.AccountId)(gi.HYDRATION_SS58_PREFIX).dec(r)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(Xt.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,r]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t,{at:this.at}),this.api.query.HSM.Collaterals.getEntries({at:this.at}),this.stableClient.getPools()]);if(i.length===0)return[];let n=this.getFacilitatorAddress(),s=ln.fromAny(n),a=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(a,s),l=i.map(async({keyArgs:p,value:d})=>{let[m]=p,{pool_id:g,max_buy_price_coefficient:b,max_in_holding:h,purchase_fee:P,buy_back_fee:f,buyback_rate:v}=d,S=r.find(T=>T.id===g);if(S){let T=this.getPoolId(g),B=await this.balance.getBalance(n,m);return{...S,address:T,type:"HSM",tokens:S.tokens.filter(N=>N.id!==g),hsmAddress:n,hsmMintCapacity:o,hollarId:t,hollarH160:a,collateralId:m,collateralBalance:B.transferable,maxBuyPriceCoefficient:b,maxInHolding:h,purchaseFee:er.fromPermill(P),buyBackFee:er.fromPermill(f),buyBackRate:er.fromPerbill(v)}}});return(await Promise.all(l)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:i}=t.log,r=e,n=Xt.Binary.toHex(i);try{let{eventName:s,args:a}=(0,un.decodeEventLog)({abi:Oe,topics:r,data:n}),o=a.facilitatorAddress.toLowerCase();return{eventName:s,facilitator:o,key:`${s}:${o}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,U.mergeMap)(({events:t})=>t),(0,U.map)(({payload:t})=>this.parseEvmLog(t)),(0,U.filter)(t=>t!==void 0),(0,U.filter)(({eventName:t})=>bs.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async i=>{let r=[],[{hsmAddress:n,hollarH160:s}]=i,a=ln.fromAny(n);if(a.toLowerCase()===e){let l=await this.ghoClient.getFacilitatorCapacity(s,a);for(let u of i)r.push({...u,hsmMintCapacity:l})}return r})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(n=>{let{tokens:s,collateralId:a}=n;s.find(l=>l.id===a).type==="Erc20"?e.push(a):t.push(a)});let[{hsmAddress:i}]=this.store.pools,r=[];if(t.length>0){let n=this.balance.watchTokensBalance(i);r.push(n)}if(e.length>0){let n=this.balance.watchErc20Balance(i,e);r.push(n)}return r.length>0?(0,U.combineLatest)(r).pipe((0,U.map)(n=>n.flat()),(0,U.pairwise)(),(0,U.map)(([n,s])=>this.balance.getDeltas(n,s)),this.watchGuard("balances")).subscribe(n=>{this.store.update(s=>{let a=[],o=new Map(s.map(l=>[l.collateralId,l]));return n.forEach(({id:l,balance:u})=>{let p=o.get(l);p&&(this.log.trace("balances",{id:l,balance:u}),a.push({...p,collateralBalance:u.transferable}))}),a})}):U.Subscription.EMPTY}subscribeStableswapUpdates(){return this.stableClient.getSubscriber().pipe(this.watchGuard("stableswap.updates")).subscribe(t=>{let e=new Map(t.map(i=>[i.id,i]));this.store.update(i=>{let r=[];for(let n of i){let s=e.get(n.id);s&&r.push({...n,fee:s.fee,tokens:s.tokens.filter(a=>a.id!==n.id),totalIssuance:s.totalIssuance,pegs:s.pegs,amplification:s.amplification,isRampPeriod:s.isRampPeriod})}return r})})}subscribeBalances(){return U.Subscription.EMPTY}subscribeUpdates(){let t=new U.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var Kt=class{static get(t){switch(t.type){case"Aave":return Ie.fromPool(t);case"XYK":return xe.fromPool(t);case"Omnipool":return Pe.fromPool(t);case"LBP":return ye.fromPool(t);case"Stableswap":return Ct.fromPool(t);case"HSM":return Ae.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var pn=require("@galacticcouncil/common"),ot=require("rxjs");var{logger:ys}=pn.log,jt=class extends D{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=ot.Subscription.EMPTY;omniSub=ot.Subscription.EMPTY;stableSub=ot.Subscription.EMPTY;hsmSub=ot.Subscription.EMPTY;xykSub=ot.Subscription.EMPTY;lbpSub=ot.Subscription.EMPTY;isReady=!1;isDestroyed=new ot.Subject;constructor(t,e,i){super(t,i),this.evm=e,this.aave=new _e(t,e,i),this.omnipool=new Se(t,e,i),this.stableswap=new we(t,e,i),this.hsm=new Fe(t,e,this.stableswap,i),this.xyk=new Te(t,e,i),this.lbp=new fe(t,e,i),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}get isHistorical(){return this.at!=="best"&&this.at!=="finalized"}subscribe(t){return this.isHistorical?ot.Subscription.EMPTY:t.getSubscriber().pipe((0,ot.takeUntil)(this.isDestroyed)).subscribe(e=>{e.forEach(i=>{this.pools.set(i.address,i)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.active.has("Stableswap")||(ys.info("[PoolContextProvider] auto-activating stableswap"),this.withStableswap()),this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let i=this.clients.find(r=>r.getPoolType()===e.type);if(i)return i.getPoolFees(t,e.address);throw new Ot(e.type)}};var bi=class{constructor(t){this.snapshot=t;let{aave:e,xyk:i,lbp:r,stable:n,omni:s}=t.pools;this.flat=[...e,...i,...r,...n,...s]}flat;async getPools(){return this.flat}async getPoolFees(t,e){let{block:i,states:r}=this.snapshot;switch(e.type){case"Aave":return{};case"XYK":{let{exchangeFee:n}=r.xyk;return{exchangeFee:n}}case"LBP":{let{repayFee:n}=r.lbp;return{exchangeFee:e.fee,repayFee:n}}case"Stableswap":return{fee:e.fee};case"Omnipool":{let n=t.assetOut,s=t.assetIn,{dynamicFees:a,emaOracles:o,assetFeeParams:l,protocolFeeParams:u,maxSlipFee:p}=r.omni,d=a.find(({asset:b})=>b===n)?.fee,m=o.find(({pair:b})=>b.join(":")===ui(n))?.oracle,g=o.find(({pair:b})=>b.join(":")===ui(s))?.oracle;return Rt.compute(t,i,d,m,g,l,u,p)}default:throw new Ot(e.type)}}};var ur={};C(ur,{DCA_TIME_RESERVE:()=>hn,DEFAULT_BLOCK_TIME:()=>dn,DEFAULT_MIN_BUDGET:()=>ar,ORDER_MIN_BLOCK_PERIOD:()=>gn,Router:()=>Qt,TWAP_EXECUTION_INTERVAL:()=>ke,TWAP_MAX_DURATION:()=>lr,TWAP_MAX_PRICE_IMPACT:()=>or,TWAP_TX_MULTIPLIER:()=>Hm,TradeOrderError:()=>sr,TradeOrderType:()=>fi,TradeRouteBuilder:()=>it,TradeRouter:()=>_t,TradeScheduler:()=>Jt,TradeType:()=>yi});var Re=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 fs=10,Ce=class{isNotVisited(t,e){let i=!0;return e.forEach(r=>{(r[0]===t[0]||r[1]===t[1])&&(i=!1)}),i}findPaths(t,e,i){let r=[],n=new Re,s=[];for(s.push([e,""]),n.enqueue(s);n.size()>0;){let a=n.dequeue();if(!a||a.length>fs)continue;let o=a[a.length-1];(i===null||o[0]===i)&&r.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let p=[...a];p.push(u),n.enqueue(p)}})}return r}findShortestPaths(t,e,i){let r=[],n=new Re,s=[];s.push([e,""]),n.enqueue(s);let a=1/0;for(;n.size()>0;){let o=n.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===i){o.length<a?(a=o.length,r.length=0,r.push(o)):o.length===a&&r.push(o);continue}let u=t.get(l[0]);for(let p of u??[])this.isNotVisited(p,o)&&n.enqueue([...o,p])}return r}buildAndPopulateGraph(t,e){let i=new Map;for(let r of t)i.set(parseInt(r),[]);for(let[r,n,s]of e)i.get(n)?.push([s,r]);return i}};function nr(c){let t={};for(let e of c){let i=e.tokens.length;for(let r=0;r<i;r++){t[e.tokens[r].id]||(t[e.tokens[r].id]=[]);for(let n=0;n<i;n++){if(r==n)continue;let s=[e.address,e.tokens[r].id,e.tokens[n].id];t[e.tokens[r].id].push(s)}}}return t}var Ee=class{getProposals(t,e,i){let r=i.filter(h=>h.type==="XYK"),n=i.filter(h=>h.type!=="XYK"),s=new Set(n.map(h=>h.tokens).flat().map(h=>h.id)),a=s.has(t),o=s.has(e),l=new Ce,u=h=>{let P=nr(h),f=Object.keys(P),v=f.flatMap(S=>P[S]);return l.buildAndPopulateGraph(f,v)};if(!a&&!o){let h=r.filter(v=>v.tokens.find(S=>S.id===t)||v.tokens.find(S=>S.id===e)),P=u(h),f=l.findPaths(P,t,e);return this.parsePaths(f)}if(a&&o){let h=u(n),P=l.findPaths(h,t,e);return this.parsePaths(P)}let p=a?e:t,d=r.filter(h=>h.tokens.some(P=>P.id===p));if(d.length===0)return[];let m=[...n,...d],g=u(m),b=l.findPaths(g,t,e);return this.parsePaths(b)}parsePaths(t){let e=[];for(let i of t){let r=[];for(let n=0;n<i.length;n++){let s=i[n],a=i[n+1];if(a==null)break;r.push(this.toEdge(s,a))}e.push(r)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var Qt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new Ee,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,i){return`${t}->${e}::${i.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:i=[]}=this.filter,r=new Set(e),n=new Set(i);return t.filter(s=>n.has(s.type)?!1:r.size>0?r.has(s.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let i=await this.getPools();return this.validateInput(t,e,i),this.getPaths(t,e,i)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(r=>r!==t).map(r=>this.getRoutes(r,t)))).filter(r=>r.length>0).map(([r])=>r[0].assetIn).sort()}validateInput(t,e,i){if(i.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let r=this.getAssets(i);if(!r.has(t))throw new Error(t+" is not supported asset");if(!r.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(i)}getAssets(t){let e=t.map(i=>i.tokens.map(r=>r.id)).flat().sort((i,r)=>i>r?1:-1);return new Set(e)}getPaths(t,e,i){let r=this.toPoolsMap(i);return this.getProposals(t,e,i).filter(s=>this.validPath(s,r)).map(s=>this.toHops(s,r))}getProposals(t,e,i){let r=this.buildRouteKey(t,e,i);if(this.routeProposals.has(r))return this.routeProposals.get(r);let n=this.routeSuggester.getProposals(t,e,i);return this.routeProposals.set(r,n),n}validPath(t,e){return t.length>0&&t.map(i=>this.validEdge(i,e)).reduce((i,r)=>i&&r)}validEdge([t,e,i],r){return r.get(t)?.validatePair(e,i)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Kt.get(e)]))}toHops(t,e){return t.map(([i,r,n])=>{let s=e.get(i);return{poolAddress:i,poolId:s?.id,pool:s?.type,assetIn:r,assetOut:n}})}};var O=require("@galacticcouncil/common");var yi=(e=>(e.Buy="Buy",e.Sell="Sell",e))(yi||{}),fi=(i=>(i.Dca="Dca",i.TwapSell="TwapSell",i.TwapBuy="TwapBuy",i))(fi||{}),sr=(i=>(i.OrderTooSmall="OrderTooSmall",i.OrderTooBig="OrderTooBig",i.OrderImpactTooBig="OrderImpactTooBig",i))(sr||{});var{FeeUtils:mn}=I,_t=class extends Qt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,i){let r=super.validateInput(t,e,i),n=super.getPaths(t,e,i);if(!n.length)throw new le(t,e);return{paths:n,pools:i,poolsMap:r}}async withCtx(t,e,i){let r=await super.getPools(),n=this.buildCtxSync(t,e,r);return i(n)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((i,r)=>{let n=i[i.length-1].amountOut,s=r[r.length-1].amountOut;return n>s?-1:1});return e.find(i=>i.every(r=>r.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(i=>i.tradeFeeRange).length>0){let i=t.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,s)=>n+s),r=t.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,s)=>n+s);return[i,r]}}getPoolFeeRange(t,e){let i=t.min?mn.toPct(t.min):void 0,r=t.max?mn.toPct(t.max):void 0;if(i&&r)return[i,Math.max(r,e)]}async getBestSell(t,e,i){return this.getSell(t,e,i)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,i,r){return this.withCtx(t,e,async({paths:n,poolsMap:s})=>{let a;if(r)a=await this.toSellSwaps(i,r,s);else{let o=n.map(u=>this.toSellSwaps(i,u,s)),l=await Promise.all(o);a=this.findBestSellRoute(l)}return this.buildSell(s,a)})}async getSells(t,e,i){return this.withCtx(t,e,async({paths:r,poolsMap:n})=>{let s=r.map(o=>this.toSellSwaps(i,o,n));return(await Promise.all(s)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(n,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let i=e[0],r=e[e.length-1],n=this.isDirectTrade(e),s=this.getSellSpot(e),a=r.amountOut,o=n?r.calculatedOut:this.calculateDelta0Y(i.amountIn,e,t),l=o-a,u=this.getRouteFeeRange(e),p=n?r.tradeFeePct:z.calculateSellFee(o,a),d=q.mulSpot(i.amountIn,s,i.assetInDecimals,r.assetOutDecimals),m=z.calculateDiffToRef(o,d);return{type:"Sell",amountIn:i.amountIn,amountOut:r.amountOut,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Sell",amountIn:O.big.toDecimal(i.amountIn,i.assetInDecimals),amountOut:O.big.toDecimal(r.amountOut,r.assetOutDecimals),spotPrice:O.big.toDecimal(s,O.RUNTIME_DECIMALS),tradeFee:O.big.toDecimal(l,r.assetOutDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e.map(g=>g.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,i)=>e*i/10n**BigInt(O.RUNTIME_DECIMALS))}calculateDelta0Y(t,e,i){let r=[];for(let n=0;n<e.length;n++){let s=e[n],a=i.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;n>0?l=r[n-1]:l=t;let u=a.calculateOutGivenIn(o,l);r.push(u)}return r[r.length-1]}async calculateMostLiquidRoute(t,e,i){let{paths:r,pools:n,poolsMap:s}=i,l=n.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,P)=>h+P)).sort((b,h)=>h<b?-1:1)[0],u=q.getFraction(l,.1),p=await Promise.all(r.map(b=>this.toSellSwaps(u,b,s))),m=this.findBestSellRoute(p).map(b=>({poolAddress:b.poolAddress,poolId:b?.poolId,pool:b.pool,assetIn:b.assetIn,assetOut:b.assetOut})),g=this.buildRouteKey(t,e,n);return this.mlr.set(g,m),m}async toSellSwaps(t,e,i){let r=[];for(let n=0;n<e.length;n++){let s=e[n],a=i.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;n>0?l=r[n-1].amountOut:l=typeof t=="string"?O.big.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(o,a),{amountOut:p,calculatedOut:d,feePct:m,errors:g}=a.validateAndSell(o,l,u),b=this.getPoolFeeRange(u,m),h=a.spotPriceOutGivenIn(o),P=q.mulSpot(l,h,o.decimalsIn,o.decimalsOut),f=z.calculateDiffToRef(d,P);r.push({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:d,spotPrice:h,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:f,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===s.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===s.assetIn},toHuman(){return{...s,amountIn:O.big.toDecimal(l,o.decimalsIn),amountOut:O.big.toDecimal(p,o.decimalsOut),calculatedOut:O.big.toDecimal(d,o.decimalsOut),spotPrice:O.big.toDecimal(h,O.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:f,errors:g}}})}return r}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async i=>{let r=this.buildRouteKey(t,e,i.pools),n=this.mlr.get(r);return n||this.calculateMostLiquidRoute(t,e,i)})}async getSpotPrice(t,e){return this.withCtx(t,e,async i=>{let{pools:r,poolsMap:n}=i,s=this.buildRouteKey(t,e,r),a=this.mlr.get(s);a||(a=await this.calculateMostLiquidRoute(t,e,i));let o=await this.toSellSwaps("1",a,n);return{amount:this.getSellSpot(o),decimals:O.RUNTIME_DECIMALS}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((i,r)=>{let n=i[0].amountIn,s=r[0].amountIn;return n>s?1:-1});return e.find(i=>i.every(r=>r.errors.length==0))||e[0]}async getBestBuy(t,e,i){return this.getBuy(t,e,i)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,i,r){return this.withCtx(t,e,async({paths:n,poolsMap:s})=>{let a;if(r)a=await this.toBuySwaps(i,r,s);else{let o=n.map(u=>this.toBuySwaps(i,u,s)),l=await Promise.all(o);a=this.findBestBuyRoute(l)}return this.buildBuy(s,a)})}async getBuys(t,e,i){return this.withCtx(t,e,async({paths:r,poolsMap:n})=>{let s=r.map(o=>this.toBuySwaps(i,o,n));return(await Promise.all(s)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(n,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let i=e[e.length-1],r=e[0],n=this.isDirectTrade(e),s=this.getBuySpot(e),a=r.amountIn,o=n?r.calculatedIn:this.calculateDelta0X(i.amountOut,e,t),l=a-o,u=this.getRouteFeeRange(e),p=n?r.tradeFeePct:z.calculateBuyFee(o,a),d=q.mulSpot(i.amountOut,s,i.assetOutDecimals,r.assetInDecimals),m;return o===0n?m=-100:m=z.calculateDiffToRef(d,o),{type:"Buy",amountOut:i.amountOut,amountIn:r.amountIn,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Buy",amountOut:O.big.toDecimal(i.amountOut,i.assetOutDecimals),amountIn:O.big.toDecimal(r.amountIn,r.assetInDecimals),spotPrice:O.big.toDecimal(s,O.RUNTIME_DECIMALS),tradeFee:O.big.toDecimal(l,r.assetInDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e.map(g=>g.toHuman())}}}}calculateDelta0X(t,e,i){let r=[];for(let n=e.length-1;n>=0;n--){let s=e[n],a=i.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;n==e.length-1?l=t:l=r[0];let u=a.calculateInGivenOut(o,l);r.unshift(u)}return r[0]}async toBuySwaps(t,e,i){let r=[];for(let n=e.length-1;n>=0;n--){let s=e[n],a=i.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;n==e.length-1?l=typeof t=="string"?O.big.toBigInt(t,o.decimalsOut):t:l=r[0].amountIn;let u=await this.ctx.getPoolFees(o,a),{amountIn:p,calculatedIn:d,feePct:m,errors:g}=a.validateAndBuy(o,l,u),b=this.getPoolFeeRange(u,m),h=a.spotPriceInGivenOut(o),P=q.mulSpot(l,h,o.decimalsOut,o.decimalsIn),f;d===0n?f=-100:f=z.calculateDiffToRef(P,d),r.unshift({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:d,spotPrice:h,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:f,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===s.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===s.assetIn},toHuman(){return{...s,amountOut:O.big.toDecimal(l,o.decimalsOut),amountIn:O.big.toDecimal(p,o.decimalsIn),calculatedIn:O.big.toDecimal(d,o.decimalsIn),spotPrice:O.big.toDecimal(h,O.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:f,errors:g}}})}return r}};var V=require("@galacticcouncil/common");var dn=6e3,ar=1000000000000000n,ke=6,or=-5,lr=216e5,Hm=3,hn=.1,gn=6;var cr=require("polkadot-api");var it=class{static build(t){return t.map(({assetIn:e,assetOut:i,pool:r,poolId:n})=>r==="Stableswap"?{pool:(0,cr.Enum)("Stableswap",n),asset_in:e,asset_out:i}:{pool:(0,cr.Enum)(r),asset_in:e,asset_out:i})}};var Jt=class{schedulerOptions;router;constructor(t,e={}){this.router=new _t(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??ar})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,i,r,n){let s=await this.router.getBestSell(t,e,i),{amountIn:a,swaps:o,priceImpactPct:l}=s,u=o[0],p=o[o.length-1],{assetInDecimals:d}=u,{assetOutDecimals:m}=p,g=Math.abs(l),b=await this.getMinimumOrderBudget(t,d),h=this.getOptimalTradeCount(g),P=this.getMaximumTradeCount(a,b,r),f=n||Math.min(h,P),v=Math.round(r/f),S=a/BigInt(f),T=await this.router.getBestSell(t,e,S),B=a<b,N=[];B&&N.push("OrderTooSmall");let W=T.amountOut*BigInt(f),ut=this.toBlockPeriod(v),bt=T.tradeFee*BigInt(f),Z=it.build(o),nt={assetIn:t,assetOut:e,errors:N,maxTradeCount:P,tradeCount:f,tradeFee:bt,tradeImpactPct:T.priceImpactPct,tradePeriod:ut,tradeRoute:Z,type:"Dca"};return{...nt,amountIn:a,amountOut:W,tradeAmountIn:T.amountIn,tradeAmountOut:T.amountOut,toHuman(){return{...nt,amountIn:V.big.toDecimal(a,d),amountOut:V.big.toDecimal(W,m),tradeAmountIn:V.big.toDecimal(T.amountIn,d),tradeAmountOut:V.big.toDecimal(T.amountOut,m)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let i=await this.router.getSpotPrice(0,t);if(i)return q.mulSpot(this.minOrderBudget,i.amount,12,e);let r=await this.router.getSpotPrice(t,0);if(r)return q.divSpot(this.minOrderBudget,r.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,i){let r=e*2n/10n;if(r===0n)return 0;let n=Number(t/r),s=Math.floor(i/this.blockTime),a=Math.max(0,Math.floor(s*(1-.1)));return Math.min(n,a)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,i,r){let n=await this.router.getBestSell(t,e,i),{swaps:s}=n,a=s[0],o=s[s.length-1],{assetInDecimals:l}=a,{assetOutDecimals:u}=o,p=await this.getMinimumOrderBudget(t,l),d=n.amountIn<p,m=[];d&&m.push("OrderTooSmall");let g=this.toBlockPeriod(r),b=it.build(s),h={assetIn:t,assetOut:e,errors:m,maxTradeCount:0,tradeCount:0,tradeFee:n.tradeFee,tradeImpactPct:n.priceImpactPct,tradePeriod:g,tradeRoute:b,type:"Dca"};return{...h,amountIn:0n,amountOut:0n,tradeAmountIn:n.amountIn,tradeAmountOut:n.amountOut,toHuman(){return{...h,amountIn:"0",amountOut:"0",tradeAmountIn:V.big.toDecimal(n.amountIn,l),tradeAmountOut:V.big.toDecimal(n.amountOut,u)}}}}async getTwapSellOrder(t,e,i){let r=await this.router.getBestSell(t,e,i),{amountIn:n,swaps:s,priceImpactPct:a}=r,o=s[0],l=s[s.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),g=n/BigInt(m),[b,h]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestSell(o.assetIn,l.assetOut,g)]),P=m===1,f=n<b,v=h.priceImpactPct<-5,S=[];f||P?S.push("OrderTooSmall"):v&&S.push("OrderImpactTooBig");let T=h.amountOut*BigInt(m),B=h.tradeFee*BigInt(m),N=it.build(s),W={assetIn:t,assetOut:e,errors:S,tradeCount:m,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:N,type:"TwapSell"};return{...W,amountIn:n,amountOut:T,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:B,toHuman(){return{...W,amountIn:V.big.toDecimal(n,u),amountOut:V.big.toDecimal(T,p),tradeAmountIn:V.big.toDecimal(h.amountIn,u),tradeAmountOut:V.big.toDecimal(h.amountOut,p),tradeFee:V.big.toDecimal(B,p)}}}}async getTwapBuyOrder(t,e,i){let r=await this.router.getBestBuy(t,e,i),{amountOut:n,swaps:s,priceImpactPct:a}=r,o=s[0],l=s[s.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),g=n/BigInt(m),[b,h]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestBuy(o.assetIn,l.assetOut,g)]),P=h.amountIn*BigInt(m),f=m===1,v=P<b,S=h.priceImpactPct<-5,T=[];v||f?T.push("OrderTooSmall"):S&&T.push("OrderImpactTooBig");let B=h.tradeFee*BigInt(m),N=it.build(s),W={assetIn:t,assetOut:e,errors:T,tradeCount:m,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:N,type:"TwapBuy"};return{...W,amountIn:P,amountOut:n,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:B,toHuman(){return{...W,amountIn:V.big.toDecimal(P,u),amountOut:V.big.toDecimal(n,p),tradeAmountIn:V.big.toDecimal(h.amountIn,u),tradeAmountOut:V.big.toDecimal(h.amountOut,p),tradeFee:V.big.toDecimal(B,u)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let r=216e5/(this.blockTime*6);return Math.round(r)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,i=Math.round(e);return Math.max(i,6)}};var dr={};C(dr,{BIG_10:()=>vn,BIG_BILL:()=>pr,StakingApi:()=>Me,StakingClient:()=>De});var j=require("@galacticcouncil/math-staking"),rt=wt(require("big.js"));var Pi={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},bn=c=>Object.keys(Pi).includes(c);var yn=require("polkadot-api"),fn=require("@polkadot-api/utils"),Pn=require("@galacticcouncil/common");function Sn(c){let t=("modl"+c).padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,fn.toHex)(e);return(0,yn.AccountId)(Pn.HYDRATION_SS58_PREFIX).dec(i)}var Si="20000000000000000",vi="2000",vn=(0,rt.default)(10),pr=(0,rt.default)(vn.pow(12)),Me=class{client;balance;constructor(t,e){this.client=t,this.balance=e}async getPotBalance(){let t=await this.client.getPalletId(),e=Sn(t);return await this.balance.getBalance(e,0)}async getStakingPosition(t){let[e,i]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let r=e.created_at,n=await i.reduce(async(s,[a,o])=>{let l=await s,u=a,p=o.amount,d=o.conviction.type.toLowerCase(),m=await this.client.getReferendumInfo(u);return m&&(m.type==="Approved"||m.type==="Rejected")&&bn(d)&&l.push({id:u,amount:p,conviction:d}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:r,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:n}}async getStake(t){let e=await this.client.getNFTCollectionId(),[i,r]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),n=r.find(s=>s)?.itemId;return{totalStake:i?.total_stake,accumulatedRewardPerStake:i?.accumulated_reward_per_stake,potReservedBalance:i?.pot_reserved_balance,positionId:n,stakePosition:n?await this.getStakingPosition(n):void 0}}getCurrentActionPoints(t,e,i,r){let n=(0,rt.default)(0),s=(0,rt.default)(0),a=Pi.locked6x,o=(0,rt.default)(i.toString()).mul(a),l=100,u=[];t.forEach(m=>{let g=Pi[m.conviction],b=r.includes(m.id.toString());b&&u.push(m.id.toString());let h=(0,rt.default)(m.amount.toString()).mul(l).div(o);n=n.plus(Math.floor(h.mul(g).toNumber())),s=s.plus(Math.floor(h.mul(b?a:g).toNumber()))});let p=Math.floor((0,rt.default)(i.toString()).mul(a).mul(l).div(o).toNumber());r.forEach(m=>{u.includes(m)||(s=s.plus(p))});let d={democracyVote:1};return n=n.mul(d.democracyVote),n=n.plus(e.toString()||"0"),s=s.mul(d.democracyVote),s=s.plus(e.toString()||"0"),{currentActionPoints:n.toString(),maxActionPoints:s.toString()}}async getRewards(t,e,i){let r=await this.getStake(t),{potReservedBalance:n,accumulatedRewardPerStake:s,totalStake:a,stakePosition:o}=r;if(!o)return;let[l,u,p,d,m,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,rt.default)(l.transferable.toString()).minus(n.toString()),P=h.gt(0)&&a>0?(0,j.calculate_accumulated_rps)(s.toString(),h.toString(),a.toString()):s.toString(),f=(0,j.calculate_period_number)(u.toString(),i,b),v=(0,j.calculate_period_number)(u.toString(),o.createdAt.toString(),b),S=(0,j.calculate_rewards)(P,o.rewardPerStake.toString(),o.stake.toString()),T=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),B=(0,j.calculate_points)(v,f,d.toString(),m.toString(),T.currentActionPoints,g.toString(),o.accumulatedSlashPoints.toString()),N=(0,j.sigmoid)(B,Si,vi),W=(()=>{if(!e.length)return;let ee=(0,j.calculate_points)(v,f,d.toString(),m.toString(),T.maxActionPoints.toString(),g.toString(),o.accumulatedSlashPoints.toString());return(0,j.sigmoid)(ee,Si,vi)})(),ut=(0,rt.default)(S).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if((0,rt.default)(f).minus(v).lte(p.toString()))return{rewards:"0",payablePercentage:N,extraPayablePercentage:W,constants:{a:Si,b:vi}};let bt=(0,j.calculate_percentage_amount)(ut.toString(),N),Z=(0,rt.default)(o.accumulatedLockedRewards.toString()),nt=Z.gt(bt)?Z:(0,rt.default)(bt);return{rewards:nt.div(pr).toString(),maxRewards:ut.div(pr).toString(),allocatedRewardsPercentage:nt.div(ut).mul(100).toNumber(),points:B,payablePercentage:N,extraPayablePercentage:W,constants:{a:Si,b:vi}}}};var mr=require("polkadot-api");var De=class extends D{async getPalletId(){let t=this.api.constants.Staking.PalletId,e=await t();return mr.Binary.toText(mr.Binary.fromHex(e))}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:s})=>{let[a,o,l]=s;return{address:a,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var gr={};C(gr,{TxBuilderFactory:()=>te});var hr=require("polkadot-api");function wn(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var Zt=class extends D{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new pt(t),this.aaveUtils=new At(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:i=>this.dryRun(i,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:Fi})}async dryRun(t,e){let i=(0,hr.Enum)("Signed",t),r=(0,hr.Enum)("system",i),s=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(r,e.decodedCall,4),a=s.success&&!s.value.execution_result.success?s.value.execution_result.value.error:null;if(a){let o=a.type==="Module"?wn(a.value):a.type;throw new Error("Dry run execution error!",{cause:o})}return s}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var wi=class extends Zt{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:i}=this.trade;if(i==="Buy")return this.buildBuyTx();let{assetIn:r}=e[0],n=await this.balance.getBalance(this.beneficiary,r);return t>=n.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,r=i[0],n=i[i.length-1],s=q.getFraction(t,this.slippagePct),a=r.assetIn,o=n.assetOut,l=t+s,u;return this.isDirectOmnipoolTrade(i)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:it.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,r=i[0],n=i[i.length-1],s=q.getFraction(e,this.slippagePct),a=r.assetIn,o=n.assetOut,l=e-s,u;return this.isDirectOmnipoolTrade(i)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:it.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,i=e[0],r=e[e.length-1],n=q.getFraction(t,this.slippagePct),s=i.assetIn,a=r.assetOut,o=t-n,l=this.api.tx.Router.sell_all({asset_in:s,asset_out:a,min_amount_out:o,route:it.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var xi=require("polkadot-api");var Ti=class extends Zt{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradePeriod:n,tradeRoute:s}=this.order,a=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,xi.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:r,min_amount_out:0n,route:s})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(a=await this.dispatchWithExtraGas(a)),this.wrapTx("DcaSchedule",a)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradeAmountOut:n,tradePeriod:s,tradeRoute:a}=this.order,o=q.getFraction(n,this.slippagePct),l=n-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,xi.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:r,min_amount_out:l,route:a})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("DcaSchedule.twapSell",u)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradeAmountOut:n,tradePeriod:s,tradeRoute:a}=this.order,o=q.getFraction(r,this.slippagePct),l=r+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,xi.Enum)("Buy",{asset_in:e,asset_out:i,amount_out:n,max_amount_in:l,route:a})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("DcaSchedule.twapBuy",u)}};var te=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new wi(this.client,this.evmClient).setTrade(t)}order(t){return new Ti(this.client,this.evmClient).setOrder(t)}};async function Ps(c,t){let{at:e}=t??{},i=new Ht(c),r=new ue(c),[n,s]=await Promise.all([i.getBlockTime(),i.getMinOrderBudget()]),a=new jt(c,r,e).withAave().withOmnipool().withStableswap().withXyk(),o=new pt(c),l=new De(c),u=new be(c),p=new At(r),d=new _t(a),m=new Jt(a,{blockTime:n,minBudgetInNative:s}),g=new Me(l,o),b=new he(u,o,{blockTime:n});return{api:{aave:p,router:d,scheduler:m,staking:g,farm:b},client:{asset:new Mt(c),balance:o,evm:r},ctx:{pool:a},tx:new te(c,r),destroy:()=>{a.destroy()}}}0&&(module.exports={QueryBus,aave,api,async,calc,client,const:null,createSdkContext,error,evm,farm,fmt,json,math,pool,sor,staking,tx});
|
|
1
|
+
"use strict";var Rs=Object.create;var We=Object.defineProperty;var Cs=Object.getOwnPropertyDescriptor;var ks=Object.getOwnPropertyNames;var Ms=Object.getPrototypeOf,Ds=Object.prototype.hasOwnProperty;var Bi=(c,t)=>()=>(c&&(t=c(c=0)),t);var R=(c,t)=>{for(var e in t)We(c,e,{get:t[e],enumerable:!0})},Ve=(c,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ks(t))!Ds.call(c,r)&&r!==e&&We(c,r,{get:()=>t[r],enumerable:!(i=Cs(t,r))||i.enumerable});return c},ft=(c,t,e)=>(Ve(c,t,"default"),e&&Ve(e,t,"default")),Tt=(c,t,e)=>(e=c!=null?Rs(Ms(c)):{},Ve(t||!c||!c.__esModule?We(e,"default",{value:c,enumerable:!0}):e,c)),Ls=c=>Ve(We({},"__esModule",{value:!0}),c);var se={};var _r=Bi(()=>{ft(se,require("@polkadot-api/sm-provider"))});var ne={};var Or=Bi(()=>{ft(ne,require("@polkadot-api/smoldot"))});var ae={};var Ar=Bi(()=>{ft(ae,require("@polkadot-api/known-chains/polkadot"))});var _n={};R(_n,{QueryBus:()=>he,aave:()=>Mi,api:()=>Fi,async:()=>me,calc:()=>C,client:()=>qi,const:()=>Li,createSdkContext:()=>In,error:()=>Hi,evm:()=>Vi,farm:()=>Qi,fmt:()=>I,json:()=>Wt,math:()=>z,pool:()=>ar,sor:()=>dr,staking:()=>br,tx:()=>Pr});module.exports=Ls(_n);var Fi={};R(Fi,{Papi:()=>N,Watcher:()=>re,getSm:()=>Hs,getWs:()=>Ns});var Dt=require("@galacticcouncil/descriptors");var xr=require("@galacticcouncil/common"),Mt=require("rxjs");var Pt=require("rxjs"),G=require("rxjs/operators");function wr(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>(0,Pt.defer)(()=>(0,Pt.from)(c._request("system_health",[]))).pipe((0,G.timeout)({first:e}),(0,G.map)(()=>"online"),(0,G.catchError)(()=>(0,Pt.of)("offline")));return(0,Pt.of)({state:"offline",delayMs:0}).pipe((0,G.expand)(s=>(0,Pt.timer)(s.delayMs).pipe((0,G.switchMap)(i),(0,G.map)(n=>({state:n,delayMs:t})))),(0,G.skip)(1),(0,G.map)(s=>s.state),(0,G.distinctUntilChanged)(),(0,G.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:qs}=xr.log,re=class c{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,Mt.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",wr(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe((0,Mt.tap)({error:i=>qs.error(t,i)}),(0,Mt.shareReplay)({bufferSize:1,refCount:!0}))}};var N=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(Dt.hydration),this.apiNext=this.client.getTypedApi(Dt.hydrationNext),this.apiIce=this.client.getTypedApi(Dt.hydrationIce),this.watcher=re.getInstance(this.client),this.at=e??"best"}};var Tr=require("polkadot-api/ws"),Ir=require("polkadot-api/logs-provider"),Ns=(c,t={})=>{let e=typeof c=="string"?c.split(","):c,i=(0,Tr.getWsProvider)(e,t);return(0,Ir.withLogsRecorder)(r=>console.log(r),i),i};async function Hs(c){let{getSmProvider:t}=await Promise.resolve().then(()=>(_r(),se)),{start:e}=await Promise.resolve().then(()=>(Or(),ne)),{chainSpec:i}=await Promise.resolve().then(()=>(Ar(),ae)),r=e(),s=await r.addChain({chainSpec:i}),n=await r.addChain({chainSpec:c,potentialRelayChains:[s]});return t(()=>n)}var Mi={};R(Mi,{AAVE_GAS_LIMIT:()=>Ci,AAVE_LENDING_POOL_ADDRESS:()=>$e,AAVE_POOL_ABI:()=>Ei,AAVE_POOL_DATA_PROVIDER:()=>Ye,AAVE_POOL_DATA_PROVIDER_ABI:()=>ze,AAVE_POOL_PROXY:()=>Ri,AAVE_ROUNDING_THRESHOLD:()=>Qn,AAVE_UINT_256_MAX:()=>Gs,AaveClient:()=>oe,AaveUtils:()=>Bt});var Ei=[{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 ze=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Ri="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ye="0x112b087b60C1a166130d59266363C45F8aa99db0",$e="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Ci=1000000n,Qn=5,Gs=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var oe=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:ze,address:Ye,args:[$e],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:ze,address:Ye,args:[$e,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:Ei,address:Ri,args:[t],functionName:"getUserAccountData"})}};var H=Tt(require("big.js")),nt=require("@galacticcouncil/common");var{ERC20:Lt}=nt.erc20,{H160:ki}=nt.h160,Us=1.01,Vs=31536000n,Br=4,Xe=-1,Ke=10n**27n,Bt=class{client;constructor(t){this.client=new oe(t)}async getSummary(t){let e=ki.fromAny(t),[i,r,s,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[a]=i,[o,l]=r,[u,p,d,m,h,b]=s,g=nt.big.toDecimal(b,18),y=[];for(let P of o){let v=P.underlyingAsset.toLowerCase(),S=a.find(({underlyingAsset:Ai})=>Ai.toLowerCase()===v);if(!S)throw new Error("Missing pool reserve for "+v);let T=P.scaledATokenBalance,B=S.liquidityIndex,D=S.liquidityRate,Q=S.availableLiquidity,U=S.priceInMarketReferenceCurrency,yt=n+6,tt=this.calculateLinearInterest(D,S.lastUpdateTimestamp,yt),ct=B*tt/Ke,xt=T*ct/Ke,He=Number(l!==0&&l===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,Ge=S.usageAsCollateralEnabled&&P.usageAsCollateralEnabledOnUser&&P.scaledATokenBalance>0n,Ue=Lt.toAssetId(v);y.push({aTokenBalance:xt,availableLiquidity:Q,decimals:Number(S.decimals),isCollateral:Ge,priceInRef:U,reserveId:Ue,reserveAsset:v,reserveLiquidationThreshold:He})}return{healthFactor:Number(g),currentLiquidationThreshold:Number(nt.big.toDecimal(m,Br)),totalCollateral:u,totalDebt:p,reserves:y}}async hasBorrowPositions(t){let e=ki.fromAny(t),i=await this.client.getUserAccountData(e),[r,s]=i;return s>0n}async getHealthFactor(t){let e=ki.fromAny(t),i=await this.client.getUserAccountData(e),[r,s,n,a,o,l]=i;return this.calculateHealthFactorFromBalances(s,r,a)}async getHealthFactorAfterWithdraw(t,e,i){let{totalCollateral:r,totalDebt:s,reserves:n,currentLiquidationThreshold:a}=await this.getSummary(t);if(s===0n)return Xe;let o=Lt.fromAssetId(e),l=n.find(v=>v.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:u,isCollateral:p,priceInRef:d,reserveLiquidationThreshold:m}=l,h=nt.big.toBigInt(i,u),b=p?h*d/10n**BigInt(u):0n,g=r-b;if(g<=0n)return 0;let y=(0,H.default)(r.toString()).mul(a).minus((0,H.default)(b.toString()).mul(m)).div(g.toString()),P=(0,H.default)(g.toString()).mul(y).div(s.toString()).toFixed(6,H.default.roundDown);return Number(P)}async getHealthFactorAfterSupply(t,e,i){let{totalCollateral:r,totalDebt:s,reserves:n,currentLiquidationThreshold:a}=await this.getSummary(t);if(s===0n)return Xe;let o=Lt.fromAssetId(e),l=n.find(P=>P.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:u,priceInRef:p,reserveLiquidationThreshold:d}=l,h=nt.big.toBigInt(i,u)*p/10n**BigInt(u),b=r+h;if(b<=0n)return 0;let g=(0,H.default)(r.toString()).mul(a).plus((0,H.default)(h.toString()).mul(d)).div(b.toString()),y=(0,H.default)(b.toString()).mul(g).div(s.toString()).toFixed(6,H.default.roundDown);return Number(y)}async getHealthFactorAfterSwap(t,e,i,r,s){let{totalDebt:n,reserves:a,healthFactor:o}=await this.getSummary(t);if(n===0n)return Xe;let l=Lt.fromAssetId(i),u=Lt.fromAssetId(s),p=a.find(B=>B.reserveAsset===l),d=a.find(B=>B.reserveAsset===u);if(!p)throw new Error(`Missing reserve ctx for ${l}`);if(!d)throw new Error(`Missing reserve ctx for ${d}`);let m=nt.big.toBigInt(e,p.decimals),h=nt.big.toBigInt(r,d.decimals),b=m*p.priceInRef/10n**BigInt(p.decimals),g=h*d.priceInRef/10n**BigInt(d.decimals),y=p.isCollateral?(0,H.default)(b.toString()).mul(p.reserveLiquidationThreshold):(0,H.default)(0),S=(d.isCollateral?(0,H.default)(g.toString()).mul(d.reserveLiquidationThreshold):(0,H.default)(0)).minus(y).div(n.toString()),T=(0,H.default)(o).plus(S).toFixed(6,H.default.roundDown);return Number(T)}async getMaxWithdraw(t,e){let{totalDebt:i,reserves:r,healthFactor:s}=await this.getSummary(t),n=Lt.fromAssetId(e),a=r.find(o=>o.reserveAsset===n);if(!a)throw new Error("Missing reserve ctx for "+n);return this.calculateWithdrawMax(a,i,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:i,healthFactor:r}=await this.getSummary(t),s={};for(let n of i){let a=this.calculateWithdrawMax(n,e,r);n.reserveId&&(s[n.reserveId]=a)}return s}calculateWithdrawMax(t,e,i){let{aTokenBalance:r,availableLiquidity:s,decimals:n,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=t,u=r;if(l&&e>0n){let d=i-Us;if(d>0){let m=(0,H.default)(d).mul(e.toString()).div(o).toFixed(0,H.default.roundDown),h=(0,H.default)(m).div(a.toString()).mul(10**n).toFixed(0,H.default.roundDown);u=r<BigInt(h)?r:BigInt(h)}else u=0n}return{amount:u<s?u:s,decimals:n}}calculateLinearInterest(t,e,i){let r=i-e;if(r<=0)return Ke;let s=t*BigInt(r)/Vs;return Ke+s}calculateHealthFactorFromBalances(t,e,i){if(t===0n)return Xe;let r=e*i/t,s=nt.big.toDecimal(r,Br);return Number(s)}};var qi={};R(qi,{AssetClient:()=>qt,BalanceClient:()=>mt,ChainParams:()=>Vt});var le=require("polkadot-api");var qt=class extends N{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:i,value:r})=>{let[s]=i;return[s,r]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:i,value:r})=>{let[s]=i;return[s,r]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:i})=>{let{asset_type:r}=i;return this.SUPPORTED_TYPES.includes(r.type)}).map(({keyArgs:i,value:r})=>{let[s]=i;return[s,r]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:i,value:r})=>{let[s]=i;return[s,r]}))}async mapToken(t,e,i,r){let{name:s,asset_type:n,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=i.get(t)??{};return{id:t,name:s?le.Binary.toText(s):void 0,symbol:l,decimals:u,icon:l,type:n.type,isSufficient:a,location:r,existentialDeposit:o}}async mapBond(t,e,i,r){let[s,n]=r,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:p}=await this.mapToken(s,e,i),d=Number(n),m=new Intl.DateTimeFormat("en-GB"),h=[u,"Bond",m.format(d)].join(" ");return{id:t,name:h,symbol:u+"b",decimals:p,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:s,maturity:d}}async mapShares(t,e,i,r){let{assets:s}=r,{name:n,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,p=await Promise.all(s.map(async h=>{let{symbol:b}=await this.mapToken(h,e,i);return[h,b]})),d=Object.fromEntries(p),m=Object.values(d);return{id:t,name:m.join(", "),symbol:a&&le.Binary.toText(a)||n&&le.Binary.toText(n),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:d}}async mapExternal(t,e,i,r){let s=await this.mapToken(t,e,new Map,r),n=i?.find(a=>a.internalId===s.id);return n?{...s,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:s}parseMetadata(t){return new Map(Array.from(t,([e,i])=>[e,{symbol:i.symbol?le.Binary.toText(i.symbol):void 0,decimals:i.decimals}]))}async getSupported(t,e){let[i,r,s,n]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(i),o=[];for(let[l,u]of Array.from(i)){let p=r.get(l),{asset_type:d}=u,m;switch(d.type){case"Bond":let h=n.get(l);m=await this.mapBond(l,u,a,h);break;case"StableSwap":let b=s.get(l);m=await this.mapShares(l,u,a,b);break;case"External":m=await this.mapExternal(l,u,e,p);break;default:m=await this.mapToken(l,u,a,p)}o.push(m)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var Fr=require("@galacticcouncil/common"),et=require("rxjs"),w=require("rxjs/operators");var Li={};R(Li,{HUB_ASSET_ID:()=>Ht,HYDRATION_OMNIPOOL_ADDRESS:()=>zs,HYDRATION_PARACHAIN_ID:()=>Ws,PERBILL_DENOMINATOR:()=>Di,PERMILL_DENOMINATOR:()=>Nt,SYSTEM_ASSET_DECIMALS:()=>je,SYSTEM_ASSET_ID:()=>k,TRADEABLE_DEFAULT:()=>Gt});var Nt=1e6,Di=1e9,k=0,je=12,Ws=2034,zs="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Ht=1,Gt=15;var{logger:Ut}=Fr.log,mt=class extends N{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:i}=await e.getValue(t,{at:this.at});return this.getBreakdown(i)}async getTokenBalance(t,e){let r=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(r)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,et.defer)(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),r=this.watchErc20Balance(t);return(0,et.combineLatest)([e,i,r]).pipe((0,w.connect)(s=>(0,et.concat)(s.pipe((0,w.take)(1)),s.pipe((0,w.skip)(1),(0,w.debounceTime)(250)))))}).pipe((0,w.map)(e=>e.flat()),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([e,i],r)=>r===0?i:this.getDeltas(e,i))).pipe((0,w.tap)({subscribe:()=>Ut.debug("balance: subscribe",t),error:e=>Ut.error("balance",e)}),(0,w.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,et.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,w.map)(({value:i})=>({id:0,balance:this.getBreakdown(i.data)})),(0,w.tap)({error:i=>Ut.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return(0,et.defer)(()=>i.watchValue(t,e,{at:"best"})).pipe((0,w.map)(({value:r})=>({id:e,balance:this.getBreakdown(r)})),(0,w.tap)({error:r=>Ut.error("balance(token)",r)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,et.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,w.distinctUntilChanged)((i,r)=>!r.deltas),(0,w.map)(({deltas:i})=>{let r=[];return i?.deleted.forEach(s=>{let[n,a]=s.args;r.push({id:a,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(s=>{let[n,a]=s.args;r.push({id:a,balance:this.getBreakdown(s.value)})}),r}),(0,w.tap)({error:i=>Ut.error("balance(tokens)",i)}))}watchErc20Balance(t,e){let i=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:n})=>n.asset_type.type==="Erc20").map(({keyArgs:n})=>{let[a]=n;return a}),this.erc20Ids},r=async s=>(await Promise.all(s.map(async a=>[a,await this.getBalanceData(t,a)]))).map(([a,o])=>({id:a,balance:o}));return(0,et.defer)(()=>(0,et.from)(e?Promise.resolve(e):i()).pipe((0,w.switchMap)(s=>this.watcher.bestBlock$.pipe((0,w.switchMap)(()=>(0,et.from)(r(s))))),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([s,n],a)=>a===0?n.filter(o=>o.balance.total>0n):this.getDeltas(s,n)),(0,w.distinctUntilChanged)((s,n)=>n.length===0),(0,w.tap)({error:s=>Ut.error("balance(erc20)",s)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(i)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,i=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:i,transferable:e}}getDeltas(t,e){let i=(s,n)=>s!==void 0&&n!==void 0&&s.transferable===n.transferable&&s.total===n.total,r=t.reduce((s,n)=>(s.set(n.id,n.balance),s),new Map);return e.filter(s=>!i(s.balance,r.get(s.id)))}};var Vt=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 Hi={};R(Hi,{AssetNotFound:()=>Ni,PoolNotFound:()=>Ft,RouteNotFound:()=>ce});var Ni=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},Ft=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},ce=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Vi={};R(Vi,{EvmClient:()=>pe,EvmRpcAdapter:()=>ue,createChain:()=>Ui});var Gi=require("polkadot-api"),Er=require("@galacticcouncil/descriptors"),Qe=require("viem"),Ys=10000000n,ue=class{api;constructor(t){this.api=t.getTypedApi(Er.hydration)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,i=e.timestamp/1000n,[r]=e.number;return{timestamp:i,number:r}}readContract=(async t=>{let{abi:e,address:i,functionName:r,args:s}=t,n=(0,Qe.encodeFunctionData)({abi:e,functionName:r,args:s}),a=await this.api.apis.EthereumRuntimeRPCApi.call("0x0000000000000000000000000000000000000000",i,Gi.Binary.fromHex(n),[0n,0n,0n,0n],[Ys,0n,0n,0n],void 0,void 0,void 0,!1,[],[]);if(!a.success)throw console.error(r,a.value.type),new Error("Contract read failure");let{exit_reason:o,value:l,used_gas:u}=a.value;if(console.log(u),o.type==="Succeed")return(0,Qe.decodeFunctionResult)({abi:e,functionName:r,data:Gi.Binary.toHex(l)});throw console.log(r,o.type,o.value.type),new Error("Contract read error")})};var Rr=require("viem"),$s=["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"],Ui=()=>(0,Rr.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:$s}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var dt=require("viem");var pe=class{client;chain;constructor(t){this.client=t,this.chain=Ui()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,dt.createPublicClient)({chain:this.chain,transport:(0,dt.http)()})}getWsProvider(){return(0,dt.createPublicClient)({transport:(0,dt.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,dt.createWalletClient)({account:t,chain:this.chain,transport:(0,dt.custom)(window.ethereum)})}getRPCAdapter(){return new ue(this.client)}};var Qi={};R(Qi,{LiquidityMiningApi:()=>ge,LiquidityMiningClient:()=>ye});var zr=require("polkadot-api"),Y=Tt(require("big.js")),St=require("@galacticcouncil/common"),ji=require("@galacticcouncil/math-liquidity-mining");var me={};R(me,{withTimeout:()=>Xs});function Xs(c,t,e="timeout"){return new Promise((i,r)=>{let s=setTimeout(()=>r(new Error(e)),t);c.then(n=>{clearTimeout(s),i(n)},n=>{clearTimeout(s),r(n)})})}var C={};R(C,{divSpot:()=>js,getFraction:()=>Qs,mulScaled:()=>Cr,mulSpot:()=>Ks});var Wi=require("@galacticcouncil/common");function Cr(c,t,e,i,r){let s=e+i-r,n=c*t;return s>0?n/BigInt(10)**BigInt(s):s<0?n*BigInt(10)**BigInt(-s):n}function Ks(c,t,e,i){return Cr(c,t,e,Wi.RUNTIME_DECIMALS,i)}function js(c,t,e,i){if(t===0n)return 0n;let r=BigInt(10)**BigInt(Wi.RUNTIME_DECIMALS+i-e);return c*r/t}function Qs(c,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let i=BigInt(10)**BigInt(e),r=BigInt(Math.round(t*Number(i)));return c*r/(BigInt(100)*i)}var I={};R(I,{FeeUtils:()=>zi,shiftNeg:()=>Js});var kr=Tt(require("big.js"));var zi=class c{static toPct(t){let[e,i]=t;return c.safeDivide(e*100,i)}static toRaw(t){let[e,i]=t;return c.safeDivide(e,i)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,i=12){let r=10**i;return Math.round(t*r/e)/r}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Js(c,t){let e=(0,kr.default)(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Wt={};R(Wt,{findNestedKey:()=>Zs,findNestedObj:()=>tn,jsonFormatter:()=>en});var Zs=(c,t)=>{let e=[];return JSON.stringify(c,(i,r)=>(r&&r[t]&&e.push(r),r)),e[0]},tn=(c,t,e)=>{let i;return JSON.stringify(c,(r,s)=>(s&&s[t]===e&&(i=s),s)),i},en=(c,t)=>typeof t=="bigint"?t.toString():t;var z={};R(z,{calculateBuyFee:()=>an,calculateDiffToAvg:()=>rn,calculateDiffToRef:()=>sn,calculateSellFee:()=>nn});var ht=Tt(require("big.js"));function rn(c,t){let e=(0,ht.default)(c.toString()),i=(0,ht.default)(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function sn(c,t){if(t===0n)return 0;let e=(0,ht.default)(c.toString()),i=(0,ht.default)(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function nn(c,t){if(c===0n)return 0;let e=(0,ht.default)(c.toString()),i=(0,ht.default)(t.toString());return(0,ht.default)(1).minus(i.div(e)).mul(100).round(2).toNumber()}function an(c,t){if(c===0n)return 0;let e=(0,ht.default)(c.toString());return(0,ht.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var de=(c,t)=>c===t?0:c==null?t==null?0:-1:t==null?c==null?0:1:typeof c.compare=="function"?c.compare(t):typeof t.compare=="function"?-t.compare(c):c<t?-1:c>t?1:0;var Je=(c,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(c(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var on=Je(()=>"illegal argument(s)"),Mr=c=>{throw new on(c)};var ln=Je(()=>"index out of bounds"),Yi=c=>{throw new ln(c)},Ze=(c,t,e)=>(c<t||c>=e)&&Yi(c);var Dr=23283064365386963e-26,ti=class{float(t=1){return this.int()*Dr*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*Dr-.5)*2*t}normMinMax(t,e){let i=this.minmax(t,e);return this.float()<.5?i:-i}minmax(t,e){return this.float()*(e-t)+t}minmaxInt(t,e){t|=0;let i=(e|0)-t;return i?t+this.int()%i:t}minmaxUint(t,e){t>>>=0;let i=(e>>>0)-t;return i?t+this.int()%i:t}};var ei=class extends ti{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 Lr=new ei(Math.random);var qr=c=>c!=null&&typeof c!="function"&&c.length!==void 0;var Nr=Object.getPrototypeOf({}),ii="function",Hr="string",zt=(c,t)=>{let e;if(c===t)return!0;if(c!=null){if(typeof c.equiv===ii)return c.equiv(t)}else return c==t;if(t!=null){if(typeof t.equiv===ii)return t.equiv(c)}else return c==t;return typeof c===Hr||typeof t===Hr?!1:(e=Object.getPrototypeOf(c),(e==null||e===Nr)&&(e=Object.getPrototypeOf(t),e==null||e===Nr)?mn(c,t):typeof c!==ii&&c.length!==void 0&&typeof t!==ii&&t.length!==void 0?cn(c,t):c instanceof Set&&t instanceof Set?un(c,t):c instanceof Map&&t instanceof Map?pn(c,t):c instanceof Date&&t instanceof Date?c.getTime()===t.getTime():c instanceof RegExp&&t instanceof RegExp?c.toString()===t.toString():c!==c&&t!==t)},cn=(c,t,e=zt)=>{let i=c.length;if(i===t.length)for(;i-- >0&&e(c[i],t[i]););return i<0},un=(c,t,e=zt)=>c.size===t.size&&e([...c.keys()].sort(),[...t.keys()].sort()),pn=(c,t,e=zt)=>c.size===t.size&&e([...c].sort(),[...t].sort()),mn=(c,t,e=zt)=>{if(Object.keys(c).length!==Object.keys(t).length)return!1;for(let i in c)if(!t.hasOwnProperty(i)||!e(c[i],t[i]))return!1;return!0};var $i=class{value;constructor(t){this.value=t}deref(){return this.value}};var Gr=c=>c instanceof $i;var ri=class c{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Ur("next",this._head)}reverseIterator(){return Ur("prev",this.tail)}clear(){this.release()}compare(t,e=de){let i=this._length;if(i<t._length)return-1;if(i>t._length)return 1;if(i===0)return 0;{let r=this._head,s=t._head,n=0;for(;i-- >0&&n===0;)n=e(r.value,s.value),r=r.next,s=s.next;return n}}concat(...t){let e=this.copy();for(let i of t)e.into(i);return e}equiv(t){if(!(t instanceof c||qr(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),i=this._head;for(let r=this._length;r-- >0;){if(!zt(i.value,e.next().value))return!1;i=i.next}return!0}filter(t){let e=this.empty();return this.traverse(i=>(t(i.value)&&e.append(i.value),!0)),e}find(t){return this.traverse(e=>e.value!==t)}findWith(t){return this.traverse(e=>!t(e.value))}first(){return this._head?.value}insertSorted(t,e){e=e||de;for(let i=this._head,r=this._length;r-- >0;){if(e(t,i.value)<=0)return this.insertBefore(i,t);i=i.next}return this.append(t)}into(t){for(let e of t)this.append(e);return this}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCellUnsafe(t){let e,i;for(t<=this._length>>>1?(e=this._head,i="next"):(e=this.tail,i="prev",t=this._length-t-1);t-- >0&&e;)e=e[i];return e}peek(){return this.tail?.value}$reduce(t,e){let i=this._head;for(let r=this._length;r-- >0&&!Gr(e);)e=t(e,i.value),i=i.next;return e}reduce(t,e){return this.$reduce(t,e)}release(){let t=this._head;if(!t)return!0;let e;for(let i=this._length;i-- >0;)e=t.next,delete t.value,delete t.prev,delete t.next,t=e;return this._head=void 0,this._length=0,!0}reverse(){let t=this._head,e=this.tail,i=(this._length>>>1)+(this._length&1);for(;t&&e&&i>0;){let r=t.value;t.value=e.value,e.value=r,t=t.next,e=e.prev,i--}return this}setHead(t){let e=this._head;return e?(e.value=t,e):this.prepend(t)}setNth(t,e){let i=this.nthCell(t);return!i&&Yi(t),i.value=e,i}setTail(t){let e=this.tail;return e?(e.value=t,e):this.append(t)}swap(t,e){if(t!==e){let i=t.value;t.value=e.value,e.value=i}return this}toArray(t=[]){return this.traverse(e=>(t.push(e.value),!0)),t}toJSON(){return this.toArray()}toString(){let t=[];return this.traverse(e=>(t.push(String(e.value)),!0)),t.join(", ")}traverse(t,e=this._head,i){if(!this._head)return;let r=e;do{if(!t(r))break;r=r.next}while(r!==i);return r}_map(t,e){return this.traverse(i=>(t.append(e(i.value)),!0)),t}};function*Ur(c,t){for(;t;)yield t.value,t=t[c]}var si=class c extends ri{_tail;constructor(t){super(),t&&this.into(t)}get tail(){return this._tail}append(t){if(this._tail){let e={value:t,prev:this._tail};return this._tail.next=e,this._tail=e,this._length++,e}else return this.prepend(t)}asHead(t){return t===this._head?this:(this.remove(t),this._head.prev=t,t.next=this._head,t.prev=void 0,this._head=t,this._length++,this)}asTail(t){return t===this._tail?this:(this.remove(t),this._tail.next=t,t.prev=this._tail,t.next=void 0,this._tail=t,this._length++,this)}cons(t){return this.prepend(t),this}copy(){return new c(this)}*cycle(){for(;;)yield*this}drop(){let t=this._head;if(t)return this._head=t.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,t.value}empty(){return new c}insertAfter(t,e){let i={value:e,next:t.next,prev:t};return t.next?t.next.prev=i:this._tail=i,t.next=i,this._length++,i}insertAfterNth(t,e){return t<0&&(t+=this._length),t>=this._length-1?this.append(e):(Ze(t,0,this._length),this.insertAfter(this.nthCellUnsafe(t),e))}insertBefore(t,e){let i={value:e,next:t,prev:t.prev};return t.prev?t.prev.next=i:this._head=i,t.prev=i,this._length++,i}insertBeforeNth(t,e){return t<0&&(t+=this._length),t<=0?this.prepend(e):(Ze(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new c,t)}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCell(t){if(t<0&&(t+=this._length),!(t<0||t>=this._length))return this.nthCellUnsafe(t)}pop(){let t=this._tail;if(t)return this._tail=t.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,t.value}prepend(t){let e={value:t,next:this._head};return this._head?this._head.prev=e:this._tail=e,this._head=e,this._length++,e}push(t){return this.append(t),this}release(){return this._tail=void 0,super.release()}remove(t){return t.prev?t.prev.next=t.next:this._head=t.next,t.next?t.next.prev=t.prev:this._tail=t.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let t=this.peek();return this.pop(),this.prepend(t),this}}seq(t=0,e=this.length){if(t>=e||t<0)return;let i=this.nthCell(t),r=this.nthCell(e-1),s=n=>({first(){return n.value},next(){return n!==r&&n.next?s(n.next):void 0}});return i?s(i):void 0}shuffle(t,e=Lr){if(this._length<2)return this;for(t=t!==void 0?t:Math.ceil(1.5*Math.log2(this._length));t>0;t--){let i=this._head;for(;i;){let r=i.next;e.probability(.5)?this.asHead(i):this.asTail(i),i=r}}return this}slice(t=0,e=this.length){let i=t<0?t+this._length:t,r=e<0?e+this._length:e;(i<0||r<0)&&Mr("invalid indices: ${from} / ${to}");let s=new c,n=this.nthCell(i);for(;n&&++i<=r;)s.push(n.value),n=n.next;return s}sort(t=de){if(!this._length)return this;let e=1;for(;;){let i=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;i;){r++;let s=i,n=0;for(let o=0;o<e&&(n++,s=s.next,!!s);o++);let a=e;for(;n>0||a>0&&s;){let o;n===0?(o=s,s=s.next,a--):!s||a===0||t(i.value,s.value)<=0?(o=i,i=i.next,n--):(o=s,s=s.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}i=s}if(this._tail.next=void 0,r<=1)return this;e*=2}}splice(t,e=0,i){let r;typeof t=="number"?(t<0&&(t+=this._length),Ze(t,0,this._length),r=this.nthCellUnsafe(t)):r=t;let s=new c;if(e>0)for(;r&&e-- >0;)this.remove(r),s.push(r.value),r=r.next;else r&&(r=r.next);if(i)if(r)for(let n of i)this.insertBefore(r,n);else for(let n of i)this.push(n);return s}};var ni=class c{map;items;opts;_size;constructor(t,e){let i={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...e};this.map=i.map(),this.items=new si,this._size=0,this.opts=i,t&&this.into(t)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let t of this.items)yield[t.k,t]}*keys(){for(let t of this.items)yield t.k}*values(){for(let t of this.items)yield t.v}copy(){let t=this.empty();t.items=this.items.copy();let e=t.items.head;for(;e;)t.map.set(e.value.k,e),e=e.next;return t}empty(){return new c(null,this.opts)}release(){this._size=0,this.map.clear();let t=this.opts.release;if(t){let e;for(;e=this.items.drop();)t(e.k,e.v);return!0}return this.items.release()}has(t){return this.map.has(t)}get(t,e){let i=this.map.get(t);return i?this.resetEntry(i):e}set(t,e){let i=this.opts.ksize(t)+this.opts.vsize(e),r=this.map.get(t),s=Math.max(0,i-(r?r.value.s:0));return this._size+=s,this.ensureSize()?this.doSetEntry(r,t,e,i):this._size-=s,e}into(t){for(let e of t)this.set(e[0],e[1]);return this}async getSet(t,e){let i=this.map.get(t);return i?this.resetEntry(i):this.set(t,await e())}delete(t){let e=this.map.get(t);return e?(this.removeEntry(e),!0):!1}resetEntry(t){return this.items.asTail(t),t.value.v}ensureSize(){let{release:t,maxsize:e,maxlen:i}=this.opts;for(;this._size>e||this.length>=i;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),t?.(r.k,r.v),this._size-=r.s}return!0}removeEntry(t){let e=t.value;this.map.delete(e.k),this.items.remove(t),this.opts.release?.(e.k,e.v),this._size-=e.s}doSetEntry(t,e,i,r){t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=r,this.items.asTail(t)):(this.items.push({k:e,v:i,s:r}),this.map.set(e,this.items.tail))}};var Et=class c extends ni{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new c(null,this.opts)}has(t){return this.get(t)!==void 0}get(t,e){let i=this.map.get(t);if(i){if(i.value.t>=Date.now())return this.resetEntry(i);this.removeEntry(i)}return e}set(t,e,i=this.opts.ttl){let r=this.opts.ksize(t)+this.opts.vsize(e),s=this.map.get(t),n=Math.max(0,r-(s?s.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(s,t,e,r,i):this._size-=n,e}async getSet(t,e,i=this.opts.ttl){let r=this.get(t);return r!==void 0?r:this.set(t,await e(),i)}prune(){let t=Date.now(),e=this.items.head,i=0;for(;e;)e.value.t<t&&(this.removeEntry(e),i++),e=e.next;return i}ensureSize(){let{maxlen:t,maxsize:e}=this.opts,i=Date.now(),r=this.items.head;for(;r&&(this._size>e||this.length>=t);)r.value.t<i&&this.removeEntry(r),r=r.next;return super.ensureSize()}doSetEntry(t,e,i,r,s=this.opts.ttl){let n=Date.now()+s;t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=r,t.value.t=n,this.items.asTail(t)):(this.items.push({k:e,v:i,s:r,t:n,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 he=class{debug;constructor(t){this.debug=t||!1}log(t,e,i){this.debug&&console.log(t,e,i)}scope(t,e,i,r){let s=new Map,n=r!==void 0?new Et(null,{ttl:r}):new Et;return{get:(...u)=>{let p=i(...u);if(s.has(p)){this.log("[live]",t,p);let m=s.get(p);return Promise.resolve(m)}if(n.has(p))return this.log("[memo]",t,p),n.get(p);this.log("[fetch]",t,p);let d=e(...u).catch(m=>{throw n.delete(p),m});return n.set(p,d),d},set:(u,...p)=>{let d=i(...p);this.log("[set-live]",t,d),s.set(d,u)},clear:()=>{this.log("[clear]",t),s.clear(),n.release()}}}};var ai=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let i=0;i<t.length;++i){let[r,s]=t[i];this.result.set(this.getKey(s,r),e[i].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,i,r){let s=this.getKey(t,e),n=this.getKey(t,i),a=this.result.get(s)??0n,o=this.result.get(n)??0n;if(a<r)throw new Error("Attempting to transfer more than is present");this.result.set(s,a+r),this.result.set(n,o+r)}};var It=Tt(require("big.js")),ut=require("@galacticcouncil/math-liquidity-mining");var Xi=Tt(require("big.js")),Ki=(0,Xi.default)(10).pow(18),Vr=BigInt((0,Xi.default)(1).pow(18).toString()),Wr=6e3;var dn="1000000000000000000",oi=class{constructor(t,e,i){this.getAccount=t;this.getAsset=e;this.multiCurrency=i}async syncGlobalFarm(t,e,i){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let r=await this.getAsset(t.reward_currency),s=e-t.updated_at,n=this.getAccount(t.id),a=r?.existential_deposit;if(!a)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,n),l=(0,It.default)(a.toString()),u=(0,It.default)(o.toString()).minus(l.lt(o.toString())?a.toString():o.toString()),p=(0,It.default)((0,ut.calculate_global_farm_rewards)(t.total_shares_z.toString(),i.toString(),(0,It.default)(t.yield_per_period.toString()).mul(Ki).round(0,It.default.roundDown).toFixed(),t.max_reward_per_period.toString(),s.toFixed()));if(u.lt(p)&&(p=u),p.eq(0))return t;let d=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,n,d,BigInt(p.toFixed())),{...t,accumulated_rpz:BigInt((0,ut.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),p.toFixed()))}}syncYieldFarm(t,e,i){if(t.state.type!=="Active"||t.updated_at===i)return t;if(t.total_valued_shares===0n)return{...t,updated_at:i};let r=(0,ut.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(r),updated_at:i}}getLoyaltyMultiplier(t,e){let i=(0,It.default)(1).mul(Ki).round(0,It.default.roundDown).toString();if(!e)return i;let{initial_reward_percentage:r,scale_coef:s}=e;return(0,ut.calculate_loyalty_multiplier)(t.toFixed(),r.toString(),s.toFixed())}async claimRewards(t,e,i,r,s){if(e.state.type==="Terminated")return null;let n=Math.floor(r/t.blocks_per_period);if(i.updated_at===n)return null;let a=await this.syncGlobalFarm(t,n,s);if(!a)return null;let o=this.syncYieldFarm(e,a,n);if(!o)return null;let l=o.total_stopped-i.stopped_at_creation,u=o.updated_at-i.entered_at-l,p=this.getLoyaltyMultiplier(u,o.loyalty_curve),d=BigInt((0,ut.calculate_user_reward)(i.accumulated_rpvs.toString(),i.valued_shares.toString(),i.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),m=BigInt((0,ut.calculate_user_reward)(i.accumulated_rpvs.toString(),i.valued_shares.toString(),i.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),dn));return{reward:d,maxReward:m,assetId:a.reward_currency,yieldFarmId:o.id,isActiveFarm:o.state.type==="Active"}}};var hn=(0,Y.default)(365.2425).times(24).times(60).times(60),ge=class{balance;client;options;constructor(t,e,i={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:i.blockTime??Wr})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let i=[t,e].sort((s,n)=>s-n);if(t===e)return Vr;let r=await this.client.getOraclePrice(i);if(r){let{n:s,d:n}=r[0].price,a;return t<e?a=(0,ji.fixed_from_rational)(s.toString(),n.toString()):a=(0,ji.fixed_from_rational)(n.toString(),s.toString()),BigInt(a)}}getFarmAddress=(t,e)=>{let i=Buffer.from("modl","utf-8"),r=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),s=Buffer.from([t]),n=Buffer.concat([i,r,s]),o="0x"+Buffer.concat([n,Buffer.alloc(32-n.length)]).toString("hex");return(0,zr.AccountId)(St.HYDRATION_SS58_PREFIX).dec(o)};getGlobalRewardPerPeriod(t,e,i,r){let s=(0,Y.default)(r).times(t.toString()).times(e.toString()).div(Math.pow(10,St.RUNTIME_DECIMALS));return s.gte(i.toString())?i.toString():s.toString()}getPoolYieldPerPeriod(t,e,i,r){let s=(0,Y.default)(t.toString()).times(e),n=(0,Y.default)(i.toString()).times(r);return s.div(n.toString()).toString()}farmData(t,e,i){let{yieldFarm:r,globalFarm:s,priceAdjustment:n,balance:a,id:o}=t,{multiplier:l,loyalty_curve:u}=r,{blocks_per_period:p,yield_per_period:d,total_shares_z:m,max_reward_per_period:h,pending_rewards:b,accumulated_paid_rewards:g,planned_yielding_periods:y,updated_at:P,incentivized_asset:v,reward_currency:S,price_adjustment:T,min_deposit:B}=s,D=I.shiftNeg(n??T,St.RUNTIME_DECIMALS),Q=I.shiftNeg(l,St.RUNTIME_DECIMALS),U=I.shiftNeg(u?.initial_reward_percentage??0,St.RUNTIME_DECIMALS),yt=hn.div((0,Y.default)(this.blockTime).div(1e3).times(p)).toString(),tt;if(m<=0)tt=(0,Y.default)(Q).times(d.toString()).times(yt).div(Math.pow(10,St.RUNTIME_DECIMALS)).toString();else{let Fs=this.getGlobalRewardPerPeriod(m,d,h,D),Es=this.getPoolYieldPerPeriod(Fs,Q,m,D);tt=(0,Y.default)(Es).times(yt).toString()}let ct=b+g,xt=h*BigInt(y),Ne=a.transferable+ct,Sr=Ne-ct,He=(0,Y.default)(Sr.toString()).div(h.toString()),Ge=(0,Y.default)(e).div(p.toString()).toString(),Ue=(m>=0?He.plus(P):He.plus(Ge)).toString(),Ai=(0,Y.default)(Ue).times(p).toString(),As=(0,Y.default)(m.toString()).div((0,Y.default)(h.toString()).div(d.toString())).div(Math.pow(10,St.RUNTIME_DECIMALS)).times(100).times(D).toFixed(2),vr=(0,Y.default)(ct.toString()).div(Ne.toString()).gte(.999);tt=vr?"0":(0,Y.default)(tt).div(i?2:1).times(100).toString();let Bs=U?(0,Y.default)(tt).times(U).toString():void 0;return{apr:tt,minApr:Bs,isDistributed:vr,estimatedEndPeriod:Ue,estimatedEndBlock:Ai,maxRewards:xt,incentivizedAsset:v,rewardCurrency:S,loyaltyCurve:u,currentPeriod:Ge,potMaxRewards:Ne,fullness:As,yieldFarmId:r.id,globalFarmId:s.id,poolId:o,distributedRewards:ct,plannedYieldingPeriods:y,minDeposit:B,blocksPerPeriod:p}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((r,s)=>r.includes(s.keyArgs[0].toString())?r:[...r,s.keyArgs[0].toString()],[]),i=await Promise.all(e.map(async r=>{let s=await this.getOmnipoolFarms(r);if(s)return[r,s]}));return Object.fromEntries(i.filter(r=>!!r))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),i=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:s,value:n})=>{let[,a]=s,o=n,l=await this.client.getOmnipoolGlobalFarm(a),u=await this.client.getOmnipoolYieldFarm(Number(t),a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a),h=await this.getOraclePrice(p,d),b=await this.balance.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:h,balance:b}}));return i?r.map(s=>s?this.farmData(s,i):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((r,s)=>r.includes(s.keyArgs[0].toString())?r:[...r,s.keyArgs[0].toString()],[]),i=await Promise.all(e.map(async r=>{let s=await this.getIsolatedFarms(r);if(s)return[r,s]}));return Object.fromEntries(i.filter(r=>!!r))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),i=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:s,value:n})=>{let[,a]=s,o=n,l=await this.client.getIsolatedGlobalFarm(a),u=await this.client.getIsolatedYieldFarm(t,a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a,!0),h=await this.getOraclePrice(p,d),b=await this.balance.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:h,balance:b,farmAddress:m}}));return i?r.map(s=>s?this.farmData(s,i,!0):void 0):[]}async getDepositReward(t,e,i,r){let s=e.global_farm_id,n=e.yield_farm_id,a=i?await this.client.getIsolatedYieldFarm(t,s,n):await this.client.getOmnipoolYieldFarm(Number(t),s,n),o=i?await this.client.getIsolatedGlobalFarm(s):await this.client.getOmnipoolGlobalFarm(s);if(!o||!a)return;let l=o.reward_currency,u=o.incentivized_asset,p=[[this.getFarmAddress(0,i),o.reward_currency],[this.getFarmAddress(o.id,i),o.reward_currency]],d=await this.getAccountAssetBalances(p),m=await this.getOraclePrice(l,u),h=new ai(p,d),g=await new oi(P=>this.getFarmAddress(P),P=>this.client.getAsset(P),h).claimRewards(o,a,e,r,m??o.price_adjustment);if(!g)return;let y=await this.client.getAsset(g.assetId);if(y&&!(g.reward<=y.existential_deposit))return g}async getAccountAssetBalances(t){let[e,i]=await Promise.all([Promise.all(t.filter(([s,n])=>n!==0).map(([s,n])=>this.balance.getTokenBalance(s,n))),Promise.all(t.filter(([s,n])=>n===0).map(([s])=>this.balance.getSystemBalance(s)))]),r=[];for(let s=0,n=0;s+n<t.length;){let a=s+n,[,o]=t[a];o===0?(r.push(i[n]),n+=1):(r.push(e[s]),s+=1)}return r}};var be=require("polkadot-api"),gn=be.Binary.toHex(be.Binary.fromText("omnipool")),ye=class extends N{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(gn,t,(0,be.Enum)("TenMinutes"))}async getRelayBlockNumber(){return(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number}async getAllOmnipooFarms(){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries()}async getOmnipooFarms(t){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries(t)}async getOmnipoolGlobalFarm(t){return this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getOmnipoolYieldFarm(t,e,i){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,i,{at:"best"})}async getAllIsolatedFarms(){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries()}async getIsolatedFarms(t){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries(t)}async getIsolatedGlobalFarm(t){return this.api.query.XYKWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getIsolatedYieldFarm(t,e,i){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,i,{at:"best"})}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};var ar={};R(ar,{PoolContextProvider:()=>Zt,PoolError:()=>_t,PoolFactory:()=>Jt,PoolType:()=>F,SnapshotPoolCtxProvider:()=>yi,aave:()=>rr,hsm:()=>nr,lbp:()=>Ji,omni:()=>tr,stable:()=>er,xyk:()=>ir});var Ji={};R(Ji,{LbpMath:()=>pt,LbpPool:()=>fe,LbpPoolClient:()=>Pe});var gt=require("@galacticcouncil/math-lbp"),pt=class{static getSpotPrice(t,e,i,r,s){return(0,gt.get_spot_price)(t,e,i,r,s)}static calculateInGivenOut(t,e,i,r,s){return(0,gt.calculate_in_given_out)(t,e,i,r,s)}static calculateOutGivenIn(t,e,i,r,s){return(0,gt.calculate_out_given_in)(t,e,i,r,s)}static calculateLinearWeights(t,e,i,r,s){return(0,gt.calculate_linear_weights)(t,e,i,r,s)}static calculatePoolTradeFee(t,e,i){return(0,gt.calculate_pool_trade_fee)(t,e,i)}};var Yt=require("@galacticcouncil/common");var F=(n=>(n.Aave="Aave",n.LBP="LBP",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="XYK",n.HSM="HSM",n))(F||{}),_t=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(_t||{});var{FeeUtils:Yr}=I,fe=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),r=i.get(t),s=i.get(e);if(r==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:r.balance,balanceOut:s.balance,decimalsIn:r.decimals,decimalsOut:s.decimals,weightIn:r.weight,weightOut:s.weight}}validateAndBuy(t,e,i){let r=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let n=t.balanceOut/this.maxOutRatio;if(e>n&&s.push("MaxOutRatioExceeded"),r===t.assetOut){let a=this.calculateTradeFee(e,i),o=Yr.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return u>p&&s.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:s}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&s.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:s}}}validateAndSell(t,e,i){let r=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let n=t.balanceIn/this.maxInRatio;if(e>n&&s.push("MaxInRatioExceeded"),r===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:s}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,i),l=Yr.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),u=a-o,p=t.balanceOut/this.maxOutRatio;return u>p&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:s}}}calculateInGivenOut(t,e){let i=pt.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}calculateOutGivenIn(t,e){let i=pt.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}spotPriceInGivenOut(t){let e=pt.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),Yt.big.toBigInt(1,Yt.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=pt.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),Yt.big.toBigInt(1,Yt.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let i=pt.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var jr=require("polkadot-api"),Ot=require("rxjs");var $r=(c,t=new Map)=>e=>{let i;return t.has(e)?t.get(e):(t.set(e,i=c(e)),i)};var _=require("rxjs"),f=require("rxjs/operators");var Xr=require("rxjs"),li=class{store$=new Xr.BehaviorSubject([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(t){return this.changeset.size===0?[]:t.filter(e=>this.changeset.has(e.address))}set(t){this.changeset=new Set(t.map(e=>e.address)),this.store$.next(t)}update(t){this.updateQueue=this.updateQueue.then(async()=>{let e=this.store$.value,i=new Map(e.map((a,o)=>[a.address,o])),r=await t(e),s=e.slice(),n=new Set;for(let a of r){let o=i.get(a.address);o===void 0?(i.set(a.address,s.length),s.push(a)):s[o]=a,n.add(a.address)}this.changeset=n,this.store$.next(s)}).catch(console.error)}destroy(){this.store$.complete()}};var Kr=require("@galacticcouncil/common");var bn={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:ci}=Kr.log,ui=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${bn[this.type]})`,10)}trace(t,...e){ci.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){ci.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){ci.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){ci.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:yn}=me,fn=3e3,J=class extends N{evm;balance;store=new li;log;shared$;resync$=new _.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new Et(null,{ttl:6*1e3});memPools=$r(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e,i){super(t,i),this.evm=e,this.balance=new mt(t,i),this.log=new ui(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){let e=(await this.getMemPools()).filter(i=>this.hasValidAssets(i));return this.store.set(e),e}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe((0,f.startWith)([]),(0,f.bufferCount)(2,1),(0,f.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,f.filter)(t=>t.length>0),(0,f.throttleTime)(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return(0,_.defer)(()=>{let t=new _.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,f.switchMap)(()=>{let e=new _.Subscription;return(0,_.from)(yn(this.getMemPools(),6e4,"getMemPools stalled")).pipe((0,f.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,f.map)(r=>r.filter(s=>this.hasValidAssets(s))),(0,f.tap)(r=>this.store.set(r)),(0,f.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),_.EMPTY))).pipe((0,f.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,f.switchMap)(r=>(0,_.merge)((0,_.of)(r),this.store.asObservable().pipe((0,f.skip)(1)))),(0,f.finalize)(()=>{e.unsubscribe()}))}),(0,f.finalize)(()=>t.unsubscribe()))}).pipe((0,f.share)({connector:()=>new _.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:i}=e,r=[this.balance.watchTokensBalance(i)];if(this.hasSystemAsset(e)){let s=this.balance.watchSystemBalance(i);r.push(s)}if(this.hasErc20Asset(e)){let s=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),n=this.balance.watchErc20Balance(i,s);r.push(n)}return(0,_.combineLatest)(r).pipe((0,f.map)(s=>s.flat()),(0,f.pairwise)(),(0,f.map)(([s,n])=>this.balance.getDeltas(s,n)),(0,f.filter)(s=>s.length>0),(0,f.map)(s=>[i,s]))});return(0,_.merge)(...t).pipe((0,f.bufferTime)(250),(0,f.filter)(e=>e.length>0),(0,f.map)(e=>new Map(e)),this.watchGuard("balances")).subscribe(e=>{this.store.update(i=>this.updateBalances(i,e))})}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:i})=>t.type==="XYK"?i>0n&&!!e:!!e)}updateBalances=(t,e)=>{let i=[],r=new Map(t.map(s=>[s.address,s]));for(let[s,n]of e){let a=r.get(s);if(a){let o=a.tokens.map(l=>{let u=n.find(p=>p.id===l.id);return u&&l.id!==a.id?{...l,balance:u.balance.transferable}:l});i.push({...a,tokens:o})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<fn||(this.resyncAt=e,this.mem++,this.resync$.next())}requestResync(t=!1){this.resyncPending||(this.resyncPending=!0,setTimeout(()=>{this.resyncPending=!1,this.resync(t)},0))}startWatchdog(){let r=this.watcher.connection$.pipe((0,f.pairwise)(),(0,f.filter)(([a,o])=>a==="offline"&&o==="online"),(0,f.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,f.catchError)(a=>(this.log.error("watchdog_recovery_error",a),_.EMPTY)),(0,f.repeat)({delay:1e3})),s=this.watcher.finalizedBlock$.pipe((0,f.pairwise)(),(0,f.tap)(([a,o])=>{let l=Number(a.number),u=Number(o.number),p=u-l;p>=3&&(this.log.debug("watchdog_gap",{from:l,to:u,gap:p}),this.requestResync())}),(0,f.catchError)(a=>(this.log.error("watchdog_gap_error",a),_.EMPTY)),(0,f.repeat)({delay:1e3})),n=(0,_.interval)(36e5).pipe((0,f.tap)(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),(0,f.catchError)(a=>(this.log.error("watchdog_periodic_error",a),_.EMPTY)),(0,f.repeat)({delay:1e3}));return(0,_.merge)(r,s,n).subscribe()}watchGuard(t){return e=>e.pipe((0,f.tap)({error:i=>{this.log.error(t,i),this.requestResync(!0)}}),(0,f.finalize)(()=>{this.log.debug(t,"unsub")}),(0,f.catchError)(()=>_.EMPTY))}};var Pe=class extends J{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}getPoolWeights(t,e){let{start:i,end:r,initial_weight:s,final_weight:n}=t,a=pt.calculateLinearWeights(i?i.toString():"0",r?r.toString():"0",s.toString(),n.toString(),e.toString()),o=BigInt(a),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){return(await this.api.getStaticApis()).compat.query.LBP.PoolData.isCompatible(jr.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:this.at}),this.api.query.ParachainSystem.ValidationData.getValue({at:this.at}),this.getPoolLimits()]),r=e?.relay_parent_number||0,s=t.filter(({value:n})=>e&&this.isActivePool(n,r)).map(async({keyArgs:n,value:a})=>{let[o]=n,l=o.toString(),u=await this.getPoolDelta(l,a,r);return{address:l,type:"LBP",fee:a.fee,...u,...i}});return Promise.all(s)}async getPoolDelta(t,e,i){let{assets:r,repay_target:s,fee_collector:n}=e,[a,o]=this.getPoolWeights(e,i),[l,u]=r,[p,d,m,h,b]=await Promise.all([this.isRepayFeeApplied(l,s,n.toString()),this.balance.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l,{at:this.at}),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u,{at:this.at})]);return{repayFeeApply:p,tokens:[{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,weight:a,type:m?.asset_type.type},{id:u,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:h.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(t,e){let{start:i,end:r}=t;return i&&r?e>=i&&e<r:!1}async isRepayFeeApplied(t,e,i){if(e===0n)return!1;try{return(await this.balance.getBalance(i,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let i=this.store.pools.find(s=>s.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:i.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue({at:"best"}).pipe((0,Ot.map)(({value:t})=>t),(0,Ot.filter)(t=>t!==void 0),(0,Ot.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let i=[];for(let r of e){let s=this.poolsData.get(r.address);if(s){let{assets:n,repay_target:a,fee_collector:o}=s,[l]=n,[u,p]=this.getPoolWeights(s,t),[d,m]=r.tokens,h=[{...d,weight:u},{...m,weight:p}],b=await this.isRepayFeeApplied(l,a,o.toString());i.push({...r,tokens:h,repayFeeApply:b})}}return i})})}subscribeUpdates(){let t=new Ot.Subscription;return t.add(this.subscribeValidationData()),t}};var tr={};R(tr,{OmniMath:()=>E,OmniPool:()=>Se,OmniPoolClient:()=>ve,OmniPoolFee:()=>Ct,getEmaKey:()=>pi,getEmaPair:()=>$t});var x=require("@galacticcouncil/math-omnipool"),Rt=Tt(require("big.js")),E=class{static calculateSpotPrice(t,e,i,r){return(0,x.calculate_spot_price)(t,e,i,r)}static calculateLrnaSpotPrice(t,e){return(0,x.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,i,r,s,n,a,o,l,u){return(0,x.calculate_in_given_out)(t,e,i,r,s,n,a,o,l,u)}static calculateLrnaInGivenOut(t,e,i,r,s,n){return(0,x.calculate_lrna_in_given_out)(t,e,i,r,s,n)}static calculateOutGivenIn(t,e,i,r,s,n,a,o,l,u){return(0,x.calculate_out_given_in)(t,e,i,r,s,n,a,o,l,u)}static calculateOutGivenLrnaIn(t,e,i,r,s,n){return(0,x.calculate_out_given_lrna_in)(t,e,i,r,s,n)}static calculateShares(t,e,i,r){return(0,x.calculate_shares)(t,e,i,r)}static calculateLiquidityOut(t,e,i,r,s,n,a,o){return(0,x.calculate_liquidity_out)(t,e,i,r,s,n,a,o)}static calculateLiquidityLRNAOut(t,e,i,r,s,n,a,o){return(0,x.calculate_liquidity_lrna_out)(t,e,i,r,s,n,a,o)}static calculateCapDifference(t,e,i,r){let s=(0,Rt.default)(e),n=(0,Rt.default)(t),a=(0,Rt.default)(r),o=(0,Rt.default)(i),l=(0,Rt.default)(10).pow(18),u=o.div(l);if(s.div(a).lt(u)){let d=u.times(a).minus(s).times(n),m=s.times((0,Rt.default)(1).minus(u));return d.div(m).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,r){return(0,x.calculate_liquidity_hub_in)(t,e,i,r)}static isSellAllowed(t){return(0,x.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,x.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,x.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,x.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,i,r,s,n,a,o,l,u,p){return(0,x.recalculate_asset_fee)(t,e,i,r,s,n,a,o,l,u,p)}static recalculateProtocolFee(t,e,i,r,s,n,a,o,l,u,p){return(0,x.recalculate_protocol_fee)(t,e,i,r,s,n,a,o,l,u,p)}static verifyAssetCap(t,e,i,r){return(0,x.verify_asset_cap)(t,e,i,r)}};var Qr=require("@galacticcouncil/common");var{FeeUtils:bt}=I,Se=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),r=i.get(t),s=i.get(e);if(r==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:r.hubReserves,hubReservesOut:s.hubReserves,sharesIn:r.shares,sharesOut:s.shares,decimalsIn:r.decimals,decimalsOut:s.decimals,balanceIn:r.balance,balanceOut:s.balance,tradeableIn:r.tradeable,tradeableOut:s.tradeable,assetInEd:r.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,i),n=r===0n?0:z.calculateBuyFee(r,s),a=[],o=E.isSellAllowed(t.tradeableIn),l=E.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return s>p&&a.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:r,amountOut:e,feePct:n,errors:a}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,i),n=z.calculateSellFee(r,s),a=[],o=E.isSellAllowed(t.tradeableIn),l=E.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return s>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:s,feePct:n,errors:a}}calculateInGivenOut(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,i);let r=E.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?bt.toRaw(i.assetFee).toString():"0",i?bt.toRaw(i.protocolFee).toString():"0",i?bt.toRaw(i.maxSlipFee).toString():"0"),s=BigInt(r);return s<0n?0n:s}calculateLrnaInGivenOut(t,e,i){let r=E.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?bt.toRaw(i.assetFee).toString():"0",i?bt.toRaw(i.maxSlipFee).toString():"0"),s=BigInt(r);return s<0n?0n:s}calculateOutGivenIn(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,i);let r=E.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?bt.toRaw(i.assetFee).toString():"0",i?bt.toRaw(i.protocolFee).toString():"0",i?bt.toRaw(i.maxSlipFee).toString():"0"),s=BigInt(r);return s<0n?0n:s}calculateOutGivenLrnaIn(t,e,i){let r=E.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?bt.toRaw(i.assetFee).toString():"0",i?bt.toRaw(i.maxSlipFee).toString():"0"),s=BigInt(r);return s<0n?0n:s}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=E.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceLrnaInGivenOut(t){let e=E.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=E.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}spotPriceOutGivenLrnaIn(t){let e=E.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,i){let r=e-i;if(r===0)return t;let s=Qr.big.pow10(Math.abs(r));return r>0?t*s:t/s}};var vt=require("polkadot-api"),ts=require("@polkadot-api/utils"),O=require("rxjs"),es=require("@galacticcouncil/common");var{FeeUtils:V}=I,Ct=class c{static compute(t,e,i,r,s,n,a,o){let l=t.assetIn,[u,p,d]=c.getAssetFee(t,e,i,r,n),m=0,h=0,b=0;l!==1&&([m,h,b]=c.getProtocolFee(t,e,i,s,a));let g=u+m,y=d+b;return{assetFee:V.fromPermill(p),protocolFee:V.fromPermill(h),maxSlipFee:V.fromPermill(o),min:V.fromPermill(g),max:V.fromPermill(y)}}static getAssetFee(t,e,i,r,s){let{assetOut:n,balanceOut:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=s;if(!i||!r)return[o,o,l];let d=V.fromPermill(o),m=V.fromPermill(l),[h]=r,{asset_fee:b,timestamp:g}=i,y=Math.max(1,e-g),P=h.volume.b_in.toString(),v=h.volume.b_out.toString(),S=h.liquidity.b.toString();n===0&&(P=h.volume.a_in.toString(),v=h.volume.a_out.toString(),S=h.liquidity.a.toString());let T=V.fromPermill(b),B=E.recalculateAssetFee(P,v,S,"9",a.toString(),V.toRaw(T).toString(),y.toString(),V.toRaw(d).toString(),V.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(B)*1e6,l]}static getProtocolFee(t,e,i,r,s){let{assetIn:n,balanceIn:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=s;if(!i||!r)return[o,o,l];let d=V.fromPermill(o),m=V.fromPermill(l),[h]=r,{protocol_fee:b,timestamp:g}=i,y=Math.max(1,e-g),P=h.volume.b_in.toString(),v=h.volume.b_out.toString(),S=h.liquidity.b.toString();n===0&&(P=h.volume.a_in.toString(),v=h.volume.a_out.toString(),S=h.liquidity.a.toString());let T=V.fromPermill(b),B=E.recalculateProtocolFee(P,v,S,"9",a.toString(),V.toRaw(T).toString(),y.toString(),V.toRaw(d).toString(),V.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(B)*1e6,l]}};var $t=c=>c===0?[0,1]:[1,c],pi=c=>$t(c).join(":");var{FeeUtils:Zi}=I,Jr=vt.Binary.toHex(vt.Binary.fromText("omnipool")),Zr=(0,vt.Enum)("Short"),ve=class extends J{queryBus=new he;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:this.at}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:this.at}),t=>String(t),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:this.at}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(Jr,t,Zr,{at:this.at}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,ts.toHex)(e);return(0,vt.AccountId)(es.HYDRATION_SS58_PREFIX).dec(i)}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Omnipool.Assets.isCompatible(vt.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,r,s,n,a,o]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:this.at}),this.api.query.Omnipool.HubAssetTradability.getValue({at:this.at}),this.api.query.AssetRegistry.Assets.getValue(t,{at:this.at}),this.balance.getBalance(e,t),this.getPoolLimits(),this.api.query.System.Number.getValue({at:this.at})]);this.block=o;let l=i.map(async({keyArgs:p,value:d})=>{let[m]=p,{hub_reserve:h,shares:b,tradable:g,cap:y,protocol_shares:P}=d,[v,S]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m,{at:this.at}),this.balance.getBalance(e,m)]);return{id:m,decimals:v?.decimals,existentialDeposit:v?.existential_deposit,balance:S.transferable,cap:y,hubReserves:h,protocolShares:P,shares:b,tradeable:g,type:v?.asset_type.type}}),u=await Promise.all(l);return u.push({id:t,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:n.transferable,tradeable:r,type:s?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:u,...a}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,s=await this.maxSlipFee.get()??0,n=await this.dynamicFeesConfig.get(e);if(n?.type==="Fixed"){let{asset_fee:d,protocol_fee:m}=n.value;return{assetFee:Zi.fromPermill(d),protocolFee:Zi.fromPermill(m),maxSlipFee:Zi.fromPermill(s)}}let[a,o,l,u,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get($t(e)),this.emaOracles.get($t(i)),n?n.value.asset_fee_params:this.api.constants.DynamicFees.AssetFeeParameters(),n?n.value.protocol_fee_params:this.api.constants.DynamicFees.ProtocolFeeParameters()]);return Ct.compute(t,this.block,a,o,l,u,p,s)}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(r=>r.id).map(r=>$t(r)).map(r=>this.api.query.EmaOracle.Oracles.watchValue(Jr,r,Zr,{at:"best"}).pipe((0,O.map)(({value:s})=>s),(0,O.filter)(s=>s!==void 0),(0,O.map)((s,n)=>({value:s,index:n})),(0,O.tap)(({index:s})=>{s>0&&this.log.trace("emaOracle.Oracles",r.join(":"))}),(0,O.map)(({value:s})=>({pair:r,value:s}))));return(0,O.merge)(...i).pipe((0,O.finalize)(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(r=>{let{pair:s,value:n}=r;this.emaOracles.set(n,s)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,O.distinctUntilChanged)((t,e)=>!e.deltas),(0,O.map)((t,e)=>({value:t,index:e})),(0,O.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),(0,O.finalize)(()=>this.dynamicFees.clear()),this.watchGuard("dynamicFees.AssetFee")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFees.set(e.value,i)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe((0,O.distinctUntilChanged)((t,e)=>!e.deltas),(0,O.map)((t,e)=>({value:t,index:e})),(0,O.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),(0,O.finalize)(()=>this.dynamicFeesConfig.clear()),this.watchGuard("dynamicFees.AssetFeeConfiguration")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFeesConfig.set(e.value,i)})})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,O.distinctUntilChanged)((t,e)=>!e.deltas),(0,O.map)((t,e)=>({value:t,index:e})),(0,O.tap)(({value:t,index:e})=>{e>0&&this.log.trace("omnipool.Assets",t.deltas?.upserted)}),this.watchGuard("omnipool.Assets")).subscribe(({value:{deltas:t}})=>{this.store.update(([e])=>{let i=t?.upserted.reduce((s,n)=>{let[a]=n.args;return s.set(a,n.value),s},new Map),r=e.tokens.map(s=>{let n=i?.get(s.id);return n?this.updateTokenState(s,n):s});return[{...e,tokens:r}]})})}subscribeUpdates(){let t=new O.Subscription;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:i,shares:r,tradable:s,cap:n,protocol_shares:a}=e;return{...t,cap:n,hubReserves:i,protocolShares:a,shares:r,tradeable:s}}};var er={};R(er,{StableMath:()=>$,StableSwap:()=>kt,StableSwapClient:()=>xe});var L=require("@galacticcouncil/math-stableswap"),$=class{static getPoolAddress(t){return(0,L.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let i=0;i<t;i++)e.push(["1","1"]);return e}static calculateAmplification(t,e,i,r,s){return(0,L.calculate_amplification)(t,e,i,r,s)}static calculateInGivenOut(t,e,i,r,s,n,a){return(0,L.calculate_in_given_out)(t,e,i,r,s,n,a)}static calculateAddOneAsset(t,e,i,r,s,n,a){return(0,L.calculate_add_one_asset)(t,e,i,r,s,n,a)}static calculateSharesForAmount(t,e,i,r,s,n,a){return(0,L.calculate_shares_for_amount)(t,e,i,r,s,n,a)}static calculateOutGivenIn(t,e,i,r,s,n,a){return(0,L.calculate_out_given_in)(t,e,i,r,s,n,a)}static calculateLiquidityOutOneAsset(t,e,i,r,s,n,a){return(0,L.calculate_liquidity_out_one_asset)(t,e,i,r,s,n,a)}static calculateShares(t,e,i,r,s,n){return(0,L.calculate_shares)(t,e,i,r,s,n)}static calculateSpotPriceWithFee(t,e,i,r,s,n,a,o){return(0,L.calculate_spot_price_with_fee)(t,e,i,r,s,n,a,o)}static recalculatePegs(t,e,i,r,s,n){let a=(0,L.recalculate_peg)(t,e,i,r,s,n);return JSON.parse(a)}};var we=require("@galacticcouncil/common");var{FeeUtils:Xt}=I,kt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new c(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),r=i.get(t),s=i.get(e);if(r==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:r.balance,balanceOut:s.balance,decimalsIn:r.decimals,decimalsOut:s.decimals,tradeableIn:this.id===t?15:r.tradeable,tradeableOut:this.id===e?15:s.tradeable,assetInEd:r.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,i),n=r===0n?0:z.calculateBuyFee(r,s),a=[],o=E.isSellAllowed(t.tradeableIn),l=E.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:s,calculatedIn:r,amountOut:e,feePct:n,errors:a}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,i),n=z.calculateSellFee(r,s),a=[],o=E.isSellAllowed(t.tradeableIn),l=E.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:r,amountOut:s,feePct:n,errors:a}}calculateIn(t,e,i){let r=$.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?Xt.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(r);return s<0n?0n:s}calculateAddOneAsset(t,e,i){let r=$.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?Xt.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(r);return s<0n?0n:s}calculateSharesForAmount(t,e,i){let r=$.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?Xt.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(r);return s<0n?0n:s}calculateInGivenOut(t,e,i){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,i):t.assetIn==this.id?this.calculateSharesForAmount(t,e,i):this.calculateIn(t,e,i)}spotPriceInGivenOut(t){let e=$.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetOut===this.id,t.assetIn===this.id,t.decimalsOut,t.decimalsIn)}calculateOut(t,e,i){let r=$.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?Xt.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(r);return s<0n?0n:s}calculateWithdrawOneAsset(t,e,i){let r=$.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?Xt.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(r);return s<0n?0n:s}calculateShares(t,e,i){let r=$.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?Xt.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(r);return s<0n?0n:s}calculateOutGivenIn(t,e,i){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,i):t.assetOut==this.id?this.calculateShares(t,e,i):this.calculateOut(t,e,i)}spotPriceOutGivenIn(t){let e=$.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetIn===this.id,t.assetOut===this.id,t.decimalsIn,t.decimalsOut)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:i,decimals:r})=>({asset_id:e,amount:i,decimals:r}));return JSON.stringify(t,Wt.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],Wt.jsonFormatter)}normalizeSpot(t,e,i,r,s){return e?t*we.big.pow10(we.RUNTIME_DECIMALS-s):i?t/we.big.pow10(s-r):t}};var mi=require("polkadot-api"),is=require("@polkadot-api/utils"),rs=require("@noble/hashes/blake2b"),Z=require("rxjs"),di=require("@galacticcouncil/common");var{FeeUtils:Pn}=I,xe=class extends J{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=$.getPoolAddress(t),i=(0,rs.blake2b)(e,{dkLen:32}),r=(0,is.toHex)(i);return(0,mi.AccountId)(di.HYDRATION_SS58_PREFIX).dec(r)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:i,final_amplification:r,initial_block:s,final_block:n}=t,a=$.calculateAmplification(i.toString(),r.toString(),s.toString(),n.toString(),e.toString()),o=Number(a)<r;return{amplification:BigInt(a),isRampPeriod:o}}async getPoolTokens(t,e){let i=this.getPoolAddress(t),r=e.assets.map(async s=>{let[n,a,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,s,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(s,{at:this.at}),this.balance.getBalance(i,s)]);return{id:s,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:o.transferable,tradeable:n,type:a?.asset_type.type}});return Promise.all(r)}async isSupported(){return(await this.api.getStaticApis()).compat.query.Stableswap.Pools.isCompatible(mi.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:this.at}),this.api.query.System.Number.getValue({at:this.at}),this.getPoolLimits()]),r=t.map(async({keyArgs:s,value:n})=>{let[a]=s,o=this.getPoolAddress(a),[l,u,p]=await Promise.all([this.getPoolTokens(a,n),this.api.query.Stableswap.PoolPegs.getValue(a,{at:this.at}),this.api.query.Tokens.TotalIssuance.getValue(a,{at:this.at})]),d=this.getPoolAmplification(n,e),m=u?this.getRecentPegs(u):this.getDefaultPegs(n);return l.push({id:a,tradeable:15,balance:p,decimals:di.RUNTIME_DECIMALS}),this.poolsData.set(a,n),{address:o,id:a,type:"Stableswap",fee:Pn.fromPermill(n.fee),tokens:l,totalIssuance:p,pegs:m,...i,...d}});return Promise.all(r)}async getPoolFees(t,e){return{fee:this.store.pools.find(r=>r.address===e).fee}}getDefaultPegs(t){return $.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([i,r])=>r.map(s=>s.toString()))}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,{at:"best"}).pipe((0,Z.map)(({value:r})=>r),(0,Z.map)((r,s)=>({value:r,index:s})),(0,Z.tap)(({index:r,value:s})=>{r>0&&this.log.trace("tokens.TotalIssuance",i,s)}),(0,Z.map)(({value:r})=>({id:i,value:r}))));return(0,Z.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:r,value:s}=i;this.store.update(n=>{let a=[];return n.filter(o=>o.id===r).forEach(o=>{let l=o.tokens.map(u=>u.id===r?{...u,balance:s}:u);a.push({...o,tokens:l,totalIssuance:s})}),a})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,Z.distinctUntilChanged)((t,e)=>!e.deltas),(0,Z.map)((t,e)=>({value:t,index:e})),(0,Z.tap)(({value:t,index:e})=>{e>0&&this.log.trace("stableswap.PoolPegs",t.deltas?.upserted)}),this.watchGuard("stableswap.PoolPegs")).subscribe({error:t=>this.log.error("stableswap.PoolPegs",t),next:({value:{deltas:t}})=>{this.store.update(e=>{let i=[],r=new Map(e.map(s=>[s.id,s]));return t?.upserted.forEach(({args:s,value:n})=>{let[a]=s,o=r.get(a);if(o){let l=this.getRecentPegs(n);i.push({...o,pegs:l})}}),i})}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(e=>{let i=[];return e.filter(r=>r.isRampPeriod).forEach(r=>{let s=this.poolsData.get(r.id);if(s){let n=this.getPoolAmplification(s,t);i.push({...r,...n})}}),i})})}subscribeUpdates(){let t=new Z.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var ir={};R(ir,{XykMath:()=>wt,XykPool:()=>Te,XykPoolClient:()=>Ie});var q=require("@galacticcouncil/math-xyk"),wt=class{static getSpotPrice(t,e,i){return(0,q.get_spot_price)(t,e,i)}static calculateInGivenOut(t,e,i){return(0,q.calculate_in_given_out)(t,e,i)}static calculateOutGivenIn(t,e,i){return(0,q.calculate_out_given_in)(t,e,i)}static calculatePoolTradeFee(t,e,i){return(0,q.calculate_pool_trade_fee)(t,e,i)}static calculateLiquidityIn(t,e,i){return(0,q.calculate_liquidity_in)(t,e,i)}static calculateSpotPrice(t,e){return(0,q.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,i,r){return(0,q.calculate_spot_price_with_fee)(t,e,i,r)}static calculateShares(t,e,i){return(0,q.calculate_shares)(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,r){return(0,q.calculate_liquidity_out_asset_a)(t,e,i,r)}static calculateLiquidityOutAssetB(t,e,i,r){return(0,q.calculate_liquidity_out_asset_b)(t,e,i,r)}};var ns=require("@galacticcouncil/common");var{FeeUtils:ss}=I,Te=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),r=i.get(t),s=i.get(e);if(r==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:r.decimals,decimalsOut:s.decimals,balanceIn:r.balance,balanceOut:s.balance,assetInEd:r.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),s=this.calculateTradeFee(r,i),n=ss.toPct(i.exchangeFee),a=r+s,o=[];(e<this.minTradingLimit||r<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:r,amountOut:e,feePct:n,errors:o}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),s=this.calculateTradeFee(r,i),n=ss.toPct(i.exchangeFee),a=r-s,o=[];(e<this.minTradingLimit||r<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:a,feePct:n,errors:o}}calculateInGivenOut(t,e){let i=wt.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}calculateOutGivenIn(t,e){let i=wt.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}spotPriceInGivenOut(t){let e=wt.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=wt.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=wt.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(i)}normalizeSpot(t,e,i){let r=e-i;if(r===0)return t;let s=ns.big.pow10(Math.abs(r));return r>0?t*s:t/s}};var as=require("polkadot-api"),os=require("rxjs");var Ie=class extends J{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){return(await this.api.getStaticApis()).compat.query.XYK.PoolAssets.isCompatible(as.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries({at:this.at}),this.getPoolLimits()]),i=t.map(async({keyArgs:r,value:s})=>{let[n]=r,[a,o]=s,[l,u,p,d]=await Promise.all([this.balance.getBalance(n,a),this.api.query.AssetRegistry.Assets.getValue(a,{at:this.at}),this.balance.getBalance(n,o),this.api.query.AssetRegistry.Assets.getValue(o,{at:this.at})]);return{address:n,type:"XYK",tokens:[{id:a,decimals:u?.decimals||this.decimals.get(a),existentialDeposit:u?.existential_deposit,balance:l.transferable,type:u?.asset_type.type},{id:o,decimals:d?.decimals||this.decimals.get(o),existentialDeposit:d?.existential_deposit,balance:p.transferable,type:d?.asset_type.type}],...e}});return Promise.all(i)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return os.Subscription.EMPTY}};var rr={};R(rr,{AavePool:()=>_e,AavePoolClient:()=>Oe});var Kt=require("@galacticcouncil/common");var _e=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),r=i.get(t),s=i.get(e);if(r==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:r.balance,balanceOut:s.balance,decimalsIn:r.decimals,decimalsOut:s.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),s=[];return e>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),s=[];return r>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return Kt.big.toBigInt(1,Kt.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return Kt.big.toBigInt(1,Kt.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var hi=require("polkadot-api"),cs=require("@polkadot-api/utils"),it=require("rxjs"),us=require("viem"),gi=require("@galacticcouncil/common");var ls=[{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:Sn}=gi.erc20,vn=["Supply","Withdraw","Repay","Borrow"],Oe=class extends J{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,r=new TextEncoder().encode(i.padEnd(32,"\0")),s=(0,cs.toHex)(r);return(0,hi.AccountId)(gi.HYDRATION_SS58_PREFIX).dec(s)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:this.at})).map(async({reserve:i,atoken:r,liqudity_in:s,liqudity_out:n})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(i,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(r,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(r,{at:this.at})]);return{address:this.getPoolId(i,r),type:"Aave",tokens:[{id:i,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:s,location:o,type:a?.asset_type.type},{id:r,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:n,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:r,liqudity_out:s}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:this.at});return t.tokens.map(n=>{let a=n.id===e.id?r:s;return{...n,balance:a}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key}throw new Error("Invalid aave reserve multilocation")}return Sn.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:i}=t;return{assetIn:e,assetOut:i,key:`${e}:${i}`}}parseEvmLog(t){let{topics:e,data:i}=t.log,r=e,s=hi.Binary.toHex(i);try{let{eventName:n,args:a}=(0,us.decodeEventLog)({abi:ls,topics:r,data:s}),o=a.reserve.toLowerCase();return{eventName:n,reserve:o,key:`${n}:${o}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(i=>i.tokens).map(([i,r])=>r).map(i=>i.id);return this.api.event.Router.Executed.watch().pipe((0,it.mergeMap)(({events:i})=>i),(0,it.map)(({payload:i})=>this.parseRouterLog(i)),(0,it.filter)(({assetIn:i,assetOut:r})=>e.includes(i)||e.includes(r)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:r,key:s})=>{this.log.trace("router.Executed",s),this.store.update(async n=>{let a=[];for(let o of n){let[l,u]=o.tokens;if(u.id===i||u.id===r){let d=await this.getPoolDelta(o);a.push({...o,tokens:d})}}return a})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,it.mergeMap)(({events:t})=>t),(0,it.map)(({payload:t})=>this.parseEvmLog(t)),(0,it.filter)(t=>t!==void 0),(0,it.filter)(({eventName:t})=>vn.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async i=>{let r=[];for(let s of i){let[n]=s.tokens;if(this.getReserveH160Id(n).toLowerCase()===t){let o=await this.getPoolDelta(s);r.push({...s,tokens:o})}}return r})})}subscribeBalances(){return it.Subscription.EMPTY}subscribeUpdates(){let t=new it.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var nr={};R(nr,{HsmMath:()=>at,HsmPool:()=>Ae,HsmPoolClient:()=>Ee});var X=require("@galacticcouncil/math-hsm"),at=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,X.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,X.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,X.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,X.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,X.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,X.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,X.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,X.calculate_max_price)(t,e)}};var K=require("@galacticcouncil/common");var{FeeUtils:jt}=I,Ae=class c extends kt{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new c(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,i){let r=this.parsePair(t.assetOut,t.assetIn),s=super.calculateInGivenOut(r,e,{fee:this.fee}),n=this.calculateBuybackLimit(t);e>n&&i.push("MaxBuyBackExceeded");let a=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,s)>a&&i.push("MaxBuyPriceExceeded"),s>this.collateralBalance&&i.push("InsufficientCollateral"),i}validateTradeHollarOut(t,e,i){return this.collateralBalance+t>this.maxInHolding&&i.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&i.push("FacilitatorCapacityExceeded"),i}validateTradeConstraints(t,e,i){let r=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,r):this.validateTradeHollarOut(e,i,r)}validateAndBuy(t,e){let i=this.calculateInGivenOut(t,e),r=this.validateTradeConstraints(t,i,e);return{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:r}}validateAndSell(t,e){let i=this.calculateOutGivenIn(t,e),r=this.validateTradeConstraints(t,e,i);return{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:r}}calculateHollarInGivenCollateralOut(t,e){let i=super.calculateInGivenOut(t,e,{fee:this.fee}),r=at.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),jt.toRaw(this.buyBackFee).toString());return BigInt(r)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=at.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),jt.toRaw(this.purchaseFee).toString());return BigInt(i)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let i=super.calculateOutGivenIn(t,e,{fee:this.fee}),r=at.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),jt.toRaw(this.buyBackFee).toString());return BigInt(r)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=at.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),jt.toRaw(this.purchaseFee).toString());return BigInt(i)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),i=at.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=at.calculateBuybackLimit(e.toString(),jt.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let r=at.calculateBuybackPriceWithFee(i.toString(),e.toString(),jt.toRaw(this.buyBackFee).toString()),[s,n]=JSON.parse(r),a=K.big.pow10(t.decimalsIn+K.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(s)*a/BigInt(n)}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=at.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[r,s]=JSON.parse(i),n=K.big.pow10(K.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(r)*n/BigInt(s)}spotPriceInGivenOut(t){let e=K.big.toBigInt(1,t.decimalsOut),r=this.calculateInGivenOut(t,e)*K.big.pow10(K.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(r,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=K.big.toBigInt(1,t.decimalsIn),r=this.calculateOutGivenIn(t,e)*K.big.pow10(K.RUNTIME_DECIMALS-t.decimalsIn);return this.normalizeSpotPrice(r,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(r=>r.id!==this.hollarId),e=this.pegs[t],i=this.tokens[t].decimals;return this.isDefaultPeg(e)?[K.big.toBigInt(1,18).toString(),K.big.toBigInt(1,i).toString()]:e}isDefaultPeg(t){let[e,i]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&i==="1"}normalizeSpotPrice(t,e,i){let r=e-i;if(r===0)return t;let s=K.big.pow10(Math.abs(r));return r>0?t*s:t/s}};var Qt=require("polkadot-api"),ms=require("@polkadot-api/utils"),W=require("rxjs"),ds=require("viem"),bi=require("@galacticcouncil/common");var Be=[{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 Fe=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,r]=await this.client.readContract({abi:Be,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-r}};var{FeeUtils:sr}=I,{H160:ps}=bi.h160,wn=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Ee=class extends J{ghoClient;stableClient;constructor(t,e,i,r){super(t,e,r),this.stableClient=i,this.ghoClient=new Fe(e)}getPoolType(){return"HSM"}getPoolId(t){return this.getPoolAddress("hsm:"+t)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(t){if(t){let e=t.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),i=new TextEncoder().encode(e),r=(0,ms.toHex)(i);return(0,Qt.AccountId)(bi.HYDRATION_SS58_PREFIX).dec(r)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(Qt.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,r]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t,{at:this.at}),this.api.query.HSM.Collaterals.getEntries({at:this.at}),this.stableClient.getPools()]);if(i.length===0)return[];let s=this.getFacilitatorAddress(),n=ps.fromAny(s),a=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(a,n),l=i.map(async({keyArgs:p,value:d})=>{let[m]=p,{pool_id:h,max_buy_price_coefficient:b,max_in_holding:g,purchase_fee:y,buy_back_fee:P,buyback_rate:v}=d,S=r.find(T=>T.id===h);if(S){let T=this.getPoolId(h),B=await this.balance.getBalance(s,m);return{...S,address:T,type:"HSM",tokens:S.tokens.filter(D=>D.id!==h),hsmAddress:s,hsmMintCapacity:o,hollarId:t,hollarH160:a,collateralId:m,collateralBalance:B.transferable,maxBuyPriceCoefficient:b,maxInHolding:g,purchaseFee:sr.fromPermill(y),buyBackFee:sr.fromPermill(P),buyBackRate:sr.fromPerbill(v)}}});return(await Promise.all(l)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:i}=t.log,r=e,s=Qt.Binary.toHex(i);try{let{eventName:n,args:a}=(0,ds.decodeEventLog)({abi:Be,topics:r,data:s}),o=a.facilitatorAddress.toLowerCase();return{eventName:n,facilitator:o,key:`${n}:${o}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,W.mergeMap)(({events:t})=>t),(0,W.map)(({payload:t})=>this.parseEvmLog(t)),(0,W.filter)(t=>t!==void 0),(0,W.filter)(({eventName:t})=>wn.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async i=>{let r=[],[{hsmAddress:s,hollarH160:n}]=i,a=ps.fromAny(s);if(a.toLowerCase()===e){let l=await this.ghoClient.getFacilitatorCapacity(n,a);for(let u of i)r.push({...u,hsmMintCapacity:l})}return r})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(s=>{let{tokens:n,collateralId:a}=s;n.find(l=>l.id===a).type==="Erc20"?e.push(a):t.push(a)});let[{hsmAddress:i}]=this.store.pools,r=[];if(t.length>0){let s=this.balance.watchTokensBalance(i);r.push(s)}if(e.length>0){let s=this.balance.watchErc20Balance(i,e);r.push(s)}return r.length>0?(0,W.combineLatest)(r).pipe((0,W.map)(s=>s.flat()),(0,W.pairwise)(),(0,W.map)(([s,n])=>this.balance.getDeltas(s,n)),this.watchGuard("balances")).subscribe(s=>{this.store.update(n=>{let a=[],o=new Map(n.map(l=>[l.collateralId,l]));return s.forEach(({id:l,balance:u})=>{let p=o.get(l);p&&(this.log.trace("balances",{id:l,balance:u}),a.push({...p,collateralBalance:u.transferable}))}),a})}):W.Subscription.EMPTY}subscribeStableswapUpdates(){return this.stableClient.getSubscriber().pipe(this.watchGuard("stableswap.updates")).subscribe(t=>{let e=new Map(t.map(i=>[i.id,i]));this.store.update(i=>{let r=[];for(let s of i){let n=e.get(s.id);n&&r.push({...s,fee:n.fee,tokens:n.tokens.filter(a=>a.id!==s.id),totalIssuance:n.totalIssuance,pegs:n.pegs,amplification:n.amplification,isRampPeriod:n.isRampPeriod})}return r})})}subscribeBalances(){return W.Subscription.EMPTY}subscribeUpdates(){let t=new W.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var Jt=class{static get(t){switch(t.type){case"Aave":return _e.fromPool(t);case"XYK":return Te.fromPool(t);case"Omnipool":return Se.fromPool(t);case"LBP":return fe.fromPool(t);case"Stableswap":return kt.fromPool(t);case"HSM":return Ae.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var hs=require("@galacticcouncil/common"),ot=require("rxjs");var{logger:xn}=hs.log,Zt=class extends N{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=ot.Subscription.EMPTY;omniSub=ot.Subscription.EMPTY;stableSub=ot.Subscription.EMPTY;hsmSub=ot.Subscription.EMPTY;xykSub=ot.Subscription.EMPTY;lbpSub=ot.Subscription.EMPTY;isReady=!1;isDestroyed=new ot.Subject;constructor(t,e,i){super(t,i),this.evm=e,this.aave=new Oe(t,e,i),this.omnipool=new ve(t,e,i),this.stableswap=new xe(t,e,i),this.hsm=new Ee(t,e,this.stableswap,i),this.xyk=new Ie(t,e,i),this.lbp=new Pe(t,e,i),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}get isHistorical(){return this.at!=="best"&&this.at!=="finalized"}subscribe(t){return this.isHistorical?ot.Subscription.EMPTY:t.getSubscriber().pipe((0,ot.takeUntil)(this.isDestroyed)).subscribe(e=>{e.forEach(i=>{this.pools.set(i.address,i)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.active.has("Stableswap")||(xn.info("[PoolContextProvider] auto-activating stableswap"),this.withStableswap()),this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let i=this.clients.find(r=>r.getPoolType()===e.type);if(i)return i.getPoolFees(t,e.address);throw new Ft(e.type)}};var yi=class{constructor(t){this.snapshot=t;let{aave:e,xyk:i,lbp:r,stable:s,omni:n}=t.pools;this.flat=[...e,...i,...r,...s,...n]}flat;async getPools(){return this.flat}async getPoolFees(t,e){let{block:i,states:r}=this.snapshot;switch(e.type){case"Aave":return{};case"XYK":{let{exchangeFee:s}=r.xyk;return{exchangeFee:s}}case"LBP":{let{repayFee:s}=r.lbp;return{exchangeFee:e.fee,repayFee:s}}case"Stableswap":return{fee:e.fee};case"Omnipool":{let s=t.assetOut,n=t.assetIn,{dynamicFees:a,emaOracles:o,assetFeeParams:l,protocolFeeParams:u,maxSlipFee:p}=r.omni,d=a.find(({asset:b})=>b===s)?.fee,m=o.find(({pair:b})=>b.join(":")===pi(s))?.oracle,h=o.find(({pair:b})=>b.join(":")===pi(n))?.oracle;return Ct.compute(t,i,d,m,h,l,u,p)}default:throw new Ft(e.type)}}};var dr={};R(dr,{DCA_TIME_RESERVE:()=>ys,DEFAULT_BLOCK_TIME:()=>bs,DEFAULT_MIN_BUDGET:()=>cr,ORDER_MIN_BLOCK_PERIOD:()=>fs,Router:()=>te,TWAP_EXECUTION_INTERVAL:()=>De,TWAP_MAX_DURATION:()=>pr,TWAP_MAX_PRICE_IMPACT:()=>ur,TWAP_TX_MULTIPLIER:()=>Ym,TradeOrderError:()=>lr,TradeOrderType:()=>Me,TradeRouteBuilder:()=>rt,TradeRouter:()=>At,TradeScheduler:()=>ee,TradeType:()=>fi});var Re=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 Tn=10,Ce=class{isNotVisited(t,e){let i=!0;return e.forEach(r=>{(r[0]===t[0]||r[1]===t[1])&&(i=!1)}),i}findPaths(t,e,i){let r=[],s=new Re,n=[];for(n.push([e,""]),s.enqueue(n);s.size()>0;){let a=s.dequeue();if(!a||a.length>Tn)continue;let o=a[a.length-1];(i===null||o[0]===i)&&r.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let p=[...a];p.push(u),s.enqueue(p)}})}return r}findShortestPaths(t,e,i){let r=[],s=new Re,n=[];n.push([e,""]),s.enqueue(n);let a=1/0;for(;s.size()>0;){let o=s.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===i){o.length<a?(a=o.length,r.length=0,r.push(o)):o.length===a&&r.push(o);continue}let u=t.get(l[0]);for(let p of u??[])this.isNotVisited(p,o)&&s.enqueue([...o,p])}return r}buildAndPopulateGraph(t,e){let i=new Map;for(let r of t)i.set(parseInt(r),[]);for(let[r,s,n]of e)i.get(s)?.push([n,r]);return i}};function or(c){let t={};for(let e of c){let i=e.tokens.length;for(let r=0;r<i;r++){t[e.tokens[r].id]||(t[e.tokens[r].id]=[]);for(let s=0;s<i;s++){if(r==s)continue;let n=[e.address,e.tokens[r].id,e.tokens[s].id];t[e.tokens[r].id].push(n)}}}return t}var ke=class{getProposals(t,e,i){let r=i.filter(g=>g.type==="XYK"),s=i.filter(g=>g.type!=="XYK"),n=new Set(s.map(g=>g.tokens).flat().map(g=>g.id)),a=n.has(t),o=n.has(e),l=new Ce,u=g=>{let y=or(g),P=Object.keys(y),v=P.flatMap(S=>y[S]);return l.buildAndPopulateGraph(P,v)};if(!a&&!o){let g=r.filter(v=>v.tokens.find(S=>S.id===t)||v.tokens.find(S=>S.id===e)),y=u(g),P=l.findPaths(y,t,e);return this.parsePaths(P)}if(a&&o){let g=u(s),y=l.findPaths(g,t,e);return this.parsePaths(y)}let p=a?e:t,d=r.filter(g=>g.tokens.some(y=>y.id===p));if(d.length===0)return[];let m=[...s,...d],h=u(m),b=l.findPaths(h,t,e);return this.parsePaths(b)}parsePaths(t){let e=[];for(let i of t){let r=[];for(let s=0;s<i.length;s++){let n=i[s],a=i[s+1];if(a==null)break;r.push(this.toEdge(n,a))}e.push(r)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var te=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new ke,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,i){return`${t}->${e}::${i.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:i=[]}=this.filter,r=new Set(e),s=new Set(i);return t.filter(n=>s.has(n.type)?!1:r.size>0?r.has(n.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let i=await this.getPools();return this.validateInput(t,e,i),this.getPaths(t,e,i)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(r=>r!==t).map(r=>this.getRoutes(r,t)))).filter(r=>r.length>0).map(([r])=>r[0].assetIn).sort()}validateInput(t,e,i){if(i.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let r=this.getAssets(i);if(!r.has(t))throw new Error(t+" is not supported asset");if(!r.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(i)}getAssets(t){let e=t.map(i=>i.tokens.map(r=>r.id)).flat().sort((i,r)=>i>r?1:-1);return new Set(e)}getPaths(t,e,i){let r=this.toPoolsMap(i);return this.getProposals(t,e,i).filter(n=>this.validPath(n,r)).map(n=>this.toHops(n,r))}getProposals(t,e,i){let r=this.buildRouteKey(t,e,i);if(this.routeProposals.has(r))return this.routeProposals.get(r);let s=this.routeSuggester.getProposals(t,e,i);return this.routeProposals.set(r,s),s}validPath(t,e){return t.length>0&&t.map(i=>this.validEdge(i,e)).reduce((i,r)=>i&&r)}validEdge([t,e,i],r){return r.get(t)?.validatePair(e,i)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Jt.get(e)]))}toHops(t,e){return t.map(([i,r,s])=>{let n=e.get(i);return{poolAddress:i,poolId:n?.id,pool:n?.type,assetIn:r,assetOut:s}})}};var A=require("@galacticcouncil/common");var fi=(e=>(e.Buy="Buy",e.Sell="Sell",e))(fi||{}),Me=(i=>(i.Dca="Dca",i.TwapSell="TwapSell",i.TwapBuy="TwapBuy",i))(Me||{}),lr=(i=>(i.OrderTooSmall="OrderTooSmall",i.OrderTooBig="OrderTooBig",i.OrderImpactTooBig="OrderImpactTooBig",i))(lr||{});var{FeeUtils:gs}=I,At=class extends te{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,i){let r=super.validateInput(t,e,i),s=super.getPaths(t,e,i);if(!s.length)throw new ce(t,e);return{paths:s,pools:i,poolsMap:r}}async withCtx(t,e,i){let r=await super.getPools(),s=this.buildCtxSync(t,e,r);return i(s)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((i,r)=>{let s=i[i.length-1].amountOut,n=r[r.length-1].amountOut;return s>n?-1:1});return e.find(i=>i.every(r=>r.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(i=>i.tradeFeeRange).length>0){let i=t.map(s=>s.tradeFeeRange?.[0]??s.tradeFeePct).reduce((s,n)=>s+n),r=t.map(s=>s.tradeFeeRange?.[1]??s.tradeFeePct).reduce((s,n)=>s+n);return[i,r]}}getPoolFeeRange(t,e){let i=t.min?gs.toPct(t.min):void 0,r=t.max?gs.toPct(t.max):void 0;if(i&&r)return[i,Math.max(r,e)]}async getBestSell(t,e,i){return this.getSell(t,e,i)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,i,r){return this.withCtx(t,e,async({paths:s,poolsMap:n})=>{let a;if(r)a=await this.toSellSwaps(i,r,n);else{let o=s.map(u=>this.toSellSwaps(i,u,n)),l=await Promise.all(o);a=this.findBestSellRoute(l)}return this.buildSell(n,a)})}async getSells(t,e,i){return this.withCtx(t,e,async({paths:r,poolsMap:s})=>{let n=r.map(o=>this.toSellSwaps(i,o,s));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(s,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let i=e[0],r=e[e.length-1],s=this.isDirectTrade(e),n=this.getSellSpot(e),a=r.amountOut,o=s?r.calculatedOut:this.calculateDelta0Y(i.amountIn,e,t),l=o-a,u=this.getRouteFeeRange(e),p=s?r.tradeFeePct:z.calculateSellFee(o,a),d=C.mulSpot(i.amountIn,n,i.assetInDecimals,r.assetOutDecimals),m=z.calculateDiffToRef(o,d);return{type:"Sell",amountIn:i.amountIn,amountOut:r.amountOut,spotPrice:n,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Sell",amountIn:A.big.toDecimal(i.amountIn,i.assetInDecimals),amountOut:A.big.toDecimal(r.amountOut,r.assetOutDecimals),spotPrice:A.big.toDecimal(n,A.RUNTIME_DECIMALS),tradeFee:A.big.toDecimal(l,r.assetOutDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e.map(h=>h.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,i)=>e*i/10n**BigInt(A.RUNTIME_DECIMALS))}calculateDelta0Y(t,e,i){let r=[];for(let s=0;s<e.length;s++){let n=e[s],a=i.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;s>0?l=r[s-1]:l=t;let u=a.calculateOutGivenIn(o,l);r.push(u)}return r[r.length-1]}async calculateMostLiquidRoute(t,e,i){let{paths:r,pools:s,poolsMap:n}=i,l=s.filter(b=>b.tokens.some(g=>g.id===t)).map(b=>b.type==="Aave"?b.tokens:b.tokens.filter(g=>g.id===t)).map(b=>b.map(g=>g.balance).reduce((g,y)=>g+y)).sort((b,g)=>g<b?-1:1)[0],u=C.getFraction(l,.1),p=await Promise.all(r.map(b=>this.toSellSwaps(u,b,n))),m=this.findBestSellRoute(p).map(b=>({poolAddress:b.poolAddress,poolId:b?.poolId,pool:b.pool,assetIn:b.assetIn,assetOut:b.assetOut})),h=this.buildRouteKey(t,e,s);return this.mlr.set(h,m),m}async toSellSwaps(t,e,i){let r=[];for(let s=0;s<e.length;s++){let n=e[s],a=i.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;s>0?l=r[s-1].amountOut:l=typeof t=="string"?A.big.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(o,a),{amountOut:p,calculatedOut:d,feePct:m,errors:h}=a.validateAndSell(o,l,u),b=this.getPoolFeeRange(u,m),g=a.spotPriceOutGivenIn(o),y=C.mulSpot(l,g,o.decimalsIn,o.decimalsOut),P=z.calculateDiffToRef(d,y);r.push({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:P,errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===n.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:A.big.toDecimal(l,o.decimalsIn),amountOut:A.big.toDecimal(p,o.decimalsOut),calculatedOut:A.big.toDecimal(d,o.decimalsOut),spotPrice:A.big.toDecimal(g,A.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:P,errors:h}}})}return r}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async i=>{let r=this.buildRouteKey(t,e,i.pools),s=this.mlr.get(r);return s||this.calculateMostLiquidRoute(t,e,i)})}async getSpotPrice(t,e){return this.withCtx(t,e,async i=>{let{pools:r,poolsMap:s}=i,n=this.buildRouteKey(t,e,r),a=this.mlr.get(n);a||(a=await this.calculateMostLiquidRoute(t,e,i));let o=await this.toSellSwaps("1",a,s);return{amount:this.getSellSpot(o),decimals:A.RUNTIME_DECIMALS}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((i,r)=>{let s=i[0].amountIn,n=r[0].amountIn;return s>n?1:-1});return e.find(i=>i.every(r=>r.errors.length==0))||e[0]}async getBestBuy(t,e,i){return this.getBuy(t,e,i)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,i,r){return this.withCtx(t,e,async({paths:s,poolsMap:n})=>{let a;if(r)a=await this.toBuySwaps(i,r,n);else{let o=s.map(u=>this.toBuySwaps(i,u,n)),l=await Promise.all(o);a=this.findBestBuyRoute(l)}return this.buildBuy(n,a)})}async getBuys(t,e,i){return this.withCtx(t,e,async({paths:r,poolsMap:s})=>{let n=r.map(o=>this.toBuySwaps(i,o,s));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(s,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let i=e[e.length-1],r=e[0],s=this.isDirectTrade(e),n=this.getBuySpot(e),a=r.amountIn,o=s?r.calculatedIn:this.calculateDelta0X(i.amountOut,e,t),l=a-o,u=this.getRouteFeeRange(e),p=s?r.tradeFeePct:z.calculateBuyFee(o,a),d=C.mulSpot(i.amountOut,n,i.assetOutDecimals,r.assetInDecimals),m;return o===0n?m=-100:m=z.calculateDiffToRef(d,o),{type:"Buy",amountOut:i.amountOut,amountIn:r.amountIn,spotPrice:n,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Buy",amountOut:A.big.toDecimal(i.amountOut,i.assetOutDecimals),amountIn:A.big.toDecimal(r.amountIn,r.assetInDecimals),spotPrice:A.big.toDecimal(n,A.RUNTIME_DECIMALS),tradeFee:A.big.toDecimal(l,r.assetInDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e.map(h=>h.toHuman())}}}}calculateDelta0X(t,e,i){let r=[];for(let s=e.length-1;s>=0;s--){let n=e[s],a=i.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;s==e.length-1?l=t:l=r[0];let u=a.calculateInGivenOut(o,l);r.unshift(u)}return r[0]}async toBuySwaps(t,e,i){let r=[];for(let s=e.length-1;s>=0;s--){let n=e[s],a=i.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;s==e.length-1?l=typeof t=="string"?A.big.toBigInt(t,o.decimalsOut):t:l=r[0].amountIn;let u=await this.ctx.getPoolFees(o,a),{amountIn:p,calculatedIn:d,feePct:m,errors:h}=a.validateAndBuy(o,l,u),b=this.getPoolFeeRange(u,m),g=a.spotPriceInGivenOut(o),y=C.mulSpot(l,g,o.decimalsOut,o.decimalsIn),P;d===0n?P=-100:P=z.calculateDiffToRef(y,d),r.unshift({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:P,errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===n.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===n.assetIn},toHuman(){return{...n,amountOut:A.big.toDecimal(l,o.decimalsOut),amountIn:A.big.toDecimal(p,o.decimalsIn),calculatedIn:A.big.toDecimal(d,o.decimalsIn),spotPrice:A.big.toDecimal(g,A.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:P,errors:h}}})}return r}};var M=require("@galacticcouncil/common");var bs=6e3,cr=1000000000000000n,De=6,ur=-5,pr=216e5,Ym=3,ys=.1,fs=6;var mr=require("polkadot-api");var rt=class{static build(t){return t.map(({assetIn:e,assetOut:i,pool:r,poolId:s})=>r==="Stableswap"?{pool:(0,mr.Enum)("Stableswap",s),asset_in:e,asset_out:i}:{pool:(0,mr.Enum)(r),asset_in:e,asset_out:i})}};var ee=class{schedulerOptions;router;constructor(t,e={}){this.router=new At(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??cr})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,i,r,s){let n=await this.router.getBestSell(t,e,i),{amountIn:a,swaps:o,priceImpactPct:l}=n,u=o[0],p=o[o.length-1],{assetInDecimals:d}=u,{assetOutDecimals:m}=p,h=Math.abs(l),b=await this.getMinimumOrderBudget(t,d),g=this.getOptimalTradeCount(h),y=this.getMaximumTradeCount(a,b,r),P=s||Math.min(g,y),v=Math.round(r/P),S=a/BigInt(P),T=await this.router.getBestSell(t,e,S),B=a<b,D=[];B&&D.push("OrderTooSmall");let Q=await this.getAssetOutEd(p),U=T.amountOut*BigInt(P),yt=this.toBlockPeriod(v),tt=T.tradeFee*BigInt(P),ct=rt.build(o),xt={assetIn:t,assetOut:e,assetOutEd:Q,errors:D,maxTradeCount:y,tradeCount:P,tradeFee:tt,tradeImpactPct:T.priceImpactPct,tradePeriod:yt,tradeRoute:ct,type:"Dca"};return{...xt,amountIn:a,amountOut:U,tradeAmountIn:T.amountIn,tradeAmountOut:T.amountOut,toHuman(){return{...xt,amountIn:M.big.toDecimal(a,d),amountOut:M.big.toDecimal(U,m),assetOutEd:M.big.toDecimal(Q,m),tradeAmountIn:M.big.toDecimal(T.amountIn,d),tradeAmountOut:M.big.toDecimal(T.amountOut,m)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let i=await this.router.getSpotPrice(0,t);if(i)return C.mulSpot(this.minOrderBudget,i.amount,12,e);let r=await this.router.getSpotPrice(t,0);if(r)return C.divSpot(this.minOrderBudget,r.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,i){let r=e*2n/10n;if(r===0n)return 0;let s=Number(t/r),n=Math.floor(i/this.blockTime),a=Math.max(0,Math.floor(n*(1-.1)));return Math.min(s,a)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,i,r){let s=await this.router.getBestSell(t,e,i),{swaps:n}=s,a=n[0],o=n[n.length-1],{assetInDecimals:l}=a,{assetOutDecimals:u}=o,p=await this.getMinimumOrderBudget(t,l),d=s.amountIn<p,m=[];d&&m.push("OrderTooSmall");let h=await this.getAssetOutEd(o),b=this.toBlockPeriod(r),g=rt.build(n),y={assetIn:t,assetOut:e,assetOutEd:h,errors:m,maxTradeCount:0,tradeCount:0,tradeFee:s.tradeFee,tradeImpactPct:s.priceImpactPct,tradePeriod:b,tradeRoute:g,type:"Dca"};return{...y,amountIn:0n,amountOut:0n,tradeAmountIn:s.amountIn,tradeAmountOut:s.amountOut,toHuman(){return{...y,amountIn:"0",amountOut:"0",assetOutEd:M.big.toDecimal(h,u),tradeAmountIn:M.big.toDecimal(s.amountIn,l),tradeAmountOut:M.big.toDecimal(s.amountOut,u)}}}}async getTwapSellOrder(t,e,i){let r=await this.router.getBestSell(t,e,i),{amountIn:s,swaps:n,priceImpactPct:a}=r,o=n[0],l=n[n.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),h=s/BigInt(m),[b,g]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestSell(o.assetIn,l.assetOut,h)]),y=m===1,P=s<b,v=g.priceImpactPct<-5,S=[];P||y?S.push("OrderTooSmall"):v&&S.push("OrderImpactTooBig");let T=await this.getAssetOutEd(l),B=g.amountOut*BigInt(m),D=g.tradeFee*BigInt(m),Q=rt.build(n),U={assetIn:t,assetOut:e,assetOutEd:T,errors:S,tradeCount:m,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:Q,type:"TwapSell"};return{...U,amountIn:s,amountOut:B,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:D,toHuman(){return{...U,amountIn:M.big.toDecimal(s,u),amountOut:M.big.toDecimal(B,p),assetOutEd:M.big.toDecimal(T,p),tradeAmountIn:M.big.toDecimal(g.amountIn,u),tradeAmountOut:M.big.toDecimal(g.amountOut,p),tradeFee:M.big.toDecimal(D,p)}}}}async getTwapBuyOrder(t,e,i){let r=await this.router.getBestBuy(t,e,i),{amountOut:s,swaps:n,priceImpactPct:a}=r,o=n[0],l=n[n.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),h=s/BigInt(m),[b,g]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestBuy(o.assetIn,l.assetOut,h)]),y=g.amountIn*BigInt(m),P=m===1,v=y<b,S=g.priceImpactPct<-5,T=[];v||P?T.push("OrderTooSmall"):S&&T.push("OrderImpactTooBig");let B=await this.getAssetOutEd(l),D=g.tradeFee*BigInt(m),Q=rt.build(n),U={assetIn:t,assetOut:e,assetOutEd:B,errors:T,tradeCount:m,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:Q,type:"TwapBuy"};return{...U,amountIn:y,amountOut:s,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:D,toHuman(){return{...U,amountIn:M.big.toDecimal(y,u),amountOut:M.big.toDecimal(s,p),assetOutEd:M.big.toDecimal(B,p),tradeAmountIn:M.big.toDecimal(g.amountIn,u),tradeAmountOut:M.big.toDecimal(g.amountOut,p),tradeFee:M.big.toDecimal(D,u)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let r=216e5/(this.blockTime*6);return Math.round(r)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,i=Math.round(e);return Math.max(i,6)}async getAssetOutEd(t){let r=(await this.router.getPools()).find(s=>s.address===t.poolAddress)?.tokens.find(s=>s.id===t.assetOut);if(!r)throw new Error(`Asset ${t.assetOut} not found in pool ${t.poolAddress}`);return r.existentialDeposit}};var br={};R(br,{BIG_10:()=>Ts,BIG_BILL:()=>hr,StakingApi:()=>Le,StakingClient:()=>qe});var j=require("@galacticcouncil/math-staking"),st=Tt(require("big.js"));var Pi={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},Ps=c=>Object.keys(Pi).includes(c);var Ss=require("polkadot-api"),vs=require("@polkadot-api/utils"),ws=require("@galacticcouncil/common");function xs(c){let t=("modl"+c).padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,vs.toHex)(e);return(0,Ss.AccountId)(ws.HYDRATION_SS58_PREFIX).dec(i)}var Si="20000000000000000",vi="2000",Ts=(0,st.default)(10),hr=(0,st.default)(Ts.pow(12)),Le=class{client;balance;constructor(t,e){this.client=t,this.balance=e}async getPotBalance(){let t=await this.client.getPalletId(),e=xs(t);return await this.balance.getBalance(e,0)}async getStakingPosition(t){let[e,i]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let r=e.created_at,s=await i.reduce(async(n,[a,o])=>{let l=await n,u=a,p=o.amount,d=o.conviction.type.toLowerCase(),m=await this.client.getReferendumInfo(u);return m&&(m.type==="Approved"||m.type==="Rejected")&&Ps(d)&&l.push({id:u,amount:p,conviction:d}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:r,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:s}}async getStake(t){let e=await this.client.getNFTCollectionId(),[i,r]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),s=r.find(n=>n)?.itemId;return{totalStake:i?.total_stake,accumulatedRewardPerStake:i?.accumulated_reward_per_stake,potReservedBalance:i?.pot_reserved_balance,positionId:s,stakePosition:s?await this.getStakingPosition(s):void 0}}getCurrentActionPoints(t,e,i,r){let s=(0,st.default)(0),n=(0,st.default)(0),a=Pi.locked6x,o=(0,st.default)(i.toString()).mul(a),l=100,u=[];t.forEach(m=>{let h=Pi[m.conviction],b=r.includes(m.id.toString());b&&u.push(m.id.toString());let g=(0,st.default)(m.amount.toString()).mul(l).div(o);s=s.plus(Math.floor(g.mul(h).toNumber())),n=n.plus(Math.floor(g.mul(b?a:h).toNumber()))});let p=Math.floor((0,st.default)(i.toString()).mul(a).mul(l).div(o).toNumber());r.forEach(m=>{u.includes(m)||(n=n.plus(p))});let d={democracyVote:1};return s=s.mul(d.democracyVote),s=s.plus(e.toString()||"0"),n=n.mul(d.democracyVote),n=n.plus(e.toString()||"0"),{currentActionPoints:s.toString(),maxActionPoints:n.toString()}}async getRewards(t,e,i){let r=await this.getStake(t),{potReservedBalance:s,accumulatedRewardPerStake:n,totalStake:a,stakePosition:o}=r;if(!o)return;let[l,u,p,d,m,h,b]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),g=(0,st.default)(l.transferable.toString()).minus(s.toString()),y=g.gt(0)&&a>0?(0,j.calculate_accumulated_rps)(n.toString(),g.toString(),a.toString()):n.toString(),P=(0,j.calculate_period_number)(u.toString(),i,b),v=(0,j.calculate_period_number)(u.toString(),o.createdAt.toString(),b),S=(0,j.calculate_rewards)(y,o.rewardPerStake.toString(),o.stake.toString()),T=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),B=(0,j.calculate_points)(v,P,d.toString(),m.toString(),T.currentActionPoints,h.toString(),o.accumulatedSlashPoints.toString()),D=(0,j.sigmoid)(B,Si,vi),Q=(()=>{if(!e.length)return;let xt=(0,j.calculate_points)(v,P,d.toString(),m.toString(),T.maxActionPoints.toString(),h.toString(),o.accumulatedSlashPoints.toString());return(0,j.sigmoid)(xt,Si,vi)})(),U=(0,st.default)(S).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if((0,st.default)(P).minus(v).lte(p.toString()))return{rewards:"0",payablePercentage:D,extraPayablePercentage:Q,constants:{a:Si,b:vi}};let yt=(0,j.calculate_percentage_amount)(U.toString(),D),tt=(0,st.default)(o.accumulatedLockedRewards.toString()),ct=tt.gt(yt)?tt:(0,st.default)(yt);return{rewards:ct.div(hr).toString(),maxRewards:U.div(hr).toString(),allocatedRewardsPercentage:ct.div(U).mul(100).toNumber(),points:B,payablePercentage:D,extraPayablePercentage:Q,constants:{a:Si,b:vi}}}};var gr=require("polkadot-api");var qe=class extends N{async getPalletId(){let t=this.api.constants.Staking.PalletId,e=await t();return gr.Binary.toText(gr.Binary.fromHex(e))}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:n})=>{let[a,o,l]=n;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 Pr={};R(Pr,{TxBuilderFactory:()=>ie});var yr=require("polkadot-api");function Is(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var lt=class extends N{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new mt(t),this.aaveUtils=new Bt(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:i=>this.dryRun(i,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:Ci})}async dryRun(t,e){let i=(0,yr.Enum)("Signed",t),r=(0,yr.Enum)("system",i),n=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(r,e.decodedCall,4),a=n.success&&!n.value.execution_result.success?n.value.execution_result.value.error:null;if(a){let o=a.type==="Module"?Is(a.value):a.type;throw new Error("Dry run execution error!",{cause:o})}return n}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var wi=class extends lt{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:i}=this.trade;if(i==="Buy")return this.buildBuyTx();let{assetIn:r}=e[0],s=await this.balance.getBalance(this.beneficiary,r);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,r=i[0],s=i[i.length-1],n=C.getFraction(t,this.slippagePct),a=r.assetIn,o=s.assetOut,l=t+n,u;return this.isDirectOmnipoolTrade(i)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:rt.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,r=i[0],s=i[i.length-1],n=C.getFraction(e,this.slippagePct),a=r.assetIn,o=s.assetOut,l=e-n,u;return this.isDirectOmnipoolTrade(i)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:rt.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,i=e[0],r=e[e.length-1],s=C.getFraction(t,this.slippagePct),n=i.assetIn,a=r.assetOut,o=t-s,l=this.api.tx.Router.sell_all({asset_in:n,asset_out:a,min_amount_out:o,route:rt.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var xi=require("polkadot-api");var Ti=class extends lt{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradePeriod:s,tradeRoute:n}=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,xi.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:r,min_amount_out:0n,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(a=await this.dispatchWithExtraGas(a)),this.wrapTx("DcaSchedule",a)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradeAmountOut:s,tradePeriod:n,tradeRoute:a}=this.order,o=C.getFraction(s,this.slippagePct),l=s-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,xi.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:r,min_amount_out:l,route:a})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("DcaSchedule.twapSell",u)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradeAmountOut:s,tradePeriod:n,tradeRoute:a}=this.order,o=C.getFraction(r,this.slippagePct),l=r+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,xi.Enum)("Buy",{asset_in:e,asset_out:i,amount_out:s,max_amount_in:l,route:a})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("DcaSchedule.twapBuy",u)}};var _s=require("polkadot-api");var Ii=class extends lt{_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,amountOut:e,swaps:i}=this.trade,r=i[0],s=i[i.length-1],n=r.assetIn,a=s.assetOut,o=C.getFraction(e,this.slippagePct),l=e-o,u=(0,_s.Enum)("Swap",{asset_in:n,asset_out:a,amount_in:t,amount_out:l,partial:!1}),p=this.apiIce.tx.Intent.submit_intent({intent:{data:u}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(p=await this.dispatchWithExtraGas(p)),this.wrapTx("IntentSwap",p)}};var Os=require("polkadot-api");var _i=class extends lt{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=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 partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,r=i[0],s=i[i.length-1],n=r.assetIn,a=s.assetOut,o=(0,Os.Enum)("Swap",{asset_in:n,asset_out:a,amount_in:t,amount_out:this.minAmountOut??e,partial:this.partial}),l=this.apiIce.tx.Intent.submit_intent({intent:{data:o,deadline:this.deadline}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("IntentLimitOrder",l)}};var fr=require("polkadot-api");var Oi=class extends lt{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=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 slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:i,assetOutEd:r,tradeAmountIn:s,tradePeriod:n}=this.order,a=(0,fr.Enum)("Dca",{asset_in:e,asset_out:i,amount_in:s,amount_out:r,slippage:this.slippagePct*1e4,budget:t,period:n}),o=this.apiIce.tx.Intent.submit_intent({intent:{data:a}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("IntentDcaSchedule",o)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradeAmountOut:s,tradePeriod:n}=this.order,a=C.getFraction(s,this.slippagePct),o=s-a,l=(0,fr.Enum)("Dca",{asset_in:e,asset_out:i,amount_in:r,amount_out:o,slippage:this.slippagePct*1e4,budget:t,period:n}),u=this.apiIce.tx.Intent.submit_intent({intent:{data:l}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("IntentDcaSchedule.twap",u)}};var ie=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new wi(this.client,this.evmClient).setTrade(t)}order(t){return new Ti(this.client,this.evmClient).setOrder(t)}intentMarket(t){return new Ii(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new _i(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new Oi(this.client,this.evmClient).setOrder(t)}};async function In(c,t){let{at:e}=t??{},i=new Vt(c),r=new pe(c),[s,n]=await Promise.all([i.getBlockTime(),i.getMinOrderBudget()]),a=new Zt(c,r,e).withAave().withOmnipool().withStableswap().withXyk(),o=new mt(c),l=new qe(c),u=new ye(c),p=new Bt(r),d=new At(a),m=new ee(a,{blockTime:s,minBudgetInNative:n}),h=new Le(l,o),b=new ge(u,o,{blockTime:s});return{api:{aave:p,router:d,scheduler:m,staking:h,farm:b},client:{asset:new qt(c),balance:o,evm:r},ctx:{pool:a},tx:new ie(c,r),destroy:()=>{a.destroy()}}}0&&(module.exports={QueryBus,aave,api,async,calc,client,const:null,createSdkContext,error,evm,farm,fmt,json,math,pool,sor,staking,tx});
|