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