@galacticcouncil/sdk-next 0.6.0-pr192-1d1a581 → 0.6.0-pr193-99644e4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var hn=Object.create;var Ue=Object.defineProperty;var Pn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var Tn=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var Ht=(c,e)=>()=>(c&&(e=c(c=0)),e);var I=(c,e)=>{for(var t in e)Ue(c,t,{get:e[t],enumerable:!0})},Ge=(c,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fn(e))!xn.call(c,s)&&s!==t&&Ue(c,s,{get:()=>e[s],enumerable:!(n=Pn(e,s))||n.enumerable});return c},ae=(c,e,t)=>(Ge(c,e,"default"),t&&Ge(t,e,"default")),st=(c,e,t)=>(t=c!=null?hn(Tn(c)):{},Ge(e||!c||!c.__esModule?Ue(t,"default",{value:c,enumerable:!0}):t,c)),Sn=c=>Ge(Ue({},"__esModule",{value:!0}),c);var Te={};var Wt=Ht(()=>{ae(Te,require("@polkadot-api/ws-provider/node"))});var xe={};var Vt=Ht(()=>{ae(xe,require("@polkadot-api/ws-provider/web"))});var Jn={};I(Jn,{aave:()=>Tt,api:()=>rt,big:()=>y,client:()=>xt,const:()=>gt,createSdkContext:()=>Qn,erc20:()=>ee,error:()=>wt,evm:()=>ut,fmt:()=>h,h160:()=>we,json:()=>Z,math:()=>A,pool:()=>_t,sor:()=>Mt,tx:()=>qt,xc:()=>Pt});module.exports=Sn(Jn);var rt={};I(rt,{Papi:()=>M,getWs:()=>wn});var Ut=require("@galacticcouncil/descriptors");function Gt(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var M=class{client;api;constructor(e){this.client=e,this.api=this.client.getTypedApi(Ut.hydration)}log(e,...t){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Gt(n)&&console.log(e,...t)}};var Xt=require("polkadot-api"),Yt=require("polkadot-api/polkadot-sdk-compat"),wn=async c=>{let e=typeof c=="string"?c.split(","):c,s=(typeof window>"u"?(await Promise.resolve().then(()=>(Wt(),Te))).getWsProvider:(await Promise.resolve().then(()=>(Vt(),xe))).getWsProvider)(e);return(0,Xt.createClient)((0,Yt.withPolkadotSdkCompat)(s))};var Tt={};I(Tt,{AAVE_GAS_LIMIT:()=>ot,AAVE_LENDING_POOL_ADDRESS:()=>Xe,AAVE_POOL_ABI:()=>at,AAVE_POOL_DATA_PROVIDER:()=>Ve,AAVE_POOL_DATA_PROVIDER_ABI:()=>We,AAVE_POOL_PROXY:()=>it,AAVE_ROUNDING_THRESHOLD:()=>gs,AAVE_UINT_256_MAX:()=>In,AaveClient:()=>Se,AaveUtils:()=>te});var at=[{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 We=[{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 it="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ve="0x112b087b60C1a166130d59266363C45F8aa99db0",Xe="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ot=1000000n,gs=5,In=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ut={};I(ut,{EvmClient:()=>L,evmMainnet:()=>lt});var Kt=require("viem"),jt=["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"],zt=["wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],lt=(0,Kt.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:jt,webSocket:zt},default:{http:jt,webSocket:zt}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var G=require("viem");var L=class{chain;constructor(e){this.chain=e||lt}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}async getGasPrice(){return this.getProvider().getGasPrice()}getProvider(){return(0,G.createPublicClient)({chain:this.chain,transport:(0,G.http)()})}getWsProvider(){return(0,G.createPublicClient)({chain:this.chain,transport:(0,G.webSocket)()})}getSigner(e){return(0,G.createWalletClient)({account:e,chain:this.chain,transport:(0,G.custom)(window.ethereum)})}};var Se=class{evmClient;constructor(e){this.evmClient=e??new L}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:We,address:Ve,args:[Xe],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:We,address:Ve,args:[Xe,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:at,address:it,args:[e],functionName:"getUserAccountData"})}};var y={};I(y,{asBigInt:()=>An,toBigInt:()=>vn,toDecimal:()=>On});var J=st(require("big.js"));J.default.NE=-18;function On(c,e,t=6,n){let s=(0,J.default)(c.toString()),r=(0,J.default)(10).pow(e);return s.div(r).round(t,n).toString()}function vn(c,e){let t=(0,J.default)(10).pow(e),s=(0,J.default)(c).mul(t).toFixed(0,J.default.roundDown);return BigInt(s)}function An(c){return BigInt(c.round(0,J.default.roundDown).toFixed(0))}var ee={};I(ee,{ERC20:()=>ct});var ct=class{static fromAssetId(e){let t=Buffer.alloc(20,0);return t[15]=1,t.writeUInt32BE(e,16),"0x"+t.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(e.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(t.subarray(0,16))}};var h={};I(h,{fromPermill:()=>Rn,toDecimals:()=>_n,toPct:()=>Bn});var $t=1e3;function Bn(c){let[e,t]=c;return e/t*100}function _n(c){let[e,t]=c;return e/t}function Rn(c){return[c/$t,$t]}var we={};I(we,{H160:()=>ht,isEvmAccount:()=>Qt,isEvmAddress:()=>Jt,isSs58Address:()=>Zt});var oe=require("polkadot-api"),bt=require("@polkadot-api/utils"),K=require("buffer");var gt={};I(gt,{HUB_ASSET_ID:()=>dt,HYDRATION_OMNIPOOL_ADDRESS:()=>Dn,HYDRATION_PARACHAIN_ID:()=>En,HYDRATION_SS58_PREFIX:()=>W,PERBILL_DENOMINATOR:()=>Fn,PERMILL_DENOMINATOR:()=>pt,RUNTIME_DECIMALS:()=>q,SYSTEM_ASSET_DECIMALS:()=>mt,SYSTEM_ASSET_ID:()=>z,TRADEABLE_DEFAULT:()=>ie});var q=18,pt=1e6,Fn=1e9,z=0,mt=12,En=2034,W=63,Dn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",dt=1,ie=15;var yt="ETH\0";function Qt(c){if(!c)return!1;try{let e=(0,oe.AccountId)().enc(c),t=K.Buffer.from(yt);return K.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Jt(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function Zt(c){try{return(0,oe.AccountId)(63).enc(c),!0}catch{return!1}}var ht=class c{static toAccount=e=>{let t=K.Buffer.from(e.slice(2),"hex"),n=K.Buffer.from(yt),s=Uint8Array.from(K.Buffer.concat([n,t,K.Buffer.alloc(8)])),r=(0,bt.toHex)(s);return(0,oe.AccountId)(63).dec(r)};static fromAccount=e=>{let t=(0,oe.AccountId)().enc(e),n=K.Buffer.from(yt),s=t.slice(n.length,-8);return"0x"+K.Buffer.from(s).toString("hex")};static fromSS58=e=>{let n=(0,oe.AccountId)().enc(e).slice(0,20);return(0,bt.toHex)(n)};static fromAny=e=>{if(Jt(e))return e;if(Qt(e))return c.fromAccount(e);if(Zt(e))return c.fromSS58(e);throw new Error("Unknown address type")}};var Z={};I(Z,{findNestedKey:()=>kn,findNestedObj:()=>Cn,jsonFormatter:()=>Mn});var kn=(c,e)=>{let t=[];return JSON.stringify(c,(n,s)=>(s&&s[e]&&t.push(s),s)),t[0]},Cn=(c,e,t)=>{let n;return JSON.stringify(c,(s,r)=>(r&&r[e]===t&&(n=r),r)),n},Mn=(c,e)=>typeof e=="bigint"?e.toString():e;var A={};I(A,{calculateBuyFee:()=>Hn,calculateDiffToAvg:()=>Ln,calculateDiffToRef:()=>qn,calculateSellFee:()=>Nn,getFraction:()=>Gn});var V=st(require("big.js"));function Ln(c,e){let t=(0,V.default)(c.toString()),n=(0,V.default)(e.toString());return t.minus(n).abs().div(t.plus(n).div(2)).mul(100).round(2).toNumber()}function qn(c,e){if(e===0n)return 0;let t=(0,V.default)(c.toString()),n=(0,V.default)(e.toString());return t.minus(n).div(n).mul(100).round(2).toNumber()}function Nn(c,e){let t=(0,V.default)(c.toString()),n=(0,V.default)(e.toString());return(0,V.default)(1).minus(n.div(t)).mul(100).round(2).toNumber()}function Hn(c,e){let t=(0,V.default)(c.toString());return(0,V.default)(e.toString()).div(t).minus(1).mul(100).round(2).toNumber()}function Gn(c,e,t=2){(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,t),s=BigInt(e*n);return c*s/BigInt(100*n)}var Pt={};I(Pt,{convertToId:()=>Un});var en=require("buffer");function Un(c){let t=en.Buffer.from(c.replace("0x",""),"hex").subarray(16);return t.readUIntBE(0,t.length)}var{ERC20:Ye}=ee,{H160:ft}=we,Wn=1.01,Vn=99999,Xn=10n**27n,Yn=10n**18n,te=class{client;constructor(e){let t=e??new L;this.client=new Se(t)}async getSummary(e){let t=ft.fromAny(e),[n,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t)]),[i]=n,[a,o]=s,[l,u,d,p,m,g]=r,P=y.toDecimal(g,18),b=[];for(let x of a){let f=x.underlyingAsset.toLowerCase(),T=i.find(({underlyingAsset:nt})=>nt.toLowerCase()===f);if(!T)throw new Error("Missing pool reserve for "+f);let v=x.scaledATokenBalance,F=T.liquidityIndex,k=T.priceInMarketReferenceCurrency,C=v*F/Xn,Ne=Number(o===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,He=T.usageAsCollateralEnabled&&x.usageAsCollateralEnabledOnUser&&x.scaledATokenBalance>0n,tt=Ye.toAssetId(f);b.push({aTokenBalance:C,decimals:Number(T.decimals),isCollateral:He,priceInRef:k,reserveId:tt,reserveAsset:f,reserveLiquidationThreshold:Ne})}return{healthFactor:Number(P),totalCollateral:l,totalDebt:u,reserves:b}}async hasBorrowPositions(e){let t=ft.fromAny(e),n=await this.client.getUserAccountData(t),[s,r]=n;return r>0n}async getHealthFactor(e){let t=ft.fromAny(e),n=await this.client.getUserAccountData(t),[s,r,i,a,o,l]=n,u=y.toDecimal(l,18);return Number(u)}async getHealthFactorAfterWithdraw(e,t,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(e),a=Ye.fromAssetId(t),o=i.find(b=>b.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,isCollateral:u,priceInRef:d,reserveLiquidationThreshold:p}=o,m=y.toBigInt(n,l),g=u?m*d/10n**BigInt(l):0n,P=s-g;return P<=0n?0:this.calculateHealthFactor(P,p,r)}async getHealthFactorAfterSupply(e,t,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(e),a=Ye.fromAssetId(t),o=i.find(P=>P.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:d}=o,m=y.toBigInt(n,l)*u/10n**BigInt(l),g=s+m;return g<=0n?0:this.calculateHealthFactor(g,d,r)}async getMaxWithdraw(e,t){let{totalCollateral:n,totalDebt:s,reserves:r}=await this.getSummary(e),i=Ye.fromAssetId(t),a=r.find(o=>o.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(a,n,s)}async getMaxWithdrawAll(e){let{totalCollateral:t,totalDebt:n,reserves:s}=await this.getSummary(e),r={};for(let i of s){let a=this.calculateWithdrawMax(i,t,n);i.reserveId&&(r[i.reserveId]=a)}return r}calculateHealthFactor(e,t,n){if(n===0n)return Vn;let s=10n**6n,r=y.toBigInt(t,18),i=e*r*s,a=n*Yn,o=i/a;return Number(o)/1e6}calculateRequiredCollateral(e,t,n){let s=y.toBigInt(e,18),r=y.toBigInt(t,18);return(s*n+r-1n)/r}calculateWithdrawMax(e,t,n){let{aTokenBalance:s,decimals:r,priceInRef:i,reserveLiquidationThreshold:a}=e,o=this.calculateRequiredCollateral(Wn,a,n),l=t-o;if(l<=0n)return{amount:0n,decimals:r};let u=l*10n**BigInt(r)/i;return{amount:s<u?s:u,decimals:r}}};var xt={};I(xt,{AssetClient:()=>le,BalanceClient:()=>X,ChainParams:()=>ue});var le=class extends M{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async queryShares(){let t=await this.api.query.Stableswap.Pools.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryBonds(){let t=await this.api.query.Bonds.Bonds.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssets(){let t=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(t.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 t=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async mapToken(e,t,n,s){let{name:r,asset_type:i,is_sufficient:a,existential_deposit:o}=t,{symbol:l,decimals:u}=n.get(e)??{};return{id:e,name:r?.asText(),symbol:l,decimals:u,icon:l,type:i.type,isSufficient:a,location:s,existentialDeposit:o}}async mapBond(e,t,n,s){let[r,i]=s,{asset_type:a,is_sufficient:o,existential_deposit:l}=t,{symbol:u,decimals:d}=await this.mapToken(r,t,n),p=Number(i),m=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",m.format(p)].join(" ");return{id:e,name:g,symbol:u+"b",decimals:d,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:r,maturity:p}}async mapShares(e,t,n,s){let{assets:r}=s,{name:i,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=t,d=await Promise.all(r.map(async g=>{let{symbol:P}=await this.mapToken(g,t,n);return[g,P]})),p=Object.fromEntries(d),m=Object.values(p);return{id:e,name:m.join(", "),symbol:a?.asText()||i?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:p}}async mapExternal(e,t,n,s){let r=await this.mapToken(e,t,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(e){return new Map(Array.from(e,([t,n])=>[t,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(e,t){let[n,s,r,i]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(n),o=[];for(let[l,u]of Array.from(n)){let d=s.get(l),{asset_type:p}=u,m;switch(p.type){case"Bond":let g=i.get(l);m=await this.mapBond(l,u,a,g);break;case"StableSwap":let P=r.get(l);m=await this.mapShares(l,u,a,P);break;case"External":m=await this.mapExternal(l,u,t,d);break;default:m=await this.mapToken(l,u,a,d)}o.push(m)}return e?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};var w=require("rxjs");var X=class extends M{constructor(e){super(e)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getTokenBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:{free:n,frozen:s}}=await t.getValue(e);return n-s}async getTokenBalance(e,t){let n=this.api.query.Tokens.Accounts,{free:s,frozen:r}=await n.getValue(e,t);return s-r}async getErc20Balance(e,t){return this.getTokenBalanceData(e,t)}subscribeBalance(e){let t=this.subscribeSystemBalance(e),n=this.subscribeTokensBalance(e),s=this.subscribeErc20Balance(e);return(0,w.combineLatest)([t,n,s]).pipe((0,w.debounceTime)(250),(0,w.map)(r=>r.flat()),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([r,i],a)=>{if(a===0)return i;let o=r.reduce((u,d)=>(u.set(d.id,d.amount),u),new Map);return i.filter(u=>u.amount!==o.get(u.id))}))}subscribeSystemBalance(e){return this.api.query.System.Account.watchValue(e,"best").pipe((0,w.map)(n=>{let{free:s,frozen:r}=n.data;return{id:0,amount:s-r}}))}subscribeTokenBalance(e,t){return this.api.query.Tokens.Accounts.watchValue(e,t,"best").pipe((0,w.map)(s=>{let{free:r,frozen:i}=s;return{id:t,amount:r-i}}))}subscribeTokensBalance(e){return this.api.query.Tokens.Accounts.watchEntries(e,{at:"best"}).pipe((0,w.distinctUntilChanged)((n,s)=>!s.deltas),(0,w.map)(({deltas:n})=>{let s=[];return n?.deleted.forEach(r=>{let[i,a]=r.args;s.push({id:a,amount:0n})}),n?.upserted.forEach(r=>{let[i,a]=r.args,{free:o,frozen:l}=r.value;s.push({id:a,amount:o-l})}),s}))}subscribeErc20Balance(e,t){let n=new w.Subject,s=n.pipe((0,w.shareReplay)(1)),r=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:u}=l;return u.type==="Erc20"}).map(({keyArgs:l})=>{let[u]=l;return u}),i=async()=>{let o=t||await r(),l=async()=>{let p=(await Promise.all(o.map(async m=>{let g=await this.getTokenBalanceData(e,m);return[m,g]}))).map(([m,g])=>({id:m,amount:g}));n.next(p)};await l();let u=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>u.unsubscribe()},a;return i().then(o=>a=o),s.pipe((0,w.finalize)(()=>a?.()),(0,w.pairwise)(),(0,w.map)(([o,l],u)=>{if(u===0)return l;let d=o.reduce((m,g)=>(m.set(g.id,g.amount),m),new Map);return l.filter(m=>m.amount!==d.get(m.id))}),(0,w.distinctUntilChanged)((o,l)=>l.length===0))}async getTokenBalanceData(e,t){let{free:n,frozen:s}=await this.api.apis.CurrenciesApi.account(t,e);return n-s}};var ue=class extends M{_minOrderBudget;_blockTime;constructor(e){super(e)}async getBlockTime(){if(this._blockTime===void 0){let e=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(e)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var wt={};I(wt,{AssetNotFound:()=>St,PoolNotFound:()=>Ie,RouteNotFound:()=>ce});var St=class extends Error{constructor(e){super(),this.message=`${e} not found`,this.name="AssetNotFound"}},Ie=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},ce=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in current configuration`,this.name="RouteNotFound"}};var _t={};I(_t,{PoolContextProvider:()=>ge,PoolError:()=>ne,PoolFactory:()=>de,PoolType:()=>E,aave:()=>Bt,lbp:()=>It,omni:()=>Ot,stable:()=>vt,xyk:()=>At});var It={};I(It,{LbpMath:()=>U,LbpPool:()=>Oe,LbpPoolClient:()=>ve});var Y=require("@galacticcouncil/math-lbp"),U=class{static getSpotPrice(e,t,n,s,r){return(0,Y.get_spot_price)(e,t,n,s,r)}static calculateInGivenOut(e,t,n,s,r){return(0,Y.calculate_in_given_out)(e,t,n,s,r)}static calculateOutGivenIn(e,t,n,s,r){return(0,Y.calculate_out_given_in)(e,t,n,s,r)}static calculateLinearWeights(e,t,n,s,r){return(0,Y.calculate_linear_weights)(e,t,n,s,r)}static calculatePoolTradeFee(e,t,n){return(0,Y.calculate_pool_trade_fee)(e,t,n)}};var E=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r))(E||{}),ne=(r=>(r.InsufficientTradingAmount="InsufficientTradingAmount",r.MaxInRatioExceeded="MaxInRatioExceeded",r.MaxOutRatioExceeded="MaxOutRatioExceeded",r.TradeNotAllowed="TradeNotAllowed",r.UnknownError="UnknownError",r))(ne||{});var Oe=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,n,s,r,i,a){this.type="LBP",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.fee=i,this.repayFeeApply=a}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,weightIn:s.weight,weightOut:r.weight}}validateAndBuy(e,t,n){let s=this.tokens[0].id,r=[];t<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=e.balanceOut/this.maxOutRatio;if(t>i&&r.push("MaxOutRatioExceeded"),s===e.assetOut){let a=this.calculateTradeFee(t,n),o=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=t+a,u=this.calculateInGivenOut(e,l),d=e.balanceIn/this.maxInRatio;return u>d&&r.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:t,feePct:o,errors:r}}else{let a=this.calculateInGivenOut(e,t),o=e.balanceIn/this.maxInRatio;return a>o&&r.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:t,feePct:0,errors:r}}}validateAndSell(e,t,n){let s=this.tokens[0].id,r=[];t<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=e.balanceIn/this.maxInRatio;if(t>i&&r.push("MaxInRatioExceeded"),s===e.assetIn){let a=this.calculateOutGivenIn(e,t),o=e.balanceOut/this.maxOutRatio;return a>o&&r.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:a,feePct:0,errors:r}}else{let a=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(a,n),l=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),u=a-o,d=e.balanceOut/this.maxOutRatio;return u>d&&r.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:u,feePct:l,errors:r}}}calculateInGivenOut(e,t){let n=U.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(e,t){let n=U.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(e){let t=U.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),this.maxOutRatio.toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=U.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),this.maxInRatio.toString());return BigInt(t)}calculateTradeFee(e,t){let n=U.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return BigInt(n)}};var nn=require("polkadot-api"),se=require("rxjs");var tn=(c,e=new Map)=>t=>{let n;return e.has(t)?e.get(t):(e.set(t,n=c(t)),n)};var O=require("rxjs");var N=class extends X{override=[];mem=0;memPools=tn(e=>(this.log(this.getPoolType(),"mem pools",e,"\u2705"),this.loadPools()));constructor(e){super(e)}async withOverride(e){this.override=e||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let e=(0,O.from)(this.getPoolsMem()).pipe((0,O.switchMap)(t=>this.subscribe(t)),(0,O.combineLatestAll)());return(0,O.firstValueFrom)(e)}getSubscriber(){return(0,O.from)(this.getPoolsMem()).pipe((0,O.switchMap)(e=>this.subscribe(e)),(0,O.mergeAll)())}subscribe(e){return e.filter(t=>this.hasValidAssets(t)).map(t=>(0,O.combineLatest)([this.subscribePoolChange(t),this.subscribePoolBalance(t)]).pipe((0,O.debounceTime)(250),(0,O.map)(([n,s])=>this.updatePool(n,s))))}subscribePoolBalance(e){if(e.type==="Aave")return(0,O.of)([]);let t=[this.subscribeTokensBalance(e.address)];if(this.hasSystemAsset(e)){let n=this.subscribeSystemBalance(e.address);t.push(n)}if(this.hasErc20Asset(e)){let n=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),s=this.subscribeErc20Balance(e.address,n);t.push(s)}return(0,O.combineLatest)(t).pipe((0,O.map)(n=>n.map(s=>Array.isArray(s)?s:[s]).flat()))}hasSystemAsset(e){return e.tokens.some(t=>t.id===0)}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}hasValidAssets(e){return e.tokens.every(({id:t,decimals:n,balance:s})=>{let r=this.override.find(a=>a.id===t),i=!!n||!!r?.decimals;return s>0n&&i})}updatePool=(e,t)=>{let n=e.tokens.map(s=>{let r=t.find(a=>a.id===s.id),i=this.override.find(a=>a.id===s.id);return r?{...s,balance:r.amount,decimals:s.decimals||i?.decimals}:{...s,decimals:s.decimals||i?.decimals}});return{...e,tokens:n}}};var ve=class extends N{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[e,t,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),s=t?.relay_parent_number||0,r=e.filter(({value:i})=>t&&this.isActivePool(i,s)).map(async({keyArgs:i,value:a})=>{let[o]=i,l=o.toString(),u=await this.getPoolDelta(l,a,s);return{address:l,type:"LBP",fee:a.fee,...u,...n}});return Promise.all(r)}async getPoolDelta(e,t,n){let{start:s,end:r,assets:i,initial_weight:a,final_weight:o,repay_target:l,fee_collector:u}=t,d=U.calculateLinearWeights(s?s.toString():"0",r?r.toString():"0",a.toString(),o.toString(),n.toString()),[p,m]=i,g=BigInt(d),P=this.MAX_FINAL_WEIGHT-BigInt(g),[b,x,f,T,v]=await Promise.all([this.isRepayFeeApplied(p,l,u.toString()),this.getBalance(e,p),this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(e,m),this.api.query.AssetRegistry.Assets.getValue(m)]);return{repayFeeApply:b,tokens:[{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:x,weight:g,type:f?.asset_type.type},{id:m,decimals:v?.decimals,existentialDeposit:v?.existential_deposit,balance:T,weight:P,type:v?.asset_type.type}]}}isActivePool(e,t){let{start:n,end:s}=e;return n&&s?t>=n&&t<s:!1}async isRepayFeeApplied(e,t,n){if(t===0n)return!1;try{return await this.getBalance(n,e)<t}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(e){return{repayFee:await this.getRepayFee(),exchangeFee:e.fee}}getPoolType(){return"LBP"}async isSupported(){let e=this.api.query.LBP.PoolData,t=await this.api.compatibilityToken;return e.isCompatible(nn.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(e.address);return n?t.watchValue("best").pipe((0,se.switchMap)(s=>s?this.getPoolDelta(e.address,n,s.relay_parent_number):(0,se.of)(e)),(0,se.map)(s=>Object.assign({},e,s))):(0,se.of)(e)}};var Ot={};I(Ot,{OmniMath:()=>B,OmniPool:()=>Ae,OmniPoolClient:()=>_e});var S=require("@galacticcouncil/math-omnipool"),re=st(require("big.js")),B=class{static calculateSpotPrice(e,t,n,s){return(0,S.calculate_spot_price)(e,t,n,s)}static calculateLrnaSpotPrice(e,t){return(0,S.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,n,s,r,i,a,o,l){return(0,S.calculate_in_given_out)(e,t,n,s,r,i,a,o,l)}static calculateLrnaInGivenOut(e,t,n,s,r){return(0,S.calculate_lrna_in_given_out)(e,t,n,s,r)}static calculateOutGivenIn(e,t,n,s,r,i,a,o,l){return(0,S.calculate_out_given_in)(e,t,n,s,r,i,a,o,l)}static calculateOutGivenLrnaIn(e,t,n,s,r){return(0,S.calculate_out_given_lrna_in)(e,t,n,s,r)}static calculateShares(e,t,n,s){return(0,S.calculate_shares)(e,t,n,s)}static calculateLiquidityOut(e,t,n,s,r,i,a,o){return(0,S.calculate_liquidity_out)(e,t,n,s,r,i,a,o)}static calculateLiquidityLRNAOut(e,t,n,s,r,i,a,o){return(0,S.calculate_liquidity_lrna_out)(e,t,n,s,r,i,a,o)}static calculateCapDifference(e,t,n,s){let r=(0,re.default)(t),i=(0,re.default)(e),a=(0,re.default)(s),o=(0,re.default)(n),l=(0,re.default)(10).pow(18),u=o.div(l);if(r.div(a).lt(u)){let p=u.times(a).minus(r).times(i),m=r.times((0,re.default)(1).minus(u));return p.div(m).toFixed(0)}else return"0"}static verifyAssetCap(e,t,n,s){return(0,S.verify_asset_cap)(e,t,n,s)}static calculateLimitHubIn(e,t,n,s){return(0,S.calculate_liquidity_hub_in)(e,t,n,s)}static isSellAllowed(e){return(0,S.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,S.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,S.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,S.is_remove_liquidity_allowed)(e)}};var Ae=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,n,s,r,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.hubAssetId=i}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,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(e,t,n){let s=this.calculateInGivenOut(e,t),r=this.calculateInGivenOut(e,t,n),i=s===0n?0:A.calculateDiffToRef(r,s),a=[],o=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetInEd)&&a.push("InsufficientTradingAmount");let u=e.balanceOut/this.maxOutRatio;t>u&&a.push("MaxOutRatioExceeded");let d=e.balanceIn/this.maxInRatio;return r>d&&a.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),r=this.calculateOutGivenIn(e,t,n),i=A.calculateDiffToRef(s,r),a=[],o=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetOutEd)&&a.push("InsufficientTradingAmount");let u=e.balanceIn/this.maxInRatio;t>u&&a.push("MaxInRatioExceeded");let d=e.balanceOut/this.maxOutRatio;return r>d&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateInGivenOut(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,n);let s=B.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateLrnaInGivenOut(e,t,n){let s=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,n);let s=B.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenLrnaIn(e,t,n){let s=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=B.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceLrnaInGivenOut(e){let t=B.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=B.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}spotPriceOutGivenLrnaIn(e){let t=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}};var je=require("polkadot-api"),sn=require("@polkadot-api/utils"),Be=require("rxjs");var _e=class extends N{async loadPools(){let e=await this.api.constants.Omnipool.HubAssetId(),t=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(e),this.getBalance(t,e),this.getPoolLimits()]),o=n.map(async({keyArgs:u,value:d})=>{let[p]=u,{hub_reserve:m,shares:g,tradable:P,cap:b,protocol_shares:x}=d,[f,T]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(t,p)]);return{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:T,cap:b,hubReserves:m,protocolShares:x,shares:g,tradeable:P,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:e,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:i,tradeable:s,type:r?.asset_type.type}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:l,...a}]}getPoolAddress(){let e="modlomnipool".padEnd(32,"\0"),t=new TextEncoder().encode(e),n=(0,sn.toHex)(t);return(0,je.AccountId)(63).dec(n)}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(e,t){let[n,s,r]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(t)]),i=n.min_fee+s.min_fee,a=n.max_fee+s.max_fee;if(r){let{asset_fee:o,protocol_fee:l}=r;return{assetFee:h.fromPermill(o),protocolFee:h.fromPermill(l),min:h.fromPermill(i),max:h.fromPermill(a)}}else return{assetFee:h.fromPermill(n.min_fee),protocolFee:h.fromPermill(s.min_fee),min:h.fromPermill(i),max:h.fromPermill(a)}}getPoolType(){return"Omnipool"}async isSupported(){let e=this.api.query.Omnipool.Assets,t=await this.api.compatibilityToken;return e.isCompatible(je.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,Be.distinctUntilChanged)((n,s)=>!s.deltas),(0,Be.map)(({entries:n})=>n.map(s=>{let[r]=s.args,{hub_reserve:i,shares:a,tradable:o,cap:l,protocol_shares:u}=s.value,d=e.tokens.findIndex(m=>m.id===r);return{...e.tokens[d],cap:l,hubReserves:i,protocolShares:u,shares:a,tradeable:o}})),(0,Be.map)(n=>{let s=e.tokens.find(r=>r.id===1);return{...e,tokens:[...n,s]}}))}};var vt={};I(vt,{StableMath:()=>D,StableSwap:()=>Re,StableSwapClient:()=>Fe});var _=require("@galacticcouncil/math-stableswap"),D=class{static getPoolAddress(e){return(0,_.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let n=0;n<e;n++)t.push(["1","1"]);return t}static calculateAmplification(e,t,n,s,r){return(0,_.calculate_amplification)(e,t,n,s,r)}static calculateInGivenOut(e,t,n,s,r,i,a){return(0,_.calculate_in_given_out)(e,t,n,s,r,i,a)}static calculateAddOneAsset(e,t,n,s,r,i,a){return(0,_.calculate_add_one_asset)(e,t,n,s,r,i,a)}static calculateSharesForAmount(e,t,n,s,r,i,a){return(0,_.calculate_shares_for_amount)(e,t,n,s,r,i,a)}static calculateOutGivenIn(e,t,n,s,r,i,a){return(0,_.calculate_out_given_in)(e,t,n,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,n,s,r,i,a){return(0,_.calculate_liquidity_out_one_asset)(e,t,n,s,r,i,a)}static calculateShares(e,t,n,s,r,i){return(0,_.calculate_shares)(e,t,n,s,r,i)}static calculateSpotPriceWithFee(e,t,n,s,r,i,a,o){return(0,_.calculate_spot_price_with_fee)(e,t,n,s,r,i,a,o)}static recalculatePegs(e,t,n,s,r){let i=(0,_.recalculate_peg)(e,t,n,s,r);return JSON.parse(i)}};var Re=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,n,s,r,i,a,o,l){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.amplification=i,this.id=a,this.fee=o,this.totalIssuance=l}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),r=this.calculateInGivenOut(e,t,n),i=h.toPct(n.fee),a=[],o=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:r,calculatedIn:s,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),r=this.calculateOutGivenIn(e,t,n),i=h.toPct(n.fee),a=[],o=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateIn(e,t,n){let s=D.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateAddOneAsset(e,t,n){let s=D.calculateAddOneAsset(this.getReserves(),t.toString(),Number(e.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateSharesForAmount(e,t,n){let s=D.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateInGivenOut(e,t,n){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,n):e.assetIn==this.id?this.calculateSharesForAmount(e,t,n):this.calculateIn(e,t,n)}spotPriceInGivenOut(e){let t=D.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetOut.toString(),e.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(e.assetOut==this.id)return BigInt(t);if(e.assetIn==this.id){let s=Math.pow(10,e.decimalsIn-e.decimalsOut);return BigInt(t)/BigInt(s)}let n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateOut(e,t,n){let s=D.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateWithdrawOneAsset(e,t,n){let s=D.calculateLiquidityOutOneAsset(this.getReserves(),t.toString(),Number(e.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateShares(e,t,n){let s=D.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(e,t,n){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,n):e.assetOut==this.id?this.calculateShares(e,t,n):this.calculateOut(e,t,n)}spotPriceOutGivenIn(e){let t=D.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetIn.toString(),e.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(e.assetIn==this.id)return BigInt(t);if(e.assetOut==this.id){let s=Math.pow(10,e.decimalsOut-e.decimalsIn);return BigInt(t)/BigInt(s)}let n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}getPegs(){let e=D.defaultPegs(this.tokens.length-1);return JSON.stringify(e)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:n,decimals:s})=>({asset_id:t,amount:n,decimals:s}));return JSON.stringify(e,Z.jsonFormatter)}getAssets(e,t){let n={asset_id:Number(e),amount:t.toString()};return JSON.stringify([n],Z.jsonFormatter)}};var ze=require("polkadot-api"),rn=require("@polkadot-api/utils"),an=require("@noble/hashes/blake2b"),pe=require("rxjs");var jn=340282366920938463463374607431768211455n,Fe=class extends N{poolsData=new Map([]);async loadPools(){let[e,t,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),s=e.map(async({keyArgs:r,value:i})=>{let[a]=r,o=this.getPoolAddress(a),[l,u,d]=await Promise.all([this.getPoolDelta(a,i,t),this.getPoolTokens(a,i),this.getPoolPegs(a,i,t)]);return this.poolsData.set(o,i),{address:o,id:a,type:"Stableswap",fee:h.fromPermill(i.fee),tokens:u,...l,...d,...n}});return Promise.all(s)}async getPoolDelta(e,t,n){let{initial_amplification:s,final_amplification:r,initial_block:i,final_block:a}=t,o=D.calculateAmplification(s.toString(),r.toString(),i.toString(),a.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(e);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(e,t){let n=this.getPoolAddress(e),s=t.assets.map(async a=>{let[o,l,u]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(e,a),this.api.query.AssetRegistry.Assets.getValue(a),this.getBalance(n,a)]);return{id:a,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:u,tradeable:o,type:l?.asset_type.type}}),r=await Promise.all(s),i=await this.api.query.AssetRegistry.Assets.getValue(e);return r.push({id:e,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:jn,tradeable:15,type:i?.asset_type.type}),r}async getPoolPegs(e,t,n){let s=await this.api.query.Stableswap.PoolPegs.getValue(e);if(!s)return this.getDefaultPegs(t);let r=await this.getLatestPegs(t,s,n),i=this.getRecentPegs(s),a=h.fromPermill(s.max_peg_update),o=h.fromPermill(t.fee),[l,u]=D.recalculatePegs(JSON.stringify(i),JSON.stringify(r),n.toString(),h.toDecimals(a).toString(),h.toDecimals(o).toString()),d=Number(l)*1e6;return{pegsFee:h.fromPermill(d),pegs:u}}getDefaultPegs(e){let t=e.fee,n=D.defaultPegs(e.assets.length);return{pegsFee:h.fromPermill(t),pegs:n}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([n,s])=>s.map(r=>r.toString()))}async getLatestPegs(e,t,n){let{source:s}=t,r=Array.from(e.assets.entries()).map(([a,o])=>o),i=s.map(async(a,o)=>{if(a.type==="Oracle"){let[l,u,d]=a.value,p=[d,r[o]].sort((f,T)=>f-T),m=await this.api.query.EmaOracle.Oracles.getValue(l,p,u);if(!m)return;let[{price:g,updated_at:P}]=m,b=g.n.toString(),x=g.d.toString();return d.toString()===p[0].toString()?[[b,x],P.toString()]:[[x,b],P.toString()]}else return[a.value.map(l=>l.toString()),n]});return Promise.all(i)}getPoolAddress(e){let t=D.getPoolAddress(e),n=(0,an.blake2b)(t,{dkLen:32}),s=(0,rn.toHex)(n);return(0,ze.AccountId)(63).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(e){return{fee:e.fee}}getPoolType(){return"Stableswap"}async isSupported(){let e=this.api.query.Stableswap.Pools,t=await this.api.compatibilityToken;return e.isCompatible(ze.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.System.Number,n=this.poolsData.get(e.address);return!n||!e.id?(0,pe.of)(e):t.watchValue("best").pipe((0,pe.switchMap)(s=>this.getPoolDelta(e.id,n,s)),(0,pe.map)(s=>Object.assign({},e,s)))}};var At={};I(At,{XykMath:()=>$,XykPool:()=>Ee,XykPoolClient:()=>De});var R=require("@galacticcouncil/math-xyk"),$=class{static getSpotPrice(e,t,n){return(0,R.get_spot_price)(e,t,n)}static calculateInGivenOut(e,t,n){return(0,R.calculate_in_given_out)(e,t,n)}static calculateOutGivenIn(e,t,n){return(0,R.calculate_out_given_in)(e,t,n)}static calculatePoolTradeFee(e,t,n){return(0,R.calculate_pool_trade_fee)(e,t,n)}static calculateLiquidityIn(e,t,n){return(0,R.calculate_liquidity_in)(e,t,n)}static calculateSpotPrice(e,t){return(0,R.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,n,s){return(0,R.calculate_spot_price_with_fee)(e,t,n,s)}static calculateShares(e,t,n){return(0,R.calculate_shares)(e,t,n)}static calculateLiquidityOutAssetA(e,t,n,s){return(0,R.calculate_liquidity_out_asset_a)(e,t,n,s)}static calculateLiquidityOutAssetB(e,t,n,s){return(0,R.calculate_liquidity_out_asset_b)(e,t,n,s)}};var Ee=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,n,s,r){this.type="XYK",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),r=this.calculateTradeFee(s,n),i=h.toPct(n.exchangeFee),a=s+r,o=[];(t<this.minTradingLimit||s<e.assetInEd)&&o.push("InsufficientTradingAmount");let l=e.balanceOut/this.maxOutRatio;t>l&&o.push("MaxOutRatioExceeded");let u=e.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:t,feePct:i,errors:o}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),r=this.calculateTradeFee(s,n),i=h.toPct(n.exchangeFee),a=s-r,o=[];(t<this.minTradingLimit||s<e.assetOutEd)&&o.push("InsufficientTradingAmount");let l=e.balanceIn/this.maxInRatio;t>l&&o.push("MaxInRatioExceeded");let u=e.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:a,feePct:i,errors:o}}calculateInGivenOut(e,t){let n=$.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(e,t){let n=$.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(e){let t=$.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){let t=$.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateTradeFee(e,t){let n=$.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return BigInt(n)}};var on=require("polkadot-api"),ln=require("rxjs");var De=class extends N{async loadPools(){let e=this.api.query.XYK.PoolAssets,[t,n]=await Promise.all([e.getEntries(),this.getPoolLimits()]),s=t.map(async({keyArgs:r,value:i})=>{let[a]=r,[o,l]=i,[u,d,p,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:d?.decimals,existentialDeposit:d?.existential_deposit,balance:u,type:d?.asset_type.type},{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:p,type:m?.asset_type.type}],...n}});return Promise.all(s)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let e=this.api.query.XYK.PoolAssets,t=await this.api.compatibilityToken;return e.isCompatible(on.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){return(0,ln.of)(e)}};var Bt={};I(Bt,{AavePool:()=>ke,AavePoolClient:()=>Ce});var ke=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,n,s,r){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),r=[];return t>e.balanceOut&&r.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:r}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),r=[];return s>e.balanceOut&&r.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:r}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){let t=Math.pow(10,e.decimalsOut);return BigInt(t)}spotPriceOutGivenIn(e){let t=Math.pow(10,e.decimalsIn);return BigInt(t)}calculateTradeFee(e,t){return 0n}};var cn=require("polkadot-api"),pn=require("@polkadot-api/utils"),me=require("rxjs"),mn=require("viem");var un=[{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:zn}=ee,Kn=["Supply","Withdraw","Repay","Borrow"],Ce=class extends N{async loadPools(){let t=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:s,liqudity_in:r,liqudity_out:i})=>{let[a,o,l,u]=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:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolDelta(e){let[t,n]=e.tokens,{liqudity_in:s,liqudity_out:r}=await this.api.apis.AaveTradeExecutor.pool(t.id,n.id);return e.tokens.map(i=>{let a=i.id===t.id?s:r;return{...i,balance:a}})}getPoolId(e,t){let n=e+"/"+t,s=new TextEncoder().encode(n.padEnd(32,"\0")),r=(0,pn.toHex)(s);return(0,cn.AccountId)(63).dec(r)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(e){let[t,n]=e.tokens,s=this.getReserveH160Id(t),r=this.api.event.Router.Executed.watch(({asset_in:a,asset_out:o})=>a===n.id||o===n.id),i=this.api.event.EVM.Log.watch(({log:a})=>{let{topics:o,data:l}=a,u=o.map(g=>g.asHex()),d=l.asHex(),{eventName:p,args:m}=(0,mn.decodeEventLog)({abi:un,topics:u,data:d});return Kn.includes(p)&&m.reserve.toLowerCase()===s.toLowerCase()});return(0,me.merge)([r,i]).pipe((0,me.switchMap)(()=>this.getPoolDelta(e)),(0,me.map)(a=>({...e,tokens:[...a]})))}getReserveH160Id(e){return e.type==="Erc20"?Z.findNestedKey(e.location,"AccountKey20").AccountKey20.key:zn.fromAssetId(e.id)}};var de=class{static get(e){switch(e.type){case"Aave":return ke.fromPool(e);case"XYK":return Ee.fromPool(e);case"Omnipool":return Ae.fromPool(e);case"LBP":return Oe.fromPool(e);case"Stableswap":return Re.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var j=require("rxjs");var ge=class extends M{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=j.Subscription.EMPTY;omniSub=j.Subscription.EMPTY;stableSub=j.Subscription.EMPTY;xykSub=j.Subscription.EMPTY;aaveSub=j.Subscription.EMPTY;isReady=!1;isDestroyed=new j.Subject;constructor(e){super(e),this.lbpClient=new ve(e),this.omniClient=new _e(e),this.stableClient=new Fe(e),this.xykClient=new De(e),this.aaveClient=new Ce(e),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(e){return e.getSubscriber().pipe((0,j.takeUntil)(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(e){return this.xykClient.withOverride(e),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),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.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let e=await Promise.all(this.clients.filter(t=>this.active.has(t.getPoolType())).map(t=>t.getPools()));return this.isReady=!0,e.flat()}async getPoolFees(e,t){let n=this.clients.find(s=>s.getPoolType()===e.type);if(n)return n.getPoolFees(e,t);throw new Ie(e.type)}};var Mt={};I(Mt,{DEFAULT_BLOCK_TIME:()=>dn,DEFAULT_MIN_BUDGET:()=>Et,ORDER_MIN_BLOCK_PERIOD:()=>gn,Router:()=>be,TWAP_BLOCK_PERIOD:()=>qe,TWAP_MAX_DURATION:()=>kt,TWAP_MAX_PRICE_IMPACT:()=>Dt,TWAP_TX_MULTIPLIER:()=>Co,TradeOrderError:()=>Ft,TradeOrderType:()=>Qe,TradeRouteBuilder:()=>H,TradeRouter:()=>ye,TradeScheduler:()=>he,TradeType:()=>$e});var Ke=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var $n=5,Me=class{isNotVisited(e,t){let n=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(n=!1)}),n}findPaths(e,t,n){let s=[],r=new Ke,i=[];for(i.push([t,""]),r.enqueue(i);r.size()>0;){let a=r.dequeue();if(a==null||a.length>$n)return s;let o=a[a.length-1];(n===null||o[0]===n)&&s.push(a),e.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let d=[...a];d.push(u),r.enqueue(d)}})}return s}buildAndPopulateGraph(e,t){let n=new Map;for(let s of e)n.set(parseInt(s),[]);for(let[s,r,i]of t)n.get(r)?.push([i,s]);return n}};function Rt(c){let e={};for(let t of c){let n=t.tokens.length;for(let s=0;s<n;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let r=0;r<n;r++){if(s==r)continue;let i=[t.address,t.tokens[s].id,t.tokens[r].id];e[t.tokens[s].id].push(i)}}}return e}var Le=class{getProposals(e,t,n){let s=Rt(n),r=Object.keys(s),i=r.map(u=>s[u]).flat(),a=new Me,o=a.buildAndPopulateGraph(r,i),l=a.findPaths(o,e,t);return this.parsePaths(l)}parsePaths(e){let t=[];for(let n of e){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))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0],t[0]]}};var be=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(e,t){this.ctx=e,this.routeSuggester=new Le,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=await this.ctx.getPools(),t=this.routerOptions.useOnly;return t.length===0?e:e.filter(n=>t.includes(n.type))}async getRoutes(e,t){let n=await this.getPools();return this.validateInput(e,t,n),this.getPaths(e,t,n)}async getTradeableAssets(){let e=await this.getPools(),t=this.getAssets(e);return Array.from(t)}validateInput(e,t,n){if(n.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(n);if(!s.has(e))throw new Error(e+" is not supported asset");if(!s.has(t))throw new Error(t+" is not supported asset");return this.toPoolsMap(n)}getAssets(e){let t=e.map(n=>n.tokens.map(s=>s.id)).flat().sort((n,s)=>n>s?1:-1);return new Set(t)}getPaths(e,t,n){let s=this.toPoolsMap(n);return this.routeSuggester.getProposals(e,t,n).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}validPath(e,t){return e.length>0&&e.map(n=>this.validEdge(n,t)).reduce((n,s)=>n&&s)}validEdge([e,t,n],s){return s.get(e)?.validatePair(t,n)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,de.get(t)]))}toHops(e,t){return e.map(([n,s,r])=>{let i=t.get(n);return{poolAddress:n,poolId:i?.id,pool:i?.type,assetIn:s,assetOut:r}})}};var $e=(t=>(t.Buy="Buy",t.Sell="Sell",t))($e||{}),Qe=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Qe||{}),Ft=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(Ft||{});var ye=class extends be{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((n,s)=>{let r=n[n.length-1].amountOut,i=s[s.length-1].amountOut;return r>i?-1:1});return t.find(n=>n.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(n=>n.tradeFeeRange).length>0){let n=e.map(r=>r.tradeFeeRange?.[0]??r.tradeFeePct).reduce((r,i)=>r+i),s=e.map(r=>r.tradeFeeRange?.[1]??r.tradeFeePct).reduce((r,i)=>r+i);return[n,s]}}getPoolFeeRange(e){let t=e.min?h.toPct(e.min):void 0,n=e.max?h.toPct(e.max):void 0;if(t&&n)return[t,n]}async getBestSell(e,t,n){return this.getSell(e,t,n)}async getSellSpot(e){let t=e[e.length-1];if(e.length===1)return t.spotPrice;let n=e.map(a=>a.assetOutDecimals).reduce((a,o)=>a+o),s=e.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-t.assetOutDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getSell(e,t,n,s){let r=await super.getPools(),i=super.validateInput(e,t,r),a=super.getPaths(e,t,r);if(a.length===0)throw new ce(e,t);let o;if(s)o=await this.toSellSwaps(n,s,i);else{let F=await Promise.all(a.map(k=>this.toSellSwaps(n,k,i)));o=this.findBestSellRoute(F)}let l=o[0],u=o[o.length-1],d=this.isDirectTrade(o),p=await this.getSellSpot(o),m=u.amountOut,g=d?u.calculatedOut:this.calculateDelta0Y(l.amountIn,o,i),P=g-m,b=this.getRouteFeeRange(o),x=d?u.tradeFeePct:A.calculateSellFee(g,m),f=Math.pow(10,l.assetInDecimals),T=l.amountIn*p/BigInt(f),v=A.calculateDiffToRef(g,T);return{type:"Sell",amountIn:l.amountIn,amountOut:u.amountOut,spotPrice:p,tradeFee:P,tradeFeePct:x,tradeFeeRange:b,priceImpactPct:v,swaps:o,toHuman(){return{type:"Sell",amountIn:y.toDecimal(l.amountIn,l.assetInDecimals),amountOut:y.toDecimal(u.amountOut,u.assetOutDecimals),spotPrice:y.toDecimal(p,u.assetOutDecimals),tradeFee:y.toDecimal(P,u.assetOutDecimals),tradeFeePct:x,tradeFeeRange:b,priceImpactPct:v,swaps:o.map(F=>F.toHuman())}}}}calculateDelta0Y(e,t,n){let s=[];for(let r=0;r<t.length;r++){let i=t[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=e;let u=a.calculateOutGivenIn(o,l);s.push(u)}return s[s.length-1]}async toSellSwaps(e,t,n){let s=[];for(let r=0;r<t.length;r++){let i=t[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 e=="string"?y.toBigInt(e,o.decimalsIn):e;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountOut:d,calculatedOut:p,feePct:m,errors:g}=a.validateAndSell(o,l,u),P=this.getPoolFeeRange(u),b=a.spotPriceOutGivenIn(o),x=Math.pow(10,o.decimalsIn),f=l*b/BigInt(x),T=A.calculateDiffToRef(p,f);s.push({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:d,calculatedOut:p,spotPrice:b,tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,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:y.toDecimal(l,o.decimalsIn),amountOut:y.toDecimal(d,o.decimalsOut),calculatedOut:y.toDecimal(p,o.decimalsOut),spotPrice:y.toDecimal(b,o.decimalsOut),tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}async getMostLiquidRoute(e,t){let n=await super.getPools(),s=super.validateInput(e,t,n),r=super.getPaths(e,t,n),o=n.filter(p=>p.tokens.some(m=>m.id===e&&m.id!==p.id)).map(p=>p.type==="Aave"?p.tokens:p.tokens.filter(m=>m.id===e)).map(p=>p.map(m=>m.balance).reduce((m,g)=>m+g)).sort((p,m)=>m<p?-1:1)[0],l=A.getFraction(o,.1),u=await Promise.all(r.map(p=>this.toSellSwaps(l,p,s)));return this.findBestSellRoute(u).map(p=>({poolAddress:p.poolAddress,poolId:p?.poolId,pool:p.pool,assetIn:p.assetIn,assetOut:p.assetOut}))}async getSpotPrice(e,t){let n=await super.getPools(),s=super.validateInput(e,t,n),r=await this.getMostLiquidRoute(e,t),i=await this.toSellSwaps("1",r,s),a=await this.getSellSpot(i),o=i[i.length-1].assetOutDecimals;return{amount:a,decimals:o}}findBestBuyRoute(e){let t=e.sort((n,s)=>{let r=n[0].amountIn,i=s[0].amountIn;return r>i?1:-1});return t.find(n=>n.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,n){return this.getBuy(e,t,n)}async getBuySpot(e){let t=e[0];if(e.length===1)return t.spotPrice;let n=e.map(a=>a.assetInDecimals).reduce((a,o)=>a+o),s=e.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-t.assetInDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getBuy(e,t,n,s){let r=await super.getPools(),i=super.validateInput(e,t,r),a=super.getPaths(e,t,r);if(a.length===0)throw new ce(e,t);let o;if(s)o=await this.toBuySwaps(n,s,i);else{let F=await Promise.all(a.map(k=>this.toBuySwaps(n,k,i)));o=this.findBestBuyRoute(F)}let l=o[o.length-1],u=o[0],d=this.isDirectTrade(o),p=await this.getBuySpot(o),m=u.amountIn,g=d?u.calculatedIn:this.calculateDelta0X(l.amountOut,o,i),P=m-g,b=this.getRouteFeeRange(o),x=d?u.tradeFeePct:A.calculateBuyFee(g,m),f=Math.pow(10,l.assetOutDecimals),T=l.amountOut*p/BigInt(f),v;return g===0n?v=-100:v=A.calculateDiffToRef(T,g),{type:"Buy",amountOut:l.amountOut,amountIn:u.amountIn,spotPrice:p,tradeFee:P,tradeFeePct:x,tradeFeeRange:b,priceImpactPct:v,swaps:o,toHuman(){return{type:"Buy",amountOut:y.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:y.toDecimal(u.amountIn,u.assetInDecimals),spotPrice:y.toDecimal(p,u.assetInDecimals),tradeFee:y.toDecimal(P,u.assetInDecimals),tradeFeePct:x,tradeFeeRange:b,priceImpactPct:v,swaps:o.map(F=>F.toHuman())}}}}calculateDelta0X(e,t,n){let s=[];for(let r=t.length-1;r>=0;r--){let i=t[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==t.length-1?l=e:l=s[0];let u=a.calculateInGivenOut(o,l);s.unshift(u)}return s[0]}async toBuySwaps(e,t,n){let s=[];for(let r=t.length-1;r>=0;r--){let i=t[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==t.length-1?l=typeof e=="string"?y.toBigInt(e,o.decimalsOut):e:l=s[0].amountIn;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountIn:d,calculatedIn:p,feePct:m,errors:g}=a.validateAndBuy(o,l,u),P=this.getPoolFeeRange(u),b=a.spotPriceInGivenOut(o),x=Math.pow(10,o.decimalsOut),f=l*b/BigInt(x),T;p===0n?T=-100:T=A.calculateDiffToRef(f,p),s.unshift({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:d,calculatedIn:p,spotPrice:b,tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,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:y.toDecimal(l,o.decimalsOut),amountIn:y.toDecimal(d,o.decimalsIn),calculatedIn:y.toDecimal(p,o.decimalsIn),spotPrice:y.toDecimal(b,o.decimalsIn),tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}};var dn=6e3,Et=1000000000000000n,qe=6,Dt=-5,kt=216e5,Co=3,gn=6;var Ct=require("polkadot-api");var H=class{static build(e){return e.map(({assetIn:t,assetOut:n,pool:s,poolId:r})=>s==="Stableswap"?{pool:(0,Ct.Enum)("Stableswap",r),asset_in:t,asset_out:n}:{pool:(0,Ct.Enum)(s),asset_in:t,asset_out:n})}};var he=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??6e3,minBudgetInNative:t.minBudgetInNative??Et})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,n,s,r){let[i,a]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:o,swaps:l,priceImpactPct:u}=a,d=l[0],p=l[l.length-1],{assetInDecimals:m}=d,{assetOutDecimals:g}=p,P=Math.abs(u),b=this.getMinimumTradeCount(o,i),x=this.getOptimalTradeCount(P),f=r?Math.round(s/r):x,T=Math.ceil(s/b),v=Math.round(s/x),F=Math.round(s/f),k=o/BigInt(f),C=await this.router.getBestSell(e,t,k),Q=o<i,Ne=[];Q&&Ne.push("OrderTooSmall");let He=C.amountOut*BigInt(f),tt=this.toBlockPeriod(F),nt=C.tradeFee*BigInt(f),yn=H.build(l),Nt={assetIn:e,assetOut:t,errors:Ne,frequencyMin:T,frequencyOpt:v,frequency:F,tradeCount:f,tradeFee:nt,tradeImpactPct:C.priceImpactPct,tradePeriod:tt,tradeRoute:yn,type:"Dca"};return{...Nt,amountIn:o,amountOut:He,tradeAmountIn:C.amountIn,tradeAmountOut:C.amountOut,toHuman(){return{...Nt,amountIn:y.toDecimal(o,m),amountOut:y.toDecimal(He,g),tradeAmountIn:y.toDecimal(C.amountIn,m),tradeAmountOut:y.toDecimal(C.amountOut,g)}}}}async getMinimumOrderBudget(e){if(0===e)return this.minOrderBudget;let t=await this.router.getSpotPrice(0,e),n=10n**BigInt(12);if(t)return this.minOrderBudget*t.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let n=t*2n/10n;if(n===0n)return 0;let s=e+n/2n;return Number(s/n)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:p}=u,m=Math.abs(o),g=this.getTwapTradeCount(m),P=i/BigInt(g),b=await this.router.getBestSell(l.assetIn,u.assetOut,P),x=g===1,f=i<s,T=b.priceImpactPct<-5,v=[];f||x?v.push("OrderTooSmall"):T&&v.push("OrderImpactTooBig");let F=b.amountOut*BigInt(g),k=b.tradeFee*BigInt(g),C=H.build(a),Q={assetIn:e,assetOut:t,errors:v,tradeCount:g,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:C,type:"TwapSell"};return{...Q,amountIn:i,amountOut:F,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:k,toHuman(){return{...Q,amountIn:y.toDecimal(i,d),amountOut:y.toDecimal(F,p),tradeAmountIn:y.toDecimal(b.amountIn,d),tradeAmountOut:y.toDecimal(b.amountOut,p),tradeFee:y.toDecimal(k,p)}}}}async getTwapBuyOrder(e,t,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,n)]),{amountOut:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:p}=u,m=Math.abs(o),g=this.getTwapTradeCount(m),P=i/BigInt(g),b=await this.router.getBestBuy(l.assetIn,u.assetOut,P),x=b.amountIn*BigInt(g),f=g===1,T=x<s,v=b.priceImpactPct<-5,F=[];T||f?F.push("OrderTooSmall"):v&&F.push("OrderImpactTooBig");let k=b.tradeFee*BigInt(g),C=H.build(a),Q={assetIn:e,assetOut:t,errors:F,tradeCount:g,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:C,type:"TwapBuy"};return{...Q,amountIn:x,amountOut:i,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:k,toHuman(){return{...Q,amountIn:y.toDecimal(x,d),amountOut:y.toDecimal(i,p),tradeAmountIn:y.toDecimal(b.amountIn,d),tradeAmountOut:y.toDecimal(b.amountOut,p),tradeFee:y.toDecimal(k,d)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}return t}getTwapExecutionTime(e){return e*6*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,n=Math.round(t);return Math.max(n,6)}};var qt={};I(qt,{TxBuilderFactory:()=>fe});var Lt=require("polkadot-api");function bn(c){let e=[],t=c;for(;t&&typeof t=="object"&&"type"in t;)e.push(t.type),t=t.value;return e.join(".")}var Pe=class extends M{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new L,this.balanceClient=new X(e),this.aaveUtils=new te(this.evmClient)}wrapTx(e,t){return{name:e,get:()=>t,dryRun:n=>this.dryRun(n,t)}}async dispatchWithExtraGas(e){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:e.decodedCall,extra_gas:ot})}async dryRun(e,t){let n=(0,Lt.Enum)("Signed",e),s=(0,Lt.Enum)("system",n),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,t.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(e){return e.length===1&&e[0].pool==="Omnipool"}};var Je=class extends Pe{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,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:e,swaps:t,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:s}=t[0],r=await this.balanceClient.getBalance(this.beneficiary,s);return e>=r-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:e,amountOut:t,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=A.getFraction(e,this.slippagePct),a=s.assetIn,o=r.assetOut,l=e+i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:t,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:t,max_amount_in:l,route:H.build(n)}),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=A.getFraction(t,this.slippagePct),a=s.assetIn,o=r.assetOut,l=t-i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:e,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:e,min_amount_out:l,route:H.build(n)}),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,n=t[0],s=t[t.length-1],r=A.getFraction(e,this.slippagePct),i=n.assetIn,a=s.assetOut,o=e-r,l=this.api.tx.Router.sell_all({asset_in:i,asset_out:a,min_amount_out:o,route:H.build(t)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var Ze=require("polkadot-api");var et=class extends Pe{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,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:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,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:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Ze.Enum)("Sell",{asset_in:t,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:e,assetIn:t,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=A.getFraction(r,this.slippagePct),l=r-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Ze.Enum)("Sell",{asset_in:t,asset_out:n,amount_in:s,min_amount_out:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=A.getFraction(s,this.slippagePct),l=s+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Ze.Enum)("Buy",{asset_in:t,asset_out:n,amount_out:r,max_amount_in:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var fe=class{client;evmClient;constructor(e,t){this.client=e,this.evmClient=t??new L}trade(e){return new Je(this.client,this.evmClient).setTrade(e)}order(e){return new et(this.client,this.evmClient).setOrder(e)}};async function Qn(c,e){let t=new ue(c),[n,s]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),r=e??new L,i=new ge(c).withAave().withOmnipool().withStableswap().withXyk(),a=new te(r),o=new ye(i),l=new he(o,{blockTime:n,minBudgetInNative:s});return{api:{aave:a,router:o,scheduler:l},client:{asset:new le(c),balance:new X(c),evm:r},ctx:{pool:i},tx:new fe(c,r),destroy:()=>{i.destroy()}}}0&&(module.exports={aave,api,big,client,const:null,createSdkContext,erc20,error,evm,fmt,h160,json,math,pool,sor,tx,xc});
1
+ "use strict";var Xn=Object.create;var rt=Object.defineProperty;var zn=Object.getOwnPropertyDescriptor;var Kn=Object.getOwnPropertyNames;var jn=Object.getPrototypeOf,Qn=Object.prototype.hasOwnProperty;var sn=(u,e)=>()=>(u&&(e=u(u=0)),e);var v=(u,e)=>{for(var t in e)rt(u,t,{get:e[t],enumerable:!0})},nt=(u,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Kn(e))!Qn.call(u,r)&&r!==t&&rt(u,r,{get:()=>e[r],enumerable:!(n=zn(e,r))||n.enumerable});return u},ge=(u,e,t)=>(nt(u,e,"default"),t&&nt(t,e,"default")),ie=(u,e,t)=>(t=u!=null?Xn(jn(u)):{},nt(e||!u||!u.__esModule?rt(t,"default",{value:u,enumerable:!0}):t,u)),$n=u=>nt(rt({},"__esModule",{value:!0}),u);var ke={};var cn=sn(()=>{ge(ke,require("@polkadot-api/ws-provider/node"))});var Ee={};var un=sn(()=>{ge(Ee,require("@polkadot-api/ws-provider/web"))});var kr={};v(kr,{aave:()=>Et,api:()=>ht,big:()=>h,client:()=>qt,const:()=>At,createSdkContext:()=>Rr,erc20:()=>oe,error:()=>Gt,evm:()=>Tt,fmt:()=>P,h160:()=>Me,json:()=>ae,math:()=>_,pool:()=>Xt,sor:()=>Zt,staking:()=>en,tx:()=>nn,xc:()=>Rt});module.exports=$n(kr);var ht={};v(ht,{Papi:()=>C,getWs:()=>Jn});var ln=require("@galacticcouncil/descriptors");function on(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var C=class{client;api;constructor(e){this.client=e,this.api=this.client.getTypedApi(ln.hydration)}log(e,...t){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");on(n)&&console.log(e,...t)}};var dn=require("polkadot-api"),pn=require("polkadot-api/polkadot-sdk-compat"),Jn=async u=>{let e=typeof u=="string"?u.split(","):u,r=(typeof window>"u"?(await Promise.resolve().then(()=>(cn(),ke))).getWsProvider:(await Promise.resolve().then(()=>(un(),Ee))).getWsProvider)(e);return(0,dn.createClient)((0,pn.withPolkadotSdkCompat)(r))};var Et={};v(Et,{AAVE_GAS_LIMIT:()=>St,AAVE_LENDING_POOL_ADDRESS:()=>it,AAVE_POOL_ABI:()=>Pt,AAVE_POOL_DATA_PROVIDER:()=>st,AAVE_POOL_DATA_PROVIDER_ABI:()=>at,AAVE_POOL_PROXY:()=>ft,AAVE_ROUNDING_THRESHOLD:()=>Kr,AAVE_UINT_256_MAX:()=>Zn,AaveClient:()=>De,AaveUtils:()=>le});var Pt=[{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 at=[{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 ft="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",st="0x112b087b60C1a166130d59266363C45F8aa99db0",it="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",St=1000000n,Kr=5,Zn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Tt={};v(Tt,{EvmClient:()=>V,evmMainnet:()=>wt});var bn=require("viem"),mn=["https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],gn=["wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],wt=(0,bn.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:mn,webSocket:gn},default:{http:mn,webSocket:gn}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var K=require("viem");var V=class{chain;constructor(e){this.chain=e||wt}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}async getGasPrice(){return this.getProvider().getGasPrice()}getProvider(){return(0,K.createPublicClient)({chain:this.chain,transport:(0,K.http)()})}getWsProvider(){return(0,K.createPublicClient)({chain:this.chain,transport:(0,K.webSocket)()})}getSigner(e){return(0,K.createWalletClient)({account:e,chain:this.chain,transport:(0,K.custom)(window.ethereum)})}};var De=class{evmClient;constructor(e){this.evmClient=e??new V}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:at,address:st,args:[it],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:at,address:st,args:[it,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:Pt,address:ft,args:[e],functionName:"getUserAccountData"})}};var h={};v(h,{asBigInt:()=>nr,toBigInt:()=>tr,toDecimal:()=>er});var re=ie(require("big.js"));re.default.NE=-18;function er(u,e,t=6,n){let r=(0,re.default)(u.toString()),a=(0,re.default)(10).pow(e);return r.div(a).round(t,n).toString()}function tr(u,e){let t=(0,re.default)(10).pow(e),r=(0,re.default)(u).mul(t).toFixed(0,re.default.roundDown);return BigInt(r)}function nr(u){return BigInt(u.round(0,re.default.roundDown).toFixed(0))}var oe={};v(oe,{ERC20:()=>xt});var xt=class{static fromAssetId(e){let t=Buffer.alloc(20,0);return t[15]=1,t.writeUInt32BE(e,16),"0x"+t.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(e.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(t.subarray(0,16))}};var P={};v(P,{fromPermill:()=>sr,shiftNeg:()=>Ce,toDecimals:()=>ar,toPct:()=>rr});var hn=ie(require("big.js")),yn=1e3;function rr(u){let[e,t]=u;return e/t*100}function ar(u){let[e,t]=u;return e/t}function sr(u){return[u/yn,yn]}function Ce(u,e){let t=(0,hn.default)(typeof u=="bigint"?u.toString():u);return e===0?t.toString():t.div(Math.pow(10,e)).toString()}var Me={};v(Me,{H160:()=>Ft,isEvmAccount:()=>Pn,isEvmAddress:()=>fn,isSs58Address:()=>Sn});var ye=require("polkadot-api"),_t=require("@polkadot-api/utils"),ee=require("buffer");var At={};v(At,{HUB_ASSET_ID:()=>Ot,HYDRATION_OMNIPOOL_ADDRESS:()=>lr,HYDRATION_PARACHAIN_ID:()=>or,HYDRATION_SS58_PREFIX:()=>G,PERBILL_DENOMINATOR:()=>ir,PERMILL_DENOMINATOR:()=>It,RUNTIME_DECIMALS:()=>E,SYSTEM_ASSET_DECIMALS:()=>vt,SYSTEM_ASSET_ID:()=>j,TRADEABLE_DEFAULT:()=>be});var E=18,It=1e6,ir=1e9,j=0,vt=12,or=2034,G=63,lr="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Ot=1,be=15;var Bt="ETH\0";function Pn(u){if(!u)return!1;try{let e=(0,ye.AccountId)().enc(u),t=ee.Buffer.from(Bt);return ee.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function fn(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Sn(u){try{return(0,ye.AccountId)(63).enc(u),!0}catch{return!1}}var Ft=class u{static toAccount=e=>{let t=ee.Buffer.from(e.slice(2),"hex"),n=ee.Buffer.from(Bt),r=Uint8Array.from(ee.Buffer.concat([n,t,ee.Buffer.alloc(8)])),a=(0,_t.toHex)(r);return(0,ye.AccountId)(63).dec(a)};static fromAccount=e=>{let t=(0,ye.AccountId)().enc(e),n=ee.Buffer.from(Bt),r=t.slice(n.length,-8);return"0x"+ee.Buffer.from(r).toString("hex")};static fromSS58=e=>{let n=(0,ye.AccountId)().enc(e).slice(0,20);return(0,_t.toHex)(n)};static fromAny=e=>{if(fn(e))return e;if(Pn(e))return u.fromAccount(e);if(Sn(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var ae={};v(ae,{findNestedKey:()=>cr,findNestedObj:()=>ur,jsonFormatter:()=>dr});var cr=(u,e)=>{let t=[];return JSON.stringify(u,(n,r)=>(r&&r[e]&&t.push(r),r)),t[0]},ur=(u,e,t)=>{let n;return JSON.stringify(u,(r,a)=>(a&&a[e]===t&&(n=a),a)),n},dr=(u,e)=>typeof e=="bigint"?e.toString():e;var _={};v(_,{calculateBuyFee:()=>br,calculateDiffToAvg:()=>pr,calculateDiffToRef:()=>mr,calculateSellFee:()=>gr,getFraction:()=>yr});var $=ie(require("big.js"));function pr(u,e){let t=(0,$.default)(u.toString()),n=(0,$.default)(e.toString());return t.minus(n).abs().div(t.plus(n).div(2)).mul(100).round(2).toNumber()}function mr(u,e){if(e===0n)return 0;let t=(0,$.default)(u.toString()),n=(0,$.default)(e.toString());return t.minus(n).div(n).mul(100).round(2).toNumber()}function gr(u,e){let t=(0,$.default)(u.toString()),n=(0,$.default)(e.toString());return(0,$.default)(1).minus(n.div(t)).mul(100).round(2).toNumber()}function br(u,e){let t=(0,$.default)(u.toString());return(0,$.default)(e.toString()).div(t).minus(1).mul(100).round(2).toNumber()}function yr(u,e,t=2){(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,t),r=BigInt(e*n);return u*r/BigInt(100*n)}var Rt={};v(Rt,{convertToId:()=>hr});var wn=require("buffer");function hr(u){let t=wn.Buffer.from(u.replace("0x",""),"hex").subarray(16);return t.readUIntBE(0,t.length)}var{ERC20:ot}=oe,{H160:kt}=Me,Pr=1.01,fr=99999,Sr=10n**27n,wr=10n**18n,le=class{client;constructor(e){let t=e??new V;this.client=new De(t)}async getSummary(e){let t=kt.fromAny(e),[n,r,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t)]),[s]=n,[i,o]=r,[l,c,d,m,p,g]=a,y=h.toDecimal(g,18),b=[];for(let f of i){let S=f.underlyingAsset.toLowerCase(),w=s.find(({underlyingAsset:se})=>se.toLowerCase()===S);if(!w)throw new Error("Missing pool reserve for "+S);let A=f.scaledATokenBalance,q=w.liquidityIndex,H=w.priceInMarketReferenceCurrency,L=A*q/Sr,z=Number(o===w.eModeCategoryId?w.eModeLiquidationThreshold:w.reserveLiquidationThreshold)/1e4,ne=w.usageAsCollateralEnabled&&f.usageAsCollateralEnabledOnUser&&f.scaledATokenBalance>0n,Fe=ot.toAssetId(S);b.push({aTokenBalance:L,decimals:Number(w.decimals),isCollateral:ne,priceInRef:H,reserveId:Fe,reserveAsset:S,reserveLiquidationThreshold:z})}return{healthFactor:Number(y),totalCollateral:l,totalDebt:c,reserves:b}}async hasBorrowPositions(e){let t=kt.fromAny(e),n=await this.client.getUserAccountData(t),[r,a]=n;return a>0n}async getHealthFactor(e){let t=kt.fromAny(e),n=await this.client.getUserAccountData(t),[r,a,s,i,o,l]=n,c=h.toDecimal(l,18);return Number(c)}async getHealthFactorAfterWithdraw(e,t,n){let{totalCollateral:r,totalDebt:a,reserves:s}=await this.getSummary(e),i=ot.fromAssetId(t),o=s.find(b=>b.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:c,priceInRef:d,reserveLiquidationThreshold:m}=o,p=h.toBigInt(n,l),g=c?p*d/10n**BigInt(l):0n,y=r-g;return y<=0n?0:this.calculateHealthFactor(y,m,a)}async getHealthFactorAfterSupply(e,t,n){let{totalCollateral:r,totalDebt:a,reserves:s}=await this.getSummary(e),i=ot.fromAssetId(t),o=s.find(y=>y.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:d}=o,p=h.toBigInt(n,l)*c/10n**BigInt(l),g=r+p;return g<=0n?0:this.calculateHealthFactor(g,d,a)}async getMaxWithdraw(e,t){let{totalCollateral:n,totalDebt:r,reserves:a}=await this.getSummary(e),s=ot.fromAssetId(t),i=a.find(o=>o.reserveAsset===s);if(!i)throw new Error("Missing reserve ctx for "+s);return this.calculateWithdrawMax(i,n,r)}async getMaxWithdrawAll(e){let{totalCollateral:t,totalDebt:n,reserves:r}=await this.getSummary(e),a={};for(let s of r){let i=this.calculateWithdrawMax(s,t,n);s.reserveId&&(a[s.reserveId]=i)}return a}calculateHealthFactor(e,t,n){if(n===0n)return fr;let r=10n**6n,a=h.toBigInt(t,18),s=e*a*r,i=n*wr,o=s/i;return Number(o)/1e6}calculateRequiredCollateral(e,t,n){let r=h.toBigInt(e,18),a=h.toBigInt(t,18);return(r*n+a-1n)/a}calculateWithdrawMax(e,t,n){let{aTokenBalance:r,decimals:a,priceInRef:s,reserveLiquidationThreshold:i}=e,o=this.calculateRequiredCollateral(Pr,i,n),l=t-o;if(l<=0n)return{amount:0n,decimals:a};let c=l*10n**BigInt(a)/s;return{amount:r<c?r:c,decimals:a}}};var qt={};v(qt,{AssetClient:()=>he,BalanceClient:()=>U,ChainParams:()=>Pe,LiquidityMining:()=>fe});var he=class extends C{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async queryShares(){let t=await this.api.query.Stableswap.Pools.getEntries();return new Map(t.map(({keyArgs:n,value:r})=>{let[a]=n;return[a,r]}))}async queryBonds(){let t=await this.api.query.Bonds.Bonds.getEntries();return new Map(t.map(({keyArgs:n,value:r})=>{let[a]=n;return[a,r]}))}async queryAssets(){let t=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(t.filter(({value:n})=>{let{asset_type:r}=n;return this.SUPPORTED_TYPES.includes(r.type)}).map(({keyArgs:n,value:r})=>{let[a]=n;return[a,r]}))}async queryAssetLocations(){let t=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(t.map(({keyArgs:n,value:r})=>{let[a]=n;return[a,r]}))}async mapToken(e,t,n,r){let{name:a,asset_type:s,is_sufficient:i,existential_deposit:o}=t,{symbol:l,decimals:c}=n.get(e)??{};return{id:e,name:a?.asText(),symbol:l,decimals:c,icon:l,type:s.type,isSufficient:i,location:r,existentialDeposit:o}}async mapBond(e,t,n,r){let[a,s]=r,{asset_type:i,is_sufficient:o,existential_deposit:l}=t,{symbol:c,decimals:d}=await this.mapToken(a,t,n),m=Number(s),p=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",p.format(m)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:d,icon:c,type:i.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:a,maturity:m}}async mapShares(e,t,n,r){let{assets:a}=r,{name:s,symbol:i,asset_type:o,is_sufficient:l,existential_deposit:c}=t,d=await Promise.all(a.map(async g=>{let{symbol:y}=await this.mapToken(g,t,n);return[g,y]})),m=Object.fromEntries(d),p=Object.values(m);return{id:e,name:p.join(", "),symbol:i?.asText()||s?.asText(),decimals:18,icon:p.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:m}}async mapExternal(e,t,n,r){let a=await this.mapToken(e,t,new Map,r),s=n?.find(i=>i.internalId===a.id);return s?{...a,decimals:s.decimals,name:s.name,symbol:s.symbol,icon:s.symbol,isWhiteListed:s.isWhiteListed}:a}parseMetadata(e){return new Map(Array.from(e,([t,n])=>[t,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(e,t){let[n,r,a,s]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),i=this.parseMetadata(n),o=[];for(let[l,c]of Array.from(n)){let d=r.get(l),{asset_type:m}=c,p;switch(m.type){case"Bond":let g=s.get(l);p=await this.mapBond(l,c,i,g);break;case"StableSwap":let y=a.get(l);p=await this.mapShares(l,c,i,y);break;case"External":p=await this.mapExternal(l,c,t,d);break;default:p=await this.mapToken(l,c,i,d)}o.push(p)}return e?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};var I=require("rxjs");var U=class extends C{constructor(e){super(e)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getTokenBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:n}=await t.getValue(e);return this.calculateBalance(n)}async getTokenBalance(e,t){let r=await this.api.query.Tokens.Accounts.getValue(e,t);return this.calculateBalance(r)}calculateBalance(e){let t=e.free>=e.frozen?e.free-e.frozen:0n,n=e.free+e.reserved;return{free:e.free,reserved:e.reserved,frozen:e.frozen,total:n,transferable:t}}async getErc20Balance(e,t){return this.getTokenBalanceData(e,t)}subscribeBalance(e){let t=this.subscribeSystemBalance(e),n=this.subscribeTokensBalance(e),r=this.subscribeErc20Balance(e);return(0,I.combineLatest)([t,n,r]).pipe((0,I.debounceTime)(250),(0,I.map)(a=>a.flat()),(0,I.startWith)([]),(0,I.bufferCount)(2,1),(0,I.map)(([a,s],i)=>{if(i===0)return s;let o=a.reduce((c,d)=>(c.set(d.id,d.balance),c),new Map);return s.filter(c=>!Tn(c.balance,o.get(c.id)))}))}subscribeSystemBalance(e){return this.api.query.System.Account.watchValue(e,"best").pipe((0,I.map)(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(e,t){return this.api.query.Tokens.Accounts.watchValue(e,t,"best").pipe((0,I.map)(r=>({id:t,balance:r})))}subscribeTokensBalance(e){return this.api.query.Tokens.Accounts.watchEntries(e,{at:"best"}).pipe((0,I.distinctUntilChanged)((n,r)=>!r.deltas),(0,I.map)(({deltas:n})=>{let r=[];return n?.deleted.forEach(a=>{let[s,i]=a.args;r.push({id:i,balance:this.calculateBalance({free:0n,reserved:0n,frozen:0n})})}),n?.upserted.forEach(a=>{let[s,i]=a.args;r.push({id:i,balance:this.calculateBalance(a.value)})}),r}))}subscribeErc20Balance(e,t){let n=new I.Subject,r=n.pipe((0,I.shareReplay)(1)),a=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}),s=async()=>{let o=t||await a(),l=async()=>{let m=(await Promise.all(o.map(async p=>{let g=await this.getTokenBalanceData(e,p);return[p,g]}))).map(([p,g])=>({id:p,balance:g}));n.next(m)};await l();let c=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>c.unsubscribe()},i;return s().then(o=>i=o),r.pipe((0,I.finalize)(()=>i?.()),(0,I.pairwise)(),(0,I.map)(([o,l],c)=>{if(c===0)return l;let d=o.reduce((p,g)=>(p.set(g.id,g.balance),p),new Map);return l.filter(p=>!Tn(p.balance,d.get(p.id)))}),(0,I.distinctUntilChanged)((o,l)=>l.length===0))}async getTokenBalanceData(e,t){let n=await this.api.apis.CurrenciesApi.account(t,e);return this.calculateBalance(n)}},Tn=(u,e)=>u!==void 0&&e!==void 0&&u.transferable===e.transferable&&u.total===e.total;var Pe=class extends C{_minOrderBudget;_blockTime;constructor(e){super(e)}async getBlockTime(){if(this._blockTime===void 0){let e=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(e)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var Se=require("polkadot-api"),Mt=require("@galacticcouncil/math-liquidity-mining"),M=ie(require("big.js"));var T=ie(require("big.js")),N=require("@galacticcouncil/math-liquidity-mining"),Tr="1000000000000000000",lt=class{constructor(e,t,n){this.get_account=e;this.multiCurrency=t;this.getAsset=n}calculate_rewards_from_pot(e,t,n){let r=(0,T.default)((0,N.calculate_reward)((0,T.default)(t.accumulated_rpz.toString()).toFixed(),(0,T.default)(e.accumulated_rpz.toString()).toFixed(),n.toFixed())),a={...t,accumulated_rpz:e.accumulated_rpz},s={...e,accumulated_paid_rewards:BigInt(r.plus(e.accumulated_paid_rewards.toString()).toFixed()),pending_rewards:BigInt((0,T.default)(e.pending_rewards.toString()).minus(r).toFixed())};return{reward:r,mutatedYieldFarm:a,mutatedGlobalFarm:s}}async sync_global_farm(e,t,n){if(e.state.type!=="Active"||e.updated_at===t)return;if(e.total_shares_z===0n)return{global_farm:{...e,updated_at:t}};let r=t-e.updated_at,a=this.get_account(e.id),s=(await this.getAsset(e.reward_currency))?.existential_deposit;if(!s)throw new Error("Missing reward currency asset list");let i=this.multiCurrency.free_balance(e.reward_currency,a),o=(0,T.default)(s.toString()),l=(0,T.default)(i.toString()).minus(o.lt(i.toString())?s.toString():i.toString()),c=(0,T.default)((0,N.calculate_global_farm_rewards)((0,T.default)(e.total_shares_z.toString()).toFixed(),(0,T.default)(n.toString()).toFixed(),(0,T.default)(e.yield_per_period.toString()).mul(Dt).round(0,T.default.roundDown).toFixed(),(0,T.default)(e.max_reward_per_period.toString()).toFixed(),r.toFixed()));l.lt(c)&&(c=l);let d={...e};if(!c.eq(0)){let m=this.get_account(0);this.multiCurrency.transfer(e.reward_currency,a,m,BigInt(c.toFixed())),d.accumulated_rpz=BigInt((0,T.default)((0,N.calculate_accumulated_rps)((0,T.default)(e.accumulated_rpz.toString()).toFixed(),(0,T.default)(e.total_shares_z.toString()).toFixed(),c.toFixed())).toFixed()),d.pending_rewards=BigInt(c.plus(e.pending_rewards.toString()).toFixed())}return d.updated_at=t,{reward:c,global_farm:d}}sync_yield_farm(e,t,n){if(e.state.type!=="Active"||e.updated_at===n)return;if(e.total_valued_shares===0n)return{yield_farm:{...e,accumulated_rpz:t.accumulated_rpz,updated_at:n}};let r=(0,N.calculate_yield_farm_rewards)((0,T.default)(e.accumulated_rpz.toString()).toFixed(),(0,T.default)(t.accumulated_rpz.toString()).toFixed(),(0,T.default)(e.multiplier.toString()).toFixed(),(0,T.default)(e.total_valued_shares.toString()).toFixed()),a=(0,N.calculate_yield_farm_delta_rpvs)((0,T.default)(e.accumulated_rpz.toString()).toFixed(),(0,T.default)(t.accumulated_rpz.toString()).toFixed(),(0,T.default)(e.multiplier.toString()).toFixed(),(0,T.default)(e.total_valued_shares.toString()).toFixed()),s=BigInt((0,T.default)(r).toFixed()),i={...e,accumulated_rpz:t.accumulated_rpz,accumulated_rpvs:e.accumulated_rpvs+BigInt((0,T.default)(a).toFixed()),updated_at:n,left_to_distribute:e.left_to_distribute+s},o={...t,accumulated_paid_rewards:t.accumulated_paid_rewards+s,pending_rewards:t.pending_rewards-s};return{yield_farm:i,global_farm:o}}get_loyalty_multiplier(e,t){let n=(0,T.default)(1).mul(Dt).round(0,T.default.roundDown).toString();if(t){let{initial_reward_percentage:r,scale_coef:a}=t;n=(0,N.calculate_loyalty_multiplier)(e.toFixed(),(0,T.default)(r.toString()).toFixed(),(0,T.default)(a.toString()).toFixed())}return n}async claim_rewards(e,t,n,r,a){if(t.state.type==="Terminated")return null;let s=Math.floor(r/e.blocks_per_period);if((0,T.default)(n.updated_at).eq(s))return null;let i=await this.sync_global_farm(e,s,a);if(!i)return null;let o=this.sync_yield_farm(t,i.global_farm,s);if(!o?.global_farm)return null;let{yield_farm:l,global_farm:c}=o,d=(0,T.default)(l.total_stopped).minus(n.stopped_at_creation),m=(0,T.default)(l.updated_at).minus(n.entered_at).minus(d),p=this.get_loyalty_multiplier(m,l.loyalty_curve),g=(0,T.default)((0,N.calculate_user_reward)(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),l.accumulated_rpvs.toString(),p)),y=(0,T.default)((0,N.calculate_user_reward)(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),l.accumulated_rpvs.toString(),Tr));return g.eq(0)||(l.left_to_distribute=l.left_to_distribute-BigInt(g.toFixed())),{reward:g,maxReward:y,assetId:c.reward_currency}}};var xr=BigInt((0,M.default)(1).pow(18).toString()),Ir=6,fe=class extends C{balanceClient;omnipoolAssetIds=[];secondsInYear=(0,M.default)(365.2425).times(24).times(60).times(60);constructor(e){super(e),this.balanceClient=new U(e)}async getOraclePrice(e,t){let n=[e,t].sort((a,s)=>a-s);if(e===t)return xr;let r=await this.api.query.EmaOracle.Oracles.getValue(Se.Binary.fromText("omnipool"),n,(0,Se.Enum)("TenMinutes"));if(r){let{n:a,d:s}=r[0].price,i;return e<t?i=(0,Mt.fixed_from_rational)(a.toString(),s.toString()):i=(0,Mt.fixed_from_rational)(s.toString(),a.toString()),BigInt(i)}}getFarmAddress=(e,t)=>{let n=Buffer.from("modl","utf-8"),r=Buffer.from(t?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),a=Buffer.from([e]),s=Buffer.concat([n,r,a]),o="0x"+Buffer.concat([s,Buffer.alloc(32-s.length)]).toString("hex");return(0,Se.AccountId)(63).dec(o)};getGlobalRewardPerPeriod(e,t,n,r){let a=(0,M.default)(r).times(e.toString()).times(t.toString()).div(18);return a.gte(n.toString())?n.toString():a.toString()}getPoolYieldPerPeriod(e,t,n,r){let a=(0,M.default)(e.toString()).times(t),s=(0,M.default)(n.toString()).times(r);return a.div(s.toString()).toString()}farmData(e,t,n){let{yieldFarm:r,globalFarm:a,priceAdjustment:s,balance:i}=e,{multiplier:o,loyalty_curve:l}=r,{blocks_per_period:c,yield_per_period:d,total_shares_z:m,max_reward_per_period:p,pending_rewards:g,accumulated_paid_rewards:y,planned_yielding_periods:b,updated_at:f,incentivized_asset:S,reward_currency:w,price_adjustment:A}=a,q=Ce(s??A,18),H=Ce(o,18),L=Ce(l?.initial_reward_percentage??0,18),X=this.secondsInYear.div((0,M.default)(Ir).times(c)).toString(),z;if(m<0)z=(0,M.default)(H).times(d.toString()).times(X).toString();else{let Wn=this.getGlobalRewardPerPeriod(m,d,p,q),Yn=this.getPoolYieldPerPeriod(Wn,H,m,q);z=(0,M.default)(Yn).times(X).toString()}let ne=g+y,Fe=p*BigInt(b),se=i.transferable+ne,yt=se-ne,Re=(0,M.default)(yt.toString()).div(p.toString()),rn=(0,M.default)(t).div(c.toString()).toString(),Vn=(m>=0?Re.plus(f):Re.plus(rn)).toString(),Hn=(0,M.default)(m.toString()).div((0,M.default)(p.toString()).div(d.toString())).div(Math.pow(10,18)).times(100).times(q).toFixed(2),an=(0,M.default)(ne.toString()).div(se.toString()).gte(.999);z=an?"0":(0,M.default)(z).div(n?2:1).times(100).toString();let Un=L?(0,M.default)(z).times(L).toString():void 0;return{apr:z,minApr:Un,isDistributed:an,estimatedEndPeriod:Vn,maxRewards:Fe,incentivizedAsset:S,rewardCurrency:w,loyaltyCurve:l,currentPeriod:rn,potMaxRewards:se,fullness:Hn}}async getOmnipoolFarms(e){let t=await this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries(Number(e)),r=(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number,a=await Promise.all(t.map(async({keyArgs:s,value:i})=>{let[,o]=s,l=i,c=await this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(o),d=await this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(Number(e),o,l);if(!c||!d)return;let m=c.reward_currency,p=c.incentivized_asset,g=this.getFarmAddress(o),y=await this.getOraclePrice(m,p),b=await this.balanceClient.getTokenBalance(g,m);return{id:e,globalFarm:c,yieldFarm:d,priceAdjustment:y,balance:b}}));return r?a.map(s=>s?this.farmData(s,r):void 0):[]}async getIsolatedFarms(e){let t=await this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries(e),r=(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number,a=await Promise.all(t.map(async({keyArgs:s,value:i})=>{let[,o]=s,l=i,c=await this.api.query.XYKWarehouseLM.GlobalFarm.getValue(o),d=await this.api.query.XYKWarehouseLM.YieldFarm.getValue(e,o,l);if(!c||!d)return;let m=c.reward_currency,p=c.incentivized_asset,g=this.getFarmAddress(o,!0),y=await this.getOraclePrice(m,p),b=await this.balanceClient.getBalance(g,m);return{id:e,globalFarm:c,yieldFarm:d,priceAdjustment:y,balance:b,farmAddress:g}}));return r?a.map(s=>s?this.farmData(s,r,!0):void 0):[]}async getDepositReward(e,t,n,r){let a=t.global_farm_id,s=t.yield_farm_id,i=n?await this.api.query.XYKWarehouseLM.YieldFarm.getValue(e,a,s):await this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(Number(e),a,s),o=n?await this.api.query.XYKWarehouseLM.GlobalFarm.getValue(a):await this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(a);if(!o||!i)return;let l=o.reward_currency,c=o.incentivized_asset,d=[[this.getFarmAddress(0,n),o.reward_currency],[this.getFarmAddress(o.id,n),o.reward_currency]],m=await vr(this.api,d)(),p=await this.getOraclePrice(l,c),g=new Lt(d,m),b=await new lt(S=>this.getFarmAddress(S),g,S=>this.api.query.AssetRegistry.Assets.getValue(S)).claim_rewards(o,i,t,r,p??o.price_adjustment);if(!b)return;let f=await this.api.query.AssetRegistry.Assets.getValue(b.assetId);if(f&&!b.reward.lte(f.existential_deposit.toString()))return b}},Dt=(0,M.default)(10).pow(18),Ct="0",vr=(u,e)=>async()=>{let[t,n]=await Promise.all([u.query.Tokens.Accounts.getValues(e.filter(([a,s])=>s.toString()!==Ct)),u.query.System.Account.getValues(e.filter(([a,s])=>s.toString()===Ct).map(([a])=>[a]))]),r=[];for(let a=0,s=0;a+s<e.length;){let i=a+s,[,o]=e[i];o.toString()===Ct?(r.push({assetId:o.toString(),free:n[s].data.free,reserved:n[s].data.reserved,frozen:n[s].data.frozen}),s+=1):(r.push({assetId:o.toString(),free:t[a].free,reserved:t[a].reserved,frozen:t[a].frozen}),a+=1)}return r},Lt=class{result=new Map;getKey(e,t){return[t,e.toString()].join(",")}constructor(e,t){for(let n=0;n<e.length;++n){let[r,a]=e[n];this.result.set(this.getKey(a,r),t[n].free)}}free_balance(e,t){return this.result.get(this.getKey(e,t))??0n}transfer(e,t,n,r){let a=this.getKey(e,t),s=this.getKey(e,n),i=this.result.get(a)??0n,o=this.result.get(s)??0n;if(i<r)throw new Error("Attempting to transfer more than is present");this.result.set(a,i+r),this.result.set(s,o+r)}};var Gt={};v(Gt,{AssetNotFound:()=>Nt,PoolNotFound:()=>Le,RouteNotFound:()=>qe});var Nt=class extends Error{constructor(e){super(),this.message=`${e} not found`,this.name="AssetNotFound"}},Le=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},qe=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in current configuration`,this.name="RouteNotFound"}};var Xt={};v(Xt,{PoolContextProvider:()=>Ie,PoolError:()=>ce,PoolFactory:()=>xe,PoolType:()=>k,aave:()=>Yt,lbp:()=>Vt,omni:()=>Ht,stable:()=>Ut,xyk:()=>Wt});var Vt={};v(Vt,{LbpMath:()=>Q,LbpPool:()=>Ne,LbpPoolClient:()=>Ge});var J=require("@galacticcouncil/math-lbp"),Q=class{static getSpotPrice(e,t,n,r,a){return(0,J.get_spot_price)(e,t,n,r,a)}static calculateInGivenOut(e,t,n,r,a){return(0,J.calculate_in_given_out)(e,t,n,r,a)}static calculateOutGivenIn(e,t,n,r,a){return(0,J.calculate_out_given_in)(e,t,n,r,a)}static calculateLinearWeights(e,t,n,r,a){return(0,J.calculate_linear_weights)(e,t,n,r,a)}static calculatePoolTradeFee(e,t,n){return(0,J.calculate_pool_trade_fee)(e,t,n)}};var k=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a))(k||{}),ce=(a=>(a.InsufficientTradingAmount="InsufficientTradingAmount",a.MaxInRatioExceeded="MaxInRatioExceeded",a.MaxOutRatioExceeded="MaxOutRatioExceeded",a.TradeNotAllowed="TradeNotAllowed",a.UnknownError="UnknownError",a))(ce||{});var Ne=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,n,r,a,s,i){this.type="LBP",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=a,this.fee=s,this.repayFeeApply=i}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(s=>[s.id,s])),r=n.get(e),a=n.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:r.balance,balanceOut:a.balance,decimalsIn:r.decimals,decimalsOut:a.decimals,weightIn:r.weight,weightOut:a.weight}}validateAndBuy(e,t,n){let r=this.tokens[0].id,a=[];t<this.minTradingLimit&&a.push("InsufficientTradingAmount");let s=e.balanceOut/this.maxOutRatio;if(t>s&&a.push("MaxOutRatioExceeded"),r===e.assetOut){let i=this.calculateTradeFee(t,n),o=P.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=t+i,c=this.calculateInGivenOut(e,l),d=e.balanceIn/this.maxInRatio;return c>d&&a.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:o,errors:a}}else{let i=this.calculateInGivenOut(e,t),o=e.balanceIn/this.maxInRatio;return i>o&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:i,amountOut:t,feePct:0,errors:a}}}validateAndSell(e,t,n){let r=this.tokens[0].id,a=[];t<this.minTradingLimit&&a.push("InsufficientTradingAmount");let s=e.balanceIn/this.maxInRatio;if(t>s&&a.push("MaxInRatioExceeded"),r===e.assetIn){let i=this.calculateOutGivenIn(e,t),o=e.balanceOut/this.maxOutRatio;return i>o&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:i,feePct:0,errors:a}}else{let i=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(i,n),l=P.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),c=i-o,d=e.balanceOut/this.maxOutRatio;return c>d&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:c,feePct:l,errors:a}}}calculateInGivenOut(e,t){let n=Q.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(e,t){let n=Q.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(e){let t=Q.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),this.maxOutRatio.toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=Q.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),this.maxInRatio.toString());return BigInt(t)}calculateTradeFee(e,t){let n=Q.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return BigInt(n)}};var In=require("polkadot-api"),ue=require("rxjs");var xn=(u,e=new Map)=>t=>{let n;return e.has(t)?e.get(t):(e.set(t,n=u(t)),n)};var O=require("rxjs");var W=class extends U{override=[];mem=0;memPools=xn(e=>(this.log(this.getPoolType(),"mem pools",e,"\u2705"),this.loadPools()));constructor(e){super(e)}async withOverride(e){this.override=e||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let e=(0,O.from)(this.getPoolsMem()).pipe((0,O.switchMap)(t=>this.subscribe(t)),(0,O.combineLatestAll)());return(0,O.firstValueFrom)(e)}getSubscriber(){return(0,O.from)(this.getPoolsMem()).pipe((0,O.switchMap)(e=>this.subscribe(e)),(0,O.mergeAll)())}subscribe(e){return e.filter(t=>this.hasValidAssets(t)).map(t=>(0,O.combineLatest)([this.subscribePoolChange(t),this.subscribePoolBalance(t)]).pipe((0,O.debounceTime)(250),(0,O.map)(([n,r])=>this.updatePool(n,r))))}subscribePoolBalance(e){if(e.type==="Aave")return(0,O.of)([]);let t=[this.subscribeTokensBalance(e.address)];if(this.hasSystemAsset(e)){let n=this.subscribeSystemBalance(e.address);t.push(n)}if(this.hasErc20Asset(e)){let n=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),r=this.subscribeErc20Balance(e.address,n);t.push(r)}return(0,O.combineLatest)(t).pipe((0,O.map)(n=>n.map(r=>Array.isArray(r)?r:[r]).flat()))}hasSystemAsset(e){return e.tokens.some(t=>t.id===0)}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}hasValidAssets(e){return e.tokens.every(({id:t,decimals:n,balance:r})=>{let a=this.override.find(i=>i.id===t),s=!!n||!!a?.decimals;return r>0n&&s})}updatePool=(e,t)=>{let n=e.tokens.map(r=>{let a=t.find(i=>i.id===r.id),s=this.override.find(i=>i.id===r.id);return a?{...r,balance:a.balance.transferable,decimals:r.decimals||s?.decimals}:{...r,decimals:r.decimals||s?.decimals}});return{...e,tokens:n}}};var Ge=class extends W{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[e,t,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),r=t?.relay_parent_number||0,a=e.filter(({value:s})=>t&&this.isActivePool(s,r)).map(async({keyArgs:s,value:i})=>{let[o]=s,l=o.toString(),c=await this.getPoolDelta(l,i,r);return{address:l,type:"LBP",fee:i.fee,...c,...n}});return Promise.all(a)}async getPoolDelta(e,t,n){let{start:r,end:a,assets:s,initial_weight:i,final_weight:o,repay_target:l,fee_collector:c}=t,d=Q.calculateLinearWeights(r?r.toString():"0",a?a.toString():"0",i.toString(),o.toString(),n.toString()),[m,p]=s,g=BigInt(d),y=this.MAX_FINAL_WEIGHT-BigInt(g),[b,f,S,w,A]=await Promise.all([this.isRepayFeeApplied(m,l,c.toString()),this.getBalance(e,m),this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,p),this.api.query.AssetRegistry.Assets.getValue(p)]);return{repayFeeApply:b,tokens:[{id:m,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:f.transferable,weight:g,type:S?.asset_type.type},{id:p,decimals:A?.decimals,existentialDeposit:A?.existential_deposit,balance:w.transferable,weight:y,type:A?.asset_type.type}]}}isActivePool(e,t){let{start:n,end:r}=e;return n&&r?t>=n&&t<r:!1}async isRepayFeeApplied(e,t,n){if(t===0n)return!1;try{return(await this.getBalance(n,e)).transferable<t}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(e){return{repayFee:await this.getRepayFee(),exchangeFee:e.fee}}getPoolType(){return"LBP"}async isSupported(){let e=this.api.query.LBP.PoolData,t=await this.api.compatibilityToken;return e.isCompatible(In.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(e.address);return n?t.watchValue("best").pipe((0,ue.switchMap)(r=>r?this.getPoolDelta(e.address,n,r.relay_parent_number):(0,ue.of)(e)),(0,ue.map)(r=>Object.assign({},e,r))):(0,ue.of)(e)}};var Ht={};v(Ht,{OmniMath:()=>B,OmniPool:()=>Ve,OmniPoolClient:()=>Ue});var x=require("@galacticcouncil/math-omnipool"),de=ie(require("big.js")),B=class{static calculateSpotPrice(e,t,n,r){return(0,x.calculate_spot_price)(e,t,n,r)}static calculateLrnaSpotPrice(e,t){return(0,x.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,n,r,a,s,i,o,l){return(0,x.calculate_in_given_out)(e,t,n,r,a,s,i,o,l)}static calculateLrnaInGivenOut(e,t,n,r,a){return(0,x.calculate_lrna_in_given_out)(e,t,n,r,a)}static calculateOutGivenIn(e,t,n,r,a,s,i,o,l){return(0,x.calculate_out_given_in)(e,t,n,r,a,s,i,o,l)}static calculateOutGivenLrnaIn(e,t,n,r,a){return(0,x.calculate_out_given_lrna_in)(e,t,n,r,a)}static calculateShares(e,t,n,r){return(0,x.calculate_shares)(e,t,n,r)}static calculateLiquidityOut(e,t,n,r,a,s,i,o){return(0,x.calculate_liquidity_out)(e,t,n,r,a,s,i,o)}static calculateLiquidityLRNAOut(e,t,n,r,a,s,i,o){return(0,x.calculate_liquidity_lrna_out)(e,t,n,r,a,s,i,o)}static calculateCapDifference(e,t,n,r){let a=(0,de.default)(t),s=(0,de.default)(e),i=(0,de.default)(r),o=(0,de.default)(n),l=(0,de.default)(10).pow(18),c=o.div(l);if(a.div(i).lt(c)){let m=c.times(i).minus(a).times(s),p=a.times((0,de.default)(1).minus(c));return m.div(p).toFixed(0)}else return"0"}static verifyAssetCap(e,t,n,r){return(0,x.verify_asset_cap)(e,t,n,r)}static calculateLimitHubIn(e,t,n,r){return(0,x.calculate_liquidity_hub_in)(e,t,n,r)}static isSellAllowed(e){return(0,x.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,x.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,x.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,x.is_remove_liquidity_allowed)(e)}};var Ve=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,n,r,a,s){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=a,this.hubAssetId=s}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let n=new Map(this.tokens.map(s=>[s.id,s])),r=n.get(e),a=n.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:a.hubReserves,sharesIn:r.shares,sharesOut:a.shares,decimalsIn:r.decimals,decimalsOut:a.decimals,balanceIn:r.balance,balanceOut:a.balance,tradeableIn:r.tradeable,tradeableOut:a.tradeable,assetInEd:r.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(e,t,n){let r=this.calculateInGivenOut(e,t),a=this.calculateInGivenOut(e,t,n),s=r===0n?0:_.calculateDiffToRef(a,r),i=[],o=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);(!o||!l)&&i.push("TradeNotAllowed"),(t<this.minTradingLimit||r<e.assetInEd)&&i.push("InsufficientTradingAmount");let c=e.balanceOut/this.maxOutRatio;t>c&&i.push("MaxOutRatioExceeded");let d=e.balanceIn/this.maxInRatio;return a>d&&i.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:r,amountOut:t,feePct:s,errors:i}}validateAndSell(e,t,n){let r=this.calculateOutGivenIn(e,t),a=this.calculateOutGivenIn(e,t,n),s=_.calculateDiffToRef(r,a),i=[],o=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);(!o||!l)&&i.push("TradeNotAllowed"),(t<this.minTradingLimit||r<e.assetOutEd)&&i.push("InsufficientTradingAmount");let c=e.balanceIn/this.maxInRatio;t>c&&i.push("MaxInRatioExceeded");let d=e.balanceOut/this.maxOutRatio;return a>d&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:a,feePct:s,errors:i}}calculateInGivenOut(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,n);let r=B.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?P.toDecimals(n.assetFee).toString():"0",n?P.toDecimals(n.protocolFee).toString():"0"),a=BigInt(r);return a<0n?0n:a}calculateLrnaInGivenOut(e,t,n){let r=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?P.toDecimals(n.assetFee).toString():"0"),a=BigInt(r);return a<0n?0n:a}calculateOutGivenIn(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,n);let r=B.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?P.toDecimals(n.assetFee).toString():"0",n?P.toDecimals(n.protocolFee).toString():"0"),a=BigInt(r);return a<0n?0n:a}calculateOutGivenLrnaIn(e,t,n){let r=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?P.toDecimals(n.assetFee).toString():"0"),a=BigInt(r);return a<0n?0n:a}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=B.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceLrnaInGivenOut(e){let t=B.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=B.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}spotPriceOutGivenLrnaIn(e){let t=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}};var ct=require("polkadot-api"),vn=require("@polkadot-api/utils"),He=require("rxjs");var Ue=class extends W{async loadPools(){let e=await this.api.constants.Omnipool.HubAssetId(),t=this.getPoolAddress(),[n,r,a,s,i]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(e),this.getBalance(t,e),this.getPoolLimits()]),o=n.map(async({keyArgs:c,value:d})=>{let[m]=c,{hub_reserve:p,shares:g,tradable:y,cap:b,protocol_shares:f}=d,[S,w]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(t,m)]);return{id:m,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:w.transferable,cap:b,hubReserves:p,protocolShares:f,shares:g,tradeable:y,type:S?.asset_type.type}}),l=await Promise.all(o);return l.push({id:e,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:s.transferable,tradeable:r,type:a?.asset_type.type}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:l,...i}]}getPoolAddress(){let e="modlomnipool".padEnd(32,"\0"),t=new TextEncoder().encode(e),n=(0,vn.toHex)(t);return(0,ct.AccountId)(63).dec(n)}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(e,t){let[n,r,a]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(t)]),s=n.min_fee+r.min_fee,i=n.max_fee+r.max_fee;if(a){let{asset_fee:o,protocol_fee:l}=a;return{assetFee:P.fromPermill(o),protocolFee:P.fromPermill(l),min:P.fromPermill(s),max:P.fromPermill(i)}}else return{assetFee:P.fromPermill(n.min_fee),protocolFee:P.fromPermill(r.min_fee),min:P.fromPermill(s),max:P.fromPermill(i)}}getPoolType(){return"Omnipool"}async isSupported(){let e=this.api.query.Omnipool.Assets,t=await this.api.compatibilityToken;return e.isCompatible(ct.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,He.distinctUntilChanged)((n,r)=>!r.deltas),(0,He.map)(({entries:n})=>n.map(r=>{let[a]=r.args,{hub_reserve:s,shares:i,tradable:o,cap:l,protocol_shares:c}=r.value,d=e.tokens.findIndex(p=>p.id===a);return{...e.tokens[d],cap:l,hubReserves:s,protocolShares:c,shares:i,tradeable:o}})),(0,He.map)(n=>{let r=e.tokens.find(a=>a.id===1);return{...e,tokens:[...n,r]}}))}};var Ut={};v(Ut,{StableMath:()=>D,StableSwap:()=>We,StableSwapClient:()=>Ye});var F=require("@galacticcouncil/math-stableswap"),D=class{static getPoolAddress(e){return(0,F.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let n=0;n<e;n++)t.push(["1","1"]);return t}static calculateAmplification(e,t,n,r,a){return(0,F.calculate_amplification)(e,t,n,r,a)}static calculateInGivenOut(e,t,n,r,a,s,i){return(0,F.calculate_in_given_out)(e,t,n,r,a,s,i)}static calculateAddOneAsset(e,t,n,r,a,s,i){return(0,F.calculate_add_one_asset)(e,t,n,r,a,s,i)}static calculateSharesForAmount(e,t,n,r,a,s,i){return(0,F.calculate_shares_for_amount)(e,t,n,r,a,s,i)}static calculateOutGivenIn(e,t,n,r,a,s,i){return(0,F.calculate_out_given_in)(e,t,n,r,a,s,i)}static calculateLiquidityOutOneAsset(e,t,n,r,a,s,i){return(0,F.calculate_liquidity_out_one_asset)(e,t,n,r,a,s,i)}static calculateShares(e,t,n,r,a,s){return(0,F.calculate_shares)(e,t,n,r,a,s)}static calculateSpotPriceWithFee(e,t,n,r,a,s,i,o){return(0,F.calculate_spot_price_with_fee)(e,t,n,r,a,s,i,o)}static recalculatePegs(e,t,n,r,a){let s=(0,F.recalculate_peg)(e,t,n,r,a);return JSON.parse(s)}};var We=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,n,r,a,s,i,o,l){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=a,this.amplification=s,this.id=i,this.fee=o,this.totalIssuance=l}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(s=>[s.id,s])),r=n.get(e),a=n.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:r.balance,balanceOut:a.balance,decimalsIn:r.decimals,decimalsOut:a.decimals,tradeableIn:this.id===e?15:r.tradeable,tradeableOut:this.id===t?15:a.tradeable,assetInEd:r.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(e,t,n){let r=this.calculateInGivenOut(e,t),a=this.calculateInGivenOut(e,t,n),s=P.toPct(n.fee),i=[],o=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!o||!l)&&i.push("TradeNotAllowed"),(t<this.minTradingLimit||r<e.assetInEd)&&i.push("InsufficientTradingAmount"),{amountIn:a,calculatedIn:r,amountOut:t,feePct:s,errors:i}}validateAndSell(e,t,n){let r=this.calculateOutGivenIn(e,t),a=this.calculateOutGivenIn(e,t,n),s=P.toPct(n.fee),i=[],o=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!o||!l)&&i.push("TradeNotAllowed"),(t<this.minTradingLimit||r<e.assetOutEd)&&i.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:a,feePct:s,errors:i}}calculateIn(e,t,n){let r=D.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?P.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(r);return a<0n?0n:a}calculateAddOneAsset(e,t,n){let r=D.calculateAddOneAsset(this.getReserves(),t.toString(),Number(e.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?P.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(r);return a<0n?0n:a}calculateSharesForAmount(e,t,n){let r=D.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?P.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(r);return a<0n?0n:a}calculateInGivenOut(e,t,n){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,n):e.assetIn==this.id?this.calculateSharesForAmount(e,t,n):this.calculateIn(e,t,n)}spotPriceInGivenOut(e){let t=D.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetOut.toString(),e.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(e.assetOut==this.id)return BigInt(t);if(e.assetIn==this.id){let r=Math.pow(10,e.decimalsIn-e.decimalsOut);return BigInt(t)/BigInt(r)}let n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateOut(e,t,n){let r=D.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?P.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(r);return a<0n?0n:a}calculateWithdrawOneAsset(e,t,n){let r=D.calculateLiquidityOutOneAsset(this.getReserves(),t.toString(),Number(e.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?P.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(r);return a<0n?0n:a}calculateShares(e,t,n){let r=D.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification.toString(),this.totalIssuance.toString(),n?P.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(r);return a<0n?0n:a}calculateOutGivenIn(e,t,n){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,n):e.assetOut==this.id?this.calculateShares(e,t,n):this.calculateOut(e,t,n)}spotPriceOutGivenIn(e){let t=D.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetIn.toString(),e.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(e.assetIn==this.id)return BigInt(t);if(e.assetOut==this.id){let r=Math.pow(10,e.decimalsOut-e.decimalsIn);return BigInt(t)/BigInt(r)}let n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}getPegs(){let e=D.defaultPegs(this.tokens.length-1);return JSON.stringify(e)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:n,decimals:r})=>({asset_id:t,amount:n,decimals:r}));return JSON.stringify(e,ae.jsonFormatter)}getAssets(e,t){let n={asset_id:Number(e),amount:t.toString()};return JSON.stringify([n],ae.jsonFormatter)}};var ut=require("polkadot-api"),On=require("@polkadot-api/utils"),An=require("@noble/hashes/blake2b"),we=require("rxjs");var Or=340282366920938463463374607431768211455n,Ye=class extends W{poolsData=new Map([]);async loadPools(){let[e,t,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),r=e.map(async({keyArgs:a,value:s})=>{let[i]=a,o=this.getPoolAddress(i),[l,c,d]=await Promise.all([this.getPoolDelta(i,s,t),this.getPoolTokens(i,s),this.getPoolPegs(i,s,t)]);return this.poolsData.set(o,s),{address:o,id:i,type:"Stableswap",fee:P.fromPermill(s.fee),tokens:c,...l,...d,...n}});return Promise.all(r)}async getPoolDelta(e,t,n){let{initial_amplification:r,final_amplification:a,initial_block:s,final_block:i}=t,o=D.calculateAmplification(r.toString(),a.toString(),s.toString(),i.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(e);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(e,t){let n=this.getPoolAddress(e),r=t.assets.map(async i=>{let[o,l,c]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(e,i),this.api.query.AssetRegistry.Assets.getValue(i),this.getBalance(n,i)]);return{id:i,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:c.transferable,tradeable:o,type:l?.asset_type.type}}),a=await Promise.all(r),s=await this.api.query.AssetRegistry.Assets.getValue(e);return a.push({id:e,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:Or,tradeable:15,type:s?.asset_type.type}),a}async getPoolPegs(e,t,n){let r=await this.api.query.Stableswap.PoolPegs.getValue(e);if(!r)return this.getDefaultPegs(t);let a=await this.getLatestPegs(t,r,n),s=this.getRecentPegs(r),i=P.fromPermill(r.max_peg_update),o=P.fromPermill(t.fee),[l,c]=D.recalculatePegs(JSON.stringify(s),JSON.stringify(a),n.toString(),P.toDecimals(i).toString(),P.toDecimals(o).toString()),d=Number(l)*1e6;return{pegsFee:P.fromPermill(d),pegs:c}}getDefaultPegs(e){let t=e.fee,n=D.defaultPegs(e.assets.length);return{pegsFee:P.fromPermill(t),pegs:n}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([n,r])=>r.map(a=>a.toString()))}async getLatestPegs(e,t,n){let{source:r}=t,a=Array.from(e.assets.entries()).map(([i,o])=>o),s=r.map(async(i,o)=>{if(i.type==="Oracle"){let[l,c,d]=i.value,m=[d,a[o]].sort((S,w)=>S-w),p=await this.api.query.EmaOracle.Oracles.getValue(l,m,c);if(!p)return;let[{price:g,updated_at:y}]=p,b=g.n.toString(),f=g.d.toString();return d.toString()===m[0].toString()?[[b,f],y.toString()]:[[f,b],y.toString()]}else return[i.value.map(l=>l.toString()),n]});return Promise.all(s)}getPoolAddress(e){let t=D.getPoolAddress(e),n=(0,An.blake2b)(t,{dkLen:32}),r=(0,On.toHex)(n);return(0,ut.AccountId)(63).dec(r)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(e){return{fee:e.fee}}getPoolType(){return"Stableswap"}async isSupported(){let e=this.api.query.Stableswap.Pools,t=await this.api.compatibilityToken;return e.isCompatible(ut.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.System.Number,n=this.poolsData.get(e.address);return!n||!e.id?(0,we.of)(e):t.watchValue("best").pipe((0,we.switchMap)(r=>this.getPoolDelta(e.id,n,r)),(0,we.map)(r=>Object.assign({},e,r)))}};var Wt={};v(Wt,{XykMath:()=>te,XykPool:()=>Xe,XykPoolClient:()=>ze});var R=require("@galacticcouncil/math-xyk"),te=class{static getSpotPrice(e,t,n){return(0,R.get_spot_price)(e,t,n)}static calculateInGivenOut(e,t,n){return(0,R.calculate_in_given_out)(e,t,n)}static calculateOutGivenIn(e,t,n){return(0,R.calculate_out_given_in)(e,t,n)}static calculatePoolTradeFee(e,t,n){return(0,R.calculate_pool_trade_fee)(e,t,n)}static calculateLiquidityIn(e,t,n){return(0,R.calculate_liquidity_in)(e,t,n)}static calculateSpotPrice(e,t){return(0,R.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,n,r){return(0,R.calculate_spot_price_with_fee)(e,t,n,r)}static calculateShares(e,t,n){return(0,R.calculate_shares)(e,t,n)}static calculateLiquidityOutAssetA(e,t,n,r){return(0,R.calculate_liquidity_out_asset_a)(e,t,n,r)}static calculateLiquidityOutAssetB(e,t,n,r){return(0,R.calculate_liquidity_out_asset_b)(e,t,n,r)}};var Xe=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,n,r,a){this.type="XYK",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=a}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(s=>[s.id,s])),r=n.get(e),a=n.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:a.decimals,balanceIn:r.balance,balanceOut:a.balance,assetInEd:r.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(e,t,n){let r=this.calculateInGivenOut(e,t),a=this.calculateTradeFee(r,n),s=P.toPct(n.exchangeFee),i=r+a,o=[];(t<this.minTradingLimit||r<e.assetInEd)&&o.push("InsufficientTradingAmount");let l=e.balanceOut/this.maxOutRatio;t>l&&o.push("MaxOutRatioExceeded");let c=e.balanceIn/this.maxInRatio;return i>c&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:s,errors:o}}validateAndSell(e,t,n){let r=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(r,n),s=P.toPct(n.exchangeFee),i=r-a,o=[];(t<this.minTradingLimit||r<e.assetOutEd)&&o.push("InsufficientTradingAmount");let l=e.balanceIn/this.maxInRatio;t>l&&o.push("MaxInRatioExceeded");let c=e.balanceOut/this.maxOutRatio;return i>c&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:s,errors:o}}calculateInGivenOut(e,t){let n=te.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(e,t){let n=te.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(e){let t=te.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){let t=te.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateTradeFee(e,t){let n=te.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return BigInt(n)}};var _n=require("polkadot-api"),Bn=require("rxjs");var ze=class extends W{async loadPools(){let e=this.api.query.XYK.PoolAssets,[t,n]=await Promise.all([e.getEntries(),this.getPoolLimits()]),r=t.map(async({keyArgs:a,value:s})=>{let[i]=a,[o,l]=s,[c,d,m,p]=await Promise.all([this.getBalance(i,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(i,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:i,type:"XYK",tokens:[{id:o,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:c.transferable,type:d?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:m.transferable,type:p?.asset_type.type}],...n}});return Promise.all(r)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let e=this.api.query.XYK.PoolAssets,t=await this.api.compatibilityToken;return e.isCompatible(_n.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){return(0,Bn.of)(e)}};var Yt={};v(Yt,{AavePool:()=>Ke,AavePoolClient:()=>je});var Ke=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,n,r,a){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=a}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(s=>[s.id,s])),r=n.get(e),a=n.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:r.balance,balanceOut:a.balance,decimalsIn:r.decimals,decimalsOut:a.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(e,t,n){let r=this.calculateInGivenOut(e,t),a=[];return t>e.balanceOut&&a.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:a}}validateAndSell(e,t,n){let r=this.calculateOutGivenIn(e,t),a=[];return r>e.balanceOut&&a.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:a}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){let t=Math.pow(10,e.decimalsOut);return BigInt(t)}spotPriceOutGivenIn(e){let t=Math.pow(10,e.decimalsIn);return BigInt(t)}calculateTradeFee(e,t){return 0n}};var Rn=require("polkadot-api"),kn=require("@polkadot-api/utils"),Te=require("rxjs"),En=require("viem");var Fn=[{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:Ar}=oe,_r=["Supply","Withdraw","Repay","Borrow"],je=class extends W{async loadPools(){let t=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:r,liqudity_in:a,liqudity_out:s})=>{let[i,o,l,c]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(r),this.api.query.AssetRegistry.AssetLocations.getValue(r)]);return{address:this.getPoolId(n,r),type:"Aave",tokens:[{id:n,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:a,location:o,type:i?.asset_type.type},{id:r,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:s,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolDelta(e){let[t,n]=e.tokens,{liqudity_in:r,liqudity_out:a}=await this.api.apis.AaveTradeExecutor.pool(t.id,n.id);return e.tokens.map(s=>{let i=s.id===t.id?r:a;return{...s,balance:i}})}getPoolId(e,t){let n=e+"/"+t,r=new TextEncoder().encode(n.padEnd(32,"\0")),a=(0,kn.toHex)(r);return(0,Rn.AccountId)(63).dec(a)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(e){let[t,n]=e.tokens,r=this.getReserveH160Id(t),a=this.api.event.Router.Executed.watch(({asset_in:i,asset_out:o})=>i===n.id||o===n.id),s=this.api.event.EVM.Log.watch(({log:i})=>{let{topics:o,data:l}=i,c=o.map(g=>g.asHex()),d=l.asHex(),{eventName:m,args:p}=(0,En.decodeEventLog)({abi:Fn,topics:c,data:d});return _r.includes(m)&&p.reserve.toLowerCase()===r.toLowerCase()});return(0,Te.merge)([a,s]).pipe((0,Te.switchMap)(()=>this.getPoolDelta(e)),(0,Te.map)(i=>({...e,tokens:[...i]})))}getReserveH160Id(e){return e.type==="Erc20"?ae.findNestedKey(e.location,"AccountKey20").AccountKey20.key:Ar.fromAssetId(e.id)}};var xe=class{static get(e){switch(e.type){case"Aave":return Ke.fromPool(e);case"XYK":return Xe.fromPool(e);case"Omnipool":return Ve.fromPool(e);case"LBP":return Ne.fromPool(e);case"Stableswap":return We.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Z=require("rxjs");var Ie=class extends C{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=Z.Subscription.EMPTY;omniSub=Z.Subscription.EMPTY;stableSub=Z.Subscription.EMPTY;xykSub=Z.Subscription.EMPTY;aaveSub=Z.Subscription.EMPTY;isReady=!1;isDestroyed=new Z.Subject;constructor(e){super(e),this.lbpClient=new Ge(e),this.omniClient=new Ue(e),this.stableClient=new Ye(e),this.xykClient=new ze(e),this.aaveClient=new je(e),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(e){return e.getSubscriber().pipe((0,Z.takeUntil)(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(e){return this.xykClient.withOverride(e),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(e={}){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let{useOnly:t=[],exclude:n=[]}=e,r=new Set(t),a=new Set(n),s=async i=>{let o=i.getPoolType();return r.size>0?r.has(o):a.size>0?!a.has(o):i.isSupported()};return this.getFilteredPools(s)}async getFilteredPools(e){let t=await Promise.all(this.clients.map(e)),n=this.clients.filter((a,s)=>t[s]);return(await Promise.all(n.map(a=>a.getPoolsMem()))).flat()}async getPoolFees(e,t){let n=this.clients.find(r=>r.getPoolType()===e.type);if(n)return n.getPoolFees(e,t);throw new Le(e.type)}};var Zt={};v(Zt,{DEFAULT_BLOCK_TIME:()=>Dn,DEFAULT_MIN_BUDGET:()=>jt,ORDER_MIN_BLOCK_PERIOD:()=>Cn,Router:()=>ve,TWAP_BLOCK_PERIOD:()=>Ze,TWAP_MAX_DURATION:()=>$t,TWAP_MAX_PRICE_IMPACT:()=>Qt,TWAP_TX_MULTIPLIER:()=>ql,TradeOrderError:()=>Kt,TradeOrderType:()=>pt,TradeRouteBuilder:()=>Y,TradeRouter:()=>Oe,TradeScheduler:()=>Ae,TradeType:()=>dt});var Qe=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Br=8,$e=class{isNotVisited(e,t){let n=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(n=!1)}),n}findPaths(e,t,n){let r=[],a=new Qe,s=[];for(s.push([t,""]),a.enqueue(s);a.size()>0;){let i=a.dequeue();if(!i||i.length>Br)continue;let o=i[i.length-1];(n===null||o[0]===n)&&r.push(i),e.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,i)){let d=[...i];d.push(c),a.enqueue(d)}})}return r}findShortestPaths(e,t,n){let r=[],a=new Qe,s=[];s.push([t,""]),a.enqueue(s);let i=1/0;for(;a.size()>0;){let o=a.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===n){o.length<i?(i=o.length,r.length=0,r.push(o)):o.length===i&&r.push(o);continue}let c=e.get(l[0]);for(let d of c??[])this.isNotVisited(d,o)&&a.enqueue([...o,d])}return r}buildAndPopulateGraph(e,t){let n=new Map;for(let r of e)n.set(parseInt(r),[]);for(let[r,a,s]of t)n.get(a)?.push([s,r]);return n}};function zt(u){let e={};for(let t of u){let n=t.tokens.length;for(let r=0;r<n;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let a=0;a<n;a++){if(r==a)continue;let s=[t.address,t.tokens[r].id,t.tokens[a].id];e[t.tokens[r].id].push(s)}}}return e}var Je=class{getProposals(e,t,n){let r=n.filter(b=>b.type==="XYK"),a=n.filter(b=>b.type!=="XYK"),s=new Set(a.map(b=>b.tokens).flat().map(b=>b.id)),i=s.has(e),o=s.has(t),l=new $e,c=b=>{let f=zt(b),S=Object.keys(f),w=S.flatMap(A=>f[A]);return l.buildAndPopulateGraph(S,w)};if(!i&&!o){let b=r.filter(w=>w.tokens.find(A=>A.id===e)||w.tokens.find(A=>A.id===t)),f=c(b),S=l.findPaths(f,e,t);return this.parsePaths(S)}if(i&&o){let b=c(a),f=l.findPaths(b,e,t);return this.parsePaths(f)}let d=i?t:e,m=r.filter(b=>b.tokens.some(f=>f.id===d));if(m.length===0)return[];let p=[...a,...m],g=c(p),y=l.findPaths(g,e,t);return this.parsePaths(y)}parsePaths(e){let t=[];for(let n of e){let r=[];for(let a=0;a<n.length;a++){let s=n[a],i=n[a+1];if(i==null)break;r.push(this.toEdge(s,i))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0],t[0]]}};var ve=class{routeSuggester;routeProposals;routerOptions;ctx;constructor(e,t={}){this.ctx=e,this.routeSuggester=new Je,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}buildRouteKey(e,t,n){return`${e}->${t}::${n.length}`}async getPools(){return this.ctx.getPools(this.routerOptions)}async getRoutes(e,t){let n=await this.getPools();return this.validateInput(e,t,n),this.getPaths(e,t,n)}async getTradeableAssets(){let e=await this.getPools(),t=this.getAssets(e);return Array.from(t)}async getRouteableAssets(e){let t=await this.getTradeableAssets();return(await Promise.all(t.filter(r=>r!==e).map(r=>this.getRoutes(r,e)))).filter(r=>r.length>0).map(([r])=>r[0].assetIn).sort()}validateInput(e,t,n){if(n.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let r=this.getAssets(n);if(!r.has(e))throw new Error(e+" is not supported asset");if(!r.has(t))throw new Error(t+" is not supported asset");return this.toPoolsMap(n)}getAssets(e){let t=e.map(n=>n.tokens.map(r=>r.id)).flat().sort((n,r)=>n>r?1:-1);return new Set(t)}getPaths(e,t,n){let r=this.toPoolsMap(n);return this.getProposals(e,t,n).filter(s=>this.validPath(s,r)).map(s=>this.toHops(s,r))}getProposals(e,t,n){let r=this.buildRouteKey(e,t,n);if(this.routeProposals.has(r))return this.routeProposals.get(r);let a=this.routeSuggester.getProposals(e,t,n);return this.routeProposals.set(r,a),a}validPath(e,t){return e.length>0&&e.map(n=>this.validEdge(n,t)).reduce((n,r)=>n&&r)}validEdge([e,t,n],r){return r.get(e)?.validatePair(t,n)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,xe.get(t)]))}toHops(e,t){return e.map(([n,r,a])=>{let s=t.get(n);return{poolAddress:n,poolId:s?.id,pool:s?.type,assetIn:r,assetOut:a}})}};var dt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(dt||{}),pt=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(pt||{}),Kt=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(Kt||{});var Oe=class extends ve{mlr;poolsSnapshot;constructor(e,t={}){super(e,t),this.mlr=new Map}buildCtxSync(e,t){let n=this.poolsSnapshot,r=super.validateInput(e,t,n),a=super.getPaths(e,t,n);if(!a.length)throw new qe(e,t);return{paths:a,pools:n,poolsMap:r}}async withCtx(e,t,n){this.poolsSnapshot||(this.poolsSnapshot=await super.getPools());let r=this.buildCtxSync(e,t);return n(r)}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((n,r)=>{let a=n[n.length-1].amountOut,s=r[r.length-1].amountOut;return a>s?-1:1});return t.find(n=>n.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(n=>n.tradeFeeRange).length>0){let n=e.map(a=>a.tradeFeeRange?.[0]??a.tradeFeePct).reduce((a,s)=>a+s),r=e.map(a=>a.tradeFeeRange?.[1]??a.tradeFeePct).reduce((a,s)=>a+s);return[n,r]}}getPoolFeeRange(e){let t=e.min?P.toPct(e.min):void 0,n=e.max?P.toPct(e.max):void 0;if(t&&n)return[t,n]}async getBestSell(e,t,n){return this.getSell(e,t,n)}getSellSpot(e){let t=e[e.length-1];if(e.length===1)return t.spotPrice;let n=e.map(i=>i.assetOutDecimals).reduce((i,o)=>i+o),r=e.map(i=>i.spotPrice).reduce((i,o)=>i*o),a=n-t.assetOutDecimals,s=Math.pow(10,a);return r/BigInt(s)}async getSell(e,t,n,r){return this.withCtx(e,t,async({paths:a,poolsMap:s})=>{let i;if(r)i=await this.toSellSwaps(n,r,s);else{let o=a.map(c=>this.toSellSwaps(n,c,s)),l=await Promise.all(o);i=this.findBestSellRoute(l)}return this.buildSell(s,i)})}buildSell(e,t){let n=t[0],r=t[t.length-1],a=this.isDirectTrade(t),s=this.getSellSpot(t),i=r.amountOut,o=a?r.calculatedOut:this.calculateDelta0Y(n.amountIn,t,e),l=o-i,c=this.getRouteFeeRange(t),d=a?r.tradeFeePct:_.calculateSellFee(o,i),m=Math.pow(10,n.assetInDecimals),p=n.amountIn*s/BigInt(m),g=_.calculateDiffToRef(o,p);return{type:"Sell",amountIn:n.amountIn,amountOut:r.amountOut,spotPrice:s,tradeFee:l,tradeFeePct:d,tradeFeeRange:c,priceImpactPct:g,swaps:t,toHuman(){return{type:"Sell",amountIn:h.toDecimal(n.amountIn,n.assetInDecimals),amountOut:h.toDecimal(r.amountOut,r.assetOutDecimals),spotPrice:h.toDecimal(s,r.assetOutDecimals),tradeFee:h.toDecimal(l,r.assetOutDecimals),tradeFeePct:d,tradeFeeRange:c,priceImpactPct:g,swaps:t.map(y=>y.toHuman())}}}}calculateDelta0Y(e,t,n){let r=[];for(let a=0;a<t.length;a++){let s=t[a],i=n.get(s.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(s.assetIn,s.assetOut),l;a>0?l=r[a-1]:l=e;let c=i.calculateOutGivenIn(o,l);r.push(c)}return r[r.length-1]}async calculateMostLiquidRoute(e,t,n){let{paths:r,pools:a,poolsMap:s}=n,l=a.filter(y=>y.tokens.some(b=>b.id===e)).map(y=>y.type==="Aave"?y.tokens:y.tokens.filter(b=>b.id===e)).map(y=>y.map(b=>b.balance).reduce((b,f)=>b+f)).sort((y,b)=>b<y?-1:1)[0],c=_.getFraction(l,.1),d=await Promise.all(r.map(y=>this.toSellSwaps(c,y,s))),p=this.findBestSellRoute(d).map(y=>({poolAddress:y.poolAddress,poolId:y?.poolId,pool:y.pool,assetIn:y.assetIn,assetOut:y.assetOut})),g=this.buildRouteKey(e,t,a);return this.mlr.set(g,p),p}async toSellSwaps(e,t,n){let r=[];for(let a=0;a<t.length;a++){let s=t[a],i=n.get(s.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(s.assetIn,s.assetOut),l;a>0?l=r[a-1].amountOut:l=typeof e=="string"?h.toBigInt(e,o.decimalsIn):e;let c=await this.ctx.getPoolFees(i,o.assetOut),{amountOut:d,calculatedOut:m,feePct:p,errors:g}=i.validateAndSell(o,l,c),y=this.getPoolFeeRange(c),b=i.spotPriceOutGivenIn(o),f=Math.pow(10,o.decimalsIn),S=l*b/BigInt(f),w=_.calculateDiffToRef(m,S);r.push({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:d,calculatedOut:m,spotPrice:b,tradeFeePct:p,tradeFeeRange:y,priceImpactPct:w,errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===s.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===s.assetIn},toHuman(){return{...s,amountIn:h.toDecimal(l,o.decimalsIn),amountOut:h.toDecimal(d,o.decimalsOut),calculatedOut:h.toDecimal(m,o.decimalsOut),spotPrice:h.toDecimal(b,o.decimalsOut),tradeFeePct:p,tradeFeeRange:y,priceImpactPct:w,errors:g}}})}return r}async getMostLiquidRoute(e,t){return this.withCtx(e,t,async n=>{let r=this.buildRouteKey(e,t,n.pools),a=this.mlr.get(r);return a||this.calculateMostLiquidRoute(e,t,n)})}async getSpotPrice(e,t){return this.withCtx(e,t,async n=>{let{pools:r,poolsMap:a}=n,s=this.buildRouteKey(e,t,r),i=this.mlr.get(s);i||(i=await this.calculateMostLiquidRoute(e,t,n));let o=await this.toSellSwaps("1",i,a),l=this.getSellSpot(o),c=o[o.length-1].assetOutDecimals;return{amount:l,decimals:c}})}findBestBuyRoute(e){let t=e.sort((n,r)=>{let a=n[0].amountIn,s=r[0].amountIn;return a>s?1:-1});return t.find(n=>n.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,n){return this.getBuy(e,t,n)}getBuySpot(e){let t=e[0];if(e.length===1)return t.spotPrice;let n=e.map(i=>i.assetInDecimals).reduce((i,o)=>i+o),r=e.map(i=>i.spotPrice).reduce((i,o)=>i*o),a=n-t.assetInDecimals,s=Math.pow(10,a);return r/BigInt(s)}async getBuy(e,t,n,r){return this.withCtx(e,t,async({paths:a,poolsMap:s})=>{let i;if(r)i=await this.toBuySwaps(n,r,s);else{let o=a.map(c=>this.toBuySwaps(n,c,s)),l=await Promise.all(o);i=this.findBestBuyRoute(l)}return this.buildBuy(s,i)})}buildBuy(e,t){let n=t[t.length-1],r=t[0],a=this.isDirectTrade(t),s=this.getBuySpot(t),i=r.amountIn,o=a?r.calculatedIn:this.calculateDelta0X(n.amountOut,t,e),l=i-o,c=this.getRouteFeeRange(t),d=a?r.tradeFeePct:_.calculateBuyFee(o,i),m=Math.pow(10,n.assetOutDecimals),p=n.amountOut*s/BigInt(m),g;return o===0n?g=-100:g=_.calculateDiffToRef(p,o),{type:"Buy",amountOut:n.amountOut,amountIn:r.amountIn,spotPrice:s,tradeFee:l,tradeFeePct:d,tradeFeeRange:c,priceImpactPct:g,swaps:t,toHuman(){return{type:"Buy",amountOut:h.toDecimal(n.amountOut,n.assetOutDecimals),amountIn:h.toDecimal(r.amountIn,r.assetInDecimals),spotPrice:h.toDecimal(s,r.assetInDecimals),tradeFee:h.toDecimal(l,r.assetInDecimals),tradeFeePct:d,tradeFeeRange:c,priceImpactPct:g,swaps:t.map(y=>y.toHuman())}}}}calculateDelta0X(e,t,n){let r=[];for(let a=t.length-1;a>=0;a--){let s=t[a],i=n.get(s.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(s.assetIn,s.assetOut),l;a==t.length-1?l=e:l=r[0];let c=i.calculateInGivenOut(o,l);r.unshift(c)}return r[0]}async toBuySwaps(e,t,n){let r=[];for(let a=t.length-1;a>=0;a--){let s=t[a],i=n.get(s.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(s.assetIn,s.assetOut),l;a==t.length-1?l=typeof e=="string"?h.toBigInt(e,o.decimalsOut):e:l=r[0].amountIn;let c=await this.ctx.getPoolFees(i,o.assetOut),{amountIn:d,calculatedIn:m,feePct:p,errors:g}=i.validateAndBuy(o,l,c),y=this.getPoolFeeRange(c),b=i.spotPriceInGivenOut(o),f=Math.pow(10,o.decimalsOut),S=l*b/BigInt(f),w;m===0n?w=-100:w=_.calculateDiffToRef(S,m),r.unshift({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:d,calculatedIn:m,spotPrice:b,tradeFeePct:p,tradeFeeRange:y,priceImpactPct:w,errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===s.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===s.assetIn},toHuman(){return{...s,amountOut:h.toDecimal(l,o.decimalsOut),amountIn:h.toDecimal(d,o.decimalsIn),calculatedIn:h.toDecimal(m,o.decimalsIn),spotPrice:h.toDecimal(b,o.decimalsIn),tradeFeePct:p,tradeFeeRange:y,priceImpactPct:w,errors:g}}})}return r}};var Dn=6e3,jt=1000000000000000n,Ze=6,Qt=-5,$t=216e5,ql=3,Cn=6;var Jt=require("polkadot-api");var Y=class{static build(e){return e.map(({assetIn:t,assetOut:n,pool:r,poolId:a})=>r==="Stableswap"?{pool:(0,Jt.Enum)("Stableswap",a),asset_in:t,asset_out:n}:{pool:(0,Jt.Enum)(r),asset_in:t,asset_out:n})}};var Ae=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??6e3,minBudgetInNative:t.minBudgetInNative??jt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,n,r,a){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:o,swaps:l,priceImpactPct:c}=i,d=l[0],m=l[l.length-1],{assetInDecimals:p}=d,{assetOutDecimals:g}=m,y=Math.abs(c),b=this.getMinimumTradeCount(o,s),f=this.getOptimalTradeCount(y),S=a?Math.round(r/a):f,w=Math.ceil(r/b),A=Math.round(r/f),q=Math.round(r/S),H=o/BigInt(S),L=await this.router.getBestSell(e,t,H),X=o<s,z=[];X&&z.push("OrderTooSmall");let ne=L.amountOut*BigInt(S),Fe=this.toBlockPeriod(q),se=L.tradeFee*BigInt(S),yt=Y.build(l),Re={assetIn:e,assetOut:t,errors:z,frequencyMin:w,frequencyOpt:A,frequency:q,tradeCount:S,tradeFee:se,tradeImpactPct:L.priceImpactPct,tradePeriod:Fe,tradeRoute:yt,type:"Dca"};return{...Re,amountIn:o,amountOut:ne,tradeAmountIn:L.amountIn,tradeAmountOut:L.amountOut,toHuman(){return{...Re,amountIn:h.toDecimal(o,p),amountOut:h.toDecimal(ne,g),tradeAmountIn:h.toDecimal(L.amountIn,p),tradeAmountOut:h.toDecimal(L.amountOut,g)}}}}async getMinimumOrderBudget(e){if(0===e)return this.minOrderBudget;let t=await this.router.getSpotPrice(0,e),n=10n**BigInt(12);if(t)return this.minOrderBudget*t.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let n=t*2n/10n;if(n===0n)return 0;let r=e+n/2n;return Number(r/n)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,n){let[r,a]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:s,swaps:i,priceImpactPct:o}=a,l=i[0],c=i[i.length-1],{assetInDecimals:d}=l,{assetOutDecimals:m}=c,p=Math.abs(o),g=this.getTwapTradeCount(p),y=s/BigInt(g),b=await this.router.getBestSell(l.assetIn,c.assetOut,y),f=g===1,S=s<r,w=b.priceImpactPct<-5,A=[];S||f?A.push("OrderTooSmall"):w&&A.push("OrderImpactTooBig");let q=b.amountOut*BigInt(g),H=b.tradeFee*BigInt(g),L=Y.build(i),X={assetIn:e,assetOut:t,errors:A,tradeCount:g,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:L,type:"TwapSell"};return{...X,amountIn:s,amountOut:q,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:H,toHuman(){return{...X,amountIn:h.toDecimal(s,d),amountOut:h.toDecimal(q,m),tradeAmountIn:h.toDecimal(b.amountIn,d),tradeAmountOut:h.toDecimal(b.amountOut,m),tradeFee:h.toDecimal(H,m)}}}}async getTwapBuyOrder(e,t,n){let[r,a]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,n)]),{amountOut:s,swaps:i,priceImpactPct:o}=a,l=i[0],c=i[i.length-1],{assetInDecimals:d}=l,{assetOutDecimals:m}=c,p=Math.abs(o),g=this.getTwapTradeCount(p),y=s/BigInt(g),b=await this.router.getBestBuy(l.assetIn,c.assetOut,y),f=b.amountIn*BigInt(g),S=g===1,w=f<r,A=b.priceImpactPct<-5,q=[];w||S?q.push("OrderTooSmall"):A&&q.push("OrderImpactTooBig");let H=b.tradeFee*BigInt(g),L=Y.build(i),X={assetIn:e,assetOut:t,errors:q,tradeCount:g,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:L,type:"TwapBuy"};return{...X,amountIn:f,amountOut:s,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:H,toHuman(){return{...X,amountIn:h.toDecimal(f,d),amountOut:h.toDecimal(s,m),tradeAmountIn:h.toDecimal(b.amountIn,d),tradeAmountOut:h.toDecimal(b.amountOut,m),tradeFee:h.toDecimal(H,d)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>216e5){let r=216e5/(this.blockTime*6);return Math.round(r)}return t}getTwapExecutionTime(e){return e*6*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,n=Math.round(t);return Math.max(n,6)}};var en={};v(en,{BIG_10:()=>qn,BIG_BILL:()=>Nn,StakingApi:()=>et,StakingClient:()=>tt});var Mn=require("@polkadot/util-crypto"),Ln=require("@polkadot/util"),me=require("@galacticcouncil/math-staking"),pe=ie(require("big.js")),qn=(0,pe.default)(10),Nn=(0,pe.default)(qn.pow(12));function Fr(u){return(0,Mn.encodeAddress)((0,Ln.stringToU8a)(("modl"+u).padEnd(32,"\0")),63)}var et=class{client;balanceClient;constructor(e,t){this.client=e,this.balanceClient=t}async getFreePotBalance(){let e=await this.client.getPalletId(),t=Fr(e);return(await this.balanceClient.getBalance(t,0)).transferable}async getStakingPosition(e){let[t,n]=await Promise.all([this.client.getStakingPositionsValue(e),this.client.getStakingVotes(e)]),r=t?.created_at,a=await n.reduce(async(s,[i,o])=>{let l=await s,c=i,d=o.amount,m=o.conviction.toString(),p=await this.client.getReferendumInfo(c);return p&&(p.type==="Approved"||p.type==="Rejected")&&l.push({id:c,amount:d,conviction:m}),l},Promise.resolve([]));return{stake:t?.stake,rewardPerStake:t?.reward_per_stake,createdAt:r,actionPoints:t?.action_points,accumulatedUnpaidRewards:t?.accumulated_unpaid_rewards,accumulatedSlashPoints:t?.accumulated_slash_points,accumulatedLockedRewards:t?.accumulated_locked_rewards,votes:a}}async getStake(e){let t=await this.client.getNFTCollectionId(),[n,r]=await Promise.all([this.client.getStaking(),this.client.getUniques(e,t)]),a=r.find(s=>s)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:a,stakePosition:a?await this.getStakingPosition(a):void 0}}async getRewards(e,t){let n=await this.getStake(e),{potReservedBalance:r,accumulatedRewardPerStake:a,totalStake:s,stakePosition:i}=n;if(!i)return;let[o,l,c,d]=await Promise.all([this.getFreePotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getSixBlockSince()]),m=(0,pe.default)(o.toString()).minus(r.toString()),p=a.toString(),g=(0,pe.default)(t).plus(1).toString();m.gt(0)&&s>0&&(p=(0,me.calculate_accumulated_rps)(a.toString(),m.toString(),s.toString()));let y=(0,me.calculate_period_number)(l.toString(),t,d??g),b=(0,me.calculate_period_number)(l.toString(),i.createdAt?.toString()??"",d??g),f=(0,me.calculate_rewards)(p,i.rewardPerStake?.toString()??"",i.stake?.toString()??""),S=(0,pe.default)(f).plus(i.accumulatedUnpaidRewards?.toString()||"0").plus(i.accumulatedLockedRewards?.toString()||"0");if(!(0,pe.default)(y).minus(b).lte(c.toString()))return S.div(Nn).toString()}};var tt=class extends C{async getPalletId(){let e=this.api.constants.Staking.PalletId;return(await e()).asText()}async getPeriodLength(){let e=this.api.constants.Staking.PeriodLength;return await e()}async getUnclaimablePeriods(){let e=this.api.constants.Staking.UnclaimablePeriods;return await e()}async getNFTCollectionId(){let e=this.api.constants.Staking.NFTCollectionId;return await e()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(e,t){return(await this.api.query.Uniques.Account.getEntries(e,t)).map(({keyArgs:s})=>{let[i,o,l]=s;return{address:i,collectionId:o,itemId:l}})}async getStakingPositionsValue(e){return await this.api.query.Staking.Positions.getValue(e)}async getStakingVotes(e){return await this.api.query.Staking.Votes.getValue(e)}async getReferendumInfo(e){return await this.api.query.Referenda.ReferendumInfoFor.getValue(e)}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var nn={};v(nn,{TxBuilderFactory:()=>Be});var tn=require("polkadot-api");function Gn(u){let e=[],t=u;for(;t&&typeof t=="object"&&"type"in t;)e.push(t.type),t=t.value;return e.join(".")}var _e=class extends C{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new V,this.balanceClient=new U(e),this.aaveUtils=new le(this.evmClient)}wrapTx(e,t){return{name:e,get:()=>t,dryRun:n=>this.dryRun(n,t)}}async dispatchWithExtraGas(e){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:e.decodedCall,extra_gas:St})}async dryRun(e,t){let n=(0,tn.Enum)("Signed",e),r=(0,tn.Enum)("system",n),s=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(r,t.decodedCall),i=s.success&&!s.value.execution_result.success?s.value.execution_result.value.error:null;if(i){let o=Gn(i.value);throw new Error("Dry run execution error!",{cause:o})}return s}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var mt=class extends _e{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,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:e,swaps:t,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:r}=t[0],a=await this.balanceClient.getBalance(this.beneficiary,r);return e>=a.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:e,amountOut:t,swaps:n}=this.trade,r=n[0],a=n[n.length-1],s=_.getFraction(e,this.slippagePct),i=r.assetIn,o=a.assetOut,l=e+s,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.buy({asset_in:i,asset_out:o,amount:t,max_sell_amount:l}):c=this.api.tx.Router.buy({asset_in:i,asset_out:o,amount_out:t,max_amount_in:l,route:Y.build(n)}),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:n}=this.trade,r=n[0],a=n[n.length-1],s=_.getFraction(t,this.slippagePct),i=r.assetIn,o=a.assetOut,l=t-s,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.sell({asset_in:i,asset_out:o,amount:e,min_buy_amount:l}):c=this.api.tx.Router.sell({asset_in:i,asset_out:o,amount_in:e,min_amount_out:l,route:Y.build(n)}),r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,n=t[0],r=t[t.length-1],a=_.getFraction(e,this.slippagePct),s=n.assetIn,i=r.assetOut,o=e-a,l=this.api.tx.Router.sell_all({asset_in:s,asset_out:i,min_amount_out:o,route:Y.build(t)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var gt=require("polkadot-api");var bt=class extends _e{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,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:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:r,tradePeriod:a,tradeRoute:s}=this.order,i=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:a,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,gt.Enum)("Sell",{asset_in:t,asset_out:n,amount_in:r,min_amount_out:0n,route:s})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",i)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:r,tradeAmountOut:a,tradePeriod:s,tradeRoute:i}=this.order,o=_.getFraction(a,this.slippagePct),l=a-o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,gt.Enum)("Sell",{asset_in:t,asset_out:n,amount_in:r,min_amount_out:l,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:r,tradeAmountOut:a,tradePeriod:s,tradeRoute:i}=this.order,o=_.getFraction(r,this.slippagePct),l=r+o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,gt.Enum)("Buy",{asset_in:t,asset_out:n,amount_out:a,max_amount_in:l,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",c)}};var Be=class{client;evmClient;constructor(e,t){this.client=e,this.evmClient=t??new V}trade(e){return new mt(this.client,this.evmClient).setTrade(e)}order(e){return new bt(this.client,this.evmClient).setOrder(e)}};async function Rr(u,e){let t=new Pe(u),[n,r]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),a=e??new V,s=new Ie(u).withAave().withOmnipool().withStableswap().withXyk(),i=new le(a),o=new Oe(s),l=new Ae(o,{blockTime:n,minBudgetInNative:r}),c=new U(u),d=new tt(u),m=new et(d,c);return{api:{aave:i,router:o,scheduler:l,staking:m},client:{asset:new he(u),balance:c,evm:a,mining:new fe(u)},ctx:{pool:s},tx:new Be(u,a),destroy:()=>{s.destroy()}}}0&&(module.exports={aave,api,big,client,const:null,createSdkContext,erc20,error,evm,fmt,h160,json,math,pool,sor,staking,tx,xc});