@galacticcouncil/sdk-next 0.8.0 → 0.9.0

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