@galacticcouncil/sdk-next 0.38.0 → 0.38.1-pr305-7b64458
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Sn=Object.create;var De=Object.defineProperty;var vn=Object.getOwnPropertyDescriptor;var wn=Object.getOwnPropertyNames;var xn=Object.getPrototypeOf,Tn=Object.prototype.hasOwnProperty;var lr=(c,t)=>()=>(c&&(t=c(c=0)),t);var F=(c,t)=>{for(var e in t)De(c,e,{get:t[e],enumerable:!0})},Me=(c,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of wn(t))!Tn.call(c,r)&&r!==e&&De(c,r,{get:()=>t[r],enumerable:!(i=vn(t,r))||i.enumerable});return c},Bt=(c,t,e)=>(Me(c,t,"default"),e&&Me(e,t,"default")),vt=(c,t,e)=>(e=c!=null?Sn(xn(c)):{},Me(t||!c||!c.__esModule?De(e,"default",{value:c,enumerable:!0}):e,c)),In=c=>Me(De({},"__esModule",{value:!0}),c);var Qt={};var gr=lr(()=>{Bt(Qt,require("@polkadot-api/smoldot"))});var Jt={};var hr=lr(()=>{Bt(Jt,require("@polkadot-api/known-chains/polkadot"))});var ms={};F(ms,{QueryBus:()=>le,aave:()=>Ii,api:()=>Si,async:()=>ae,calc:()=>q,client:()=>Ai,const:()=>Oi,createSdkContext:()=>ps,error:()=>Fi,evm:()=>Ci,farm:()=>Hi,fmt:()=>_,json:()=>Dt,math:()=>W,pool:()=>Xi,sor:()=>er,staking:()=>rr,tx:()=>sr});module.exports=In(ms);var Si={};F(Si,{Papi:()=>L,Watcher:()=>jt,getSm:()=>An,getWs:()=>On});var qe=require("@galacticcouncil/descriptors");var ur=require("@galacticcouncil/common"),Le=require("rxjs");var yt=require("rxjs"),H=require("rxjs/operators");function cr(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>(0,yt.defer)(()=>(0,yt.from)(c._request("system_health",[]))).pipe((0,H.timeout)({first:e}),(0,H.map)(()=>"online"),(0,H.catchError)(()=>(0,yt.of)("offline")));return(0,yt.of)({state:"offline",delayMs:0}).pipe((0,H.expand)(n=>(0,yt.timer)(n.delayMs).pipe((0,H.switchMap)(i),(0,H.map)(s=>({state:s,delayMs:t})))),(0,H.skip)(1),(0,H.map)(n=>n.state),(0,H.distinctUntilChanged)(),(0,H.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:_n}=ur.log,jt=class c{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)",cr(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe((0,Le.tap)({error:i=>_n.error(t,i)}),(0,Le.shareReplay)({bufferSize:1,refCount:!0}))}};var L=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(qe.hydration),this.apiNext=this.client.getTypedApi(qe.hydrationNext),this.watcher=jt.getInstance(this.client)}};var pr=require("polkadot-api/ws-provider"),mr=require("polkadot-api/logs-provider"),dr=require("@polkadot-api/legacy-provider"),On=(c,t={})=>{let e=typeof c=="string"?c.split(","):c,i=(0,pr.getWsProvider)(e,{innerEnhancer:(0,dr.withLegacy)(),...t});return(0,mr.withLogsRecorder)(r=>console.log(r),i),i};var br=require("polkadot-api/sm-provider");async function An(c){let{start:t}=await Promise.resolve().then(()=>(gr(),Qt)),{chainSpec:e}=await Promise.resolve().then(()=>(hr(),Jt)),i=t(),r=await i.addChain({chainSpec:e}),n=await i.addChain({chainSpec:c,potentialRelayChains:[r]});return(0,br.getSmProvider)(n)}var Ii={};F(Ii,{AAVE_GAS_LIMIT:()=>xi,AAVE_LENDING_POOL_ADDRESS:()=>Ge,AAVE_POOL_ABI:()=>vi,AAVE_POOL_DATA_PROVIDER:()=>He,AAVE_POOL_DATA_PROVIDER_ABI:()=>Ne,AAVE_POOL_PROXY:()=>wi,AAVE_ROUNDING_THRESHOLD:()=>Ds,AAVE_UINT_256_MAX:()=>Bn,AaveClient:()=>Zt,AaveUtils:()=>It});var vi=[{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 Ne=[{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 wi="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",He="0x112b087b60C1a166130d59266363C45F8aa99db0",Ge="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",xi=1000000n,Ds=5,Bn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Zt=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:Ne,address:He,args:[Ge],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:Ne,address:He,args:[Ge,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:vi,address:wi,args:[t],functionName:"getUserAccountData"})}};var G=vt(require("big.js")),nt=require("@galacticcouncil/common");var{ERC20:Ft}=nt.erc20,{H160:Ti}=nt.h160,Fn=1.01,Rn=31536000n,yr=4,Ue=-1,Ve=10n**27n,It=class{client;constructor(t){this.client=new Zt(t)}async getSummary(t){let e=Ti.fromAny(t),[i,r,n,s]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[a]=i,[o,l]=r,[u,p,d,m,h,b]=n,g=nt.big.toDecimal(b,18),f=[];for(let y of o){let v=y.underlyingAsset.toLowerCase(),S=a.find(({underlyingAsset:Pi})=>Pi.toLowerCase()===v);if(!S)throw new Error("Missing pool reserve for "+v);let T=y.scaledATokenBalance,A=S.liquidityIndex,N=S.liquidityRate,V=S.availableLiquidity,ct=S.priceInMarketReferenceCurrency,bt=s+6,J=this.calculateLinearInterest(N,S.lastUpdateTimestamp,bt),rt=A*J/Ve,Kt=T*rt/Ve,Ce=Number(l!==0&&l===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,Ee=S.usageAsCollateralEnabled&&y.usageAsCollateralEnabledOnUser&&y.scaledATokenBalance>0n,ke=Ft.toAssetId(v);f.push({aTokenBalance:Kt,availableLiquidity:V,decimals:Number(S.decimals),isCollateral:Ee,priceInRef:ct,reserveId:ke,reserveAsset:v,reserveLiquidationThreshold:Ce})}return{healthFactor:Number(g),currentLiquidationThreshold:Number(nt.big.toDecimal(m,yr)),totalCollateral:u,totalDebt:p,reserves:f}}async hasBorrowPositions(t){let e=Ti.fromAny(t),i=await this.client.getUserAccountData(e),[r,n]=i;return n>0n}async getHealthFactor(t){let e=Ti.fromAny(t),i=await this.client.getUserAccountData(e),[r,n,s,a,o,l]=i;return this.calculateHealthFactorFromBalances(n,r,a)}async getHealthFactorAfterWithdraw(t,e,i){let{totalCollateral:r,totalDebt:n,reserves:s,currentLiquidationThreshold:a}=await this.getSummary(t);if(n===0n)return Ue;let o=Ft.fromAssetId(e),l=s.find(v=>v.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:u,isCollateral:p,priceInRef:d,reserveLiquidationThreshold:m}=l,h=nt.big.toBigInt(i,u),b=p?h*d/10n**BigInt(u):0n,g=r-b;if(g<=0n)return 0;let f=(0,G.default)(r.toString()).mul(a).minus((0,G.default)(b.toString()).mul(m)).div(g.toString()),y=(0,G.default)(g.toString()).mul(f).div(n.toString()).toFixed(6,G.default.roundDown);return Number(y)}async getHealthFactorAfterSupply(t,e,i){let{totalCollateral:r,totalDebt:n,reserves:s,currentLiquidationThreshold:a}=await this.getSummary(t);if(n===0n)return Ue;let o=Ft.fromAssetId(e),l=s.find(y=>y.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:u,priceInRef:p,reserveLiquidationThreshold:d}=l,h=nt.big.toBigInt(i,u)*p/10n**BigInt(u),b=r+h;if(b<=0n)return 0;let g=(0,G.default)(r.toString()).mul(a).plus((0,G.default)(h.toString()).mul(d)).div(b.toString()),f=(0,G.default)(b.toString()).mul(g).div(n.toString()).toFixed(6,G.default.roundDown);return Number(f)}async getHealthFactorAfterSwap(t,e,i,r,n){let{totalDebt:s,reserves:a,healthFactor:o}=await this.getSummary(t);if(s===0n)return Ue;let l=Ft.fromAssetId(i),u=Ft.fromAssetId(n),p=a.find(A=>A.reserveAsset===l),d=a.find(A=>A.reserveAsset===u);if(!p)throw new Error(`Missing reserve ctx for ${l}`);if(!d)throw new Error(`Missing reserve ctx for ${d}`);let m=nt.big.toBigInt(e,p.decimals),h=nt.big.toBigInt(r,d.decimals),b=m*p.priceInRef/10n**BigInt(p.decimals),g=h*d.priceInRef/10n**BigInt(d.decimals),f=p.isCollateral?(0,G.default)(b.toString()).mul(p.reserveLiquidationThreshold):(0,G.default)(0),S=(0,G.default)(g.toString()).mul(d.reserveLiquidationThreshold).minus(f).div(s.toString()),T=(0,G.default)(o).plus(S).toFixed(6,G.default.roundDown);return Number(T)}async getMaxWithdraw(t,e){let{totalDebt:i,reserves:r,healthFactor:n}=await this.getSummary(t),s=Ft.fromAssetId(e),a=r.find(o=>o.reserveAsset===s);if(!a)throw new Error("Missing reserve ctx for "+s);return this.calculateWithdrawMax(a,i,n)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:i,healthFactor:r}=await this.getSummary(t),n={};for(let s of i){let a=this.calculateWithdrawMax(s,e,r);s.reserveId&&(n[s.reserveId]=a)}return n}calculateWithdrawMax(t,e,i){let{aTokenBalance:r,availableLiquidity:n,decimals:s,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=t,u=r;if(l&&e>0n){let d=i-Fn;if(d>0){let m=(0,G.default)(d).mul(e.toString()).div(o).toFixed(0,G.default.roundDown),h=(0,G.default)(m).div(a.toString()).mul(10**s).toFixed(0,G.default.roundDown);u=r<BigInt(h)?r:BigInt(h)}else u=0n}return{amount:u<n?u:n,decimals:s}}calculateLinearInterest(t,e,i){let r=i-e;if(r<=0)return Ve;let n=t*BigInt(r)/Rn;return Ve+n}calculateHealthFactorFromBalances(t,e,i){if(t===0n)return Ue;let r=e*i/t,n=nt.big.toDecimal(r,yr);return Number(n)}};var Ai={};F(Ai,{AssetClient:()=>Rt,BalanceClient:()=>ut,ChainParams:()=>Mt});var Rt=class extends L{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:i,value:r})=>{let[n]=i;return[n,r]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:i,value:r})=>{let[n]=i;return[n,r]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:i})=>{let{asset_type:r}=i;return this.SUPPORTED_TYPES.includes(r.type)}).map(({keyArgs:i,value:r})=>{let[n]=i;return[n,r]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:i,value:r})=>{let[n]=i;return[n,r]}))}async mapToken(t,e,i,r){let{name:n,asset_type:s,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=i.get(t)??{};return{id:t,name:n?.asText(),symbol:l,decimals:u,icon:l,type:s.type,isSufficient:a,location:r,existentialDeposit:o}}async mapBond(t,e,i,r){let[n,s]=r,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:p}=await this.mapToken(n,e,i),d=Number(s),m=new Intl.DateTimeFormat("en-GB"),h=[u,"Bond",m.format(d)].join(" ");return{id:t,name:h,symbol:u+"b",decimals:p,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:n,maturity:d}}async mapShares(t,e,i,r){let{assets:n}=r,{name:s,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,p=await Promise.all(n.map(async h=>{let{symbol:b}=await this.mapToken(h,e,i);return[h,b]})),d=Object.fromEntries(p),m=Object.values(d);return{id:t,name:m.join(", "),symbol:a?.asText()||s?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:d}}async mapExternal(t,e,i,r){let n=await this.mapToken(t,e,new Map,r),s=i?.find(a=>a.internalId===n.id);return s?{...n,decimals:s.decimals,name:s.name,symbol:s.symbol,icon:s.symbol,isWhiteListed:s.isWhiteListed}:n}parseMetadata(t){return new Map(Array.from(t,([e,i])=>[e,{symbol:i.symbol?.asText(),decimals:i.decimals}]))}async getSupported(t,e){let[i,r,n,s]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(i),o=[];for(let[l,u]of Array.from(i)){let p=r.get(l),{asset_type:d}=u,m;switch(d.type){case"Bond":let h=s.get(l);m=await this.mapBond(l,u,a,h);break;case"StableSwap":let b=n.get(l);m=await this.mapShares(l,u,a,b);break;case"External":m=await this.mapExternal(l,u,e,p);break;default:m=await this.mapToken(l,u,a,p)}o.push(m)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var fr=require("@galacticcouncil/common"),Z=require("rxjs"),w=require("rxjs/operators");var Oi={};F(Oi,{HUB_ASSET_ID:()=>te,HYDRATION_OMNIPOOL_ADDRESS:()=>En,HYDRATION_PARACHAIN_ID:()=>Cn,PERBILL_DENOMINATOR:()=>_i,PERMILL_DENOMINATOR:()=>Ct,SYSTEM_ASSET_DECIMALS:()=>We,SYSTEM_ASSET_ID:()=>E,TRADEABLE_DEFAULT:()=>Et});var Ct=1e6,_i=1e9,E=0,We=12,Cn=2034,En="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",te=1,Et=15;var{logger:kt}=fr.log,ut=class extends L{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:i}=await e.getValue(t,{at:"best"});return this.getBreakdown(i)}async getTokenBalance(t,e){let r=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(r)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,Z.defer)(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),r=this.watchErc20Balance(t);return(0,Z.combineLatest)([e,i,r]).pipe((0,w.connect)(n=>(0,Z.concat)(n.pipe((0,w.take)(1)),n.pipe((0,w.skip)(1),(0,w.debounceTime)(250)))))}).pipe((0,w.map)(e=>e.flat()),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([e,i],r)=>r===0?i:this.getDeltas(e,i))).pipe((0,w.tap)({subscribe:()=>kt.debug("balance: subscribe",t),error:e=>kt.error("balance",e)}),(0,w.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,Z.defer)(()=>e.watchValue(t,"best")).pipe((0,w.map)(i=>({id:0,balance:this.getBreakdown(i.data)})),(0,w.tap)({error:i=>kt.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return(0,Z.defer)(()=>i.watchValue(t,e,"best")).pipe((0,w.map)(r=>({id:e,balance:this.getBreakdown(r)})),(0,w.tap)({error:r=>kt.error("balance(token)",r)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,Z.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,w.distinctUntilChanged)((i,r)=>!r.deltas),(0,w.map)(({deltas:i})=>{let r=[];return i?.deleted.forEach(n=>{let[s,a]=n.args;r.push({id:a,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(n=>{let[s,a]=n.args;r.push({id:a,balance:this.getBreakdown(n.value)})}),r}),(0,w.tap)({error:i=>kt.error("balance(tokens)",i)}))}watchErc20Balance(t,e){let i=async()=>(await this.api.query.AssetRegistry.Assets.getEntries({at:"best"})).filter(({value:s})=>s.asset_type.type==="Erc20").map(({keyArgs:s})=>{let[a]=s;return a}),r=async n=>(await Promise.all(n.map(async a=>[a,await this.getBalanceData(t,a)]))).map(([a,o])=>({id:a,balance:o}));return(0,Z.defer)(()=>(0,Z.from)(e?Promise.resolve(e):i()).pipe((0,w.switchMap)(n=>this.watcher.bestBlock$.pipe((0,w.startWith)(null),(0,w.switchMap)(()=>(0,Z.from)(r(n))))),(0,w.pairwise)(),(0,w.map)(([n,s],a)=>a===0?s.filter(o=>o.balance.total>0n):this.getDeltas(n,s)),(0,w.distinctUntilChanged)((n,s)=>s.length===0),(0,w.tap)({error:n=>kt.error("balance(erc20)",n)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.getBreakdown(i)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,i=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:i,transferable:e}}getDeltas(t,e){let i=(n,s)=>n!==void 0&&s!==void 0&&n.transferable===s.transferable&&n.total===s.total,r=t.reduce((n,s)=>(n.set(s.id,s.balance),n),new Map);return e.filter(n=>!i(n.balance,r.get(n.id)))}};var Mt=class extends L{_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 Fi={};F(Fi,{AssetNotFound:()=>Bi,PoolNotFound:()=>ee,RouteNotFound:()=>ie});var Bi=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},ee=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},ie=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Ci={};F(Ci,{EvmClient:()=>se,EvmRpcAdapter:()=>ne,createChain:()=>Ri});var re=require("polkadot-api"),Pr=require("@galacticcouncil/descriptors"),Ye=require("viem"),kn=10000000n,ne=class{api;constructor(t){this.api=t.getTypedApi(Pr.hydration)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,i=e.timestamp/1000n,[r]=e.number;return{timestamp:i,number:r}}readContract=(async t=>{let{abi:e,address:i,functionName:r,args:n}=t,s=(0,Ye.encodeFunctionData)({abi:e,functionName:r,args:n}),a=await this.api.apis.EthereumRuntimeRPCApi.call(re.FixedSizeBinary.fromText(""),re.FixedSizeBinary.fromHex(i),re.Binary.fromHex(s),[0n,0n,0n,0n],[kn,0n,0n,0n],void 0,void 0,void 0,!1,[],[]);if(!a.success)throw console.error(r,a.value.type),new Error("Contract read failure");let{exit_reason:o,value:l,used_gas:u}=a.value;if(console.log(u),o.type==="Succeed")return(0,Ye.decodeFunctionResult)({abi:e,functionName:r,data:l.asHex()});throw console.log(r,o.type,o.value.type),new Error("Contract read error")})};var Sr=require("viem"),Mn=["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"],Ri=()=>(0,Sr.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:Mn}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var pt=require("viem");var se=class{client;chain;constructor(t){this.client=t,this.chain=Ri()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,pt.createPublicClient)({chain:this.chain,transport:(0,pt.http)()})}getWsProvider(){return(0,pt.createPublicClient)({transport:(0,pt.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,pt.createWalletClient)({account:t,chain:this.chain,transport:(0,pt.custom)(window.ethereum)})}getRPCAdapter(){return new ne(this.client)}};var Hi={};F(Hi,{LiquidityMiningApi:()=>ce,LiquidityMiningClient:()=>ue});var Er=require("polkadot-api"),Y=vt(require("big.js")),ft=require("@galacticcouncil/common"),Ni=require("@galacticcouncil/math-liquidity-mining");var ae={};F(ae,{withTimeout:()=>Dn});function Dn(c,t,e="timeout"){return new Promise((i,r)=>{let n=setTimeout(()=>r(new Error(e)),t);c.then(s=>{clearTimeout(n),i(s)},s=>{clearTimeout(n),r(s)})})}var q={};F(q,{divSpot:()=>qn,getFraction:()=>Nn,mulScaled:()=>vr,mulSpot:()=>Ln});var Ei=require("@galacticcouncil/common");function vr(c,t,e,i,r){let n=e+i-r,s=c*t;return n>0?s/BigInt(10)**BigInt(n):n<0?s*BigInt(10)**BigInt(-n):s}function Ln(c,t,e,i){return vr(c,t,e,Ei.RUNTIME_DECIMALS,i)}function qn(c,t,e,i){if(t===0n)return 0n;let r=BigInt(10)**BigInt(Ei.RUNTIME_DECIMALS+i-e);return c*r/t}function Nn(c,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let i=BigInt(10)**BigInt(e),r=BigInt(Math.round(t*Number(i)));return c*r/(BigInt(100)*i)}var _={};F(_,{FeeUtils:()=>ki,shiftNeg:()=>Hn});var wr=vt(require("big.js"));var ki=class c{static toPct(t){let[e,i]=t;return c.safeDivide(e*100,i)}static toRaw(t){let[e,i]=t;return c.safeDivide(e,i)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,i=12){let r=10**i;return Math.round(t*r/e)/r}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Hn(c,t){let e=(0,wr.default)(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Dt={};F(Dt,{findNestedKey:()=>Gn,findNestedObj:()=>Un,jsonFormatter:()=>Vn});var Gn=(c,t)=>{let e=[];return JSON.stringify(c,(i,r)=>(r&&r[t]&&e.push(r),r)),e[0]},Un=(c,t,e)=>{let i;return JSON.stringify(c,(r,n)=>(n&&n[t]===e&&(i=n),n)),i},Vn=(c,t)=>typeof t=="bigint"?t.toString():t;var W={};F(W,{calculateBuyFee:()=>$n,calculateDiffToAvg:()=>Wn,calculateDiffToRef:()=>Yn,calculateSellFee:()=>zn});var mt=vt(require("big.js"));function Wn(c,t){let e=(0,mt.default)(c.toString()),i=(0,mt.default)(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function Yn(c,t){if(t===0n)return 0;let e=(0,mt.default)(c.toString()),i=(0,mt.default)(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function zn(c,t){if(c===0n)return 0;let e=(0,mt.default)(c.toString()),i=(0,mt.default)(t.toString());return(0,mt.default)(1).minus(i.div(e)).mul(100).round(2).toNumber()}function $n(c,t){if(c===0n)return 0;let e=(0,mt.default)(c.toString());return(0,mt.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var oe=(c,t)=>c===t?0:c==null?t==null?0:-1:t==null?c==null?0:1:typeof c.compare=="function"?c.compare(t):typeof t.compare=="function"?-t.compare(c):c<t?-1:c>t?1:0;var ze=(c,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(c(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var Xn=ze(()=>"illegal argument(s)"),xr=c=>{throw new Xn(c)};var Kn=ze(()=>"index out of bounds"),Mi=c=>{throw new Kn(c)},$e=(c,t,e)=>(c<t||c>=e)&&Mi(c);var Tr=23283064365386963e-26,Xe=class{float(t=1){return this.int()*Tr*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*Tr-.5)*2*t}normMinMax(t,e){let i=this.minmax(t,e);return this.float()<.5?i:-i}minmax(t,e){return this.float()*(e-t)+t}minmaxInt(t,e){t|=0;let i=(e|0)-t;return i?t+this.int()%i:t}minmaxUint(t,e){t>>>=0;let i=(e>>>0)-t;return i?t+this.int()%i:t}};var Ke=class extends Xe{constructor(t){super(),this.rnd=t}float(t=1){return this.rnd()*t}norm(t=1){return(this.rnd()-.5)*2*t}int(){return this.rnd()*4294967296>>>0}};var Ir=new Ke(Math.random);var _r=c=>c!=null&&typeof c!="function"&&c.length!==void 0;var Or=Object.getPrototypeOf({}),je="function",Ar="string",Lt=(c,t)=>{let e;if(c===t)return!0;if(c!=null){if(typeof c.equiv===je)return c.equiv(t)}else return c==t;if(t!=null){if(typeof t.equiv===je)return t.equiv(c)}else return c==t;return typeof c===Ar||typeof t===Ar?!1:(e=Object.getPrototypeOf(c),(e==null||e===Or)&&(e=Object.getPrototypeOf(t),e==null||e===Or)?Zn(c,t):typeof c!==je&&c.length!==void 0&&typeof t!==je&&t.length!==void 0?jn(c,t):c instanceof Set&&t instanceof Set?Qn(c,t):c instanceof Map&&t instanceof Map?Jn(c,t):c instanceof Date&&t instanceof Date?c.getTime()===t.getTime():c instanceof RegExp&&t instanceof RegExp?c.toString()===t.toString():c!==c&&t!==t)},jn=(c,t,e=Lt)=>{let i=c.length;if(i===t.length)for(;i-- >0&&e(c[i],t[i]););return i<0},Qn=(c,t,e=Lt)=>c.size===t.size&&e([...c.keys()].sort(),[...t.keys()].sort()),Jn=(c,t,e=Lt)=>c.size===t.size&&e([...c].sort(),[...t].sort()),Zn=(c,t,e=Lt)=>{if(Object.keys(c).length!==Object.keys(t).length)return!1;for(let i in c)if(!t.hasOwnProperty(i)||!e(c[i],t[i]))return!1;return!0};var Di=class{value;constructor(t){this.value=t}deref(){return this.value}};var Br=c=>c instanceof Di;var Qe=class c{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Fr("next",this._head)}reverseIterator(){return Fr("prev",this.tail)}clear(){this.release()}compare(t,e=oe){let i=this._length;if(i<t._length)return-1;if(i>t._length)return 1;if(i===0)return 0;{let r=this._head,n=t._head,s=0;for(;i-- >0&&s===0;)s=e(r.value,n.value),r=r.next,n=n.next;return s}}concat(...t){let e=this.copy();for(let i of t)e.into(i);return e}equiv(t){if(!(t instanceof c||_r(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),i=this._head;for(let r=this._length;r-- >0;){if(!Lt(i.value,e.next().value))return!1;i=i.next}return!0}filter(t){let e=this.empty();return this.traverse(i=>(t(i.value)&&e.append(i.value),!0)),e}find(t){return this.traverse(e=>e.value!==t)}findWith(t){return this.traverse(e=>!t(e.value))}first(){return this._head?.value}insertSorted(t,e){e=e||oe;for(let i=this._head,r=this._length;r-- >0;){if(e(t,i.value)<=0)return this.insertBefore(i,t);i=i.next}return this.append(t)}into(t){for(let e of t)this.append(e);return this}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCellUnsafe(t){let e,i;for(t<=this._length>>>1?(e=this._head,i="next"):(e=this.tail,i="prev",t=this._length-t-1);t-- >0&&e;)e=e[i];return e}peek(){return this.tail?.value}$reduce(t,e){let i=this._head;for(let r=this._length;r-- >0&&!Br(e);)e=t(e,i.value),i=i.next;return e}reduce(t,e){return this.$reduce(t,e)}release(){let t=this._head;if(!t)return!0;let e;for(let i=this._length;i-- >0;)e=t.next,delete t.value,delete t.prev,delete t.next,t=e;return this._head=void 0,this._length=0,!0}reverse(){let t=this._head,e=this.tail,i=(this._length>>>1)+(this._length&1);for(;t&&e&&i>0;){let r=t.value;t.value=e.value,e.value=r,t=t.next,e=e.prev,i--}return this}setHead(t){let e=this._head;return e?(e.value=t,e):this.prepend(t)}setNth(t,e){let i=this.nthCell(t);return!i&&Mi(t),i.value=e,i}setTail(t){let e=this.tail;return e?(e.value=t,e):this.append(t)}swap(t,e){if(t!==e){let i=t.value;t.value=e.value,e.value=i}return this}toArray(t=[]){return this.traverse(e=>(t.push(e.value),!0)),t}toJSON(){return this.toArray()}toString(){let t=[];return this.traverse(e=>(t.push(String(e.value)),!0)),t.join(", ")}traverse(t,e=this._head,i){if(!this._head)return;let r=e;do{if(!t(r))break;r=r.next}while(r!==i);return r}_map(t,e){return this.traverse(i=>(t.append(e(i.value)),!0)),t}};function*Fr(c,t){for(;t;)yield t.value,t=t[c]}var Je=class c extends Qe{_tail;constructor(t){super(),t&&this.into(t)}get tail(){return this._tail}append(t){if(this._tail){let e={value:t,prev:this._tail};return this._tail.next=e,this._tail=e,this._length++,e}else return this.prepend(t)}asHead(t){return t===this._head?this:(this.remove(t),this._head.prev=t,t.next=this._head,t.prev=void 0,this._head=t,this._length++,this)}asTail(t){return t===this._tail?this:(this.remove(t),this._tail.next=t,t.prev=this._tail,t.next=void 0,this._tail=t,this._length++,this)}cons(t){return this.prepend(t),this}copy(){return new c(this)}*cycle(){for(;;)yield*this}drop(){let t=this._head;if(t)return this._head=t.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,t.value}empty(){return new c}insertAfter(t,e){let i={value:e,next:t.next,prev:t};return t.next?t.next.prev=i:this._tail=i,t.next=i,this._length++,i}insertAfterNth(t,e){return t<0&&(t+=this._length),t>=this._length-1?this.append(e):($e(t,0,this._length),this.insertAfter(this.nthCellUnsafe(t),e))}insertBefore(t,e){let i={value:e,next:t,prev:t.prev};return t.prev?t.prev.next=i:this._head=i,t.prev=i,this._length++,i}insertBeforeNth(t,e){return t<0&&(t+=this._length),t<=0?this.prepend(e):($e(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new c,t)}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCell(t){if(t<0&&(t+=this._length),!(t<0||t>=this._length))return this.nthCellUnsafe(t)}pop(){let t=this._tail;if(t)return this._tail=t.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,t.value}prepend(t){let e={value:t,next:this._head};return this._head?this._head.prev=e:this._tail=e,this._head=e,this._length++,e}push(t){return this.append(t),this}release(){return this._tail=void 0,super.release()}remove(t){return t.prev?t.prev.next=t.next:this._head=t.next,t.next?t.next.prev=t.prev:this._tail=t.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let t=this.peek();return this.pop(),this.prepend(t),this}}seq(t=0,e=this.length){if(t>=e||t<0)return;let i=this.nthCell(t),r=this.nthCell(e-1),n=s=>({first(){return s.value},next(){return s!==r&&s.next?n(s.next):void 0}});return i?n(i):void 0}shuffle(t,e=Ir){if(this._length<2)return this;for(t=t!==void 0?t:Math.ceil(1.5*Math.log2(this._length));t>0;t--){let i=this._head;for(;i;){let r=i.next;e.probability(.5)?this.asHead(i):this.asTail(i),i=r}}return this}slice(t=0,e=this.length){let i=t<0?t+this._length:t,r=e<0?e+this._length:e;(i<0||r<0)&&xr("invalid indices: ${from} / ${to}");let n=new c,s=this.nthCell(i);for(;s&&++i<=r;)n.push(s.value),s=s.next;return n}sort(t=oe){if(!this._length)return this;let e=1;for(;;){let i=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;i;){r++;let n=i,s=0;for(let o=0;o<e&&(s++,n=n.next,!!n);o++);let a=e;for(;s>0||a>0&&n;){let o;s===0?(o=n,n=n.next,a--):!n||a===0||t(i.value,n.value)<=0?(o=i,i=i.next,s--):(o=n,n=n.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}i=n}if(this._tail.next=void 0,r<=1)return this;e*=2}}splice(t,e=0,i){let r;typeof t=="number"?(t<0&&(t+=this._length),$e(t,0,this._length),r=this.nthCellUnsafe(t)):r=t;let n=new c;if(e>0)for(;r&&e-- >0;)this.remove(r),n.push(r.value),r=r.next;else r&&(r=r.next);if(i)if(r)for(let s of i)this.insertBefore(r,s);else for(let s of i)this.push(s);return n}};var Ze=class c{map;items;opts;_size;constructor(t,e){let i={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...e};this.map=i.map(),this.items=new Je,this._size=0,this.opts=i,t&&this.into(t)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let t of this.items)yield[t.k,t]}*keys(){for(let t of this.items)yield t.k}*values(){for(let t of this.items)yield t.v}copy(){let t=this.empty();t.items=this.items.copy();let e=t.items.head;for(;e;)t.map.set(e.value.k,e),e=e.next;return t}empty(){return new c(null,this.opts)}release(){this._size=0,this.map.clear();let t=this.opts.release;if(t){let e;for(;e=this.items.drop();)t(e.k,e.v);return!0}return this.items.release()}has(t){return this.map.has(t)}get(t,e){let i=this.map.get(t);return i?this.resetEntry(i):e}set(t,e){let i=this.opts.ksize(t)+this.opts.vsize(e),r=this.map.get(t),n=Math.max(0,i-(r?r.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(r,t,e,i):this._size-=n,e}into(t){for(let e of t)this.set(e[0],e[1]);return this}async getSet(t,e){let i=this.map.get(t);return i?this.resetEntry(i):this.set(t,await e())}delete(t){let e=this.map.get(t);return e?(this.removeEntry(e),!0):!1}resetEntry(t){return this.items.asTail(t),t.value.v}ensureSize(){let{release:t,maxsize:e,maxlen:i}=this.opts;for(;this._size>e||this.length>=i;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),t?.(r.k,r.v),this._size-=r.s}return!0}removeEntry(t){let e=t.value;this.map.delete(e.k),this.items.remove(t),this.opts.release?.(e.k,e.v),this._size-=e.s}doSetEntry(t,e,i,r){t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=r,this.items.asTail(t)):(this.items.push({k:e,v:i,s:r}),this.map.set(e,this.items.tail))}};var _t=class c extends Ze{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new c(null,this.opts)}has(t){return this.get(t)!==void 0}get(t,e){let i=this.map.get(t);if(i){if(i.value.t>=Date.now())return this.resetEntry(i);this.removeEntry(i)}return e}set(t,e,i=this.opts.ttl){let r=this.opts.ksize(t)+this.opts.vsize(e),n=this.map.get(t),s=Math.max(0,r-(n?n.value.s:0));return this._size+=s,this.ensureSize()?this.doSetEntry(n,t,e,r,i):this._size-=s,e}async getSet(t,e,i=this.opts.ttl){let r=this.get(t);return r!==void 0?r:this.set(t,await e(),i)}prune(){let t=Date.now(),e=this.items.head,i=0;for(;e;)e.value.t<t&&(this.removeEntry(e),i++),e=e.next;return i}ensureSize(){let{maxlen:t,maxsize:e}=this.opts,i=Date.now(),r=this.items.head;for(;r&&(this._size>e||this.length>=t);)r.value.t<i&&this.removeEntry(r),r=r.next;return super.ensureSize()}doSetEntry(t,e,i,r,n=this.opts.ttl){let s=Date.now()+n;t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=r,t.value.t=s,this.items.asTail(t)):(this.items.push({k:e,v:i,s:r,t:s,ttl:n}),this.map.set(e,this.items.tail))}resetEntry(t){return this.opts.autoExtend&&(t.value.t=Date.now()+t.value.ttl),super.resetEntry(t)}};var le=class{debug;constructor(t){this.debug=t||!1}log(t,e,i){this.debug&&console.log(t,e,i)}scope(t,e,i,r){let n=new Map,s=r!==void 0?new _t(null,{ttl:r}):new _t;return{get:(...u)=>{let p=i(...u);if(n.has(p)){this.log("[live]",t,p);let m=n.get(p);return Promise.resolve(m)}if(s.has(p))return this.log("[memo]",t,p),s.get(p);this.log("[fetch]",t,p);let d=e(...u).catch(m=>{throw s.delete(p),m});return s.set(p,d),d},set:(u,...p)=>{let d=i(...p);this.log("[set-live]",t,d),n.set(d,u)},clear:()=>{this.log("[clear]",t),n.clear(),s.release()}}}};var ti=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let i=0;i<t.length;++i){let[r,n]=t[i];this.result.set(this.getKey(n,r),e[i].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,i,r){let n=this.getKey(t,e),s=this.getKey(t,i),a=this.result.get(n)??0n,o=this.result.get(s)??0n;if(a<r)throw new Error("Attempting to transfer more than is present");this.result.set(n,a+r),this.result.set(s,o+r)}};var wt=vt(require("big.js")),at=require("@galacticcouncil/math-liquidity-mining");var Li=vt(require("big.js")),qi=(0,Li.default)(10).pow(18),Rr=BigInt((0,Li.default)(1).pow(18).toString()),Cr=6e3;var ts="1000000000000000000",ei=class{constructor(t,e,i){this.getAccount=t;this.getAsset=e;this.multiCurrency=i}async syncGlobalFarm(t,e,i){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let r=await this.getAsset(t.reward_currency),n=e-t.updated_at,s=this.getAccount(t.id),a=r?.existential_deposit;if(!a)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,s),l=(0,wt.default)(a.toString()),u=(0,wt.default)(o.toString()).minus(l.lt(o.toString())?a.toString():o.toString()),p=(0,wt.default)((0,at.calculate_global_farm_rewards)(t.total_shares_z.toString(),i.toString(),(0,wt.default)(t.yield_per_period.toString()).mul(qi).round(0,wt.default.roundDown).toFixed(),t.max_reward_per_period.toString(),n.toFixed()));if(u.lt(p)&&(p=u),p.eq(0))return t;let d=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,s,d,BigInt(p.toFixed())),{...t,accumulated_rpz:BigInt((0,at.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),p.toFixed()))}}syncYieldFarm(t,e,i){if(t.state.type!=="Active"||t.updated_at===i)return null;if(t.total_valued_shares===0n)return{...t,updated_at:i};let r=(0,at.calculate_yield_farm_delta_rpvs)(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(r),updated_at:i}}getLoyaltyMultiplier(t,e){let i=(0,wt.default)(1).mul(qi).round(0,wt.default.roundDown).toString();if(!e)return i;let{initial_reward_percentage:r,scale_coef:n}=e;return(0,at.calculate_loyalty_multiplier)(t.toFixed(),r.toString(),n.toFixed())}async claimRewards(t,e,i,r,n){if(e.state.type==="Terminated")return null;let s=Math.floor(r/t.blocks_per_period);if(i.updated_at===s)return null;let a=await this.syncGlobalFarm(t,s,n);if(!a)return null;let o=this.syncYieldFarm(e,a,s);if(!o)return null;let l=o.total_stopped-i.stopped_at_creation,u=o.updated_at-i.entered_at-l,p=this.getLoyaltyMultiplier(u,o.loyalty_curve),d=BigInt((0,at.calculate_user_reward)(i.accumulated_rpvs.toString(),i.valued_shares.toString(),i.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),m=BigInt((0,at.calculate_user_reward)(i.accumulated_rpvs.toString(),i.valued_shares.toString(),i.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),ts));return{reward:d,maxReward:m,assetId:a.reward_currency,yieldFarmId:o.id,isActiveFarm:o.state.type==="Active"}}};var es=(0,Y.default)(365.2425).times(24).times(60).times(60),ce=class{balance;client;options;constructor(t,e,i={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:i.blockTime??Cr})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let i=[t,e].sort((n,s)=>n-s);if(t===e)return Rr;let r=await this.client.getOraclePrice(i);if(r){let{n,d:s}=r[0].price,a;return t<e?a=(0,Ni.fixed_from_rational)(n.toString(),s.toString()):a=(0,Ni.fixed_from_rational)(s.toString(),n.toString()),BigInt(a)}}getFarmAddress=(t,e)=>{let i=Buffer.from("modl","utf-8"),r=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),n=Buffer.from([t]),s=Buffer.concat([i,r,n]),o="0x"+Buffer.concat([s,Buffer.alloc(32-s.length)]).toString("hex");return(0,Er.AccountId)(ft.HYDRATION_SS58_PREFIX).dec(o)};getGlobalRewardPerPeriod(t,e,i,r){let n=(0,Y.default)(r).times(t.toString()).times(e.toString()).div(Math.pow(10,ft.RUNTIME_DECIMALS));return n.gte(i.toString())?i.toString():n.toString()}getPoolYieldPerPeriod(t,e,i,r){let n=(0,Y.default)(t.toString()).times(e),s=(0,Y.default)(i.toString()).times(r);return n.div(s.toString()).toString()}farmData(t,e,i){let{yieldFarm:r,globalFarm:n,priceAdjustment:s,balance:a,id:o}=t,{multiplier:l,loyalty_curve:u}=r,{blocks_per_period:p,yield_per_period:d,total_shares_z:m,max_reward_per_period:h,pending_rewards:b,accumulated_paid_rewards:g,planned_yielding_periods:f,updated_at:y,incentivized_asset:v,reward_currency:S,price_adjustment:T,min_deposit:A}=n,N=_.shiftNeg(s??T,ft.RUNTIME_DECIMALS),V=_.shiftNeg(l,ft.RUNTIME_DECIMALS),ct=_.shiftNeg(u?.initial_reward_percentage??0,ft.RUNTIME_DECIMALS),bt=es.div((0,Y.default)(this.blockTime).div(1e3).times(p)).toString(),J;if(m<=0)J=(0,Y.default)(V).times(d.toString()).times(bt).div(Math.pow(10,ft.RUNTIME_DECIMALS)).toString();else{let fn=this.getGlobalRewardPerPeriod(m,d,h,N),Pn=this.getPoolYieldPerPeriod(fn,V,m,N);J=(0,Y.default)(Pn).times(bt).toString()}let rt=b+g,Kt=h*BigInt(f),Re=a.transferable+rt,ar=Re-rt,Ce=(0,Y.default)(ar.toString()).div(h.toString()),Ee=(0,Y.default)(e).div(p.toString()).toString(),ke=(m>=0?Ce.plus(y):Ce.plus(Ee)).toString(),Pi=(0,Y.default)(ke).times(p).toString(),bn=(0,Y.default)(m.toString()).div((0,Y.default)(h.toString()).div(d.toString())).div(Math.pow(10,ft.RUNTIME_DECIMALS)).times(100).times(N).toFixed(2),or=(0,Y.default)(rt.toString()).div(Re.toString()).gte(.999);J=or?"0":(0,Y.default)(J).div(i?2:1).times(100).toString();let yn=ct?(0,Y.default)(J).times(ct).toString():void 0;return{apr:J,minApr:yn,isDistributed:or,estimatedEndPeriod:ke,estimatedEndBlock:Pi,maxRewards:Kt,incentivizedAsset:v,rewardCurrency:S,loyaltyCurve:u,currentPeriod:Ee,potMaxRewards:Re,fullness:bn,yieldFarmId:r.id,globalFarmId:n.id,poolId:o,distributedRewards:rt,plannedYieldingPeriods:f,minDeposit:A,blocksPerPeriod:p}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((r,n)=>r.includes(n.keyArgs[0].toString())?r:[...r,n.keyArgs[0].toString()],[]),i=await Promise.all(e.map(async r=>{let n=await this.getOmnipoolFarms(r);if(n)return[r,n]}));return Object.fromEntries(i.filter(r=>!!r))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),i=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:n,value:s})=>{let[,a]=n,o=s,l=await this.client.getOmnipoolGlobalFarm(a),u=await this.client.getOmnipoolYieldFarm(Number(t),a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a),h=await this.getOraclePrice(p,d),b=await this.balance.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:h,balance:b}}));return i?r.map(n=>n?this.farmData(n,i):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((r,n)=>r.includes(n.keyArgs[0].toString())?r:[...r,n.keyArgs[0].toString()],[]),i=await Promise.all(e.map(async r=>{let n=await this.getIsolatedFarms(r);if(n)return[r,n]}));return Object.fromEntries(i.filter(r=>!!r))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),i=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:n,value:s})=>{let[,a]=n,o=s,l=await this.client.getIsolatedGlobalFarm(a),u=await this.client.getIsolatedYieldFarm(t,a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a,!0),h=await this.getOraclePrice(p,d),b=await this.balance.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:h,balance:b,farmAddress:m}}));return i?r.map(n=>n?this.farmData(n,i,!0):void 0):[]}async getDepositReward(t,e,i,r){let n=e.global_farm_id,s=e.yield_farm_id,a=i?await this.client.getIsolatedYieldFarm(t,n,s):await this.client.getOmnipoolYieldFarm(Number(t),n,s),o=i?await this.client.getIsolatedGlobalFarm(n):await this.client.getOmnipoolGlobalFarm(n);if(!o||!a)return;let l=o.reward_currency,u=o.incentivized_asset,p=[[this.getFarmAddress(0,i),o.reward_currency],[this.getFarmAddress(o.id,i),o.reward_currency]],d=await this.getAccountAssetBalances(p),m=await this.getOraclePrice(l,u),h=new ti(p,d),g=await new ei(y=>this.getFarmAddress(y),y=>this.client.getAsset(y),h).claimRewards(o,a,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,i]=await Promise.all([Promise.all(t.filter(([n,s])=>s!==0).map(([n,s])=>this.balance.getTokenBalance(n,s))),Promise.all(t.filter(([n,s])=>s===0).map(([n])=>this.balance.getSystemBalance(n)))]),r=[];for(let n=0,s=0;n+s<t.length;){let a=n+s,[,o]=t[a];o===0?(r.push(i[s]),s+=1):(r.push(e[n]),n+=1)}return r}};var ii=require("polkadot-api"),ue=class extends L{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(ii.Binary.fromText("omnipool"),t,(0,ii.Enum)("TenMinutes"))}async getRelayBlockNumber(){return(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number}async getAllOmnipooFarms(){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries()}async getOmnipooFarms(t){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries(t)}async getOmnipoolGlobalFarm(t){return this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getOmnipoolYieldFarm(t,e,i){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,i,{at:"best"})}async getAllIsolatedFarms(){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries()}async getIsolatedFarms(t){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries(t)}async getIsolatedGlobalFarm(t){return this.api.query.XYKWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getIsolatedYieldFarm(t,e,i){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,i,{at:"best"})}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};var Xi={};F(Xi,{PoolContextProvider:()=>Wt,PoolError:()=>xt,PoolFactory:()=>Vt,PoolType:()=>C,aave:()=>Yi,hsm:()=>$i,lbp:()=>Gi,omni:()=>Ui,stable:()=>Vi,xyk:()=>Wi});var Gi={};F(Gi,{LbpMath:()=>ot,LbpPool:()=>pe,LbpPoolClient:()=>me});var dt=require("@galacticcouncil/math-lbp"),ot=class{static getSpotPrice(t,e,i,r,n){return(0,dt.get_spot_price)(t,e,i,r,n)}static calculateInGivenOut(t,e,i,r,n){return(0,dt.calculate_in_given_out)(t,e,i,r,n)}static calculateOutGivenIn(t,e,i,r,n){return(0,dt.calculate_out_given_in)(t,e,i,r,n)}static calculateLinearWeights(t,e,i,r,n){return(0,dt.calculate_linear_weights)(t,e,i,r,n)}static calculatePoolTradeFee(t,e,i){return(0,dt.calculate_pool_trade_fee)(t,e,i)}};var qt=require("@galacticcouncil/common");var C=(s=>(s.Aave="Aave",s.LBP="LBP",s.Omni="Omnipool",s.Stable="Stableswap",s.XYK="XYK",s.HSM="HSM",s))(C||{}),xt=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(xt||{});var{FeeUtils:kr}=_,pe=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(s=>[s.id,s])),r=i.get(t),n=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:n.balance,decimalsIn:r.decimals,decimalsOut:n.decimals,weightIn:r.weight,weightOut:n.weight}}validateAndBuy(t,e,i){let r=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let s=t.balanceOut/this.maxOutRatio;if(e>s&&n.push("MaxOutRatioExceeded"),r===t.assetOut){let a=this.calculateTradeFee(e,i),o=kr.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return u>p&&n.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:n}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&n.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:n}}}validateAndSell(t,e,i){let r=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let s=t.balanceIn/this.maxInRatio;if(e>s&&n.push("MaxInRatioExceeded"),r===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:n}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,i),l=kr.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),u=a-o,p=t.balanceOut/this.maxOutRatio;return u>p&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:n}}}calculateInGivenOut(t,e){let i=ot.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}calculateOutGivenIn(t,e){let i=ot.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}spotPriceInGivenOut(t){let e=ot.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),qt.big.toBigInt(1,qt.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=ot.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),qt.big.toBigInt(1,qt.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let i=ot.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var qr=require("polkadot-api"),Nt=require("rxjs");var Mr=(c,t=new Map)=>e=>{let i;return t.has(e)?t.get(e):(t.set(e,i=c(e)),i)};var R=require("rxjs"),P=require("rxjs/operators");var Dr=require("rxjs"),ri=class{store$=new Dr.BehaviorSubject([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(t){return this.changeset.size===0?[]:t.filter(e=>this.changeset.has(e.address))}set(t){this.changeset=new Set(t.map(e=>e.address)),this.store$.next(t)}update(t){this.updateQueue=this.updateQueue.then(async()=>{let e=this.store$.value,i=new Map(e.map((a,o)=>[a.address,o])),r=await t(e),n=e.slice(),s=new Set;for(let a of r){let o=i.get(a.address);o===void 0?(i.set(a.address,n.length),n.push(a)):n[o]=a,s.add(a.address)}this.changeset=s,this.store$.next(n)}).catch(console.error)}destroy(){this.store$.complete()}};var Lr=require("@galacticcouncil/common");var is={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:ni}=Lr.log,si=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${is[this.type]})`,10)}trace(t,...e){ni.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){ni.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){ni.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){ni.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:rs}=ae,ns=3e3,Q=class extends L{evm;balance;store=new ri;log;shared$;resync$=new R.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new _t(null,{ttl:6*1e3});memPools=Mr(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e,this.balance=new ut(t),this.log=new si(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((0,P.startWith)([]),(0,P.bufferCount)(2,1),(0,P.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,P.filter)(t=>t.length>0),(0,P.throttleTime)(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return(0,R.defer)(()=>{let t=new R.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,P.switchMap)(()=>{let e=new R.Subscription;return(0,R.from)(rs(this.getMemPools(),6e4,"getMemPools stalled")).pipe((0,P.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,P.map)(r=>r.filter(n=>this.hasValidAssets(n))),(0,P.tap)(r=>this.store.set(r)),(0,P.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),R.EMPTY))).pipe((0,P.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,P.switchMap)(r=>(0,R.merge)((0,R.of)(r),this.store.asObservable().pipe((0,P.skip)(1)))),(0,P.finalize)(()=>{e.unsubscribe()}))}),(0,P.finalize)(()=>t.unsubscribe()))}).pipe((0,P.share)({connector:()=>new R.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:i}=e,r=[this.balance.watchTokensBalance(i)];if(this.hasSystemAsset(e)){let n=this.balance.watchSystemBalance(i);r.push(n)}if(this.hasErc20Asset(e)){let n=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),s=this.balance.watchErc20Balance(i,n);r.push(s)}return(0,R.combineLatest)(r).pipe((0,P.map)(n=>n.flat()),(0,P.pairwise)(),(0,P.map)(([n,s])=>this.balance.getDeltas(n,s)),(0,P.filter)(n=>n.length>0),(0,P.map)(n=>[i,n]))});return(0,R.merge)(...t).pipe((0,P.bufferTime)(250),(0,P.filter)(e=>e.length>0),(0,P.map)(e=>new Map(e)),this.watchGuard("balances")).subscribe(e=>{this.store.update(i=>this.updateBalances(i,e))})}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:i})=>i>0n&&!!e)}updateBalances=(t,e)=>{let i=[],r=new Map(t.map(n=>[n.address,n]));for(let[n,s]of e){let a=r.get(n);if(a){let o=a.tokens.map(l=>{let u=s.find(p=>p.id===l.id);return u&&l.id!==a.id?{...l,balance:u.balance.transferable}:l});i.push({...a,tokens:o})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<ns||(this.resyncAt=e,this.mem++,this.resync$.next())}requestResync(t=!1){this.resyncPending||(this.resyncPending=!0,setTimeout(()=>{this.resyncPending=!1,this.resync(t)},0))}startWatchdog(){let i=this.watcher.connection$.pipe((0,P.pairwise)(),(0,P.filter)(([n,s])=>n==="offline"&&s==="online"),(0,P.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,P.catchError)(n=>(this.log.error("watchdog_recovery_error",n),R.EMPTY)),(0,P.repeat)({delay:1e3})),r=this.watcher.finalizedBlock$.pipe((0,P.pairwise)(),(0,P.tap)(([n,s])=>{let a=Number(n.number),o=Number(s.number),l=o-a;l>=3&&(this.log.debug("watchdog_gap",{from:a,to:o,gap:l}),this.requestResync())}),(0,P.catchError)(n=>(this.log.error("watchdog_gap_error",n),R.EMPTY)),(0,P.repeat)({delay:1e3}));return(0,R.merge)(i,r).subscribe()}watchGuard(t){return e=>e.pipe((0,P.tap)({error:i=>{this.log.error(t,i),this.requestResync(!0)}}),(0,P.finalize)(()=>{this.log.debug(t,"unsub")}),(0,P.catchError)(()=>R.EMPTY))}};var me=class extends Q{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}getPoolWeights(t,e){let{start:i,end:r,initial_weight:n,final_weight:s}=t,a=ot.calculateLinearWeights(i?i.toString():"0",r?r.toString():"0",n.toString(),s.toString(),e.toString()),o=BigInt(a),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(qr.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e,i]=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,n=t.filter(({value:s})=>e&&this.isActivePool(s,r)).map(async({keyArgs:s,value:a})=>{let[o]=s,l=o.toString(),u=await this.getPoolDelta(l,a,r);return{address:l,type:"LBP",fee:a.fee,...u,...i}});return Promise.all(n)}async getPoolDelta(t,e,i){let{assets:r,repay_target:n,fee_collector:s}=e,[a,o]=this.getPoolWeights(e,i),[l,u]=r,[p,d,m,h,b]=await Promise.all([this.isRepayFeeApplied(l,n,s.toString()),this.balance.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u)]);return{repayFeeApply:p,tokens:[{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,weight:a,type:m?.asset_type.type},{id:u,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:h.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(t,e){let{start:i,end:r}=t;return i&&r?e>=i&&e<r:!1}async isRepayFeeApplied(t,e,i){if(e===0n)return!1;try{return(await this.balance.getBalance(i,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let i=this.store.pools.find(n=>n.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:i.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue("best").pipe((0,Nt.filter)(t=>t!==void 0),(0,Nt.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let i=[];for(let r of e){let n=this.poolsData.get(r.address);if(n){let{assets:s,repay_target:a,fee_collector:o}=n,[l]=s,[u,p]=this.getPoolWeights(n,t),[d,m]=r.tokens,h=[{...d,weight:u},{...m,weight:p}],b=await this.isRepayFeeApplied(l,a,o.toString());i.push({...r,tokens:h,repayFeeApply:b})}}return i})})}subscribeUpdates(){let t=new Nt.Subscription;return t.add(this.subscribeValidationData()),t}};var Ui={};F(Ui,{OmniMath:()=>B,OmniPool:()=>de,OmniPoolClient:()=>ge});var x=require("@galacticcouncil/math-omnipool"),Ot=vt(require("big.js")),B=class{static calculateSpotPrice(t,e,i,r){return(0,x.calculate_spot_price)(t,e,i,r)}static calculateLrnaSpotPrice(t,e){return(0,x.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,i,r,n,s,a,o,l,u){return(0,x.calculate_in_given_out)(t,e,i,r,n,s,a,o,l,u)}static calculateLrnaInGivenOut(t,e,i,r,n,s){return(0,x.calculate_lrna_in_given_out)(t,e,i,r,n,s)}static calculateOutGivenIn(t,e,i,r,n,s,a,o,l,u){return(0,x.calculate_out_given_in)(t,e,i,r,n,s,a,o,l,u)}static calculateOutGivenLrnaIn(t,e,i,r,n,s){return(0,x.calculate_out_given_lrna_in)(t,e,i,r,n,s)}static calculateShares(t,e,i,r){return(0,x.calculate_shares)(t,e,i,r)}static calculateLiquidityOut(t,e,i,r,n,s,a,o){return(0,x.calculate_liquidity_out)(t,e,i,r,n,s,a,o)}static calculateLiquidityLRNAOut(t,e,i,r,n,s,a,o){return(0,x.calculate_liquidity_lrna_out)(t,e,i,r,n,s,a,o)}static calculateCapDifference(t,e,i,r){let n=(0,Ot.default)(e),s=(0,Ot.default)(t),a=(0,Ot.default)(r),o=(0,Ot.default)(i),l=(0,Ot.default)(10).pow(18),u=o.div(l);if(n.div(a).lt(u)){let d=u.times(a).minus(n).times(s),m=n.times((0,Ot.default)(1).minus(u));return d.div(m).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,r){return(0,x.calculate_liquidity_hub_in)(t,e,i,r)}static isSellAllowed(t){return(0,x.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,x.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,x.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,x.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,i,r,n,s,a,o,l,u,p){return(0,x.recalculate_asset_fee)(t,e,i,r,n,s,a,o,l,u,p)}static recalculateProtocolFee(t,e,i,r,n,s,a,o,l,u,p){return(0,x.recalculate_protocol_fee)(t,e,i,r,n,s,a,o,l,u,p)}static verifyAssetCap(t,e,i,r){return(0,x.verify_asset_cap)(t,e,i,r)}};var Nr=require("@galacticcouncil/common");var{FeeUtils:gt}=_,de=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let i=new Map(this.tokens.map(s=>[s.id,s])),r=i.get(t),n=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:r.hubReserves,hubReservesOut:n.hubReserves,sharesIn:r.shares,sharesOut:n.shares,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:r.balance,balanceOut:n.balance,tradeableIn:r.tradeable,tradeableOut:n.tradeable,assetInEd:r.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,i),s=r===0n?0:W.calculateBuyFee(r,n),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return n>p&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:r,amountOut:e,feePct:s,errors:a}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),s=W.calculateSellFee(r,n),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return n>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:n,feePct:s,errors:a}}calculateInGivenOut(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,i);let r=B.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?gt.toRaw(i.assetFee).toString():"0",i?gt.toRaw(i.protocolFee).toString():"0",i?gt.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(r);return n<0n?0n:n}calculateLrnaInGivenOut(t,e,i){let r=B.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?gt.toRaw(i.assetFee).toString():"0",i?gt.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(r);return n<0n?0n:n}calculateOutGivenIn(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,i);let r=B.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?gt.toRaw(i.assetFee).toString():"0",i?gt.toRaw(i.protocolFee).toString():"0",i?gt.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(r);return n<0n?0n:n}calculateOutGivenLrnaIn(t,e,i){let r=B.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?gt.toRaw(i.assetFee).toString():"0",i?gt.toRaw(i.maxSlipFee).toString():"0"),n=BigInt(r);return n<0n?0n:n}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=B.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=B.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=B.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=B.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,i){let r=e-i;if(r===0)return t;let n=Nr.big.pow10(Math.abs(r));return r>0?t*n:t/n}};var Pt=require("polkadot-api"),Ur=require("@polkadot-api/utils"),O=require("rxjs"),Vr=require("@galacticcouncil/common");var{FeeUtils:k}=_,Hr=Pt.Binary.fromText("omnipool"),Gr=(0,Pt.Enum)("Short"),ge=class extends Q{queryBus=new le;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);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:"best"}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(Hr,t,Gr,{at:"best"}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,Ur.toHex)(e);return(0,Pt.AccountId)(Vr.HYDRATION_SS58_PREFIX).dec(i)}getOraclePair(t){return t===0?[0,1]:[1,t]}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Pt.CompatibilityLevel.BackwardsCompatible,e)}async isSlipFeeSupported(){return this.apiNext.query.Omnipool.SlipFee.isCompatible(Pt.CompatibilityLevel.Partial)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,r,n,s,a]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:"best"}),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.balance.getBalance(e,t),this.getPoolLimits()]),o=i.map(async({keyArgs:u,value:p})=>{let[d]=u,{hub_reserve:m,shares:h,tradable:b,cap:g,protocol_shares:f}=p,[y,v]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d),this.balance.getBalance(e,d)]);return{id:d,decimals:y?.decimals,existentialDeposit:y?.existential_deposit,balance:v.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:n?.decimals,existentialDeposit:n?.existential_deposit,balance:s.transferable,tradeable:r,type:n?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...a}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,r=0;await this.isSlipFeeSupported()&&(r=await this.maxSlipFee.get()??0);let s=await this.dynamicFeesConfig.get(e);if(s?.type==="Fixed"){let{asset_fee:S,protocol_fee:T}=s.value;return{assetFee:k.fromPermill(S),protocolFee:k.fromPermill(T),maxSlipFee:k.fromPermill(r)}}let a=this.getOraclePair(e),o=this.getOraclePair(i),[l,u,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(a),this.emaOracles.get(o)]),[d,m,h]=await this.getAssetFee(t,this.block,l,u,s?.value.asset_fee_params),[b,g,f]=i===1?[0,0,0]:await this.getProtocolFee(t,this.block,l,p,s?.value.protocol_fee_params),y=d+b,v=h+f;return{assetFee:k.fromPermill(m),protocolFee:k.fromPermill(g),maxSlipFee:k.fromPermill(r),min:k.fromPermill(y),max:k.fromPermill(v)}}async getAssetFee(t,e,i,r,n){let{assetOut:s,balanceOut:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=n||await this.api.constants.DynamicFees.AssetFeeParameters();if(!i||!r)return[o,o,l];let d=k.fromPermill(o),m=k.fromPermill(l),[h]=r,{asset_fee:b,timestamp:g}=i,f=Math.max(1,e-g),y=h.volume.b_in.toString(),v=h.volume.b_out.toString(),S=h.liquidity.b.toString();s===0&&(y=h.volume.a_in.toString(),v=h.volume.a_out.toString(),S=h.liquidity.a.toString());let T=k.fromPermill(b),A=B.recalculateAssetFee(y,v,S,"9",a.toString(),k.toRaw(T).toString(),f.toString(),k.toRaw(d).toString(),k.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(A)*1e6,l]}async getProtocolFee(t,e,i,r,n){let{assetIn:s,balanceIn:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=n||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!i||!r)return[o,o,l];let d=k.fromPermill(o),m=k.fromPermill(l),[h]=r,{protocol_fee:b,timestamp:g}=i,f=Math.max(1,e-g),y=h.volume.b_in.toString(),v=h.volume.b_out.toString(),S=h.liquidity.b.toString();s===0&&(y=h.volume.a_in.toString(),v=h.volume.a_out.toString(),S=h.liquidity.a.toString());let T=k.fromPermill(b),A=B.recalculateProtocolFee(y,v,S,"9",a.toString(),k.toRaw(T).toString(),f.toString(),k.toRaw(d).toString(),k.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(A)*1e6,l]}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(r=>r.id).map(r=>this.getOraclePair(r)).map(r=>this.api.query.EmaOracle.Oracles.watchValue(Hr,r,Gr,"best").pipe((0,O.filter)(n=>n!==void 0),(0,O.map)((n,s)=>({value:n,index:s})),(0,O.tap)(({index:n})=>{n>0&&this.log.trace("emaOracle.Oracles",r.join(":"))}),(0,O.map)(({value:n})=>({pair:r,value:n}))));return(0,O.merge)(...i).pipe((0,O.finalize)(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(r=>{let{pair:n,value:s}=r;this.emaOracles.set(s,n)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,O.distinctUntilChanged)((t,e)=>!e.deltas),(0,O.map)((t,e)=>({value:t,index:e})),(0,O.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),(0,O.finalize)(()=>this.dynamicFees.clear()),this.watchGuard("dynamicFees.AssetFee")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFees.set(e.value,i)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe((0,O.distinctUntilChanged)((t,e)=>!e.deltas),(0,O.map)((t,e)=>({value:t,index:e})),(0,O.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),(0,O.finalize)(()=>this.dynamicFeesConfig.clear()),this.watchGuard("dynamicFees.AssetFeeConfiguration")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[i]=e.args;this.dynamicFeesConfig.set(e.value,i)})})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,O.distinctUntilChanged)((t,e)=>!e.deltas),(0,O.map)((t,e)=>({value:t,index:e})),(0,O.tap)(({value:t,index:e})=>{e>0&&this.log.trace("omnipool.Assets",t.deltas?.upserted)}),this.watchGuard("omnipool.Assets")).subscribe(({value:{deltas:t}})=>{this.store.update(([e])=>{let i=t?.upserted.reduce((n,s)=>{let[a]=s.args;return n.set(a,s.value),n},new Map),r=e.tokens.map(n=>{let s=i?.get(n.id);return s?this.updateTokenState(n,s):n});return[{...e,tokens:r}]})})}subscribeUpdates(){let t=new O.Subscription;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:i,shares:r,tradable:n,cap:s,protocol_shares:a}=e;return{...t,cap:s,hubReserves:i,protocolShares:a,shares:r,tradeable:n}}};var Vi={};F(Vi,{StableMath:()=>z,StableSwap:()=>At,StableSwapClient:()=>be});var M=require("@galacticcouncil/math-stableswap"),z=class{static getPoolAddress(t){return(0,M.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let i=0;i<t;i++)e.push(["1","1"]);return e}static calculateAmplification(t,e,i,r,n){return(0,M.calculate_amplification)(t,e,i,r,n)}static calculateInGivenOut(t,e,i,r,n,s,a){return(0,M.calculate_in_given_out)(t,e,i,r,n,s,a)}static calculateAddOneAsset(t,e,i,r,n,s,a){return(0,M.calculate_add_one_asset)(t,e,i,r,n,s,a)}static calculateSharesForAmount(t,e,i,r,n,s,a){return(0,M.calculate_shares_for_amount)(t,e,i,r,n,s,a)}static calculateOutGivenIn(t,e,i,r,n,s,a){return(0,M.calculate_out_given_in)(t,e,i,r,n,s,a)}static calculateLiquidityOutOneAsset(t,e,i,r,n,s,a){return(0,M.calculate_liquidity_out_one_asset)(t,e,i,r,n,s,a)}static calculateShares(t,e,i,r,n,s){return(0,M.calculate_shares)(t,e,i,r,n,s)}static calculateSpotPriceWithFee(t,e,i,r,n,s,a,o){return(0,M.calculate_spot_price_with_fee)(t,e,i,r,n,s,a,o)}static recalculatePegs(t,e,i,r,n,s){let a=(0,M.recalculate_peg)(t,e,i,r,n,s);return JSON.parse(a)}};var he=require("@galacticcouncil/common");var{FeeUtils:Ht}=_,At=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new c(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(s=>[s.id,s])),r=i.get(t),n=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:n.balance,decimalsIn:r.decimals,decimalsOut:n.decimals,tradeableIn:this.id===t?15:r.tradeable,tradeableOut:this.id===e?15:n.tradeable,assetInEd:r.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,i),s=r===0n?0:W.calculateBuyFee(r,n),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:r,amountOut:e,feePct:s,errors:a}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,i),s=W.calculateSellFee(r,n),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:r,amountOut:n,feePct:s,errors:a}}calculateIn(t,e,i){let r=z.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?Ht.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(r);return n<0n?0n:n}calculateAddOneAsset(t,e,i){let r=z.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?Ht.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(r);return n<0n?0n:n}calculateSharesForAmount(t,e,i){let r=z.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?Ht.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(r);return n<0n?0n:n}calculateInGivenOut(t,e,i){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,i):t.assetIn==this.id?this.calculateSharesForAmount(t,e,i):this.calculateIn(t,e,i)}spotPriceInGivenOut(t){let e=z.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetOut===this.id,t.assetIn===this.id,t.decimalsOut,t.decimalsIn)}calculateOut(t,e,i){let r=z.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?Ht.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(r);return n<0n?0n:n}calculateWithdrawOneAsset(t,e,i){let r=z.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?Ht.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(r);return n<0n?0n:n}calculateShares(t,e,i){let r=z.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?Ht.toRaw(i.fee).toString():"0",this.getPegs()),n=BigInt(r);return n<0n?0n:n}calculateOutGivenIn(t,e,i){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,i):t.assetOut==this.id?this.calculateShares(t,e,i):this.calculateOut(t,e,i)}spotPriceOutGivenIn(t){let e=z.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetIn===this.id,t.assetOut===this.id,t.decimalsIn,t.decimalsOut)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:i,decimals:r})=>({asset_id:e,amount:i,decimals:r}));return JSON.stringify(t,Dt.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],Dt.jsonFormatter)}normalizeSpot(t,e,i,r,n){return e?t*he.big.pow10(he.RUNTIME_DECIMALS-n):i?t/he.big.pow10(n-r):t}};var ai=require("polkadot-api"),Wr=require("@polkadot-api/utils"),Yr=require("@noble/hashes/blake2b"),tt=require("rxjs"),oi=require("@galacticcouncil/common");var{FeeUtils:ss}=_,be=class extends Q{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=z.getPoolAddress(t),i=(0,Yr.blake2b)(e,{dkLen:32}),r=(0,Wr.toHex)(i);return(0,ai.AccountId)(oi.HYDRATION_SS58_PREFIX).dec(r)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:i,final_amplification:r,initial_block:n,final_block:s}=t,a=z.calculateAmplification(i.toString(),r.toString(),n.toString(),s.toString(),e.toString()),o=Number(a)<r;return{amplification:BigInt(a),isRampPeriod:o}}async getPoolTokens(t,e){let i=this.getPoolAddress(t),r=e.assets.map(async n=>{let[s,a,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,n),this.api.query.AssetRegistry.Assets.getValue(n),this.balance.getBalance(i,n)]);return{id:n,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:o.transferable,tradeable:s,type:a?.asset_type.type}});return Promise.all(r)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(ai.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e,i]=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:n,value:s})=>{let[a]=n,o=this.getPoolAddress(a),[l,u,p]=await Promise.all([this.getPoolTokens(a,s),this.api.query.Stableswap.PoolPegs.getValue(a,{at:"best"}),this.api.query.Tokens.TotalIssuance.getValue(a,{at:"best"})]),d=this.getPoolAmplification(s,e),m=u?this.getRecentPegs(u):this.getDefaultPegs(s);return l.push({id:a,tradeable:15,balance:p,decimals:oi.RUNTIME_DECIMALS}),this.poolsData.set(a,s),{address:o,id:a,type:"Stableswap",fee:ss.fromPermill(s.fee),tokens:l,totalIssuance:p,pegs:m,...i,...d}});return Promise.all(r)}async getPoolFees(t,e){return{fee:this.store.pools.find(r=>r.address===e).fee}}getDefaultPegs(t){return z.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([i,r])=>r.map(n=>n.toString()))}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,"best").pipe((0,tt.map)((r,n)=>({value:r,index:n})),(0,tt.tap)(({index:r,value:n})=>{r>0&&this.log.trace("tokens.TotalIssuance",i,n)}),(0,tt.map)(({value:r})=>({id:i,value:r}))));return(0,tt.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:r,value:n}=i;this.store.update(s=>{let a=[];return s.filter(o=>o.id===r).forEach(o=>{let l=o.tokens.map(u=>u.id===r?{...u,balance:n}:u);a.push({...o,tokens:l,totalIssuance:n})}),a})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,tt.distinctUntilChanged)((t,e)=>!e.deltas),(0,tt.map)((t,e)=>({value:t,index:e})),(0,tt.tap)(({value:t,index:e})=>{e>0&&this.log.trace("stableswap.PoolPegs",t.deltas?.upserted)}),this.watchGuard("stableswap.PoolPegs")).subscribe({error:t=>this.log.error("stableswap.PoolPegs",t),next:({value:{deltas:t}})=>{this.store.update(e=>{let i=[],r=new Map(e.map(n=>[n.id,n]));return t?.upserted.forEach(({args:n,value:s})=>{let[a]=n,o=r.get(a);if(o){let l=this.getRecentPegs(s);i.push({...o,pegs:l})}}),i})}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(e=>{let i=[];return e.filter(r=>r.isRampPeriod).forEach(r=>{let n=this.poolsData.get(r.id);if(n){let s=this.getPoolAmplification(n,t);i.push({...r,...s})}}),i})})}subscribeUpdates(){let t=new tt.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var Wi={};F(Wi,{XykMath:()=>St,XykPool:()=>ye,XykPoolClient:()=>fe});var D=require("@galacticcouncil/math-xyk"),St=class{static getSpotPrice(t,e,i){return(0,D.get_spot_price)(t,e,i)}static calculateInGivenOut(t,e,i){return(0,D.calculate_in_given_out)(t,e,i)}static calculateOutGivenIn(t,e,i){return(0,D.calculate_out_given_in)(t,e,i)}static calculatePoolTradeFee(t,e,i){return(0,D.calculate_pool_trade_fee)(t,e,i)}static calculateLiquidityIn(t,e,i){return(0,D.calculate_liquidity_in)(t,e,i)}static calculateSpotPrice(t,e){return(0,D.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,i,r){return(0,D.calculate_spot_price_with_fee)(t,e,i,r)}static calculateShares(t,e,i){return(0,D.calculate_shares)(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,r){return(0,D.calculate_liquidity_out_asset_a)(t,e,i,r)}static calculateLiquidityOutAssetB(t,e,i,r){return(0,D.calculate_liquidity_out_asset_b)(t,e,i,r)}};var $r=require("@galacticcouncil/common");var{FeeUtils:zr}=_,ye=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(s=>[s.id,s])),r=i.get(t),n=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:r.balance,balanceOut:n.balance,assetInEd:r.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),n=this.calculateTradeFee(r,i),s=zr.toPct(i.exchangeFee),a=r+n,o=[];(e<this.minTradingLimit||r<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:r,amountOut:e,feePct:s,errors:o}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),n=this.calculateTradeFee(r,i),s=zr.toPct(i.exchangeFee),a=r-n,o=[];(e<this.minTradingLimit||r<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:a,feePct:s,errors:o}}calculateInGivenOut(t,e){let i=St.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}calculateOutGivenIn(t,e){let i=St.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}spotPriceInGivenOut(t){let e=St.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=St.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=St.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(i)}normalizeSpot(t,e,i){let r=e-i;if(r===0)return t;let n=$r.big.pow10(Math.abs(r));return r>0?t*n:t/n}};var Xr=require("polkadot-api"),Kr=require("rxjs");var fe=class extends Q{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(Xr.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries(),this.getPoolLimits()]),i=t.map(async({keyArgs:r,value:n})=>{let[s]=r,[a,o]=n,[l,u,p,d]=await Promise.all([this.balance.getBalance(s,a),this.api.query.AssetRegistry.Assets.getValue(a),this.balance.getBalance(s,o),this.api.query.AssetRegistry.Assets.getValue(o)]);return{address:s,type:"XYK",tokens:[{id:a,decimals:u?.decimals||this.decimals.get(a),existentialDeposit:u?.existential_deposit,balance:l.transferable,type:u?.asset_type.type},{id:o,decimals:d?.decimals||this.decimals.get(o),existentialDeposit:d?.existential_deposit,balance:p.transferable,type:d?.asset_type.type}],...e}});return Promise.all(i)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return Kr.Subscription.EMPTY}};var Yi={};F(Yi,{AavePool:()=>Pe,AavePoolClient:()=>Se});var Gt=require("@galacticcouncil/common");var Pe=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(s=>[s.id,s])),r=i.get(t),n=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:n.balance,decimalsIn:r.decimals,decimalsOut:n.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),n=[];return e>t.balanceOut&&n.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:n}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),n=[];return r>t.balanceOut&&n.push("TradeNotAllowed"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:n}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return Gt.big.toBigInt(1,Gt.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return Gt.big.toBigInt(1,Gt.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var Qr=require("polkadot-api"),Jr=require("@polkadot-api/utils"),ht=require("rxjs"),Zr=require("viem"),li=require("@galacticcouncil/common");var jr=[{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:as}=li.erc20,os=["Supply","Withdraw","Repay","Borrow"],Se=class extends Q{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,r=new TextEncoder().encode(i.padEnd(32,"\0")),n=(0,Jr.toHex)(r);return(0,Qr.AccountId)(li.HYDRATION_SS58_PREFIX).dec(n)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:"best"})).map(async({reserve:i,atoken:r,liqudity_in:n,liqudity_out:s})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i),this.api.query.AssetRegistry.AssetLocations.getValue(i),this.api.query.AssetRegistry.Assets.getValue(r),this.api.query.AssetRegistry.AssetLocations.getValue(r)]);return{address:this.getPoolId(i,r),type:"Aave",tokens:[{id:i,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:n,location:o,type:a?.asset_type.type},{id:r,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:s,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:r,liqudity_out:n}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:"best"});return t.tokens.map(s=>{let a=s.id===e.id?r:n;return{...s,balance:a}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key.asHex()}throw new Error("Invalid aave reserve multilocation")}return as.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:i}=t;return{assetIn:e,assetOut:i,key:`${e}:${i}`}}parseEvmLog(t){let{topics:e,data:i}=t.log,r=e.map(s=>s.asHex()),n=i.asHex();try{let{eventName:s,args:a}=(0,Zr.decodeEventLog)({abi:jr,topics:r,data:n}),o=a.reserve.toLowerCase();return{eventName:s,reserve:o,key:`${s}:${o}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(i=>i.tokens).map(([i,r])=>r).map(i=>i.id);return this.api.event.Router.Executed.watch().pipe((0,ht.map)(({payload:i})=>this.parseRouterLog(i)),(0,ht.filter)(({assetIn:i,assetOut:r})=>e.includes(i)||e.includes(r)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:r,key:n})=>{this.log.trace("router.Executed",n),this.store.update(async s=>{let a=[];for(let o of s){let[l,u]=o.tokens;if(u.id===i||u.id===r){let d=await this.getPoolDelta(o);a.push({...o,tokens:d})}}return a})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,ht.map)(({payload:t})=>this.parseEvmLog(t)),(0,ht.filter)(t=>t!==void 0),(0,ht.filter)(({eventName:t})=>os.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async i=>{let r=[];for(let n of i){let[s]=n.tokens;if(this.getReserveH160Id(s).toLowerCase()===t){let o=await this.getPoolDelta(n);r.push({...n,tokens:o})}}return r})})}subscribeBalances(){return ht.Subscription.EMPTY}subscribeUpdates(){let t=new ht.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var $i={};F($i,{HsmMath:()=>st,HsmPool:()=>ve,HsmPoolClient:()=>Te});var $=require("@galacticcouncil/math-hsm"),st=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,$.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,$.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,$.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,$.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,$.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,$.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,$.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,$.calculate_max_price)(t,e)}};var X=require("@galacticcouncil/common");var{FeeUtils:Ut}=_,ve=class c extends At{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new c(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,i){let r=this.parsePair(t.assetOut,t.assetIn),n=super.calculateInGivenOut(r,e,{fee:this.fee}),s=this.calculateBuybackLimit(t);e>s&&i.push("MaxBuyBackExceeded");let a=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,n)>a&&i.push("MaxBuyPriceExceeded"),n>this.collateralBalance&&i.push("InsufficientCollateral"),i}validateTradeHollarOut(t,e,i){return this.collateralBalance+t>this.maxInHolding&&i.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&i.push("FacilitatorCapacityExceeded"),i}validateTradeConstraints(t,e,i){let r=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,r):this.validateTradeHollarOut(e,i,r)}validateAndBuy(t,e){let i=this.calculateInGivenOut(t,e),r=this.validateTradeConstraints(t,i,e);return{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:r}}validateAndSell(t,e){let i=this.calculateOutGivenIn(t,e),r=this.validateTradeConstraints(t,e,i);return{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:r}}calculateHollarInGivenCollateralOut(t,e){let i=super.calculateInGivenOut(t,e,{fee:this.fee}),r=st.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),Ut.toRaw(this.buyBackFee).toString());return BigInt(r)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=st.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),Ut.toRaw(this.purchaseFee).toString());return BigInt(i)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let i=super.calculateOutGivenIn(t,e,{fee:this.fee}),r=st.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),Ut.toRaw(this.buyBackFee).toString());return BigInt(r)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=st.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),Ut.toRaw(this.purchaseFee).toString());return BigInt(i)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),i=st.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=st.calculateBuybackLimit(e.toString(),Ut.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let r=st.calculateBuybackPriceWithFee(i.toString(),e.toString(),Ut.toRaw(this.buyBackFee).toString()),[n,s]=JSON.parse(r),a=X.big.pow10(t.decimalsIn+X.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(n)*a/BigInt(s)}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=st.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[r,n]=JSON.parse(i),s=X.big.pow10(X.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(r)*s/BigInt(n)}spotPriceInGivenOut(t){let e=X.big.toBigInt(1,t.decimalsOut),r=this.calculateInGivenOut(t,e)*X.big.pow10(X.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(r,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=X.big.toBigInt(1,t.decimalsIn),r=this.calculateOutGivenIn(t,e)*X.big.pow10(X.RUNTIME_DECIMALS-t.decimalsIn);return this.normalizeSpotPrice(r,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(r=>r.id!==this.hollarId),e=this.pegs[t],i=this.tokens[t].decimals;return this.isDefaultPeg(e)?[X.big.toBigInt(1,18).toString(),X.big.toBigInt(1,i).toString()]:e}isDefaultPeg(t){let[e,i]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&i==="1"}normalizeSpotPrice(t,e,i){let r=e-i;if(r===0)return t;let n=X.big.pow10(Math.abs(r));return r>0?t*n:t/n}};var ci=require("polkadot-api"),en=require("@polkadot-api/utils"),K=require("rxjs"),rn=require("viem"),ui=require("@galacticcouncil/common");var we=[{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 xe=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,r]=await this.client.readContract({abi:we,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-r}};var{FeeUtils:zi}=_,{H160:tn}=ui.h160,ls=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Te=class extends Q{ghoClient;stableClient;constructor(t,e,i){super(t,e),this.stableClient=i,this.ghoClient=new xe(e)}getPoolType(){return"HSM"}getPoolId(t){return this.getPoolAddress("hsm:"+t)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(t){if(t){let e=t.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key.asHex()}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),i=new TextEncoder().encode(e),r=(0,en.toHex)(i);return(0,ci.AccountId)(ui.HYDRATION_SS58_PREFIX).dec(r)}async isSupported(){let t=this.api.query.HSM.Collaterals,e=await this.api.compatibilityToken;return t.isCompatible(ci.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,r]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t),this.api.query.HSM.Collaterals.getEntries({at:"best"}),this.stableClient.getPools()]);if(i.length===0)return[];let n=this.getFacilitatorAddress(),s=tn.fromAny(n),a=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(a,s),l=i.map(async({keyArgs:p,value:d})=>{let[m]=p,{pool_id:h,max_buy_price_coefficient:b,max_in_holding:g,purchase_fee:f,buy_back_fee:y,buyback_rate:v}=d,S=r.find(T=>T.id===h);if(S){let T=this.getPoolId(h),A=await this.balance.getBalance(n,m);return{...S,address:T,type:"HSM",tokens:S.tokens.filter(N=>N.id!==h),hsmAddress:n,hsmMintCapacity:o,hollarId:t,hollarH160:a,collateralId:m,collateralBalance:A.transferable,maxBuyPriceCoefficient:b,maxInHolding:g,purchaseFee:zi.fromPermill(f),buyBackFee:zi.fromPermill(y),buyBackRate:zi.fromPerbill(v)}}});return(await Promise.all(l)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:i}=t.log,r=e.map(s=>s.asHex()),n=i.asHex();try{let{eventName:s,args:a}=(0,rn.decodeEventLog)({abi:we,topics:r,data:n}),o=a.facilitatorAddress.toLowerCase();return{eventName:s,facilitator:o,key:`${s}:${o}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,K.map)(({payload:t})=>this.parseEvmLog(t)),(0,K.filter)(t=>t!==void 0),(0,K.filter)(({eventName:t})=>ls.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async i=>{let r=[],[{hsmAddress:n,hollarH160:s}]=i,a=tn.fromAny(n);if(a.toLowerCase()===e){let l=await this.ghoClient.getFacilitatorCapacity(s,a);for(let u of i)r.push({...u,hsmMintCapacity:l})}return r})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(n=>{let{tokens:s,collateralId:a}=n;s.find(l=>l.id===a).type==="Erc20"?e.push(a):t.push(a)});let[{hsmAddress:i}]=this.store.pools,r=[];if(t.length>0){let n=this.balance.watchTokensBalance(i);r.push(n)}if(e.length>0){let n=this.balance.watchErc20Balance(i,e);r.push(n)}return r.length>0?(0,K.combineLatest)(r).pipe((0,K.map)(n=>n.flat()),(0,K.pairwise)(),(0,K.map)(([n,s])=>this.balance.getDeltas(n,s)),this.watchGuard("balances")).subscribe(n=>{this.store.update(s=>{let a=[],o=new Map(s.map(l=>[l.collateralId,l]));return n.forEach(({id:l,balance:u})=>{let p=o.get(l);p&&(this.log.trace("balances",{id:l,balance:u}),a.push({...p,collateralBalance:u.transferable}))}),a})}):K.Subscription.EMPTY}subscribeStableswapUpdates(){return this.stableClient.getSubscriber().pipe(this.watchGuard("stableswap.updates")).subscribe(t=>{let e=new Map(t.map(i=>[i.id,i]));this.store.update(i=>{let r=[];for(let n of i){let s=e.get(n.id);s&&r.push({...n,fee:s.fee,tokens:s.tokens.filter(a=>a.id!==n.id),totalIssuance:s.totalIssuance,pegs:s.pegs,amplification:s.amplification,isRampPeriod:s.isRampPeriod})}return r})})}subscribeBalances(){return K.Subscription.EMPTY}subscribeUpdates(){let t=new K.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var Vt=class{static get(t){switch(t.type){case"Aave":return Pe.fromPool(t);case"XYK":return ye.fromPool(t);case"Omnipool":return de.fromPool(t);case"LBP":return pe.fromPool(t);case"Stableswap":return At.fromPool(t);case"HSM":return ve.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var nn=require("@galacticcouncil/common"),lt=require("rxjs");var{logger:cs}=nn.log,Wt=class extends L{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=lt.Subscription.EMPTY;omniSub=lt.Subscription.EMPTY;stableSub=lt.Subscription.EMPTY;hsmSub=lt.Subscription.EMPTY;xykSub=lt.Subscription.EMPTY;lbpSub=lt.Subscription.EMPTY;isReady=!1;isDestroyed=new lt.Subject;constructor(t,e){super(t),this.evm=e,this.aave=new Se(t,e),this.omnipool=new ge(t,e),this.stableswap=new be(t,e),this.hsm=new Te(t,e,this.stableswap),this.xyk=new fe(t,e),this.lbp=new me(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe((0,lt.takeUntil)(this.isDestroyed)).subscribe(e=>{e.forEach(i=>{this.pools.set(i.address,i)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.active.has("Stableswap")||(cs.info("[PoolContextProvider] auto-activating stableswap"),this.withStableswap()),this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let i=this.clients.find(r=>r.getPoolType()===e.type);if(i)return i.getPoolFees(t,e.address);throw new ee(e.type)}};var er={};F(er,{DCA_TIME_RESERVE:()=>on,DEFAULT_BLOCK_TIME:()=>an,DEFAULT_MIN_BUDGET:()=>Qi,ORDER_MIN_BLOCK_PERIOD:()=>ln,Router:()=>Yt,TWAP_EXECUTION_INTERVAL:()=>Ae,TWAP_MAX_DURATION:()=>Zi,TWAP_MAX_PRICE_IMPACT:()=>Ji,TWAP_TX_MULTIPLIER:()=>jp,TradeOrderError:()=>ji,TradeOrderType:()=>mi,TradeRouteBuilder:()=>et,TradeRouter:()=>Tt,TradeScheduler:()=>zt,TradeType:()=>pi});var Ie=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,_e=class{isNotVisited(t,e){let i=!0;return e.forEach(r=>{(r[0]===t[0]||r[1]===t[1])&&(i=!1)}),i}findPaths(t,e,i){let r=[],n=new Ie,s=[];for(s.push([e,""]),n.enqueue(s);n.size()>0;){let a=n.dequeue();if(!a||a.length>us)continue;let o=a[a.length-1];(i===null||o[0]===i)&&r.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let p=[...a];p.push(u),n.enqueue(p)}})}return r}findShortestPaths(t,e,i){let r=[],n=new Ie,s=[];s.push([e,""]),n.enqueue(s);let a=1/0;for(;n.size()>0;){let o=n.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===i){o.length<a?(a=o.length,r.length=0,r.push(o)):o.length===a&&r.push(o);continue}let u=t.get(l[0]);for(let p of u??[])this.isNotVisited(p,o)&&n.enqueue([...o,p])}return r}buildAndPopulateGraph(t,e){let i=new Map;for(let r of t)i.set(parseInt(r),[]);for(let[r,n,s]of e)i.get(n)?.push([s,r]);return i}};function Ki(c){let t={};for(let e of c){let i=e.tokens.length;for(let r=0;r<i;r++){t[e.tokens[r].id]||(t[e.tokens[r].id]=[]);for(let n=0;n<i;n++){if(r==n)continue;let s=[e.address,e.tokens[r].id,e.tokens[n].id];t[e.tokens[r].id].push(s)}}}return t}var Oe=class{getProposals(t,e,i){let r=i.filter(g=>g.type==="XYK"),n=i.filter(g=>g.type!=="XYK"),s=new Set(n.map(g=>g.tokens).flat().map(g=>g.id)),a=s.has(t),o=s.has(e),l=new _e,u=g=>{let f=Ki(g),y=Object.keys(f),v=y.flatMap(S=>f[S]);return l.buildAndPopulateGraph(y,v)};if(!a&&!o){let g=r.filter(v=>v.tokens.find(S=>S.id===t)||v.tokens.find(S=>S.id===e)),f=u(g),y=l.findPaths(f,t,e);return this.parsePaths(y)}if(a&&o){let g=u(n),f=l.findPaths(g,t,e);return this.parsePaths(f)}let p=a?e:t,d=r.filter(g=>g.tokens.some(f=>f.id===p));if(d.length===0)return[];let m=[...n,...d],h=u(m),b=l.findPaths(h,t,e);return this.parsePaths(b)}parsePaths(t){let e=[];for(let i of t){let r=[];for(let n=0;n<i.length;n++){let s=i[n],a=i[n+1];if(a==null)break;r.push(this.toEdge(s,a))}e.push(r)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var Yt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new Oe,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,i){return`${t}->${e}::${i.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:i=[]}=this.filter,r=new Set(e),n=new Set(i);return t.filter(s=>n.has(s.type)?!1:r.size>0?r.has(s.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let i=await this.getPools();return this.validateInput(t,e,i),this.getPaths(t,e,i)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(r=>r!==t).map(r=>this.getRoutes(r,t)))).filter(r=>r.length>0).map(([r])=>r[0].assetIn).sort()}validateInput(t,e,i){if(i.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let r=this.getAssets(i);if(!r.has(t))throw new Error(t+" is not supported asset");if(!r.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(i)}getAssets(t){let e=t.map(i=>i.tokens.map(r=>r.id)).flat().sort((i,r)=>i>r?1:-1);return new Set(e)}getPaths(t,e,i){let r=this.toPoolsMap(i);return this.getProposals(t,e,i).filter(s=>this.validPath(s,r)).map(s=>this.toHops(s,r))}getProposals(t,e,i){let r=this.buildRouteKey(t,e,i);if(this.routeProposals.has(r))return this.routeProposals.get(r);let n=this.routeSuggester.getProposals(t,e,i);return this.routeProposals.set(r,n),n}validPath(t,e){return t.length>0&&t.map(i=>this.validEdge(i,e)).reduce((i,r)=>i&&r)}validEdge([t,e,i],r){return r.get(t)?.validatePair(e,i)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Vt.get(e)]))}toHops(t,e){return t.map(([i,r,n])=>{let s=e.get(i);return{poolAddress:i,poolId:s?.id,pool:s?.type,assetIn:r,assetOut:n}})}};var I=require("@galacticcouncil/common");var pi=(e=>(e.Buy="Buy",e.Sell="Sell",e))(pi||{}),mi=(i=>(i.Dca="Dca",i.TwapSell="TwapSell",i.TwapBuy="TwapBuy",i))(mi||{}),ji=(i=>(i.OrderTooSmall="OrderTooSmall",i.OrderTooBig="OrderTooBig",i.OrderImpactTooBig="OrderImpactTooBig",i))(ji||{});var{FeeUtils:sn}=_,Tt=class extends Yt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,i){let r=super.validateInput(t,e,i),n=super.getPaths(t,e,i);if(!n.length)throw new ie(t,e);return{paths:n,pools:i,poolsMap:r}}async withCtx(t,e,i){let r=await super.getPools(),n=this.buildCtxSync(t,e,r);return i(n)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((i,r)=>{let n=i[i.length-1].amountOut,s=r[r.length-1].amountOut;return n>s?-1:1});return e.find(i=>i.every(r=>r.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(i=>i.tradeFeeRange).length>0){let i=t.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,s)=>n+s),r=t.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,s)=>n+s);return[i,r]}}getPoolFeeRange(t,e){let i=t.min?sn.toPct(t.min):void 0,r=t.max?sn.toPct(t.max):void 0;if(i&&r)return[i,Math.max(r,e)]}async getBestSell(t,e,i){return this.getSell(t,e,i)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,i,r){return this.withCtx(t,e,async({paths:n,poolsMap:s})=>{let a;if(r)a=await this.toSellSwaps(i,r,s);else{let o=n.map(u=>this.toSellSwaps(i,u,s)),l=await Promise.all(o);a=this.findBestSellRoute(l)}return this.buildSell(s,a)})}async getSells(t,e,i){return this.withCtx(t,e,async({paths:r,poolsMap:n})=>{let s=r.map(o=>this.toSellSwaps(i,o,n));return(await Promise.all(s)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(n,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let i=e[0],r=e[e.length-1],n=this.isDirectTrade(e),s=this.getSellSpot(e),a=r.amountOut,o=n?r.calculatedOut:this.calculateDelta0Y(i.amountIn,e,t),l=o-a,u=this.getRouteFeeRange(e),p=n?r.tradeFeePct:W.calculateSellFee(o,a),d=q.mulSpot(i.amountIn,s,i.assetInDecimals,r.assetOutDecimals),m=W.calculateDiffToRef(o,d);return{type:"Sell",amountIn:i.amountIn,amountOut:r.amountOut,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Sell",amountIn:I.big.toDecimal(i.amountIn,i.assetInDecimals),amountOut:I.big.toDecimal(r.amountOut,r.assetOutDecimals),spotPrice:I.big.toDecimal(s,I.RUNTIME_DECIMALS),tradeFee:I.big.toDecimal(l,r.assetOutDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e.map(h=>h.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,i)=>e*i/10n**BigInt(I.RUNTIME_DECIMALS))}calculateDelta0Y(t,e,i){let r=[];for(let n=0;n<e.length;n++){let s=e[n],a=i.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;n>0?l=r[n-1]:l=t;let u=a.calculateOutGivenIn(o,l);r.push(u)}return r[r.length-1]}async calculateMostLiquidRoute(t,e,i){let{paths:r,pools:n,poolsMap:s}=i,l=n.filter(b=>b.tokens.some(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],u=q.getFraction(l,.1),p=await Promise.all(r.map(b=>this.toSellSwaps(u,b,s))),m=this.findBestSellRoute(p).map(b=>({poolAddress:b.poolAddress,poolId:b?.poolId,pool:b.pool,assetIn:b.assetIn,assetOut:b.assetOut})),h=this.buildRouteKey(t,e,n);return this.mlr.set(h,m),m}async toSellSwaps(t,e,i){let r=[];for(let n=0;n<e.length;n++){let s=e[n],a=i.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;n>0?l=r[n-1].amountOut:l=typeof t=="string"?I.big.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(o,a),{amountOut:p,calculatedOut:d,feePct:m,errors:h}=a.validateAndSell(o,l,u),b=this.getPoolFeeRange(u,m),g=a.spotPriceOutGivenIn(o),f=q.mulSpot(l,g,o.decimalsIn,o.decimalsOut),y=W.calculateDiffToRef(d,f);r.push({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===s.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===s.assetIn},toHuman(){return{...s,amountIn:I.big.toDecimal(l,o.decimalsIn),amountOut:I.big.toDecimal(p,o.decimalsOut),calculatedOut:I.big.toDecimal(d,o.decimalsOut),spotPrice:I.big.toDecimal(g,I.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h}}})}return r}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async i=>{let r=this.buildRouteKey(t,e,i.pools),n=this.mlr.get(r);return n||this.calculateMostLiquidRoute(t,e,i)})}async getSpotPrice(t,e){return this.withCtx(t,e,async i=>{let{pools:r,poolsMap:n}=i,s=this.buildRouteKey(t,e,r),a=this.mlr.get(s);a||(a=await this.calculateMostLiquidRoute(t,e,i));let o=await this.toSellSwaps("1",a,n);return{amount:this.getSellSpot(o),decimals:I.RUNTIME_DECIMALS}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((i,r)=>{let n=i[0].amountIn,s=r[0].amountIn;return n>s?1:-1});return e.find(i=>i.every(r=>r.errors.length==0))||e[0]}async getBestBuy(t,e,i){return this.getBuy(t,e,i)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,i,r){return this.withCtx(t,e,async({paths:n,poolsMap:s})=>{let a;if(r)a=await this.toBuySwaps(i,r,s);else{let o=n.map(u=>this.toBuySwaps(i,u,s)),l=await Promise.all(o);a=this.findBestBuyRoute(l)}return this.buildBuy(s,a)})}async getBuys(t,e,i){return this.withCtx(t,e,async({paths:r,poolsMap:n})=>{let s=r.map(o=>this.toBuySwaps(i,o,n));return(await Promise.all(s)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(n,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let i=e[e.length-1],r=e[0],n=this.isDirectTrade(e),s=this.getBuySpot(e),a=r.amountIn,o=n?r.calculatedIn:this.calculateDelta0X(i.amountOut,e,t),l=a-o,u=this.getRouteFeeRange(e),p=n?r.tradeFeePct:W.calculateBuyFee(o,a),d=q.mulSpot(i.amountOut,s,i.assetOutDecimals,r.assetInDecimals),m;return o===0n?m=-100:m=W.calculateDiffToRef(d,o),{type:"Buy",amountOut:i.amountOut,amountIn:r.amountIn,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Buy",amountOut:I.big.toDecimal(i.amountOut,i.assetOutDecimals),amountIn:I.big.toDecimal(r.amountIn,r.assetInDecimals),spotPrice:I.big.toDecimal(s,I.RUNTIME_DECIMALS),tradeFee:I.big.toDecimal(l,r.assetInDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e.map(h=>h.toHuman())}}}}calculateDelta0X(t,e,i){let r=[];for(let n=e.length-1;n>=0;n--){let s=e[n],a=i.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;n==e.length-1?l=t:l=r[0];let u=a.calculateInGivenOut(o,l);r.unshift(u)}return r[0]}async toBuySwaps(t,e,i){let r=[];for(let n=e.length-1;n>=0;n--){let s=e[n],a=i.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;n==e.length-1?l=typeof t=="string"?I.big.toBigInt(t,o.decimalsOut):t:l=r[0].amountIn;let u=await this.ctx.getPoolFees(o,a),{amountIn:p,calculatedIn:d,feePct:m,errors:h}=a.validateAndBuy(o,l,u),b=this.getPoolFeeRange(u,m),g=a.spotPriceInGivenOut(o),f=q.mulSpot(l,g,o.decimalsOut,o.decimalsIn),y;d===0n?y=-100:y=W.calculateDiffToRef(f,d),r.unshift({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===s.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===s.assetIn},toHuman(){return{...s,amountOut:I.big.toDecimal(l,o.decimalsOut),amountIn:I.big.toDecimal(p,o.decimalsIn),calculatedIn:I.big.toDecimal(d,o.decimalsIn),spotPrice:I.big.toDecimal(g,I.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h}}})}return r}};var U=require("@galacticcouncil/common");var an=6e3,Qi=1000000000000000n,Ae=6,Ji=-5,Zi=216e5,jp=3,on=.1,ln=6;var tr=require("polkadot-api");var et=class{static build(t){return t.map(({assetIn:e,assetOut:i,pool:r,poolId:n})=>r==="Stableswap"?{pool:(0,tr.Enum)("Stableswap",n),asset_in:e,asset_out:i}:{pool:(0,tr.Enum)(r),asset_in:e,asset_out:i})}};var zt=class{schedulerOptions;router;constructor(t,e={}){this.router=new Tt(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Qi})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,i,r,n){let s=await this.router.getBestSell(t,e,i),{amountIn:a,swaps:o,priceImpactPct:l}=s,u=o[0],p=o[o.length-1],{assetInDecimals:d}=u,{assetOutDecimals:m}=p,h=Math.abs(l),b=await this.getMinimumOrderBudget(t,d),g=this.getOptimalTradeCount(h),f=this.getMaximumTradeCount(a,b,r),y=n||Math.min(g,f),v=Math.round(r/y),S=a/BigInt(y),T=await this.router.getBestSell(t,e,S),A=a<b,N=[];A&&N.push("OrderTooSmall");let V=T.amountOut*BigInt(y),ct=this.toBlockPeriod(v),bt=T.tradeFee*BigInt(y),J=et.build(o),rt={assetIn:t,assetOut:e,errors:N,maxTradeCount:f,tradeCount:y,tradeFee:bt,tradeImpactPct:T.priceImpactPct,tradePeriod:ct,tradeRoute:J,type:"Dca"};return{...rt,amountIn:a,amountOut:V,tradeAmountIn:T.amountIn,tradeAmountOut:T.amountOut,toHuman(){return{...rt,amountIn:U.big.toDecimal(a,d),amountOut:U.big.toDecimal(V,m),tradeAmountIn:U.big.toDecimal(T.amountIn,d),tradeAmountOut:U.big.toDecimal(T.amountOut,m)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let i=await this.router.getSpotPrice(0,t);if(i)return q.mulSpot(this.minOrderBudget,i.amount,12,e);let r=await this.router.getSpotPrice(t,0);if(r)return q.divSpot(this.minOrderBudget,r.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,i){let r=e*2n/10n;if(r===0n)return 0;let n=Number(t/r),s=Math.floor(i/this.blockTime),a=Math.max(0,Math.floor(s*(1-.1)));return Math.min(n,a)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,i,r){let n=await this.router.getBestSell(t,e,i),{swaps:s}=n,a=s[0],o=s[s.length-1],{assetInDecimals:l}=a,{assetOutDecimals:u}=o,p=await this.getMinimumOrderBudget(t,l),d=n.amountIn<p,m=[];d&&m.push("OrderTooSmall");let h=this.toBlockPeriod(r),b=et.build(s),g={assetIn:t,assetOut:e,errors:m,maxTradeCount:0,tradeCount:0,tradeFee:n.tradeFee,tradeImpactPct:n.priceImpactPct,tradePeriod:h,tradeRoute:b,type:"Dca"};return{...g,amountIn:0n,amountOut:0n,tradeAmountIn:n.amountIn,tradeAmountOut:n.amountOut,toHuman(){return{...g,amountIn:"0",amountOut:"0",tradeAmountIn:U.big.toDecimal(n.amountIn,l),tradeAmountOut:U.big.toDecimal(n.amountOut,u)}}}}async getTwapSellOrder(t,e,i){let r=await this.router.getBestSell(t,e,i),{amountIn:n,swaps:s,priceImpactPct:a}=r,o=s[0],l=s[s.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),h=n/BigInt(m),[b,g]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestSell(o.assetIn,l.assetOut,h)]),f=m===1,y=n<b,v=g.priceImpactPct<-5,S=[];y||f?S.push("OrderTooSmall"):v&&S.push("OrderImpactTooBig");let T=g.amountOut*BigInt(m),A=g.tradeFee*BigInt(m),N=et.build(s),V={assetIn:t,assetOut:e,errors:S,tradeCount:m,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:N,type:"TwapSell"};return{...V,amountIn:n,amountOut:T,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:A,toHuman(){return{...V,amountIn:U.big.toDecimal(n,u),amountOut:U.big.toDecimal(T,p),tradeAmountIn:U.big.toDecimal(g.amountIn,u),tradeAmountOut:U.big.toDecimal(g.amountOut,p),tradeFee:U.big.toDecimal(A,p)}}}}async getTwapBuyOrder(t,e,i){let r=await this.router.getBestBuy(t,e,i),{amountOut:n,swaps:s,priceImpactPct:a}=r,o=s[0],l=s[s.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),h=n/BigInt(m),[b,g]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestBuy(o.assetIn,l.assetOut,h)]),f=g.amountIn*BigInt(m),y=m===1,v=f<b,S=g.priceImpactPct<-5,T=[];v||y?T.push("OrderTooSmall"):S&&T.push("OrderImpactTooBig");let A=g.tradeFee*BigInt(m),N=et.build(s),V={assetIn:t,assetOut:e,errors:T,tradeCount:m,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:N,type:"TwapBuy"};return{...V,amountIn:f,amountOut:n,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:A,toHuman(){return{...V,amountIn:U.big.toDecimal(f,u),amountOut:U.big.toDecimal(n,p),tradeAmountIn:U.big.toDecimal(g.amountIn,u),tradeAmountOut:U.big.toDecimal(g.amountOut,p),tradeFee:U.big.toDecimal(A,u)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let r=216e5/(this.blockTime*6);return Math.round(r)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,i=Math.round(e);return Math.max(i,6)}};var rr={};F(rr,{BIG_10:()=>gn,BIG_BILL:()=>ir,StakingApi:()=>Be,StakingClient:()=>Fe});var j=require("@galacticcouncil/math-staking"),it=vt(require("big.js"));var di={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},cn=c=>Object.keys(di).includes(c);var un=require("polkadot-api"),pn=require("@polkadot-api/utils"),mn=require("@galacticcouncil/common");function dn(c){let t=("modl"+c).padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,pn.toHex)(e);return(0,un.AccountId)(mn.HYDRATION_SS58_PREFIX).dec(i)}var gi="20000000000000000",hi="2000",gn=(0,it.default)(10),ir=(0,it.default)(gn.pow(12)),Be=class{client;balance;constructor(t,e){this.client=t,this.balance=e}async getPotBalance(){let t=await this.client.getPalletId(),e=dn(t);return await this.balance.getBalance(e,0)}async getStakingPosition(t){let[e,i]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let r=e.created_at,n=await i.reduce(async(s,[a,o])=>{let l=await s,u=a,p=o.amount,d=o.conviction.type.toLowerCase(),m=await this.client.getReferendumInfo(u);return m&&(m.type==="Approved"||m.type==="Rejected")&&cn(d)&&l.push({id:u,amount:p,conviction:d}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:r,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:n}}async getStake(t){let e=await this.client.getNFTCollectionId(),[i,r]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),n=r.find(s=>s)?.itemId;return{totalStake:i?.total_stake,accumulatedRewardPerStake:i?.accumulated_reward_per_stake,potReservedBalance:i?.pot_reserved_balance,positionId:n,stakePosition:n?await this.getStakingPosition(n):void 0}}getCurrentActionPoints(t,e,i,r){let n=(0,it.default)(0),s=(0,it.default)(0),a=di.locked6x,o=(0,it.default)(i.toString()).mul(a),l=100,u=[];t.forEach(m=>{let h=di[m.conviction],b=r.includes(m.id.toString());b&&u.push(m.id.toString());let g=(0,it.default)(m.amount.toString()).mul(l).div(o);n=n.plus(Math.floor(g.mul(h).toNumber())),s=s.plus(Math.floor(g.mul(b?a:h).toNumber()))});let p=Math.floor((0,it.default)(i.toString()).mul(a).mul(l).div(o).toNumber());r.forEach(m=>{u.includes(m)||(s=s.plus(p))});let d={democracyVote:1};return n=n.mul(d.democracyVote),n=n.plus(e.toString()||"0"),s=s.mul(d.democracyVote),s=s.plus(e.toString()||"0"),{currentActionPoints:n.toString(),maxActionPoints:s.toString()}}async getRewards(t,e,i){let r=await this.getStake(t),{potReservedBalance:n,accumulatedRewardPerStake:s,totalStake:a,stakePosition:o}=r;if(!o)return;let[l,u,p,d,m,h,b]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),g=(0,it.default)(l.transferable.toString()).minus(n.toString()),f=g.gt(0)&&a>0?(0,j.calculate_accumulated_rps)(s.toString(),g.toString(),a.toString()):s.toString(),y=(0,j.calculate_period_number)(u.toString(),i,b),v=(0,j.calculate_period_number)(u.toString(),o.createdAt.toString(),b),S=(0,j.calculate_rewards)(f,o.rewardPerStake.toString(),o.stake.toString()),T=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),A=(0,j.calculate_points)(v,y,d.toString(),m.toString(),T.currentActionPoints,h.toString(),o.accumulatedSlashPoints.toString()),N=(0,j.sigmoid)(A,gi,hi),V=(()=>{if(!e.length)return;let Kt=(0,j.calculate_points)(v,y,d.toString(),m.toString(),T.maxActionPoints.toString(),h.toString(),o.accumulatedSlashPoints.toString());return(0,j.sigmoid)(Kt,gi,hi)})(),ct=(0,it.default)(S).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if((0,it.default)(y).minus(v).lte(p.toString()))return{rewards:"0",payablePercentage:N,extraPayablePercentage:V,constants:{a:gi,b:hi}};let bt=(0,j.calculate_percentage_amount)(ct.toString(),N),J=(0,it.default)(o.accumulatedLockedRewards.toString()),rt=J.gt(bt)?J:(0,it.default)(bt);return{rewards:rt.div(ir).toString(),maxRewards:ct.div(ir).toString(),allocatedRewardsPercentage:rt.div(ct).mul(100).toNumber(),points:A,payablePercentage:N,extraPayablePercentage:V,constants:{a:gi,b:hi}}}};var Fe=class extends L{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:s})=>{let[a,o,l]=s;return{address:a,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var sr={};F(sr,{TxBuilderFactory:()=>Xt});var nr=require("polkadot-api");function hn(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var $t=class extends L{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new ut(t),this.aaveUtils=new It(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:i=>this.dryRun(i,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:xi})}async dryRun(t,e){let i=(0,nr.Enum)("Signed",t),r=(0,nr.Enum)("system",i),s=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(r,e.decodedCall),a=s.success&&!s.value.execution_result.success?s.value.execution_result.value.error:null;if(a){let o=hn(a.value);throw new Error("Dry run execution error!",{cause:o})}return s}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var bi=class extends $t{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:i}=this.trade;if(i==="Buy")return this.buildBuyTx();let{assetIn:r}=e[0],n=await this.balance.getBalance(this.beneficiary,r);return t>=n.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,r=i[0],n=i[i.length-1],s=q.getFraction(t,this.slippagePct),a=r.assetIn,o=n.assetOut,l=t+s,u;return this.isDirectOmnipoolTrade(i)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:et.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,r=i[0],n=i[i.length-1],s=q.getFraction(e,this.slippagePct),a=r.assetIn,o=n.assetOut,l=e-s,u;return this.isDirectOmnipoolTrade(i)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:et.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,i=e[0],r=e[e.length-1],n=q.getFraction(t,this.slippagePct),s=i.assetIn,a=r.assetOut,o=t-n,l=this.api.tx.Router.sell_all({asset_in:s,asset_out:a,min_amount_out:o,route:et.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var yi=require("polkadot-api");var fi=class extends $t{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradePeriod:n,tradeRoute:s}=this.order,a=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,yi.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:r,min_amount_out:0n,route:s})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(a=await this.dispatchWithExtraGas(a)),this.wrapTx("DcaSchedule",a)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradeAmountOut:n,tradePeriod:s,tradeRoute:a}=this.order,o=q.getFraction(n,this.slippagePct),l=n-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,yi.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:r,min_amount_out:l,route:a})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("DcaSchedule.twapSell",u)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradeAmountOut:n,tradePeriod:s,tradeRoute:a}=this.order,o=q.getFraction(r,this.slippagePct),l=r+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,yi.Enum)("Buy",{asset_in:e,asset_out:i,amount_out:n,max_amount_in:l,route:a})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("DcaSchedule.twapBuy",u)}};var Xt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new bi(this.client,this.evmClient).setTrade(t)}order(t){return new fi(this.client,this.evmClient).setOrder(t)}};async function ps(c){let t=new Mt(c),e=new se(c),[i,r]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),n=new Wt(c,e).withAave().withOmnipool().withStableswap().withXyk(),s=new ut(c),a=new Fe(c),o=new ue(c),l=new It(e),u=new Tt(n),p=new zt(n,{blockTime:i,minBudgetInNative:r}),d=new Be(a,s),m=new ce(o,s,{blockTime:i});return{api:{aave:l,router:u,scheduler:p,staking:d,farm:m},client:{asset:new Rt(c),balance:s,evm:e},ctx:{pool:n},tx:new Xt(c,e),destroy:()=>{n.destroy()}}}0&&(module.exports={QueryBus,aave,api,async,calc,client,const:null,createSdkContext,error,evm,farm,fmt,json,math,pool,sor,staking,tx});
|
|
1
|
+
"use strict";var vi=Object.create;var Le=Object.defineProperty;var wi=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var Ti=Object.getPrototypeOf,Ii=Object.prototype.hasOwnProperty;var pn=(c,t)=>()=>(c&&(t=c(c=0)),t);var R=(c,t)=>{for(var e in t)Le(c,e,{get:t[e],enumerable:!0})},De=(c,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of xi(t))!Ii.call(c,n)&&n!==e&&Le(c,n,{get:()=>t[n],enumerable:!(r=wi(t,n))||r.enumerable});return c},Bt=(c,t,e)=>(De(c,t,"default"),e&&De(e,t,"default")),vt=(c,t,e)=>(e=c!=null?vi(Ti(c)):{},De(t||!c||!c.__esModule?Le(e,"default",{value:c,enumerable:!0}):e,c)),_i=c=>De(Le({},"__esModule",{value:!0}),c);var Qt={};var yn=pn(()=>{Bt(Qt,require("@polkadot-api/smoldot"))});var Jt={};var fn=pn(()=>{Bt(Jt,require("@polkadot-api/known-chains/polkadot"))});var ds={};R(ds,{QueryBus:()=>ce,aave:()=>Or,api:()=>wr,async:()=>oe,calc:()=>q,client:()=>Rr,const:()=>Br,createSdkContext:()=>ms,error:()=>Er,evm:()=>kr,farm:()=>Vr,fmt:()=>_,json:()=>Dt,math:()=>W,pool:()=>jr,sor:()=>nn,staking:()=>an,tx:()=>ln});module.exports=_i(ds);var wr={};R(wr,{Papi:()=>L,Watcher:()=>jt,getSm:()=>Bi,getWs:()=>Ai});var Ne=require("@galacticcouncil/descriptors");var dn=require("@galacticcouncil/common"),qe=require("rxjs");var yt=require("rxjs"),H=require("rxjs/operators");function mn(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let r=()=>(0,yt.defer)(()=>(0,yt.from)(c._request("system_health",[]))).pipe((0,H.timeout)({first:e}),(0,H.map)(()=>"online"),(0,H.catchError)(()=>(0,yt.of)("offline")));return(0,yt.of)({state:"offline",delayMs:0}).pipe((0,H.expand)(i=>(0,yt.timer)(i.delayMs).pipe((0,H.switchMap)(r),(0,H.map)(s=>({state:s,delayMs:t})))),(0,H.skip)(1),(0,H.map)(i=>i.state),(0,H.distinctUntilChanged)(),(0,H.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Oi}=dn.log,jt=class c{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)",mn(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe((0,qe.tap)({error:r=>Oi.error(t,r)}),(0,qe.shareReplay)({bufferSize:1,refCount:!0}))}};var L=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(Ne.hydration),this.apiNext=this.client.getTypedApi(Ne.hydrationNext),this.watcher=jt.getInstance(this.client)}};var gn=require("polkadot-api/ws-provider"),hn=require("polkadot-api/logs-provider"),bn=require("@polkadot-api/legacy-provider"),Ai=(c,t={})=>{let e=typeof c=="string"?c.split(","):c,r=(0,gn.getWsProvider)(e,{innerEnhancer:(0,bn.withLegacy)(),...t});return(0,hn.withLogsRecorder)(n=>console.log(n),r),r};var Pn=require("polkadot-api/sm-provider");async function Bi(c){let{start:t}=await Promise.resolve().then(()=>(yn(),Qt)),{chainSpec:e}=await Promise.resolve().then(()=>(fn(),Jt)),r=t(),n=await r.addChain({chainSpec:e}),i=await r.addChain({chainSpec:c,potentialRelayChains:[n]});return(0,Pn.getSmProvider)(i)}var Or={};R(Or,{AAVE_GAS_LIMIT:()=>It,AAVE_LENDING_POOL_ADDRESS:()=>Ve,AAVE_POOL_ABI:()=>xr,AAVE_POOL_DATA_PROVIDER:()=>Ge,AAVE_POOL_DATA_PROVIDER_ABI:()=>He,AAVE_POOL_PROXY:()=>Tr,AAVE_ROUNDING_THRESHOLD:()=>Ls,AAVE_UINT_256_MAX:()=>Ri,AaveClient:()=>Zt,AaveUtils:()=>te,WEIGHT_PER_GAS:()=>Ir});var xr=[{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 He=[{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 Tr="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ge="0x112b087b60C1a166130d59266363C45F8aa99db0",Ve="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",It=1000000n,Ir=25000n,Ls=5,Ri=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Zt=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:He,address:Ge,args:[Ve],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:He,address:Ge,args:[Ve,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:xr,address:Tr,args:[t],functionName:"getUserAccountData"})}};var G=vt(require("big.js")),it=require("@galacticcouncil/common");var{ERC20:Rt}=it.erc20,{H160:_r}=it.h160,Fi=1.01,Ei=31536000n,Sn=4,Ue=-1,We=10n**27n,te=class{client;constructor(t){this.client=new Zt(t)}async getSummary(t){let e=_r.fromAny(t),[r,n,i,s]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[a]=r,[o,l]=n,[u,p,d,m,h,b]=i,g=it.big.toDecimal(b,18),f=[];for(let y of o){let v=y.underlyingAsset.toLowerCase(),S=a.find(({underlyingAsset:vr})=>vr.toLowerCase()===v);if(!S)throw new Error("Missing pool reserve for "+v);let T=y.scaledATokenBalance,A=S.liquidityIndex,N=S.liquidityRate,U=S.availableLiquidity,ct=S.priceInMarketReferenceCurrency,bt=s+6,J=this.calculateLinearInterest(N,S.lastUpdateTimestamp,bt),nt=A*J/We,Kt=T*nt/We,Ce=Number(l!==0&&l===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,ke=S.usageAsCollateralEnabled&&y.usageAsCollateralEnabledOnUser&&y.scaledATokenBalance>0n,Me=Rt.toAssetId(v);f.push({aTokenBalance:Kt,availableLiquidity:U,decimals:Number(S.decimals),isCollateral:ke,priceInRef:ct,reserveId:Me,reserveAsset:v,reserveLiquidationThreshold:Ce})}return{healthFactor:Number(g),currentLiquidationThreshold:Number(it.big.toDecimal(m,Sn)),totalCollateral:u,totalDebt:p,reserves:f}}async hasBorrowPositions(t){let e=_r.fromAny(t),r=await this.client.getUserAccountData(e),[n,i]=r;return i>0n}async getHealthFactor(t){let e=_r.fromAny(t),r=await this.client.getUserAccountData(e),[n,i,s,a,o,l]=r;return this.calculateHealthFactorFromBalances(i,n,a)}async getHealthFactorAfterWithdraw(t,e,r){let{totalCollateral:n,totalDebt:i,reserves:s,currentLiquidationThreshold:a}=await this.getSummary(t);if(i===0n)return Ue;let o=Rt.fromAssetId(e),l=s.find(v=>v.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:u,isCollateral:p,priceInRef:d,reserveLiquidationThreshold:m}=l,h=it.big.toBigInt(r,u),b=p?h*d/10n**BigInt(u):0n,g=n-b;if(g<=0n)return 0;let f=(0,G.default)(n.toString()).mul(a).minus((0,G.default)(b.toString()).mul(m)).div(g.toString()),y=(0,G.default)(g.toString()).mul(f).div(i.toString()).toFixed(6,G.default.roundDown);return Number(y)}async getHealthFactorAfterSupply(t,e,r){let{totalCollateral:n,totalDebt:i,reserves:s,currentLiquidationThreshold:a}=await this.getSummary(t);if(i===0n)return Ue;let o=Rt.fromAssetId(e),l=s.find(y=>y.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:u,priceInRef:p,reserveLiquidationThreshold:d}=l,h=it.big.toBigInt(r,u)*p/10n**BigInt(u),b=n+h;if(b<=0n)return 0;let g=(0,G.default)(n.toString()).mul(a).plus((0,G.default)(h.toString()).mul(d)).div(b.toString()),f=(0,G.default)(b.toString()).mul(g).div(i.toString()).toFixed(6,G.default.roundDown);return Number(f)}async getHealthFactorAfterSwap(t,e,r,n,i){let{totalDebt:s,reserves:a,healthFactor:o}=await this.getSummary(t);if(s===0n)return Ue;let l=Rt.fromAssetId(r),u=Rt.fromAssetId(i),p=a.find(A=>A.reserveAsset===l),d=a.find(A=>A.reserveAsset===u);if(!p)throw new Error(`Missing reserve ctx for ${l}`);if(!d)throw new Error(`Missing reserve ctx for ${d}`);let m=it.big.toBigInt(e,p.decimals),h=it.big.toBigInt(n,d.decimals),b=m*p.priceInRef/10n**BigInt(p.decimals),g=h*d.priceInRef/10n**BigInt(d.decimals),f=p.isCollateral?(0,G.default)(b.toString()).mul(p.reserveLiquidationThreshold):(0,G.default)(0),S=(0,G.default)(g.toString()).mul(d.reserveLiquidationThreshold).minus(f).div(s.toString()),T=(0,G.default)(o).plus(S).toFixed(6,G.default.roundDown);return Number(T)}async getMaxWithdraw(t,e){let{totalDebt:r,reserves:n,healthFactor:i}=await this.getSummary(t),s=Rt.fromAssetId(e),a=n.find(o=>o.reserveAsset===s);if(!a)throw new Error("Missing reserve ctx for "+s);return this.calculateWithdrawMax(a,r,i)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:r,healthFactor:n}=await this.getSummary(t),i={};for(let s of r){let a=this.calculateWithdrawMax(s,e,n);s.reserveId&&(i[s.reserveId]=a)}return i}calculateWithdrawMax(t,e,r){let{aTokenBalance:n,availableLiquidity:i,decimals:s,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=t,u=n;if(l&&e>0n){let d=r-Fi;if(d>0){let m=(0,G.default)(d).mul(e.toString()).div(o).toFixed(0,G.default.roundDown),h=(0,G.default)(m).div(a.toString()).mul(10**s).toFixed(0,G.default.roundDown);u=n<BigInt(h)?n:BigInt(h)}else u=0n}return{amount:u<i?u:i,decimals:s}}calculateLinearInterest(t,e,r){let n=r-e;if(n<=0)return We;let i=t*BigInt(n)/Ei;return We+i}calculateHealthFactorFromBalances(t,e,r){if(t===0n)return Ue;let n=e*r/t,i=it.big.toDecimal(n,Sn);return Number(i)}};var Rr={};R(Rr,{AssetClient:()=>Ft,BalanceClient:()=>ut,ChainParams:()=>Mt});var Ft=class extends L{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:r,value:n})=>{let[i]=r;return[i,n]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:r,value:n})=>{let[i]=r;return[i,n]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:r})=>{let{asset_type:n}=r;return this.SUPPORTED_TYPES.includes(n.type)}).map(({keyArgs:r,value:n})=>{let[i]=r;return[i,n]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:r,value:n})=>{let[i]=r;return[i,n]}))}async mapToken(t,e,r,n){let{name:i,asset_type:s,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=r.get(t)??{};return{id:t,name:i?.asText(),symbol:l,decimals:u,icon:l,type:s.type,isSufficient:a,location:n,existentialDeposit:o}}async mapBond(t,e,r,n){let[i,s]=n,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:p}=await this.mapToken(i,e,r),d=Number(s),m=new Intl.DateTimeFormat("en-GB"),h=[u,"Bond",m.format(d)].join(" ");return{id:t,name:h,symbol:u+"b",decimals:p,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:i,maturity:d}}async mapShares(t,e,r,n){let{assets:i}=n,{name:s,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,p=await Promise.all(i.map(async h=>{let{symbol:b}=await this.mapToken(h,e,r);return[h,b]})),d=Object.fromEntries(p),m=Object.values(d);return{id:t,name:m.join(", "),symbol:a?.asText()||s?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:d}}async mapExternal(t,e,r,n){let i=await this.mapToken(t,e,new Map,n),s=r?.find(a=>a.internalId===i.id);return s?{...i,decimals:s.decimals,name:s.name,symbol:s.symbol,icon:s.symbol,isWhiteListed:s.isWhiteListed}:i}parseMetadata(t){return new Map(Array.from(t,([e,r])=>[e,{symbol:r.symbol?.asText(),decimals:r.decimals}]))}async getSupported(t,e){let[r,n,i,s]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(r),o=[];for(let[l,u]of Array.from(r)){let p=n.get(l),{asset_type:d}=u,m;switch(d.type){case"Bond":let h=s.get(l);m=await this.mapBond(l,u,a,h);break;case"StableSwap":let b=i.get(l);m=await this.mapShares(l,u,a,b);break;case"External":m=await this.mapExternal(l,u,e,p);break;default:m=await this.mapToken(l,u,a,p)}o.push(m)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var vn=require("@galacticcouncil/common"),Z=require("rxjs"),w=require("rxjs/operators");var Br={};R(Br,{HUB_ASSET_ID:()=>ee,HYDRATION_OMNIPOOL_ADDRESS:()=>ki,HYDRATION_PARACHAIN_ID:()=>Ci,PERBILL_DENOMINATOR:()=>Ar,PERMILL_DENOMINATOR:()=>Et,SYSTEM_ASSET_DECIMALS:()=>Ye,SYSTEM_ASSET_ID:()=>C,TRADEABLE_DEFAULT:()=>Ct});var Et=1e6,Ar=1e9,C=0,Ye=12,Ci=2034,ki="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",ee=1,Ct=15;var{logger:kt}=vn.log,ut=class extends L{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:r}=await e.getValue(t,{at:"best"});return this.getBreakdown(r)}async getTokenBalance(t,e){let n=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(n)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,Z.defer)(()=>{let e=this.watchSystemBalance(t),r=this.watchTokensBalance(t),n=this.watchErc20Balance(t);return(0,Z.combineLatest)([e,r,n]).pipe((0,w.connect)(i=>(0,Z.concat)(i.pipe((0,w.take)(1)),i.pipe((0,w.skip)(1),(0,w.debounceTime)(250)))))}).pipe((0,w.map)(e=>e.flat()),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([e,r],n)=>n===0?r:this.getDeltas(e,r))).pipe((0,w.tap)({subscribe:()=>kt.debug("balance: subscribe",t),error:e=>kt.error("balance",e)}),(0,w.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,Z.defer)(()=>e.watchValue(t,"best")).pipe((0,w.map)(r=>({id:0,balance:this.getBreakdown(r.data)})),(0,w.tap)({error:r=>kt.error("balance(system)",r)}))}watchTokenBalance(t,e){let r=this.api.query.Tokens.Accounts;return(0,Z.defer)(()=>r.watchValue(t,e,"best")).pipe((0,w.map)(n=>({id:e,balance:this.getBreakdown(n)})),(0,w.tap)({error:n=>kt.error("balance(token)",n)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,Z.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,w.distinctUntilChanged)((r,n)=>!n.deltas),(0,w.map)(({deltas:r})=>{let n=[];return r?.deleted.forEach(i=>{let[s,a]=i.args;n.push({id:a,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),r?.upserted.forEach(i=>{let[s,a]=i.args;n.push({id:a,balance:this.getBreakdown(i.value)})}),n}),(0,w.tap)({error:r=>kt.error("balance(tokens)",r)}))}watchErc20Balance(t,e){let r=async()=>(await this.api.query.AssetRegistry.Assets.getEntries({at:"best"})).filter(({value:s})=>s.asset_type.type==="Erc20").map(({keyArgs:s})=>{let[a]=s;return a}),n=async i=>(await Promise.all(i.map(async a=>[a,await this.getBalanceData(t,a)]))).map(([a,o])=>({id:a,balance:o}));return(0,Z.defer)(()=>(0,Z.from)(e?Promise.resolve(e):r()).pipe((0,w.switchMap)(i=>this.watcher.bestBlock$.pipe((0,w.startWith)(null),(0,w.switchMap)(()=>(0,Z.from)(n(i))))),(0,w.pairwise)(),(0,w.map)(([i,s],a)=>a===0?s.filter(o=>o.balance.total>0n):this.getDeltas(i,s)),(0,w.distinctUntilChanged)((i,s)=>s.length===0),(0,w.tap)({error:i=>kt.error("balance(erc20)",i)})))}async getBalanceData(t,e){let r=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.getBreakdown(r)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,r=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:r,transferable:e}}getDeltas(t,e){let r=(i,s)=>i!==void 0&&s!==void 0&&i.transferable===s.transferable&&i.total===s.total,n=t.reduce((i,s)=>(i.set(s.id,s.balance),i),new Map);return e.filter(i=>!r(i.balance,n.get(i.id)))}};var Mt=class extends L{_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 Er={};R(Er,{AssetNotFound:()=>Fr,PoolNotFound:()=>re,RouteNotFound:()=>ne});var Fr=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},re=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},ne=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var kr={};R(kr,{EvmClient:()=>ae,EvmRpcAdapter:()=>se,createChain:()=>Cr});var ie=require("polkadot-api"),wn=require("@galacticcouncil/descriptors"),ze=require("viem"),Mi=10000000n,se=class{api;constructor(t){this.api=t.getTypedApi(wn.hydration)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,r=e.timestamp/1000n,[n]=e.number;return{timestamp:r,number:n}}readContract=(async t=>{let{abi:e,address:r,functionName:n,args:i}=t,s=(0,ze.encodeFunctionData)({abi:e,functionName:n,args:i}),a=await this.api.apis.EthereumRuntimeRPCApi.call(ie.FixedSizeBinary.fromText(""),ie.FixedSizeBinary.fromHex(r),ie.Binary.fromHex(s),[0n,0n,0n,0n],[Mi,0n,0n,0n],void 0,void 0,void 0,!1,[],[]);if(!a.success)throw console.error(n,a.value.type),new Error("Contract read failure");let{exit_reason:o,value:l,used_gas:u}=a.value;if(console.log(u),o.type==="Succeed")return(0,ze.decodeFunctionResult)({abi:e,functionName:n,data:l.asHex()});throw console.log(n,o.type,o.value.type),new Error("Contract read error")})};var xn=require("viem"),Di=["https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],Cr=()=>(0,xn.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:Di}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var pt=require("viem");var ae=class{client;chain;constructor(t){this.client=t,this.chain=Cr()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,pt.createPublicClient)({chain:this.chain,transport:(0,pt.http)()})}getWsProvider(){return(0,pt.createPublicClient)({transport:(0,pt.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,pt.createWalletClient)({account:t,chain:this.chain,transport:(0,pt.custom)(window.ethereum)})}getRPCAdapter(){return new se(this.client)}};var Vr={};R(Vr,{LiquidityMiningApi:()=>ue,LiquidityMiningClient:()=>pe});var Dn=require("polkadot-api"),Y=vt(require("big.js")),ft=require("@galacticcouncil/common"),Gr=require("@galacticcouncil/math-liquidity-mining");var oe={};R(oe,{withTimeout:()=>Li});function Li(c,t,e="timeout"){return new Promise((r,n)=>{let i=setTimeout(()=>n(new Error(e)),t);c.then(s=>{clearTimeout(i),r(s)},s=>{clearTimeout(i),n(s)})})}var q={};R(q,{divSpot:()=>Ni,getFraction:()=>Hi,mulScaled:()=>Tn,mulSpot:()=>qi});var Mr=require("@galacticcouncil/common");function Tn(c,t,e,r,n){let i=e+r-n,s=c*t;return i>0?s/BigInt(10)**BigInt(i):i<0?s*BigInt(10)**BigInt(-i):s}function qi(c,t,e,r){return Tn(c,t,e,Mr.RUNTIME_DECIMALS,r)}function Ni(c,t,e,r){if(t===0n)return 0n;let n=BigInt(10)**BigInt(Mr.RUNTIME_DECIMALS+r-e);return c*n/t}function Hi(c,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let r=BigInt(10)**BigInt(e),n=BigInt(Math.round(t*Number(r)));return c*n/(BigInt(100)*r)}var _={};R(_,{FeeUtils:()=>Dr,shiftNeg:()=>Gi});var In=vt(require("big.js"));var Dr=class c{static toPct(t){let[e,r]=t;return c.safeDivide(e*100,r)}static toRaw(t){let[e,r]=t;return c.safeDivide(e,r)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,r=12){let n=10**r;return Math.round(t*n/e)/n}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Gi(c,t){let e=(0,In.default)(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Dt={};R(Dt,{findNestedKey:()=>Vi,findNestedObj:()=>Ui,jsonFormatter:()=>Wi});var Vi=(c,t)=>{let e=[];return JSON.stringify(c,(r,n)=>(n&&n[t]&&e.push(n),n)),e[0]},Ui=(c,t,e)=>{let r;return JSON.stringify(c,(n,i)=>(i&&i[t]===e&&(r=i),i)),r},Wi=(c,t)=>typeof t=="bigint"?t.toString():t;var W={};R(W,{calculateBuyFee:()=>Xi,calculateDiffToAvg:()=>Yi,calculateDiffToRef:()=>zi,calculateSellFee:()=>$i});var mt=vt(require("big.js"));function Yi(c,t){let e=(0,mt.default)(c.toString()),r=(0,mt.default)(t.toString());return e.minus(r).abs().div(e.plus(r).div(2)).mul(100).round(2).toNumber()}function zi(c,t){if(t===0n)return 0;let e=(0,mt.default)(c.toString()),r=(0,mt.default)(t.toString());return e.minus(r).div(r).mul(100).round(2).toNumber()}function $i(c,t){if(c===0n)return 0;let e=(0,mt.default)(c.toString()),r=(0,mt.default)(t.toString());return(0,mt.default)(1).minus(r.div(e)).mul(100).round(2).toNumber()}function Xi(c,t){if(c===0n)return 0;let e=(0,mt.default)(c.toString());return(0,mt.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var le=(c,t)=>c===t?0:c==null?t==null?0:-1:t==null?c==null?0:1:typeof c.compare=="function"?c.compare(t):typeof t.compare=="function"?-t.compare(c):c<t?-1:c>t?1:0;var $e=(c,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(c(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var Ki=$e(()=>"illegal argument(s)"),_n=c=>{throw new Ki(c)};var ji=$e(()=>"index out of bounds"),Lr=c=>{throw new ji(c)},Xe=(c,t,e)=>(c<t||c>=e)&&Lr(c);var On=23283064365386963e-26,Ke=class{float(t=1){return this.int()*On*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*On-.5)*2*t}normMinMax(t,e){let r=this.minmax(t,e);return this.float()<.5?r:-r}minmax(t,e){return this.float()*(e-t)+t}minmaxInt(t,e){t|=0;let r=(e|0)-t;return r?t+this.int()%r:t}minmaxUint(t,e){t>>>=0;let r=(e>>>0)-t;return r?t+this.int()%r:t}};var je=class extends Ke{constructor(t){super(),this.rnd=t}float(t=1){return this.rnd()*t}norm(t=1){return(this.rnd()-.5)*2*t}int(){return this.rnd()*4294967296>>>0}};var An=new je(Math.random);var Bn=c=>c!=null&&typeof c!="function"&&c.length!==void 0;var Rn=Object.getPrototypeOf({}),Qe="function",Fn="string",Lt=(c,t)=>{let e;if(c===t)return!0;if(c!=null){if(typeof c.equiv===Qe)return c.equiv(t)}else return c==t;if(t!=null){if(typeof t.equiv===Qe)return t.equiv(c)}else return c==t;return typeof c===Fn||typeof t===Fn?!1:(e=Object.getPrototypeOf(c),(e==null||e===Rn)&&(e=Object.getPrototypeOf(t),e==null||e===Rn)?ts(c,t):typeof c!==Qe&&c.length!==void 0&&typeof t!==Qe&&t.length!==void 0?Qi(c,t):c instanceof Set&&t instanceof Set?Ji(c,t):c instanceof Map&&t instanceof Map?Zi(c,t):c instanceof Date&&t instanceof Date?c.getTime()===t.getTime():c instanceof RegExp&&t instanceof RegExp?c.toString()===t.toString():c!==c&&t!==t)},Qi=(c,t,e=Lt)=>{let r=c.length;if(r===t.length)for(;r-- >0&&e(c[r],t[r]););return r<0},Ji=(c,t,e=Lt)=>c.size===t.size&&e([...c.keys()].sort(),[...t.keys()].sort()),Zi=(c,t,e=Lt)=>c.size===t.size&&e([...c].sort(),[...t].sort()),ts=(c,t,e=Lt)=>{if(Object.keys(c).length!==Object.keys(t).length)return!1;for(let r in c)if(!t.hasOwnProperty(r)||!e(c[r],t[r]))return!1;return!0};var qr=class{value;constructor(t){this.value=t}deref(){return this.value}};var En=c=>c instanceof qr;var Je=class c{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Cn("next",this._head)}reverseIterator(){return Cn("prev",this.tail)}clear(){this.release()}compare(t,e=le){let r=this._length;if(r<t._length)return-1;if(r>t._length)return 1;if(r===0)return 0;{let n=this._head,i=t._head,s=0;for(;r-- >0&&s===0;)s=e(n.value,i.value),n=n.next,i=i.next;return s}}concat(...t){let e=this.copy();for(let r of t)e.into(r);return e}equiv(t){if(!(t instanceof c||Bn(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),r=this._head;for(let n=this._length;n-- >0;){if(!Lt(r.value,e.next().value))return!1;r=r.next}return!0}filter(t){let e=this.empty();return this.traverse(r=>(t(r.value)&&e.append(r.value),!0)),e}find(t){return this.traverse(e=>e.value!==t)}findWith(t){return this.traverse(e=>!t(e.value))}first(){return this._head?.value}insertSorted(t,e){e=e||le;for(let r=this._head,n=this._length;n-- >0;){if(e(t,r.value)<=0)return this.insertBefore(r,t);r=r.next}return this.append(t)}into(t){for(let e of t)this.append(e);return this}nth(t,e){let r=this.nthCell(t);return r?r.value:e}nthCellUnsafe(t){let e,r;for(t<=this._length>>>1?(e=this._head,r="next"):(e=this.tail,r="prev",t=this._length-t-1);t-- >0&&e;)e=e[r];return e}peek(){return this.tail?.value}$reduce(t,e){let r=this._head;for(let n=this._length;n-- >0&&!En(e);)e=t(e,r.value),r=r.next;return e}reduce(t,e){return this.$reduce(t,e)}release(){let t=this._head;if(!t)return!0;let e;for(let r=this._length;r-- >0;)e=t.next,delete t.value,delete t.prev,delete t.next,t=e;return this._head=void 0,this._length=0,!0}reverse(){let t=this._head,e=this.tail,r=(this._length>>>1)+(this._length&1);for(;t&&e&&r>0;){let n=t.value;t.value=e.value,e.value=n,t=t.next,e=e.prev,r--}return this}setHead(t){let e=this._head;return e?(e.value=t,e):this.prepend(t)}setNth(t,e){let r=this.nthCell(t);return!r&&Lr(t),r.value=e,r}setTail(t){let e=this.tail;return e?(e.value=t,e):this.append(t)}swap(t,e){if(t!==e){let r=t.value;t.value=e.value,e.value=r}return this}toArray(t=[]){return this.traverse(e=>(t.push(e.value),!0)),t}toJSON(){return this.toArray()}toString(){let t=[];return this.traverse(e=>(t.push(String(e.value)),!0)),t.join(", ")}traverse(t,e=this._head,r){if(!this._head)return;let n=e;do{if(!t(n))break;n=n.next}while(n!==r);return n}_map(t,e){return this.traverse(r=>(t.append(e(r.value)),!0)),t}};function*Cn(c,t){for(;t;)yield t.value,t=t[c]}var Ze=class c extends Je{_tail;constructor(t){super(),t&&this.into(t)}get tail(){return this._tail}append(t){if(this._tail){let e={value:t,prev:this._tail};return this._tail.next=e,this._tail=e,this._length++,e}else return this.prepend(t)}asHead(t){return t===this._head?this:(this.remove(t),this._head.prev=t,t.next=this._head,t.prev=void 0,this._head=t,this._length++,this)}asTail(t){return t===this._tail?this:(this.remove(t),this._tail.next=t,t.prev=this._tail,t.next=void 0,this._tail=t,this._length++,this)}cons(t){return this.prepend(t),this}copy(){return new c(this)}*cycle(){for(;;)yield*this}drop(){let t=this._head;if(t)return this._head=t.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,t.value}empty(){return new c}insertAfter(t,e){let r={value:e,next:t.next,prev:t};return t.next?t.next.prev=r:this._tail=r,t.next=r,this._length++,r}insertAfterNth(t,e){return t<0&&(t+=this._length),t>=this._length-1?this.append(e):(Xe(t,0,this._length),this.insertAfter(this.nthCellUnsafe(t),e))}insertBefore(t,e){let r={value:e,next:t,prev:t.prev};return t.prev?t.prev.next=r:this._head=r,t.prev=r,this._length++,r}insertBeforeNth(t,e){return t<0&&(t+=this._length),t<=0?this.prepend(e):(Xe(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new c,t)}nth(t,e){let r=this.nthCell(t);return r?r.value:e}nthCell(t){if(t<0&&(t+=this._length),!(t<0||t>=this._length))return this.nthCellUnsafe(t)}pop(){let t=this._tail;if(t)return this._tail=t.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,t.value}prepend(t){let e={value:t,next:this._head};return this._head?this._head.prev=e:this._tail=e,this._head=e,this._length++,e}push(t){return this.append(t),this}release(){return this._tail=void 0,super.release()}remove(t){return t.prev?t.prev.next=t.next:this._head=t.next,t.next?t.next.prev=t.prev:this._tail=t.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let t=this.peek();return this.pop(),this.prepend(t),this}}seq(t=0,e=this.length){if(t>=e||t<0)return;let r=this.nthCell(t),n=this.nthCell(e-1),i=s=>({first(){return s.value},next(){return s!==n&&s.next?i(s.next):void 0}});return r?i(r):void 0}shuffle(t,e=An){if(this._length<2)return this;for(t=t!==void 0?t:Math.ceil(1.5*Math.log2(this._length));t>0;t--){let r=this._head;for(;r;){let n=r.next;e.probability(.5)?this.asHead(r):this.asTail(r),r=n}}return this}slice(t=0,e=this.length){let r=t<0?t+this._length:t,n=e<0?e+this._length:e;(r<0||n<0)&&_n("invalid indices: ${from} / ${to}");let i=new c,s=this.nthCell(r);for(;s&&++r<=n;)i.push(s.value),s=s.next;return i}sort(t=le){if(!this._length)return this;let e=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let n=0;for(;r;){n++;let i=r,s=0;for(let o=0;o<e&&(s++,i=i.next,!!i);o++);let a=e;for(;s>0||a>0&&i;){let o;s===0?(o=i,i=i.next,a--):!i||a===0||t(r.value,i.value)<=0?(o=r,r=r.next,s--):(o=i,i=i.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}r=i}if(this._tail.next=void 0,n<=1)return this;e*=2}}splice(t,e=0,r){let n;typeof t=="number"?(t<0&&(t+=this._length),Xe(t,0,this._length),n=this.nthCellUnsafe(t)):n=t;let i=new c;if(e>0)for(;n&&e-- >0;)this.remove(n),i.push(n.value),n=n.next;else n&&(n=n.next);if(r)if(n)for(let s of r)this.insertBefore(n,s);else for(let s of r)this.push(s);return i}};var tr=class c{map;items;opts;_size;constructor(t,e){let r={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...e};this.map=r.map(),this.items=new Ze,this._size=0,this.opts=r,t&&this.into(t)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let t of this.items)yield[t.k,t]}*keys(){for(let t of this.items)yield t.k}*values(){for(let t of this.items)yield t.v}copy(){let t=this.empty();t.items=this.items.copy();let e=t.items.head;for(;e;)t.map.set(e.value.k,e),e=e.next;return t}empty(){return new c(null,this.opts)}release(){this._size=0,this.map.clear();let t=this.opts.release;if(t){let e;for(;e=this.items.drop();)t(e.k,e.v);return!0}return this.items.release()}has(t){return this.map.has(t)}get(t,e){let r=this.map.get(t);return r?this.resetEntry(r):e}set(t,e){let r=this.opts.ksize(t)+this.opts.vsize(e),n=this.map.get(t),i=Math.max(0,r-(n?n.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(n,t,e,r):this._size-=i,e}into(t){for(let e of t)this.set(e[0],e[1]);return this}async getSet(t,e){let r=this.map.get(t);return r?this.resetEntry(r):this.set(t,await e())}delete(t){let e=this.map.get(t);return e?(this.removeEntry(e),!0):!1}resetEntry(t){return this.items.asTail(t),t.value.v}ensureSize(){let{release:t,maxsize:e,maxlen:r}=this.opts;for(;this._size>e||this.length>=r;){let n=this.items.drop();if(!n)return!1;this.map.delete(n.k),t?.(n.k,n.v),this._size-=n.s}return!0}removeEntry(t){let e=t.value;this.map.delete(e.k),this.items.remove(t),this.opts.release?.(e.k,e.v),this._size-=e.s}doSetEntry(t,e,r,n){t?(this.opts.update?.(e,t.value.v,r),t.value.v=r,t.value.s=n,this.items.asTail(t)):(this.items.push({k:e,v:r,s:n}),this.map.set(e,this.items.tail))}};var _t=class c extends tr{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new c(null,this.opts)}has(t){return this.get(t)!==void 0}get(t,e){let r=this.map.get(t);if(r){if(r.value.t>=Date.now())return this.resetEntry(r);this.removeEntry(r)}return e}set(t,e,r=this.opts.ttl){let n=this.opts.ksize(t)+this.opts.vsize(e),i=this.map.get(t),s=Math.max(0,n-(i?i.value.s:0));return this._size+=s,this.ensureSize()?this.doSetEntry(i,t,e,n,r):this._size-=s,e}async getSet(t,e,r=this.opts.ttl){let n=this.get(t);return n!==void 0?n:this.set(t,await e(),r)}prune(){let t=Date.now(),e=this.items.head,r=0;for(;e;)e.value.t<t&&(this.removeEntry(e),r++),e=e.next;return r}ensureSize(){let{maxlen:t,maxsize:e}=this.opts,r=Date.now(),n=this.items.head;for(;n&&(this._size>e||this.length>=t);)n.value.t<r&&this.removeEntry(n),n=n.next;return super.ensureSize()}doSetEntry(t,e,r,n,i=this.opts.ttl){let s=Date.now()+i;t?(this.opts.update?.(e,t.value.v,r),t.value.v=r,t.value.s=n,t.value.t=s,this.items.asTail(t)):(this.items.push({k:e,v:r,s:n,t:s,ttl:i}),this.map.set(e,this.items.tail))}resetEntry(t){return this.opts.autoExtend&&(t.value.t=Date.now()+t.value.ttl),super.resetEntry(t)}};var ce=class{debug;constructor(t){this.debug=t||!1}log(t,e,r){this.debug&&console.log(t,e,r)}scope(t,e,r,n){let i=new Map,s=n!==void 0?new _t(null,{ttl:n}):new _t;return{get:(...u)=>{let p=r(...u);if(i.has(p)){this.log("[live]",t,p);let m=i.get(p);return Promise.resolve(m)}if(s.has(p))return this.log("[memo]",t,p),s.get(p);this.log("[fetch]",t,p);let d=e(...u).catch(m=>{throw s.delete(p),m});return s.set(p,d),d},set:(u,...p)=>{let d=r(...p);this.log("[set-live]",t,d),i.set(d,u)},clear:()=>{this.log("[clear]",t),i.clear(),s.release()}}}};var er=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let r=0;r<t.length;++r){let[n,i]=t[r];this.result.set(this.getKey(i,n),e[r].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,r,n){let i=this.getKey(t,e),s=this.getKey(t,r),a=this.result.get(i)??0n,o=this.result.get(s)??0n;if(a<n)throw new Error("Attempting to transfer more than is present");this.result.set(i,a+n),this.result.set(s,o+n)}};var wt=vt(require("big.js")),at=require("@galacticcouncil/math-liquidity-mining");var Nr=vt(require("big.js")),Hr=(0,Nr.default)(10).pow(18),kn=BigInt((0,Nr.default)(1).pow(18).toString()),Mn=6e3;var es="1000000000000000000",rr=class{constructor(t,e,r){this.getAccount=t;this.getAsset=e;this.multiCurrency=r}async syncGlobalFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let n=await this.getAsset(t.reward_currency),i=e-t.updated_at,s=this.getAccount(t.id),a=n?.existential_deposit;if(!a)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,s),l=(0,wt.default)(a.toString()),u=(0,wt.default)(o.toString()).minus(l.lt(o.toString())?a.toString():o.toString()),p=(0,wt.default)((0,at.calculate_global_farm_rewards)(t.total_shares_z.toString(),r.toString(),(0,wt.default)(t.yield_per_period.toString()).mul(Hr).round(0,wt.default.roundDown).toFixed(),t.max_reward_per_period.toString(),i.toFixed()));if(u.lt(p)&&(p=u),p.eq(0))return t;let d=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,s,d,BigInt(p.toFixed())),{...t,accumulated_rpz:BigInt((0,at.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),p.toFixed()))}}syncYieldFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===r)return null;if(t.total_valued_shares===0n)return{...t,updated_at:r};let n=(0,at.calculate_yield_farm_delta_rpvs)(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(n),updated_at:r}}getLoyaltyMultiplier(t,e){let r=(0,wt.default)(1).mul(Hr).round(0,wt.default.roundDown).toString();if(!e)return r;let{initial_reward_percentage:n,scale_coef:i}=e;return(0,at.calculate_loyalty_multiplier)(t.toFixed(),n.toString(),i.toFixed())}async claimRewards(t,e,r,n,i){if(e.state.type==="Terminated")return null;let s=Math.floor(n/t.blocks_per_period);if(r.updated_at===s)return null;let a=await this.syncGlobalFarm(t,s,i);if(!a)return null;let o=this.syncYieldFarm(e,a,s);if(!o)return null;let l=o.total_stopped-r.stopped_at_creation,u=o.updated_at-r.entered_at-l,p=this.getLoyaltyMultiplier(u,o.loyalty_curve),d=BigInt((0,at.calculate_user_reward)(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),m=BigInt((0,at.calculate_user_reward)(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),es));return{reward:d,maxReward:m,assetId:a.reward_currency,yieldFarmId:o.id,isActiveFarm:o.state.type==="Active"}}};var rs=(0,Y.default)(365.2425).times(24).times(60).times(60),ue=class{balance;client;options;constructor(t,e,r={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:r.blockTime??Mn})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let r=[t,e].sort((i,s)=>i-s);if(t===e)return kn;let n=await this.client.getOraclePrice(r);if(n){let{n:i,d:s}=n[0].price,a;return t<e?a=(0,Gr.fixed_from_rational)(i.toString(),s.toString()):a=(0,Gr.fixed_from_rational)(s.toString(),i.toString()),BigInt(a)}}getFarmAddress=(t,e)=>{let r=Buffer.from("modl","utf-8"),n=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),i=Buffer.from([t]),s=Buffer.concat([r,n,i]),o="0x"+Buffer.concat([s,Buffer.alloc(32-s.length)]).toString("hex");return(0,Dn.AccountId)(ft.HYDRATION_SS58_PREFIX).dec(o)};getGlobalRewardPerPeriod(t,e,r,n){let i=(0,Y.default)(n).times(t.toString()).times(e.toString()).div(Math.pow(10,ft.RUNTIME_DECIMALS));return i.gte(r.toString())?r.toString():i.toString()}getPoolYieldPerPeriod(t,e,r,n){let i=(0,Y.default)(t.toString()).times(e),s=(0,Y.default)(r.toString()).times(n);return i.div(s.toString()).toString()}farmData(t,e,r){let{yieldFarm:n,globalFarm:i,priceAdjustment:s,balance:a,id:o}=t,{multiplier:l,loyalty_curve:u}=n,{blocks_per_period:p,yield_per_period:d,total_shares_z:m,max_reward_per_period:h,pending_rewards:b,accumulated_paid_rewards:g,planned_yielding_periods:f,updated_at:y,incentivized_asset:v,reward_currency:S,price_adjustment:T,min_deposit:A}=i,N=_.shiftNeg(s??T,ft.RUNTIME_DECIMALS),U=_.shiftNeg(l,ft.RUNTIME_DECIMALS),ct=_.shiftNeg(u?.initial_reward_percentage??0,ft.RUNTIME_DECIMALS),bt=rs.div((0,Y.default)(this.blockTime).div(1e3).times(p)).toString(),J;if(m<=0)J=(0,Y.default)(U).times(d.toString()).times(bt).div(Math.pow(10,ft.RUNTIME_DECIMALS)).toString();else{let Pi=this.getGlobalRewardPerPeriod(m,d,h,N),Si=this.getPoolYieldPerPeriod(Pi,U,m,N);J=(0,Y.default)(Si).times(bt).toString()}let nt=b+g,Kt=h*BigInt(f),Ee=a.transferable+nt,cn=Ee-nt,Ce=(0,Y.default)(cn.toString()).div(h.toString()),ke=(0,Y.default)(e).div(p.toString()).toString(),Me=(m>=0?Ce.plus(y):Ce.plus(ke)).toString(),vr=(0,Y.default)(Me).times(p).toString(),yi=(0,Y.default)(m.toString()).div((0,Y.default)(h.toString()).div(d.toString())).div(Math.pow(10,ft.RUNTIME_DECIMALS)).times(100).times(N).toFixed(2),un=(0,Y.default)(nt.toString()).div(Ee.toString()).gte(.999);J=un?"0":(0,Y.default)(J).div(r?2:1).times(100).toString();let fi=ct?(0,Y.default)(J).times(ct).toString():void 0;return{apr:J,minApr:fi,isDistributed:un,estimatedEndPeriod:Me,estimatedEndBlock:vr,maxRewards:Kt,incentivizedAsset:v,rewardCurrency:S,loyaltyCurve:u,currentPeriod:ke,potMaxRewards:Ee,fullness:yi,yieldFarmId:n.id,globalFarmId:i.id,poolId:o,distributedRewards:nt,plannedYieldingPeriods:f,minDeposit:A,blocksPerPeriod:p}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((n,i)=>n.includes(i.keyArgs[0].toString())?n:[...n,i.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async n=>{let i=await this.getOmnipoolFarms(n);if(i)return[n,i]}));return Object.fromEntries(r.filter(n=>!!n))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),r=await this.client.getRelayBlockNumber(),n=await Promise.all(e.map(async({keyArgs:i,value:s})=>{let[,a]=i,o=s,l=await this.client.getOmnipoolGlobalFarm(a),u=await this.client.getOmnipoolYieldFarm(Number(t),a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a),h=await this.getOraclePrice(p,d),b=await this.balance.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:h,balance:b}}));return r?n.map(i=>i?this.farmData(i,r):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((n,i)=>n.includes(i.keyArgs[0].toString())?n:[...n,i.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async n=>{let i=await this.getIsolatedFarms(n);if(i)return[n,i]}));return Object.fromEntries(r.filter(n=>!!n))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),r=await this.client.getRelayBlockNumber(),n=await Promise.all(e.map(async({keyArgs:i,value:s})=>{let[,a]=i,o=s,l=await this.client.getIsolatedGlobalFarm(a),u=await this.client.getIsolatedYieldFarm(t,a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a,!0),h=await this.getOraclePrice(p,d),b=await this.balance.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:h,balance:b,farmAddress:m}}));return r?n.map(i=>i?this.farmData(i,r,!0):void 0):[]}async getDepositReward(t,e,r,n){let i=e.global_farm_id,s=e.yield_farm_id,a=r?await this.client.getIsolatedYieldFarm(t,i,s):await this.client.getOmnipoolYieldFarm(Number(t),i,s),o=r?await this.client.getIsolatedGlobalFarm(i):await this.client.getOmnipoolGlobalFarm(i);if(!o||!a)return;let l=o.reward_currency,u=o.incentivized_asset,p=[[this.getFarmAddress(0,r),o.reward_currency],[this.getFarmAddress(o.id,r),o.reward_currency]],d=await this.getAccountAssetBalances(p),m=await this.getOraclePrice(l,u),h=new er(p,d),g=await new rr(y=>this.getFarmAddress(y),y=>this.client.getAsset(y),h).claimRewards(o,a,e,n,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,r]=await Promise.all([Promise.all(t.filter(([i,s])=>s!==0).map(([i,s])=>this.balance.getTokenBalance(i,s))),Promise.all(t.filter(([i,s])=>s===0).map(([i])=>this.balance.getSystemBalance(i)))]),n=[];for(let i=0,s=0;i+s<t.length;){let a=i+s,[,o]=t[a];o===0?(n.push(r[s]),s+=1):(n.push(e[i]),i+=1)}return n}};var nr=require("polkadot-api"),pe=class extends L{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(nr.Binary.fromText("omnipool"),t,(0,nr.Enum)("TenMinutes"))}async getRelayBlockNumber(){return(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number}async getAllOmnipooFarms(){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries()}async getOmnipooFarms(t){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries(t)}async getOmnipoolGlobalFarm(t){return this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getOmnipoolYieldFarm(t,e,r){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,r,{at:"best"})}async getAllIsolatedFarms(){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries()}async getIsolatedFarms(t){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries(t)}async getIsolatedGlobalFarm(t){return this.api.query.XYKWarehouseLM.GlobalFarm.getValue(t,{at:"best"})}async getIsolatedYieldFarm(t,e,r){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,r,{at:"best"})}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};var jr={};R(jr,{PoolContextProvider:()=>Wt,PoolError:()=>xt,PoolFactory:()=>Ut,PoolType:()=>F,aave:()=>$r,hsm:()=>Kr,lbp:()=>Ur,omni:()=>Wr,stable:()=>Yr,xyk:()=>zr});var Ur={};R(Ur,{LbpMath:()=>ot,LbpPool:()=>me,LbpPoolClient:()=>de});var dt=require("@galacticcouncil/math-lbp"),ot=class{static getSpotPrice(t,e,r,n,i){return(0,dt.get_spot_price)(t,e,r,n,i)}static calculateInGivenOut(t,e,r,n,i){return(0,dt.calculate_in_given_out)(t,e,r,n,i)}static calculateOutGivenIn(t,e,r,n,i){return(0,dt.calculate_out_given_in)(t,e,r,n,i)}static calculateLinearWeights(t,e,r,n,i){return(0,dt.calculate_linear_weights)(t,e,r,n,i)}static calculatePoolTradeFee(t,e,r){return(0,dt.calculate_pool_trade_fee)(t,e,r)}};var qt=require("@galacticcouncil/common");var F=(s=>(s.Aave="Aave",s.LBP="LBP",s.Omni="Omnipool",s.Stable="Stableswap",s.XYK="XYK",s.HSM="HSM",s))(F||{}),xt=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(xt||{});var{FeeUtils:Ln}=_,me=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let r=new Map(this.tokens.map(s=>[s.id,s])),n=r.get(t),i=r.get(e);if(n==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:n.balance,balanceOut:i.balance,decimalsIn:n.decimals,decimalsOut:i.decimals,weightIn:n.weight,weightOut:i.weight}}validateAndBuy(t,e,r){let n=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let s=t.balanceOut/this.maxOutRatio;if(e>s&&i.push("MaxOutRatioExceeded"),n===t.assetOut){let a=this.calculateTradeFee(e,r),o=Ln.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return u>p&&i.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:i}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&i.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:i}}}validateAndSell(t,e,r){let n=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let s=t.balanceIn/this.maxInRatio;if(e>s&&i.push("MaxInRatioExceeded"),n===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:i}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,r),l=Ln.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),u=a-o,p=t.balanceOut/this.maxOutRatio;return u>p&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:i}}}calculateInGivenOut(t,e){let r=ot.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),n=BigInt(r);return n<0n?0n:n}calculateOutGivenIn(t,e){let r=ot.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),n=BigInt(r);return n<0n?0n:n}spotPriceInGivenOut(t){let e=ot.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),qt.big.toBigInt(1,qt.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=ot.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),qt.big.toBigInt(1,qt.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let r=ot.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(r)}};var Gn=require("polkadot-api"),Nt=require("rxjs");var qn=(c,t=new Map)=>e=>{let r;return t.has(e)?t.get(e):(t.set(e,r=c(e)),r)};var E=require("rxjs"),P=require("rxjs/operators");var Nn=require("rxjs"),ir=class{store$=new Nn.BehaviorSubject([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(t){return this.changeset.size===0?[]:t.filter(e=>this.changeset.has(e.address))}set(t){this.changeset=new Set(t.map(e=>e.address)),this.store$.next(t)}update(t){this.updateQueue=this.updateQueue.then(async()=>{let e=this.store$.value,r=new Map(e.map((a,o)=>[a.address,o])),n=await t(e),i=e.slice(),s=new Set;for(let a of n){let o=r.get(a.address);o===void 0?(r.set(a.address,i.length),i.push(a)):i[o]=a,s.add(a.address)}this.changeset=s,this.store$.next(i)}).catch(console.error)}destroy(){this.store$.complete()}};var Hn=require("@galacticcouncil/common");var ns={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:sr}=Hn.log,ar=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${ns[this.type]})`,10)}trace(t,...e){sr.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){sr.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){sr.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){sr.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:is}=oe,ss=3e3,Q=class extends L{evm;balance;store=new ir;log;shared$;resync$=new E.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new _t(null,{ttl:6*1e3});memPools=qn(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e,this.balance=new ut(t),this.log=new ar(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((0,P.startWith)([]),(0,P.bufferCount)(2,1),(0,P.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,P.filter)(t=>t.length>0),(0,P.throttleTime)(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return(0,E.defer)(()=>{let t=new E.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,P.switchMap)(()=>{let e=new E.Subscription;return(0,E.from)(is(this.getMemPools(),6e4,"getMemPools stalled")).pipe((0,P.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,P.map)(n=>n.filter(i=>this.hasValidAssets(i))),(0,P.tap)(n=>this.store.set(n)),(0,P.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),E.EMPTY))).pipe((0,P.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,P.switchMap)(n=>(0,E.merge)((0,E.of)(n),this.store.asObservable().pipe((0,P.skip)(1)))),(0,P.finalize)(()=>{e.unsubscribe()}))}),(0,P.finalize)(()=>t.unsubscribe()))}).pipe((0,P.share)({connector:()=>new E.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:r}=e,n=[this.balance.watchTokensBalance(r)];if(this.hasSystemAsset(e)){let i=this.balance.watchSystemBalance(r);n.push(i)}if(this.hasErc20Asset(e)){let i=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),s=this.balance.watchErc20Balance(r,i);n.push(s)}return(0,E.combineLatest)(n).pipe((0,P.map)(i=>i.flat()),(0,P.pairwise)(),(0,P.map)(([i,s])=>this.balance.getDeltas(i,s)),(0,P.filter)(i=>i.length>0),(0,P.map)(i=>[r,i]))});return(0,E.merge)(...t).pipe((0,P.bufferTime)(250),(0,P.filter)(e=>e.length>0),(0,P.map)(e=>new Map(e)),this.watchGuard("balances")).subscribe(e=>{this.store.update(r=>this.updateBalances(r,e))})}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:r})=>r>0n&&!!e)}updateBalances=(t,e)=>{let r=[],n=new Map(t.map(i=>[i.address,i]));for(let[i,s]of e){let a=n.get(i);if(a){let o=a.tokens.map(l=>{let u=s.find(p=>p.id===l.id);return u&&l.id!==a.id?{...l,balance:u.balance.transferable}:l});r.push({...a,tokens:o})}}return r};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<ss||(this.resyncAt=e,this.mem++,this.resync$.next())}requestResync(t=!1){this.resyncPending||(this.resyncPending=!0,setTimeout(()=>{this.resyncPending=!1,this.resync(t)},0))}startWatchdog(){let r=this.watcher.connection$.pipe((0,P.pairwise)(),(0,P.filter)(([i,s])=>i==="offline"&&s==="online"),(0,P.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,P.catchError)(i=>(this.log.error("watchdog_recovery_error",i),E.EMPTY)),(0,P.repeat)({delay:1e3})),n=this.watcher.finalizedBlock$.pipe((0,P.pairwise)(),(0,P.tap)(([i,s])=>{let a=Number(i.number),o=Number(s.number),l=o-a;l>=3&&(this.log.debug("watchdog_gap",{from:a,to:o,gap:l}),this.requestResync())}),(0,P.catchError)(i=>(this.log.error("watchdog_gap_error",i),E.EMPTY)),(0,P.repeat)({delay:1e3}));return(0,E.merge)(r,n).subscribe()}watchGuard(t){return e=>e.pipe((0,P.tap)({error:r=>{this.log.error(t,r),this.requestResync(!0)}}),(0,P.finalize)(()=>{this.log.debug(t,"unsub")}),(0,P.catchError)(()=>E.EMPTY))}};var de=class extends Q{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,r]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:r}}getPoolWeights(t,e){let{start:r,end:n,initial_weight:i,final_weight:s}=t,a=ot.calculateLinearWeights(r?r.toString():"0",n?n.toString():"0",i.toString(),s.toString(),e.toString()),o=BigInt(a),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Gn.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e,r]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:"best"}),this.api.query.ParachainSystem.ValidationData.getValue({at:"best"}),this.getPoolLimits()]),n=e?.relay_parent_number||0,i=t.filter(({value:s})=>e&&this.isActivePool(s,n)).map(async({keyArgs:s,value:a})=>{let[o]=s,l=o.toString(),u=await this.getPoolDelta(l,a,n);return{address:l,type:"LBP",fee:a.fee,...u,...r}});return Promise.all(i)}async getPoolDelta(t,e,r){let{assets:n,repay_target:i,fee_collector:s}=e,[a,o]=this.getPoolWeights(e,r),[l,u]=n,[p,d,m,h,b]=await Promise.all([this.isRepayFeeApplied(l,i,s.toString()),this.balance.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u)]);return{repayFeeApply:p,tokens:[{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,weight:a,type:m?.asset_type.type},{id:u,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:h.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(t,e){let{start:r,end:n}=t;return r&&n?e>=r&&e<n:!1}async isRepayFeeApplied(t,e,r){if(e===0n)return!1;try{return(await this.balance.getBalance(r,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let r=this.store.pools.find(i=>i.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:r.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue("best").pipe((0,Nt.filter)(t=>t!==void 0),(0,Nt.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let r=[];for(let n of e){let i=this.poolsData.get(n.address);if(i){let{assets:s,repay_target:a,fee_collector:o}=i,[l]=s,[u,p]=this.getPoolWeights(i,t),[d,m]=n.tokens,h=[{...d,weight:u},{...m,weight:p}],b=await this.isRepayFeeApplied(l,a,o.toString());r.push({...n,tokens:h,repayFeeApply:b})}}return r})})}subscribeUpdates(){let t=new Nt.Subscription;return t.add(this.subscribeValidationData()),t}};var Wr={};R(Wr,{OmniMath:()=>B,OmniPool:()=>ge,OmniPoolClient:()=>he});var x=require("@galacticcouncil/math-omnipool"),Ot=vt(require("big.js")),B=class{static calculateSpotPrice(t,e,r,n){return(0,x.calculate_spot_price)(t,e,r,n)}static calculateLrnaSpotPrice(t,e){return(0,x.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,r,n,i,s,a,o,l,u){return(0,x.calculate_in_given_out)(t,e,r,n,i,s,a,o,l,u)}static calculateLrnaInGivenOut(t,e,r,n,i,s){return(0,x.calculate_lrna_in_given_out)(t,e,r,n,i,s)}static calculateOutGivenIn(t,e,r,n,i,s,a,o,l,u){return(0,x.calculate_out_given_in)(t,e,r,n,i,s,a,o,l,u)}static calculateOutGivenLrnaIn(t,e,r,n,i,s){return(0,x.calculate_out_given_lrna_in)(t,e,r,n,i,s)}static calculateShares(t,e,r,n){return(0,x.calculate_shares)(t,e,r,n)}static calculateLiquidityOut(t,e,r,n,i,s,a,o){return(0,x.calculate_liquidity_out)(t,e,r,n,i,s,a,o)}static calculateLiquidityLRNAOut(t,e,r,n,i,s,a,o){return(0,x.calculate_liquidity_lrna_out)(t,e,r,n,i,s,a,o)}static calculateCapDifference(t,e,r,n){let i=(0,Ot.default)(e),s=(0,Ot.default)(t),a=(0,Ot.default)(n),o=(0,Ot.default)(r),l=(0,Ot.default)(10).pow(18),u=o.div(l);if(i.div(a).lt(u)){let d=u.times(a).minus(i).times(s),m=i.times((0,Ot.default)(1).minus(u));return d.div(m).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,r,n){return(0,x.calculate_liquidity_hub_in)(t,e,r,n)}static isSellAllowed(t){return(0,x.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,x.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,x.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,x.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,r,n,i,s,a,o,l,u,p){return(0,x.recalculate_asset_fee)(t,e,r,n,i,s,a,o,l,u,p)}static recalculateProtocolFee(t,e,r,n,i,s,a,o,l,u,p){return(0,x.recalculate_protocol_fee)(t,e,r,n,i,s,a,o,l,u,p)}static verifyAssetCap(t,e,r,n){return(0,x.verify_asset_cap)(t,e,r,n)}};var Vn=require("@galacticcouncil/common");var{FeeUtils:gt}=_,ge=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let r=new Map(this.tokens.map(s=>[s.id,s])),n=r.get(t),i=r.get(e);if(n==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:n.hubReserves,hubReservesOut:i.hubReserves,sharesIn:n.shares,sharesOut:i.shares,decimalsIn:n.decimals,decimalsOut:i.decimals,balanceIn:n.balance,balanceOut:i.balance,tradeableIn:n.tradeable,tradeableOut:i.tradeable,assetInEd:n.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,r){let n=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,r),s=n===0n?0:W.calculateBuyFee(n,i),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return i>p&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:n,amountOut:e,feePct:s,errors:a}}validateAndSell(t,e,r){let n=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,r),s=W.calculateSellFee(n,i),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return i>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:n,amountOut:i,feePct:s,errors:a}}calculateInGivenOut(t,e,r){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,r);let n=B.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),r?gt.toRaw(r.assetFee).toString():"0",r?gt.toRaw(r.protocolFee).toString():"0",r?gt.toRaw(r.maxSlipFee).toString():"0"),i=BigInt(n);return i<0n?0n:i}calculateLrnaInGivenOut(t,e,r){let n=B.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),r?gt.toRaw(r.assetFee).toString():"0",r?gt.toRaw(r.maxSlipFee).toString():"0"),i=BigInt(n);return i<0n?0n:i}calculateOutGivenIn(t,e,r){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,r);let n=B.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),r?gt.toRaw(r.assetFee).toString():"0",r?gt.toRaw(r.protocolFee).toString():"0",r?gt.toRaw(r.maxSlipFee).toString():"0"),i=BigInt(n);return i<0n?0n:i}calculateOutGivenLrnaIn(t,e,r){let n=B.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),r?gt.toRaw(r.assetFee).toString():"0",r?gt.toRaw(r.maxSlipFee).toString():"0"),i=BigInt(n);return i<0n?0n:i}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=B.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=B.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=B.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=B.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,r){let n=e-r;if(n===0)return t;let i=Vn.big.pow10(Math.abs(n));return n>0?t*i:t/i}};var Pt=require("polkadot-api"),Yn=require("@polkadot-api/utils"),O=require("rxjs"),zn=require("@galacticcouncil/common");var{FeeUtils:k}=_,Un=Pt.Binary.fromText("omnipool"),Wn=(0,Pt.Enum)("Short"),he=class extends Q{queryBus=new ce;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);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:"best"}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(Un,t,Wn,{at:"best"}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),r=(0,Yn.toHex)(e);return(0,Pt.AccountId)(zn.HYDRATION_SS58_PREFIX).dec(r)}getOraclePair(t){return t===0?[0,1]:[1,t]}async getPoolLimits(){let[t,e,r]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:r}}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Pt.CompatibilityLevel.BackwardsCompatible,e)}async isSlipFeeSupported(){return this.apiNext.query.Omnipool.SlipFee.isCompatible(Pt.CompatibilityLevel.Partial)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[r,n,i,s,a]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:"best"}),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.balance.getBalance(e,t),this.getPoolLimits()]),o=r.map(async({keyArgs:u,value:p})=>{let[d]=u,{hub_reserve:m,shares:h,tradable:b,cap:g,protocol_shares:f}=p,[y,v]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d),this.balance.getBalance(e,d)]);return{id:d,decimals:y?.decimals,existentialDeposit:y?.existential_deposit,balance:v.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:s.transferable,tradeable:n,type:i?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...a}]}async getPoolFees(t){let e=t.assetOut,r=t.assetIn,n=0;await this.isSlipFeeSupported()&&(n=await this.maxSlipFee.get()??0);let s=await this.dynamicFeesConfig.get(e);if(s?.type==="Fixed"){let{asset_fee:S,protocol_fee:T}=s.value;return{assetFee:k.fromPermill(S),protocolFee:k.fromPermill(T),maxSlipFee:k.fromPermill(n)}}let a=this.getOraclePair(e),o=this.getOraclePair(r),[l,u,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(a),this.emaOracles.get(o)]),[d,m,h]=await this.getAssetFee(t,this.block,l,u,s?.value.asset_fee_params),[b,g,f]=r===1?[0,0,0]:await this.getProtocolFee(t,this.block,l,p,s?.value.protocol_fee_params),y=d+b,v=h+f;return{assetFee:k.fromPermill(m),protocolFee:k.fromPermill(g),maxSlipFee:k.fromPermill(n),min:k.fromPermill(y),max:k.fromPermill(v)}}async getAssetFee(t,e,r,n,i){let{assetOut:s,balanceOut:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=i||await this.api.constants.DynamicFees.AssetFeeParameters();if(!r||!n)return[o,o,l];let d=k.fromPermill(o),m=k.fromPermill(l),[h]=n,{asset_fee:b,timestamp:g}=r,f=Math.max(1,e-g),y=h.volume.b_in.toString(),v=h.volume.b_out.toString(),S=h.liquidity.b.toString();s===0&&(y=h.volume.a_in.toString(),v=h.volume.a_out.toString(),S=h.liquidity.a.toString());let T=k.fromPermill(b),A=B.recalculateAssetFee(y,v,S,"9",a.toString(),k.toRaw(T).toString(),f.toString(),k.toRaw(d).toString(),k.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(A)*1e6,l]}async getProtocolFee(t,e,r,n,i){let{assetIn:s,balanceIn:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=i||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!r||!n)return[o,o,l];let d=k.fromPermill(o),m=k.fromPermill(l),[h]=n,{protocol_fee:b,timestamp:g}=r,f=Math.max(1,e-g),y=h.volume.b_in.toString(),v=h.volume.b_out.toString(),S=h.liquidity.b.toString();s===0&&(y=h.volume.a_in.toString(),v=h.volume.a_out.toString(),S=h.liquidity.a.toString());let T=k.fromPermill(b),A=B.recalculateProtocolFee(y,v,S,"9",a.toString(),k.toRaw(T).toString(),f.toString(),k.toRaw(d).toString(),k.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(A)*1e6,l]}subscribeEmaOracles(){let[t]=this.store.pools,r=t.tokens.map(n=>n.id).map(n=>this.getOraclePair(n)).map(n=>this.api.query.EmaOracle.Oracles.watchValue(Un,n,Wn,"best").pipe((0,O.filter)(i=>i!==void 0),(0,O.map)((i,s)=>({value:i,index:s})),(0,O.tap)(({index:i})=>{i>0&&this.log.trace("emaOracle.Oracles",n.join(":"))}),(0,O.map)(({value:i})=>({pair:n,value:i}))));return(0,O.merge)(...r).pipe((0,O.finalize)(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(n=>{let{pair:i,value:s}=n;this.emaOracles.set(s,i)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,O.distinctUntilChanged)((t,e)=>!e.deltas),(0,O.map)((t,e)=>({value:t,index:e})),(0,O.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),(0,O.finalize)(()=>this.dynamicFees.clear()),this.watchGuard("dynamicFees.AssetFee")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[r]=e.args;this.dynamicFees.set(e.value,r)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe((0,O.distinctUntilChanged)((t,e)=>!e.deltas),(0,O.map)((t,e)=>({value:t,index:e})),(0,O.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),(0,O.finalize)(()=>this.dynamicFeesConfig.clear()),this.watchGuard("dynamicFees.AssetFeeConfiguration")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[r]=e.args;this.dynamicFeesConfig.set(e.value,r)})})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,O.distinctUntilChanged)((t,e)=>!e.deltas),(0,O.map)((t,e)=>({value:t,index:e})),(0,O.tap)(({value:t,index:e})=>{e>0&&this.log.trace("omnipool.Assets",t.deltas?.upserted)}),this.watchGuard("omnipool.Assets")).subscribe(({value:{deltas:t}})=>{this.store.update(([e])=>{let r=t?.upserted.reduce((i,s)=>{let[a]=s.args;return i.set(a,s.value),i},new Map),n=e.tokens.map(i=>{let s=r?.get(i.id);return s?this.updateTokenState(i,s):i});return[{...e,tokens:n}]})})}subscribeUpdates(){let t=new O.Subscription;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:r,shares:n,tradable:i,cap:s,protocol_shares:a}=e;return{...t,cap:s,hubReserves:r,protocolShares:a,shares:n,tradeable:i}}};var Yr={};R(Yr,{StableMath:()=>z,StableSwap:()=>At,StableSwapClient:()=>ye});var M=require("@galacticcouncil/math-stableswap"),z=class{static getPoolAddress(t){return(0,M.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let r=0;r<t;r++)e.push(["1","1"]);return e}static calculateAmplification(t,e,r,n,i){return(0,M.calculate_amplification)(t,e,r,n,i)}static calculateInGivenOut(t,e,r,n,i,s,a){return(0,M.calculate_in_given_out)(t,e,r,n,i,s,a)}static calculateAddOneAsset(t,e,r,n,i,s,a){return(0,M.calculate_add_one_asset)(t,e,r,n,i,s,a)}static calculateSharesForAmount(t,e,r,n,i,s,a){return(0,M.calculate_shares_for_amount)(t,e,r,n,i,s,a)}static calculateOutGivenIn(t,e,r,n,i,s,a){return(0,M.calculate_out_given_in)(t,e,r,n,i,s,a)}static calculateLiquidityOutOneAsset(t,e,r,n,i,s,a){return(0,M.calculate_liquidity_out_one_asset)(t,e,r,n,i,s,a)}static calculateShares(t,e,r,n,i,s){return(0,M.calculate_shares)(t,e,r,n,i,s)}static calculateSpotPriceWithFee(t,e,r,n,i,s,a,o){return(0,M.calculate_spot_price_with_fee)(t,e,r,n,i,s,a,o)}static recalculatePegs(t,e,r,n,i,s){let a=(0,M.recalculate_peg)(t,e,r,n,i,s);return JSON.parse(a)}};var be=require("@galacticcouncil/common");var{FeeUtils:Ht}=_,At=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new c(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let r=new Map(this.tokens.map(s=>[s.id,s])),n=r.get(t),i=r.get(e);if(n==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:n.balance,balanceOut:i.balance,decimalsIn:n.decimals,decimalsOut:i.decimals,tradeableIn:this.id===t?15:n.tradeable,tradeableOut:this.id===e?15:i.tradeable,assetInEd:n.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,r){let n=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,r),s=n===0n?0:W.calculateBuyFee(n,i),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:n,amountOut:e,feePct:s,errors:a}}validateAndSell(t,e,r){let n=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,r),s=W.calculateSellFee(n,i),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||n<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:n,amountOut:i,feePct:s,errors:a}}calculateIn(t,e,r){let n=z.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),r?Ht.toRaw(r.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateAddOneAsset(t,e,r){let n=z.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),r?Ht.toRaw(r.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateSharesForAmount(t,e,r){let n=z.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),r?Ht.toRaw(r.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateInGivenOut(t,e,r){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,r):t.assetIn==this.id?this.calculateSharesForAmount(t,e,r):this.calculateIn(t,e,r)}spotPriceInGivenOut(t){let e=z.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetOut===this.id,t.assetIn===this.id,t.decimalsOut,t.decimalsIn)}calculateOut(t,e,r){let n=z.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),r?Ht.toRaw(r.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateWithdrawOneAsset(t,e,r){let n=z.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),r?Ht.toRaw(r.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateShares(t,e,r){let n=z.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),r?Ht.toRaw(r.fee).toString():"0",this.getPegs()),i=BigInt(n);return i<0n?0n:i}calculateOutGivenIn(t,e,r){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,r):t.assetOut==this.id?this.calculateShares(t,e,r):this.calculateOut(t,e,r)}spotPriceOutGivenIn(t){let e=z.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetIn===this.id,t.assetOut===this.id,t.decimalsIn,t.decimalsOut)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:r,decimals:n})=>({asset_id:e,amount:r,decimals:n}));return JSON.stringify(t,Dt.jsonFormatter)}getAssets(t,e){let r={asset_id:Number(t),amount:e.toString()};return JSON.stringify([r],Dt.jsonFormatter)}normalizeSpot(t,e,r,n,i){return e?t*be.big.pow10(be.RUNTIME_DECIMALS-i):r?t/be.big.pow10(i-n):t}};var or=require("polkadot-api"),$n=require("@polkadot-api/utils"),Xn=require("@noble/hashes/blake2b"),tt=require("rxjs"),lr=require("@galacticcouncil/common");var{FeeUtils:as}=_,ye=class extends Q{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=z.getPoolAddress(t),r=(0,Xn.blake2b)(e,{dkLen:32}),n=(0,$n.toHex)(r);return(0,or.AccountId)(lr.HYDRATION_SS58_PREFIX).dec(n)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:r,final_amplification:n,initial_block:i,final_block:s}=t,a=z.calculateAmplification(r.toString(),n.toString(),i.toString(),s.toString(),e.toString()),o=Number(a)<n;return{amplification:BigInt(a),isRampPeriod:o}}async getPoolTokens(t,e){let r=this.getPoolAddress(t),n=e.assets.map(async i=>{let[s,a,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,i),this.api.query.AssetRegistry.Assets.getValue(i),this.balance.getBalance(r,i)]);return{id:i,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:o.transferable,tradeable:s,type:a?.asset_type.type}});return Promise.all(n)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(or.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e,r]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:"best"}),this.api.query.System.Number.getValue({at:"best"}),this.getPoolLimits()]),n=t.map(async({keyArgs:i,value:s})=>{let[a]=i,o=this.getPoolAddress(a),[l,u,p]=await Promise.all([this.getPoolTokens(a,s),this.api.query.Stableswap.PoolPegs.getValue(a,{at:"best"}),this.api.query.Tokens.TotalIssuance.getValue(a,{at:"best"})]),d=this.getPoolAmplification(s,e),m=u?this.getRecentPegs(u):this.getDefaultPegs(s);return l.push({id:a,tradeable:15,balance:p,decimals:lr.RUNTIME_DECIMALS}),this.poolsData.set(a,s),{address:o,id:a,type:"Stableswap",fee:as.fromPermill(s.fee),tokens:l,totalIssuance:p,pegs:m,...r,...d}});return Promise.all(n)}async getPoolFees(t,e){return{fee:this.store.pools.find(n=>n.address===e).fee}}getDefaultPegs(t){return z.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([r,n])=>n.map(i=>i.toString()))}subscribeIssuance(){let e=this.store.pools.map(r=>r.id).map(r=>this.api.query.Tokens.TotalIssuance.watchValue(r,"best").pipe((0,tt.map)((n,i)=>({value:n,index:i})),(0,tt.tap)(({index:n,value:i})=>{n>0&&this.log.trace("tokens.TotalIssuance",r,i)}),(0,tt.map)(({value:n})=>({id:r,value:n}))));return(0,tt.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(r=>{let{id:n,value:i}=r;this.store.update(s=>{let a=[];return s.filter(o=>o.id===n).forEach(o=>{let l=o.tokens.map(u=>u.id===n?{...u,balance:i}:u);a.push({...o,tokens:l,totalIssuance:i})}),a})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,tt.distinctUntilChanged)((t,e)=>!e.deltas),(0,tt.map)((t,e)=>({value:t,index:e})),(0,tt.tap)(({value:t,index:e})=>{e>0&&this.log.trace("stableswap.PoolPegs",t.deltas?.upserted)}),this.watchGuard("stableswap.PoolPegs")).subscribe({error:t=>this.log.error("stableswap.PoolPegs",t),next:({value:{deltas:t}})=>{this.store.update(e=>{let r=[],n=new Map(e.map(i=>[i.id,i]));return t?.upserted.forEach(({args:i,value:s})=>{let[a]=i,o=n.get(a);if(o){let l=this.getRecentPegs(s);r.push({...o,pegs:l})}}),r})}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(e=>{let r=[];return e.filter(n=>n.isRampPeriod).forEach(n=>{let i=this.poolsData.get(n.id);if(i){let s=this.getPoolAmplification(i,t);r.push({...n,...s})}}),r})})}subscribeUpdates(){let t=new tt.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var zr={};R(zr,{XykMath:()=>St,XykPool:()=>fe,XykPoolClient:()=>Pe});var D=require("@galacticcouncil/math-xyk"),St=class{static getSpotPrice(t,e,r){return(0,D.get_spot_price)(t,e,r)}static calculateInGivenOut(t,e,r){return(0,D.calculate_in_given_out)(t,e,r)}static calculateOutGivenIn(t,e,r){return(0,D.calculate_out_given_in)(t,e,r)}static calculatePoolTradeFee(t,e,r){return(0,D.calculate_pool_trade_fee)(t,e,r)}static calculateLiquidityIn(t,e,r){return(0,D.calculate_liquidity_in)(t,e,r)}static calculateSpotPrice(t,e){return(0,D.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,r,n){return(0,D.calculate_spot_price_with_fee)(t,e,r,n)}static calculateShares(t,e,r){return(0,D.calculate_shares)(t,e,r)}static calculateLiquidityOutAssetA(t,e,r,n){return(0,D.calculate_liquidity_out_asset_a)(t,e,r,n)}static calculateLiquidityOutAssetB(t,e,r,n){return(0,D.calculate_liquidity_out_asset_b)(t,e,r,n)}};var jn=require("@galacticcouncil/common");var{FeeUtils:Kn}=_,fe=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let r=new Map(this.tokens.map(s=>[s.id,s])),n=r.get(t),i=r.get(e);if(n==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:n.decimals,decimalsOut:i.decimals,balanceIn:n.balance,balanceOut:i.balance,assetInEd:n.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,r){let n=this.calculateInGivenOut(t,e),i=this.calculateTradeFee(n,r),s=Kn.toPct(r.exchangeFee),a=n+i,o=[];(e<this.minTradingLimit||n<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:n,amountOut:e,feePct:s,errors:o}}validateAndSell(t,e,r){let n=this.calculateOutGivenIn(t,e),i=this.calculateTradeFee(n,r),s=Kn.toPct(r.exchangeFee),a=n-i,o=[];(e<this.minTradingLimit||n<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:n,amountOut:a,feePct:s,errors:o}}calculateInGivenOut(t,e){let r=St.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),n=BigInt(r);return n<0n?0n:n}calculateOutGivenIn(t,e){let r=St.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),n=BigInt(r);return n<0n?0n:n}spotPriceInGivenOut(t){let e=St.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=St.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let r=St.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(r)}normalizeSpot(t,e,r){let n=e-r;if(n===0)return t;let i=jn.big.pow10(Math.abs(n));return n>0?t*i:t/i}};var Qn=require("polkadot-api"),Jn=require("rxjs");var Pe=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,r]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:r}}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(Qn.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries(),this.getPoolLimits()]),r=t.map(async({keyArgs:n,value:i})=>{let[s]=n,[a,o]=i,[l,u,p,d]=await Promise.all([this.balance.getBalance(s,a),this.api.query.AssetRegistry.Assets.getValue(a),this.balance.getBalance(s,o),this.api.query.AssetRegistry.Assets.getValue(o)]);return{address:s,type:"XYK",tokens:[{id:a,decimals:u?.decimals||this.decimals.get(a),existentialDeposit:u?.existential_deposit,balance:l.transferable,type:u?.asset_type.type},{id:o,decimals:d?.decimals||this.decimals.get(o),existentialDeposit:d?.existential_deposit,balance:p.transferable,type:d?.asset_type.type}],...e}});return Promise.all(r)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return Jn.Subscription.EMPTY}};var $r={};R($r,{AavePool:()=>Se,AavePoolClient:()=>ve});var Gt=require("@galacticcouncil/common");var Se=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let r=new Map(this.tokens.map(s=>[s.id,s])),n=r.get(t),i=r.get(e);if(n==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:n.balance,balanceOut:i.balance,decimalsIn:n.decimals,decimalsOut:i.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,r){let n=this.calculateInGivenOut(t,e),i=[];return e>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:n,calculatedIn:n,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e,r){let n=this.calculateOutGivenIn(t,e),i=[];return n>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:e,calculatedOut:n,amountOut:n,feePct:0,errors:i}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return Gt.big.toBigInt(1,Gt.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return Gt.big.toBigInt(1,Gt.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var ti=require("polkadot-api"),ei=require("@polkadot-api/utils"),ht=require("rxjs"),ri=require("viem"),cr=require("@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:os}=cr.erc20,ls=["Supply","Withdraw","Repay","Borrow"],ve=class extends Q{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let r=t+"/"+e,n=new TextEncoder().encode(r.padEnd(32,"\0")),i=(0,ei.toHex)(n);return(0,ti.AccountId)(cr.HYDRATION_SS58_PREFIX).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:r,atoken:n,liqudity_in:i,liqudity_out:s})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(r),this.api.query.AssetRegistry.AssetLocations.getValue(r),this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n)]);return{address:this.getPoolId(r,n),type:"Aave",tokens:[{id:r,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:i,location:o,type:a?.asset_type.type},{id:n,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:s,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,r]=t.tokens,{liqudity_in:n,liqudity_out:i}=await this.api.apis.AaveTradeExecutor.pool(e.id,r.id,{at:"best"});return t.tokens.map(s=>{let a=s.id===e.id?n:i;return{...s,balance:a}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:r}=e.value;return r.key.asHex()}throw new Error("Invalid aave reserve multilocation")}return os.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:r}=t;return{assetIn:e,assetOut:r,key:`${e}:${r}`}}parseEvmLog(t){let{topics:e,data:r}=t.log,n=e.map(s=>s.asHex()),i=r.asHex();try{let{eventName:s,args:a}=(0,ri.decodeEventLog)({abi:Zn,topics:n,data:i}),o=a.reserve.toLowerCase();return{eventName:s,reserve:o,key:`${s}:${o}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(r=>r.tokens).map(([r,n])=>n).map(r=>r.id);return this.api.event.Router.Executed.watch().pipe((0,ht.map)(({payload:r})=>this.parseRouterLog(r)),(0,ht.filter)(({assetIn:r,assetOut:n})=>e.includes(r)||e.includes(n)),this.watchGuard("router.Execute")).subscribe(({assetIn:r,assetOut:n,key:i})=>{this.log.trace("router.Executed",i),this.store.update(async s=>{let a=[];for(let o of s){let[l,u]=o.tokens;if(u.id===r||u.id===n){let d=await this.getPoolDelta(o);a.push({...o,tokens:d})}}return a})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,ht.map)(({payload:t})=>this.parseEvmLog(t)),(0,ht.filter)(t=>t!==void 0),(0,ht.filter)(({eventName:t})=>ls.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async r=>{let n=[];for(let i of r){let[s]=i.tokens;if(this.getReserveH160Id(s).toLowerCase()===t){let o=await this.getPoolDelta(i);n.push({...i,tokens:o})}}return n})})}subscribeBalances(){return ht.Subscription.EMPTY}subscribeUpdates(){let t=new ht.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var Kr={};R(Kr,{HsmMath:()=>st,HsmPool:()=>we,HsmPoolClient:()=>Ie});var $=require("@galacticcouncil/math-hsm"),st=class{static calculateCollateralInGivenHollarOut(t,e,r){return(0,$.calculate_collateral_in_given_hollar_out)(t,e,r)}static calculateCollateralOutGivenHollarIn(t,e,r){return(0,$.calculate_collateral_out_given_hollar_in)(t,e,r)}static calculateHollarOutGivenCollateralIn(t,e,r){return(0,$.calculate_hollar_out_given_collateral_in)(t,e,r)}static calculateHollarInGivenCollateralOut(t,e,r){return(0,$.calculate_hollar_in_given_collateral_out)(t,e,r)}static calculateImbalance(t,e,r){return(0,$.calculate_imbalance)(t,e,r)}static calculateBuybackLimit(t,e){return(0,$.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,r){return(0,$.calculate_buyback_price_with_fee)(t,e,r)}static calculateMaxPrice(t,e){return(0,$.calculate_max_price)(t,e)}};var X=require("@galacticcouncil/common");var{FeeUtils:Vt}=_,we=class c extends At{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new c(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,r){let n=this.parsePair(t.assetOut,t.assetIn),i=super.calculateInGivenOut(n,e,{fee:this.fee}),s=this.calculateBuybackLimit(t);e>s&&r.push("MaxBuyBackExceeded");let a=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,i)>a&&r.push("MaxBuyPriceExceeded"),i>this.collateralBalance&&r.push("InsufficientCollateral"),r}validateTradeHollarOut(t,e,r){return this.collateralBalance+t>this.maxInHolding&&r.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&r.push("FacilitatorCapacityExceeded"),r}validateTradeConstraints(t,e,r){let n=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,n):this.validateTradeHollarOut(e,r,n)}validateAndBuy(t,e){let r=this.calculateInGivenOut(t,e),n=this.validateTradeConstraints(t,r,e);return{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:n}}validateAndSell(t,e){let r=this.calculateOutGivenIn(t,e),n=this.validateTradeConstraints(t,e,r);return{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:n}}calculateHollarInGivenCollateralOut(t,e){let r=super.calculateInGivenOut(t,e,{fee:this.fee}),n=st.calculateHollarInGivenCollateralOut(e.toString(),r.toString(),Vt.toRaw(this.buyBackFee).toString());return BigInt(n)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),r=st.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),Vt.toRaw(this.purchaseFee).toString());return BigInt(r)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let r=super.calculateOutGivenIn(t,e,{fee:this.fee}),n=st.calculateCollateralOutGivenHollarIn(e.toString(),r.toString(),Vt.toRaw(this.buyBackFee).toString());return BigInt(n)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),r=st.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),Vt.toRaw(this.purchaseFee).toString());return BigInt(r)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),r=st.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(r)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),r=st.calculateBuybackLimit(e.toString(),Vt.toRaw(this.buyBackRate).toString());return BigInt(r)}calculateBuyPrice(t,e,r){let n=st.calculateBuybackPriceWithFee(r.toString(),e.toString(),Vt.toRaw(this.buyBackFee).toString()),[i,s]=JSON.parse(n),a=X.big.pow10(t.decimalsIn+X.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(i)*a/BigInt(s)}calculateMaxPrice(t){let e=this.getCollateralPeg(),r=st.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[n,i]=JSON.parse(r),s=X.big.pow10(X.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(n)*s/BigInt(i)}spotPriceInGivenOut(t){let e=X.big.toBigInt(1,t.decimalsOut),n=this.calculateInGivenOut(t,e)*X.big.pow10(X.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(n,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=X.big.toBigInt(1,t.decimalsIn),n=this.calculateOutGivenIn(t,e)*X.big.pow10(X.RUNTIME_DECIMALS-t.decimalsIn);return this.normalizeSpotPrice(n,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(n=>n.id!==this.hollarId),e=this.pegs[t],r=this.tokens[t].decimals;return this.isDefaultPeg(e)?[X.big.toBigInt(1,18).toString(),X.big.toBigInt(1,r).toString()]:e}isDefaultPeg(t){let[e,r]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&r==="1"}normalizeSpotPrice(t,e,r){let n=e-r;if(n===0)return t;let i=X.big.pow10(Math.abs(n));return n>0?t*i:t/i}};var ur=require("polkadot-api"),ii=require("@polkadot-api/utils"),K=require("rxjs"),si=require("viem"),pr=require("@galacticcouncil/common");var xe=[{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 Te=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[r,n]=await this.client.readContract({abi:xe,address:t,functionName:"getFacilitatorBucket",args:[e]});return r-n}};var{FeeUtils:Xr}=_,{H160:ni}=pr.h160,cs=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Ie=class extends Q{ghoClient;stableClient;constructor(t,e,r){super(t,e),this.stableClient=r,this.ghoClient=new Te(e)}getPoolType(){return"HSM"}getPoolId(t){return this.getPoolAddress("hsm:"+t)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(t){if(t){let e=t.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:r}=e.value;return r.key.asHex()}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),r=new TextEncoder().encode(e),n=(0,ii.toHex)(r);return(0,ur.AccountId)(pr.HYDRATION_SS58_PREFIX).dec(n)}async isSupported(){let t=this.api.query.HSM.Collaterals,e=await this.api.compatibilityToken;return t.isCompatible(ur.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,r,n]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t),this.api.query.HSM.Collaterals.getEntries({at:"best"}),this.stableClient.getPools()]);if(r.length===0)return[];let i=this.getFacilitatorAddress(),s=ni.fromAny(i),a=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(a,s),l=r.map(async({keyArgs:p,value:d})=>{let[m]=p,{pool_id:h,max_buy_price_coefficient:b,max_in_holding:g,purchase_fee:f,buy_back_fee:y,buyback_rate:v}=d,S=n.find(T=>T.id===h);if(S){let T=this.getPoolId(h),A=await this.balance.getBalance(i,m);return{...S,address:T,type:"HSM",tokens:S.tokens.filter(N=>N.id!==h),hsmAddress:i,hsmMintCapacity:o,hollarId:t,hollarH160:a,collateralId:m,collateralBalance:A.transferable,maxBuyPriceCoefficient:b,maxInHolding:g,purchaseFee:Xr.fromPermill(f),buyBackFee:Xr.fromPermill(y),buyBackRate:Xr.fromPerbill(v)}}});return(await Promise.all(l)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:r}=t.log,n=e.map(s=>s.asHex()),i=r.asHex();try{let{eventName:s,args:a}=(0,si.decodeEventLog)({abi:xe,topics:n,data:i}),o=a.facilitatorAddress.toLowerCase();return{eventName:s,facilitator:o,key:`${s}:${o}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,K.map)(({payload:t})=>this.parseEvmLog(t)),(0,K.filter)(t=>t!==void 0),(0,K.filter)(({eventName:t})=>cs.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async r=>{let n=[],[{hsmAddress:i,hollarH160:s}]=r,a=ni.fromAny(i);if(a.toLowerCase()===e){let l=await this.ghoClient.getFacilitatorCapacity(s,a);for(let u of r)n.push({...u,hsmMintCapacity:l})}return n})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(i=>{let{tokens:s,collateralId:a}=i;s.find(l=>l.id===a).type==="Erc20"?e.push(a):t.push(a)});let[{hsmAddress:r}]=this.store.pools,n=[];if(t.length>0){let i=this.balance.watchTokensBalance(r);n.push(i)}if(e.length>0){let i=this.balance.watchErc20Balance(r,e);n.push(i)}return n.length>0?(0,K.combineLatest)(n).pipe((0,K.map)(i=>i.flat()),(0,K.pairwise)(),(0,K.map)(([i,s])=>this.balance.getDeltas(i,s)),this.watchGuard("balances")).subscribe(i=>{this.store.update(s=>{let a=[],o=new Map(s.map(l=>[l.collateralId,l]));return i.forEach(({id:l,balance:u})=>{let p=o.get(l);p&&(this.log.trace("balances",{id:l,balance:u}),a.push({...p,collateralBalance:u.transferable}))}),a})}):K.Subscription.EMPTY}subscribeStableswapUpdates(){return this.stableClient.getSubscriber().pipe(this.watchGuard("stableswap.updates")).subscribe(t=>{let e=new Map(t.map(r=>[r.id,r]));this.store.update(r=>{let n=[];for(let i of r){let s=e.get(i.id);s&&n.push({...i,fee:s.fee,tokens:s.tokens.filter(a=>a.id!==i.id),totalIssuance:s.totalIssuance,pegs:s.pegs,amplification:s.amplification,isRampPeriod:s.isRampPeriod})}return n})})}subscribeBalances(){return K.Subscription.EMPTY}subscribeUpdates(){let t=new K.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var Ut=class{static get(t){switch(t.type){case"Aave":return Se.fromPool(t);case"XYK":return fe.fromPool(t);case"Omnipool":return ge.fromPool(t);case"LBP":return me.fromPool(t);case"Stableswap":return At.fromPool(t);case"HSM":return we.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var ai=require("@galacticcouncil/common"),lt=require("rxjs");var{logger:us}=ai.log,Wt=class extends L{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=lt.Subscription.EMPTY;omniSub=lt.Subscription.EMPTY;stableSub=lt.Subscription.EMPTY;hsmSub=lt.Subscription.EMPTY;xykSub=lt.Subscription.EMPTY;lbpSub=lt.Subscription.EMPTY;isReady=!1;isDestroyed=new lt.Subject;constructor(t,e){super(t),this.evm=e,this.aave=new ve(t,e),this.omnipool=new he(t,e),this.stableswap=new ye(t,e),this.hsm=new Ie(t,e,this.stableswap),this.xyk=new Pe(t,e),this.lbp=new de(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe((0,lt.takeUntil)(this.isDestroyed)).subscribe(e=>{e.forEach(r=>{this.pools.set(r.address,r)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.active.has("Stableswap")||(us.info("[PoolContextProvider] auto-activating stableswap"),this.withStableswap()),this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let r=this.clients.find(n=>n.getPoolType()===e.type);if(r)return r.getPoolFees(t,e.address);throw new re(e.type)}};var nn={};R(nn,{DCA_TIME_RESERVE:()=>ci,DEFAULT_BLOCK_TIME:()=>li,DEFAULT_MIN_BUDGET:()=>Zr,ORDER_MIN_BLOCK_PERIOD:()=>ui,Router:()=>Yt,TWAP_EXECUTION_INTERVAL:()=>Be,TWAP_MAX_DURATION:()=>en,TWAP_MAX_PRICE_IMPACT:()=>tn,TWAP_TX_MULTIPLIER:()=>Qp,TradeOrderError:()=>Jr,TradeOrderType:()=>dr,TradeRouteBuilder:()=>et,TradeRouter:()=>Tt,TradeScheduler:()=>zt,TradeType:()=>mr});var _e=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 ps=10,Oe=class{isNotVisited(t,e){let r=!0;return e.forEach(n=>{(n[0]===t[0]||n[1]===t[1])&&(r=!1)}),r}findPaths(t,e,r){let n=[],i=new _e,s=[];for(s.push([e,""]),i.enqueue(s);i.size()>0;){let a=i.dequeue();if(!a||a.length>ps)continue;let o=a[a.length-1];(r===null||o[0]===r)&&n.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let p=[...a];p.push(u),i.enqueue(p)}})}return n}findShortestPaths(t,e,r){let n=[],i=new _e,s=[];s.push([e,""]),i.enqueue(s);let a=1/0;for(;i.size()>0;){let o=i.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===r){o.length<a?(a=o.length,n.length=0,n.push(o)):o.length===a&&n.push(o);continue}let u=t.get(l[0]);for(let p of u??[])this.isNotVisited(p,o)&&i.enqueue([...o,p])}return n}buildAndPopulateGraph(t,e){let r=new Map;for(let n of t)r.set(parseInt(n),[]);for(let[n,i,s]of e)r.get(i)?.push([s,n]);return r}};function Qr(c){let t={};for(let e of c){let r=e.tokens.length;for(let n=0;n<r;n++){t[e.tokens[n].id]||(t[e.tokens[n].id]=[]);for(let i=0;i<r;i++){if(n==i)continue;let s=[e.address,e.tokens[n].id,e.tokens[i].id];t[e.tokens[n].id].push(s)}}}return t}var Ae=class{getProposals(t,e,r){let n=r.filter(g=>g.type==="XYK"),i=r.filter(g=>g.type!=="XYK"),s=new Set(i.map(g=>g.tokens).flat().map(g=>g.id)),a=s.has(t),o=s.has(e),l=new Oe,u=g=>{let f=Qr(g),y=Object.keys(f),v=y.flatMap(S=>f[S]);return l.buildAndPopulateGraph(y,v)};if(!a&&!o){let g=n.filter(v=>v.tokens.find(S=>S.id===t)||v.tokens.find(S=>S.id===e)),f=u(g),y=l.findPaths(f,t,e);return this.parsePaths(y)}if(a&&o){let g=u(i),f=l.findPaths(g,t,e);return this.parsePaths(f)}let p=a?e:t,d=n.filter(g=>g.tokens.some(f=>f.id===p));if(d.length===0)return[];let m=[...i,...d],h=u(m),b=l.findPaths(h,t,e);return this.parsePaths(b)}parsePaths(t){let e=[];for(let r of t){let n=[];for(let i=0;i<r.length;i++){let s=r[i],a=r[i+1];if(a==null)break;n.push(this.toEdge(s,a))}e.push(n)}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 Ae,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,r){return`${t}->${e}::${r.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:r=[]}=this.filter,n=new Set(e),i=new Set(r);return t.filter(s=>i.has(s.type)?!1:n.size>0?n.has(s.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let r=await this.getPools();return this.validateInput(t,e,r),this.getPaths(t,e,r)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(n=>n!==t).map(n=>this.getRoutes(n,t)))).filter(n=>n.length>0).map(([n])=>n[0].assetIn).sort()}validateInput(t,e,r){if(r.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let n=this.getAssets(r);if(!n.has(t))throw new Error(t+" is not supported asset");if(!n.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(r)}getAssets(t){let e=t.map(r=>r.tokens.map(n=>n.id)).flat().sort((r,n)=>r>n?1:-1);return new Set(e)}getPaths(t,e,r){let n=this.toPoolsMap(r);return this.getProposals(t,e,r).filter(s=>this.validPath(s,n)).map(s=>this.toHops(s,n))}getProposals(t,e,r){let n=this.buildRouteKey(t,e,r);if(this.routeProposals.has(n))return this.routeProposals.get(n);let i=this.routeSuggester.getProposals(t,e,r);return this.routeProposals.set(n,i),i}validPath(t,e){return t.length>0&&t.map(r=>this.validEdge(r,e)).reduce((r,n)=>r&&n)}validEdge([t,e,r],n){return n.get(t)?.validatePair(e,r)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Ut.get(e)]))}toHops(t,e){return t.map(([r,n,i])=>{let s=e.get(r);return{poolAddress:r,poolId:s?.id,pool:s?.type,assetIn:n,assetOut:i}})}};var I=require("@galacticcouncil/common");var mr=(e=>(e.Buy="Buy",e.Sell="Sell",e))(mr||{}),dr=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(dr||{}),Jr=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(Jr||{});var{FeeUtils:oi}=_,Tt=class extends Yt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,r){let n=super.validateInput(t,e,r),i=super.getPaths(t,e,r);if(!i.length)throw new ne(t,e);return{paths:i,pools:r,poolsMap:n}}async withCtx(t,e,r){let n=await super.getPools(),i=this.buildCtxSync(t,e,n);return r(i)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((r,n)=>{let i=r[r.length-1].amountOut,s=n[n.length-1].amountOut;return i>s?-1:1});return e.find(r=>r.every(n=>n.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(r=>r.tradeFeeRange).length>0){let r=t.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,s)=>i+s),n=t.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,s)=>i+s);return[r,n]}}getPoolFeeRange(t,e){let r=t.min?oi.toPct(t.min):void 0,n=t.max?oi.toPct(t.max):void 0;if(r&&n)return[r,Math.max(n,e)]}async getBestSell(t,e,r){return this.getSell(t,e,r)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,r,n){return this.withCtx(t,e,async({paths:i,poolsMap:s})=>{let a;if(n)a=await this.toSellSwaps(r,n,s);else{let o=i.map(u=>this.toSellSwaps(r,u,s)),l=await Promise.all(o);a=this.findBestSellRoute(l)}return this.buildSell(s,a)})}async getSells(t,e,r){return this.withCtx(t,e,async({paths:n,poolsMap:i})=>{let s=n.map(o=>this.toSellSwaps(r,o,i));return(await Promise.all(s)).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 r=e[0],n=e[e.length-1],i=this.isDirectTrade(e),s=this.getSellSpot(e),a=n.amountOut,o=i?n.calculatedOut:this.calculateDelta0Y(r.amountIn,e,t),l=o-a,u=this.getRouteFeeRange(e),p=i?n.tradeFeePct:W.calculateSellFee(o,a),d=q.mulSpot(r.amountIn,s,r.assetInDecimals,n.assetOutDecimals),m=W.calculateDiffToRef(o,d);return{type:"Sell",amountIn:r.amountIn,amountOut:n.amountOut,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Sell",amountIn:I.big.toDecimal(r.amountIn,r.assetInDecimals),amountOut:I.big.toDecimal(n.amountOut,n.assetOutDecimals),spotPrice:I.big.toDecimal(s,I.RUNTIME_DECIMALS),tradeFee:I.big.toDecimal(l,n.assetOutDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e.map(h=>h.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,r)=>e*r/10n**BigInt(I.RUNTIME_DECIMALS))}calculateDelta0Y(t,e,r){let n=[];for(let i=0;i<e.length;i++){let s=e[i],a=r.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;i>0?l=n[i-1]:l=t;let u=a.calculateOutGivenIn(o,l);n.push(u)}return n[n.length-1]}async calculateMostLiquidRoute(t,e,r){let{paths:n,pools:i,poolsMap:s}=r,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],u=q.getFraction(l,.1),p=await Promise.all(n.map(b=>this.toSellSwaps(u,b,s))),m=this.findBestSellRoute(p).map(b=>({poolAddress:b.poolAddress,poolId:b?.poolId,pool:b.pool,assetIn:b.assetIn,assetOut:b.assetOut})),h=this.buildRouteKey(t,e,i);return this.mlr.set(h,m),m}async toSellSwaps(t,e,r){let n=[];for(let i=0;i<e.length;i++){let s=e[i],a=r.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;i>0?l=n[i-1].amountOut:l=typeof t=="string"?I.big.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(o,a),{amountOut:p,calculatedOut:d,feePct:m,errors:h}=a.validateAndSell(o,l,u),b=this.getPoolFeeRange(u,m),g=a.spotPriceOutGivenIn(o),f=q.mulSpot(l,g,o.decimalsIn,o.decimalsOut),y=W.calculateDiffToRef(d,f);n.push({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===s.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===s.assetIn},toHuman(){return{...s,amountIn:I.big.toDecimal(l,o.decimalsIn),amountOut:I.big.toDecimal(p,o.decimalsOut),calculatedOut:I.big.toDecimal(d,o.decimalsOut),spotPrice:I.big.toDecimal(g,I.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h}}})}return n}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async r=>{let n=this.buildRouteKey(t,e,r.pools),i=this.mlr.get(n);return i||this.calculateMostLiquidRoute(t,e,r)})}async getSpotPrice(t,e){return this.withCtx(t,e,async r=>{let{pools:n,poolsMap:i}=r,s=this.buildRouteKey(t,e,n),a=this.mlr.get(s);a||(a=await this.calculateMostLiquidRoute(t,e,r));let o=await this.toSellSwaps("1",a,i);return{amount:this.getSellSpot(o),decimals:I.RUNTIME_DECIMALS}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((r,n)=>{let i=r[0].amountIn,s=n[0].amountIn;return i>s?1:-1});return e.find(r=>r.every(n=>n.errors.length==0))||e[0]}async getBestBuy(t,e,r){return this.getBuy(t,e,r)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,r,n){return this.withCtx(t,e,async({paths:i,poolsMap:s})=>{let a;if(n)a=await this.toBuySwaps(r,n,s);else{let o=i.map(u=>this.toBuySwaps(r,u,s)),l=await Promise.all(o);a=this.findBestBuyRoute(l)}return this.buildBuy(s,a)})}async getBuys(t,e,r){return this.withCtx(t,e,async({paths:n,poolsMap:i})=>{let s=n.map(o=>this.toBuySwaps(r,o,i));return(await Promise.all(s)).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 r=e[e.length-1],n=e[0],i=this.isDirectTrade(e),s=this.getBuySpot(e),a=n.amountIn,o=i?n.calculatedIn:this.calculateDelta0X(r.amountOut,e,t),l=a-o,u=this.getRouteFeeRange(e),p=i?n.tradeFeePct:W.calculateBuyFee(o,a),d=q.mulSpot(r.amountOut,s,r.assetOutDecimals,n.assetInDecimals),m;return o===0n?m=-100:m=W.calculateDiffToRef(d,o),{type:"Buy",amountOut:r.amountOut,amountIn:n.amountIn,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Buy",amountOut:I.big.toDecimal(r.amountOut,r.assetOutDecimals),amountIn:I.big.toDecimal(n.amountIn,n.assetInDecimals),spotPrice:I.big.toDecimal(s,I.RUNTIME_DECIMALS),tradeFee:I.big.toDecimal(l,n.assetInDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e.map(h=>h.toHuman())}}}}calculateDelta0X(t,e,r){let n=[];for(let i=e.length-1;i>=0;i--){let s=e[i],a=r.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;i==e.length-1?l=t:l=n[0];let u=a.calculateInGivenOut(o,l);n.unshift(u)}return n[0]}async toBuySwaps(t,e,r){let n=[];for(let i=e.length-1;i>=0;i--){let s=e[i],a=r.get(s.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(s.assetIn,s.assetOut),l;i==e.length-1?l=typeof t=="string"?I.big.toBigInt(t,o.decimalsOut):t:l=n[0].amountIn;let u=await this.ctx.getPoolFees(o,a),{amountIn:p,calculatedIn:d,feePct:m,errors:h}=a.validateAndBuy(o,l,u),b=this.getPoolFeeRange(u,m),g=a.spotPriceInGivenOut(o),f=q.mulSpot(l,g,o.decimalsOut,o.decimalsIn),y;d===0n?y=-100:y=W.calculateDiffToRef(f,d),n.unshift({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===s.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===s.assetIn},toHuman(){return{...s,amountOut:I.big.toDecimal(l,o.decimalsOut),amountIn:I.big.toDecimal(p,o.decimalsIn),calculatedIn:I.big.toDecimal(d,o.decimalsIn),spotPrice:I.big.toDecimal(g,I.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h}}})}return n}};var V=require("@galacticcouncil/common");var li=6e3,Zr=1000000000000000n,Be=6,tn=-5,en=216e5,Qp=3,ci=.1,ui=6;var rn=require("polkadot-api");var et=class{static build(t){return t.map(({assetIn:e,assetOut:r,pool:n,poolId:i})=>n==="Stableswap"?{pool:(0,rn.Enum)("Stableswap",i),asset_in:e,asset_out:r}:{pool:(0,rn.Enum)(n),asset_in:e,asset_out:r})}};var zt=class{schedulerOptions;router;constructor(t,e={}){this.router=new Tt(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Zr})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,r,n,i){let s=await this.router.getBestSell(t,e,r),{amountIn:a,swaps:o,priceImpactPct:l}=s,u=o[0],p=o[o.length-1],{assetInDecimals:d}=u,{assetOutDecimals:m}=p,h=Math.abs(l),b=await this.getMinimumOrderBudget(t,d),g=this.getOptimalTradeCount(h),f=this.getMaximumTradeCount(a,b,n),y=i||Math.min(g,f),v=Math.round(n/y),S=a/BigInt(y),T=await this.router.getBestSell(t,e,S),A=a<b,N=[];A&&N.push("OrderTooSmall");let U=T.amountOut*BigInt(y),ct=this.toBlockPeriod(v),bt=T.tradeFee*BigInt(y),J=et.build(o),nt={assetIn:t,assetOut:e,errors:N,maxTradeCount:f,tradeCount:y,tradeFee:bt,tradeImpactPct:T.priceImpactPct,tradePeriod:ct,tradeRoute:J,type:"Dca"};return{...nt,amountIn:a,amountOut:U,tradeAmountIn:T.amountIn,tradeAmountOut:T.amountOut,toHuman(){return{...nt,amountIn:V.big.toDecimal(a,d),amountOut:V.big.toDecimal(U,m),tradeAmountIn:V.big.toDecimal(T.amountIn,d),tradeAmountOut:V.big.toDecimal(T.amountOut,m)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let r=await this.router.getSpotPrice(0,t);if(r)return q.mulSpot(this.minOrderBudget,r.amount,12,e);let n=await this.router.getSpotPrice(t,0);if(n)return q.divSpot(this.minOrderBudget,n.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,r){let n=e*2n/10n;if(n===0n)return 0;let i=Number(t/n),s=Math.floor(r/this.blockTime),a=Math.max(0,Math.floor(s*(1-.1)));return Math.min(i,a)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,r,n){let i=await this.router.getBestSell(t,e,r),{swaps:s}=i,a=s[0],o=s[s.length-1],{assetInDecimals:l}=a,{assetOutDecimals:u}=o,p=await this.getMinimumOrderBudget(t,l),d=i.amountIn<p,m=[];d&&m.push("OrderTooSmall");let h=this.toBlockPeriod(n),b=et.build(s),g={assetIn:t,assetOut:e,errors:m,maxTradeCount:0,tradeCount:0,tradeFee:i.tradeFee,tradeImpactPct:i.priceImpactPct,tradePeriod:h,tradeRoute:b,type:"Dca"};return{...g,amountIn:0n,amountOut:0n,tradeAmountIn:i.amountIn,tradeAmountOut:i.amountOut,toHuman(){return{...g,amountIn:"0",amountOut:"0",tradeAmountIn:V.big.toDecimal(i.amountIn,l),tradeAmountOut:V.big.toDecimal(i.amountOut,u)}}}}async getTwapSellOrder(t,e,r){let n=await this.router.getBestSell(t,e,r),{amountIn:i,swaps:s,priceImpactPct:a}=n,o=s[0],l=s[s.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),h=i/BigInt(m),[b,g]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestSell(o.assetIn,l.assetOut,h)]),f=m===1,y=i<b,v=g.priceImpactPct<-5,S=[];y||f?S.push("OrderTooSmall"):v&&S.push("OrderImpactTooBig");let T=g.amountOut*BigInt(m),A=g.tradeFee*BigInt(m),N=et.build(s),U={assetIn:t,assetOut:e,errors:S,tradeCount:m,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:N,type:"TwapSell"};return{...U,amountIn:i,amountOut:T,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:A,toHuman(){return{...U,amountIn:V.big.toDecimal(i,u),amountOut:V.big.toDecimal(T,p),tradeAmountIn:V.big.toDecimal(g.amountIn,u),tradeAmountOut:V.big.toDecimal(g.amountOut,p),tradeFee:V.big.toDecimal(A,p)}}}}async getTwapBuyOrder(t,e,r){let n=await this.router.getBestBuy(t,e,r),{amountOut:i,swaps:s,priceImpactPct:a}=n,o=s[0],l=s[s.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),h=i/BigInt(m),[b,g]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestBuy(o.assetIn,l.assetOut,h)]),f=g.amountIn*BigInt(m),y=m===1,v=f<b,S=g.priceImpactPct<-5,T=[];v||y?T.push("OrderTooSmall"):S&&T.push("OrderImpactTooBig");let A=g.tradeFee*BigInt(m),N=et.build(s),U={assetIn:t,assetOut:e,errors:T,tradeCount:m,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:N,type:"TwapBuy"};return{...U,amountIn:f,amountOut:i,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:A,toHuman(){return{...U,amountIn:V.big.toDecimal(f,u),amountOut:V.big.toDecimal(i,p),tradeAmountIn:V.big.toDecimal(g.amountIn,u),tradeAmountOut:V.big.toDecimal(g.amountOut,p),tradeFee:V.big.toDecimal(A,u)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let n=216e5/(this.blockTime*6);return Math.round(n)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,r=Math.round(e);return Math.max(r,6)}};var an={};R(an,{BIG_10:()=>bi,BIG_BILL:()=>sn,StakingApi:()=>Re,StakingClient:()=>Fe});var j=require("@galacticcouncil/math-staking"),rt=vt(require("big.js"));var gr={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},pi=c=>Object.keys(gr).includes(c);var mi=require("polkadot-api"),di=require("@polkadot-api/utils"),gi=require("@galacticcouncil/common");function hi(c){let t=("modl"+c).padEnd(32,"\0"),e=new TextEncoder().encode(t),r=(0,di.toHex)(e);return(0,mi.AccountId)(gi.HYDRATION_SS58_PREFIX).dec(r)}var hr="20000000000000000",br="2000",bi=(0,rt.default)(10),sn=(0,rt.default)(bi.pow(12)),Re=class{client;balance;constructor(t,e){this.client=t,this.balance=e}async getPotBalance(){let t=await this.client.getPalletId(),e=hi(t);return await this.balance.getBalance(e,0)}async getStakingPosition(t){let[e,r]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let n=e.created_at,i=await r.reduce(async(s,[a,o])=>{let l=await s,u=a,p=o.amount,d=o.conviction.type.toLowerCase(),m=await this.client.getReferendumInfo(u);return m&&(m.type==="Approved"||m.type==="Rejected")&&pi(d)&&l.push({id:u,amount:p,conviction:d}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:n,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(),[r,n]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),i=n.find(s=>s)?.itemId;return{totalStake:r?.total_stake,accumulatedRewardPerStake:r?.accumulated_reward_per_stake,potReservedBalance:r?.pot_reserved_balance,positionId:i,stakePosition:i?await this.getStakingPosition(i):void 0}}getCurrentActionPoints(t,e,r,n){let i=(0,rt.default)(0),s=(0,rt.default)(0),a=gr.locked6x,o=(0,rt.default)(r.toString()).mul(a),l=100,u=[];t.forEach(m=>{let h=gr[m.conviction],b=n.includes(m.id.toString());b&&u.push(m.id.toString());let g=(0,rt.default)(m.amount.toString()).mul(l).div(o);i=i.plus(Math.floor(g.mul(h).toNumber())),s=s.plus(Math.floor(g.mul(b?a:h).toNumber()))});let p=Math.floor((0,rt.default)(r.toString()).mul(a).mul(l).div(o).toNumber());n.forEach(m=>{u.includes(m)||(s=s.plus(p))});let d={democracyVote:1};return i=i.mul(d.democracyVote),i=i.plus(e.toString()||"0"),s=s.mul(d.democracyVote),s=s.plus(e.toString()||"0"),{currentActionPoints:i.toString(),maxActionPoints:s.toString()}}async getRewards(t,e,r){let n=await this.getStake(t),{potReservedBalance:i,accumulatedRewardPerStake:s,totalStake:a,stakePosition:o}=n;if(!o)return;let[l,u,p,d,m,h,b]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),g=(0,rt.default)(l.transferable.toString()).minus(i.toString()),f=g.gt(0)&&a>0?(0,j.calculate_accumulated_rps)(s.toString(),g.toString(),a.toString()):s.toString(),y=(0,j.calculate_period_number)(u.toString(),r,b),v=(0,j.calculate_period_number)(u.toString(),o.createdAt.toString(),b),S=(0,j.calculate_rewards)(f,o.rewardPerStake.toString(),o.stake.toString()),T=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),A=(0,j.calculate_points)(v,y,d.toString(),m.toString(),T.currentActionPoints,h.toString(),o.accumulatedSlashPoints.toString()),N=(0,j.sigmoid)(A,hr,br),U=(()=>{if(!e.length)return;let Kt=(0,j.calculate_points)(v,y,d.toString(),m.toString(),T.maxActionPoints.toString(),h.toString(),o.accumulatedSlashPoints.toString());return(0,j.sigmoid)(Kt,hr,br)})(),ct=(0,rt.default)(S).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if((0,rt.default)(y).minus(v).lte(p.toString()))return{rewards:"0",payablePercentage:N,extraPayablePercentage:U,constants:{a:hr,b:br}};let bt=(0,j.calculate_percentage_amount)(ct.toString(),N),J=(0,rt.default)(o.accumulatedLockedRewards.toString()),nt=J.gt(bt)?J:(0,rt.default)(bt);return{rewards:nt.div(sn).toString(),maxRewards:ct.div(sn).toString(),allocatedRewardsPercentage:nt.div(ct).mul(100).toNumber(),points:A,payablePercentage:N,extraPayablePercentage:U,constants:{a:hr,b:br}}}};var Fe=class extends L{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:s})=>{let[a,o,l]=s;return{address:a,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var ln={};R(ln,{TxBuilderFactory:()=>Xt});var on=require("polkadot-api");function yr(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var $t=class extends L{evm;evmClient;balance;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new ut(t)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:async r=>{let n=await this.dryRun(r,e);if(n.success&&!n.value.execution_result.success){let i=yr(n.value.execution_result.value.error.value);throw new Error("Dry run execution error!",{cause:i})}return n}}}dispatchWithExtraGas(t,e=It){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:e})}async dryRun(t,e){let r=(0,on.Enum)("Signed",t),n=(0,on.Enum)("system",r);return await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(n,e.decodedCall)}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var fr=class extends $t{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let{assetIn:n}=e[0],i=await this.balance.getBalance(this.beneficiary,n);return t>=i.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:r}=this.trade,n=r[0],i=r[r.length-1],s=q.getFraction(t,this.slippagePct),a=n.assetIn,o=i.assetOut,l=t+s,u;return this.isDirectOmnipoolTrade(r)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:et.build(r)}),u=await this.applyExtraGas(this.beneficiary,u,r),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:r}=this.trade,n=r[0],i=r[r.length-1],s=q.getFraction(e,this.slippagePct),a=n.assetIn,o=i.assetOut,l=e-s,u;return this.isDirectOmnipoolTrade(r)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:et.build(r)}),u=await this.applyExtraGas(this.beneficiary,u,r),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,r=e[0],n=e[e.length-1],i=q.getFraction(t,this.slippagePct),s=r.assetIn,a=n.assetOut,o=t-i,l=this.api.tx.Router.sell_all({asset_in:s,asset_out:a,min_amount_out:o,route:et.build(e)});return l=await this.applyExtraGas(this.beneficiary,l,e),this.wrapTx("RouterSellAll",l)}async applyExtraGas(t,e,r){if(!r.some(a=>a.pool==="Aave"))return e;let i=await this.dryRun(t,e),s=this.getDryRunError(i);return!s||!s.includes("OutOfGas")?e:this.estimateExtraGas(t,e)}async estimateExtraGas(t,e){let r=this.dispatchWithExtraGas(e,0n),n=this.dispatchWithExtraGas(e,It),[i,s]=await Promise.all([r.getPaymentInfo(t),this.dryRun(t,n)]);if(this.getDryRunError(s))return n;let o=BigInt(i.weight.ref_time),l=this.getActualRefTime(s);if(l<=o)return n;let d=(l-o)/Ir*110n/100n,m=d>It?It:d;return this.dispatchWithExtraGas(e,m)}getDryRunError(t){if(!t.success)return"DryRun call failed";let e=t.value.execution_result;return e.success?null:yr(e.value.error.value)}getActualRefTime(t){if(!t.success)return 0n;let e=t.value.execution_result;return e.success?e.value.actual_weight?.ref_time??0n:e.value.post_info?.actual_weight?.ref_time??0n}};var Pr=require("polkadot-api");var Sr=class extends $t{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:r,tradeAmountIn:n,tradePeriod:i,tradeRoute:s}=this.order,a=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:(0,Pr.Enum)("Sell",{asset_in:e,asset_out:r,amount_in:n,min_amount_out:0n,route:s})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",a)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:r,tradeAmountIn:n,tradeAmountOut:i,tradePeriod:s,tradeRoute:a}=this.order,o=q.getFraction(i,this.slippagePct),l=i-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Pr.Enum)("Sell",{asset_in:e,asset_out:r,amount_in:n,min_amount_out:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:r,tradeAmountIn:n,tradeAmountOut:i,tradePeriod:s,tradeRoute:a}=this.order,o=q.getFraction(n,this.slippagePct),l=n+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Pr.Enum)("Buy",{asset_in:e,asset_out:r,amount_out:i,max_amount_in:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var Xt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new fr(this.client,this.evmClient).setTrade(t)}order(t){return new Sr(this.client,this.evmClient).setOrder(t)}};async function ms(c){let t=new Mt(c),e=new ae(c),[r,n]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),i=new Wt(c,e).withAave().withOmnipool().withStableswap().withXyk(),s=new ut(c),a=new Fe(c),o=new pe(c),l=new te(e),u=new Tt(i),p=new zt(i,{blockTime:r,minBudgetInNative:n}),d=new Re(a,s),m=new ue(o,s,{blockTime:r});return{api:{aave:l,router:u,scheduler:p,staking:d,farm:m},client:{asset:new Ft(c),balance:s,evm:e},ctx:{pool:i},tx:new Xt(c,e),destroy:()=>{i.destroy()}}}0&&(module.exports={QueryBus,aave,api,async,calc,client,const:null,createSdkContext,error,evm,farm,fmt,json,math,pool,sor,staking,tx});
|