@galacticcouncil/sdk-next 0.26.0 → 0.27.0

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