@galacticcouncil/sdk-next 1.5.0 → 1.5.1

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