@galacticcouncil/sdk-next 1.3.0 → 1.5.0-pr333-2f0929e
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 +1 -1
- package/build/index.mjs +1 -1
- package/build/pool/PoolContextProvider.d.ts +4 -0
- package/build/pool/index.cjs +1 -1
- package/build/pool/index.d.ts +1 -0
- package/build/pool/index.mjs +1 -1
- package/build/pool/types.d.ts +3 -1
- package/build/pool/uniswapv3/UniswapV3Math.d.ts +7 -0
- package/build/pool/uniswapv3/UniswapV3Pool.d.ts +46 -0
- package/build/pool/uniswapv3/UniswapV3PoolClient.d.ts +45 -0
- package/build/pool/uniswapv3/abi.d.ts +111 -0
- package/build/pool/uniswapv3/const.d.ts +7 -0
- package/build/pool/uniswapv3/index.d.ts +5 -0
- package/build/pool/uniswapv3/types.d.ts +21 -0
- package/build/sor/index.cjs +1 -1
- package/build/sor/index.mjs +1 -1
- package/build/tx/index.cjs +1 -1
- package/build/tx/index.mjs +1 -1
- package/package.json +4 -1
package/build/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var nn=Object.create;var je=Object.defineProperty;var an=Object.getOwnPropertyDescriptor;var on=Object.getOwnPropertyNames;var ln=Object.getPrototypeOf,cn=Object.prototype.hasOwnProperty;var Hr=(c,t)=>()=>(c&&(t=c(c=0)),t);var E=(c,t)=>{for(var e in t)je(c,e,{get:t[e],enumerable:!0})},Xe=(c,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of on(t))!cn.call(c,i)&&i!==e&&je(c,i,{get:()=>t[i],enumerable:!(r=an(t,i))||r.enumerable});return c},yt=(c,t,e)=>(Xe(c,t,"default"),e&&Xe(e,t,"default")),Tt=(c,t,e)=>(e=c!=null?nn(ln(c)):{},Xe(t||!c||!c.__esModule?je(e,"default",{value:c,enumerable:!0}):e,c)),un=c=>Xe(je({},"__esModule",{value:!0}),c);var le={};var Gi=Hr(()=>{yt(le,require("@polkadot-api/sm-provider"))});var ce={};var Ui=Hr(()=>{yt(ce,require("@polkadot-api/smoldot"))});var ue={};var Vi=Hr(()=>{yt(ue,require("@polkadot-api/known-chains/polkadot"))});var Jn={};E(Jn,{QueryBus:()=>Ft,aave:()=>zr,api:()=>Ur,async:()=>ye,calc:()=>F,client:()=>Xr,const:()=>Kr,createSdkContext:()=>Qn,error:()=>Qr,evm:()=>ti,farm:()=>li,fmt:()=>I,indexer:()=>ui,json:()=>zt,math:()=>$,pool:()=>Si,sor:()=>Ai,staking:()=>ki,tx:()=>Ci});module.exports=un(Jn);var Ur={};E(Ur,{Papi:()=>H,Watcher:()=>oe,getSm:()=>mn,getWs:()=>Gr});var Nt=require("@galacticcouncil/descriptors");var qi=require("@galacticcouncil/common"),qt=require("rxjs");var Pt=require("rxjs"),U=require("rxjs/operators");function Li(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let r=()=>(0,Pt.defer)(()=>(0,Pt.from)(c._request("system_health",[]))).pipe((0,U.timeout)({first:e}),(0,U.map)(()=>"online"),(0,U.catchError)(()=>(0,Pt.of)("offline")));return(0,Pt.of)({state:"offline",delayMs:0}).pipe((0,U.expand)(s=>(0,Pt.timer)(s.delayMs).pipe((0,U.switchMap)(r),(0,U.map)(n=>({state:n,delayMs:t})))),(0,U.skip)(1),(0,U.map)(s=>s.state),(0,U.distinctUntilChanged)(),(0,U.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:pn}=qi.log,oe=class c{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,qt.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Li(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe((0,qt.tap)({error:r=>pn.error(t,r)}),(0,qt.shareReplay)({bufferSize:1,refCount:!0}))}};var H=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(Nt.hydration),this.apiNext=this.client.getTypedApi(Nt.hydrationNext),this.apiIce=this.client.getTypedApi(Nt.hydrationIce),this.watcher=oe.getInstance(this.client),this.at=e??"best"}};var Ni=require("polkadot-api/ws"),Hi=require("polkadot-api/logs-provider"),Gr=(c,t={})=>{let e=typeof c=="string"?c.split(","):c,r=(0,Ni.getWsProvider)(e,t);return(0,Hi.withLogsRecorder)(i=>console.log(i),r),r};async function mn(c){let{getSmProvider:t}=await Promise.resolve().then(()=>(Gi(),le)),{start:e}=await Promise.resolve().then(()=>(Ui(),ce)),{chainSpec:r}=await Promise.resolve().then(()=>(Vi(),ue)),i=e(),s=await i.addChain({chainSpec:r}),n=await i.addChain({chainSpec:c,potentialRelayChains:[s]});return t(()=>n)}var zr={};E(zr,{AAVE_GAS_LIMIT:()=>Yr,AAVE_LENDING_POOL_ADDRESS:()=>Ze,AAVE_POOL_ABI:()=>pe,AAVE_POOL_DATA_PROVIDER:()=>Je,AAVE_POOL_DATA_PROVIDER_ABI:()=>Qe,AAVE_POOL_PROXY:()=>Vr,AAVE_ROUNDING_THRESHOLD:()=>xa,AAVE_UINT_256_MAX:()=>dn,AaveClient:()=>me,AaveLog:()=>de,AaveUtils:()=>Et});var pe=[{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 Qe=[{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 Vr="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Je="0x112b087b60C1a166130d59266363C45F8aa99db0",Ze="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Yr=1000000n,xa=5,dn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var me=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:Qe,address:Je,args:[Ze],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:Qe,address:Je,args:[Ze,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:pe,address:Vr,args:[t],functionName:"getUserAccountData"})}};var Yi=require("polkadot-api"),Wi=require("viem");var de=class{static parse(t){let{topics:e,data:r}=t.log,i=Yi.Binary.toHex(r);try{let{eventName:s,args:n}=(0,Wi.decodeEventLog)({abi:pe,topics:e,data:i}),a=n.reserve.toLowerCase();return{eventName:s,reserve:a,key:`${s}:${a}`}}catch{return}}};var G=Tt(require("big.js")),nt=require("@galacticcouncil/common");var{ERC20:Ht}=nt.erc20,{H160:Wr}=nt.h160,hn=1.01,gn=31536000n,zi=4,tr=-1,er=10n**27n,Et=class{client;constructor(t){this.client=new me(t)}async getSummary(t){let e=Wr.fromAny(t),[r,i,s,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[a]=r,[o,l]=i,[u,p,d,m,h,b]=s,g=nt.big.toDecimal(b,18),f=[];for(let y of o){let S=y.underlyingAsset.toLowerCase(),v=a.find(({underlyingAsset:Nr})=>Nr.toLowerCase()===S);if(!v)throw new Error("Missing pool reserve for "+S);let T=y.scaledATokenBalance,B=v.liquidityIndex,D=v.liquidityRate,J=v.availableLiquidity,Y=v.priceInMarketReferenceCurrency,ft=n+6,tt=this.calculateLinearInterest(D,v.lastUpdateTimestamp,ft),ct=B*tt/er,xt=T*ct/er,ze=Number(l!==0&&l===v.eModeCategoryId?v.eModeLiquidationThreshold:v.reserveLiquidationThreshold)/1e4,$e=v.usageAsCollateralEnabled&&y.usageAsCollateralEnabledOnUser&&y.scaledATokenBalance>0n,Ke=Ht.toAssetId(S);f.push({aTokenBalance:xt,availableLiquidity:J,decimals:Number(v.decimals),isCollateral:$e,priceInRef:Y,reserveId:Ke,reserveAsset:S,reserveLiquidationThreshold:ze})}return{healthFactor:Number(g),currentLiquidationThreshold:Number(nt.big.toDecimal(m,zi)),totalCollateral:u,totalDebt:p,reserves:f}}async hasBorrowPositions(t){let e=Wr.fromAny(t),r=await this.client.getUserAccountData(e),[i,s]=r;return s>0n}async getHealthFactor(t){let e=Wr.fromAny(t),r=await this.client.getUserAccountData(e),[i,s,n,a,o,l]=r;return this.calculateHealthFactorFromBalances(s,i,a)}async getHealthFactorAfterWithdraw(t,e,r){let{totalCollateral:i,totalDebt:s,reserves:n,currentLiquidationThreshold:a}=await this.getSummary(t);if(s===0n)return tr;let o=Ht.fromAssetId(e),l=n.find(S=>S.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(r,u),b=p?h*d/10n**BigInt(u):0n,g=i-b;if(g<=0n)return 0;let f=(0,G.default)(i.toString()).mul(a).minus((0,G.default)(b.toString()).mul(m)).div(g.toString()),y=(0,G.default)(g.toString()).mul(f).div(s.toString()).toFixed(6,G.default.roundDown);return Number(y)}async getHealthFactorAfterSupply(t,e,r){let{totalCollateral:i,totalDebt:s,reserves:n,currentLiquidationThreshold:a}=await this.getSummary(t);if(s===0n)return tr;let o=Ht.fromAssetId(e),l=n.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(r,u)*p/10n**BigInt(u),b=i+h;if(b<=0n)return 0;let g=(0,G.default)(i.toString()).mul(a).plus((0,G.default)(h.toString()).mul(d)).div(b.toString()),f=(0,G.default)(b.toString()).mul(g).div(s.toString()).toFixed(6,G.default.roundDown);return Number(f)}async getHealthFactorAfterSwap(t,e,r,i,s){let{totalDebt:n,reserves:a,healthFactor:o}=await this.getSummary(t);if(n===0n)return tr;let l=Ht.fromAssetId(r),u=Ht.fromAssetId(s),p=a.find(B=>B.reserveAsset===l),d=a.find(B=>B.reserveAsset===u);if(!p)throw new Error(`Missing reserve ctx for ${l}`);if(!d)throw new Error(`Missing reserve ctx for ${d}`);let m=nt.big.toBigInt(e,p.decimals),h=nt.big.toBigInt(i,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),v=(d.isCollateral?(0,G.default)(g.toString()).mul(d.reserveLiquidationThreshold):(0,G.default)(0)).minus(f).div(n.toString()),T=(0,G.default)(o).plus(v).toFixed(6,G.default.roundDown);return Number(T)}async getMaxWithdraw(t,e){let{totalDebt:r,reserves:i,healthFactor:s}=await this.getSummary(t),n=Ht.fromAssetId(e),a=i.find(o=>o.reserveAsset===n);if(!a)throw new Error("Missing reserve ctx for "+n);return this.calculateWithdrawMax(a,r,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:r,healthFactor:i}=await this.getSummary(t),s={};for(let n of r){let a=this.calculateWithdrawMax(n,e,i);n.reserveId&&(s[n.reserveId]=a)}return s}calculateWithdrawMax(t,e,r){let{aTokenBalance:i,availableLiquidity:s,decimals:n,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=t,u=i;if(l&&e>0n){let d=r-hn;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**n).toFixed(0,G.default.roundDown);u=i<BigInt(h)?i:BigInt(h)}else u=0n}return{amount:u<s?u:s,decimals:n}}calculateLinearInterest(t,e,r){let i=r-e;if(i<=0)return er;let s=t*BigInt(i)/gn;return er+s}calculateHealthFactorFromBalances(t,e,r){if(t===0n)return tr;let i=e*r/t,s=nt.big.toDecimal(i,zi);return Number(s)}};var Xr={};E(Xr,{AssetClient:()=>Gt,BalanceClient:()=>mt,ChainParams:()=>Wt});var he=require("polkadot-api");var Gt=class extends H{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:r,value:i})=>{let[s]=r;return[s,i]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:r,value:i})=>{let[s]=r;return[s,i]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:r})=>{let{asset_type:i}=r;return this.SUPPORTED_TYPES.includes(i.type)}).map(({keyArgs:r,value:i})=>{let[s]=r;return[s,i]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:r,value:i})=>{let[s]=r;return[s,i]}))}async mapToken(t,e,r,i){let{name:s,asset_type:n,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=r.get(t)??{};return{id:t,name:s?he.Binary.toText(s):void 0,symbol:l,decimals:u,icon:l,type:n.type,isSufficient:a,location:i,existentialDeposit:o}}async mapBond(t,e,r,i){let[s,n]=i,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:p}=await this.mapToken(s,e,r),d=Number(n),m=new Intl.DateTimeFormat("en-GB"),h=[u,"Bond",m.format(d)].join(" ");return{id:t,name:h,symbol:u+"b",decimals:p,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:s,maturity:d}}async mapShares(t,e,r,i){let{assets:s}=i,{name:n,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,p=await Promise.all(s.map(async h=>{let{symbol:b}=await this.mapToken(h,e,r);return[h,b]})),d=Object.fromEntries(p),m=Object.values(d);return{id:t,name:m.join(", "),symbol:a&&he.Binary.toText(a)||n&&he.Binary.toText(n),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:d}}async mapExternal(t,e,r,i){let s=await this.mapToken(t,e,new Map,i),n=r?.find(a=>a.internalId===s.id);return n?{...s,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:s}parseMetadata(t){return new Map(Array.from(t,([e,r])=>[e,{symbol:r.symbol?he.Binary.toText(r.symbol):void 0,decimals:r.decimals}]))}async getSupported(t,e){let[r,i,s,n]=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=i.get(l),{asset_type:d}=u,m;switch(d.type){case"Bond":let h=n.get(l);m=await this.mapBond(l,u,a,h);break;case"StableSwap":let b=s.get(l);m=await this.mapShares(l,u,a,b);break;case"External":m=await this.mapExternal(l,u,e,p);break;default:m=await this.mapToken(l,u,a,p)}o.push(m)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var $i=require("@galacticcouncil/common"),et=require("rxjs"),w=require("rxjs/operators");var Kr={};E(Kr,{HUB_ASSET_ID:()=>Ut,HYDRATION_OMNIPOOL_ADDRESS:()=>fn,HYDRATION_PARACHAIN_ID:()=>bn,PERBILL_DENOMINATOR:()=>$r,PERMILL_DENOMINATOR:()=>It,SYSTEM_ASSET_DECIMALS:()=>rr,SYSTEM_ASSET_ID:()=>C,TRADEABLE_DEFAULT:()=>Vt});var It=1e6,$r=1e9,C=0,rr=12,bn=2034,fn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Ut=1,Vt=15;var{logger:Yt}=$i.log,mt=class extends H{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:r}=await e.getValue(t,{at:this.at});return this.getBreakdown(r)}async getTokenBalance(t,e){let i=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(i)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,et.defer)(()=>{let e=this.watchSystemBalance(t),r=this.watchTokensBalance(t),i=this.watchErc20Balance(t);return(0,et.combineLatest)([e,r,i]).pipe((0,w.connect)(s=>(0,et.concat)(s.pipe((0,w.take)(1)),s.pipe((0,w.skip)(1),(0,w.debounceTime)(250)))))}).pipe((0,w.map)(e=>e.flat()),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([e,r],i)=>i===0?r:this.getDeltas(e,r))).pipe((0,w.tap)({subscribe:()=>Yt.debug("balance: subscribe",t),error:e=>Yt.error("balance",e)}),(0,w.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,et.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,w.map)(({value:r})=>({id:0,balance:this.getBreakdown(r.data)})),(0,w.tap)({error:r=>Yt.error("balance(system)",r)}))}watchTokenBalance(t,e){let r=this.api.query.Tokens.Accounts;return(0,et.defer)(()=>r.watchValue(t,e,{at:"best"})).pipe((0,w.map)(({value:i})=>({id:e,balance:this.getBreakdown(i)})),(0,w.tap)({error:i=>Yt.error("balance(token)",i)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,et.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,w.distinctUntilChanged)((r,i)=>!i.deltas),(0,w.map)(({deltas:r})=>{let i=[];return r?.deleted.forEach(s=>{let[n,a]=s.args;i.push({id:a,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),r?.upserted.forEach(s=>{let[n,a]=s.args;i.push({id:a,balance:this.getBreakdown(s.value)})}),i}),(0,w.tap)({error:r=>Yt.error("balance(tokens)",r)}))}watchErc20Balance(t,e){let r=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:n})=>n.asset_type.type==="Erc20").map(({keyArgs:n})=>{let[a]=n;return a}),this.erc20Ids},i=async s=>(await Promise.all(s.map(async a=>[a,await this.getBalanceData(t,a)]))).map(([a,o])=>({id:a,balance:o}));return(0,et.defer)(()=>(0,et.from)(e?Promise.resolve(e):r()).pipe((0,w.switchMap)(s=>this.watcher.bestBlock$.pipe((0,w.switchMap)(()=>(0,et.from)(i(s))))),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([s,n],a)=>a===0?n.filter(o=>o.balance.total>0n):this.getDeltas(s,n)),(0,w.distinctUntilChanged)((s,n)=>n.length===0),(0,w.tap)({error:s=>Yt.error("balance(erc20)",s)})))}async getBalanceData(t,e){let r=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(r)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,r=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:r,transferable:e}}getDeltas(t,e){let r=(s,n)=>s!==void 0&&n!==void 0&&s.transferable===n.transferable&&s.total===n.total,i=t.reduce((s,n)=>(s.set(n.id,n.balance),s),new Map);return e.filter(s=>!r(s.balance,i.get(s.id)))}};var Wt=class extends H{_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 Qr={};E(Qr,{AssetNotFound:()=>jr,PoolNotFound:()=>kt,RouteNotFound:()=>ge});var jr=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},kt=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},ge=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var ti={};E(ti,{EvmClient:()=>fe,EvmRpcAdapter:()=>be,createChain:()=>Zr});var Jr=require("polkadot-api"),Ki=require("@galacticcouncil/descriptors"),ir=require("viem"),yn=10000000n,be=class{api;at;constructor(t,e="best"){this.api=t.getTypedApi(Ki.hydration),this.at=e}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:this.at}),{header:e}=t,r=e.timestamp/1000n,[i]=e.number;return{timestamp:r,number:i}}readContract=(async t=>{let{abi:e,address:r,functionName:i,args:s}=t,n=(0,ir.encodeFunctionData)({abi:e,functionName:i,args:s}),a=await this.api.apis.EthereumRuntimeRPCApi.call("0x0000000000000000000000000000000000000000",r,Jr.Binary.fromHex(n),[0n,0n,0n,0n],[yn,0n,0n,0n],void 0,void 0,void 0,!1,[],[],{at:this.at});if(!a.success)throw console.error(i,a.value.type),new Error("Contract read failure");let{exit_reason:o,value:l,used_gas:u}=a.value;if(o.type==="Succeed")return(0,ir.decodeFunctionResult)({abi:e,functionName:i,data:Jr.Binary.toHex(l)});throw console.log(i,o.type,o.value.type),new Error("Contract read error")})};var Xi=require("viem"),Pn=["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"],Zr=()=>(0,Xi.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:Pn}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var dt=require("viem");var fe=class{client;at;chain;constructor(t,e="best"){this.client=t,this.at=e,this.chain=Zr()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,dt.createPublicClient)({chain:this.chain,transport:(0,dt.http)()})}getWsProvider(){return(0,dt.createPublicClient)({transport:(0,dt.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,dt.createWalletClient)({account:t,chain:this.chain,transport:(0,dt.custom)(window.ethereum)})}getRPCAdapter(){return new be(this.client,this.at)}};var li={};E(li,{LiquidityMiningApi:()=>ve,LiquidityMiningClient:()=>we});var ls=require("polkadot-api"),K=Tt(require("big.js")),vt=require("@galacticcouncil/common"),oi=require("@galacticcouncil/math-liquidity-mining");var ye={};E(ye,{withTimeout:()=>vn});function vn(c,t,e="timeout"){return new Promise((r,i)=>{let s=setTimeout(()=>i(new Error(e)),t);c.then(n=>{clearTimeout(s),r(n)},n=>{clearTimeout(s),i(n)})})}var F={};E(F,{divSpot:()=>wn,getFraction:()=>xn,mulScaled:()=>ji,mulSpot:()=>Sn});var ei=require("@galacticcouncil/common");function ji(c,t,e,r,i){let s=e+r-i,n=c*t;return s>0?n/BigInt(10)**BigInt(s):s<0?n*BigInt(10)**BigInt(-s):n}function Sn(c,t,e,r){return ji(c,t,e,ei.RUNTIME_DECIMALS,r)}function wn(c,t,e,r){if(t===0n)return 0n;let i=BigInt(10)**BigInt(ei.RUNTIME_DECIMALS+r-e);return c*i/t}function xn(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),i=BigInt(Math.round(t*Number(r)));return c*i/(BigInt(100)*r)}var I={};E(I,{FeeUtils:()=>ri,shiftNeg:()=>Tn});var Qi=Tt(require("big.js"));var ri=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 i=10**r;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Tn(c,t){let e=(0,Qi.default)(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var zt={};E(zt,{findNestedKey:()=>In,findNestedObj:()=>_n,jsonFormatter:()=>On});var In=(c,t)=>{let e=[];return JSON.stringify(c,(r,i)=>(i&&i[t]&&e.push(i),i)),e[0]},_n=(c,t,e)=>{let r;return JSON.stringify(c,(i,s)=>(s&&s[t]===e&&(r=s),s)),r},On=(c,t)=>typeof t=="bigint"?t.toString():t;var $={};E($,{calculateBuyFee:()=>kn,calculateDiffToAvg:()=>An,calculateDiffToRef:()=>Bn,calculateSellFee:()=>En});var ht=Tt(require("big.js"));function An(c,t){let e=(0,ht.default)(c.toString()),r=(0,ht.default)(t.toString());return e.minus(r).abs().div(e.plus(r).div(2)).mul(100).round(2).toNumber()}function Bn(c,t){if(t===0n)return 0;let e=(0,ht.default)(c.toString()),r=(0,ht.default)(t.toString());return e.minus(r).div(r).mul(100).round(2).toNumber()}function En(c,t){if(c===0n)return 0;let e=(0,ht.default)(c.toString()),r=(0,ht.default)(t.toString());return(0,ht.default)(1).minus(r.div(e)).mul(100).round(2).toNumber()}function kn(c,t){if(c===0n)return 0;let e=(0,ht.default)(c.toString());return(0,ht.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var Pe=(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 sr=(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 Rn=sr(()=>"illegal argument(s)"),Ji=c=>{throw new Rn(c)};var Fn=sr(()=>"index out of bounds"),ii=c=>{throw new Fn(c)},nr=(c,t,e)=>(c<t||c>=e)&&ii(c);var Zi=23283064365386963e-26,ar=class{float(t=1){return this.int()*Zi*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*Zi-.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 or=class extends ar{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 ts=new or(Math.random);var es=c=>c!=null&&typeof c!="function"&&c.length!==void 0;var rs=Object.getPrototypeOf({}),lr="function",is="string",$t=(c,t)=>{let e;if(c===t)return!0;if(c!=null){if(typeof c.equiv===lr)return c.equiv(t)}else return c==t;if(t!=null){if(typeof t.equiv===lr)return t.equiv(c)}else return c==t;return typeof c===is||typeof t===is?!1:(e=Object.getPrototypeOf(c),(e==null||e===rs)&&(e=Object.getPrototypeOf(t),e==null||e===rs)?Ln(c,t):typeof c!==lr&&c.length!==void 0&&typeof t!==lr&&t.length!==void 0?Cn(c,t):c instanceof Set&&t instanceof Set?Mn(c,t):c instanceof Map&&t instanceof Map?Dn(c,t):c instanceof Date&&t instanceof Date?c.getTime()===t.getTime():c instanceof RegExp&&t instanceof RegExp?c.toString()===t.toString():c!==c&&t!==t)},Cn=(c,t,e=$t)=>{let r=c.length;if(r===t.length)for(;r-- >0&&e(c[r],t[r]););return r<0},Mn=(c,t,e=$t)=>c.size===t.size&&e([...c.keys()].sort(),[...t.keys()].sort()),Dn=(c,t,e=$t)=>c.size===t.size&&e([...c].sort(),[...t].sort()),Ln=(c,t,e=$t)=>{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 si=class{value;constructor(t){this.value=t}deref(){return this.value}};var ss=c=>c instanceof si;var cr=class c{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return ns("next",this._head)}reverseIterator(){return ns("prev",this.tail)}clear(){this.release()}compare(t,e=Pe){let r=this._length;if(r<t._length)return-1;if(r>t._length)return 1;if(r===0)return 0;{let i=this._head,s=t._head,n=0;for(;r-- >0&&n===0;)n=e(i.value,s.value),i=i.next,s=s.next;return n}}concat(...t){let e=this.copy();for(let r of t)e.into(r);return e}equiv(t){if(!(t instanceof c||es(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),r=this._head;for(let i=this._length;i-- >0;){if(!$t(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||Pe;for(let r=this._head,i=this._length;i-- >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 i=this._length;i-- >0&&!ss(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 i=t.value;t.value=e.value,e.value=i,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&&ii(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 i=e;do{if(!t(i))break;i=i.next}while(i!==r);return i}_map(t,e){return this.traverse(r=>(t.append(e(r.value)),!0)),t}};function*ns(c,t){for(;t;)yield t.value,t=t[c]}var ur=class c extends cr{_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):(nr(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):(nr(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),i=this.nthCell(e-1),s=n=>({first(){return n.value},next(){return n!==i&&n.next?s(n.next):void 0}});return r?s(r):void 0}shuffle(t,e=ts){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 i=r.next;e.probability(.5)?this.asHead(r):this.asTail(r),r=i}}return this}slice(t=0,e=this.length){let r=t<0?t+this._length:t,i=e<0?e+this._length:e;(r<0||i<0)&&Ji("invalid indices: ${from} / ${to}");let s=new c,n=this.nthCell(r);for(;n&&++r<=i;)s.push(n.value),n=n.next;return s}sort(t=Pe){if(!this._length)return this;let e=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let i=0;for(;r;){i++;let s=r,n=0;for(let o=0;o<e&&(n++,s=s.next,!!s);o++);let a=e;for(;n>0||a>0&&s;){let o;n===0?(o=s,s=s.next,a--):!s||a===0||t(r.value,s.value)<=0?(o=r,r=r.next,n--):(o=s,s=s.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}r=s}if(this._tail.next=void 0,i<=1)return this;e*=2}}splice(t,e=0,r){let i;typeof t=="number"?(t<0&&(t+=this._length),nr(t,0,this._length),i=this.nthCellUnsafe(t)):i=t;let s=new c;if(e>0)for(;i&&e-- >0;)this.remove(i),s.push(i.value),i=i.next;else i&&(i=i.next);if(r)if(i)for(let n of r)this.insertBefore(i,n);else for(let n of r)this.push(n);return s}};var pr=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 ur,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),i=this.map.get(t),s=Math.max(0,r-(i?i.value.s:0));return this._size+=s,this.ensureSize()?this.doSetEntry(i,t,e,r):this._size-=s,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 i=this.items.drop();if(!i)return!1;this.map.delete(i.k),t?.(i.k,i.v),this._size-=i.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,i){t?(this.opts.update?.(e,t.value.v,r),t.value.v=r,t.value.s=i,this.items.asTail(t)):(this.items.push({k:e,v:r,s:i}),this.map.set(e,this.items.tail))}};var Rt=class c extends pr{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 i=this.opts.ksize(t)+this.opts.vsize(e),s=this.map.get(t),n=Math.max(0,i-(s?s.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(s,t,e,i,r):this._size-=n,e}async getSet(t,e,r=this.opts.ttl){let i=this.get(t);return i!==void 0?i: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(),i=this.items.head;for(;i&&(this._size>e||this.length>=t);)i.value.t<r&&this.removeEntry(i),i=i.next;return super.ensureSize()}doSetEntry(t,e,r,i,s=this.opts.ttl){let n=Date.now()+s;t?(this.opts.update?.(e,t.value.v,r),t.value.v=r,t.value.s=i,t.value.t=n,this.items.asTail(t)):(this.items.push({k:e,v:r,s:i,t:n,ttl:s}),this.map.set(e,this.items.tail))}resetEntry(t){return this.opts.autoExtend&&(t.value.t=Date.now()+t.value.ttl),super.resetEntry(t)}};var Ft=class{debug;constructor(t){this.debug=t||!1}log(t,e,r){this.debug&&console.log(t,e,r)}scope(t,e,r,i){let s=new Map,n=i!==void 0?new Rt(null,{ttl:i}):new Rt;return{get:(...u)=>{let p=r(...u);if(s.has(p)){this.log("[live]",t,p);let m=s.get(p);return Promise.resolve(m)}if(n.has(p))return this.log("[memo]",t,p),n.get(p);this.log("[fetch]",t,p);let d=e(...u).catch(m=>{throw n.delete(p),m});return n.set(p,d),d},set:(u,...p)=>{let d=r(...p);this.log("[set-live]",t,d),s.set(d,u)},clear:()=>{this.log("[clear]",t),s.clear(),n.release()}}}};var mr=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let r=0;r<t.length;++r){let[i,s]=t[r];this.result.set(this.getKey(s,i),e[r].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,r,i){let s=this.getKey(t,e),n=this.getKey(t,r),a=this.result.get(s)??0n,o=this.result.get(n)??0n;if(a<i)throw new Error("Attempting to transfer more than is present");this.result.set(s,a+i),this.result.set(n,o+i)}};var _t=Tt(require("big.js")),ut=require("@galacticcouncil/math-liquidity-mining");var ni=Tt(require("big.js")),ai=(0,ni.default)(10).pow(18),as=BigInt((0,ni.default)(1).pow(18).toString()),os=6e3;var qn="1000000000000000000",dr=class{constructor(t,e,r){this.getAccount=t;this.getAsset=e;this.multiCurrency=r}async syncGlobalFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let i=await this.getAsset(t.reward_currency),s=e-t.updated_at,n=this.getAccount(t.id),a=i?.existential_deposit;if(!a)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,n),l=(0,_t.default)(a.toString()),u=(0,_t.default)(o.toString()).minus(l.lt(o.toString())?a.toString():o.toString()),p=(0,_t.default)((0,ut.calculate_global_farm_rewards)(t.total_shares_z.toString(),r.toString(),(0,_t.default)(t.yield_per_period.toString()).mul(ai).round(0,_t.default.roundDown).toFixed(),t.max_reward_per_period.toString(),s.toFixed()));if(u.lt(p)&&(p=u),p.eq(0))return t;let d=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,n,d,BigInt(p.toFixed())),{...t,accumulated_rpz:BigInt((0,ut.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),p.toFixed()))}}syncYieldFarm(t,e,r){if(t.state.type!=="Active"||t.updated_at===r)return t;if(t.total_valued_shares===0n)return{...t,updated_at:r};let i=(0,ut.calculate_yield_farm_delta_rpvs)(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(i),updated_at:r}}getLoyaltyMultiplier(t,e){let r=(0,_t.default)(1).mul(ai).round(0,_t.default.roundDown).toString();if(!e)return r;let{initial_reward_percentage:i,scale_coef:s}=e;return(0,ut.calculate_loyalty_multiplier)(t.toFixed(),i.toString(),s.toFixed())}async claimRewards(t,e,r,i,s){if(e.state.type==="Terminated")return null;let n=Math.floor(i/t.blocks_per_period);if(r.updated_at===n)return null;let a=await this.syncGlobalFarm(t,n,s);if(!a)return null;let o=this.syncYieldFarm(e,a,n);if(!o)return null;let l=o.total_stopped-r.stopped_at_creation,u=o.updated_at-r.entered_at-l,p=this.getLoyaltyMultiplier(u,o.loyalty_curve),d=BigInt((0,ut.calculate_user_reward)(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),m=BigInt((0,ut.calculate_user_reward)(r.accumulated_rpvs.toString(),r.valued_shares.toString(),r.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),qn));return{reward:d,maxReward:m,assetId:a.reward_currency,yieldFarmId:o.id,isActiveFarm:o.state.type==="Active"}}};var Nn=(0,K.default)(365.2425).times(24).times(60).times(60),ve=class{balance;client;options;constructor(t,e,r={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:r.blockTime??os})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let r=[t,e].sort((s,n)=>s-n);if(t===e)return as;let i=await this.client.getOraclePrice(r);if(i){let{n:s,d:n}=i[0].price,a;return t<e?a=(0,oi.fixed_from_rational)(s.toString(),n.toString()):a=(0,oi.fixed_from_rational)(n.toString(),s.toString()),BigInt(a)}}getFarmAddress=(t,e)=>{let r=Buffer.from("modl","utf-8"),i=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),s=Buffer.from([t]),n=Buffer.concat([r,i,s]),o="0x"+Buffer.concat([n,Buffer.alloc(32-n.length)]).toString("hex");return(0,ls.AccountId)(vt.HYDRATION_SS58_PREFIX).dec(o)};getGlobalRewardPerPeriod(t,e,r,i){let s=(0,K.default)(i).times(t.toString()).times(e.toString()).div(Math.pow(10,vt.RUNTIME_DECIMALS));return s.gte(r.toString())?r.toString():s.toString()}getPoolYieldPerPeriod(t,e,r,i){let s=(0,K.default)(t.toString()).times(e),n=(0,K.default)(r.toString()).times(i);return s.div(n.toString()).toString()}farmData(t,e,r){let{yieldFarm:i,globalFarm:s,priceAdjustment:n,balance:a,id:o}=t,{multiplier:l,loyalty_curve:u}=i,{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:S,reward_currency:v,price_adjustment:T,min_deposit:B}=s,D=I.shiftNeg(n??T,vt.RUNTIME_DECIMALS),J=I.shiftNeg(l,vt.RUNTIME_DECIMALS),Y=I.shiftNeg(u?.initial_reward_percentage??0,vt.RUNTIME_DECIMALS),ft=Nn.div((0,K.default)(this.blockTime).div(1e3).times(p)).toString(),tt;if(m<=0)tt=(0,K.default)(J).times(d.toString()).times(ft).div(Math.pow(10,vt.RUNTIME_DECIMALS)).toString();else{let rn=this.getGlobalRewardPerPeriod(m,d,h,D),sn=this.getPoolYieldPerPeriod(rn,J,m,D);tt=(0,K.default)(sn).times(ft).toString()}let ct=b+g,xt=h*BigInt(f),We=a.transferable+ct,Mi=We-ct,ze=(0,K.default)(Mi.toString()).div(h.toString()),$e=(0,K.default)(e).div(p.toString()).toString(),Ke=(m>=0?ze.plus(y):ze.plus($e)).toString(),Nr=(0,K.default)(Ke).times(p).toString(),tn=(0,K.default)(m.toString()).div((0,K.default)(h.toString()).div(d.toString())).div(Math.pow(10,vt.RUNTIME_DECIMALS)).times(100).times(D).toFixed(2),Di=(0,K.default)(ct.toString()).div(We.toString()).gte(.999);tt=Di?"0":(0,K.default)(tt).div(r?2:1).times(100).toString();let en=Y?(0,K.default)(tt).times(Y).toString():void 0;return{apr:tt,minApr:en,isDistributed:Di,estimatedEndPeriod:Ke,estimatedEndBlock:Nr,maxRewards:xt,incentivizedAsset:S,rewardCurrency:v,loyaltyCurve:u,currentPeriod:$e,potMaxRewards:We,fullness:tn,yieldFarmId:i.id,globalFarmId:s.id,poolId:o,distributedRewards:ct,plannedYieldingPeriods:f,minDeposit:B,blocksPerPeriod:p}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((i,s)=>i.includes(s.keyArgs[0].toString())?i:[...i,s.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async i=>{let s=await this.getOmnipoolFarms(i);if(s)return[i,s]}));return Object.fromEntries(r.filter(i=>!!i))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),r=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:s,value:n})=>{let[,a]=s,o=n,l=await this.client.getOmnipoolGlobalFarm(a),u=await this.client.getOmnipoolYieldFarm(Number(t),a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a),h=await this.getOraclePrice(p,d),b=await this.balance.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:h,balance:b}}));return r?i.map(s=>s?this.farmData(s,r):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((i,s)=>i.includes(s.keyArgs[0].toString())?i:[...i,s.keyArgs[0].toString()],[]),r=await Promise.all(e.map(async i=>{let s=await this.getIsolatedFarms(i);if(s)return[i,s]}));return Object.fromEntries(r.filter(i=>!!i))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),r=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:s,value:n})=>{let[,a]=s,o=n,l=await this.client.getIsolatedGlobalFarm(a),u=await this.client.getIsolatedYieldFarm(t,a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a,!0),h=await this.getOraclePrice(p,d),b=await this.balance.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:h,balance:b,farmAddress:m}}));return r?i.map(s=>s?this.farmData(s,r,!0):void 0):[]}async getDepositReward(t,e,r,i){let s=e.global_farm_id,n=e.yield_farm_id,a=r?await this.client.getIsolatedYieldFarm(t,s,n):await this.client.getOmnipoolYieldFarm(Number(t),s,n),o=r?await this.client.getIsolatedGlobalFarm(s):await this.client.getOmnipoolGlobalFarm(s);if(!o||!a)return;let l=o.reward_currency,u=o.incentivized_asset,p=[[this.getFarmAddress(0,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 mr(p,d),g=await new dr(y=>this.getFarmAddress(y),y=>this.client.getAsset(y),h).claimRewards(o,a,e,i,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(([s,n])=>n!==0).map(([s,n])=>this.balance.getTokenBalance(s,n))),Promise.all(t.filter(([s,n])=>n===0).map(([s])=>this.balance.getSystemBalance(s)))]),i=[];for(let s=0,n=0;s+n<t.length;){let a=s+n,[,o]=t[a];o===0?(i.push(r[n]),n+=1):(i.push(e[s]),s+=1)}return i}};var Se=require("polkadot-api"),Hn=Se.Binary.toHex(Se.Binary.fromText("omnipool")),we=class extends H{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(Hn,t,(0,Se.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 ui={};E(ui,{BlockFetcher:()=>Kt,IndexerStats:()=>Ct,RpcPool:()=>gr,SYSTEM_EVENTS_KEY:()=>ci,Semaphore:()=>Xt,decodeCompactLength:()=>hr,indexBlocks:()=>us});function hr(c){let t=c.startsWith("0x")?c.slice(2):c;if(t.length<2)return 0;let e=parseInt(t.slice(0,2),16);switch(e&3){case 0:return e>>2;case 1:{if(t.length<4)return 0;let i=e;return(parseInt(t.slice(2,4),16)<<8|i)>>2}case 2:{if(t.length<8)return 0;let i=e,s=parseInt(t.slice(2,4),16),n=parseInt(t.slice(4,6),16);return(parseInt(t.slice(6,8),16)<<24|n<<16|s<<8|i)>>>2}default:return 0}}var ci="0x26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7";var Kt=class c{constructor(t){this.select=t}static withClient(t){return new c(()=>t)}async getHash(t){let r=await this.select()._request("chain_getBlockHash",[t]);return r&&r.length===66?r:null}async getBlock(t,e={}){let r=await this.getHash(t);return r?this.getBlockAt(t,r,e):null}async getBlockAt(t,e,r={}){let i=this.select(),[s,n]=await Promise.all([r.withBlock?i._request("chain_getBlock",[e]):Promise.resolve(null),r.withEvents?i._request("state_getStorage",[ci,e]):Promise.resolve(null)]),a=s?.block?.extrinsics??[],o=s?.block?.header,l=s?JSON.stringify(s).length:0,u=n?n.length/2:0;return{number:t,hash:e,header:o,extrinsics:a,eventsHex:n??void 0,eventsCount:n?hr(n):0,bytes:l+u}}};var Ct=class{blocks=0;events=0;extrinsics=0;bytes=0;errors=0;startedAt=0;batchTimes=[];start(){this.startedAt=performance.now()}recordBlock(t={}){this.blocks++,t.events&&(this.events+=t.events),t.extrinsics&&(this.extrinsics+=t.extrinsics),t.bytes&&(this.bytes+=t.bytes)}recordBatch(t){this.batchTimes.push(t)}recordError(){this.errors++}elapsedMs(){return this.startedAt===0?0:performance.now()-this.startedAt}percentile(t){if(this.batchTimes.length===0)return 0;let e=[...this.batchTimes].sort((i,s)=>i-s),r=Math.floor(t/100*e.length);return e[Math.min(r,e.length-1)]}snapshot(){let t=this.elapsedMs(),e=t/1e3;return{blocks:this.blocks,events:this.events,extrinsics:this.extrinsics,bytes:this.bytes,errors:this.errors,elapsedMs:t,blocksPerSec:e>0?this.blocks/e:0,eventsPerSec:e>0?this.events/e:0,batchP50Ms:this.percentile(50),batchP95Ms:this.percentile(95),batchP99Ms:this.percentile(99)}}};var cs=require("polkadot-api");var gr=class c{clients=[];owned;idx=0;constructor(t,e){if(t.length===0)throw new Error("RpcPool requires at least one client");this.clients=t,this.owned=e}static fromEndpoints(t){let r=(typeof t=="string"?t.split(","):t).map(i=>(0,cs.createClient)(Gr(i)));return new c(r,!0)}static fromClients(t){return new c(t,!1)}size(){return this.clients.length}next(){let t=this.clients[this.idx%this.clients.length];return this.idx++,t}destroy(){if(this.owned)for(let t of this.clients)t.destroy()}};var Xt=class{constructor(t){this.max=t;if(t<1)throw new Error("Semaphore max must be >= 1")}queue=[];running=0;async acquire(){if(this.running<this.max){this.running++;return}return new Promise(t=>{this.queue.push(()=>{this.running++,t()})})}release(){this.running--;let t=this.queue.shift();t&&t()}async run(t){await this.acquire();try{return await t()}finally{this.release()}}};async function us(c){let{pool:t,fromBlock:e,blockCount:r,concurrency:i=100,batchSize:s=50,withBlock:n=!1,withEvents:a=!1,onBlock:o,onError:l}=c;if(r<=0){let h=c.stats??new Ct;return h.start(),{stats:h}}let u=c.stats??new Ct,p=new Xt(i),d=new Kt(()=>t.next()),m=[];for(let h=0;h<r;h+=s){let b=[];for(let g=0;g<s&&h+g<r;g++)b.push(e+h+g);m.push(b)}return u.start(),await Promise.all(m.map(h=>p.run(async()=>{let b=performance.now();await Promise.all(h.map(async g=>{let f=null;try{f=await d.getBlock(g,{withBlock:n,withEvents:a})}catch(y){u.recordError(),l?.(y,g);return}if(!f){u.recordError();return}if(u.recordBlock({events:f.eventsCount,extrinsics:f.extrinsics.length,bytes:f.bytes}),o)try{await o(f)}catch(y){u.recordError(),l?.(y,g)}})),u.recordBatch(performance.now()-b)}))),{stats:u}}var Si={};E(Si,{PoolContextProvider:()=>ie,PoolError:()=>Ot,PoolFactory:()=>re,PoolType:()=>k,SnapshotPoolCtxProvider:()=>Ar,aave:()=>yi,hsm:()=>vi,lbp:()=>pi,omni:()=>di,stable:()=>bi,xyk:()=>fi});var pi={};E(pi,{LbpMath:()=>pt,LbpPool:()=>xe,LbpPoolClient:()=>Te});var gt=require("@galacticcouncil/math-lbp"),pt=class{static getSpotPrice(t,e,r,i,s){return(0,gt.get_spot_price)(t,e,r,i,s)}static calculateInGivenOut(t,e,r,i,s){return(0,gt.calculate_in_given_out)(t,e,r,i,s)}static calculateOutGivenIn(t,e,r,i,s){return(0,gt.calculate_out_given_in)(t,e,r,i,s)}static calculateLinearWeights(t,e,r,i,s){return(0,gt.calculate_linear_weights)(t,e,r,i,s)}static calculatePoolTradeFee(t,e,r){return(0,gt.calculate_pool_trade_fee)(t,e,r)}};var jt=require("@galacticcouncil/common");var k=(n=>(n.Aave="Aave",n.LBP="LBP",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="XYK",n.HSM="HSM",n))(k||{}),Ot=(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))(Ot||{});var{FeeUtils:ps}=I,xe=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(n=>[n.id,n])),i=r.get(t),s=r.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,weightIn:i.weight,weightOut:s.weight}}validateAndBuy(t,e,r){let i=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let n=t.balanceOut/this.maxOutRatio;if(e>n&&s.push("MaxOutRatioExceeded"),i===t.assetOut){let a=this.calculateTradeFee(e,r),o=ps.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return u>p&&s.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:s}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&s.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:s}}}validateAndSell(t,e,r){let i=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let n=t.balanceIn/this.maxInRatio;if(e>n&&s.push("MaxInRatioExceeded"),i===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:s}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,r),l=ps.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),u=a-o,p=t.balanceOut/this.maxOutRatio;return u>p&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:s}}}calculateInGivenOut(t,e){let r=pt.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(r);return i<0n?0n:i}calculateOutGivenIn(t,e){let r=pt.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(r);return i<0n?0n:i}spotPriceInGivenOut(t){let e=pt.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),jt.big.toBigInt(1,jt.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=pt.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),jt.big.toBigInt(1,jt.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let r=pt.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(r)}};var gs=require("polkadot-api"),At=require("rxjs");var ms=(c,t=new Map)=>e=>{let r;return t.has(e)?t.get(e):(t.set(e,r=c(e)),r)};var _=require("rxjs"),P=require("rxjs/operators");var ds=require("rxjs"),br=class{store$=new ds.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])),i=await t(e),s=e.slice(),n=new Set;for(let a of i){let o=r.get(a.address);o===void 0?(r.set(a.address,s.length),s.push(a)):s[o]=a,n.add(a.address)}this.changeset=n,this.store$.next(s)}).catch(console.error)}destroy(){this.store$.complete()}};var hs=require("@galacticcouncil/common");var Gn={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:fr}=hs.log,yr=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${Gn[this.type]})`,10)}trace(t,...e){fr.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){fr.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){fr.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){fr.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:Un}=ye,Vn=3e3,Z=class extends H{evm;balance;store=new br;log;shared$;resync$=new _.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new Rt(null,{ttl:6*1e3});memPools=ms(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e,r){super(t,r),this.evm=e,this.balance=new mt(t,r),this.log=new yr(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){let e=(await this.getMemPools()).filter(r=>this.hasValidAssets(r));return this.store.set(e),e}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe((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,_.defer)(()=>{let t=new _.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,P.switchMap)(()=>{let e=new _.Subscription;return(0,_.from)(Un(this.getMemPools(),6e4,"getMemPools stalled")).pipe((0,P.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,P.map)(i=>i.filter(s=>this.hasValidAssets(s))),(0,P.tap)(i=>this.store.set(i)),(0,P.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),_.EMPTY))).pipe((0,P.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,P.switchMap)(i=>(0,_.merge)((0,_.of)(i),this.store.asObservable().pipe((0,P.skip)(1)))),(0,P.finalize)(()=>{e.unsubscribe()}))}),(0,P.finalize)(()=>t.unsubscribe()))}).pipe((0,P.share)({connector:()=>new _.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:r}=e,i=[this.balance.watchTokensBalance(r)];if(this.hasSystemAsset(e)){let s=this.balance.watchSystemBalance(r);i.push(s)}if(this.hasErc20Asset(e)){let s=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),n=this.balance.watchErc20Balance(r,s);i.push(n)}return(0,_.combineLatest)(i).pipe((0,P.map)(s=>s.flat()),(0,P.pairwise)(),(0,P.map)(([s,n])=>this.balance.getDeltas(s,n)),(0,P.filter)(s=>s.length>0),(0,P.map)(s=>[r,s]))});return(0,_.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})=>t.type==="XYK"?r>0n&&!!e:!!e)}updateBalances=(t,e)=>{let r=[],i=new Map(t.map(s=>[s.address,s]));for(let[s,n]of e){let a=i.get(s);if(a){let o=a.tokens.map(l=>{let u=n.find(p=>p.id===l.id);return u&&l.id!==a.id?{...l,balance:u.balance.transferable}:l});r.push({...a,tokens:o})}}return r};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<Vn||(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)(([a,o])=>a==="offline"&&o==="online"),(0,P.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,P.catchError)(a=>(this.log.error("watchdog_recovery_error",a),_.EMPTY)),(0,P.repeat)({delay:1e3})),s=this.watcher.finalizedBlock$.pipe((0,P.pairwise)(),(0,P.tap)(([a,o])=>{let l=Number(a.number),u=Number(o.number),p=u-l;p>=3&&(this.log.debug("watchdog_gap",{from:l,to:u,gap:p}),this.requestResync())}),(0,P.catchError)(a=>(this.log.error("watchdog_gap_error",a),_.EMPTY)),(0,P.repeat)({delay:1e3})),n=(0,_.interval)(36e5).pipe((0,P.tap)(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),(0,P.catchError)(a=>(this.log.error("watchdog_periodic_error",a),_.EMPTY)),(0,P.repeat)({delay:1e3}));return(0,_.merge)(i,s,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)(()=>_.EMPTY))}};var Te=class extends Z{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,r]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:r}}getPoolWeights(t,e){let{start:r,end:i,initial_weight:s,final_weight:n}=t,a=pt.calculateLinearWeights(r?r.toString():"0",i?i.toString():"0",s.toString(),n.toString(),e.toString()),o=BigInt(a),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){return(await this.api.getStaticApis()).compat.query.LBP.PoolData.isCompatible(gs.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,r]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:this.at}),this.api.query.ParachainSystem.ValidationData.getValue({at:this.at}),this.getPoolLimits()]),i=e?.relay_parent_number||0,s=t.filter(({value:n})=>e&&this.isActivePool(n,i)).map(async({keyArgs:n,value:a})=>{let[o]=n,l=o.toString(),u=await this.getPoolDelta(l,a,i);return{address:l,type:"LBP",fee:a.fee,...u,...r}});return Promise.all(s)}async getPoolDelta(t,e,r){let{assets:i,repay_target:s,fee_collector:n}=e,[a,o]=this.getPoolWeights(e,r),[l,u]=i,[p,d,m,h,b]=await Promise.all([this.isRepayFeeApplied(l,s,n.toString()),this.balance.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l,{at:this.at}),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u,{at:this.at})]);return{repayFeeApply:p,tokens:[{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,weight:a,type:m?.asset_type.type},{id:u,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:h.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(t,e){let{start:r,end:i}=t;return r&&i?e>=r&&e<i:!1}async isRepayFeeApplied(t,e,r){if(e===0n)return!1;try{return(await this.balance.getBalance(r,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let r=this.store.pools.find(s=>s.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:r.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue({at:"best"}).pipe((0,At.map)(({value:t})=>t),(0,At.filter)(t=>t!==void 0),(0,At.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 i of e){let s=this.poolsData.get(i.address);if(s){let{assets:n,repay_target:a,fee_collector:o}=s,[l]=n,[u,p]=this.getPoolWeights(s,t),[d,m]=i.tokens,h=[{...d,weight:u},{...m,weight:p}],b=await this.isRepayFeeApplied(l,a,o.toString());r.push({...i,tokens:h,repayFeeApply:b})}}return r})})}subscribeUpdates(){let t=new At.Subscription;return t.add(this.subscribeValidationData()),t}};var di={};E(di,{OmniMath:()=>R,OmniPool:()=>Ie,OmniPoolClient:()=>_e,OmniPoolFee:()=>Dt,getEmaKey:()=>Pr,getEmaPair:()=>Qt});var x=require("@galacticcouncil/math-omnipool"),Mt=Tt(require("big.js")),R=class{static calculateSpotPrice(t,e,r,i){return(0,x.calculate_spot_price)(t,e,r,i)}static calculateLrnaSpotPrice(t,e){return(0,x.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,r,i,s,n,a,o,l,u){return(0,x.calculate_in_given_out)(t,e,r,i,s,n,a,o,l,u)}static calculateLrnaInGivenOut(t,e,r,i,s,n){return(0,x.calculate_lrna_in_given_out)(t,e,r,i,s,n)}static calculateOutGivenIn(t,e,r,i,s,n,a,o,l,u){return(0,x.calculate_out_given_in)(t,e,r,i,s,n,a,o,l,u)}static calculateOutGivenLrnaIn(t,e,r,i,s,n){return(0,x.calculate_out_given_lrna_in)(t,e,r,i,s,n)}static calculateShares(t,e,r,i){return(0,x.calculate_shares)(t,e,r,i)}static calculateLiquidityOut(t,e,r,i,s,n,a,o){return(0,x.calculate_liquidity_out)(t,e,r,i,s,n,a,o)}static calculateLiquidityLRNAOut(t,e,r,i,s,n,a,o){return(0,x.calculate_liquidity_lrna_out)(t,e,r,i,s,n,a,o)}static calculateCapDifference(t,e,r,i){let s=(0,Mt.default)(e),n=(0,Mt.default)(t),a=(0,Mt.default)(i),o=(0,Mt.default)(r),l=(0,Mt.default)(10).pow(18),u=o.div(l);if(s.div(a).lt(u)){let d=u.times(a).minus(s).times(n),m=s.times((0,Mt.default)(1).minus(u));return d.div(m).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,r,i){return(0,x.calculate_liquidity_hub_in)(t,e,r,i)}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,i,s,n,a,o,l,u,p){return(0,x.recalculate_asset_fee)(t,e,r,i,s,n,a,o,l,u,p)}static recalculateProtocolFee(t,e,r,i,s,n,a,o,l,u,p){return(0,x.recalculate_protocol_fee)(t,e,r,i,s,n,a,o,l,u,p)}static verifyAssetCap(t,e,r,i){return(0,x.verify_asset_cap)(t,e,r,i)}};var bs=require("@galacticcouncil/common");var{FeeUtils:bt}=I,Ie=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(n=>[n.id,n])),i=r.get(t),s=r.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:i.hubReserves,hubReservesOut:s.hubReserves,sharesIn:i.shares,sharesOut:s.shares,decimalsIn:i.decimals,decimalsOut:s.decimals,balanceIn:i.balance,balanceOut:s.balance,tradeableIn:i.tradeable,tradeableOut:s.tradeable,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,r){let i=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,r),n=i===0n?0:$.calculateBuyFee(i,s),a=[],o=R.isSellAllowed(t.tradeableIn),l=R.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return s>p&&a.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:i,amountOut:e,feePct:n,errors:a}}validateAndSell(t,e,r){let i=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,r),n=$.calculateSellFee(i,s),a=[],o=R.isSellAllowed(t.tradeableIn),l=R.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return s>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:s,feePct:n,errors:a}}calculateInGivenOut(t,e,r){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,r);let i=R.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),r?bt.toRaw(r.assetFee).toString():"0",r?bt.toRaw(r.protocolFee).toString():"0",r?bt.toRaw(r.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateLrnaInGivenOut(t,e,r){let i=R.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),r?bt.toRaw(r.assetFee).toString():"0",r?bt.toRaw(r.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e,r){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,r);let i=R.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),r?bt.toRaw(r.assetFee).toString():"0",r?bt.toRaw(r.protocolFee).toString():"0",r?bt.toRaw(r.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateOutGivenLrnaIn(t,e,r){let i=R.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),r?bt.toRaw(r.assetFee).toString():"0",r?bt.toRaw(r.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=R.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceLrnaInGivenOut(t){let e=R.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=R.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}spotPriceOutGivenLrnaIn(t){let e=R.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,r){let i=e-r;if(i===0)return t;let s=bs.big.pow10(Math.abs(i));return i>0?t*s:t/s}};var St=require("polkadot-api"),Ps=require("@polkadot-api/utils"),O=require("rxjs"),vs=require("@galacticcouncil/common");var{FeeUtils:W}=I,Dt=class c{static compute(t,e,r,i,s,n,a,o){let l=t.assetIn,[u,p,d]=c.getAssetFee(t,e,r,i,n),m=0,h=0,b=0;l!==1&&([m,h,b]=c.getProtocolFee(t,e,r,s,a));let g=u+m,f=d+b;return{assetFee:W.fromPermill(p),protocolFee:W.fromPermill(h),maxSlipFee:W.fromPermill(o),min:W.fromPermill(g),max:W.fromPermill(f)}}static getAssetFee(t,e,r,i,s){let{assetOut:n,balanceOut:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=s;if(!r||!i)return[o,o,l];let d=W.fromPermill(o),m=W.fromPermill(l),[h]=i,{asset_fee:b,timestamp:g}=r,f=Math.max(1,e-g),y=h.volume.b_in.toString(),S=h.volume.b_out.toString(),v=h.liquidity.b.toString();n===0&&(y=h.volume.a_in.toString(),S=h.volume.a_out.toString(),v=h.liquidity.a.toString());let T=W.fromPermill(b),B=R.recalculateAssetFee(y,S,v,"9",a.toString(),W.toRaw(T).toString(),f.toString(),W.toRaw(d).toString(),W.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(B)*1e6,l]}static getProtocolFee(t,e,r,i,s){let{assetIn:n,balanceIn:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=s;if(!r||!i)return[o,o,l];let d=W.fromPermill(o),m=W.fromPermill(l),[h]=i,{protocol_fee:b,timestamp:g}=r,f=Math.max(1,e-g),y=h.volume.b_in.toString(),S=h.volume.b_out.toString(),v=h.liquidity.b.toString();n===0&&(y=h.volume.a_in.toString(),S=h.volume.a_out.toString(),v=h.liquidity.a.toString());let T=W.fromPermill(b),B=R.recalculateProtocolFee(y,S,v,"9",a.toString(),W.toRaw(T).toString(),f.toString(),W.toRaw(d).toString(),W.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(B)*1e6,l]}};var Qt=c=>c===0?[0,1]:[1,c],Pr=c=>Qt(c).join(":");var{FeeUtils:mi}=I,fs=St.Binary.toHex(St.Binary.fromText("omnipool")),ys=(0,St.Enum)("Short"),_e=class extends Z{queryBus=new Ft;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:this.at}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:this.at}),t=>String(t),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:this.at}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(fs,t,ys,{at:this.at}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),r=(0,Ps.toHex)(e);return(0,St.AccountId)(vs.HYDRATION_SS58_PREFIX).dec(r)}async getPoolLimits(){let[t,e,r]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:r}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Omnipool.Assets.isCompatible(St.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[r,i,s,n,a,o]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:this.at}),this.api.query.Omnipool.HubAssetTradability.getValue({at:this.at}),this.api.query.AssetRegistry.Assets.getValue(t,{at:this.at}),this.balance.getBalance(e,t),this.getPoolLimits(),this.api.query.System.Number.getValue({at:this.at})]);this.block=o;let l=r.map(async({keyArgs:p,value:d})=>{let[m]=p,{hub_reserve:h,shares:b,tradable:g,cap:f,protocol_shares:y}=d,[S,v]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m,{at:this.at}),this.balance.getBalance(e,m)]);return{id:m,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:v.transferable,cap:f,hubReserves:h,protocolShares:y,shares:b,tradeable:g,type:S?.asset_type.type}}),u=await Promise.all(l);return u.push({id:t,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:n.transferable,tradeable:i,type:s?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:u,...a}]}async getPoolFees(t){let e=t.assetOut,r=t.assetIn,s=await this.maxSlipFee.get()??0,n=await this.dynamicFeesConfig.get(e);if(n?.type==="Fixed"){let{asset_fee:d,protocol_fee:m}=n.value;return{assetFee:mi.fromPermill(d),protocolFee:mi.fromPermill(m),maxSlipFee:mi.fromPermill(s)}}let[a,o,l,u,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(Qt(e)),this.emaOracles.get(Qt(r)),n?n.value.asset_fee_params:this.api.constants.DynamicFees.AssetFeeParameters(),n?n.value.protocol_fee_params:this.api.constants.DynamicFees.ProtocolFeeParameters()]);return Dt.compute(t,this.block,a,o,l,u,p,s)}subscribeEmaOracles(){let[t]=this.store.pools,r=t.tokens.map(i=>i.id).map(i=>Qt(i)).map(i=>this.api.query.EmaOracle.Oracles.watchValue(fs,i,ys,{at:"best"}).pipe((0,O.map)(({value:s})=>s),(0,O.filter)(s=>s!==void 0),(0,O.map)((s,n)=>({value:s,index:n})),(0,O.tap)(({index:s})=>{s>0&&this.log.trace("emaOracle.Oracles",i.join(":"))}),(0,O.map)(({value:s})=>({pair:i,value:s}))));return(0,O.merge)(...r).pipe((0,O.finalize)(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(i=>{let{pair:s,value:n}=i;this.emaOracles.set(n,s)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,O.distinctUntilChanged)((t,e)=>!e.deltas),(0,O.map)((t,e)=>({value:t,index:e})),(0,O.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),(0,O.finalize)(()=>this.dynamicFees.clear()),this.watchGuard("dynamicFees.AssetFee")).subscribe(({value:{deltas:t}})=>{t?.upserted.forEach(e=>{let[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((s,n)=>{let[a]=n.args;return s.set(a,n.value),s},new Map),i=e.tokens.map(s=>{let n=r?.get(s.id);return n?this.updateTokenState(s,n):s});return[{...e,tokens:i}]})})}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:i,tradable:s,cap:n,protocol_shares:a}=e;return{...t,cap:n,hubReserves:r,protocolShares:a,shares:i,tradeable:s}}};var bi={};E(bi,{StableMath:()=>V,StableSwap:()=>Lt,StableSwapClient:()=>ke});var L=require("@galacticcouncil/math-stableswap"),V=class{static getPoolAddress(t){return(0,L.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,i,s){return(0,L.calculate_amplification)(t,e,r,i,s)}static calculateInGivenOut(t,e,r,i,s,n,a){return(0,L.calculate_in_given_out)(t,e,r,i,s,n,a)}static calculateAddOneAsset(t,e,r,i,s,n,a){return(0,L.calculate_add_one_asset)(t,e,r,i,s,n,a)}static calculateSharesForAmount(t,e,r,i,s,n,a){return(0,L.calculate_shares_for_amount)(t,e,r,i,s,n,a)}static calculateOutGivenIn(t,e,r,i,s,n,a){return(0,L.calculate_out_given_in)(t,e,r,i,s,n,a)}static calculateLiquidityOutOneAsset(t,e,r,i,s,n,a){return(0,L.calculate_liquidity_out_one_asset)(t,e,r,i,s,n,a)}static calculateShares(t,e,r,i,s,n){return(0,L.calculate_shares)(t,e,r,i,s,n)}static calculateSpotPriceWithFee(t,e,r,i,s,n,a,o){return(0,L.calculate_spot_price_with_fee)(t,e,r,i,s,n,a,o)}static recalculatePegs(t,e,r,i,s,n){let a=(0,L.recalculate_peg)(t,e,r,i,s,n);return JSON.parse(a)}};var Oe=require("@galacticcouncil/common");var{FeeUtils:Jt}=I,Lt=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(n=>[n.id,n])),i=r.get(t),s=r.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,tradeableIn:this.id===t?15:i.tradeable,tradeableOut:this.id===e?15:s.tradeable,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,r){let i=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,r),n=i===0n?0:$.calculateBuyFee(i,s),a=[],o=R.isSellAllowed(t.tradeableIn),l=R.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:s,calculatedIn:i,amountOut:e,feePct:n,errors:a}}validateAndSell(t,e,r){let i=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,r),n=$.calculateSellFee(i,s),a=[],o=R.isSellAllowed(t.tradeableIn),l=R.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:i,amountOut:s,feePct:n,errors:a}}calculateIn(t,e,r){let i=V.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),r?Jt.toRaw(r.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateAddOneAsset(t,e,r){let i=V.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),r?Jt.toRaw(r.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateSharesForAmount(t,e,r){let i=V.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),r?Jt.toRaw(r.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}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=V.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetOut===this.id,t.assetIn===this.id,t.decimalsOut,t.decimalsIn)}calculateOut(t,e,r){let i=V.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),r?Jt.toRaw(r.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateWithdrawOneAsset(t,e,r){let i=V.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),r?Jt.toRaw(r.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateShares(t,e,r){let i=V.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),r?Jt.toRaw(r.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}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=V.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetIn===this.id,t.assetOut===this.id,t.decimalsIn,t.decimalsOut)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:r,decimals:i})=>({asset_id:e,amount:r,decimals:i}));return JSON.stringify(t,zt.jsonFormatter)}getAssets(t,e){let r={asset_id:Number(t),amount:e.toString()};return JSON.stringify([r],zt.jsonFormatter)}normalizeSpot(t,e,r,i,s){return e?t*Oe.big.pow10(Oe.RUNTIME_DECIMALS-s):r?t/Oe.big.pow10(s-i):t}};var vr=require("polkadot-api"),As=require("@polkadot-api/utils"),Bs=require("@noble/hashes/blake2b"),q=require("rxjs"),Sr=require("@galacticcouncil/common");var xs=require("polkadot-api"),gi=require("viem");var hi=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}],Ss=[{anonymous:!1,inputs:[{indexed:!1,name:"key",type:"string"},{indexed:!1,name:"value",type:"uint128"},{indexed:!1,name:"timestamp",type:"uint128"}],name:"OracleUpdate",type:"event"}],ws=[{anonymous:!1,inputs:[{indexed:!0,name:"roundId",type:"uint80"},{indexed:!1,name:"answer",type:"int256"},{indexed:!1,name:"timestamp",type:"uint256"}],name:"PriceUpdated",type:"event"}];var Ae=class{static parse(t){let{address:e,topics:r,data:i}=t.log,s=e.toLowerCase(),n=xs.Binary.toHex(i);try{let{eventName:a,args:o}=(0,gi.decodeEventLog)({abi:ws,topics:r,data:n});return{eventName:`ManagedOracle.${a}`,emitter:s,value:o.answer,timestamp:o.timestamp}}catch{}try{let{eventName:a,args:o}=(0,gi.decodeEventLog)({abi:Ss,topics:r,data:n});return{eventName:`DIA.${a}`,emitter:s,key:o.key,value:o.value,timestamp:o.timestamp}}catch{}}};var Be=class{adapter;constructor(t){this.adapter=t.getRPCAdapter()}async getData(t,e=6){let[r,i,s]=await Promise.all([this.adapter.readContract({abi:hi,address:t,functionName:"latestRoundData"}),this.adapter.readContract({abi:hi,address:t,functionName:"decimals"}),this.adapter.getBlock()]),[n,a,o,l]=r,u=s.number-(s.timestamp-l)/BigInt(e),p=Number(u);return{price:a,decimals:i,updatedAt:p<0?0:p}}};var Ts={"EUR/USD":"0xaa47a5662269270d3df33ae08f806e383611575c","sUSDs/USD":"0x4b32bffc6acd751446e79e8687ef3815fd7924fd","sUSDe/USD":"0x22cdea305cee63d082e79f8c5db939eecd0265d0"},Is={"0xcfab6a4031c70da0f0cf6f31a252c16119db3611":"0xaafd758688cefd0a7b7770a825f1aad551e16185"},_s={"bifrosto:5:15:LastBlock":"0xaafd758688cefd0a7b7770a825f1aad551e16185"};function Os(c,t,e){let r=Buffer.from(c.replace(/^0x/,""),"hex").toString("ascii").replace(/\0+$/,""),[i,s]=[t[0],t[1]].sort((n,a)=>n-a);return`${r}:${i}:${s}:${e}`}var{FeeUtils:Zt}=I,Ee=class c{static compute(t,e,r,i){let s=c.getRecent(e),n=Zt.fromPermill(t.fee),a=Zt.fromPerbill(e.max_peg_update),o=r.map(({pair:h,updatedAt:b})=>[h,b]),l=r.find(h=>h.source),u=e.updated_at?e.updated_at.toString():l?.updatedAt;if(!u)throw new Error("Current peg unknown!");let[p,d]=V.recalculatePegs(JSON.stringify(s),u,JSON.stringify(o),i.toString(),Zt.toRaw(a).toString(),Zt.toRaw(n).toString()),m=Number(p)*1e6;return{pegsFee:Zt.fromPermill(m),pegs:d}}static getDefault(t){return{pegsFee:Zt.fromPermill(t.fee),pegs:V.defaultPegs(t.assets.length)}}static getRecent(t){let{current:e}=t;return Array.from(e.entries()).map(([r,i])=>i.map(s=>s.toString()))}};var{FeeUtils:Yn}=I,Wn=["ManagedOracle.PriceUpdated","DIA.OracleUpdate"],ke=class extends Z{poolsData=new Map([]);mmOracle=new Be(this.evm);mmAddresses=new Set;mmRouting={byEmitter:new Map,byDiaKey:new Map,byEma:new Map};queryBus=new Ft;emaOracles=this.queryBus.scope("EmaOracle.Oracles",(t,e,r)=>this.api.query.EmaOracle.Oracles.getValue(t,e,r,{at:this.at}),(t,e,r)=>`${t.toString()}:${e.join(":")}:${r.type}`,6*1e3);mmOracles=this.queryBus.scope("MmOracle",t=>this.mmOracle.getData(t),t=>t.toLowerCase(),600*1e3);pegs=this.queryBus.scope("Stableswap.PoolPegs",t=>this.api.query.Stableswap.PoolPegs.getValue(t,{at:this.at}),t=>String(t),6*1e3);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=V.getPoolAddress(t),r=(0,Bs.blake2b)(e,{dkLen:32}),i=(0,As.toHex)(r);return(0,vr.AccountId)(Sr.HYDRATION_SS58_PREFIX).dec(i)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:r,final_amplification:i,initial_block:s,final_block:n}=t,a=V.calculateAmplification(r.toString(),i.toString(),s.toString(),n.toString(),e.toString()),o=Number(a)<i;return{amplification:BigInt(a),isRampPeriod:o}}async getPoolTokens(t,e){let r=this.getPoolAddress(t),i=e.assets.map(async s=>{let[n,a,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,s,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(s,{at:this.at}),this.balance.getBalance(r,s)]);return{id:s,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:o.transferable,tradeable:n,type:a?.asset_type.type}});return Promise.all(i)}buildRouting(){this.mmRouting.byEmitter.clear(),this.mmRouting.byDiaKey.clear(),this.mmRouting.byEma.clear();for(let t of this.mmAddresses)this.mmRouting.byEmitter.set(t,t);for(let[t,e]of Object.entries(Is)){let r=t.toLowerCase(),i=e.toLowerCase();this.mmAddresses.has(i)&&this.mmRouting.byEmitter.set(r,i)}for(let[t,e]of Object.entries(Ts)){let r=e.toLowerCase();this.mmAddresses.has(r)&&this.mmRouting.byDiaKey.set(t,r)}for(let[t,e]of Object.entries(_s)){let r=e.toLowerCase();this.mmAddresses.has(r)&&this.mmRouting.byEma.set(t,r)}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Stableswap.Pools.isCompatible(vr.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,r,i]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:this.at}),this.api.query.Stableswap.PoolPegs.getEntries({at:this.at}),this.api.query.System.Number.getValue({at:this.at}),this.getPoolLimits()]);for(let{keyArgs:n,value:a}of e){let[o]=n;this.pegs.set(a,o);for(let l of a.source)l.type==="MMOracle"&&this.mmAddresses.add(l.value.toString().toLowerCase())}this.buildRouting();let s=t.map(async({keyArgs:n,value:a})=>{let[o]=n,l=this.getPoolAddress(o),[u,p,d,m]=await Promise.all([this.getPoolTokens(o,a),this.getPoolAmplification(a,r),this.getPoolPegs(o,a,r),this.api.query.Tokens.TotalIssuance.getValue(o,{at:this.at})]);return u.push({id:o,tradeable:15,balance:m,decimals:Sr.RUNTIME_DECIMALS}),this.poolsData.set(o,a),{address:l,id:o,type:"Stableswap",fee:Yn.fromPermill(a.fee),tokens:u,totalIssuance:m,...d,...i,...p}});return Promise.all(s)}async getPoolFees(t,e){return{fee:this.store.pools.find(i=>i.address===e).fee}}async getPoolPegs(t,e,r){let i=await this.pegs.get(t);if(!i)return Ee.getDefault(e);let s=await this.getLatestPegs(e,i,r);return Ee.compute(e,i,s,r)}async getLatestPegs(t,e,r){let{source:i}=e,s=t.assets,n=i.map(async(a,o)=>{if(a.type==="Oracle"){let[l,u,p]=a.value,d=[p,s[o]].sort((f,y)=>f-y),m=await this.emaOracles.get(l,d,u);if(!m)throw new Error("EmaOracle missing for "+l+" / "+d);let[{price:h,updated_at:b}]=m;return{pair:p===d[0]?[h.n.toString(),h.d.toString()]:[h.d.toString(),h.n.toString()],updatedAt:b.toString(),source:a.type}}if(a.type==="MMOracle"){let l=a.value.toString(),{price:u,decimals:p,updatedAt:d}=await this.mmOracles.get(l),m=(10n**BigInt(p)).toString();return{pair:[u.toString(),m],updatedAt:d.toString(),source:a.type}}if(a.type==="Value")return{pair:a.value.map(u=>u.toString()),updatedAt:r.toString()};throw new Error(a+" source not supported")});return Promise.all(n)}subscribeIssuance(){let e=this.store.pools.map(r=>r.id).map(r=>this.api.query.Tokens.TotalIssuance.watchValue(r,{at:"best"}).pipe((0,q.map)(({value:i})=>i),(0,q.map)((i,s)=>({value:i,index:s})),(0,q.tap)(({index:i,value:s})=>{i>0&&this.log.trace("tokens.TotalIssuance",r,s)}),(0,q.map)(({value:i})=>({id:r,value:i}))));return(0,q.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(r=>{let{id:i,value:s}=r;this.store.update(n=>{let a=[];return n.filter(o=>o.id===i).forEach(o=>{let l=o.tokens.map(u=>u.id===i?{...u,balance:s}:u);a.push({...o,tokens:l,totalIssuance:s})}),a})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,q.distinctUntilChanged)((t,e)=>!e.deltas),(0,q.map)((t,e)=>({value:t,index:e})),(0,q.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}})=>{for(let{args:e,value:r}of t?.upserted??[]){let[i]=e;this.pegs.set(r,i)}}})}subscribeEmaOracles(){return this.api.query.EmaOracle.Oracles.watchEntries({at:"best"}).pipe((0,q.distinctUntilChanged)((t,e)=>!e.deltas),(0,q.map)((t,e)=>({value:t,index:e})),(0,q.tap)(({value:t,index:e})=>{e>0&&this.log.trace("emaOracle.Oracles",t.deltas?.upserted)}),this.watchGuard("emaOracle.Oracles")).subscribe(async({value:{deltas:t}})=>{let e=new Set;for(let{args:r,value:i}of t?.upserted??[]){let[s,n,a]=r;this.emaOracles.set(i,s,n,a);let o=Os(s,n,a.type),l=this.mmRouting.byEma.get(o);l&&e.add(l)}for(let r of e){let i=await this.mmOracle.getData(r);this.log.trace("mmOracle.Hybrid",{h160:r,fresh:i}),this.mmOracles.set(i,r)}})}subscribeMMOracles(){return this.api.event.EVM.Log.watch().pipe((0,q.map)(({events:t})=>t.map(e=>Ae.parse(e.payload)).filter(e=>!!e).filter(({eventName:e})=>Wn.includes(e))),(0,q.filter)(t=>t.length>0),this.watchGuard("evm.Log")).subscribe(async t=>{let e=new Set;for(let r of t){if(console.log(r),r.eventName==="ManagedOracle.PriceUpdated"){let i=this.mmRouting.byEmitter.get(r.emitter);i&&e.add(i)}if(r.eventName==="DIA.OracleUpdate"&&r.key){let i=this.mmRouting.byDiaKey.get(r.key);i&&e.add(i)}}for(let r of e){let i=await this.mmOracle.getData(r);this.log.trace("mmOracle",{h160:r,fresh:i}),this.mmOracles.set(i,r)}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(async e=>{let r=[];for(let i of e){let s=this.poolsData.get(i.id);if(s){let n=await this.getPoolPegs(i.id,s,t),a=this.getPoolAmplification(s,t);r.push({...i,...n,...a})}}return r})})}subscribeUpdates(){let t=new q.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeMMOracles()),t.add(this.subscribeIssuance()),t.add(this.subscribeBlock()),t}};var fi={};E(fi,{XykMath:()=>wt,XykPool:()=>Re,XykPoolClient:()=>Fe});var N=require("@galacticcouncil/math-xyk"),wt=class{static getSpotPrice(t,e,r){return(0,N.get_spot_price)(t,e,r)}static calculateInGivenOut(t,e,r){return(0,N.calculate_in_given_out)(t,e,r)}static calculateOutGivenIn(t,e,r){return(0,N.calculate_out_given_in)(t,e,r)}static calculatePoolTradeFee(t,e,r){return(0,N.calculate_pool_trade_fee)(t,e,r)}static calculateLiquidityIn(t,e,r){return(0,N.calculate_liquidity_in)(t,e,r)}static calculateSpotPrice(t,e){return(0,N.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,r,i){return(0,N.calculate_spot_price_with_fee)(t,e,r,i)}static calculateShares(t,e,r){return(0,N.calculate_shares)(t,e,r)}static calculateLiquidityOutAssetA(t,e,r,i){return(0,N.calculate_liquidity_out_asset_a)(t,e,r,i)}static calculateLiquidityOutAssetB(t,e,r,i){return(0,N.calculate_liquidity_out_asset_b)(t,e,r,i)}};var ks=require("@galacticcouncil/common");var{FeeUtils:Es}=I,Re=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(n=>[n.id,n])),i=r.get(t),s=r.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:i.decimals,decimalsOut:s.decimals,balanceIn:i.balance,balanceOut:s.balance,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,r){let i=this.calculateInGivenOut(t,e),s=this.calculateTradeFee(i,r),n=Es.toPct(r.exchangeFee),a=i+s,o=[];(e<this.minTradingLimit||i<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:i,amountOut:e,feePct:n,errors:o}}validateAndSell(t,e,r){let i=this.calculateOutGivenIn(t,e),s=this.calculateTradeFee(i,r),n=Es.toPct(r.exchangeFee),a=i-s,o=[];(e<this.minTradingLimit||i<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:i,amountOut:a,feePct:n,errors:o}}calculateInGivenOut(t,e){let r=wt.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(r);return i<0n?0n:i}calculateOutGivenIn(t,e){let r=wt.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(r);return i<0n?0n:i}spotPriceInGivenOut(t){let e=wt.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=wt.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let r=wt.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(r)}normalizeSpot(t,e,r){let i=e-r;if(i===0)return t;let s=ks.big.pow10(Math.abs(i));return i>0?t*s:t/s}};var Rs=require("polkadot-api"),Fs=require("rxjs");var Fe=class extends Z{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,r]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:r}}async isSupported(){return(await this.api.getStaticApis()).compat.query.XYK.PoolAssets.isCompatible(Rs.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries({at:this.at}),this.getPoolLimits()]),r=t.map(async({keyArgs:i,value:s})=>{let[n]=i,[a,o]=s,[l,u,p,d]=await Promise.all([this.balance.getBalance(n,a),this.api.query.AssetRegistry.Assets.getValue(a,{at:this.at}),this.balance.getBalance(n,o),this.api.query.AssetRegistry.Assets.getValue(o,{at:this.at})]);return{address:n,type:"XYK",tokens:[{id:a,decimals:u?.decimals||this.decimals.get(a),existentialDeposit:u?.existential_deposit,balance:l.transferable,type:u?.asset_type.type},{id:o,decimals:d?.decimals||this.decimals.get(o),existentialDeposit:d?.existential_deposit,balance:p.transferable,type:d?.asset_type.type}],...e}});return Promise.all(r)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return Fs.Subscription.EMPTY}};var yi={};E(yi,{AavePool:()=>Ce,AavePoolClient:()=>Me});var te=require("@galacticcouncil/common");var Ce=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(n=>[n.id,n])),i=r.get(t),s=r.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,r){let i=this.calculateInGivenOut(t,e),s=[];return e>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e,r){let i=this.calculateOutGivenIn(t,e),s=[];return i>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:s}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return te.big.toBigInt(1,te.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return te.big.toBigInt(1,te.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var Cs=require("polkadot-api"),Ms=require("@polkadot-api/utils"),rt=require("rxjs"),wr=require("@galacticcouncil/common");var{ERC20:zn}=wr.erc20,$n=["Supply","Withdraw","Repay","Borrow"],Me=class extends Z{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let r=t+"/"+e,i=new TextEncoder().encode(r.padEnd(32,"\0")),s=(0,Ms.toHex)(i);return(0,Cs.AccountId)(wr.HYDRATION_SS58_PREFIX).dec(s)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:this.at})).map(async({reserve:r,atoken:i,liqudity_in:s,liqudity_out:n})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(r,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(r,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(i,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(i,{at:this.at})]);return{address:this.getPoolId(r,i),type:"Aave",tokens:[{id:r,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:s,location:o,type:a?.asset_type.type},{id:i,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:n,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,r]=t.tokens,{liqudity_in:i,liqudity_out:s}=await this.api.apis.AaveTradeExecutor.pool(e.id,r.id,{at:this.at});return t.tokens.map(n=>{let a=n.id===e.id?i:s;return{...n,balance:a}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:r}=e.value;return r.key}throw new Error("Invalid aave reserve multilocation")}return zn.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:r}=t;return{assetIn:e,assetOut:r,key:`${e}:${r}`}}subscribeRouterExecuted(){let e=this.store.pools.map(r=>r.tokens).map(([r,i])=>i).map(r=>r.id);return this.api.event.Router.Executed.watch().pipe((0,rt.mergeMap)(({events:r})=>r),(0,rt.map)(({payload:r})=>this.parseRouterLog(r)),(0,rt.filter)(({assetIn:r,assetOut:i})=>e.includes(r)||e.includes(i)),this.watchGuard("router.Execute")).subscribe(({assetIn:r,assetOut:i,key:s})=>{this.log.trace("router.Executed",s),this.store.update(async n=>{let a=[];for(let o of n){let[l,u]=o.tokens;if(u.id===r||u.id===i){let d=await this.getPoolDelta(o);a.push({...o,tokens:d})}}return a})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,rt.mergeMap)(({events:t})=>t),(0,rt.map)(({payload:t})=>de.parse(t)),(0,rt.filter)(t=>t!==void 0),(0,rt.filter)(({eventName:t})=>$n.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async r=>{let i=[];for(let s of r){let[n]=s.tokens;if(this.getReserveH160Id(n).toLowerCase()===t){let o=await this.getPoolDelta(s);i.push({...s,tokens:o})}}return i})})}subscribeBalances(){return rt.Subscription.EMPTY}subscribeUpdates(){let t=new rt.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var vi={};E(vi,{HsmMath:()=>at,HsmPool:()=>De,HsmPoolClient:()=>Le});var X=require("@galacticcouncil/math-hsm"),at=class{static calculateCollateralInGivenHollarOut(t,e,r){return(0,X.calculate_collateral_in_given_hollar_out)(t,e,r)}static calculateCollateralOutGivenHollarIn(t,e,r){return(0,X.calculate_collateral_out_given_hollar_in)(t,e,r)}static calculateHollarOutGivenCollateralIn(t,e,r){return(0,X.calculate_hollar_out_given_collateral_in)(t,e,r)}static calculateHollarInGivenCollateralOut(t,e,r){return(0,X.calculate_hollar_in_given_collateral_out)(t,e,r)}static calculateImbalance(t,e,r){return(0,X.calculate_imbalance)(t,e,r)}static calculateBuybackLimit(t,e){return(0,X.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,r){return(0,X.calculate_buyback_price_with_fee)(t,e,r)}static calculateMaxPrice(t,e){return(0,X.calculate_max_price)(t,e)}};var j=require("@galacticcouncil/common");var{FeeUtils:ee}=I,De=class c extends Lt{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 i=this.parsePair(t.assetOut,t.assetIn),s=super.calculateInGivenOut(i,e,{fee:this.fee}),n=this.calculateBuybackLimit(t);e>n&&r.push("MaxBuyBackExceeded");let a=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,s)>a&&r.push("MaxBuyPriceExceeded"),s>this.collateralBalance&&r.push("InsufficientCollateral"),r}validateTradeHollarOut(t,e,r){return this.collateralBalance+t>this.maxInHolding&&r.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&r.push("FacilitatorCapacityExceeded"),r}validateTradeConstraints(t,e,r){let i=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,i):this.validateTradeHollarOut(e,r,i)}validateAndBuy(t,e){let r=this.calculateInGivenOut(t,e),i=this.validateTradeConstraints(t,r,e);return{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e){let r=this.calculateOutGivenIn(t,e),i=this.validateTradeConstraints(t,e,r);return{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:i}}calculateHollarInGivenCollateralOut(t,e){let r=super.calculateInGivenOut(t,e,{fee:this.fee}),i=at.calculateHollarInGivenCollateralOut(e.toString(),r.toString(),ee.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),r=at.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),ee.toRaw(this.purchaseFee).toString());return BigInt(r)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let r=super.calculateOutGivenIn(t,e,{fee:this.fee}),i=at.calculateCollateralOutGivenHollarIn(e.toString(),r.toString(),ee.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),r=at.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),ee.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=at.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(r)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),r=at.calculateBuybackLimit(e.toString(),ee.toRaw(this.buyBackRate).toString());return BigInt(r)}calculateBuyPrice(t,e,r){let i=at.calculateBuybackPriceWithFee(r.toString(),e.toString(),ee.toRaw(this.buyBackFee).toString()),[s,n]=JSON.parse(i),a=j.big.pow10(t.decimalsIn+j.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(s)*a/BigInt(n)}calculateMaxPrice(t){let e=this.getCollateralPeg(),r=at.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[i,s]=JSON.parse(r),n=j.big.pow10(j.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(i)*n/BigInt(s)}spotPriceInGivenOut(t){let e=j.big.toBigInt(1,t.decimalsOut),i=this.calculateInGivenOut(t,e)*j.big.pow10(j.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(i,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=j.big.toBigInt(1,t.decimalsIn),i=this.calculateOutGivenIn(t,e)*j.big.pow10(j.RUNTIME_DECIMALS-t.decimalsIn);return this.normalizeSpotPrice(i,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(i=>i.id!==this.hollarId),e=this.pegs[t],r=this.tokens[t].decimals;return this.isDefaultPeg(e)?[j.big.toBigInt(1,18).toString(),j.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 i=e-r;if(i===0)return t;let s=j.big.pow10(Math.abs(i));return i>0?t*s:t/s}};var _r=require("polkadot-api"),Ns=require("@polkadot-api/utils"),z=require("rxjs"),Or=require("@galacticcouncil/common");var Ds=require("polkadot-api"),Ls=require("viem");var xr=[{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 Tr=class{static parse(t){let{topics:e,data:r}=t.log,i=Ds.Binary.toHex(r);try{let{eventName:s,args:n}=(0,Ls.decodeEventLog)({abi:xr,topics:e,data:i}),a=n.facilitatorAddress.toLowerCase();return{eventName:s,facilitator:a,key:`${s}:${a}`}}catch{return}}};var Ir=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[r,i]=await this.client.readContract({abi:xr,address:t,functionName:"getFacilitatorBucket",args:[e]});return r-i}};var{FeeUtils:Pi}=I,{H160:qs}=Or.h160,Kn=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Le=class extends Z{ghoClient;stableClient;constructor(t,e,r,i){super(t,e,i),this.stableClient=r,this.ghoClient=new Ir(e)}getPoolType(){return"HSM"}getPoolId(t){return this.getPoolAddress("hsm:"+t)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(t){if(t){let e=t.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:r}=e.value;return r.key}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),r=new TextEncoder().encode(e),i=(0,Ns.toHex)(r);return(0,_r.AccountId)(Or.HYDRATION_SS58_PREFIX).dec(i)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(_r.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,r,i]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t,{at:this.at}),this.api.query.HSM.Collaterals.getEntries({at:this.at}),this.stableClient.getPools()]);if(r.length===0)return[];let s=this.getFacilitatorAddress(),n=qs.fromAny(s),a=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(a,n),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:S}=d,v=i.find(T=>T.id===h);if(v){let T=this.getPoolId(h),B=await this.balance.getBalance(s,m);return{...v,address:T,type:"HSM",tokens:v.tokens.filter(D=>D.id!==h),hsmAddress:s,hsmMintCapacity:o,hollarId:t,hollarH160:a,collateralId:m,collateralBalance:B.transferable,maxBuyPriceCoefficient:b,maxInHolding:g,purchaseFee:Pi.fromPermill(f),buyBackFee:Pi.fromPermill(y),buyBackRate:Pi.fromPerbill(S)}}});return(await Promise.all(l)).filter(p=>p!==null)}async getPoolFees(){return{}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,z.mergeMap)(({events:t})=>t),(0,z.map)(({payload:t})=>Tr.parse(t)),(0,z.filter)(t=>t!==void 0),(0,z.filter)(({eventName:t})=>Kn.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async r=>{let i=[],[{hsmAddress:s,hollarH160:n}]=r,a=qs.fromAny(s);if(a.toLowerCase()===e){let l=await this.ghoClient.getFacilitatorCapacity(n,a);for(let u of r)i.push({...u,hsmMintCapacity:l})}return i})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(s=>{let{tokens:n,collateralId:a}=s;n.find(l=>l.id===a).type==="Erc20"?e.push(a):t.push(a)});let[{hsmAddress:r}]=this.store.pools,i=[];if(t.length>0){let s=this.balance.watchTokensBalance(r);i.push(s)}if(e.length>0){let s=this.balance.watchErc20Balance(r,e);i.push(s)}return i.length>0?(0,z.combineLatest)(i).pipe((0,z.map)(s=>s.flat()),(0,z.pairwise)(),(0,z.map)(([s,n])=>this.balance.getDeltas(s,n)),this.watchGuard("balances")).subscribe(s=>{this.store.update(n=>{let a=[],o=new Map(n.map(l=>[l.collateralId,l]));return s.forEach(({id:l,balance:u})=>{let p=o.get(l);p&&(this.log.trace("balances",{id:l,balance:u}),a.push({...p,collateralBalance:u.transferable}))}),a})}):z.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 i=[];for(let s of r){let n=e.get(s.id);n&&i.push({...s,fee:n.fee,tokens:n.tokens.filter(a=>a.id!==s.id),totalIssuance:n.totalIssuance,pegs:n.pegs,amplification:n.amplification,isRampPeriod:n.isRampPeriod})}return i})})}subscribeBalances(){return z.Subscription.EMPTY}subscribeUpdates(){let t=new z.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var re=class{static get(t){switch(t.type){case"Aave":return Ce.fromPool(t);case"XYK":return Re.fromPool(t);case"Omnipool":return Ie.fromPool(t);case"LBP":return xe.fromPool(t);case"Stableswap":return Lt.fromPool(t);case"HSM":return De.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var Hs=require("@galacticcouncil/common"),ot=require("rxjs");var{logger:Xn}=Hs.log,ie=class extends H{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=ot.Subscription.EMPTY;omniSub=ot.Subscription.EMPTY;stableSub=ot.Subscription.EMPTY;hsmSub=ot.Subscription.EMPTY;xykSub=ot.Subscription.EMPTY;lbpSub=ot.Subscription.EMPTY;isReady=!1;isDestroyed=new ot.Subject;constructor(t,e,r){super(t,r),this.evm=e,this.aave=new Me(t,e,r),this.omnipool=new _e(t,e,r),this.stableswap=new ke(t,e,r),this.hsm=new Le(t,e,this.stableswap,r),this.xyk=new Fe(t,e,r),this.lbp=new Te(t,e,r),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}get isHistorical(){return this.at!=="best"&&this.at!=="finalized"}subscribe(t){return this.isHistorical?ot.Subscription.EMPTY:t.getSubscriber().pipe((0,ot.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")||(Xn.info("[PoolContextProvider] auto-activating stableswap"),this.withStableswap()),this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let r=this.clients.find(i=>i.getPoolType()===e.type);if(r)return r.getPoolFees(t,e.address);throw new kt(e.type)}};var Ar=class{constructor(t){this.snapshot=t;let{aave:e,xyk:r,lbp:i,stable:s,omni:n}=t.pools;this.flat=[...e,...r,...i,...s,...n]}flat;async getPools(){return this.flat}async getPoolFees(t,e){let{block:r,states:i}=this.snapshot;switch(e.type){case"Aave":return{};case"XYK":{let{exchangeFee:s}=i.xyk;return{exchangeFee:s}}case"LBP":{let{repayFee:s}=i.lbp;return{exchangeFee:e.fee,repayFee:s}}case"Stableswap":return{fee:e.fee};case"Omnipool":{let s=t.assetOut,n=t.assetIn,{dynamicFees:a,emaOracles:o,assetFeeParams:l,protocolFeeParams:u,maxSlipFee:p}=i.omni,d=a.find(({asset:b})=>b===s)?.fee,m=o.find(({pair:b})=>b.join(":")===Pr(s))?.oracle,h=o.find(({pair:b})=>b.join(":")===Pr(n))?.oracle;return Dt.compute(t,r,d,m,h,l,u,p)}default:throw new kt(e.type)}}};var Ai={};E(Ai,{DCA_TIME_RESERVE:()=>Vs,DEFAULT_BLOCK_TIME:()=>Us,DEFAULT_MIN_BUDGET:()=>Ti,ORDER_MIN_BLOCK_PERIOD:()=>Ys,Router:()=>se,TWAP_EXECUTION_INTERVAL:()=>Ue,TWAP_MAX_DURATION:()=>_i,TWAP_MAX_PRICE_IMPACT:()=>Ii,TWAP_TX_MULTIPLIER:()=>fh,TradeOrderError:()=>xi,TradeOrderType:()=>Ge,TradeRouteBuilder:()=>it,TradeRouter:()=>Bt,TradeScheduler:()=>ne,TradeType:()=>Br});var qe=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 jn=10,Ne=class{isNotVisited(t,e){let r=!0;return e.forEach(i=>{(i[0]===t[0]||i[1]===t[1])&&(r=!1)}),r}findPaths(t,e,r){let i=[],s=new qe,n=[];for(n.push([e,""]),s.enqueue(n);s.size()>0;){let a=s.dequeue();if(!a||a.length>jn)continue;let o=a[a.length-1];(r===null||o[0]===r)&&i.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let p=[...a];p.push(u),s.enqueue(p)}})}return i}findShortestPaths(t,e,r){let i=[],s=new qe,n=[];n.push([e,""]),s.enqueue(n);let a=1/0;for(;s.size()>0;){let o=s.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===r){o.length<a?(a=o.length,i.length=0,i.push(o)):o.length===a&&i.push(o);continue}let u=t.get(l[0]);for(let p of u??[])this.isNotVisited(p,o)&&s.enqueue([...o,p])}return i}buildAndPopulateGraph(t,e){let r=new Map;for(let i of t)r.set(parseInt(i),[]);for(let[i,s,n]of e)r.get(s)?.push([n,i]);return r}};function wi(c){let t={};for(let e of c){let r=e.tokens.length;for(let i=0;i<r;i++){t[e.tokens[i].id]||(t[e.tokens[i].id]=[]);for(let s=0;s<r;s++){if(i==s)continue;let n=[e.address,e.tokens[i].id,e.tokens[s].id];t[e.tokens[i].id].push(n)}}}return t}var He=class{getProposals(t,e,r){let i=r.filter(g=>g.type==="XYK"),s=r.filter(g=>g.type!=="XYK"),n=new Set(s.map(g=>g.tokens).flat().map(g=>g.id)),a=n.has(t),o=n.has(e),l=new Ne,u=g=>{let f=wi(g),y=Object.keys(f),S=y.flatMap(v=>f[v]);return l.buildAndPopulateGraph(y,S)};if(!a&&!o){let g=i.filter(S=>S.tokens.find(v=>v.id===t)||S.tokens.find(v=>v.id===e)),f=u(g),y=l.findPaths(f,t,e);return this.parsePaths(y)}if(a&&o){let g=u(s),f=l.findPaths(g,t,e);return this.parsePaths(f)}let p=a?e:t,d=i.filter(g=>g.tokens.some(f=>f.id===p));if(d.length===0)return[];let m=[...s,...d],h=u(m),b=l.findPaths(h,t,e);return this.parsePaths(b)}parsePaths(t){let e=[];for(let r of t){let i=[];for(let s=0;s<r.length;s++){let n=r[s],a=r[s+1];if(a==null)break;i.push(this.toEdge(n,a))}e.push(i)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var se=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new He,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,r){return`${t}->${e}::${r.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:r=[]}=this.filter,i=new Set(e),s=new Set(r);return t.filter(n=>s.has(n.type)?!1:i.size>0?i.has(n.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let r=await this.getPools();return this.validateInput(t,e,r),this.getPaths(t,e,r)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(i=>i!==t).map(i=>this.getRoutes(i,t)))).filter(i=>i.length>0).map(([i])=>i[0].assetIn).sort()}validateInput(t,e,r){if(r.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let i=this.getAssets(r);if(!i.has(t))throw new Error(t+" is not supported asset");if(!i.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(r)}getAssets(t){let e=t.map(r=>r.tokens.map(i=>i.id)).flat().sort((r,i)=>r>i?1:-1);return new Set(e)}getPaths(t,e,r){let i=this.toPoolsMap(r);return this.getProposals(t,e,r).filter(n=>this.validPath(n,i)).map(n=>this.toHops(n,i))}getProposals(t,e,r){let i=this.buildRouteKey(t,e,r);if(this.routeProposals.has(i))return this.routeProposals.get(i);let s=this.routeSuggester.getProposals(t,e,r);return this.routeProposals.set(i,s),s}validPath(t,e){return t.length>0&&t.map(r=>this.validEdge(r,e)).reduce((r,i)=>r&&i)}validEdge([t,e,r],i){return i.get(t)?.validatePair(e,r)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,re.get(e)]))}toHops(t,e){return t.map(([r,i,s])=>{let n=e.get(r);return{poolAddress:r,poolId:n?.id,pool:n?.type,assetIn:i,assetOut:s}})}};var A=require("@galacticcouncil/common");var Br=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Br||{}),Ge=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(Ge||{}),xi=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(xi||{});var{FeeUtils:Gs}=I,Bt=class extends se{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,r){let i=super.validateInput(t,e,r),s=super.getPaths(t,e,r);if(!s.length)throw new ge(t,e);return{paths:s,pools:r,poolsMap:i}}async withCtx(t,e,r){let i=await super.getPools(),s=this.buildCtxSync(t,e,i);return r(s)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((r,i)=>{let s=r[r.length-1].amountOut,n=i[i.length-1].amountOut;return s>n?-1:1});return e.find(r=>r.every(i=>i.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(r=>r.tradeFeeRange).length>0){let r=t.map(s=>s.tradeFeeRange?.[0]??s.tradeFeePct).reduce((s,n)=>s+n),i=t.map(s=>s.tradeFeeRange?.[1]??s.tradeFeePct).reduce((s,n)=>s+n);return[r,i]}}getPoolFeeRange(t,e){let r=t.min?Gs.toPct(t.min):void 0,i=t.max?Gs.toPct(t.max):void 0;if(r&&i)return[r,Math.max(i,e)]}async getBestSell(t,e,r){return this.getSell(t,e,r)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,r,i){return this.withCtx(t,e,async({paths:s,poolsMap:n})=>{let a;if(i)a=await this.toSellSwaps(r,i,n);else{let o=s.map(u=>this.toSellSwaps(r,u,n)),l=await Promise.all(o);a=this.findBestSellRoute(l)}return this.buildSell(n,a)})}async getSells(t,e,r){return this.withCtx(t,e,async({paths:i,poolsMap:s})=>{let n=i.map(o=>this.toSellSwaps(r,o,s));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(s,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let r=e[0],i=e[e.length-1],s=this.isDirectTrade(e),n=this.getSellSpot(e),a=i.amountOut,o=s?i.calculatedOut:this.calculateDelta0Y(r.amountIn,e,t),l=o-a,u=this.getRouteFeeRange(e),p=s?i.tradeFeePct:$.calculateSellFee(o,a),d=F.mulSpot(r.amountIn,n,r.assetInDecimals,i.assetOutDecimals),m=$.calculateDiffToRef(o,d);return{type:"Sell",amountIn:r.amountIn,amountOut:i.amountOut,spotPrice:n,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Sell",amountIn:A.big.toDecimal(r.amountIn,r.assetInDecimals),amountOut:A.big.toDecimal(i.amountOut,i.assetOutDecimals),spotPrice:A.big.toDecimal(n,A.RUNTIME_DECIMALS),tradeFee:A.big.toDecimal(l,i.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(A.RUNTIME_DECIMALS))}calculateDelta0Y(t,e,r){let i=[];for(let s=0;s<e.length;s++){let n=e[s],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;s>0?l=i[s-1]:l=t;let u=a.calculateOutGivenIn(o,l);i.push(u)}return i[i.length-1]}async calculateMostLiquidRoute(t,e,r){let{paths:i,pools:s,poolsMap:n}=r,l=s.filter(b=>b.tokens.some(g=>g.id===t)).map(b=>b.type==="Aave"?b.tokens:b.tokens.filter(g=>g.id===t)).map(b=>b.map(g=>g.balance).reduce((g,f)=>g+f)).sort((b,g)=>g<b?-1:1)[0],u=F.getFraction(l,.1),p=await Promise.all(i.map(b=>this.toSellSwaps(u,b,n))),m=this.findBestSellRoute(p).map(b=>({poolAddress:b.poolAddress,poolId:b?.poolId,pool:b.pool,assetIn:b.assetIn,assetOut:b.assetOut})),h=this.buildRouteKey(t,e,s);return this.mlr.set(h,m),m}async toSellSwaps(t,e,r){let i=[];for(let s=0;s<e.length;s++){let n=e[s],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;s>0?l=i[s-1].amountOut:l=typeof t=="string"?A.big.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(o,a),{amountOut:p,calculatedOut:d,feePct:m,errors:h}=a.validateAndSell(o,l,u),b=this.getPoolFeeRange(u,m),g=a.spotPriceOutGivenIn(o),f=F.mulSpot(l,g,o.decimalsIn,o.decimalsOut),y=$.calculateDiffToRef(d,f);i.push({...n,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===n.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:A.big.toDecimal(l,o.decimalsIn),amountOut:A.big.toDecimal(p,o.decimalsOut),calculatedOut:A.big.toDecimal(d,o.decimalsOut),spotPrice:A.big.toDecimal(g,A.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h}}})}return i}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async r=>{let i=this.buildRouteKey(t,e,r.pools),s=this.mlr.get(i);return s||this.calculateMostLiquidRoute(t,e,r)})}async getSpotPrice(t,e){return this.withCtx(t,e,async r=>{let{pools:i,poolsMap:s}=r,n=this.buildRouteKey(t,e,i),a=this.mlr.get(n);a||(a=await this.calculateMostLiquidRoute(t,e,r));let o=await this.toSellSwaps("1",a,s);return{amount:this.getSellSpot(o),decimals:A.RUNTIME_DECIMALS}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((r,i)=>{let s=r[0].amountIn,n=i[0].amountIn;return s>n?1:-1});return e.find(r=>r.every(i=>i.errors.length==0))||e[0]}async getBestBuy(t,e,r){return this.getBuy(t,e,r)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,r,i){return this.withCtx(t,e,async({paths:s,poolsMap:n})=>{let a;if(i)a=await this.toBuySwaps(r,i,n);else{let o=s.map(u=>this.toBuySwaps(r,u,n)),l=await Promise.all(o);a=this.findBestBuyRoute(l)}return this.buildBuy(n,a)})}async getBuys(t,e,r){return this.withCtx(t,e,async({paths:i,poolsMap:s})=>{let n=i.map(o=>this.toBuySwaps(r,o,s));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(s,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let r=e[e.length-1],i=e[0],s=this.isDirectTrade(e),n=this.getBuySpot(e),a=i.amountIn,o=s?i.calculatedIn:this.calculateDelta0X(r.amountOut,e,t),l=a-o,u=this.getRouteFeeRange(e),p=s?i.tradeFeePct:$.calculateBuyFee(o,a),d=F.mulSpot(r.amountOut,n,r.assetOutDecimals,i.assetInDecimals),m;return o===0n?m=-100:m=$.calculateDiffToRef(d,o),{type:"Buy",amountOut:r.amountOut,amountIn:i.amountIn,spotPrice:n,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Buy",amountOut:A.big.toDecimal(r.amountOut,r.assetOutDecimals),amountIn:A.big.toDecimal(i.amountIn,i.assetInDecimals),spotPrice:A.big.toDecimal(n,A.RUNTIME_DECIMALS),tradeFee:A.big.toDecimal(l,i.assetInDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e.map(h=>h.toHuman())}}}}calculateDelta0X(t,e,r){let i=[];for(let s=e.length-1;s>=0;s--){let n=e[s],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;s==e.length-1?l=t:l=i[0];let u=a.calculateInGivenOut(o,l);i.unshift(u)}return i[0]}async toBuySwaps(t,e,r){let i=[];for(let s=e.length-1;s>=0;s--){let n=e[s],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;s==e.length-1?l=typeof t=="string"?A.big.toBigInt(t,o.decimalsOut):t:l=i[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=F.mulSpot(l,g,o.decimalsOut,o.decimalsIn),y;d===0n?y=-100:y=$.calculateDiffToRef(f,d),i.unshift({...n,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===n.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===n.assetIn},toHuman(){return{...n,amountOut:A.big.toDecimal(l,o.decimalsOut),amountIn:A.big.toDecimal(p,o.decimalsIn),calculatedIn:A.big.toDecimal(d,o.decimalsIn),spotPrice:A.big.toDecimal(g,A.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:y,errors:h}}})}return i}};var M=require("@galacticcouncil/common");var Us=6e3,Ti=1000000000000000n,Ue=6,Ii=-5,_i=216e5,fh=3,Vs=.1,Ys=6;var Oi=require("polkadot-api");var it=class{static build(t){return t.map(({assetIn:e,assetOut:r,pool:i,poolId:s})=>i==="Stableswap"?{pool:(0,Oi.Enum)("Stableswap",s),asset_in:e,asset_out:r}:{pool:(0,Oi.Enum)(i),asset_in:e,asset_out:r})}};var ne=class{schedulerOptions;router;constructor(t,e={}){this.router=new Bt(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Ti})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,r,i,s){let n=await this.router.getBestSell(t,e,r),{amountIn:a,swaps:o,priceImpactPct:l}=n,u=o[0],p=o[o.length-1],{assetInDecimals:d}=u,{assetOutDecimals:m}=p,h=Math.abs(l),b=await this.getMinimumOrderBudget(t,d),g=this.getOptimalTradeCount(h),f=this.getMaximumTradeCount(a,b,i),y=s||Math.min(g,f),S=Math.round(i/y),v=a/BigInt(y),T=await this.router.getBestSell(t,e,v),B=a<b,D=[];B&&D.push("OrderTooSmall");let J=await this.getAssetOutEd(p),Y=T.amountOut*BigInt(y),ft=this.toBlockPeriod(S),tt=T.tradeFee*BigInt(y),ct=it.build(o),xt={assetIn:t,assetOut:e,assetOutEd:J,errors:D,maxTradeCount:f,tradeCount:y,tradeFee:tt,tradeImpactPct:T.priceImpactPct,tradePeriod:ft,tradeRoute:ct,type:"Dca"};return{...xt,amountIn:a,amountOut:Y,tradeAmountIn:T.amountIn,tradeAmountOut:T.amountOut,toHuman(){return{...xt,amountIn:M.big.toDecimal(a,d),amountOut:M.big.toDecimal(Y,m),assetOutEd:M.big.toDecimal(J,m),tradeAmountIn:M.big.toDecimal(T.amountIn,d),tradeAmountOut:M.big.toDecimal(T.amountOut,m)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let r=await this.router.getSpotPrice(0,t);if(r)return F.mulSpot(this.minOrderBudget,r.amount,12,e);let i=await this.router.getSpotPrice(t,0);if(i)return F.divSpot(this.minOrderBudget,i.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,r){let i=e*2n/10n;if(i===0n)return 0;let s=Number(t/i),n=Math.floor(r/this.blockTime),a=Math.max(0,Math.floor(n*(1-.1)));return Math.min(s,a)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,r,i){let s=await this.router.getBestSell(t,e,r),{swaps:n}=s,a=n[0],o=n[n.length-1],{assetInDecimals:l}=a,{assetOutDecimals:u}=o,p=await this.getMinimumOrderBudget(t,l),d=s.amountIn<p,m=[];d&&m.push("OrderTooSmall");let h=await this.getAssetOutEd(o),b=this.toBlockPeriod(i),g=it.build(n),f={assetIn:t,assetOut:e,assetOutEd:h,errors:m,maxTradeCount:0,tradeCount:0,tradeFee:s.tradeFee,tradeImpactPct:s.priceImpactPct,tradePeriod:b,tradeRoute:g,type:"Dca"};return{...f,amountIn:0n,amountOut:0n,tradeAmountIn:s.amountIn,tradeAmountOut:s.amountOut,toHuman(){return{...f,amountIn:"0",amountOut:"0",assetOutEd:M.big.toDecimal(h,u),tradeAmountIn:M.big.toDecimal(s.amountIn,l),tradeAmountOut:M.big.toDecimal(s.amountOut,u)}}}}async getTwapSellOrder(t,e,r){let i=await this.router.getBestSell(t,e,r),{amountIn:s,swaps:n,priceImpactPct:a}=i,o=n[0],l=n[n.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),h=s/BigInt(m),[b,g]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestSell(o.assetIn,l.assetOut,h)]),f=m===1,y=s<b,S=g.priceImpactPct<-5,v=[];y||f?v.push("OrderTooSmall"):S&&v.push("OrderImpactTooBig");let T=await this.getAssetOutEd(l),B=g.amountOut*BigInt(m),D=g.tradeFee*BigInt(m),J=it.build(n),Y={assetIn:t,assetOut:e,assetOutEd:T,errors:v,tradeCount:m,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:J,type:"TwapSell"};return{...Y,amountIn:s,amountOut:B,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:D,toHuman(){return{...Y,amountIn:M.big.toDecimal(s,u),amountOut:M.big.toDecimal(B,p),assetOutEd:M.big.toDecimal(T,p),tradeAmountIn:M.big.toDecimal(g.amountIn,u),tradeAmountOut:M.big.toDecimal(g.amountOut,p),tradeFee:M.big.toDecimal(D,p)}}}}async getTwapBuyOrder(t,e,r){let i=await this.router.getBestBuy(t,e,r),{amountOut:s,swaps:n,priceImpactPct:a}=i,o=n[0],l=n[n.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),h=s/BigInt(m),[b,g]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestBuy(o.assetIn,l.assetOut,h)]),f=g.amountIn*BigInt(m),y=m===1,S=f<b,v=g.priceImpactPct<-5,T=[];S||y?T.push("OrderTooSmall"):v&&T.push("OrderImpactTooBig");let B=await this.getAssetOutEd(l),D=g.tradeFee*BigInt(m),J=it.build(n),Y={assetIn:t,assetOut:e,assetOutEd:B,errors:T,tradeCount:m,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:J,type:"TwapBuy"};return{...Y,amountIn:f,amountOut:s,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:D,toHuman(){return{...Y,amountIn:M.big.toDecimal(f,u),amountOut:M.big.toDecimal(s,p),assetOutEd:M.big.toDecimal(B,p),tradeAmountIn:M.big.toDecimal(g.amountIn,u),tradeAmountOut:M.big.toDecimal(g.amountOut,p),tradeFee:M.big.toDecimal(D,u)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let i=216e5/(this.blockTime*6);return Math.round(i)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,r=Math.round(e);return Math.max(r,6)}async getAssetOutEd(t){let i=(await this.router.getPools()).find(s=>s.address===t.poolAddress)?.tokens.find(s=>s.id===t.assetOut);if(!i)throw new Error(`Asset ${t.assetOut} not found in pool ${t.poolAddress}`);return i.existentialDeposit}};var ki={};E(ki,{BIG_10:()=>js,BIG_BILL:()=>Bi,StakingApi:()=>Ve,StakingClient:()=>Ye});var Q=require("@galacticcouncil/math-staking"),st=Tt(require("big.js"));var Er={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},Ws=c=>Object.keys(Er).includes(c);var zs=require("polkadot-api"),$s=require("@polkadot-api/utils"),Ks=require("@galacticcouncil/common");function Xs(c){let t=("modl"+c).padEnd(32,"\0"),e=new TextEncoder().encode(t),r=(0,$s.toHex)(e);return(0,zs.AccountId)(Ks.HYDRATION_SS58_PREFIX).dec(r)}var kr="20000000000000000",Rr="2000",js=(0,st.default)(10),Bi=(0,st.default)(js.pow(12)),Ve=class{client;balance;constructor(t,e){this.client=t,this.balance=e}async getPotBalance(){let t=await this.client.getPalletId(),e=Xs(t);return await this.balance.getBalance(e,0)}async getStakingPosition(t){let[e,r]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let i=e.created_at,s=await r.reduce(async(n,[a,o])=>{let l=await n,u=a,p=o.amount,d=o.conviction.type.toLowerCase(),m=await this.client.getReferendumInfo(u);return m&&(m.type==="Approved"||m.type==="Rejected")&&Ws(d)&&l.push({id:u,amount:p,conviction:d}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:i,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:s}}async getStake(t){let e=await this.client.getNFTCollectionId(),[r,i]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),s=i.find(n=>n)?.itemId;return{totalStake:r?.total_stake,accumulatedRewardPerStake:r?.accumulated_reward_per_stake,potReservedBalance:r?.pot_reserved_balance,positionId:s,stakePosition:s?await this.getStakingPosition(s):void 0}}getCurrentActionPoints(t,e,r,i){let s=(0,st.default)(0),n=(0,st.default)(0),a=Er.locked6x,o=(0,st.default)(r.toString()).mul(a),l=100,u=[];t.forEach(m=>{let h=Er[m.conviction],b=i.includes(m.id.toString());b&&u.push(m.id.toString());let g=(0,st.default)(m.amount.toString()).mul(l).div(o);s=s.plus(Math.floor(g.mul(h).toNumber())),n=n.plus(Math.floor(g.mul(b?a:h).toNumber()))});let p=Math.floor((0,st.default)(r.toString()).mul(a).mul(l).div(o).toNumber());i.forEach(m=>{u.includes(m)||(n=n.plus(p))});let d={democracyVote:1};return s=s.mul(d.democracyVote),s=s.plus(e.toString()||"0"),n=n.mul(d.democracyVote),n=n.plus(e.toString()||"0"),{currentActionPoints:s.toString(),maxActionPoints:n.toString()}}async getRewards(t,e,r){let i=await this.getStake(t),{potReservedBalance:s,accumulatedRewardPerStake:n,totalStake:a,stakePosition:o}=i;if(!o)return;let[l,u,p,d,m,h,b]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),g=(0,st.default)(l.transferable.toString()).minus(s.toString()),f=g.gt(0)&&a>0?(0,Q.calculate_accumulated_rps)(n.toString(),g.toString(),a.toString()):n.toString(),y=(0,Q.calculate_period_number)(u.toString(),r,b),S=(0,Q.calculate_period_number)(u.toString(),o.createdAt.toString(),b),v=(0,Q.calculate_rewards)(f,o.rewardPerStake.toString(),o.stake.toString()),T=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),B=(0,Q.calculate_points)(S,y,d.toString(),m.toString(),T.currentActionPoints,h.toString(),o.accumulatedSlashPoints.toString()),D=(0,Q.sigmoid)(B,kr,Rr),J=(()=>{if(!e.length)return;let xt=(0,Q.calculate_points)(S,y,d.toString(),m.toString(),T.maxActionPoints.toString(),h.toString(),o.accumulatedSlashPoints.toString());return(0,Q.sigmoid)(xt,kr,Rr)})(),Y=(0,st.default)(v).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if((0,st.default)(y).minus(S).lte(p.toString()))return{rewards:"0",payablePercentage:D,extraPayablePercentage:J,constants:{a:kr,b:Rr}};let ft=(0,Q.calculate_percentage_amount)(Y.toString(),D),tt=(0,st.default)(o.accumulatedLockedRewards.toString()),ct=tt.gt(ft)?tt:(0,st.default)(ft);return{rewards:ct.div(Bi).toString(),maxRewards:Y.div(Bi).toString(),allocatedRewardsPercentage:ct.div(Y).mul(100).toNumber(),points:B,payablePercentage:D,extraPayablePercentage:J,constants:{a:kr,b:Rr}}}};var Ei=require("polkadot-api");var Ye=class extends H{async getPalletId(){let t=this.api.constants.Staking.PalletId,e=await t();return Ei.Binary.toText(Ei.Binary.fromHex(e))}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:n})=>{let[a,o,l]=n;return{address:a,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var Ci={};E(Ci,{TxBuilderFactory:()=>ae});var Ri=require("polkadot-api");function Qs(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var lt=class extends H{evm;evmClient;balance;aaveUtils;constructor(t,e,r){super(t,r),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new mt(t,r),this.aaveUtils=new Et(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:r=>this.dryRun(r,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:Yr})}async dryRun(t,e){let r=(0,Ri.Enum)("Signed",t),i=(0,Ri.Enum)("system",r),n=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(i,e.decodedCall,4,{at:this.at}),a=n.success&&!n.value.execution_result.success?n.value.execution_result.value.error:null;if(a){let o=a.type==="Module"?Qs(a.value):a.type;throw new Error("Dry run execution error!",{cause:o})}return n}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var Fr=class extends lt{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let{assetIn:i}=e[0],s=await this.balance.getBalance(this.beneficiary,i);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:r}=this.trade,i=r[0],s=r[r.length-1],n=F.getFraction(t,this.slippagePct),a=i.assetIn,o=s.assetOut,l=t+n,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:it.build(r)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:r}=this.trade,i=r[0],s=r[r.length-1],n=F.getFraction(e,this.slippagePct),a=i.assetIn,o=s.assetOut,l=e-n,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:it.build(r)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,r=e[0],i=e[e.length-1],s=F.getFraction(t,this.slippagePct),n=r.assetIn,a=i.assetOut,o=t-s,l=this.api.tx.Router.sell_all({asset_in:n,asset_out:a,min_amount_out:o,route:it.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var Cr=require("polkadot-api");var Mr=class extends lt{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:r,tradeAmountIn:i,tradePeriod:s,tradeRoute:n}=this.order,a=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Cr.Enum)("Sell",{asset_in:e,asset_out:r,amount_in:i,min_amount_out:0n,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(a=await this.dispatchWithExtraGas(a)),this.wrapTx("DcaSchedule",a)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:r,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:n,tradeRoute:a}=this.order,o=F.getFraction(s,this.slippagePct),l=s-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Cr.Enum)("Sell",{asset_in:e,asset_out:r,amount_in:i,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:r,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:n,tradeRoute:a}=this.order,o=F.getFraction(i,this.slippagePct),l=i+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Cr.Enum)("Buy",{asset_in:e,asset_out:r,amount_out:s,max_amount_in:l,route:a})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("DcaSchedule.twapBuy",u)}};var Js=require("polkadot-api");var Dr=class extends lt{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,amountOut:e,swaps:r}=this.trade,i=r[0],s=r[r.length-1],n=i.assetIn,a=s.assetOut,o=F.getFraction(e,this.slippagePct),l=e-o,u=(0,Js.Enum)("Swap",{asset_in:n,asset_out:a,amount_in:t,amount_out:l,partial:!1}),p=this.apiIce.tx.Intent.submit_intent({intent:{data:u}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(p=await this.dispatchWithExtraGas(p)),this.wrapTx("IntentSwap",p)}};var Zs=require("polkadot-api");var Lr=class extends lt{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:r}=this.trade,i=r[0],s=r[r.length-1],n=i.assetIn,a=s.assetOut,o=(0,Zs.Enum)("Swap",{asset_in:n,asset_out:a,amount_in:t,amount_out:this.minAmountOut??e,partial:this.partial}),l=this.apiIce.tx.Intent.submit_intent({intent:{data:o,deadline:this.deadline}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("IntentLimitOrder",l)}};var Fi=require("polkadot-api");var qr=class extends lt{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:r,assetOutEd:i,tradeAmountIn:s,tradePeriod:n}=this.order,a=(0,Fi.Enum)("Dca",{asset_in:e,asset_out:r,amount_in:s,amount_out:i,slippage:this.slippagePct*1e4,budget:t,period:n}),o=this.apiIce.tx.Intent.submit_intent({intent:{data:a}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("IntentDcaSchedule",o)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:r,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:n}=this.order,a=F.getFraction(s,this.slippagePct),o=s-a,l=(0,Fi.Enum)("Dca",{asset_in:e,asset_out:r,amount_in:i,amount_out:o,slippage:this.slippagePct*1e4,budget:t,period:n}),u=this.apiIce.tx.Intent.submit_intent({intent:{data:l}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("IntentDcaSchedule.twap",u)}};var ae=class{client;evmClient;at;constructor(t,e,r){this.client=t,this.evmClient=e,this.at=r}trade(t){return new Fr(this.client,this.evmClient,this.at).setTrade(t)}order(t){return new Mr(this.client,this.evmClient,this.at).setOrder(t)}intentMarket(t){return new Dr(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new Lr(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new qr(this.client,this.evmClient).setOrder(t)}};async function Qn(c,t){let{at:e}=t??{},r=new Wt(c),i=new fe(c,e),[s,n]=await Promise.all([r.getBlockTime(),r.getMinOrderBudget()]),a=new ie(c,i,e).withAave().withOmnipool().withStableswap().withXyk(),o=new mt(c,e),l=new Ye(c),u=new we(c),p=new Et(i),d=new Bt(a),m=new ne(a,{blockTime:s,minBudgetInNative:n}),h=new Ve(l,o),b=new ve(u,o,{blockTime:s});return{api:{aave:p,router:d,scheduler:m,staking:h,farm:b},client:{asset:new Gt(c),balance:o,evm:i},ctx:{pool:a},tx:new ae(c,i,e),destroy:()=>{a.destroy()}}}0&&(module.exports={QueryBus,aave,api,async,calc,client,const:null,createSdkContext,error,evm,farm,fmt,indexer,json,math,pool,sor,staking,tx});
|
|
1
|
+
"use strict";var Bn=Object.create;var ni=Object.defineProperty;var kn=Object.getOwnPropertyDescriptor;var En=Object.getOwnPropertyNames;var Rn=Object.getPrototypeOf,Cn=Object.prototype.hasOwnProperty;var Ji=(c,t)=>()=>(c&&(t=c(c=0)),t);var C=(c,t)=>{for(var e in t)ni(c,e,{get:t[e],enumerable:!0})},si=(c,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of En(t))!Cn.call(c,r)&&r!==e&&ni(c,r,{get:()=>t[r],enumerable:!(i=kn(t,r))||i.enumerable});return c},wt=(c,t,e)=>(si(c,t,"default"),e&&si(e,t,"default")),St=(c,t,e)=>(e=c!=null?Bn(Rn(c)):{},si(t||!c||!c.__esModule?ni(e,"default",{value:c,enumerable:!0}):e,c)),Fn=c=>si(ni({},"__esModule",{value:!0}),c);var ge={};var rs=Ji(()=>{wt(ge,require("@polkadot-api/sm-provider"))});var be={};var ss=Ji(()=>{wt(be,require("@polkadot-api/smoldot"))});var fe={};var ns=Ji(()=>{wt(fe,require("@polkadot-api/known-chains/polkadot"))});var Ia={};C(Ia,{QueryBus:()=>Lt,aave:()=>sr,api:()=>tr,async:()=>Ie,calc:()=>M,client:()=>or,const:()=>ar,createSdkContext:()=>Ta,error:()=>cr,evm:()=>mr,farm:()=>wr,fmt:()=>O,indexer:()=>vr,json:()=>Jt,math:()=>U,pool:()=>qr,sor:()=>Wr,staking:()=>$r,tx:()=>jr});module.exports=Fn(Ia);var tr={};C(tr,{Papi:()=>V,Watcher:()=>he,getSm:()=>Dn,getWs:()=>Zi});var Yt=require("@galacticcouncil/descriptors");var ts=require("@galacticcouncil/common"),Wt=require("rxjs");var vt=require("rxjs"),W=require("rxjs/operators");function Zr(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>(0,vt.defer)(()=>(0,vt.from)(c._request("system_health",[]))).pipe((0,W.timeout)({first:e}),(0,W.map)(()=>"online"),(0,W.catchError)(()=>(0,vt.of)("offline")));return(0,vt.of)({state:"offline",delayMs:0}).pipe((0,W.expand)(s=>(0,vt.timer)(s.delayMs).pipe((0,W.switchMap)(i),(0,W.map)(n=>({state:n,delayMs:t})))),(0,W.skip)(1),(0,W.map)(s=>s.state),(0,W.distinctUntilChanged)(),(0,W.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Mn}=ts.log,he=class c{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,Wt.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Zr(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe((0,Wt.tap)({error:i=>Mn.error(t,i)}),(0,Wt.shareReplay)({bufferSize:1,refCount:!0}))}};var V=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(Yt.hydration),this.apiNext=this.client.getTypedApi(Yt.hydrationNext),this.apiIce=this.client.getTypedApi(Yt.hydrationIce),this.watcher=he.getInstance(this.client),this.at=e??"best"}};var es=require("polkadot-api/ws"),is=require("polkadot-api/logs-provider"),Zi=(c,t={})=>{let e=typeof c=="string"?c.split(","):c,i=(0,es.getWsProvider)(e,t);return(0,is.withLogsRecorder)(r=>console.log(r),i),i};async function Dn(c){let{getSmProvider:t}=await Promise.resolve().then(()=>(rs(),ge)),{start:e}=await Promise.resolve().then(()=>(ss(),be)),{chainSpec:i}=await Promise.resolve().then(()=>(ns(),fe)),r=e(),s=await r.addChain({chainSpec:i}),n=await r.addChain({chainSpec:c,potentialRelayChains:[s]});return t(()=>n)}var sr={};C(sr,{AAVE_GAS_LIMIT:()=>ir,AAVE_LENDING_POOL_ADDRESS:()=>li,AAVE_POOL_ABI:()=>ye,AAVE_POOL_DATA_PROVIDER:()=>oi,AAVE_POOL_DATA_PROVIDER_ABI:()=>ai,AAVE_POOL_PROXY:()=>er,AAVE_ROUNDING_THRESHOLD:()=>ja,AAVE_UINT_256_MAX:()=>Ln,AaveClient:()=>Pe,AaveLog:()=>we,AaveUtils:()=>Ft});var ye=[{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 ai=[{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 er="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",oi="0x112b087b60C1a166130d59266363C45F8aa99db0",li="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ir=1000000n,ja=5,Ln=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Pe=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:ai,address:oi,args:[li],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:ai,address:oi,args:[li,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:ye,address:er,args:[t],functionName:"getUserAccountData"})}};var as=require("polkadot-api"),os=require("viem");var we=class{static parse(t){let{topics:e,data:i}=t.log,r=as.Binary.toHex(i);try{let{eventName:s,args:n}=(0,os.decodeEventLog)({abi:ye,topics:e,data:r}),a=n.reserve.toLowerCase();return{eventName:s,reserve:a,key:`${s}:${a}`}}catch{return}}};var G=St(require("big.js")),lt=require("@galacticcouncil/common");var{ERC20:zt}=lt.erc20,{H160:rr}=lt.h160,qn=1.01,Nn=31536000n,ls=4,ci=-1,ui=10n**27n,Ft=class{client;constructor(t){this.client=new Pe(t)}async getSummary(t){let e=rr.fromAny(t),[i,r,s,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[a]=i,[o,l]=r,[u,p,d,m,h,g]=s,b=lt.big.toDecimal(g,18),f=[];for(let y of o){let S=y.underlyingAsset.toLowerCase(),w=a.find(({underlyingAsset:Qi})=>Qi.toLowerCase()===S);if(!w)throw new Error("Missing pool reserve for "+S);let v=y.scaledATokenBalance,I=w.liquidityIndex,_=w.liquidityRate,et=w.availableLiquidity,$=w.priceInMarketReferenceCurrency,Pt=n+6,it=this.calculateLinearInterest(_,w.lastUpdateTimestamp,Pt),pt=I*it/ui,_t=v*pt/ui,ei=Number(l!==0&&l===w.eModeCategoryId?w.eModeLiquidationThreshold:w.reserveLiquidationThreshold)/1e4,ii=w.usageAsCollateralEnabled&&y.usageAsCollateralEnabledOnUser&&y.scaledATokenBalance>0n,ri=zt.toAssetId(S);f.push({aTokenBalance:_t,availableLiquidity:et,decimals:Number(w.decimals),isCollateral:ii,priceInRef:$,reserveId:ri,reserveAsset:S,reserveLiquidationThreshold:ei})}return{healthFactor:Number(b),currentLiquidationThreshold:Number(lt.big.toDecimal(m,ls)),totalCollateral:u,totalDebt:p,reserves:f}}async hasBorrowPositions(t){let e=rr.fromAny(t),i=await this.client.getUserAccountData(e),[r,s]=i;return s>0n}async getHealthFactor(t){let e=rr.fromAny(t),i=await this.client.getUserAccountData(e),[r,s,n,a,o,l]=i;return this.calculateHealthFactorFromBalances(s,r,a)}async getHealthFactorAfterWithdraw(t,e,i){let{totalCollateral:r,totalDebt:s,reserves:n,currentLiquidationThreshold:a}=await this.getSummary(t);if(s===0n)return ci;let o=zt.fromAssetId(e),l=n.find(S=>S.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:u,isCollateral:p,priceInRef:d,reserveLiquidationThreshold:m}=l,h=lt.big.toBigInt(i,u),g=p?h*d/10n**BigInt(u):0n,b=r-g;if(b<=0n)return 0;let f=(0,G.default)(r.toString()).mul(a).minus((0,G.default)(g.toString()).mul(m)).div(b.toString()),y=(0,G.default)(b.toString()).mul(f).div(s.toString()).toFixed(6,G.default.roundDown);return Number(y)}async getHealthFactorAfterSupply(t,e,i){let{totalCollateral:r,totalDebt:s,reserves:n,currentLiquidationThreshold:a}=await this.getSummary(t);if(s===0n)return ci;let o=zt.fromAssetId(e),l=n.find(y=>y.reserveAsset===o);if(!l)throw new Error("Missing reserve ctx for "+o);let{decimals:u,priceInRef:p,reserveLiquidationThreshold:d}=l,h=lt.big.toBigInt(i,u)*p/10n**BigInt(u),g=r+h;if(g<=0n)return 0;let b=(0,G.default)(r.toString()).mul(a).plus((0,G.default)(h.toString()).mul(d)).div(g.toString()),f=(0,G.default)(g.toString()).mul(b).div(s.toString()).toFixed(6,G.default.roundDown);return Number(f)}async getHealthFactorAfterSwap(t,e,i,r,s){let{totalDebt:n,reserves:a,healthFactor:o}=await this.getSummary(t);if(n===0n)return ci;let l=zt.fromAssetId(i),u=zt.fromAssetId(s),p=a.find(I=>I.reserveAsset===l),d=a.find(I=>I.reserveAsset===u);if(!p)throw new Error(`Missing reserve ctx for ${l}`);if(!d)throw new Error(`Missing reserve ctx for ${d}`);let m=lt.big.toBigInt(e,p.decimals),h=lt.big.toBigInt(r,d.decimals),g=m*p.priceInRef/10n**BigInt(p.decimals),b=h*d.priceInRef/10n**BigInt(d.decimals),f=p.isCollateral?(0,G.default)(g.toString()).mul(p.reserveLiquidationThreshold):(0,G.default)(0),w=(d.isCollateral?(0,G.default)(b.toString()).mul(d.reserveLiquidationThreshold):(0,G.default)(0)).minus(f).div(n.toString()),v=(0,G.default)(o).plus(w).toFixed(6,G.default.roundDown);return Number(v)}async getMaxWithdraw(t,e){let{totalDebt:i,reserves:r,healthFactor:s}=await this.getSummary(t),n=zt.fromAssetId(e),a=r.find(o=>o.reserveAsset===n);if(!a)throw new Error("Missing reserve ctx for "+n);return this.calculateWithdrawMax(a,i,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:i,healthFactor:r}=await this.getSummary(t),s={};for(let n of i){let a=this.calculateWithdrawMax(n,e,r);n.reserveId&&(s[n.reserveId]=a)}return s}calculateWithdrawMax(t,e,i){let{aTokenBalance:r,availableLiquidity:s,decimals:n,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=t,u=r;if(l&&e>0n){let d=i-qn;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**n).toFixed(0,G.default.roundDown);u=r<BigInt(h)?r:BigInt(h)}else u=0n}return{amount:u<s?u:s,decimals:n}}calculateLinearInterest(t,e,i){let r=i-e;if(r<=0)return ui;let s=t*BigInt(r)/Nn;return ui+s}calculateHealthFactorFromBalances(t,e,i){if(t===0n)return ci;let r=e*i/t,s=lt.big.toDecimal(r,ls);return Number(s)}};var or={};C(or,{AssetClient:()=>$t,BalanceClient:()=>ht,ChainParams:()=>Qt});var Se=require("polkadot-api");var $t=class extends V{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:i,value:r})=>{let[s]=i;return[s,r]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:i,value:r})=>{let[s]=i;return[s,r]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:i})=>{let{asset_type:r}=i;return this.SUPPORTED_TYPES.includes(r.type)}).map(({keyArgs:i,value:r})=>{let[s]=i;return[s,r]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:i,value:r})=>{let[s]=i;return[s,r]}))}async mapToken(t,e,i,r){let{name:s,asset_type:n,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=i.get(t)??{};return{id:t,name:s?Se.Binary.toText(s):void 0,symbol:l,decimals:u,icon:l,type:n.type,isSufficient:a,location:r,existentialDeposit:o}}async mapBond(t,e,i,r){let[s,n]=r,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:p}=await this.mapToken(s,e,i),d=Number(n),m=new Intl.DateTimeFormat("en-GB"),h=[u,"Bond",m.format(d)].join(" ");return{id:t,name:h,symbol:u+"b",decimals:p,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:s,maturity:d}}async mapShares(t,e,i,r){let{assets:s}=r,{name:n,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,p=await Promise.all(s.map(async h=>{let{symbol:g}=await this.mapToken(h,e,i);return[h,g]})),d=Object.fromEntries(p),m=Object.values(d);return{id:t,name:m.join(", "),symbol:a&&Se.Binary.toText(a)||n&&Se.Binary.toText(n),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:d}}async mapExternal(t,e,i,r){let s=await this.mapToken(t,e,new Map,r),n=i?.find(a=>a.internalId===s.id);return n?{...s,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:s}parseMetadata(t){return new Map(Array.from(t,([e,i])=>[e,{symbol:i.symbol?Se.Binary.toText(i.symbol):void 0,decimals:i.decimals}]))}async getSupported(t,e){let[i,r,s,n]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(i),o=[];for(let[l,u]of Array.from(i)){let p=r.get(l),{asset_type:d}=u,m;switch(d.type){case"Bond":let h=n.get(l);m=await this.mapBond(l,u,a,h);break;case"StableSwap":let g=s.get(l);m=await this.mapShares(l,u,a,g);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 cs=require("@galacticcouncil/common"),rt=require("rxjs"),x=require("rxjs/operators");var ar={};C(ar,{HUB_ASSET_ID:()=>Xt,HYDRATION_OMNIPOOL_ADDRESS:()=>Vn,HYDRATION_PARACHAIN_ID:()=>Hn,PERBILL_DENOMINATOR:()=>nr,PERMILL_DENOMINATOR:()=>At,SYSTEM_ASSET_DECIMALS:()=>pi,SYSTEM_ASSET_ID:()=>D,TRADEABLE_DEFAULT:()=>Kt});var At=1e6,nr=1e9,D=0,pi=12,Hn=2034,Vn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Xt=1,Kt=15;var{logger:jt}=cs.log,ht=class extends V{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:i}=await e.getValue(t,{at:this.at});return this.getBreakdown(i)}async getTokenBalance(t,e){let r=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(r)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,rt.defer)(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),r=this.watchErc20Balance(t);return(0,rt.combineLatest)([e,i,r]).pipe((0,x.connect)(s=>(0,rt.concat)(s.pipe((0,x.take)(1)),s.pipe((0,x.skip)(1),(0,x.debounceTime)(250)))))}).pipe((0,x.map)(e=>e.flat()),(0,x.startWith)([]),(0,x.bufferCount)(2,1),(0,x.map)(([e,i],r)=>r===0?i:this.getDeltas(e,i))).pipe((0,x.tap)({subscribe:()=>jt.debug("balance: subscribe",t),error:e=>jt.error("balance",e)}),(0,x.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,rt.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,x.map)(({value:i})=>({id:0,balance:this.getBreakdown(i.data)})),(0,x.tap)({error:i=>jt.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return(0,rt.defer)(()=>i.watchValue(t,e,{at:"best"})).pipe((0,x.map)(({value:r})=>({id:e,balance:this.getBreakdown(r)})),(0,x.tap)({error:r=>jt.error("balance(token)",r)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,rt.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,x.distinctUntilChanged)((i,r)=>!r.deltas),(0,x.map)(({deltas:i})=>{let r=[];return i?.deleted.forEach(s=>{let[n,a]=s.args;r.push({id:a,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(s=>{let[n,a]=s.args;r.push({id:a,balance:this.getBreakdown(s.value)})}),r}),(0,x.tap)({error:i=>jt.error("balance(tokens)",i)}))}watchErc20Balance(t,e){let i=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:n})=>n.asset_type.type==="Erc20").map(({keyArgs:n})=>{let[a]=n;return a}),this.erc20Ids},r=async s=>(await Promise.all(s.map(async a=>[a,await this.getBalanceData(t,a)]))).map(([a,o])=>({id:a,balance:o}));return(0,rt.defer)(()=>(0,rt.from)(e?Promise.resolve(e):i()).pipe((0,x.switchMap)(s=>this.watcher.bestBlock$.pipe((0,x.switchMap)(()=>(0,rt.from)(r(s))))),(0,x.startWith)([]),(0,x.bufferCount)(2,1),(0,x.map)(([s,n],a)=>a===0?n.filter(o=>o.balance.total>0n):this.getDeltas(s,n)),(0,x.distinctUntilChanged)((s,n)=>n.length===0),(0,x.tap)({error:s=>jt.error("balance(erc20)",s)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(i)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,i=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:i,transferable:e}}getDeltas(t,e){let i=(s,n)=>s!==void 0&&n!==void 0&&s.transferable===n.transferable&&s.total===n.total,r=t.reduce((s,n)=>(s.set(n.id,n.balance),s),new Map);return e.filter(s=>!i(s.balance,r.get(s.id)))}};var Qt=class extends V{_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 cr={};C(cr,{AssetNotFound:()=>lr,PoolNotFound:()=>Mt,RouteNotFound:()=>ve});var lr=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},Mt=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},ve=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var mr={};C(mr,{EvmClient:()=>Te,EvmRpcAdapter:()=>xe,createChain:()=>pr});var ur=require("polkadot-api"),us=require("@galacticcouncil/descriptors"),mi=require("viem"),Gn=10000000n,xe=class{api;at;constructor(t,e="best"){this.api=t.getTypedApi(us.hydration),this.at=e}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:this.at}),{header:e}=t,i=e.timestamp/1000n,[r]=e.number;return{timestamp:i,number:r}}readContract=(async t=>{let{abi:e,address:i,functionName:r,args:s}=t,n=(0,mi.encodeFunctionData)({abi:e,functionName:r,args:s}),a=await this.api.apis.EthereumRuntimeRPCApi.call("0x0000000000000000000000000000000000000000",i,ur.Binary.fromHex(n),[0n,0n,0n,0n],[Gn,0n,0n,0n],void 0,void 0,void 0,!1,[],[],{at:this.at});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(o.type==="Succeed")return(0,mi.decodeFunctionResult)({abi:e,functionName:r,data:ur.Binary.toHex(l)});throw console.log(r,o.type,o.value.type),new Error("Contract read error")})};var ps=require("viem"),Un=["https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],pr=()=>(0,ps.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:Un}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var gt=require("viem");var Te=class{client;at;chain;constructor(t,e="best"){this.client=t,this.at=e,this.chain=pr()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,gt.createPublicClient)({chain:this.chain,transport:(0,gt.http)()})}getWsProvider(){return(0,gt.createPublicClient)({transport:(0,gt.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,gt.createWalletClient)({account:t,chain:this.chain,transport:(0,gt.custom)(window.ethereum)})}getRPCAdapter(){return new xe(this.client,this.at)}};var wr={};C(wr,{LiquidityMiningApi:()=>_e,LiquidityMiningClient:()=>Be});var Ts=require("polkadot-api"),j=St(require("big.js")),xt=require("@galacticcouncil/common"),Pr=require("@galacticcouncil/math-liquidity-mining");var Ie={};C(Ie,{withTimeout:()=>Wn});function Wn(c,t,e="timeout"){return new Promise((i,r)=>{let s=setTimeout(()=>r(new Error(e)),t);c.then(n=>{clearTimeout(s),i(n)},n=>{clearTimeout(s),r(n)})})}var M={};C(M,{divSpot:()=>zn,getFraction:()=>$n,mulScaled:()=>ms,mulSpot:()=>Yn});var dr=require("@galacticcouncil/common");function ms(c,t,e,i,r){let s=e+i-r,n=c*t;return s>0?n/BigInt(10)**BigInt(s):s<0?n*BigInt(10)**BigInt(-s):n}function Yn(c,t,e,i){return ms(c,t,e,dr.RUNTIME_DECIMALS,i)}function zn(c,t,e,i){if(t===0n)return 0n;let r=BigInt(10)**BigInt(dr.RUNTIME_DECIMALS+i-e);return c*r/t}function $n(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 O={};C(O,{FeeUtils:()=>hr,shiftNeg:()=>Xn});var ds=St(require("big.js"));var hr=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 Xn(c,t){let e=(0,ds.default)(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Jt={};C(Jt,{findNestedKey:()=>Kn,findNestedObj:()=>jn,jsonFormatter:()=>Qn});var Kn=(c,t)=>{let e=[];return JSON.stringify(c,(i,r)=>(r&&r[t]&&e.push(r),r)),e[0]},jn=(c,t,e)=>{let i;return JSON.stringify(c,(r,s)=>(s&&s[t]===e&&(i=s),s)),i},Qn=(c,t)=>typeof t=="bigint"?t.toString():t;var U={};C(U,{calculateBuyFee:()=>ea,calculateDiffToAvg:()=>Jn,calculateDiffToRef:()=>Zn,calculateSellFee:()=>ta});var bt=St(require("big.js"));function Jn(c,t){let e=(0,bt.default)(c.toString()),i=(0,bt.default)(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function Zn(c,t){if(t===0n)return 0;let e=(0,bt.default)(c.toString()),i=(0,bt.default)(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function ta(c,t){if(c===0n)return 0;let e=(0,bt.default)(c.toString()),i=(0,bt.default)(t.toString());return(0,bt.default)(1).minus(i.div(e)).mul(100).round(2).toNumber()}function ea(c,t){if(c===0n)return 0;let e=(0,bt.default)(c.toString());return(0,bt.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 di=(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 ia=di(()=>"illegal argument(s)"),hs=c=>{throw new ia(c)};var ra=di(()=>"index out of bounds"),gr=c=>{throw new ra(c)},hi=(c,t,e)=>(c<t||c>=e)&&gr(c);var gs=23283064365386963e-26,gi=class{float(t=1){return this.int()*gs*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*gs-.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 bi=class extends gi{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 bs=new bi(Math.random);var fs=c=>c!=null&&typeof c!="function"&&c.length!==void 0;var ys=Object.getPrototypeOf({}),fi="function",Ps="string",Zt=(c,t)=>{let e;if(c===t)return!0;if(c!=null){if(typeof c.equiv===fi)return c.equiv(t)}else return c==t;if(t!=null){if(typeof t.equiv===fi)return t.equiv(c)}else return c==t;return typeof c===Ps||typeof t===Ps?!1:(e=Object.getPrototypeOf(c),(e==null||e===ys)&&(e=Object.getPrototypeOf(t),e==null||e===ys)?oa(c,t):typeof c!==fi&&c.length!==void 0&&typeof t!==fi&&t.length!==void 0?sa(c,t):c instanceof Set&&t instanceof Set?na(c,t):c instanceof Map&&t instanceof Map?aa(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)},sa=(c,t,e=Zt)=>{let i=c.length;if(i===t.length)for(;i-- >0&&e(c[i],t[i]););return i<0},na=(c,t,e=Zt)=>c.size===t.size&&e([...c.keys()].sort(),[...t.keys()].sort()),aa=(c,t,e=Zt)=>c.size===t.size&&e([...c].sort(),[...t].sort()),oa=(c,t,e=Zt)=>{if(Object.keys(c).length!==Object.keys(t).length)return!1;for(let i in c)if(!t.hasOwnProperty(i)||!e(c[i],t[i]))return!1;return!0};var br=class{value;constructor(t){this.value=t}deref(){return this.value}};var ws=c=>c instanceof br;var yi=class c{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Ss("next",this._head)}reverseIterator(){return Ss("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,s=t._head,n=0;for(;i-- >0&&n===0;)n=e(r.value,s.value),r=r.next,s=s.next;return n}}concat(...t){let e=this.copy();for(let i of t)e.into(i);return e}equiv(t){if(!(t instanceof c||fs(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),i=this._head;for(let r=this._length;r-- >0;){if(!Zt(i.value,e.next().value))return!1;i=i.next}return!0}filter(t){let e=this.empty();return this.traverse(i=>(t(i.value)&&e.append(i.value),!0)),e}find(t){return this.traverse(e=>e.value!==t)}findWith(t){return this.traverse(e=>!t(e.value))}first(){return this._head?.value}insertSorted(t,e){e=e||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&&!ws(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&&gr(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*Ss(c,t){for(;t;)yield t.value,t=t[c]}var Pi=class c extends yi{_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):(hi(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):(hi(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new c,t)}nth(t,e){let i=this.nthCell(t);return i?i.value:e}nthCell(t){if(t<0&&(t+=this._length),!(t<0||t>=this._length))return this.nthCellUnsafe(t)}pop(){let t=this._tail;if(t)return this._tail=t.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,t.value}prepend(t){let e={value:t,next:this._head};return this._head?this._head.prev=e:this._tail=e,this._head=e,this._length++,e}push(t){return this.append(t),this}release(){return this._tail=void 0,super.release()}remove(t){return t.prev?t.prev.next=t.next:this._head=t.next,t.next?t.next.prev=t.prev:this._tail=t.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let t=this.peek();return this.pop(),this.prepend(t),this}}seq(t=0,e=this.length){if(t>=e||t<0)return;let i=this.nthCell(t),r=this.nthCell(e-1),s=n=>({first(){return n.value},next(){return n!==r&&n.next?s(n.next):void 0}});return i?s(i):void 0}shuffle(t,e=bs){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)&&hs("invalid indices: ${from} / ${to}");let s=new c,n=this.nthCell(i);for(;n&&++i<=r;)s.push(n.value),n=n.next;return s}sort(t=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 s=i,n=0;for(let o=0;o<e&&(n++,s=s.next,!!s);o++);let a=e;for(;n>0||a>0&&s;){let o;n===0?(o=s,s=s.next,a--):!s||a===0||t(i.value,s.value)<=0?(o=i,i=i.next,n--):(o=s,s=s.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}i=s}if(this._tail.next=void 0,r<=1)return this;e*=2}}splice(t,e=0,i){let r;typeof t=="number"?(t<0&&(t+=this._length),hi(t,0,this._length),r=this.nthCellUnsafe(t)):r=t;let s=new c;if(e>0)for(;r&&e-- >0;)this.remove(r),s.push(r.value),r=r.next;else r&&(r=r.next);if(i)if(r)for(let n of i)this.insertBefore(r,n);else for(let n of i)this.push(n);return s}};var wi=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 Pi,this._size=0,this.opts=i,t&&this.into(t)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let t of this.items)yield[t.k,t]}*keys(){for(let t of this.items)yield t.k}*values(){for(let t of this.items)yield t.v}copy(){let t=this.empty();t.items=this.items.copy();let e=t.items.head;for(;e;)t.map.set(e.value.k,e),e=e.next;return t}empty(){return new c(null,this.opts)}release(){this._size=0,this.map.clear();let t=this.opts.release;if(t){let e;for(;e=this.items.drop();)t(e.k,e.v);return!0}return this.items.release()}has(t){return this.map.has(t)}get(t,e){let i=this.map.get(t);return i?this.resetEntry(i):e}set(t,e){let i=this.opts.ksize(t)+this.opts.vsize(e),r=this.map.get(t),s=Math.max(0,i-(r?r.value.s:0));return this._size+=s,this.ensureSize()?this.doSetEntry(r,t,e,i):this._size-=s,e}into(t){for(let e of t)this.set(e[0],e[1]);return this}async getSet(t,e){let i=this.map.get(t);return i?this.resetEntry(i):this.set(t,await e())}delete(t){let e=this.map.get(t);return e?(this.removeEntry(e),!0):!1}resetEntry(t){return this.items.asTail(t),t.value.v}ensureSize(){let{release:t,maxsize:e,maxlen:i}=this.opts;for(;this._size>e||this.length>=i;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),t?.(r.k,r.v),this._size-=r.s}return!0}removeEntry(t){let e=t.value;this.map.delete(e.k),this.items.remove(t),this.opts.release?.(e.k,e.v),this._size-=e.s}doSetEntry(t,e,i,r){t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=r,this.items.asTail(t)):(this.items.push({k:e,v:i,s:r}),this.map.set(e,this.items.tail))}};var Dt=class c extends wi{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new c(null,this.opts)}has(t){return this.get(t)!==void 0}get(t,e){let i=this.map.get(t);if(i){if(i.value.t>=Date.now())return this.resetEntry(i);this.removeEntry(i)}return e}set(t,e,i=this.opts.ttl){let r=this.opts.ksize(t)+this.opts.vsize(e),s=this.map.get(t),n=Math.max(0,r-(s?s.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(s,t,e,r,i):this._size-=n,e}async getSet(t,e,i=this.opts.ttl){let r=this.get(t);return r!==void 0?r:this.set(t,await e(),i)}prune(){let t=Date.now(),e=this.items.head,i=0;for(;e;)e.value.t<t&&(this.removeEntry(e),i++),e=e.next;return i}ensureSize(){let{maxlen:t,maxsize:e}=this.opts,i=Date.now(),r=this.items.head;for(;r&&(this._size>e||this.length>=t);)r.value.t<i&&this.removeEntry(r),r=r.next;return super.ensureSize()}doSetEntry(t,e,i,r,s=this.opts.ttl){let n=Date.now()+s;t?(this.opts.update?.(e,t.value.v,i),t.value.v=i,t.value.s=r,t.value.t=n,this.items.asTail(t)):(this.items.push({k:e,v:i,s:r,t:n,ttl:s}),this.map.set(e,this.items.tail))}resetEntry(t){return this.opts.autoExtend&&(t.value.t=Date.now()+t.value.ttl),super.resetEntry(t)}};var Lt=class{debug;constructor(t){this.debug=t||!1}log(t,e,i){this.debug&&console.log(t,e,i)}scope(t,e,i,r){let s=new Map,n=r!==void 0?new Dt(null,{ttl:r}):new Dt;return{get:(...u)=>{let p=i(...u);if(s.has(p)){this.log("[live]",t,p);let m=s.get(p);return Promise.resolve(m)}if(n.has(p))return this.log("[memo]",t,p),n.get(p);this.log("[fetch]",t,p);let d=e(...u).catch(m=>{throw n.delete(p),m});return n.set(p,d),d},set:(u,...p)=>{let d=i(...p);this.log("[set-live]",t,d),s.set(d,u)},clear:()=>{this.log("[clear]",t),s.clear(),n.release()}}}};var Si=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let i=0;i<t.length;++i){let[r,s]=t[i];this.result.set(this.getKey(s,r),e[i].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,i,r){let s=this.getKey(t,e),n=this.getKey(t,i),a=this.result.get(s)??0n,o=this.result.get(n)??0n;if(a<r)throw new Error("Attempting to transfer more than is present");this.result.set(s,a+r),this.result.set(n,o+r)}};var Bt=St(require("big.js")),mt=require("@galacticcouncil/math-liquidity-mining");var fr=St(require("big.js")),yr=(0,fr.default)(10).pow(18),vs=BigInt((0,fr.default)(1).pow(18).toString()),xs=6e3;var la="1000000000000000000",vi=class{constructor(t,e,i){this.getAccount=t;this.getAsset=e;this.multiCurrency=i}async syncGlobalFarm(t,e,i){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let r=await this.getAsset(t.reward_currency),s=e-t.updated_at,n=this.getAccount(t.id),a=r?.existential_deposit;if(!a)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,n),l=(0,Bt.default)(a.toString()),u=(0,Bt.default)(o.toString()).minus(l.lt(o.toString())?a.toString():o.toString()),p=(0,Bt.default)((0,mt.calculate_global_farm_rewards)(t.total_shares_z.toString(),i.toString(),(0,Bt.default)(t.yield_per_period.toString()).mul(yr).round(0,Bt.default.roundDown).toFixed(),t.max_reward_per_period.toString(),s.toFixed()));if(u.lt(p)&&(p=u),p.eq(0))return t;let d=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,n,d,BigInt(p.toFixed())),{...t,accumulated_rpz:BigInt((0,mt.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),p.toFixed()))}}syncYieldFarm(t,e,i){if(t.state.type!=="Active"||t.updated_at===i)return t;if(t.total_valued_shares===0n)return{...t,updated_at:i};let r=(0,mt.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,Bt.default)(1).mul(yr).round(0,Bt.default.roundDown).toString();if(!e)return i;let{initial_reward_percentage:r,scale_coef:s}=e;return(0,mt.calculate_loyalty_multiplier)(t.toFixed(),r.toString(),s.toFixed())}async claimRewards(t,e,i,r,s){if(e.state.type==="Terminated")return null;let n=Math.floor(r/t.blocks_per_period);if(i.updated_at===n)return null;let a=await this.syncGlobalFarm(t,n,s);if(!a)return null;let o=this.syncYieldFarm(e,a,n);if(!o)return null;let l=o.total_stopped-i.stopped_at_creation,u=o.updated_at-i.entered_at-l,p=this.getLoyaltyMultiplier(u,o.loyalty_curve),d=BigInt((0,mt.calculate_user_reward)(i.accumulated_rpvs.toString(),i.valued_shares.toString(),i.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),m=BigInt((0,mt.calculate_user_reward)(i.accumulated_rpvs.toString(),i.valued_shares.toString(),i.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),la));return{reward:d,maxReward:m,assetId:a.reward_currency,yieldFarmId:o.id,isActiveFarm:o.state.type==="Active"}}};var ca=(0,j.default)(365.2425).times(24).times(60).times(60),_e=class{balance;client;options;constructor(t,e,i={}){this.client=t,this.balance=e,this.options=Object.freeze({blockTime:i.blockTime??xs})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let i=[t,e].sort((s,n)=>s-n);if(t===e)return vs;let r=await this.client.getOraclePrice(i);if(r){let{n:s,d:n}=r[0].price,a;return t<e?a=(0,Pr.fixed_from_rational)(s.toString(),n.toString()):a=(0,Pr.fixed_from_rational)(n.toString(),s.toString()),BigInt(a)}}getFarmAddress=(t,e)=>{let i=Buffer.from("modl","utf-8"),r=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),s=Buffer.from([t]),n=Buffer.concat([i,r,s]),o="0x"+Buffer.concat([n,Buffer.alloc(32-n.length)]).toString("hex");return(0,Ts.AccountId)(xt.HYDRATION_SS58_PREFIX).dec(o)};getGlobalRewardPerPeriod(t,e,i,r){let s=(0,j.default)(r).times(t.toString()).times(e.toString()).div(Math.pow(10,xt.RUNTIME_DECIMALS));return s.gte(i.toString())?i.toString():s.toString()}getPoolYieldPerPeriod(t,e,i,r){let s=(0,j.default)(t.toString()).times(e),n=(0,j.default)(i.toString()).times(r);return s.div(n.toString()).toString()}farmData(t,e,i){let{yieldFarm:r,globalFarm:s,priceAdjustment:n,balance:a,id:o}=t,{multiplier:l,loyalty_curve:u}=r,{blocks_per_period:p,yield_per_period:d,total_shares_z:m,max_reward_per_period:h,pending_rewards:g,accumulated_paid_rewards:b,planned_yielding_periods:f,updated_at:y,incentivized_asset:S,reward_currency:w,price_adjustment:v,min_deposit:I}=s,_=O.shiftNeg(n??v,xt.RUNTIME_DECIMALS),et=O.shiftNeg(l,xt.RUNTIME_DECIMALS),$=O.shiftNeg(u?.initial_reward_percentage??0,xt.RUNTIME_DECIMALS),Pt=ca.div((0,j.default)(this.blockTime).div(1e3).times(p)).toString(),it;if(m<=0)it=(0,j.default)(et).times(d.toString()).times(Pt).div(Math.pow(10,xt.RUNTIME_DECIMALS)).toString();else{let _n=this.getGlobalRewardPerPeriod(m,d,h,_),An=this.getPoolYieldPerPeriod(_n,et,m,_);it=(0,j.default)(An).times(Pt).toString()}let pt=g+b,_t=h*BigInt(f),ti=a.transferable+pt,Qr=ti-pt,ei=(0,j.default)(Qr.toString()).div(h.toString()),ii=(0,j.default)(e).div(p.toString()).toString(),ri=(m>=0?ei.plus(y):ei.plus(ii)).toString(),Qi=(0,j.default)(ri).times(p).toString(),In=(0,j.default)(m.toString()).div((0,j.default)(h.toString()).div(d.toString())).div(Math.pow(10,xt.RUNTIME_DECIMALS)).times(100).times(_).toFixed(2),Jr=(0,j.default)(pt.toString()).div(ti.toString()).gte(.999);it=Jr?"0":(0,j.default)(it).div(i?2:1).times(100).toString();let On=$?(0,j.default)(it).times($).toString():void 0;return{apr:it,minApr:On,isDistributed:Jr,estimatedEndPeriod:ri,estimatedEndBlock:Qi,maxRewards:_t,incentivizedAsset:S,rewardCurrency:w,loyaltyCurve:u,currentPeriod:ii,potMaxRewards:ti,fullness:In,yieldFarmId:r.id,globalFarmId:s.id,poolId:o,distributedRewards:pt,plannedYieldingPeriods:f,minDeposit:I,blocksPerPeriod:p}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((r,s)=>r.includes(s.keyArgs[0].toString())?r:[...r,s.keyArgs[0].toString()],[]),i=await Promise.all(e.map(async r=>{let s=await this.getOmnipoolFarms(r);if(s)return[r,s]}));return Object.fromEntries(i.filter(r=>!!r))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),i=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:s,value:n})=>{let[,a]=s,o=n,l=await this.client.getOmnipoolGlobalFarm(a),u=await this.client.getOmnipoolYieldFarm(Number(t),a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a),h=await this.getOraclePrice(p,d),g=await this.balance.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:h,balance:g}}));return i?r.map(s=>s?this.farmData(s,i):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((r,s)=>r.includes(s.keyArgs[0].toString())?r:[...r,s.keyArgs[0].toString()],[]),i=await Promise.all(e.map(async r=>{let s=await this.getIsolatedFarms(r);if(s)return[r,s]}));return Object.fromEntries(i.filter(r=>!!r))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),i=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:s,value:n})=>{let[,a]=s,o=n,l=await this.client.getIsolatedGlobalFarm(a),u=await this.client.getIsolatedYieldFarm(t,a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a,!0),h=await this.getOraclePrice(p,d),g=await this.balance.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:h,balance:g,farmAddress:m}}));return i?r.map(s=>s?this.farmData(s,i,!0):void 0):[]}async getDepositReward(t,e,i,r){let s=e.global_farm_id,n=e.yield_farm_id,a=i?await this.client.getIsolatedYieldFarm(t,s,n):await this.client.getOmnipoolYieldFarm(Number(t),s,n),o=i?await this.client.getIsolatedGlobalFarm(s):await this.client.getOmnipoolGlobalFarm(s);if(!o||!a)return;let l=o.reward_currency,u=o.incentivized_asset,p=[[this.getFarmAddress(0,i),o.reward_currency],[this.getFarmAddress(o.id,i),o.reward_currency]],d=await this.getAccountAssetBalances(p),m=await this.getOraclePrice(l,u),h=new Si(p,d),b=await new vi(y=>this.getFarmAddress(y),y=>this.client.getAsset(y),h).claimRewards(o,a,e,r,m??o.price_adjustment);if(!b)return;let f=await this.client.getAsset(b.assetId);if(f&&!(b.reward<=f.existential_deposit))return b}async getAccountAssetBalances(t){let[e,i]=await Promise.all([Promise.all(t.filter(([s,n])=>n!==0).map(([s,n])=>this.balance.getTokenBalance(s,n))),Promise.all(t.filter(([s,n])=>n===0).map(([s])=>this.balance.getSystemBalance(s)))]),r=[];for(let s=0,n=0;s+n<t.length;){let a=s+n,[,o]=t[a];o===0?(r.push(i[n]),n+=1):(r.push(e[s]),s+=1)}return r}};var Ae=require("polkadot-api"),ua=Ae.Binary.toHex(Ae.Binary.fromText("omnipool")),Be=class extends V{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(ua,t,(0,Ae.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 vr={};C(vr,{BlockFetcher:()=>te,IndexerStats:()=>qt,RpcPool:()=>Ti,SYSTEM_EVENTS_KEY:()=>Sr,Semaphore:()=>ee,decodeCompactLength:()=>xi,indexBlocks:()=>Os});function xi(c){let t=c.startsWith("0x")?c.slice(2):c;if(t.length<2)return 0;let e=parseInt(t.slice(0,2),16);switch(e&3){case 0:return e>>2;case 1:{if(t.length<4)return 0;let r=e;return(parseInt(t.slice(2,4),16)<<8|r)>>2}case 2:{if(t.length<8)return 0;let r=e,s=parseInt(t.slice(2,4),16),n=parseInt(t.slice(4,6),16);return(parseInt(t.slice(6,8),16)<<24|n<<16|s<<8|r)>>>2}default:return 0}}var Sr="0x26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7";var te=class c{constructor(t){this.select=t}static withClient(t){return new c(()=>t)}async getHash(t){let i=await this.select()._request("chain_getBlockHash",[t]);return i&&i.length===66?i:null}async getBlock(t,e={}){let i=await this.getHash(t);return i?this.getBlockAt(t,i,e):null}async getBlockAt(t,e,i={}){let r=this.select(),[s,n]=await Promise.all([i.withBlock?r._request("chain_getBlock",[e]):Promise.resolve(null),i.withEvents?r._request("state_getStorage",[Sr,e]):Promise.resolve(null)]),a=s?.block?.extrinsics??[],o=s?.block?.header,l=s?JSON.stringify(s).length:0,u=n?n.length/2:0;return{number:t,hash:e,header:o,extrinsics:a,eventsHex:n??void 0,eventsCount:n?xi(n):0,bytes:l+u}}};var qt=class{blocks=0;events=0;extrinsics=0;bytes=0;errors=0;startedAt=0;batchTimes=[];start(){this.startedAt=performance.now()}recordBlock(t={}){this.blocks++,t.events&&(this.events+=t.events),t.extrinsics&&(this.extrinsics+=t.extrinsics),t.bytes&&(this.bytes+=t.bytes)}recordBatch(t){this.batchTimes.push(t)}recordError(){this.errors++}elapsedMs(){return this.startedAt===0?0:performance.now()-this.startedAt}percentile(t){if(this.batchTimes.length===0)return 0;let e=[...this.batchTimes].sort((r,s)=>r-s),i=Math.floor(t/100*e.length);return e[Math.min(i,e.length-1)]}snapshot(){let t=this.elapsedMs(),e=t/1e3;return{blocks:this.blocks,events:this.events,extrinsics:this.extrinsics,bytes:this.bytes,errors:this.errors,elapsedMs:t,blocksPerSec:e>0?this.blocks/e:0,eventsPerSec:e>0?this.events/e:0,batchP50Ms:this.percentile(50),batchP95Ms:this.percentile(95),batchP99Ms:this.percentile(99)}}};var Is=require("polkadot-api");var Ti=class c{clients=[];owned;idx=0;constructor(t,e){if(t.length===0)throw new Error("RpcPool requires at least one client");this.clients=t,this.owned=e}static fromEndpoints(t){let i=(typeof t=="string"?t.split(","):t).map(r=>(0,Is.createClient)(Zi(r)));return new c(i,!0)}static fromClients(t){return new c(t,!1)}size(){return this.clients.length}next(){let t=this.clients[this.idx%this.clients.length];return this.idx++,t}destroy(){if(this.owned)for(let t of this.clients)t.destroy()}};var ee=class{constructor(t){this.max=t;if(t<1)throw new Error("Semaphore max must be >= 1")}queue=[];running=0;async acquire(){if(this.running<this.max){this.running++;return}return new Promise(t=>{this.queue.push(()=>{this.running++,t()})})}release(){this.running--;let t=this.queue.shift();t&&t()}async run(t){await this.acquire();try{return await t()}finally{this.release()}}};async function Os(c){let{pool:t,fromBlock:e,blockCount:i,concurrency:r=100,batchSize:s=50,withBlock:n=!1,withEvents:a=!1,onBlock:o,onError:l}=c;if(i<=0){let h=c.stats??new qt;return h.start(),{stats:h}}let u=c.stats??new qt,p=new ee(r),d=new te(()=>t.next()),m=[];for(let h=0;h<i;h+=s){let g=[];for(let b=0;b<s&&h+b<i;b++)g.push(e+h+b);m.push(g)}return u.start(),await Promise.all(m.map(h=>p.run(async()=>{let g=performance.now();await Promise.all(h.map(async b=>{let f=null;try{f=await d.getBlock(b,{withBlock:n,withEvents:a})}catch(y){u.recordError(),l?.(y,b);return}if(!f){u.recordError();return}if(u.recordBlock({events:f.eventsCount,extrinsics:f.extrinsics.length,bytes:f.bytes}),o)try{await o(f)}catch(y){u.recordError(),l?.(y,b)}})),u.recordBatch(performance.now()-g)}))),{stats:u}}var qr={};C(qr,{PoolContextProvider:()=>ue,PoolError:()=>Tt,PoolFactory:()=>ce,PoolType:()=>A,SnapshotPoolCtxProvider:()=>Ni,aave:()=>kr,hsm:()=>Rr,lbp:()=>xr,omni:()=>Ir,stable:()=>Ar,uniswapv3:()=>Lr,xyk:()=>Br});var xr={};C(xr,{LbpMath:()=>dt,LbpPool:()=>ke,LbpPoolClient:()=>Ee});var ft=require("@galacticcouncil/math-lbp"),dt=class{static getSpotPrice(t,e,i,r,s){return(0,ft.get_spot_price)(t,e,i,r,s)}static calculateInGivenOut(t,e,i,r,s){return(0,ft.calculate_in_given_out)(t,e,i,r,s)}static calculateOutGivenIn(t,e,i,r,s){return(0,ft.calculate_out_given_in)(t,e,i,r,s)}static calculateLinearWeights(t,e,i,r,s){return(0,ft.calculate_linear_weights)(t,e,i,r,s)}static calculatePoolTradeFee(t,e,i){return(0,ft.calculate_pool_trade_fee)(t,e,i)}};var ie=require("@galacticcouncil/common");var A=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a.HSM="HSM",a.V3="UniswapV3",a))(A||{}),Tt=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(Tt||{});var{FeeUtils:_s}=O,ke=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),r=i.get(t),s=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:s.balance,decimalsIn:r.decimals,decimalsOut:s.decimals,weightIn:r.weight,weightOut:s.weight}}validateAndBuy(t,e,i){let r=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let n=t.balanceOut/this.maxOutRatio;if(e>n&&s.push("MaxOutRatioExceeded"),r===t.assetOut){let a=this.calculateTradeFee(e,i),o=_s.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return u>p&&s.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:s}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&s.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:s}}}validateAndSell(t,e,i){let r=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let n=t.balanceIn/this.maxInRatio;if(e>n&&s.push("MaxInRatioExceeded"),r===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:s}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,i),l=_s.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),u=a-o,p=t.balanceOut/this.maxOutRatio;return u>p&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:s}}}calculateInGivenOut(t,e){let i=dt.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=dt.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=dt.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),ie.big.toBigInt(1,ie.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=dt.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),ie.big.toBigInt(1,ie.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let i=dt.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(i)}};var Es=require("polkadot-api"),kt=require("rxjs");var As=(c,t=new Map)=>e=>{let i;return t.has(e)?t.get(e):(t.set(e,i=c(e)),i)};var B=require("rxjs"),P=require("rxjs/operators");var Bs=require("rxjs"),Ii=class{store$=new Bs.BehaviorSubject([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(t){return this.changeset.size===0?[]:t.filter(e=>this.changeset.has(e.address))}set(t){this.changeset=new Set(t.map(e=>e.address)),this.store$.next(t)}update(t){this.updateQueue=this.updateQueue.then(async()=>{let e=this.store$.value,i=new Map(e.map((a,o)=>[a.address,o])),r=await t(e),s=e.slice(),n=new Set;for(let a of r){let o=i.get(a.address);o===void 0?(i.set(a.address,s.length),s.push(a)):s[o]=a,n.add(a.address)}this.changeset=n,this.store$.next(s)}).catch(console.error)}destroy(){this.store$.complete()}};var ks=require("@galacticcouncil/common");var pa={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM",UniswapV3:"UNIV3"},{logger:Oi}=ks.log,_i=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${pa[this.type]})`,10)}trace(t,...e){Oi.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){Oi.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){Oi.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){Oi.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:ma}=Ie,da=3e3,Q=class extends V{evm;balance;store=new Ii;log;shared$;resync$=new B.ReplaySubject(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new Dt(null,{ttl:6*1e3});memPools=As(t=>(this.log.info("pool_sync",{mem:t}),this.loadPools()),this.memPoolsCache);constructor(t,e,i){super(t,i),this.evm=e,this.balance=new ht(t,i),this.log=new _i(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){let e=(await this.getMemPools()).filter(i=>this.hasValidAssets(i));return this.store.set(e),e}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe((0,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,B.defer)(()=>{let t=new B.Subscription;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe((0,P.switchMap)(()=>{let e=new B.Subscription;return(0,B.from)(ma(this.getMemPools(),6e4,"getMemPools stalled")).pipe((0,P.tap)(()=>this.log.info("pool_synced",{mem:this.mem})),(0,P.map)(r=>r.filter(s=>this.hasValidAssets(s))),(0,P.tap)(r=>this.store.set(r)),(0,P.catchError)(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),B.EMPTY))).pipe((0,P.tap)(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),(0,P.switchMap)(r=>(0,B.merge)((0,B.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 B.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:i}=e,r=[this.balance.watchTokensBalance(i)];if(this.hasSystemAsset(e)){let s=this.balance.watchSystemBalance(i);r.push(s)}if(this.hasErc20Asset(e)){let s=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),n=this.balance.watchErc20Balance(i,s);r.push(n)}return(0,B.combineLatest)(r).pipe((0,P.map)(s=>s.flat()),(0,P.pairwise)(),(0,P.map)(([s,n])=>this.balance.getDeltas(s,n)),(0,P.filter)(s=>s.length>0),(0,P.map)(s=>[i,s]))});return(0,B.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})=>t.type==="XYK"?i>0n&&!!e:!!e)}updateBalances=(t,e)=>{let i=[],r=new Map(t.map(s=>[s.address,s]));for(let[s,n]of e){let a=r.get(s);if(a){let o=a.tokens.map(l=>{let u=n.find(p=>p.id===l.id);return u&&l.id!==a.id?{...l,balance:u.balance.transferable}:l});i.push({...a,tokens:o})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<da||(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)(([a,o])=>a==="offline"&&o==="online"),(0,P.tap)(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),(0,P.catchError)(a=>(this.log.error("watchdog_recovery_error",a),B.EMPTY)),(0,P.repeat)({delay:1e3})),s=this.watcher.finalizedBlock$.pipe((0,P.pairwise)(),(0,P.tap)(([a,o])=>{let l=Number(a.number),u=Number(o.number),p=u-l;p>=3&&(this.log.debug("watchdog_gap",{from:l,to:u,gap:p}),this.requestResync())}),(0,P.catchError)(a=>(this.log.error("watchdog_gap_error",a),B.EMPTY)),(0,P.repeat)({delay:1e3})),n=(0,B.interval)(36e5).pipe((0,P.tap)(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),(0,P.catchError)(a=>(this.log.error("watchdog_periodic_error",a),B.EMPTY)),(0,P.repeat)({delay:1e3}));return(0,B.merge)(r,s,n).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)(()=>B.EMPTY))}};var Ee=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:s,final_weight:n}=t,a=dt.calculateLinearWeights(i?i.toString():"0",r?r.toString():"0",s.toString(),n.toString(),e.toString()),o=BigInt(a),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){return(await this.api.getStaticApis()).compat.query.LBP.PoolData.isCompatible(Es.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,i]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:this.at}),this.api.query.ParachainSystem.ValidationData.getValue({at:this.at}),this.getPoolLimits()]),r=e?.relay_parent_number||0,s=t.filter(({value:n})=>e&&this.isActivePool(n,r)).map(async({keyArgs:n,value:a})=>{let[o]=n,l=o.toString(),u=await this.getPoolDelta(l,a,r);return{address:l,type:"LBP",fee:a.fee,...u,...i}});return Promise.all(s)}async getPoolDelta(t,e,i){let{assets:r,repay_target:s,fee_collector:n}=e,[a,o]=this.getPoolWeights(e,i),[l,u]=r,[p,d,m,h,g]=await Promise.all([this.isRepayFeeApplied(l,s,n.toString()),this.balance.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l,{at:this.at}),this.balance.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u,{at:this.at})]);return{repayFeeApply:p,tokens:[{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,weight:a,type:m?.asset_type.type},{id:u,decimals:g?.decimals,existentialDeposit:g?.existential_deposit,balance:h.transferable,weight:o,type:g?.asset_type.type}]}}isActivePool(t,e){let{start:i,end:r}=t;return i&&r?e>=i&&e<r:!1}async isRepayFeeApplied(t,e,i){if(e===0n)return!1;try{return(await this.balance.getBalance(i,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let i=this.store.pools.find(s=>s.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:i.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue({at:"best"}).pipe((0,kt.map)(({value:t})=>t),(0,kt.filter)(t=>t!==void 0),(0,kt.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let i=[];for(let r of e){let s=this.poolsData.get(r.address);if(s){let{assets:n,repay_target:a,fee_collector:o}=s,[l]=n,[u,p]=this.getPoolWeights(s,t),[d,m]=r.tokens,h=[{...d,weight:u},{...m,weight:p}],g=await this.isRepayFeeApplied(l,a,o.toString());i.push({...r,tokens:h,repayFeeApply:g})}}return i})})}subscribeUpdates(){let t=new kt.Subscription;return t.add(this.subscribeValidationData()),t}};var Ir={};C(Ir,{OmniMath:()=>F,OmniPool:()=>Re,OmniPoolClient:()=>Ce,OmniPoolFee:()=>Ht,getEmaKey:()=>Ai,getEmaPair:()=>re});var T=require("@galacticcouncil/math-omnipool"),Nt=St(require("big.js")),F=class{static calculateSpotPrice(t,e,i,r){return(0,T.calculate_spot_price)(t,e,i,r)}static calculateLrnaSpotPrice(t,e){return(0,T.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,i,r,s,n,a,o,l,u){return(0,T.calculate_in_given_out)(t,e,i,r,s,n,a,o,l,u)}static calculateLrnaInGivenOut(t,e,i,r,s,n){return(0,T.calculate_lrna_in_given_out)(t,e,i,r,s,n)}static calculateOutGivenIn(t,e,i,r,s,n,a,o,l,u){return(0,T.calculate_out_given_in)(t,e,i,r,s,n,a,o,l,u)}static calculateOutGivenLrnaIn(t,e,i,r,s,n){return(0,T.calculate_out_given_lrna_in)(t,e,i,r,s,n)}static calculateShares(t,e,i,r){return(0,T.calculate_shares)(t,e,i,r)}static calculateLiquidityOut(t,e,i,r,s,n,a,o){return(0,T.calculate_liquidity_out)(t,e,i,r,s,n,a,o)}static calculateLiquidityLRNAOut(t,e,i,r,s,n,a,o){return(0,T.calculate_liquidity_lrna_out)(t,e,i,r,s,n,a,o)}static calculateCapDifference(t,e,i,r){let s=(0,Nt.default)(e),n=(0,Nt.default)(t),a=(0,Nt.default)(r),o=(0,Nt.default)(i),l=(0,Nt.default)(10).pow(18),u=o.div(l);if(s.div(a).lt(u)){let d=u.times(a).minus(s).times(n),m=s.times((0,Nt.default)(1).minus(u));return d.div(m).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,r){return(0,T.calculate_liquidity_hub_in)(t,e,i,r)}static isSellAllowed(t){return(0,T.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,T.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,T.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,T.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,i,r,s,n,a,o,l,u,p){return(0,T.recalculate_asset_fee)(t,e,i,r,s,n,a,o,l,u,p)}static recalculateProtocolFee(t,e,i,r,s,n,a,o,l,u,p){return(0,T.recalculate_protocol_fee)(t,e,i,r,s,n,a,o,l,u,p)}static verifyAssetCap(t,e,i,r){return(0,T.verify_asset_cap)(t,e,i,r)}};var Rs=require("@galacticcouncil/common");var{FeeUtils:yt}=O,Re=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),r=i.get(t),s=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:r.hubReserves,hubReservesOut:s.hubReserves,sharesIn:r.shares,sharesOut:s.shares,decimalsIn:r.decimals,decimalsOut:s.decimals,balanceIn:r.balance,balanceOut:s.balance,tradeableIn:r.tradeable,tradeableOut:s.tradeable,assetInEd:r.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,i),n=r===0n?0:U.calculateBuyFee(r,s),a=[],o=F.isSellAllowed(t.tradeableIn),l=F.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return s>p&&a.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:r,amountOut:e,feePct:n,errors:a}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,i),n=U.calculateSellFee(r,s),a=[],o=F.isSellAllowed(t.tradeableIn),l=F.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return s>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:s,feePct:n,errors:a}}calculateInGivenOut(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,i);let r=F.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?yt.toRaw(i.assetFee).toString():"0",i?yt.toRaw(i.protocolFee).toString():"0",i?yt.toRaw(i.maxSlipFee).toString():"0"),s=BigInt(r);return s<0n?0n:s}calculateLrnaInGivenOut(t,e,i){let r=F.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?yt.toRaw(i.assetFee).toString():"0",i?yt.toRaw(i.maxSlipFee).toString():"0"),s=BigInt(r);return s<0n?0n:s}calculateOutGivenIn(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,i);let r=F.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?yt.toRaw(i.assetFee).toString():"0",i?yt.toRaw(i.protocolFee).toString():"0",i?yt.toRaw(i.maxSlipFee).toString():"0"),s=BigInt(r);return s<0n?0n:s}calculateOutGivenLrnaIn(t,e,i){let r=F.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?yt.toRaw(i.assetFee).toString():"0",i?yt.toRaw(i.maxSlipFee).toString():"0"),s=BigInt(r);return s<0n?0n:s}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=F.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=F.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=F.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=F.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,i){let r=e-i;if(r===0)return t;let s=Rs.big.pow10(Math.abs(r));return r>0?t*s:t/s}};var It=require("polkadot-api"),Ms=require("@polkadot-api/utils"),k=require("rxjs"),Ds=require("@galacticcouncil/common");var{FeeUtils:X}=O,Ht=class c{static compute(t,e,i,r,s,n,a,o){let l=t.assetIn,[u,p,d]=c.getAssetFee(t,e,i,r,n),m=0,h=0,g=0;l!==1&&([m,h,g]=c.getProtocolFee(t,e,i,s,a));let b=u+m,f=d+g;return{assetFee:X.fromPermill(p),protocolFee:X.fromPermill(h),maxSlipFee:X.fromPermill(o),min:X.fromPermill(b),max:X.fromPermill(f)}}static getAssetFee(t,e,i,r,s){let{assetOut:n,balanceOut:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=s;if(!i||!r)return[o,o,l];let d=X.fromPermill(o),m=X.fromPermill(l),[h]=r,{asset_fee:g,timestamp:b}=i,f=Math.max(1,e-b),y=h.volume.b_in.toString(),S=h.volume.b_out.toString(),w=h.liquidity.b.toString();n===0&&(y=h.volume.a_in.toString(),S=h.volume.a_out.toString(),w=h.liquidity.a.toString());let v=X.fromPermill(g),I=F.recalculateAssetFee(y,S,w,"9",a.toString(),X.toRaw(v).toString(),f.toString(),X.toRaw(d).toString(),X.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(I)*1e6,l]}static getProtocolFee(t,e,i,r,s){let{assetIn:n,balanceIn:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=s;if(!i||!r)return[o,o,l];let d=X.fromPermill(o),m=X.fromPermill(l),[h]=r,{protocol_fee:g,timestamp:b}=i,f=Math.max(1,e-b),y=h.volume.b_in.toString(),S=h.volume.b_out.toString(),w=h.liquidity.b.toString();n===0&&(y=h.volume.a_in.toString(),S=h.volume.a_out.toString(),w=h.liquidity.a.toString());let v=X.fromPermill(g),I=F.recalculateProtocolFee(y,S,w,"9",a.toString(),X.toRaw(v).toString(),f.toString(),X.toRaw(d).toString(),X.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(I)*1e6,l]}};var re=c=>c===0?[0,1]:[1,c],Ai=c=>re(c).join(":");var{FeeUtils:Tr}=O,Cs=It.Binary.toHex(It.Binary.fromText("omnipool")),Fs=(0,It.Enum)("Short"),Ce=class extends Q{queryBus=new Lt;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:this.at}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:this.at}),t=>String(t),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:this.at}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(Cs,t,Fs,{at:this.at}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,Ms.toHex)(e);return(0,It.AccountId)(Ds.HYDRATION_SS58_PREFIX).dec(i)}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Omnipool.Assets.isCompatible(It.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,r,s,n,a,o]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:this.at}),this.api.query.Omnipool.HubAssetTradability.getValue({at:this.at}),this.api.query.AssetRegistry.Assets.getValue(t,{at:this.at}),this.balance.getBalance(e,t),this.getPoolLimits(),this.api.query.System.Number.getValue({at:this.at})]);this.block=o;let l=i.map(async({keyArgs:p,value:d})=>{let[m]=p,{hub_reserve:h,shares:g,tradable:b,cap:f,protocol_shares:y}=d,[S,w]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m,{at:this.at}),this.balance.getBalance(e,m)]);return{id:m,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:w.transferable,cap:f,hubReserves:h,protocolShares:y,shares:g,tradeable:b,type:S?.asset_type.type}}),u=await Promise.all(l);return u.push({id:t,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:n.transferable,tradeable:r,type:s?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:u,...a}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,s=await this.maxSlipFee.get()??0,n=await this.dynamicFeesConfig.get(e);if(n?.type==="Fixed"){let{asset_fee:d,protocol_fee:m}=n.value;return{assetFee:Tr.fromPermill(d),protocolFee:Tr.fromPermill(m),maxSlipFee:Tr.fromPermill(s)}}let[a,o,l,u,p]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(re(e)),this.emaOracles.get(re(i)),n?n.value.asset_fee_params:this.api.constants.DynamicFees.AssetFeeParameters(),n?n.value.protocol_fee_params:this.api.constants.DynamicFees.ProtocolFeeParameters()]);return Ht.compute(t,this.block,a,o,l,u,p,s)}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(r=>r.id).map(r=>re(r)).map(r=>this.api.query.EmaOracle.Oracles.watchValue(Cs,r,Fs,{at:"best"}).pipe((0,k.map)(({value:s})=>s),(0,k.filter)(s=>s!==void 0),(0,k.map)((s,n)=>({value:s,index:n})),(0,k.tap)(({index:s})=>{s>0&&this.log.trace("emaOracle.Oracles",r.join(":"))}),(0,k.map)(({value:s})=>({pair:r,value:s}))));return(0,k.merge)(...i).pipe((0,k.finalize)(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(r=>{let{pair:s,value:n}=r;this.emaOracles.set(n,s)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,k.distinctUntilChanged)((t,e)=>!e.deltas),(0,k.map)((t,e)=>({value:t,index:e})),(0,k.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),(0,k.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,k.distinctUntilChanged)((t,e)=>!e.deltas),(0,k.map)((t,e)=>({value:t,index:e})),(0,k.tap)(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),(0,k.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,k.distinctUntilChanged)((t,e)=>!e.deltas),(0,k.map)((t,e)=>({value:t,index:e})),(0,k.tap)(({value:t,index:e})=>{e>0&&this.log.trace("omnipool.Assets",t.deltas?.upserted)}),this.watchGuard("omnipool.Assets")).subscribe(({value:{deltas:t}})=>{this.store.update(([e])=>{let i=t?.upserted.reduce((s,n)=>{let[a]=n.args;return s.set(a,n.value),s},new Map),r=e.tokens.map(s=>{let n=i?.get(s.id);return n?this.updateTokenState(s,n):s});return[{...e,tokens:r}]})})}subscribeUpdates(){let t=new k.Subscription;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:i,shares:r,tradable:s,cap:n,protocol_shares:a}=e;return{...t,cap:n,hubReserves:i,protocolShares:a,shares:r,tradeable:s}}};var Ar={};C(Ar,{StableMath:()=>Y,StableSwap:()=>Vt,StableSwapClient:()=>qe});var q=require("@galacticcouncil/math-stableswap"),Y=class{static getPoolAddress(t){return(0,q.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let i=0;i<t;i++)e.push(["1","1"]);return e}static calculateAmplification(t,e,i,r,s){return(0,q.calculate_amplification)(t,e,i,r,s)}static calculateInGivenOut(t,e,i,r,s,n,a){return(0,q.calculate_in_given_out)(t,e,i,r,s,n,a)}static calculateAddOneAsset(t,e,i,r,s,n,a){return(0,q.calculate_add_one_asset)(t,e,i,r,s,n,a)}static calculateSharesForAmount(t,e,i,r,s,n,a){return(0,q.calculate_shares_for_amount)(t,e,i,r,s,n,a)}static calculateOutGivenIn(t,e,i,r,s,n,a){return(0,q.calculate_out_given_in)(t,e,i,r,s,n,a)}static calculateLiquidityOutOneAsset(t,e,i,r,s,n,a){return(0,q.calculate_liquidity_out_one_asset)(t,e,i,r,s,n,a)}static calculateShares(t,e,i,r,s,n){return(0,q.calculate_shares)(t,e,i,r,s,n)}static calculateSpotPriceWithFee(t,e,i,r,s,n,a,o){return(0,q.calculate_spot_price_with_fee)(t,e,i,r,s,n,a,o)}static recalculatePegs(t,e,i,r,s,n){let a=(0,q.recalculate_peg)(t,e,i,r,s,n);return JSON.parse(a)}};var Fe=require("@galacticcouncil/common");var{FeeUtils:se}=O,Vt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new c(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),r=i.get(t),s=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:s.balance,decimalsIn:r.decimals,decimalsOut:s.decimals,tradeableIn:this.id===t?15:r.tradeable,tradeableOut:this.id===e?15:s.tradeable,assetInEd:r.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,i),n=r===0n?0:U.calculateBuyFee(r,s),a=[],o=F.isSellAllowed(t.tradeableIn),l=F.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:s,calculatedIn:r,amountOut:e,feePct:n,errors:a}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,i),n=U.calculateSellFee(r,s),a=[],o=F.isSellAllowed(t.tradeableIn),l=F.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:r,amountOut:s,feePct:n,errors:a}}calculateIn(t,e,i){let r=Y.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?se.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(r);return s<0n?0n:s}calculateAddOneAsset(t,e,i){let r=Y.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?se.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(r);return s<0n?0n:s}calculateSharesForAmount(t,e,i){let r=Y.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?se.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(r);return s<0n?0n:s}calculateInGivenOut(t,e,i){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,i):t.assetIn==this.id?this.calculateSharesForAmount(t,e,i):this.calculateIn(t,e,i)}spotPriceInGivenOut(t){let e=Y.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=Y.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?se.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(r);return s<0n?0n:s}calculateWithdrawOneAsset(t,e,i){let r=Y.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?se.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(r);return s<0n?0n:s}calculateShares(t,e,i){let r=Y.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?se.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(r);return s<0n?0n:s}calculateOutGivenIn(t,e,i){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,i):t.assetOut==this.id?this.calculateShares(t,e,i):this.calculateOut(t,e,i)}spotPriceOutGivenIn(t){let e=Y.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,Jt.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],Jt.jsonFormatter)}normalizeSpot(t,e,i,r,s){return e?t*Fe.big.pow10(Fe.RUNTIME_DECIMALS-s):i?t/Fe.big.pow10(s-r):t}};var Bi=require("polkadot-api"),Ws=require("@polkadot-api/utils"),Ys=require("@noble/hashes/blake2b"),N=require("rxjs"),ki=require("@galacticcouncil/common");var Ns=require("polkadot-api"),_r=require("viem");var Or=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}],Ls=[{anonymous:!1,inputs:[{indexed:!1,name:"key",type:"string"},{indexed:!1,name:"value",type:"uint128"},{indexed:!1,name:"timestamp",type:"uint128"}],name:"OracleUpdate",type:"event"}],qs=[{anonymous:!1,inputs:[{indexed:!0,name:"roundId",type:"uint80"},{indexed:!1,name:"answer",type:"int256"},{indexed:!1,name:"timestamp",type:"uint256"}],name:"PriceUpdated",type:"event"}];var Me=class{static parse(t){let{address:e,topics:i,data:r}=t.log,s=e.toLowerCase(),n=Ns.Binary.toHex(r);try{let{eventName:a,args:o}=(0,_r.decodeEventLog)({abi:qs,topics:i,data:n});return{eventName:`ManagedOracle.${a}`,emitter:s,value:o.answer,timestamp:o.timestamp}}catch{}try{let{eventName:a,args:o}=(0,_r.decodeEventLog)({abi:Ls,topics:i,data:n});return{eventName:`DIA.${a}`,emitter:s,key:o.key,value:o.value,timestamp:o.timestamp}}catch{}}};var De=class{adapter;constructor(t){this.adapter=t.getRPCAdapter()}async getData(t,e=6){let[i,r,s]=await Promise.all([this.adapter.readContract({abi:Or,address:t,functionName:"latestRoundData"}),this.adapter.readContract({abi:Or,address:t,functionName:"decimals"}),this.adapter.getBlock()]),[n,a,o,l]=i,u=s.number-(s.timestamp-l)/BigInt(e),p=Number(u);return{price:a,decimals:r,updatedAt:p<0?0:p}}};var Hs={"EUR/USD":"0xaa47a5662269270d3df33ae08f806e383611575c","sUSDs/USD":"0x4b32bffc6acd751446e79e8687ef3815fd7924fd","sUSDe/USD":"0x22cdea305cee63d082e79f8c5db939eecd0265d0"},Vs={"0xcfab6a4031c70da0f0cf6f31a252c16119db3611":"0xaafd758688cefd0a7b7770a825f1aad551e16185"},Gs={"bifrosto:5:15:LastBlock":"0xaafd758688cefd0a7b7770a825f1aad551e16185"};function Us(c,t,e){let i=Buffer.from(c.replace(/^0x/,""),"hex").toString("ascii").replace(/\0+$/,""),[r,s]=[t[0],t[1]].sort((n,a)=>n-a);return`${i}:${r}:${s}:${e}`}var{FeeUtils:ne}=O,Le=class c{static compute(t,e,i,r){let s=c.getRecent(e),n=ne.fromPermill(t.fee),a=ne.fromPerbill(e.max_peg_update),o=i.map(({pair:h,updatedAt:g})=>[h,g]),l=i.find(h=>h.source),u=e.updated_at?e.updated_at.toString():l?.updatedAt;if(!u)throw new Error("Current peg unknown!");let[p,d]=Y.recalculatePegs(JSON.stringify(s),u,JSON.stringify(o),r.toString(),ne.toRaw(a).toString(),ne.toRaw(n).toString()),m=Number(p)*1e6;return{pegsFee:ne.fromPermill(m),pegs:d}}static getDefault(t){return{pegsFee:ne.fromPermill(t.fee),pegs:Y.defaultPegs(t.assets.length)}}static getRecent(t){let{current:e}=t;return Array.from(e.entries()).map(([i,r])=>r.map(s=>s.toString()))}};var{FeeUtils:ha}=O,ga=["ManagedOracle.PriceUpdated","DIA.OracleUpdate"],qe=class extends Q{poolsData=new Map([]);mmOracle=new De(this.evm);mmAddresses=new Set;mmRouting={byEmitter:new Map,byDiaKey:new Map,byEma:new Map};queryBus=new Lt;emaOracles=this.queryBus.scope("EmaOracle.Oracles",(t,e,i)=>this.api.query.EmaOracle.Oracles.getValue(t,e,i,{at:this.at}),(t,e,i)=>`${t.toString()}:${e.join(":")}:${i.type}`,6*1e3);mmOracles=this.queryBus.scope("MmOracle",t=>this.mmOracle.getData(t),t=>t.toLowerCase(),600*1e3);pegs=this.queryBus.scope("Stableswap.PoolPegs",t=>this.api.query.Stableswap.PoolPegs.getValue(t,{at:this.at}),t=>String(t),6*1e3);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=Y.getPoolAddress(t),i=(0,Ys.blake2b)(e,{dkLen:32}),r=(0,Ws.toHex)(i);return(0,Bi.AccountId)(ki.HYDRATION_SS58_PREFIX).dec(r)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:i,final_amplification:r,initial_block:s,final_block:n}=t,a=Y.calculateAmplification(i.toString(),r.toString(),s.toString(),n.toString(),e.toString()),o=Number(a)<r;return{amplification:BigInt(a),isRampPeriod:o}}async getPoolTokens(t,e){let i=this.getPoolAddress(t),r=e.assets.map(async s=>{let[n,a,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,s,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(s,{at:this.at}),this.balance.getBalance(i,s)]);return{id:s,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:o.transferable,tradeable:n,type:a?.asset_type.type}});return Promise.all(r)}buildRouting(){this.mmRouting.byEmitter.clear(),this.mmRouting.byDiaKey.clear(),this.mmRouting.byEma.clear();for(let t of this.mmAddresses)this.mmRouting.byEmitter.set(t,t);for(let[t,e]of Object.entries(Vs)){let i=t.toLowerCase(),r=e.toLowerCase();this.mmAddresses.has(r)&&this.mmRouting.byEmitter.set(i,r)}for(let[t,e]of Object.entries(Hs)){let i=e.toLowerCase();this.mmAddresses.has(i)&&this.mmRouting.byDiaKey.set(t,i)}for(let[t,e]of Object.entries(Gs)){let i=e.toLowerCase();this.mmAddresses.has(i)&&this.mmRouting.byEma.set(t,i)}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Stableswap.Pools.isCompatible(Bi.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e,i,r]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:this.at}),this.api.query.Stableswap.PoolPegs.getEntries({at:this.at}),this.api.query.System.Number.getValue({at:this.at}),this.getPoolLimits()]);for(let{keyArgs:n,value:a}of e){let[o]=n;this.pegs.set(a,o);for(let l of a.source)l.type==="MMOracle"&&this.mmAddresses.add(l.value.toString().toLowerCase())}this.buildRouting();let s=t.map(async({keyArgs:n,value:a})=>{let[o]=n,l=this.getPoolAddress(o),[u,p,d,m]=await Promise.all([this.getPoolTokens(o,a),this.getPoolAmplification(a,i),this.getPoolPegs(o,a,i),this.api.query.Tokens.TotalIssuance.getValue(o,{at:this.at})]);return u.push({id:o,tradeable:15,balance:m,decimals:ki.RUNTIME_DECIMALS}),this.poolsData.set(o,a),{address:l,id:o,type:"Stableswap",fee:ha.fromPermill(a.fee),tokens:u,totalIssuance:m,...d,...r,...p}});return Promise.all(s)}async getPoolFees(t,e){return{fee:this.store.pools.find(r=>r.address===e).fee}}async getPoolPegs(t,e,i){let r=await this.pegs.get(t);if(!r)return Le.getDefault(e);let s=await this.getLatestPegs(e,r,i);return Le.compute(e,r,s,i)}async getLatestPegs(t,e,i){let{source:r}=e,s=t.assets,n=r.map(async(a,o)=>{if(a.type==="Oracle"){let[l,u,p]=a.value,d=[p,s[o]].sort((f,y)=>f-y),m=await this.emaOracles.get(l,d,u);if(!m)throw new Error("EmaOracle missing for "+l+" / "+d);let[{price:h,updated_at:g}]=m;return{pair:p===d[0]?[h.n.toString(),h.d.toString()]:[h.d.toString(),h.n.toString()],updatedAt:g.toString(),source:a.type}}if(a.type==="MMOracle"){let l=a.value.toString(),{price:u,decimals:p,updatedAt:d}=await this.mmOracles.get(l),m=(10n**BigInt(p)).toString();return{pair:[u.toString(),m],updatedAt:d.toString(),source:a.type}}if(a.type==="Value")return{pair:a.value.map(u=>u.toString()),updatedAt:i.toString()};throw new Error(a+" source not supported")});return Promise.all(n)}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,{at:"best"}).pipe((0,N.map)(({value:r})=>r),(0,N.map)((r,s)=>({value:r,index:s})),(0,N.tap)(({index:r,value:s})=>{r>0&&this.log.trace("tokens.TotalIssuance",i,s)}),(0,N.map)(({value:r})=>({id:i,value:r}))));return(0,N.merge)(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:r,value:s}=i;this.store.update(n=>{let a=[];return n.filter(o=>o.id===r).forEach(o=>{let l=o.tokens.map(u=>u.id===r?{...u,balance:s}:u);a.push({...o,tokens:l,totalIssuance:s})}),a})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,N.distinctUntilChanged)((t,e)=>!e.deltas),(0,N.map)((t,e)=>({value:t,index:e})),(0,N.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}})=>{for(let{args:e,value:i}of t?.upserted??[]){let[r]=e;this.pegs.set(i,r)}}})}subscribeEmaOracles(){return this.api.query.EmaOracle.Oracles.watchEntries({at:"best"}).pipe((0,N.distinctUntilChanged)((t,e)=>!e.deltas),(0,N.map)((t,e)=>({value:t,index:e})),(0,N.tap)(({value:t,index:e})=>{e>0&&this.log.trace("emaOracle.Oracles",t.deltas?.upserted)}),this.watchGuard("emaOracle.Oracles")).subscribe(async({value:{deltas:t}})=>{let e=new Set;for(let{args:i,value:r}of t?.upserted??[]){let[s,n,a]=i;this.emaOracles.set(r,s,n,a);let o=Us(s,n,a.type),l=this.mmRouting.byEma.get(o);l&&e.add(l)}for(let i of e){let r=await this.mmOracle.getData(i);this.log.trace("mmOracle.Hybrid",{h160:i,fresh:r}),this.mmOracles.set(r,i)}})}subscribeMMOracles(){return this.api.event.EVM.Log.watch().pipe((0,N.map)(({events:t})=>t.map(e=>Me.parse(e.payload)).filter(e=>!!e).filter(({eventName:e})=>ga.includes(e))),(0,N.filter)(t=>t.length>0),this.watchGuard("evm.Log")).subscribe(async t=>{let e=new Set;for(let i of t){if(console.log(i),i.eventName==="ManagedOracle.PriceUpdated"){let r=this.mmRouting.byEmitter.get(i.emitter);r&&e.add(r)}if(i.eventName==="DIA.OracleUpdate"&&i.key){let r=this.mmRouting.byDiaKey.get(i.key);r&&e.add(r)}}for(let i of e){let r=await this.mmOracle.getData(i);this.log.trace("mmOracle",{h160:i,fresh:r}),this.mmOracles.set(r,i)}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(async e=>{let i=[];for(let r of e){let s=this.poolsData.get(r.id);if(s){let n=await this.getPoolPegs(r.id,s,t),a=this.getPoolAmplification(s,t);i.push({...r,...n,...a})}}return i})})}subscribeUpdates(){let t=new N.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeMMOracles()),t.add(this.subscribeIssuance()),t.add(this.subscribeBlock()),t}};var Br={};C(Br,{XykMath:()=>Ot,XykPool:()=>Ne,XykPoolClient:()=>He});var H=require("@galacticcouncil/math-xyk"),Ot=class{static getSpotPrice(t,e,i){return(0,H.get_spot_price)(t,e,i)}static calculateInGivenOut(t,e,i){return(0,H.calculate_in_given_out)(t,e,i)}static calculateOutGivenIn(t,e,i){return(0,H.calculate_out_given_in)(t,e,i)}static calculatePoolTradeFee(t,e,i){return(0,H.calculate_pool_trade_fee)(t,e,i)}static calculateLiquidityIn(t,e,i){return(0,H.calculate_liquidity_in)(t,e,i)}static calculateSpotPrice(t,e){return(0,H.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,i,r){return(0,H.calculate_spot_price_with_fee)(t,e,i,r)}static calculateShares(t,e,i){return(0,H.calculate_shares)(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,r){return(0,H.calculate_liquidity_out_asset_a)(t,e,i,r)}static calculateLiquidityOutAssetB(t,e,i,r){return(0,H.calculate_liquidity_out_asset_b)(t,e,i,r)}};var $s=require("@galacticcouncil/common");var{FeeUtils:zs}=O,Ne=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),r=i.get(t),s=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:r.decimals,decimalsOut:s.decimals,balanceIn:r.balance,balanceOut:s.balance,assetInEd:r.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),s=this.calculateTradeFee(r,i),n=zs.toPct(i.exchangeFee),a=r+s,o=[];(e<this.minTradingLimit||r<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:r,amountOut:e,feePct:n,errors:o}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),s=this.calculateTradeFee(r,i),n=zs.toPct(i.exchangeFee),a=r-s,o=[];(e<this.minTradingLimit||r<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:a,feePct:n,errors:o}}calculateInGivenOut(t,e){let i=Ot.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}calculateOutGivenIn(t,e){let i=Ot.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(i);return r<0n?0n:r}spotPriceInGivenOut(t){let e=Ot.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=Ot.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=Ot.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(i)}normalizeSpot(t,e,i){let r=e-i;if(r===0)return t;let s=$s.big.pow10(Math.abs(r));return r>0?t*s:t/s}};var Xs=require("polkadot-api"),Ks=require("rxjs");var He=class extends Q{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,i]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:i}}async isSupported(){return(await this.api.getStaticApis()).compat.query.XYK.PoolAssets.isCompatible(Xs.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries({at:this.at}),this.getPoolLimits()]),i=t.map(async({keyArgs:r,value:s})=>{let[n]=r,[a,o]=s,[l,u,p,d]=await Promise.all([this.balance.getBalance(n,a),this.api.query.AssetRegistry.Assets.getValue(a,{at:this.at}),this.balance.getBalance(n,o),this.api.query.AssetRegistry.Assets.getValue(o,{at:this.at})]);return{address:n,type:"XYK",tokens:[{id:a,decimals:u?.decimals||this.decimals.get(a),existentialDeposit:u?.existential_deposit,balance:l.transferable,type:u?.asset_type.type},{id:o,decimals:d?.decimals||this.decimals.get(o),existentialDeposit:d?.existential_deposit,balance:p.transferable,type:d?.asset_type.type}],...e}});return Promise.all(i)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return Ks.Subscription.EMPTY}};var kr={};C(kr,{AavePool:()=>Ve,AavePoolClient:()=>Ge});var ae=require("@galacticcouncil/common");var Ve=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),r=i.get(t),s=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:s.balance,decimalsIn:r.decimals,decimalsOut:s.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),s=[];return e>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),s=[];return r>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return ae.big.toBigInt(1,ae.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return ae.big.toBigInt(1,ae.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var js=require("polkadot-api"),Qs=require("@polkadot-api/utils"),st=require("rxjs"),Ei=require("@galacticcouncil/common");var{ERC20:ba}=Ei.erc20,fa=["Supply","Withdraw","Repay","Borrow"],Ge=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")),s=(0,Qs.toHex)(r);return(0,js.AccountId)(Ei.HYDRATION_SS58_PREFIX).dec(s)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:this.at})).map(async({reserve:i,atoken:r,liqudity_in:s,liqudity_out:n})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(i,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(i,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(r,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(r,{at:this.at})]);return{address:this.getPoolId(i,r),type:"Aave",tokens:[{id:i,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:s,location:o,type:a?.asset_type.type},{id:r,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:n,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:r,liqudity_out:s}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:this.at});return t.tokens.map(n=>{let a=n.id===e.id?r:s;return{...n,balance:a}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key}throw new Error("Invalid aave reserve multilocation")}return ba.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:i}=t;return{assetIn:e,assetOut:i,key:`${e}:${i}`}}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,st.mergeMap)(({events:i})=>i),(0,st.map)(({payload:i})=>this.parseRouterLog(i)),(0,st.filter)(({assetIn:i,assetOut:r})=>e.includes(i)||e.includes(r)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:r,key:s})=>{this.log.trace("router.Executed",s),this.store.update(async n=>{let a=[];for(let o of n){let[l,u]=o.tokens;if(u.id===i||u.id===r){let d=await this.getPoolDelta(o);a.push({...o,tokens:d})}}return a})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,st.mergeMap)(({events:t})=>t),(0,st.map)(({payload:t})=>we.parse(t)),(0,st.filter)(t=>t!==void 0),(0,st.filter)(({eventName:t})=>fa.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async i=>{let r=[];for(let s of i){let[n]=s.tokens;if(this.getReserveH160Id(n).toLowerCase()===t){let o=await this.getPoolDelta(s);r.push({...s,tokens:o})}}return r})})}subscribeBalances(){return st.Subscription.EMPTY}subscribeUpdates(){let t=new st.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var Rr={};C(Rr,{HsmMath:()=>ct,HsmPool:()=>Ue,HsmPoolClient:()=>We});var J=require("@galacticcouncil/math-hsm"),ct=class{static calculateCollateralInGivenHollarOut(t,e,i){return(0,J.calculate_collateral_in_given_hollar_out)(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return(0,J.calculate_collateral_out_given_hollar_in)(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return(0,J.calculate_hollar_out_given_collateral_in)(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return(0,J.calculate_hollar_in_given_collateral_out)(t,e,i)}static calculateImbalance(t,e,i){return(0,J.calculate_imbalance)(t,e,i)}static calculateBuybackLimit(t,e){return(0,J.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,i){return(0,J.calculate_buyback_price_with_fee)(t,e,i)}static calculateMaxPrice(t,e){return(0,J.calculate_max_price)(t,e)}};var Z=require("@galacticcouncil/common");var{FeeUtils:oe}=O,Ue=class c extends Vt{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new c(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,i){let r=this.parsePair(t.assetOut,t.assetIn),s=super.calculateInGivenOut(r,e,{fee:this.fee}),n=this.calculateBuybackLimit(t);e>n&&i.push("MaxBuyBackExceeded");let a=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,s)>a&&i.push("MaxBuyPriceExceeded"),s>this.collateralBalance&&i.push("InsufficientCollateral"),i}validateTradeHollarOut(t,e,i){return this.collateralBalance+t>this.maxInHolding&&i.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&i.push("FacilitatorCapacityExceeded"),i}validateTradeConstraints(t,e,i){let r=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,r):this.validateTradeHollarOut(e,i,r)}validateAndBuy(t,e){let i=this.calculateInGivenOut(t,e),r=this.validateTradeConstraints(t,i,e);return{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:r}}validateAndSell(t,e){let i=this.calculateOutGivenIn(t,e),r=this.validateTradeConstraints(t,e,i);return{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:r}}calculateHollarInGivenCollateralOut(t,e){let i=super.calculateInGivenOut(t,e,{fee:this.fee}),r=ct.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),oe.toRaw(this.buyBackFee).toString());return BigInt(r)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=ct.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),oe.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=ct.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),oe.toRaw(this.buyBackFee).toString());return BigInt(r)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=ct.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),oe.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=ct.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=ct.calculateBuybackLimit(e.toString(),oe.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let r=ct.calculateBuybackPriceWithFee(i.toString(),e.toString(),oe.toRaw(this.buyBackFee).toString()),[s,n]=JSON.parse(r),a=Z.big.pow10(t.decimalsIn+Z.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(s)*a/BigInt(n)}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=ct.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[r,s]=JSON.parse(i),n=Z.big.pow10(Z.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(r)*n/BigInt(s)}spotPriceInGivenOut(t){let e=Z.big.toBigInt(1,t.decimalsOut),r=this.calculateInGivenOut(t,e)*Z.big.pow10(Z.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(r,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=Z.big.toBigInt(1,t.decimalsIn),r=this.calculateOutGivenIn(t,e)*Z.big.pow10(Z.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)?[Z.big.toBigInt(1,18).toString(),Z.big.toBigInt(1,i).toString()]:e}isDefaultPeg(t){let[e,i]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&i==="1"}normalizeSpotPrice(t,e,i){let r=e-i;if(r===0)return t;let s=Z.big.pow10(Math.abs(r));return r>0?t*s:t/s}};var Mi=require("polkadot-api"),en=require("@polkadot-api/utils"),K=require("rxjs"),Di=require("@galacticcouncil/common");var Js=require("polkadot-api"),Zs=require("viem");var Ri=[{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 Ci=class{static parse(t){let{topics:e,data:i}=t.log,r=Js.Binary.toHex(i);try{let{eventName:s,args:n}=(0,Zs.decodeEventLog)({abi:Ri,topics:e,data:r}),a=n.facilitatorAddress.toLowerCase();return{eventName:s,facilitator:a,key:`${s}:${a}`}}catch{return}}};var Fi=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,r]=await this.client.readContract({abi:Ri,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-r}};var{FeeUtils:Er}=O,{H160:tn}=Di.h160,ya=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],We=class extends Q{ghoClient;stableClient;constructor(t,e,i,r){super(t,e,r),this.stableClient=i,this.ghoClient=new Fi(e)}getPoolType(){return"HSM"}getPoolId(t){return this.getPoolAddress("hsm:"+t)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(t){if(t){let e=t.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:i}=e.value;return i.key}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),i=new TextEncoder().encode(e),r=(0,en.toHex)(i);return(0,Mi.AccountId)(Di.HYDRATION_SS58_PREFIX).dec(r)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(Mi.CompatibilityLevel.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,r]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t,{at:this.at}),this.api.query.HSM.Collaterals.getEntries({at:this.at}),this.stableClient.getPools()]);if(i.length===0)return[];let s=this.getFacilitatorAddress(),n=tn.fromAny(s),a=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(a,n),l=i.map(async({keyArgs:p,value:d})=>{let[m]=p,{pool_id:h,max_buy_price_coefficient:g,max_in_holding:b,purchase_fee:f,buy_back_fee:y,buyback_rate:S}=d,w=r.find(v=>v.id===h);if(w){let v=this.getPoolId(h),I=await this.balance.getBalance(s,m);return{...w,address:v,type:"HSM",tokens:w.tokens.filter(_=>_.id!==h),hsmAddress:s,hsmMintCapacity:o,hollarId:t,hollarH160:a,collateralId:m,collateralBalance:I.transferable,maxBuyPriceCoefficient:g,maxInHolding:b,purchaseFee:Er.fromPermill(f),buyBackFee:Er.fromPermill(y),buyBackRate:Er.fromPerbill(S)}}});return(await Promise.all(l)).filter(p=>p!==null)}async getPoolFees(){return{}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,K.mergeMap)(({events:t})=>t),(0,K.map)(({payload:t})=>Ci.parse(t)),(0,K.filter)(t=>t!==void 0),(0,K.filter)(({eventName:t})=>ya.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async i=>{let r=[],[{hsmAddress:s,hollarH160:n}]=i,a=tn.fromAny(s);if(a.toLowerCase()===e){let l=await this.ghoClient.getFacilitatorCapacity(n,a);for(let u of i)r.push({...u,hsmMintCapacity:l})}return r})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(s=>{let{tokens:n,collateralId:a}=s;n.find(l=>l.id===a).type==="Erc20"?e.push(a):t.push(a)});let[{hsmAddress:i}]=this.store.pools,r=[];if(t.length>0){let s=this.balance.watchTokensBalance(i);r.push(s)}if(e.length>0){let s=this.balance.watchErc20Balance(i,e);r.push(s)}return r.length>0?(0,K.combineLatest)(r).pipe((0,K.map)(s=>s.flat()),(0,K.pairwise)(),(0,K.map)(([s,n])=>this.balance.getDeltas(s,n)),this.watchGuard("balances")).subscribe(s=>{this.store.update(n=>{let a=[],o=new Map(n.map(l=>[l.collateralId,l]));return s.forEach(({id:l,balance:u})=>{let p=o.get(l);p&&(this.log.trace("balances",{id:l,balance:u}),a.push({...p,collateralBalance:u.transferable}))}),a})}):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 s of i){let n=e.get(s.id);n&&r.push({...s,fee:n.fee,tokens:n.tokens.filter(a=>a.id!==s.id),totalIssuance:n.totalIssuance,pegs:n.pegs,amplification:n.amplification,isRampPeriod:n.isRampPeriod})}return r})})}subscribeBalances(){return K.Subscription.EMPTY}subscribeUpdates(){let t=new K.Subscription;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var Lr={};C(Lr,{UNISWAP_V3_FACTORY:()=>Cr,UniswapV3Math:()=>le,UniswapV3Pool:()=>Gt,UniswapV3PoolClient:()=>ze,V3_POOLS:()=>Fr,ticksInWord:()=>un});var Cr="0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0",Fr=[{assetA:16,assetB:9,fee:3e3},{assetA:16,assetB:9,fee:500}];var E=St(require("jsbi")),z=require("@uniswap/v3-sdk"),Mr=E.default.BigInt(0),rn=E.default.BigInt(1),Dr=E.default.BigInt(-1),le=class c{static calculateOutGivenIn(t,e,i){if(i<=0n||t.liquidity<=0n)return 0n;let r=c.computeSwap(t,e,E.default.BigInt(i.toString())),s=E.default.multiply(r.amountCalculated,Dr);return BigInt(s.toString())}static calculateInGivenOut(t,e,i){if(i<=0n||t.liquidity<=0n)return 0n;let r=c.computeSwap(t,e,E.default.multiply(E.default.BigInt(i.toString()),Dr));return BigInt(r.amountCalculated.toString())}static computeSwap(t,e,i){let r=c.buildTicks(t.ticks),s=t.tickSpacing,n=t.fee,a=e?E.default.add(z.TickMath.MIN_SQRT_RATIO,rn):E.default.subtract(z.TickMath.MAX_SQRT_RATIO,rn),o=E.default.greaterThanOrEqual(i,Mr),l=i,u=Mr,p=E.default.BigInt(t.sqrtPriceX96.toString()),d=t.tick,m=E.default.BigInt(t.liquidity.toString());for(;E.default.notEqual(l,Mr)&&E.default.notEqual(p,a);){let h=p,[g,b]=z.TickList.nextInitializedTickWithinOneWord(r,d,e,s);g<z.TickMath.MIN_TICK?g=z.TickMath.MIN_TICK:g>z.TickMath.MAX_TICK&&(g=z.TickMath.MAX_TICK);let f=z.TickMath.getSqrtRatioAtTick(g),y=(e?E.default.lessThan(f,a):E.default.greaterThan(f,a))?a:f,[S,w,v,I]=z.SwapMath.computeSwapStep(p,y,m,l,n);if(p=S,o?(l=E.default.subtract(l,E.default.add(w,I)),u=E.default.subtract(u,v)):(l=E.default.add(l,v),u=E.default.add(u,E.default.add(w,I))),E.default.equal(p,f)){if(b){let _=z.TickList.getTick(r,g).liquidityNet;e&&(_=E.default.multiply(_,Dr)),m=z.LiquidityMath.addDelta(m,_)}d=e?g-1:g}else E.default.notEqual(p,h)&&(d=z.TickMath.getTickAtSqrtRatio(p))}return{amountCalculated:u,sqrtPriceX96:p,liquidity:m,tick:d}}static buildTicks(t){return t.map(e=>new z.Tick({index:e.index,liquidityGross:e.liquidityGross.toString(),liquidityNet:e.liquidityNet.toString()})).sort((e,i)=>e.index-i.index)}};var an=require("@galacticcouncil/common");var Pa=1e6,sn=10n**BigInt(an.RUNTIME_DECIMALS),nn=192n,Gt=class c{type;address;id;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;token0;token1;sqrtPriceX96;tick;liquidity;tickSpacing;ticks;static fromPool(t){return new c(t)}constructor(t){this.type="UniswapV3",this.address=t.address,this.id=t.id,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.token0=t.token0,this.token1=t.token1,this.sqrtPriceX96=t.sqrtPriceX96,this.tick=t.tick,this.liquidity=t.liquidity,this.tickSpacing=t.tickSpacing,this.ticks=t.ticks}validatePair(t,e){let i=r=>r===this.token0||r===this.token1;return i(t)&&i(e)&&t!==e}parsePair(t,e){let i=new Map(this.tokens.map(n=>[n.id,n])),r=i.get(t),s=i.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:r.decimals,decimalsOut:s.decimals,balanceIn:r.balance,balanceOut:s.balance,assetInEd:r.existentialDeposit,assetOutEd:s.existentialDeposit}}calculateInGivenOut(t,e,i){return le.calculateInGivenOut(this.toState(i!=null),this.isZeroForOne(t.assetIn),e)}calculateOutGivenIn(t,e,i){return le.calculateOutGivenIn(this.toState(i!=null),this.isZeroForOne(t.assetIn),e)}spotPriceOutGivenIn(t){let e=this.spotOutPerIn(this.isZeroForOne(t.assetIn));return this.normalizeSpot(e,t.decimalsIn,t.decimalsOut)}spotPriceInGivenOut(t){let e=this.spotOutPerIn(!this.isZeroForOne(t.assetIn));return this.normalizeSpot(e,t.decimalsOut,t.decimalsIn)}validateAndSell(t,e,i){let r=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,this.fees()),n=U.calculateSellFee(r,s),a=[];(e<this.minTradingLimit||r<t.assetOutEd)&&a.push("InsufficientTradingAmount");let o=t.balanceIn/this.maxInRatio;e>o&&a.push("MaxInRatioExceeded");let l=t.balanceOut/this.maxOutRatio;return s>l&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:s,feePct:n,errors:a}}validateAndBuy(t,e,i){let r=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,this.fees()),n=U.calculateBuyFee(r,s),a=[];(e<this.minTradingLimit||r<t.assetInEd)&&a.push("InsufficientTradingAmount");let o=t.balanceOut/this.maxOutRatio;e>o&&a.push("MaxOutRatioExceeded");let l=t.balanceIn/this.maxInRatio;return s>l&&a.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:r,amountOut:e,feePct:n,errors:a}}fees(){return{fee:[this.fee,Pa]}}isZeroForOne(t){return t===this.token0}toState(t){return{fee:t?this.fee:0,sqrtPriceX96:this.sqrtPriceX96,tick:this.tick,liquidity:this.liquidity,tickSpacing:this.tickSpacing,ticks:this.ticks}}spotOutPerIn(t){let e=this.sqrtPriceX96*this.sqrtPriceX96;if(e===0n)return 0n;let i=e*sn>>nn;return t?i:(sn<<nn)/e}normalizeSpot(t,e,i){let r=e-i;if(r===0)return t;let s=10n**BigInt(Math.abs(r));return r>0?t*s:t/s}};var Rt=require("rxjs"),cn=require("@galacticcouncil/common"),Et=require("@uniswap/v3-sdk");var Li=require("viem"),on=(0,Li.parseAbi)(["function getPool(address tokenA, address tokenB, uint24 fee) view returns (address pool)"]),Ut=(0,Li.parseAbi)(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)","function liquidity() view returns (uint128)","function tickBitmap(int16 wordPosition) view returns (uint256)","function ticks(int24 tick) view returns (uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized)"]),Ye=(0,Li.parseAbi)(["function balanceOf(address account) view returns (uint256)"]);var{ERC20:qi}=cn.erc20,wa="0x0000000000000000000000000000000000000000",Sa=1e6,ln=5;function un(c,t,e){let i=[];for(let r=0;r<256;r++)c>>BigInt(r)&1n&&i.push((t*256+r)*e);return i}var ze=class extends Q{getPoolType(){return"UniswapV3"}async isSupported(){return!0}async getPoolFees(t,e){let i=this.store.pools.find(s=>s.address===e);return{fee:[i?i.fee:0,Sa]}}async loadPools(){let t=this.evm.getWsProvider();return(await Promise.all(Fr.map(i=>this.loadPool(t,i)))).filter(i=>i!==void 0)}async loadPool(t,e){try{let{assetA:i,assetB:r,fee:s}=e,n=Et.TICK_SPACINGS[s];if(n===void 0)return;let a=qi.fromAssetId(i).toLowerCase(),o=qi.fromAssetId(r).toLowerCase(),l=a<o,u=l?i:r,p=l?r:i,d=l?a:o,m=l?o:a,h=await t.readContract({abi:on,address:Cr,functionName:"getPool",args:[d,m,s]});if(h.toLowerCase()===wa)return;let[g,b,f,y,S,w]=await Promise.all([t.readContract({abi:Ut,address:h,functionName:"slot0"}),t.readContract({abi:Ut,address:h,functionName:"liquidity"}),t.readContract({abi:Ye,address:d,functionName:"balanceOf",args:[h]}),t.readContract({abi:Ye,address:m,functionName:"balanceOf",args:[h]}),this.api.query.AssetRegistry.Assets.getValue(u,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(p,{at:this.at})]),v=g[0],I=g[1],_=await this.loadTicks(t,h,I,n);return{address:h,type:"UniswapV3",token0:u,token1:p,fee:s,sqrtPriceX96:v,tick:I,liquidity:b,tickSpacing:n,ticks:_,tokens:[{id:u,decimals:S?.decimals,existentialDeposit:S?.existential_deposit??0n,balance:f,type:S?.asset_type.type},{id:p,decimals:w?.decimals,existentialDeposit:w?.existential_deposit??0n,balance:y,type:w?.asset_type.type}],maxInRatio:3n,maxOutRatio:3n,minTradingLimit:0n}}catch(i){this.log.error("v3_load_pool",e,i);return}}async loadTicks(t,e,i,r){let s=Math.floor(i/r)>>8,n=[];for(let m=s-ln;m<=s+ln;m++)n.push(m);let a=await Promise.all(n.map(m=>t.readContract({abi:Ut,address:e,functionName:"tickBitmap",args:[m]}))),o=n.flatMap((m,h)=>un(a[h],m,r)),l=await Promise.all(o.map(m=>t.readContract({abi:Ut,address:e,functionName:"ticks",args:[m]}))),u=o.map((m,h)=>({index:m,liquidityGross:l[h][0],liquidityNet:l[h][1]})),p=(0,Et.nearestUsableTick)(Et.TickMath.MIN_TICK,r),d=(0,Et.nearestUsableTick)(Et.TickMath.MAX_TICK,r);return u.some(m=>m.index===p)||u.push({index:p,liquidityNet:0n,liquidityGross:0n}),u.some(m=>m.index===d)||u.push({index:d,liquidityNet:0n,liquidityGross:0n}),u.sort((m,h)=>m.index-h.index),u}async refreshPool(t,e){let i=e.address,r=qi.fromAssetId(e.token0).toLowerCase(),s=qi.fromAssetId(e.token1).toLowerCase(),[n,a,o,l]=await Promise.all([t.readContract({abi:Ut,address:i,functionName:"slot0"}),t.readContract({abi:Ut,address:i,functionName:"liquidity"}),t.readContract({abi:Ye,address:r,functionName:"balanceOf",args:[i]}),t.readContract({abi:Ye,address:s,functionName:"balanceOf",args:[i]})]),u=n[1],p=await this.loadTicks(t,i,u,e.tickSpacing),d=e.tokens.map(m=>m.id===e.token0?{...m,balance:o}:{...m,balance:l});return{...e,sqrtPriceX96:n[0],tick:u,liquidity:a,ticks:p,tokens:d}}subscribeBalances(){return Rt.Subscription.EMPTY}subscribeUpdates(){let t=new Set(this.store.pools.map(e=>e.address.toLowerCase()));return this.api.event.EVM.Log.watch().pipe((0,Rt.mergeMap)(({events:e})=>e),(0,Rt.map)(({payload:e})=>e.log.address.toLowerCase()),(0,Rt.filter)(e=>t.has(e)),this.watchGuard("evm.Log")).subscribe(e=>{this.log.trace("evm.Log",e),this.store.update(async i=>{let r=this.evm.getWsProvider(),s=[];for(let n of i)n.address.toLowerCase()===e&&s.push(await this.refreshPool(r,n));return s})})}};var ce=class{static get(t){switch(t.type){case"Aave":return Ve.fromPool(t);case"XYK":return Ne.fromPool(t);case"Omnipool":return Re.fromPool(t);case"LBP":return ke.fromPool(t);case"Stableswap":return Vt.fromPool(t);case"HSM":return Ue.fromPool(t);case"UniswapV3":return Gt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var pn=require("@galacticcouncil/common"),nt=require("rxjs");var{logger:va}=pn.log,ue=class extends V{evm;aave;omnipool;stableswap;hsm;xyk;lbp;uniswapv3;active=new Set([]);pools=new Map([]);clients=[];aaveSub=nt.Subscription.EMPTY;omniSub=nt.Subscription.EMPTY;stableSub=nt.Subscription.EMPTY;hsmSub=nt.Subscription.EMPTY;xykSub=nt.Subscription.EMPTY;lbpSub=nt.Subscription.EMPTY;v3Sub=nt.Subscription.EMPTY;isReady=!1;isDestroyed=new nt.Subject;constructor(t,e,i){super(t,i),this.evm=e,this.aave=new Ge(t,e,i),this.omnipool=new Ce(t,e,i),this.stableswap=new qe(t,e,i),this.hsm=new We(t,e,this.stableswap,i),this.xyk=new He(t,e,i),this.lbp=new Ee(t,e,i),this.uniswapv3=new ze(t,e,i),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp,this.uniswapv3]}get isHistorical(){return this.at!=="best"&&this.at!=="finalized"}subscribe(t){return this.isHistorical?nt.Subscription.EMPTY:t.getSubscriber().pipe((0,nt.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")||(va.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}withV3(){return this.v3Sub.unsubscribe(),this.v3Sub=this.subscribe(this.uniswapv3),this.active.add("UniswapV3"),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 Mt(e.type)}};var Ni=class{constructor(t){this.snapshot=t;let{aave:e,xyk:i,lbp:r,stable:s,omni:n}=t.pools;this.flat=[...e,...i,...r,...s,...n]}flat;async getPools(){return this.flat}async getPoolFees(t,e){let{block:i,states:r}=this.snapshot;switch(e.type){case"Aave":return{};case"XYK":{let{exchangeFee:s}=r.xyk;return{exchangeFee:s}}case"LBP":{let{repayFee:s}=r.lbp;return{exchangeFee:e.fee,repayFee:s}}case"Stableswap":return{fee:e.fee};case"Omnipool":{let s=t.assetOut,n=t.assetIn,{dynamicFees:a,emaOracles:o,assetFeeParams:l,protocolFeeParams:u,maxSlipFee:p}=r.omni,d=a.find(({asset:g})=>g===s)?.fee,m=o.find(({pair:g})=>g.join(":")===Ai(s))?.oracle,h=o.find(({pair:g})=>g.join(":")===Ai(n))?.oracle;return Ht.compute(t,i,d,m,h,l,u,p)}default:throw new Mt(e.type)}}};var Wr={};C(Wr,{DCA_TIME_RESERVE:()=>hn,DEFAULT_BLOCK_TIME:()=>dn,DEFAULT_MIN_BUDGET:()=>Vr,ORDER_MIN_BLOCK_PERIOD:()=>gn,Router:()=>pe,TWAP_EXECUTION_INTERVAL:()=>Qe,TWAP_MAX_DURATION:()=>Ur,TWAP_MAX_PRICE_IMPACT:()=>Gr,TWAP_TX_MULTIPLIER:()=>vg,TradeOrderError:()=>Hr,TradeOrderType:()=>je,TradeRouteBuilder:()=>at,TradeRouter:()=>Ct,TradeScheduler:()=>me,TradeType:()=>Hi});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 xa=10,Xe=class{isNotVisited(t,e){let i=!0;return e.forEach(r=>{(r[0]===t[0]||r[1]===t[1])&&(i=!1)}),i}findPaths(t,e,i){let r=[],s=new $e,n=[];for(n.push([e,""]),s.enqueue(n);s.size()>0;){let a=s.dequeue();if(!a||a.length>xa)continue;let o=a[a.length-1];(i===null||o[0]===i)&&r.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let p=[...a];p.push(u),s.enqueue(p)}})}return r}findShortestPaths(t,e,i){let r=[],s=new $e,n=[];n.push([e,""]),s.enqueue(n);let a=1/0;for(;s.size()>0;){let o=s.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===i){o.length<a?(a=o.length,r.length=0,r.push(o)):o.length===a&&r.push(o);continue}let u=t.get(l[0]);for(let p of u??[])this.isNotVisited(p,o)&&s.enqueue([...o,p])}return r}buildAndPopulateGraph(t,e){let i=new Map;for(let r of t)i.set(parseInt(r),[]);for(let[r,s,n]of e)i.get(s)?.push([n,r]);return i}};function Nr(c){let t={};for(let e of c){let i=e.tokens.length;for(let r=0;r<i;r++){t[e.tokens[r].id]||(t[e.tokens[r].id]=[]);for(let s=0;s<i;s++){if(r==s)continue;let n=[e.address,e.tokens[r].id,e.tokens[s].id];t[e.tokens[r].id].push(n)}}}return t}var Ke=class{getProposals(t,e,i){let r=i.filter(b=>b.type==="XYK"),s=i.filter(b=>b.type!=="XYK"),n=new Set(s.map(b=>b.tokens).flat().map(b=>b.id)),a=n.has(t),o=n.has(e),l=new Xe,u=b=>{let f=Nr(b),y=Object.keys(f),S=y.flatMap(w=>f[w]);return l.buildAndPopulateGraph(y,S)};if(!a&&!o){let b=r.filter(S=>S.tokens.find(w=>w.id===t)||S.tokens.find(w=>w.id===e)),f=u(b),y=l.findPaths(f,t,e);return this.parsePaths(y)}if(a&&o){let b=u(s),f=l.findPaths(b,t,e);return this.parsePaths(f)}let p=a?e:t,d=r.filter(b=>b.tokens.some(f=>f.id===p));if(d.length===0)return[];let m=[...s,...d],h=u(m),g=l.findPaths(h,t,e);return this.parsePaths(g)}parsePaths(t){let e=[];for(let i of t){let r=[];for(let s=0;s<i.length;s++){let n=i[s],a=i[s+1];if(a==null)break;r.push(this.toEdge(n,a))}e.push(r)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var pe=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new Ke,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,i){return`${t}->${e}::${i.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:i=[]}=this.filter,r=new Set(e),s=new Set(i);return t.filter(n=>s.has(n.type)?!1:r.size>0?r.has(n.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let i=await this.getPools();return this.validateInput(t,e,i),this.getPaths(t,e,i)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(r=>r!==t).map(r=>this.getRoutes(r,t)))).filter(r=>r.length>0).map(([r])=>r[0].assetIn).sort()}validateInput(t,e,i){if(i.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let r=this.getAssets(i);if(!r.has(t))throw new Error(t+" is not supported asset");if(!r.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(i)}getAssets(t){let e=t.map(i=>i.tokens.map(r=>r.id)).flat().sort((i,r)=>i>r?1:-1);return new Set(e)}getPaths(t,e,i){let r=this.toPoolsMap(i);return this.getProposals(t,e,i).filter(n=>this.validPath(n,r)).map(n=>this.toHops(n,r))}getProposals(t,e,i){let r=this.buildRouteKey(t,e,i);if(this.routeProposals.has(r))return this.routeProposals.get(r);let s=this.routeSuggester.getProposals(t,e,i);return this.routeProposals.set(r,s),s}validPath(t,e){return t.length>0&&t.map(i=>this.validEdge(i,e)).reduce((i,r)=>i&&r)}validEdge([t,e,i],r){return r.get(t)?.validatePair(e,i)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,ce.get(e)]))}toHops(t,e){return t.map(([i,r,s])=>{let n=e.get(i),a={poolAddress:i,poolId:n?.id,pool:n?.type,assetIn:r,assetOut:s};return n instanceof Gt&&(a.fee=n.fee),a})}};var R=require("@galacticcouncil/common");var Hi=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Hi||{}),je=(i=>(i.Dca="Dca",i.TwapSell="TwapSell",i.TwapBuy="TwapBuy",i))(je||{}),Hr=(i=>(i.OrderTooSmall="OrderTooSmall",i.OrderTooBig="OrderTooBig",i.OrderImpactTooBig="OrderImpactTooBig",i))(Hr||{});var{FeeUtils:mn}=O,Ct=class extends pe{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,i){let r=super.validateInput(t,e,i),s=super.getPaths(t,e,i);if(!s.length)throw new ve(t,e);return{paths:s,pools:i,poolsMap:r}}async withCtx(t,e,i){let r=await super.getPools(),s=this.buildCtxSync(t,e,r);return i(s)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((i,r)=>{let s=i[i.length-1].amountOut,n=r[r.length-1].amountOut;return s>n?-1:1});return e.find(i=>i.every(r=>r.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(i=>i.tradeFeeRange).length>0){let i=t.map(s=>s.tradeFeeRange?.[0]??s.tradeFeePct).reduce((s,n)=>s+n),r=t.map(s=>s.tradeFeeRange?.[1]??s.tradeFeePct).reduce((s,n)=>s+n);return[i,r]}}getPoolFeeRange(t,e){let i=t.min?mn.toPct(t.min):void 0,r=t.max?mn.toPct(t.max):void 0;if(i&&r)return[i,Math.max(r,e)]}async getBestSell(t,e,i){return this.getSell(t,e,i)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,i,r){return this.withCtx(t,e,async({paths:s,poolsMap:n})=>{let a;if(r)a=await this.toSellSwaps(i,r,n);else{let o=s.map(u=>this.toSellSwaps(i,u,n)),l=await Promise.all(o);a=this.findBestSellRoute(l)}return this.buildSell(n,a)})}async getSells(t,e,i){return this.withCtx(t,e,async({paths:r,poolsMap:s})=>{let n=r.map(o=>this.toSellSwaps(i,o,s));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(s,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let i=e[0],r=e[e.length-1],s=this.isDirectTrade(e),n=this.getSellSpot(e),a=r.amountOut,o=s?r.calculatedOut:this.calculateDelta0Y(i.amountIn,e,t),l=o-a,u=this.getRouteFeeRange(e),p=s?r.tradeFeePct:U.calculateSellFee(o,a),d=M.mulSpot(i.amountIn,n,i.assetInDecimals,r.assetOutDecimals),m=U.calculateDiffToRef(o,d);return{type:"Sell",amountIn:i.amountIn,amountOut:r.amountOut,spotPrice:n,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Sell",amountIn:R.big.toDecimal(i.amountIn,i.assetInDecimals),amountOut:R.big.toDecimal(r.amountOut,r.assetOutDecimals),spotPrice:R.big.toDecimal(n,R.RUNTIME_DECIMALS),tradeFee:R.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(R.RUNTIME_DECIMALS))}calculateDelta0Y(t,e,i){let r=[];for(let s=0;s<e.length;s++){let n=e[s],a=i.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;s>0?l=r[s-1]:l=t;let u=a.calculateOutGivenIn(o,l);r.push(u)}return r[r.length-1]}async calculateMostLiquidRoute(t,e,i){let{paths:r,pools:s,poolsMap:n}=i,l=s.filter(g=>g.tokens.some(b=>b.id===t)).map(g=>g.type==="Aave"?g.tokens:g.tokens.filter(b=>b.id===t)).map(g=>g.map(b=>b.balance).reduce((b,f)=>b+f)).sort((g,b)=>b<g?-1:1)[0],u=M.getFraction(l,.1),p=await Promise.all(r.map(g=>this.toSellSwaps(u,g,n))),m=this.findBestSellRoute(p).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut})),h=this.buildRouteKey(t,e,s);return this.mlr.set(h,m),m}async toSellSwaps(t,e,i){let r=[];for(let s=0;s<e.length;s++){let n=e[s],a=i.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;s>0?l=r[s-1].amountOut:l=typeof t=="string"?R.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),g=this.getPoolFeeRange(u,m),b=a.spotPriceOutGivenIn(o),f=M.mulSpot(l,b,o.decimalsIn,o.decimalsOut),y=U.calculateDiffToRef(d,f);r.push({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:d,spotPrice:b,tradeFeePct:m,tradeFeeRange:g,priceImpactPct:y,errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===n.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:R.big.toDecimal(l,o.decimalsIn),amountOut:R.big.toDecimal(p,o.decimalsOut),calculatedOut:R.big.toDecimal(d,o.decimalsOut),spotPrice:R.big.toDecimal(b,R.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:g,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),s=this.mlr.get(r);return s||this.calculateMostLiquidRoute(t,e,i)})}async getSpotPrice(t,e){return this.withCtx(t,e,async i=>{let{pools:r,poolsMap:s}=i,n=this.buildRouteKey(t,e,r),a=this.mlr.get(n);a||(a=await this.calculateMostLiquidRoute(t,e,i));let o=await this.toSellSwaps("1",a,s);return{amount:this.getSellSpot(o),decimals:R.RUNTIME_DECIMALS}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((i,r)=>{let s=i[0].amountIn,n=r[0].amountIn;return s>n?1:-1});return e.find(i=>i.every(r=>r.errors.length==0))||e[0]}async getBestBuy(t,e,i){return this.getBuy(t,e,i)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,i,r){return this.withCtx(t,e,async({paths:s,poolsMap:n})=>{let a;if(r)a=await this.toBuySwaps(i,r,n);else{let o=s.map(u=>this.toBuySwaps(i,u,n)),l=await Promise.all(o);a=this.findBestBuyRoute(l)}return this.buildBuy(n,a)})}async getBuys(t,e,i){return this.withCtx(t,e,async({paths:r,poolsMap:s})=>{let n=r.map(o=>this.toBuySwaps(i,o,s));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(s,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let i=e[e.length-1],r=e[0],s=this.isDirectTrade(e),n=this.getBuySpot(e),a=r.amountIn,o=s?r.calculatedIn:this.calculateDelta0X(i.amountOut,e,t),l=a-o,u=this.getRouteFeeRange(e),p=s?r.tradeFeePct:U.calculateBuyFee(o,a),d=M.mulSpot(i.amountOut,n,i.assetOutDecimals,r.assetInDecimals),m;return o===0n?m=-100:m=U.calculateDiffToRef(d,o),{type:"Buy",amountOut:i.amountOut,amountIn:r.amountIn,spotPrice:n,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e,toHuman(){return{type:"Buy",amountOut:R.big.toDecimal(i.amountOut,i.assetOutDecimals),amountIn:R.big.toDecimal(r.amountIn,r.assetInDecimals),spotPrice:R.big.toDecimal(n,R.RUNTIME_DECIMALS),tradeFee:R.big.toDecimal(l,r.assetInDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:m,swaps:e.map(h=>h.toHuman())}}}}calculateDelta0X(t,e,i){let r=[];for(let s=e.length-1;s>=0;s--){let n=e[s],a=i.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;s==e.length-1?l=t:l=r[0];let u=a.calculateInGivenOut(o,l);r.unshift(u)}return r[0]}async toBuySwaps(t,e,i){let r=[];for(let s=e.length-1;s>=0;s--){let n=e[s],a=i.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;s==e.length-1?l=typeof t=="string"?R.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),g=this.getPoolFeeRange(u,m),b=a.spotPriceInGivenOut(o),f=M.mulSpot(l,b,o.decimalsOut,o.decimalsIn),y;d===0n?y=-100:y=U.calculateDiffToRef(f,d),r.unshift({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:d,spotPrice:b,tradeFeePct:m,tradeFeeRange:g,priceImpactPct:y,errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===n.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===n.assetIn},toHuman(){return{...n,amountOut:R.big.toDecimal(l,o.decimalsOut),amountIn:R.big.toDecimal(p,o.decimalsIn),calculatedIn:R.big.toDecimal(d,o.decimalsIn),spotPrice:R.big.toDecimal(b,R.RUNTIME_DECIMALS),tradeFeePct:m,tradeFeeRange:g,priceImpactPct:y,errors:h}}})}return r}};var L=require("@galacticcouncil/common");var dn=6e3,Vr=1000000000000000n,Qe=6,Gr=-5,Ur=216e5,vg=3,hn=.1,gn=6;var Vi=require("polkadot-api");var at=class{static build(t){return t.map(({assetIn:e,assetOut:i,pool:r,poolId:s,fee:n})=>r==="Stableswap"?{pool:(0,Vi.Enum)("Stableswap",s),asset_in:e,asset_out:i}:r==="UniswapV3"?{pool:(0,Vi.Enum)("UniswapV3",n),asset_in:e,asset_out:i}:{pool:(0,Vi.Enum)(r),asset_in:e,asset_out:i})}};var me=class{schedulerOptions;router;constructor(t,e={}){this.router=new Ct(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Vr})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,i,r,s){let n=await this.router.getBestSell(t,e,i),{amountIn:a,swaps:o,priceImpactPct:l}=n,u=o[0],p=o[o.length-1],{assetInDecimals:d}=u,{assetOutDecimals:m}=p,h=Math.abs(l),g=await this.getMinimumOrderBudget(t,d),b=this.getOptimalTradeCount(h),f=this.getMaximumTradeCount(a,g,r),y=s||Math.min(b,f),S=Math.round(r/y),w=a/BigInt(y),v=await this.router.getBestSell(t,e,w),I=a<g,_=[];I&&_.push("OrderTooSmall");let et=await this.getAssetOutEd(p),$=v.amountOut*BigInt(y),Pt=this.toBlockPeriod(S),it=v.tradeFee*BigInt(y),pt=at.build(o),_t={assetIn:t,assetOut:e,assetOutEd:et,errors:_,maxTradeCount:f,tradeCount:y,tradeFee:it,tradeImpactPct:v.priceImpactPct,tradePeriod:Pt,tradeRoute:pt,type:"Dca"};return{..._t,amountIn:a,amountOut:$,tradeAmountIn:v.amountIn,tradeAmountOut:v.amountOut,toHuman(){return{..._t,amountIn:L.big.toDecimal(a,d),amountOut:L.big.toDecimal($,m),assetOutEd:L.big.toDecimal(et,m),tradeAmountIn:L.big.toDecimal(v.amountIn,d),tradeAmountOut:L.big.toDecimal(v.amountOut,m)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let i=await this.router.getSpotPrice(0,t);if(i)return M.mulSpot(this.minOrderBudget,i.amount,12,e);let r=await this.router.getSpotPrice(t,0);if(r)return M.divSpot(this.minOrderBudget,r.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,i){let r=e*2n/10n;if(r===0n)return 0;let s=Number(t/r),n=Math.floor(i/this.blockTime),a=Math.max(0,Math.floor(n*(1-.1)));return Math.min(s,a)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,i,r){let s=await this.router.getBestSell(t,e,i),{swaps:n}=s,a=n[0],o=n[n.length-1],{assetInDecimals:l}=a,{assetOutDecimals:u}=o,p=await this.getMinimumOrderBudget(t,l),d=s.amountIn<p,m=[];d&&m.push("OrderTooSmall");let h=await this.getAssetOutEd(o),g=this.toBlockPeriod(r),b=at.build(n),f={assetIn:t,assetOut:e,assetOutEd:h,errors:m,maxTradeCount:0,tradeCount:0,tradeFee:s.tradeFee,tradeImpactPct:s.priceImpactPct,tradePeriod:g,tradeRoute:b,type:"Dca"};return{...f,amountIn:0n,amountOut:0n,tradeAmountIn:s.amountIn,tradeAmountOut:s.amountOut,toHuman(){return{...f,amountIn:"0",amountOut:"0",assetOutEd:L.big.toDecimal(h,u),tradeAmountIn:L.big.toDecimal(s.amountIn,l),tradeAmountOut:L.big.toDecimal(s.amountOut,u)}}}}async getTwapSellOrder(t,e,i){let r=await this.router.getBestSell(t,e,i),{amountIn:s,swaps:n,priceImpactPct:a}=r,o=n[0],l=n[n.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),h=s/BigInt(m),[g,b]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestSell(o.assetIn,l.assetOut,h)]),f=m===1,y=s<g,S=b.priceImpactPct<-5,w=[];y||f?w.push("OrderTooSmall"):S&&w.push("OrderImpactTooBig");let v=await this.getAssetOutEd(l),I=b.amountOut*BigInt(m),_=b.tradeFee*BigInt(m),et=at.build(n),$={assetIn:t,assetOut:e,assetOutEd:v,errors:w,tradeCount:m,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:et,type:"TwapSell"};return{...$,amountIn:s,amountOut:I,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:_,toHuman(){return{...$,amountIn:L.big.toDecimal(s,u),amountOut:L.big.toDecimal(I,p),assetOutEd:L.big.toDecimal(v,p),tradeAmountIn:L.big.toDecimal(b.amountIn,u),tradeAmountOut:L.big.toDecimal(b.amountOut,p),tradeFee:L.big.toDecimal(_,p)}}}}async getTwapBuyOrder(t,e,i){let r=await this.router.getBestBuy(t,e,i),{amountOut:s,swaps:n,priceImpactPct:a}=r,o=n[0],l=n[n.length-1],{assetInDecimals:u}=o,{assetOutDecimals:p}=l,d=Math.abs(a),m=this.getTwapTradeCount(d),h=s/BigInt(m),[g,b]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestBuy(o.assetIn,l.assetOut,h)]),f=b.amountIn*BigInt(m),y=m===1,S=f<g,w=b.priceImpactPct<-5,v=[];S||y?v.push("OrderTooSmall"):w&&v.push("OrderImpactTooBig");let I=await this.getAssetOutEd(l),_=b.tradeFee*BigInt(m),et=at.build(n),$={assetIn:t,assetOut:e,assetOutEd:I,errors:v,tradeCount:m,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:et,type:"TwapBuy"};return{...$,amountIn:f,amountOut:s,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:_,toHuman(){return{...$,amountIn:L.big.toDecimal(f,u),amountOut:L.big.toDecimal(s,p),assetOutEd:L.big.toDecimal(I,p),tradeAmountIn:L.big.toDecimal(b.amountIn,u),tradeAmountOut:L.big.toDecimal(b.amountOut,p),tradeFee:L.big.toDecimal(_,u)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let r=216e5/(this.blockTime*6);return Math.round(r)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,i=Math.round(e);return Math.max(i,6)}async getAssetOutEd(t){let r=(await this.router.getPools()).find(s=>s.address===t.poolAddress)?.tokens.find(s=>s.id===t.assetOut);if(!r)throw new Error(`Asset ${t.assetOut} not found in pool ${t.poolAddress}`);return r.existentialDeposit}};var $r={};C($r,{BIG_10:()=>Sn,BIG_BILL:()=>Yr,StakingApi:()=>Je,StakingClient:()=>Ze});var tt=require("@galacticcouncil/math-staking"),ot=St(require("big.js"));var Gi={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},bn=c=>Object.keys(Gi).includes(c);var fn=require("polkadot-api"),yn=require("@polkadot-api/utils"),Pn=require("@galacticcouncil/common");function wn(c){let t=("modl"+c).padEnd(32,"\0"),e=new TextEncoder().encode(t),i=(0,yn.toHex)(e);return(0,fn.AccountId)(Pn.HYDRATION_SS58_PREFIX).dec(i)}var Ui="20000000000000000",Wi="2000",Sn=(0,ot.default)(10),Yr=(0,ot.default)(Sn.pow(12)),Je=class{client;balance;constructor(t,e){this.client=t,this.balance=e}async getPotBalance(){let t=await this.client.getPalletId(),e=wn(t);return await this.balance.getBalance(e,0)}async getStakingPosition(t){let[e,i]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let r=e.created_at,s=await i.reduce(async(n,[a,o])=>{let l=await n,u=a,p=o.amount,d=o.conviction.type.toLowerCase(),m=await this.client.getReferendumInfo(u);return m&&(m.type==="Approved"||m.type==="Rejected")&&bn(d)&&l.push({id:u,amount:p,conviction:d}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:r,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:s}}async getStake(t){let e=await this.client.getNFTCollectionId(),[i,r]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),s=r.find(n=>n)?.itemId;return{totalStake:i?.total_stake,accumulatedRewardPerStake:i?.accumulated_reward_per_stake,potReservedBalance:i?.pot_reserved_balance,positionId:s,stakePosition:s?await this.getStakingPosition(s):void 0}}getCurrentActionPoints(t,e,i,r){let s=(0,ot.default)(0),n=(0,ot.default)(0),a=Gi.locked6x,o=(0,ot.default)(i.toString()).mul(a),l=100,u=[];t.forEach(m=>{let h=Gi[m.conviction],g=r.includes(m.id.toString());g&&u.push(m.id.toString());let b=(0,ot.default)(m.amount.toString()).mul(l).div(o);s=s.plus(Math.floor(b.mul(h).toNumber())),n=n.plus(Math.floor(b.mul(g?a:h).toNumber()))});let p=Math.floor((0,ot.default)(i.toString()).mul(a).mul(l).div(o).toNumber());r.forEach(m=>{u.includes(m)||(n=n.plus(p))});let d={democracyVote:1};return s=s.mul(d.democracyVote),s=s.plus(e.toString()||"0"),n=n.mul(d.democracyVote),n=n.plus(e.toString()||"0"),{currentActionPoints:s.toString(),maxActionPoints:n.toString()}}async getRewards(t,e,i){let r=await this.getStake(t),{potReservedBalance:s,accumulatedRewardPerStake:n,totalStake:a,stakePosition:o}=r;if(!o)return;let[l,u,p,d,m,h,g]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),b=(0,ot.default)(l.transferable.toString()).minus(s.toString()),f=b.gt(0)&&a>0?(0,tt.calculate_accumulated_rps)(n.toString(),b.toString(),a.toString()):n.toString(),y=(0,tt.calculate_period_number)(u.toString(),i,g),S=(0,tt.calculate_period_number)(u.toString(),o.createdAt.toString(),g),w=(0,tt.calculate_rewards)(f,o.rewardPerStake.toString(),o.stake.toString()),v=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),I=(0,tt.calculate_points)(S,y,d.toString(),m.toString(),v.currentActionPoints,h.toString(),o.accumulatedSlashPoints.toString()),_=(0,tt.sigmoid)(I,Ui,Wi),et=(()=>{if(!e.length)return;let _t=(0,tt.calculate_points)(S,y,d.toString(),m.toString(),v.maxActionPoints.toString(),h.toString(),o.accumulatedSlashPoints.toString());return(0,tt.sigmoid)(_t,Ui,Wi)})(),$=(0,ot.default)(w).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if((0,ot.default)(y).minus(S).lte(p.toString()))return{rewards:"0",payablePercentage:_,extraPayablePercentage:et,constants:{a:Ui,b:Wi}};let Pt=(0,tt.calculate_percentage_amount)($.toString(),_),it=(0,ot.default)(o.accumulatedLockedRewards.toString()),pt=it.gt(Pt)?it:(0,ot.default)(Pt);return{rewards:pt.div(Yr).toString(),maxRewards:$.div(Yr).toString(),allocatedRewardsPercentage:pt.div($).mul(100).toNumber(),points:I,payablePercentage:_,extraPayablePercentage:et,constants:{a:Ui,b:Wi}}}};var zr=require("polkadot-api");var Ze=class extends V{async getPalletId(){let t=this.api.constants.Staking.PalletId,e=await t();return zr.Binary.toText(zr.Binary.fromHex(e))}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:n})=>{let[a,o,l]=n;return{address:a,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var jr={};C(jr,{TxBuilderFactory:()=>de});var Xr=require("polkadot-api");function vn(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var ut=class extends V{evm;evmClient;balance;aaveUtils;constructor(t,e,i){super(t,i),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new ht(t,i),this.aaveUtils=new Ft(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:ir})}async dryRun(t,e){let i=(0,Xr.Enum)("Signed",t),r=(0,Xr.Enum)("system",i),n=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(r,e.decodedCall,4,{at:this.at}),a=n.success&&!n.value.execution_result.success?n.value.execution_result.value.error:null;if(a){let o=a.type==="Module"?vn(a.value):a.type;throw new Error("Dry run execution error!",{cause:o})}return n}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var Yi=class extends ut{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:i}=this.trade;if(i==="Buy")return this.buildBuyTx();let{assetIn:r}=e[0],s=await this.balance.getBalance(this.beneficiary,r);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,r=i[0],s=i[i.length-1],n=M.getFraction(t,this.slippagePct),a=r.assetIn,o=s.assetOut,l=t+n,u;return this.isDirectOmnipoolTrade(i)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:at.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,r=i[0],s=i[i.length-1],n=M.getFraction(e,this.slippagePct),a=r.assetIn,o=s.assetOut,l=e-n,u;return this.isDirectOmnipoolTrade(i)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:at.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,i=e[0],r=e[e.length-1],s=M.getFraction(t,this.slippagePct),n=i.assetIn,a=r.assetOut,o=t-s,l=this.api.tx.Router.sell_all({asset_in:n,asset_out:a,min_amount_out:o,route:at.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var zi=require("polkadot-api");var $i=class extends ut{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradePeriod:s,tradeRoute:n}=this.order,a=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,zi.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:r,min_amount_out:0n,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(a=await this.dispatchWithExtraGas(a)),this.wrapTx("DcaSchedule",a)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradeAmountOut:s,tradePeriod:n,tradeRoute:a}=this.order,o=M.getFraction(s,this.slippagePct),l=s-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,zi.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:r,min_amount_out:l,route:a})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("DcaSchedule.twapSell",u)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradeAmountOut:s,tradePeriod:n,tradeRoute:a}=this.order,o=M.getFraction(r,this.slippagePct),l=r+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,zi.Enum)("Buy",{asset_in:e,asset_out:i,amount_out:s,max_amount_in:l,route:a})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("DcaSchedule.twapBuy",u)}};var xn=require("polkadot-api");var Xi=class extends ut{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,r=i[0],s=i[i.length-1],n=r.assetIn,a=s.assetOut,o=M.getFraction(e,this.slippagePct),l=e-o,u=(0,xn.Enum)("Swap",{asset_in:n,asset_out:a,amount_in:t,amount_out:l,partial:!1}),p=this.apiIce.tx.Intent.submit_intent({intent:{data:u}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(p=await this.dispatchWithExtraGas(p)),this.wrapTx("IntentSwap",p)}};var Tn=require("polkadot-api");var Ki=class extends ut{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,r=i[0],s=i[i.length-1],n=r.assetIn,a=s.assetOut,o=(0,Tn.Enum)("Swap",{asset_in:n,asset_out:a,amount_in:t,amount_out:this.minAmountOut??e,partial:this.partial}),l=this.apiIce.tx.Intent.submit_intent({intent:{data:o,deadline:this.deadline}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("IntentLimitOrder",l)}};var Kr=require("polkadot-api");var ji=class extends ut{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:i,assetOutEd:r,tradeAmountIn:s,tradePeriod:n}=this.order,a=(0,Kr.Enum)("Dca",{asset_in:e,asset_out:i,amount_in:s,amount_out:r,slippage:this.slippagePct*1e4,budget:t,period:n}),o=this.apiIce.tx.Intent.submit_intent({intent:{data:a}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("IntentDcaSchedule",o)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:r,tradeAmountOut:s,tradePeriod:n}=this.order,a=M.getFraction(s,this.slippagePct),o=s-a,l=(0,Kr.Enum)("Dca",{asset_in:e,asset_out:i,amount_in:r,amount_out:o,slippage:this.slippagePct*1e4,budget:t,period:n}),u=this.apiIce.tx.Intent.submit_intent({intent:{data:l}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("IntentDcaSchedule.twap",u)}};var de=class{client;evmClient;at;constructor(t,e,i){this.client=t,this.evmClient=e,this.at=i}trade(t){return new Yi(this.client,this.evmClient,this.at).setTrade(t)}order(t){return new $i(this.client,this.evmClient,this.at).setOrder(t)}intentMarket(t){return new Xi(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new Ki(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new ji(this.client,this.evmClient).setOrder(t)}};async function Ta(c,t){let{at:e}=t??{},i=new Qt(c),r=new Te(c,e),[s,n]=await Promise.all([i.getBlockTime(),i.getMinOrderBudget()]),a=new ue(c,r,e).withAave().withOmnipool().withStableswap().withXyk().withV3(),o=new ht(c,e),l=new Ze(c),u=new Be(c),p=new Ft(r),d=new Ct(a),m=new me(a,{blockTime:s,minBudgetInNative:n}),h=new Je(l,o),g=new _e(u,o,{blockTime:s});return{api:{aave:p,router:d,scheduler:m,staking:h,farm:g},client:{asset:new $t(c),balance:o,evm:r},ctx:{pool:a},tx:new de(c,r,e),destroy:()=>{a.destroy()}}}0&&(module.exports={QueryBus,aave,api,async,calc,client,const:null,createSdkContext,error,evm,farm,fmt,indexer,json,math,pool,sor,staking,tx});
|