@galacticcouncil/sdk-next 0.36.3 → 0.36.4

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