@galacticcouncil/sdk-next 0.6.0-pr193-686a593 → 0.6.0-pr193-9ed18b3
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 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 I=(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={};I(kr,{aave:()=>Et,api:()=>ht,big:()=>h,client:()=>qt,const:()=>At,createSdkContext:()=>Fr,erc20:()=>oe,error:()=>Gt,evm:()=>Tt,fmt:()=>P,h160:()=>Me,json:()=>re,math:()=>A,pool:()=>Xt,sor:()=>Zt,staking:()=>en,tx:()=>nn,xc:()=>Ft});module.exports=$n(kr);var ht={};I(ht,{Papi:()=>D,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 D=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 pn=require("polkadot-api"),mn=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,pn.createClient)((0,mn.withPolkadotSdkCompat)(r))};var Et={};I(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={};I(Tt,{EvmClient:()=>N,evmMainnet:()=>wt});var bn=require("viem"),dn=["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:dn,webSocket:gn},default:{http:dn,webSocket:gn}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var X=require("viem");var N=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,X.createPublicClient)({chain:this.chain,transport:(0,X.http)()})}getWsProvider(){return(0,X.createPublicClient)({chain:this.chain,transport:(0,X.webSocket)()})}getSigner(e){return(0,X.createWalletClient)({account:e,chain:this.chain,transport:(0,X.custom)(window.ethereum)})}};var De=class{evmClient;constructor(e){this.evmClient=e??new N}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={};I(h,{asBigInt:()=>nr,toBigInt:()=>tr,toDecimal:()=>er});var ne=ie(require("big.js"));ne.default.NE=-18;function er(u,e,t=6,n){let r=(0,ne.default)(u.toString()),a=(0,ne.default)(10).pow(e);return r.div(a).round(t,n).toString()}function tr(u,e){let t=(0,ne.default)(10).pow(e),r=(0,ne.default)(u).mul(t).toFixed(0,ne.default.roundDown);return BigInt(r)}function nr(u){return BigInt(u.round(0,ne.default.roundDown).toFixed(0))}var oe={};I(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={};I(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={};I(Me,{H160:()=>Rt,isEvmAccount:()=>Pn,isEvmAddress:()=>fn,isSs58Address:()=>Sn});var ye=require("polkadot-api"),_t=require("@polkadot-api/utils"),Z=require("buffer");var At={};I(At,{HUB_ASSET_ID:()=>Ot,HYDRATION_OMNIPOOL_ADDRESS:()=>lr,HYDRATION_PARACHAIN_ID:()=>or,HYDRATION_SS58_PREFIX:()=>q,PERBILL_DENOMINATOR:()=>ir,PERMILL_DENOMINATOR:()=>It,RUNTIME_DECIMALS:()=>k,SYSTEM_ASSET_DECIMALS:()=>vt,SYSTEM_ASSET_ID:()=>z,TRADEABLE_DEFAULT:()=>be});var k=18,It=1e6,ir=1e9,z=0,vt=12,or=2034,q=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=Z.Buffer.from(Bt);return Z.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 Rt=class u{static toAccount=e=>{let t=Z.Buffer.from(e.slice(2),"hex"),n=Z.Buffer.from(Bt),r=Uint8Array.from(Z.Buffer.concat([n,t,Z.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=Z.Buffer.from(Bt),r=t.slice(n.length,-8);return"0x"+Z.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 re={};I(re,{findNestedKey:()=>cr,findNestedObj:()=>ur,jsonFormatter:()=>pr});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},pr=(u,e)=>typeof e=="bigint"?e.toString():e;var A={};I(A,{calculateBuyFee:()=>br,calculateDiffToAvg:()=>mr,calculateDiffToRef:()=>dr,calculateSellFee:()=>gr,getFraction:()=>yr});var Q=ie(require("big.js"));function mr(u,e){let t=(0,Q.default)(u.toString()),n=(0,Q.default)(e.toString());return t.minus(n).abs().div(t.plus(n).div(2)).mul(100).round(2).toNumber()}function dr(u,e){if(e===0n)return 0;let t=(0,Q.default)(u.toString()),n=(0,Q.default)(e.toString());return t.minus(n).div(n).mul(100).round(2).toNumber()}function gr(u,e){let t=(0,Q.default)(u.toString()),n=(0,Q.default)(e.toString());return(0,Q.default)(1).minus(n.div(t)).mul(100).round(2).toNumber()}function br(u,e){let t=(0,Q.default)(u.toString());return(0,Q.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 Ft={};I(Ft,{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 N;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,p,d,m,b]=a,y=h.toDecimal(b,18),g=[];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 O=f.scaledATokenBalance,L=w.liquidityIndex,G=w.priceInMarketReferenceCurrency,M=O*L/Sr,Y=Number(o===w.eModeCategoryId?w.eModeLiquidationThreshold:w.reserveLiquidationThreshold)/1e4,te=w.usageAsCollateralEnabled&&f.usageAsCollateralEnabledOnUser&&f.scaledATokenBalance>0n,Re=ot.toAssetId(S);g.push({aTokenBalance:M,decimals:Number(w.decimals),isCollateral:te,priceInRef:G,reserveId:Re,reserveAsset:S,reserveLiquidationThreshold:Y})}return{healthFactor:Number(y),totalCollateral:l,totalDebt:c,reserves:g}}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(g=>g.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:c,priceInRef:p,reserveLiquidationThreshold:d}=o,m=h.toBigInt(n,l),b=c?m*p/10n**BigInt(l):0n,y=r-b;return y<=0n?0:this.calculateHealthFactor(y,d,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:p}=o,m=h.toBigInt(n,l)*c/10n**BigInt(l),b=r+m;return b<=0n?0:this.calculateHealthFactor(b,p,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={};I(qt,{AssetClient:()=>he,BalanceClient:()=>V,ChainParams:()=>Pe,LiquidityMining:()=>fe});var he=class extends D{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:p}=await this.mapToken(a,t,n),d=Number(s),m=new Intl.DateTimeFormat("en-GB"),b=[c,"Bond",m.format(d)].join(" ");return{id:e,name:b,symbol:c+"b",decimals:p,icon:c,type:i.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:a,maturity:d}}async mapShares(e,t,n,r){let{assets:a}=r,{name:s,symbol:i,asset_type:o,is_sufficient:l,existential_deposit:c}=t,p=await Promise.all(a.map(async b=>{let{symbol:y}=await this.mapToken(b,t,n);return[b,y]})),d=Object.fromEntries(p),m=Object.values(d);return{id:e,name:m.join(", "),symbol:i?.asText()||s?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:d}}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 p=r.get(l),{asset_type:d}=c,m;switch(d.type){case"Bond":let b=s.get(l);m=await this.mapBond(l,c,i,b);break;case"StableSwap":let y=a.get(l);m=await this.mapShares(l,c,i,y);break;case"External":m=await this.mapExternal(l,c,t,p);break;default:m=await this.mapToken(l,c,i,p)}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 x=require("rxjs");var V=class extends D{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,x.combineLatest)([t,n,r]).pipe((0,x.debounceTime)(250),(0,x.map)(a=>a.flat()),(0,x.startWith)([]),(0,x.bufferCount)(2,1),(0,x.map)(([a,s],i)=>{if(i===0)return s;let o=a.reduce((c,p)=>(c.set(p.id,p.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,x.map)(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(e,t){return this.api.query.Tokens.Accounts.watchValue(e,t,"best").pipe((0,x.map)(r=>({id:t,balance:r})))}subscribeTokensBalance(e){return this.api.query.Tokens.Accounts.watchEntries(e,{at:"best"}).pipe((0,x.distinctUntilChanged)((n,r)=>!r.deltas),(0,x.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 x.Subject,r=n.pipe((0,x.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 d=(await Promise.all(o.map(async m=>{let b=await this.getTokenBalanceData(e,m);return[m,b]}))).map(([m,b])=>({id:m,balance:b}));n.next(d)};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,x.finalize)(()=>i?.()),(0,x.pairwise)(),(0,x.map)(([o,l],c)=>{if(c===0)return l;let p=o.reduce((m,b)=>(m.set(b.id,b.balance),m),new Map);return l.filter(m=>!Tn(m.balance,p.get(m.id)))}),(0,x.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 D{_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"),C=ie(require("big.js"));var ae=ie(require("big.js")),K=require("@galacticcouncil/math-liquidity-mining"),Tr="1000000000000000000",lt=class{constructor(e,t,n){this.get_account=e;this.multiCurrency=t;this.getAsset=n}async sync_global_farm(e,t,n){if(e.state.type!=="Active"||e.updated_at===t)return null;if(e.total_shares_z===0n)return e;let r=await this.getAsset(e.reward_currency),a=t-e.updated_at,s=this.get_account(e.id),i=r?.existential_deposit;if(!i)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.free_balance(e.reward_currency,s),l=(0,ae.default)(i.toString()),c=(0,ae.default)(o.toString()).minus(l.lt(o.toString())?i.toString():o.toString()),p=(0,ae.default)((0,K.calculate_global_farm_rewards)(e.total_shares_z.toString(),n.toString(),(0,ae.default)(e.yield_per_period.toString()).mul(Dt).round(0,ae.default.roundDown).toFixed(),e.max_reward_per_period.toString(),a.toFixed()));if(c.lt(p)&&(p=c),p.eq(0))return e;let d=this.get_account(0);return this.multiCurrency.transfer(e.reward_currency,s,d,BigInt(p.toFixed())),{...e,accumulated_rpz:BigInt((0,K.calculate_accumulated_rps)(e.accumulated_rpz.toString(),e.total_shares_z.toString(),p.toFixed()))}}sync_yield_farm(e,t,n){if(e.state.type!=="Active"||e.updated_at===n)return null;if(e.total_valued_shares===0n)return{...e,updated_at:n};let r=(0,K.calculate_yield_farm_delta_rpvs)(e.accumulated_rpz.toString(),t.accumulated_rpz.toString(),e.multiplier.toString(),e.total_valued_shares.toString());return{...e,accumulated_rpvs:e.accumulated_rpvs+BigInt(r),updated_at:n}}get_loyalty_multiplier(e,t){let n=(0,ae.default)(1).mul(Dt).round(0,ae.default.roundDown).toString();if(!t)return n;let{initial_reward_percentage:r,scale_coef:a}=t;return(0,K.calculate_loyalty_multiplier)(e.toFixed(),r.toString(),a.toFixed())}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(n.updated_at===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,s);if(!o)return null;let l=o.total_stopped-n.stopped_at_creation,c=o.updated_at-n.entered_at-l,p=this.get_loyalty_multiplier(c,o.loyalty_curve),d=BigInt((0,K.calculate_user_reward)(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),m=BigInt((0,K.calculate_user_reward)(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),Tr));return{reward:d,maxReward:m,assetId:i.reward_currency}}};var xr=BigInt((0,C.default)(1).pow(18).toString()),Ir=6,fe=class extends D{balanceClient;omnipoolAssetIds=[];secondsInYear=(0,C.default)(365.2425).times(24).times(60).times(60);constructor(e){super(e),this.balanceClient=new V(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,C.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,C.default)(e.toString()).times(t),s=(0,C.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:p,total_shares_z:d,max_reward_per_period:m,pending_rewards:b,accumulated_paid_rewards:y,planned_yielding_periods:g,updated_at:f,incentivized_asset:S,reward_currency:w,price_adjustment:O}=a,L=Ce(s??O,18),G=Ce(o,18),M=Ce(l?.initial_reward_percentage??0,18),W=this.secondsInYear.div((0,C.default)(Ir).times(c)).toString(),Y;if(d<0)Y=(0,C.default)(G).times(p.toString()).times(W).toString();else{let Wn=this.getGlobalRewardPerPeriod(d,p,m,L),Yn=this.getPoolYieldPerPeriod(Wn,G,d,L);Y=(0,C.default)(Yn).times(W).toString()}let te=b+y,Re=m*BigInt(g),se=i.transferable+te,yt=se-te,Fe=(0,C.default)(yt.toString()).div(m.toString()),rn=(0,C.default)(t).div(c.toString()).toString(),Vn=(d>=0?Fe.plus(f):Fe.plus(rn)).toString(),Hn=(0,C.default)(d.toString()).div((0,C.default)(m.toString()).div(p.toString())).div(Math.pow(10,18)).times(100).times(L).toFixed(2),an=(0,C.default)(te.toString()).div(se.toString()).gte(.999);Y=an?"0":(0,C.default)(Y).div(n?2:1).times(100).toString();let Un=M?(0,C.default)(Y).times(M).toString():void 0;return{apr:Y,minApr:Un,isDistributed:an,estimatedEndPeriod:Vn,maxRewards:Re,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),p=await this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(Number(e),o,l);if(!c||!p)return;let d=c.reward_currency,m=c.incentivized_asset,b=this.getFarmAddress(o),y=await this.getOraclePrice(d,m),g=await this.balanceClient.getTokenBalance(b,d);return{id:e,globalFarm:c,yieldFarm:p,priceAdjustment:y,balance:g}}));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),p=await this.api.query.XYKWarehouseLM.YieldFarm.getValue(e,o,l);if(!c||!p)return;let d=c.reward_currency,m=c.incentivized_asset,b=this.getFarmAddress(o,!0),y=await this.getOraclePrice(d,m),g=await this.balanceClient.getBalance(b,d);return{id:e,globalFarm:c,yieldFarm:p,priceAdjustment:y,balance:g,farmAddress:b}}));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,p=[[this.getFarmAddress(0,n),o.reward_currency],[this.getFarmAddress(o.id,n),o.reward_currency]],d=await vr(this.api,p)(),m=await this.getOraclePrice(l,c),b=new Lt(p,d),g=await new lt(S=>this.getFarmAddress(S),b,S=>this.api.query.AssetRegistry.Assets.getValue(S)).claim_rewards(o,i,t,r,m??o.price_adjustment);if(!g)return;let f=await this.api.query.AssetRegistry.Assets.getValue(g.assetId);if(f&&!(g.reward<=f.existential_deposit))return g}},Dt=(0,C.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={};I(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={};I(Xt,{PoolContextProvider:()=>Ie,PoolError:()=>ce,PoolFactory:()=>xe,PoolType:()=>F,aave:()=>Yt,lbp:()=>Vt,omni:()=>Ht,stable:()=>Ut,xyk:()=>Wt});var Vt={};I(Vt,{LbpMath:()=>j,LbpPool:()=>Ne,LbpPoolClient:()=>Ge});var $=require("@galacticcouncil/math-lbp"),j=class{static getSpotPrice(e,t,n,r,a){return(0,$.get_spot_price)(e,t,n,r,a)}static calculateInGivenOut(e,t,n,r,a){return(0,$.calculate_in_given_out)(e,t,n,r,a)}static calculateOutGivenIn(e,t,n,r,a){return(0,$.calculate_out_given_in)(e,t,n,r,a)}static calculateLinearWeights(e,t,n,r,a){return(0,$.calculate_linear_weights)(e,t,n,r,a)}static calculatePoolTradeFee(e,t,n){return(0,$.calculate_pool_trade_fee)(e,t,n)}};var F=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a))(F||{}),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),p=e.balanceIn/this.maxInRatio;return c>p&&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,p=e.balanceOut/this.maxOutRatio;return c>p&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:c,feePct:l,errors:a}}}calculateInGivenOut(e,t){let n=j.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=j.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=j.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),this.maxOutRatio.toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=j.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),this.maxInRatio.toString());return BigInt(t)}calculateTradeFee(e,t){let n=j.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 v=require("rxjs");var H=class extends V{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,v.from)(this.getPoolsMem()).pipe((0,v.switchMap)(t=>this.subscribe(t)),(0,v.combineLatestAll)());return(0,v.firstValueFrom)(e)}getSubscriber(){return(0,v.from)(this.getPoolsMem()).pipe((0,v.switchMap)(e=>this.subscribe(e)),(0,v.mergeAll)())}subscribe(e){return e.filter(t=>this.hasValidAssets(t)).map(t=>(0,v.combineLatest)([this.subscribePoolChange(t),this.subscribePoolBalance(t)]).pipe((0,v.debounceTime)(250),(0,v.map)(([n,r])=>this.updatePool(n,r))))}subscribePoolBalance(e){if(e.type==="Aave")return(0,v.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,v.combineLatest)(t).pipe((0,v.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 H{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,p=j.calculateLinearWeights(r?r.toString():"0",a?a.toString():"0",i.toString(),o.toString(),n.toString()),[d,m]=s,b=BigInt(p),y=this.MAX_FINAL_WEIGHT-BigInt(b),[g,f,S,w,O]=await Promise.all([this.isRepayFeeApplied(d,l,c.toString()),this.getBalance(e,d),this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(e,m),this.api.query.AssetRegistry.Assets.getValue(m)]);return{repayFeeApply:g,tokens:[{id:d,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:f.transferable,weight:b,type:S?.asset_type.type},{id:m,decimals:O?.decimals,existentialDeposit:O?.existential_deposit,balance:w.transferable,weight:y,type:O?.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={};I(Ht,{OmniMath:()=>_,OmniPool:()=>Ve,OmniPoolClient:()=>Ue});var T=require("@galacticcouncil/math-omnipool"),pe=ie(require("big.js")),_=class{static calculateSpotPrice(e,t,n,r){return(0,T.calculate_spot_price)(e,t,n,r)}static calculateLrnaSpotPrice(e,t){return(0,T.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,n,r,a,s,i,o,l){return(0,T.calculate_in_given_out)(e,t,n,r,a,s,i,o,l)}static calculateLrnaInGivenOut(e,t,n,r,a){return(0,T.calculate_lrna_in_given_out)(e,t,n,r,a)}static calculateOutGivenIn(e,t,n,r,a,s,i,o,l){return(0,T.calculate_out_given_in)(e,t,n,r,a,s,i,o,l)}static calculateOutGivenLrnaIn(e,t,n,r,a){return(0,T.calculate_out_given_lrna_in)(e,t,n,r,a)}static calculateShares(e,t,n,r){return(0,T.calculate_shares)(e,t,n,r)}static calculateLiquidityOut(e,t,n,r,a,s,i,o){return(0,T.calculate_liquidity_out)(e,t,n,r,a,s,i,o)}static calculateLiquidityLRNAOut(e,t,n,r,a,s,i,o){return(0,T.calculate_liquidity_lrna_out)(e,t,n,r,a,s,i,o)}static calculateCapDifference(e,t,n,r){let a=(0,pe.default)(t),s=(0,pe.default)(e),i=(0,pe.default)(r),o=(0,pe.default)(n),l=(0,pe.default)(10).pow(18),c=o.div(l);if(a.div(i).lt(c)){let d=c.times(i).minus(a).times(s),m=a.times((0,pe.default)(1).minus(c));return d.div(m).toFixed(0)}else return"0"}static verifyAssetCap(e,t,n,r){return(0,T.verify_asset_cap)(e,t,n,r)}static calculateLimitHubIn(e,t,n,r){return(0,T.calculate_liquidity_hub_in)(e,t,n,r)}static isSellAllowed(e){return(0,T.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,T.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,T.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,T.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:A.calculateDiffToRef(a,r),i=[],o=_.isSellAllowed(e.tradeableIn),l=_.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 p=e.balanceIn/this.maxInRatio;return a>p&&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=A.calculateDiffToRef(r,a),i=[],o=_.isSellAllowed(e.tradeableIn),l=_.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 p=e.balanceOut/this.maxOutRatio;return a>p&&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=_.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=_.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=_.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=_.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=_.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=_.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=_.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=_.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 H{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:p})=>{let[d]=c,{hub_reserve:m,shares:b,tradable:y,cap:g,protocol_shares:f}=p,[S,w]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(t,d)]);return{id:d,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:w.transferable,cap:g,hubReserves:m,protocolShares:f,shares:b,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,p=e.tokens.findIndex(m=>m.id===a);return{...e.tokens[p],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={};I(Ut,{StableMath:()=>E,StableSwap:()=>We,StableSwapClient:()=>Ye});var B=require("@galacticcouncil/math-stableswap"),E=class{static getPoolAddress(e){return(0,B.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,B.calculate_amplification)(e,t,n,r,a)}static calculateInGivenOut(e,t,n,r,a,s,i){return(0,B.calculate_in_given_out)(e,t,n,r,a,s,i)}static calculateAddOneAsset(e,t,n,r,a,s,i){return(0,B.calculate_add_one_asset)(e,t,n,r,a,s,i)}static calculateSharesForAmount(e,t,n,r,a,s,i){return(0,B.calculate_shares_for_amount)(e,t,n,r,a,s,i)}static calculateOutGivenIn(e,t,n,r,a,s,i){return(0,B.calculate_out_given_in)(e,t,n,r,a,s,i)}static calculateLiquidityOutOneAsset(e,t,n,r,a,s,i){return(0,B.calculate_liquidity_out_one_asset)(e,t,n,r,a,s,i)}static calculateShares(e,t,n,r,a,s){return(0,B.calculate_shares)(e,t,n,r,a,s)}static calculateSpotPriceWithFee(e,t,n,r,a,s,i,o){return(0,B.calculate_spot_price_with_fee)(e,t,n,r,a,s,i,o)}static recalculatePegs(e,t,n,r,a){let s=(0,B.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=_.isSellAllowed(e.tradeableIn),l=_.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=_.isSellAllowed(e.tradeableIn),l=_.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=E.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=E.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=E.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=E.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=E.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=E.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=E.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=E.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=E.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,re.jsonFormatter)}getAssets(e,t){let n={asset_id:Number(e),amount:t.toString()};return JSON.stringify([n],re.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 H{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,p]=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,...p,...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=E.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]=E.recalculatePegs(JSON.stringify(s),JSON.stringify(a),n.toString(),P.toDecimals(i).toString(),P.toDecimals(o).toString()),p=Number(l)*1e6;return{pegsFee:P.fromPermill(p),pegs:c}}getDefaultPegs(e){let t=e.fee,n=E.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,p]=i.value,d=[p,a[o]].sort((S,w)=>S-w),m=await this.api.query.EmaOracle.Oracles.getValue(l,d,c);if(!m)return;let[{price:b,updated_at:y}]=m,g=b.n.toString(),f=b.d.toString();return p.toString()===d[0].toString()?[[g,f],y.toString()]:[[f,g],y.toString()]}else return[i.value.map(l=>l.toString()),n]});return Promise.all(s)}getPoolAddress(e){let t=E.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={};I(Wt,{XykMath:()=>ee,XykPool:()=>Xe,XykPoolClient:()=>ze});var R=require("@galacticcouncil/math-xyk"),ee=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=ee.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(e,t){let n=ee.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(e){let t=ee.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){let t=ee.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateTradeFee(e,t){let n=ee.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return BigInt(n)}};var _n=require("polkadot-api"),Bn=require("rxjs");var ze=class extends H{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,p,d,m]=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:p?.decimals,existentialDeposit:p?.existential_deposit,balance:c.transferable,type:p?.asset_type.type},{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,type:m?.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={};I(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 Fn=require("polkadot-api"),kn=require("@polkadot-api/utils"),Te=require("rxjs"),En=require("viem");var Rn=[{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 H{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,Fn.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(b=>b.asHex()),p=l.asHex(),{eventName:d,args:m}=(0,En.decodeEventLog)({abi:Rn,topics:c,data:p});return _r.includes(d)&&m.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"?re.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 J=require("rxjs");var Ie=class extends D{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 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,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(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={};I(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:()=>Ll,TradeOrderError:()=>Kt,TradeOrderType:()=>mt,TradeRouteBuilder:()=>U,TradeRouter:()=>Oe,TradeScheduler:()=>Ae,TradeType:()=>pt});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 p=[...i];p.push(c),a.enqueue(p)}})}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 p of c??[])this.isNotVisited(p,o)&&a.enqueue([...o,p])}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(g=>g.type==="XYK"),a=n.filter(g=>g.type!=="XYK"),s=new Set(a.map(g=>g.tokens).flat().map(g=>g.id)),i=s.has(e),o=s.has(t),l=new $e,c=g=>{let f=zt(g),S=Object.keys(f),w=S.flatMap(O=>f[O]);return l.buildAndPopulateGraph(S,w)};if(!i&&!o){let g=r.filter(w=>w.tokens.find(O=>O.id===e)||w.tokens.find(O=>O.id===t)),f=c(g),S=l.findPaths(f,e,t);return this.parsePaths(S)}if(i&&o){let g=c(a),f=l.findPaths(g,e,t);return this.parsePaths(f)}let p=i?t:e,d=r.filter(g=>g.tokens.some(f=>f.id===p));if(d.length===0)return[];let m=[...a,...d],b=c(m),y=l.findPaths(b,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 pt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(pt||{}),mt=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(mt||{}),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),p=a?r.tradeFeePct:A.calculateSellFee(o,i),d=Math.pow(10,n.assetInDecimals),m=n.amountIn*s/BigInt(d),b=A.calculateDiffToRef(o,m);return{type:"Sell",amountIn:n.amountIn,amountOut:r.amountOut,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,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:p,tradeFeeRange:c,priceImpactPct:b,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(g=>g.id===e)).map(y=>y.type==="Aave"?y.tokens:y.tokens.filter(g=>g.id===e)).map(y=>y.map(g=>g.balance).reduce((g,f)=>g+f)).sort((y,g)=>g<y?-1:1)[0],c=A.getFraction(l,.1),p=await Promise.all(r.map(y=>this.toSellSwaps(c,y,s))),m=this.findBestSellRoute(p).map(y=>({poolAddress:y.poolAddress,poolId:y?.poolId,pool:y.pool,assetIn:y.assetIn,assetOut:y.assetOut})),b=this.buildRouteKey(e,t,a);return this.mlr.set(b,m),m}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:p,calculatedOut:d,feePct:m,errors:b}=i.validateAndSell(o,l,c),y=this.getPoolFeeRange(c),g=i.spotPriceOutGivenIn(o),f=Math.pow(10,o.decimalsIn),S=l*g/BigInt(f),w=A.calculateDiffToRef(d,S);r.push({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:y,priceImpactPct:w,errors:b,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(p,o.decimalsOut),calculatedOut:h.toDecimal(d,o.decimalsOut),spotPrice:h.toDecimal(g,o.decimalsOut),tradeFeePct:m,tradeFeeRange:y,priceImpactPct:w,errors:b}}})}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),p=a?r.tradeFeePct:A.calculateBuyFee(o,i),d=Math.pow(10,n.assetOutDecimals),m=n.amountOut*s/BigInt(d),b;return o===0n?b=-100:b=A.calculateDiffToRef(m,o),{type:"Buy",amountOut:n.amountOut,amountIn:r.amountIn,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,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:p,tradeFeeRange:c,priceImpactPct:b,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:p,calculatedIn:d,feePct:m,errors:b}=i.validateAndBuy(o,l,c),y=this.getPoolFeeRange(c),g=i.spotPriceInGivenOut(o),f=Math.pow(10,o.decimalsOut),S=l*g/BigInt(f),w;d===0n?w=-100:w=A.calculateDiffToRef(S,d),r.unshift({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:y,priceImpactPct:w,errors:b,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(p,o.decimalsIn),calculatedIn:h.toDecimal(d,o.decimalsIn),spotPrice:h.toDecimal(g,o.decimalsIn),tradeFeePct:m,tradeFeeRange:y,priceImpactPct:w,errors:b}}})}return r}};var Dn=6e3,jt=1000000000000000n,Ze=6,Qt=-5,$t=216e5,Ll=3,Cn=6;var Jt=require("polkadot-api");var U=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,p=l[0],d=l[l.length-1],{assetInDecimals:m}=p,{assetOutDecimals:b}=d,y=Math.abs(c),g=this.getMinimumTradeCount(o,s),f=this.getOptimalTradeCount(y),S=a?Math.round(r/a):f,w=Math.ceil(r/g),O=Math.round(r/f),L=Math.round(r/S),G=o/BigInt(S),M=await this.router.getBestSell(e,t,G),W=o<s,Y=[];W&&Y.push("OrderTooSmall");let te=M.amountOut*BigInt(S),Re=this.toBlockPeriod(L),se=M.tradeFee*BigInt(S),yt=U.build(l),Fe={assetIn:e,assetOut:t,errors:Y,frequencyMin:w,frequencyOpt:O,frequency:L,tradeCount:S,tradeFee:se,tradeImpactPct:M.priceImpactPct,tradePeriod:Re,tradeRoute:yt,type:"Dca"};return{...Fe,amountIn:o,amountOut:te,tradeAmountIn:M.amountIn,tradeAmountOut:M.amountOut,toHuman(){return{...Fe,amountIn:h.toDecimal(o,m),amountOut:h.toDecimal(te,b),tradeAmountIn:h.toDecimal(M.amountIn,m),tradeAmountOut:h.toDecimal(M.amountOut,b)}}}}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:p}=l,{assetOutDecimals:d}=c,m=Math.abs(o),b=this.getTwapTradeCount(m),y=s/BigInt(b),g=await this.router.getBestSell(l.assetIn,c.assetOut,y),f=b===1,S=s<r,w=g.priceImpactPct<-5,O=[];S||f?O.push("OrderTooSmall"):w&&O.push("OrderImpactTooBig");let L=g.amountOut*BigInt(b),G=g.tradeFee*BigInt(b),M=U.build(i),W={assetIn:e,assetOut:t,errors:O,tradeCount:b,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:M,type:"TwapSell"};return{...W,amountIn:s,amountOut:L,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:G,toHuman(){return{...W,amountIn:h.toDecimal(s,p),amountOut:h.toDecimal(L,d),tradeAmountIn:h.toDecimal(g.amountIn,p),tradeAmountOut:h.toDecimal(g.amountOut,d),tradeFee:h.toDecimal(G,d)}}}}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:p}=l,{assetOutDecimals:d}=c,m=Math.abs(o),b=this.getTwapTradeCount(m),y=s/BigInt(b),g=await this.router.getBestBuy(l.assetIn,c.assetOut,y),f=g.amountIn*BigInt(b),S=b===1,w=f<r,O=g.priceImpactPct<-5,L=[];w||S?L.push("OrderTooSmall"):O&&L.push("OrderImpactTooBig");let G=g.tradeFee*BigInt(b),M=U.build(i),W={assetIn:e,assetOut:t,errors:L,tradeCount:b,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:M,type:"TwapBuy"};return{...W,amountIn:f,amountOut:s,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:G,toHuman(){return{...W,amountIn:h.toDecimal(f,p),amountOut:h.toDecimal(s,d),tradeAmountIn:h.toDecimal(g.amountIn,p),tradeAmountOut:h.toDecimal(g.amountOut,d),tradeFee:h.toDecimal(G,p)}}}}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={};I(en,{BIG_10:()=>qn,BIG_BILL:()=>Nn,StakingApi:()=>et,StakingClient:()=>tt});var Mn=require("@polkadot/util-crypto"),Ln=require("@polkadot/util"),de=require("@galacticcouncil/math-staking"),me=ie(require("big.js")),qn=(0,me.default)(10),Nn=(0,me.default)(qn.pow(12));function Rr(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 getTransferablePotBalance(){let e=await this.client.getPalletId(),t=Rr(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,p=o.amount,d=o.conviction.toString(),m=await this.client.getReferendumInfo(c);return m&&(m.type==="Approved"||m.type==="Rejected")&&l.push({id:c,amount:p,conviction:d}),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,p]=await Promise.all([this.getTransferablePotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getSixBlockSince()]),d=(0,me.default)(o.toString()).minus(r.toString()),m=a.toString(),b=(0,me.default)(t).plus(1).toString();d.gt(0)&&s>0&&(m=(0,de.calculate_accumulated_rps)(a.toString(),d.toString(),s.toString()));let y=(0,de.calculate_period_number)(l.toString(),t,p??b),g=(0,de.calculate_period_number)(l.toString(),i.createdAt?.toString()??"",p??b),f=(0,de.calculate_rewards)(m,i.rewardPerStake?.toString()??"",i.stake?.toString()??""),S=(0,me.default)(f).plus(i.accumulatedUnpaidRewards?.toString()||"0").plus(i.accumulatedLockedRewards?.toString()||"0");if(!(0,me.default)(y).minus(g).lte(c.toString()))return S.div(Nn).toString()}};var tt=class extends D{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={};I(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 D{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new N,this.balanceClient=new V(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 dt=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=A.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:U.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=A.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:U.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=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:U.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=A.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=A.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 N}trade(e){return new dt(this.client,this.evmClient).setTrade(e)}order(e){return new bt(this.client,this.evmClient).setOrder(e)}};async function Fr(u,e){let t=new Pe(u),[n,r]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),a=e??new N,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 V(u),p=new tt(u),d=new et(p,c);return{api:{aave:i,router:o,scheduler:l,staking:d},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});
|
|
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 I=(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={};I(kr,{aave:()=>Et,api:()=>ht,big:()=>h,client:()=>qt,const:()=>At,createSdkContext:()=>Fr,erc20:()=>oe,error:()=>Gt,evm:()=>Tt,fmt:()=>P,h160:()=>Me,json:()=>re,math:()=>A,pool:()=>Xt,sor:()=>Zt,staking:()=>en,tx:()=>nn,xc:()=>Ft});module.exports=$n(kr);var ht={};I(ht,{Papi:()=>D,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 D=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 pn=require("polkadot-api"),mn=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,pn.createClient)((0,mn.withPolkadotSdkCompat)(r))};var Et={};I(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={};I(Tt,{EvmClient:()=>N,evmMainnet:()=>wt});var bn=require("viem"),dn=["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:dn,webSocket:gn},default:{http:dn,webSocket:gn}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var X=require("viem");var N=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,X.createPublicClient)({chain:this.chain,transport:(0,X.http)()})}getWsProvider(){return(0,X.createPublicClient)({chain:this.chain,transport:(0,X.webSocket)()})}getSigner(e){return(0,X.createWalletClient)({account:e,chain:this.chain,transport:(0,X.custom)(window.ethereum)})}};var De=class{evmClient;constructor(e){this.evmClient=e??new N}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={};I(h,{asBigInt:()=>nr,toBigInt:()=>tr,toDecimal:()=>er});var ne=ie(require("big.js"));ne.default.NE=-18;function er(u,e,t=6,n){let r=(0,ne.default)(u.toString()),a=(0,ne.default)(10).pow(e);return r.div(a).round(t,n).toString()}function tr(u,e){let t=(0,ne.default)(10).pow(e),r=(0,ne.default)(u).mul(t).toFixed(0,ne.default.roundDown);return BigInt(r)}function nr(u){return BigInt(u.round(0,ne.default.roundDown).toFixed(0))}var oe={};I(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={};I(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={};I(Me,{H160:()=>Rt,isEvmAccount:()=>Pn,isEvmAddress:()=>fn,isSs58Address:()=>Sn});var ye=require("polkadot-api"),_t=require("@polkadot-api/utils"),Z=require("buffer");var At={};I(At,{HUB_ASSET_ID:()=>Ot,HYDRATION_OMNIPOOL_ADDRESS:()=>lr,HYDRATION_PARACHAIN_ID:()=>or,HYDRATION_SS58_PREFIX:()=>q,PERBILL_DENOMINATOR:()=>ir,PERMILL_DENOMINATOR:()=>It,RUNTIME_DECIMALS:()=>k,SYSTEM_ASSET_DECIMALS:()=>vt,SYSTEM_ASSET_ID:()=>z,TRADEABLE_DEFAULT:()=>be});var k=18,It=1e6,ir=1e9,z=0,vt=12,or=2034,q=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=Z.Buffer.from(Bt);return Z.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 Rt=class u{static toAccount=e=>{let t=Z.Buffer.from(e.slice(2),"hex"),n=Z.Buffer.from(Bt),r=Uint8Array.from(Z.Buffer.concat([n,t,Z.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=Z.Buffer.from(Bt),r=t.slice(n.length,-8);return"0x"+Z.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 re={};I(re,{findNestedKey:()=>cr,findNestedObj:()=>ur,jsonFormatter:()=>pr});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},pr=(u,e)=>typeof e=="bigint"?e.toString():e;var A={};I(A,{calculateBuyFee:()=>br,calculateDiffToAvg:()=>mr,calculateDiffToRef:()=>dr,calculateSellFee:()=>gr,getFraction:()=>yr});var Q=ie(require("big.js"));function mr(u,e){let t=(0,Q.default)(u.toString()),n=(0,Q.default)(e.toString());return t.minus(n).abs().div(t.plus(n).div(2)).mul(100).round(2).toNumber()}function dr(u,e){if(e===0n)return 0;let t=(0,Q.default)(u.toString()),n=(0,Q.default)(e.toString());return t.minus(n).div(n).mul(100).round(2).toNumber()}function gr(u,e){let t=(0,Q.default)(u.toString()),n=(0,Q.default)(e.toString());return(0,Q.default)(1).minus(n.div(t)).mul(100).round(2).toNumber()}function br(u,e){let t=(0,Q.default)(u.toString());return(0,Q.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 Ft={};I(Ft,{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 N;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,p,d,m,b]=a,y=h.toDecimal(b,18),g=[];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 O=f.scaledATokenBalance,L=w.liquidityIndex,G=w.priceInMarketReferenceCurrency,M=O*L/Sr,Y=Number(o===w.eModeCategoryId?w.eModeLiquidationThreshold:w.reserveLiquidationThreshold)/1e4,te=w.usageAsCollateralEnabled&&f.usageAsCollateralEnabledOnUser&&f.scaledATokenBalance>0n,Re=ot.toAssetId(S);g.push({aTokenBalance:M,decimals:Number(w.decimals),isCollateral:te,priceInRef:G,reserveId:Re,reserveAsset:S,reserveLiquidationThreshold:Y})}return{healthFactor:Number(y),totalCollateral:l,totalDebt:c,reserves:g}}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(g=>g.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:c,priceInRef:p,reserveLiquidationThreshold:d}=o,m=h.toBigInt(n,l),b=c?m*p/10n**BigInt(l):0n,y=r-b;return y<=0n?0:this.calculateHealthFactor(y,d,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:p}=o,m=h.toBigInt(n,l)*c/10n**BigInt(l),b=r+m;return b<=0n?0:this.calculateHealthFactor(b,p,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={};I(qt,{AssetClient:()=>he,BalanceClient:()=>V,ChainParams:()=>Pe,LiquidityMining:()=>fe});var he=class extends D{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:p}=await this.mapToken(a,t,n),d=Number(s),m=new Intl.DateTimeFormat("en-GB"),b=[c,"Bond",m.format(d)].join(" ");return{id:e,name:b,symbol:c+"b",decimals:p,icon:c,type:i.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:a,maturity:d}}async mapShares(e,t,n,r){let{assets:a}=r,{name:s,symbol:i,asset_type:o,is_sufficient:l,existential_deposit:c}=t,p=await Promise.all(a.map(async b=>{let{symbol:y}=await this.mapToken(b,t,n);return[b,y]})),d=Object.fromEntries(p),m=Object.values(d);return{id:e,name:m.join(", "),symbol:i?.asText()||s?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:d}}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 p=r.get(l),{asset_type:d}=c,m;switch(d.type){case"Bond":let b=s.get(l);m=await this.mapBond(l,c,i,b);break;case"StableSwap":let y=a.get(l);m=await this.mapShares(l,c,i,y);break;case"External":m=await this.mapExternal(l,c,t,p);break;default:m=await this.mapToken(l,c,i,p)}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 x=require("rxjs");var V=class extends D{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,x.combineLatest)([t,n,r]).pipe((0,x.debounceTime)(250),(0,x.map)(a=>a.flat()),(0,x.startWith)([]),(0,x.bufferCount)(2,1),(0,x.map)(([a,s],i)=>{if(i===0)return s;let o=a.reduce((c,p)=>(c.set(p.id,p.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,x.map)(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(e,t){return this.api.query.Tokens.Accounts.watchValue(e,t,"best").pipe((0,x.map)(r=>({id:t,balance:r})))}subscribeTokensBalance(e){return this.api.query.Tokens.Accounts.watchEntries(e,{at:"best"}).pipe((0,x.distinctUntilChanged)((n,r)=>!r.deltas),(0,x.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 x.Subject,r=n.pipe((0,x.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 d=(await Promise.all(o.map(async m=>{let b=await this.getTokenBalanceData(e,m);return[m,b]}))).map(([m,b])=>({id:m,balance:b}));n.next(d)};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,x.finalize)(()=>i?.()),(0,x.pairwise)(),(0,x.map)(([o,l],c)=>{if(c===0)return l;let p=o.reduce((m,b)=>(m.set(b.id,b.balance),m),new Map);return l.filter(m=>!Tn(m.balance,p.get(m.id)))}),(0,x.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 D{_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"),C=ie(require("big.js"));var ae=ie(require("big.js")),K=require("@galacticcouncil/math-liquidity-mining"),Tr="1000000000000000000",lt=class{constructor(e,t,n){this.get_account=e;this.multiCurrency=t;this.getAsset=n}async sync_global_farm(e,t,n){if(e.state.type!=="Active"||e.updated_at===t)return null;if(e.total_shares_z===0n)return e;let r=await this.getAsset(e.reward_currency),a=t-e.updated_at,s=this.get_account(e.id),i=r?.existential_deposit;if(!i)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.free_balance(e.reward_currency,s),l=(0,ae.default)(i.toString()),c=(0,ae.default)(o.toString()).minus(l.lt(o.toString())?i.toString():o.toString()),p=(0,ae.default)((0,K.calculate_global_farm_rewards)(e.total_shares_z.toString(),n.toString(),(0,ae.default)(e.yield_per_period.toString()).mul(Dt).round(0,ae.default.roundDown).toFixed(),e.max_reward_per_period.toString(),a.toFixed()));if(c.lt(p)&&(p=c),p.eq(0))return e;let d=this.get_account(0);return this.multiCurrency.transfer(e.reward_currency,s,d,BigInt(p.toFixed())),{...e,accumulated_rpz:BigInt((0,K.calculate_accumulated_rps)(e.accumulated_rpz.toString(),e.total_shares_z.toString(),p.toFixed()))}}sync_yield_farm(e,t,n){if(e.state.type!=="Active"||e.updated_at===n)return null;if(e.total_valued_shares===0n)return{...e,updated_at:n};let r=(0,K.calculate_yield_farm_delta_rpvs)(e.accumulated_rpz.toString(),t.accumulated_rpz.toString(),e.multiplier.toString(),e.total_valued_shares.toString());return{...e,accumulated_rpvs:e.accumulated_rpvs+BigInt(r),updated_at:n}}get_loyalty_multiplier(e,t){let n=(0,ae.default)(1).mul(Dt).round(0,ae.default.roundDown).toString();if(!t)return n;let{initial_reward_percentage:r,scale_coef:a}=t;return(0,K.calculate_loyalty_multiplier)(e.toFixed(),r.toString(),a.toFixed())}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(n.updated_at===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,s);if(!o)return null;let l=o.total_stopped-n.stopped_at_creation,c=o.updated_at-n.entered_at-l,p=this.get_loyalty_multiplier(c,o.loyalty_curve),d=BigInt((0,K.calculate_user_reward)(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),m=BigInt((0,K.calculate_user_reward)(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),Tr));return{reward:d,maxReward:m,assetId:i.reward_currency}}};var xr=BigInt((0,C.default)(1).pow(18).toString()),Ir=6,fe=class extends D{balanceClient;omnipoolAssetIds=[];secondsInYear=(0,C.default)(365.2425).times(24).times(60).times(60);constructor(e){super(e),this.balanceClient=new V(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,C.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,C.default)(e.toString()).times(t),s=(0,C.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:p,total_shares_z:d,max_reward_per_period:m,pending_rewards:b,accumulated_paid_rewards:y,planned_yielding_periods:g,updated_at:f,incentivized_asset:S,reward_currency:w,price_adjustment:O}=a,L=Ce(s??O,18),G=Ce(o,18),M=Ce(l?.initial_reward_percentage??0,18),W=this.secondsInYear.div((0,C.default)(Ir).times(c)).toString(),Y;if(d<0)Y=(0,C.default)(G).times(p.toString()).times(W).toString();else{let Wn=this.getGlobalRewardPerPeriod(d,p,m,L),Yn=this.getPoolYieldPerPeriod(Wn,G,d,L);Y=(0,C.default)(Yn).times(W).toString()}let te=b+y,Re=m*BigInt(g),se=i.transferable+te,yt=se-te,Fe=(0,C.default)(yt.toString()).div(m.toString()),rn=(0,C.default)(t).div(c.toString()).toString(),Vn=(d>=0?Fe.plus(f):Fe.plus(rn)).toString(),Hn=(0,C.default)(d.toString()).div((0,C.default)(m.toString()).div(p.toString())).div(Math.pow(10,18)).times(100).times(L).toFixed(2),an=(0,C.default)(te.toString()).div(se.toString()).gte(.999);Y=an?"0":(0,C.default)(Y).div(n?2:1).times(100).toString();let Un=M?(0,C.default)(Y).times(M).toString():void 0;return{apr:Y,minApr:Un,isDistributed:an,estimatedEndPeriod:Vn,maxRewards:Re,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),p=await this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(Number(e),o,l);if(!c||!p)return;let d=c.reward_currency,m=c.incentivized_asset,b=this.getFarmAddress(o),y=await this.getOraclePrice(d,m),g=await this.balanceClient.getTokenBalance(b,d);return{id:e,globalFarm:c,yieldFarm:p,priceAdjustment:y,balance:g}}));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),p=await this.api.query.XYKWarehouseLM.YieldFarm.getValue(e,o,l);if(!c||!p)return;let d=c.reward_currency,m=c.incentivized_asset,b=this.getFarmAddress(o,!0),y=await this.getOraclePrice(d,m),g=await this.balanceClient.getBalance(b,d);return{id:e,globalFarm:c,yieldFarm:p,priceAdjustment:y,balance:g,farmAddress:b}}));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,p=[[this.getFarmAddress(0,n),o.reward_currency],[this.getFarmAddress(o.id,n),o.reward_currency]],d=await vr(this.api,p)(),m=await this.getOraclePrice(l,c),b=new Lt(p,d),g=await new lt(S=>this.getFarmAddress(S),b,S=>this.api.query.AssetRegistry.Assets.getValue(S)).claim_rewards(o,i,t,r,m??o.price_adjustment);if(!g)return;let f=await this.api.query.AssetRegistry.Assets.getValue(g.assetId);if(f&&!(g.reward<=f.existential_deposit))return g}},Dt=(0,C.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={};I(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={};I(Xt,{PoolContextProvider:()=>Ie,PoolError:()=>ce,PoolFactory:()=>xe,PoolType:()=>F,aave:()=>Yt,lbp:()=>Vt,omni:()=>Ht,stable:()=>Ut,xyk:()=>Wt});var Vt={};I(Vt,{LbpMath:()=>j,LbpPool:()=>Ne,LbpPoolClient:()=>Ge});var $=require("@galacticcouncil/math-lbp"),j=class{static getSpotPrice(e,t,n,r,a){return(0,$.get_spot_price)(e,t,n,r,a)}static calculateInGivenOut(e,t,n,r,a){return(0,$.calculate_in_given_out)(e,t,n,r,a)}static calculateOutGivenIn(e,t,n,r,a){return(0,$.calculate_out_given_in)(e,t,n,r,a)}static calculateLinearWeights(e,t,n,r,a){return(0,$.calculate_linear_weights)(e,t,n,r,a)}static calculatePoolTradeFee(e,t,n){return(0,$.calculate_pool_trade_fee)(e,t,n)}};var F=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a))(F||{}),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),p=e.balanceIn/this.maxInRatio;return c>p&&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,p=e.balanceOut/this.maxOutRatio;return c>p&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:c,feePct:l,errors:a}}}calculateInGivenOut(e,t){let n=j.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=j.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=j.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),this.maxOutRatio.toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=j.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),this.maxInRatio.toString());return BigInt(t)}calculateTradeFee(e,t){let n=j.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 v=require("rxjs");var H=class extends V{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,v.from)(this.getPoolsMem()).pipe((0,v.switchMap)(t=>this.subscribe(t)),(0,v.combineLatestAll)());return(0,v.firstValueFrom)(e)}getSubscriber(){return(0,v.from)(this.getPoolsMem()).pipe((0,v.switchMap)(e=>this.subscribe(e)),(0,v.mergeAll)())}subscribe(e){return e.filter(t=>this.hasValidAssets(t)).map(t=>(0,v.combineLatest)([this.subscribePoolChange(t),this.subscribePoolBalance(t)]).pipe((0,v.debounceTime)(250),(0,v.map)(([n,r])=>this.updatePool(n,r))))}subscribePoolBalance(e){if(e.type==="Aave")return(0,v.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,v.combineLatest)(t).pipe((0,v.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 H{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,p=j.calculateLinearWeights(r?r.toString():"0",a?a.toString():"0",i.toString(),o.toString(),n.toString()),[d,m]=s,b=BigInt(p),y=this.MAX_FINAL_WEIGHT-BigInt(b),[g,f,S,w,O]=await Promise.all([this.isRepayFeeApplied(d,l,c.toString()),this.getBalance(e,d),this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(e,m),this.api.query.AssetRegistry.Assets.getValue(m)]);return{repayFeeApply:g,tokens:[{id:d,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:f.transferable,weight:b,type:S?.asset_type.type},{id:m,decimals:O?.decimals,existentialDeposit:O?.existential_deposit,balance:w.transferable,weight:y,type:O?.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={};I(Ht,{OmniMath:()=>_,OmniPool:()=>Ve,OmniPoolClient:()=>Ue});var T=require("@galacticcouncil/math-omnipool"),pe=ie(require("big.js")),_=class{static calculateSpotPrice(e,t,n,r){return(0,T.calculate_spot_price)(e,t,n,r)}static calculateLrnaSpotPrice(e,t){return(0,T.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,n,r,a,s,i,o,l){return(0,T.calculate_in_given_out)(e,t,n,r,a,s,i,o,l)}static calculateLrnaInGivenOut(e,t,n,r,a){return(0,T.calculate_lrna_in_given_out)(e,t,n,r,a)}static calculateOutGivenIn(e,t,n,r,a,s,i,o,l){return(0,T.calculate_out_given_in)(e,t,n,r,a,s,i,o,l)}static calculateOutGivenLrnaIn(e,t,n,r,a){return(0,T.calculate_out_given_lrna_in)(e,t,n,r,a)}static calculateShares(e,t,n,r){return(0,T.calculate_shares)(e,t,n,r)}static calculateLiquidityOut(e,t,n,r,a,s,i,o){return(0,T.calculate_liquidity_out)(e,t,n,r,a,s,i,o)}static calculateLiquidityLRNAOut(e,t,n,r,a,s,i,o){return(0,T.calculate_liquidity_lrna_out)(e,t,n,r,a,s,i,o)}static calculateCapDifference(e,t,n,r){let a=(0,pe.default)(t),s=(0,pe.default)(e),i=(0,pe.default)(r),o=(0,pe.default)(n),l=(0,pe.default)(10).pow(18),c=o.div(l);if(a.div(i).lt(c)){let d=c.times(i).minus(a).times(s),m=a.times((0,pe.default)(1).minus(c));return d.div(m).toFixed(0)}else return"0"}static verifyAssetCap(e,t,n,r){return(0,T.verify_asset_cap)(e,t,n,r)}static calculateLimitHubIn(e,t,n,r){return(0,T.calculate_liquidity_hub_in)(e,t,n,r)}static isSellAllowed(e){return(0,T.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,T.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,T.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,T.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:A.calculateDiffToRef(a,r),i=[],o=_.isSellAllowed(e.tradeableIn),l=_.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 p=e.balanceIn/this.maxInRatio;return a>p&&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=A.calculateDiffToRef(r,a),i=[],o=_.isSellAllowed(e.tradeableIn),l=_.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 p=e.balanceOut/this.maxOutRatio;return a>p&&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=_.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=_.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=_.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=_.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=_.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=_.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=_.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=_.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 H{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:p})=>{let[d]=c,{hub_reserve:m,shares:b,tradable:y,cap:g,protocol_shares:f}=p,[S,w]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(t,d)]);return{id:d,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:w.transferable,cap:g,hubReserves:m,protocolShares:f,shares:b,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,p=e.tokens.findIndex(m=>m.id===a);return{...e.tokens[p],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={};I(Ut,{StableMath:()=>E,StableSwap:()=>We,StableSwapClient:()=>Ye});var B=require("@galacticcouncil/math-stableswap"),E=class{static getPoolAddress(e){return(0,B.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,B.calculate_amplification)(e,t,n,r,a)}static calculateInGivenOut(e,t,n,r,a,s,i){return(0,B.calculate_in_given_out)(e,t,n,r,a,s,i)}static calculateAddOneAsset(e,t,n,r,a,s,i){return(0,B.calculate_add_one_asset)(e,t,n,r,a,s,i)}static calculateSharesForAmount(e,t,n,r,a,s,i){return(0,B.calculate_shares_for_amount)(e,t,n,r,a,s,i)}static calculateOutGivenIn(e,t,n,r,a,s,i){return(0,B.calculate_out_given_in)(e,t,n,r,a,s,i)}static calculateLiquidityOutOneAsset(e,t,n,r,a,s,i){return(0,B.calculate_liquidity_out_one_asset)(e,t,n,r,a,s,i)}static calculateShares(e,t,n,r,a,s){return(0,B.calculate_shares)(e,t,n,r,a,s)}static calculateSpotPriceWithFee(e,t,n,r,a,s,i,o){return(0,B.calculate_spot_price_with_fee)(e,t,n,r,a,s,i,o)}static recalculatePegs(e,t,n,r,a){let s=(0,B.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=_.isSellAllowed(e.tradeableIn),l=_.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=_.isSellAllowed(e.tradeableIn),l=_.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=E.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=E.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=E.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=E.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=E.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=E.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=E.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=E.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=E.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,re.jsonFormatter)}getAssets(e,t){let n={asset_id:Number(e),amount:t.toString()};return JSON.stringify([n],re.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 H{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,p]=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,...p,...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=E.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]=E.recalculatePegs(JSON.stringify(s),JSON.stringify(a),n.toString(),P.toDecimals(i).toString(),P.toDecimals(o).toString()),p=Number(l)*1e6;return{pegsFee:P.fromPermill(p),pegs:c}}getDefaultPegs(e){let t=e.fee,n=E.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,p]=i.value,d=[p,a[o]].sort((S,w)=>S-w),m=await this.api.query.EmaOracle.Oracles.getValue(l,d,c);if(!m)return;let[{price:b,updated_at:y}]=m,g=b.n.toString(),f=b.d.toString();return p.toString()===d[0].toString()?[[g,f],y.toString()]:[[f,g],y.toString()]}else return[i.value.map(l=>l.toString()),n]});return Promise.all(s)}getPoolAddress(e){let t=E.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={};I(Wt,{XykMath:()=>ee,XykPool:()=>Xe,XykPoolClient:()=>ze});var R=require("@galacticcouncil/math-xyk"),ee=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=ee.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(e,t){let n=ee.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(e){let t=ee.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){let t=ee.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateTradeFee(e,t){let n=ee.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return BigInt(n)}};var _n=require("polkadot-api"),Bn=require("rxjs");var ze=class extends H{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,p,d,m]=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:p?.decimals,existentialDeposit:p?.existential_deposit,balance:c.transferable,type:p?.asset_type.type},{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,type:m?.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={};I(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 Fn=require("polkadot-api"),kn=require("@polkadot-api/utils"),Te=require("rxjs"),En=require("viem");var Rn=[{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 H{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,Fn.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(b=>b.asHex()),p=l.asHex(),{eventName:d,args:m}=(0,En.decodeEventLog)({abi:Rn,topics:c,data:p});return _r.includes(d)&&m.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"?re.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 J=require("rxjs");var Ie=class extends D{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 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,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(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={};I(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:()=>mt,TradeRouteBuilder:()=>U,TradeRouter:()=>Oe,TradeScheduler:()=>Ae,TradeType:()=>pt});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 p=[...i];p.push(c),a.enqueue(p)}})}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 p of c??[])this.isNotVisited(p,o)&&a.enqueue([...o,p])}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(g=>g.type==="XYK"),a=n.filter(g=>g.type!=="XYK"),s=new Set(a.map(g=>g.tokens).flat().map(g=>g.id)),i=s.has(e),o=s.has(t),l=new $e,c=g=>{let f=zt(g),S=Object.keys(f),w=S.flatMap(O=>f[O]);return l.buildAndPopulateGraph(S,w)};if(!i&&!o){let g=r.filter(w=>w.tokens.find(O=>O.id===e)||w.tokens.find(O=>O.id===t)),f=c(g),S=l.findPaths(f,e,t);return this.parsePaths(S)}if(i&&o){let g=c(a),f=l.findPaths(g,e,t);return this.parsePaths(f)}let p=i?t:e,d=r.filter(g=>g.tokens.some(f=>f.id===p));if(d.length===0)return[];let m=[...a,...d],b=c(m),y=l.findPaths(b,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 pt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(pt||{}),mt=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(mt||{}),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),p=a?r.tradeFeePct:A.calculateSellFee(o,i),d=Math.pow(10,n.assetInDecimals),m=n.amountIn*s/BigInt(d),b=A.calculateDiffToRef(o,m);return{type:"Sell",amountIn:n.amountIn,amountOut:r.amountOut,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,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:p,tradeFeeRange:c,priceImpactPct:b,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(g=>g.id===e)).map(y=>y.type==="Aave"?y.tokens:y.tokens.filter(g=>g.id===e)).map(y=>y.map(g=>g.balance).reduce((g,f)=>g+f)).sort((y,g)=>g<y?-1:1)[0],c=A.getFraction(l,.1),p=await Promise.all(r.map(y=>this.toSellSwaps(c,y,s))),m=this.findBestSellRoute(p).map(y=>({poolAddress:y.poolAddress,poolId:y?.poolId,pool:y.pool,assetIn:y.assetIn,assetOut:y.assetOut})),b=this.buildRouteKey(e,t,a);return this.mlr.set(b,m),m}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:p,calculatedOut:d,feePct:m,errors:b}=i.validateAndSell(o,l,c),y=this.getPoolFeeRange(c),g=i.spotPriceOutGivenIn(o),f=Math.pow(10,o.decimalsIn),S=l*g/BigInt(f),w=A.calculateDiffToRef(d,S);r.push({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:y,priceImpactPct:w,errors:b,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(p,o.decimalsOut),calculatedOut:h.toDecimal(d,o.decimalsOut),spotPrice:h.toDecimal(g,o.decimalsOut),tradeFeePct:m,tradeFeeRange:y,priceImpactPct:w,errors:b}}})}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),p=a?r.tradeFeePct:A.calculateBuyFee(o,i),d=Math.pow(10,n.assetOutDecimals),m=n.amountOut*s/BigInt(d),b;return o===0n?b=-100:b=A.calculateDiffToRef(m,o),{type:"Buy",amountOut:n.amountOut,amountIn:r.amountIn,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,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:p,tradeFeeRange:c,priceImpactPct:b,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:p,calculatedIn:d,feePct:m,errors:b}=i.validateAndBuy(o,l,c),y=this.getPoolFeeRange(c),g=i.spotPriceInGivenOut(o),f=Math.pow(10,o.decimalsOut),S=l*g/BigInt(f),w;d===0n?w=-100:w=A.calculateDiffToRef(S,d),r.unshift({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:y,priceImpactPct:w,errors:b,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(p,o.decimalsIn),calculatedIn:h.toDecimal(d,o.decimalsIn),spotPrice:h.toDecimal(g,o.decimalsIn),tradeFeePct:m,tradeFeeRange:y,priceImpactPct:w,errors:b}}})}return r}};var Dn=6e3,jt=1000000000000000n,Ze=6,Qt=-5,$t=216e5,ql=3,Cn=6;var Jt=require("polkadot-api");var U=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,p=l[0],d=l[l.length-1],{assetInDecimals:m}=p,{assetOutDecimals:b}=d,y=Math.abs(c),g=this.getMinimumTradeCount(o,s),f=this.getOptimalTradeCount(y),S=a?Math.round(r/a):f,w=Math.ceil(r/g),O=Math.round(r/f),L=Math.round(r/S),G=o/BigInt(S),M=await this.router.getBestSell(e,t,G),W=o<s,Y=[];W&&Y.push("OrderTooSmall");let te=M.amountOut*BigInt(S),Re=this.toBlockPeriod(L),se=M.tradeFee*BigInt(S),yt=U.build(l),Fe={assetIn:e,assetOut:t,errors:Y,frequencyMin:w,frequencyOpt:O,frequency:L,tradeCount:S,tradeFee:se,tradeImpactPct:M.priceImpactPct,tradePeriod:Re,tradeRoute:yt,type:"Dca"};return{...Fe,amountIn:o,amountOut:te,tradeAmountIn:M.amountIn,tradeAmountOut:M.amountOut,toHuman(){return{...Fe,amountIn:h.toDecimal(o,m),amountOut:h.toDecimal(te,b),tradeAmountIn:h.toDecimal(M.amountIn,m),tradeAmountOut:h.toDecimal(M.amountOut,b)}}}}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:p}=l,{assetOutDecimals:d}=c,m=Math.abs(o),b=this.getTwapTradeCount(m),y=s/BigInt(b),g=await this.router.getBestSell(l.assetIn,c.assetOut,y),f=b===1,S=s<r,w=g.priceImpactPct<-5,O=[];S||f?O.push("OrderTooSmall"):w&&O.push("OrderImpactTooBig");let L=g.amountOut*BigInt(b),G=g.tradeFee*BigInt(b),M=U.build(i),W={assetIn:e,assetOut:t,errors:O,tradeCount:b,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:M,type:"TwapSell"};return{...W,amountIn:s,amountOut:L,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:G,toHuman(){return{...W,amountIn:h.toDecimal(s,p),amountOut:h.toDecimal(L,d),tradeAmountIn:h.toDecimal(g.amountIn,p),tradeAmountOut:h.toDecimal(g.amountOut,d),tradeFee:h.toDecimal(G,d)}}}}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:p}=l,{assetOutDecimals:d}=c,m=Math.abs(o),b=this.getTwapTradeCount(m),y=s/BigInt(b),g=await this.router.getBestBuy(l.assetIn,c.assetOut,y),f=g.amountIn*BigInt(b),S=b===1,w=f<r,O=g.priceImpactPct<-5,L=[];w||S?L.push("OrderTooSmall"):O&&L.push("OrderImpactTooBig");let G=g.tradeFee*BigInt(b),M=U.build(i),W={assetIn:e,assetOut:t,errors:L,tradeCount:b,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:M,type:"TwapBuy"};return{...W,amountIn:f,amountOut:s,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:G,toHuman(){return{...W,amountIn:h.toDecimal(f,p),amountOut:h.toDecimal(s,d),tradeAmountIn:h.toDecimal(g.amountIn,p),tradeAmountOut:h.toDecimal(g.amountOut,d),tradeFee:h.toDecimal(G,p)}}}}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={};I(en,{BIG_10:()=>qn,BIG_BILL:()=>Nn,StakingApi:()=>et,StakingClient:()=>tt});var Mn=require("@polkadot/util-crypto"),Ln=require("@polkadot/util"),de=require("@galacticcouncil/math-staking"),me=ie(require("big.js")),qn=(0,me.default)(10),Nn=(0,me.default)(qn.pow(12));function Rr(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 getTransferablePotBalance(){let e=await this.client.getPalletId(),t=Rr(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,p=o.amount,d=o.conviction.toString(),m=await this.client.getReferendumInfo(c);return m&&(m.type==="Approved"||m.type==="Rejected")&&l.push({id:c,amount:p,conviction:d}),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,p]=await Promise.all([this.getTransferablePotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getSixBlockSince()]),d=(0,me.default)(o.toString()).minus(r.toString()),m=a.toString(),b=(0,me.default)(t).plus(1).toString();d.gt(0)&&s>0&&(m=(0,de.calculate_accumulated_rps)(a.toString(),d.toString(),s.toString()));let y=(0,de.calculate_period_number)(l.toString(),t,p??b),g=(0,de.calculate_period_number)(l.toString(),i.createdAt?.toString()??"",p??b),f=(0,de.calculate_rewards)(m,i.rewardPerStake?.toString()??"",i.stake?.toString()??""),S=(0,me.default)(f).plus(i.accumulatedUnpaidRewards?.toString()||"0").plus(i.accumulatedLockedRewards?.toString()||"0");if(!(0,me.default)(y).minus(g).lte(c.toString()))return S.div(Nn).toString()}};var tt=class extends D{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={};I(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 D{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new N,this.balanceClient=new V(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 dt=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=A.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:U.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=A.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:U.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=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:U.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=A.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=A.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 N}trade(e){return new dt(this.client,this.evmClient).setTrade(e)}order(e){return new bt(this.client,this.evmClient).setOrder(e)}};async function Fr(u,e){let t=new Pe(u),[n,r]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),a=e??new N,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 V(u),p=new tt(u),d=new et(p,c);return{api:{aave:i,router:o,scheduler:l,staking:d},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});
|
package/build/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var gn=Object.defineProperty;var T=(u,e)=>{for(var t in e)gn(u,t,{get:e[t],enumerable:!0})};var It={};T(It,{Papi:()=>B,getWs:()=>Pn});import{hydration as bn}from"@galacticcouncil/descriptors";function xt(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var B=class{client;api;constructor(e){this.client=e,this.api=this.client.getTypedApi(bn)}log(e,...t){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");xt(n)&&console.log(e,...t)}};import{createClient as hn}from"polkadot-api";import{withPolkadotSdkCompat as yn}from"polkadot-api/polkadot-sdk-compat";var Pn=async u=>{let e=typeof u=="string"?u.split(","):u,r=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(e);return hn(yn(r))};var Mt={};T(Mt,{AAVE_GAS_LIMIT:()=>$e,AAVE_LENDING_POOL_ADDRESS:()=>Ge,AAVE_POOL_ABI:()=>je,AAVE_POOL_DATA_PROVIDER:()=>Ne,AAVE_POOL_DATA_PROVIDER_ABI:()=>qe,AAVE_POOL_PROXY:()=>Qe,AAVE_ROUNDING_THRESHOLD:()=>ts,AAVE_UINT_256_MAX:()=>fn,AaveClient:()=>he,AaveUtils:()=>Q});var je=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var qe=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Qe="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ne="0x112b087b60C1a166130d59266363C45F8aa99db0",Ge="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",$e=1000000n,ts=5,fn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var _t={};T(_t,{EvmClient:()=>D,evmMainnet:()=>Je});import{defineChain as Sn}from"viem";var vt=["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"],Ot=["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"],Je=Sn({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:vt,webSocket:Ot},default:{http:vt,webSocket:Ot}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as At,createWalletClient as wn,custom as Tn,http as xn,webSocket as In}from"viem";var D=class{chain;constructor(e){this.chain=e||Je}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 At({chain:this.chain,transport:xn()})}getWsProvider(){return At({chain:this.chain,transport:In()})}getSigner(e){return wn({account:e,chain:this.chain,transport:Tn(window.ethereum)})}};var he=class{evmClient;constructor(e){this.evmClient=e??new D}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:qe,address:Ne,args:[Ge],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:qe,address:Ne,args:[Ge,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:je,address:Qe,args:[e],functionName:"getUserAccountData"})}};var y={};T(y,{asBigInt:()=>An,toBigInt:()=>On,toDecimal:()=>vn});import z from"big.js";z.NE=-18;function vn(u,e,t=6,n){let r=z(u.toString()),a=z(10).pow(e);return r.div(a).round(t,n).toString()}function On(u,e){let t=z(10).pow(e),r=z(u).mul(t).toFixed(0,z.roundDown);return BigInt(r)}function An(u){return BigInt(u.round(0,z.roundDown).toFixed(0))}var Z={};T(Z,{ERC20:()=>Ze});var Ze=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={};T(P,{fromPermill:()=>Fn,shiftNeg:()=>ye,toDecimals:()=>Rn,toPct:()=>Bn});import _n from"big.js";var Bt=1e3;function Bn(u){let[e,t]=u;return e/t*100}function Rn(u){let[e,t]=u;return e/t}function Fn(u){return[u/Bt,Bt]}function ye(u,e){let t=_n(typeof u=="bigint"?u.toString():u);return e===0?t.toString():t.div(Math.pow(10,e)).toString()}var Ve={};T(Ve,{H160:()=>at,isEvmAccount:()=>kt,isEvmAddress:()=>Et,isSs58Address:()=>Dt});import{AccountId as Pe}from"polkadot-api";import{toHex as Ft}from"@polkadot-api/utils";import{Buffer as X}from"buffer";var Rt={};T(Rt,{HUB_ASSET_ID:()=>nt,HYDRATION_OMNIPOOL_ADDRESS:()=>Dn,HYDRATION_PARACHAIN_ID:()=>En,HYDRATION_SS58_PREFIX:()=>E,PERBILL_DENOMINATOR:()=>kn,PERMILL_DENOMINATOR:()=>et,RUNTIME_DECIMALS:()=>A,SYSTEM_ASSET_DECIMALS:()=>tt,SYSTEM_ASSET_ID:()=>V,TRADEABLE_DEFAULT:()=>ee});var A=18,et=1e6,kn=1e9,V=0,tt=12,En=2034,E=63,Dn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",nt=1,ee=15;var rt="ETH\0";function kt(u){if(!u)return!1;try{let e=Pe().enc(u),t=X.from(rt);return X.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Et(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Dt(u){try{return Pe(63).enc(u),!0}catch{return!1}}var at=class u{static toAccount=e=>{let t=X.from(e.slice(2),"hex"),n=X.from(rt),r=Uint8Array.from(X.concat([n,t,X.alloc(8)])),a=Ft(r);return Pe(63).dec(a)};static fromAccount=e=>{let t=Pe().enc(e),n=X.from(rt),r=t.slice(n.length,-8);return"0x"+X.from(r).toString("hex")};static fromSS58=e=>{let n=Pe().enc(e).slice(0,20);return Ft(n)};static fromAny=e=>{if(Et(e))return e;if(kt(e))return u.fromAccount(e);if(Dt(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var j={};T(j,{findNestedKey:()=>Cn,findNestedObj:()=>Mn,jsonFormatter:()=>Ln});var Cn=(u,e)=>{let t=[];return JSON.stringify(u,(n,r)=>(r&&r[e]&&t.push(r),r)),t[0]},Mn=(u,e,t)=>{let n;return JSON.stringify(u,(r,a)=>(a&&a[e]===t&&(n=a),a)),n},Ln=(u,e)=>typeof e=="bigint"?e.toString():e;var v={};T(v,{calculateBuyFee:()=>Vn,calculateDiffToAvg:()=>qn,calculateDiffToRef:()=>Nn,calculateSellFee:()=>Gn,getFraction:()=>Hn});import U from"big.js";function qn(u,e){let t=U(u.toString()),n=U(e.toString());return t.minus(n).abs().div(t.plus(n).div(2)).mul(100).round(2).toNumber()}function Nn(u,e){if(e===0n)return 0;let t=U(u.toString()),n=U(e.toString());return t.minus(n).div(n).mul(100).round(2).toNumber()}function Gn(u,e){let t=U(u.toString()),n=U(e.toString());return U(1).minus(n.div(t)).mul(100).round(2).toNumber()}function Vn(u,e){let t=U(u.toString());return U(e.toString()).div(t).minus(1).mul(100).round(2).toNumber()}function Hn(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 Ct={};T(Ct,{convertToId:()=>Wn});import{Buffer as Un}from"buffer";function Wn(u){let t=Un.from(u.replace("0x",""),"hex").subarray(16);return t.readUIntBE(0,t.length)}var{ERC20:He}=Z,{H160:st}=Ve,Yn=1.01,Xn=99999,Kn=10n**27n,zn=10n**18n,Q=class{client;constructor(e){let t=e??new D;this.client=new he(t)}async getSummary(e){let t=st.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,p,d,m,b]=a,h=y.toDecimal(b,18),g=[];for(let f of i){let S=f.underlyingAsset.toLowerCase(),w=s.find(({underlyingAsset:K})=>K.toLowerCase()===S);if(!w)throw new Error("Missing pool reserve for "+S);let x=f.scaledATokenBalance,k=w.liquidityIndex,C=w.priceInMarketReferenceCurrency,R=x*k/Kn,G=Number(o===w.eModeCategoryId?w.eModeLiquidationThreshold:w.reserveLiquidationThreshold)/1e4,Y=w.usageAsCollateralEnabled&&f.usageAsCollateralEnabledOnUser&&f.scaledATokenBalance>0n,ge=He.toAssetId(S);g.push({aTokenBalance:R,decimals:Number(w.decimals),isCollateral:Y,priceInRef:C,reserveId:ge,reserveAsset:S,reserveLiquidationThreshold:G})}return{healthFactor:Number(h),totalCollateral:l,totalDebt:c,reserves:g}}async hasBorrowPositions(e){let t=st.fromAny(e),n=await this.client.getUserAccountData(t),[r,a]=n;return a>0n}async getHealthFactor(e){let t=st.fromAny(e),n=await this.client.getUserAccountData(t),[r,a,s,i,o,l]=n,c=y.toDecimal(l,18);return Number(c)}async getHealthFactorAfterWithdraw(e,t,n){let{totalCollateral:r,totalDebt:a,reserves:s}=await this.getSummary(e),i=He.fromAssetId(t),o=s.find(g=>g.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:c,priceInRef:p,reserveLiquidationThreshold:d}=o,m=y.toBigInt(n,l),b=c?m*p/10n**BigInt(l):0n,h=r-b;return h<=0n?0:this.calculateHealthFactor(h,d,a)}async getHealthFactorAfterSupply(e,t,n){let{totalCollateral:r,totalDebt:a,reserves:s}=await this.getSummary(e),i=He.fromAssetId(t),o=s.find(h=>h.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:p}=o,m=y.toBigInt(n,l)*c/10n**BigInt(l),b=r+m;return b<=0n?0:this.calculateHealthFactor(b,p,a)}async getMaxWithdraw(e,t){let{totalCollateral:n,totalDebt:r,reserves:a}=await this.getSummary(e),s=He.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 Xn;let r=10n**6n,a=y.toBigInt(t,18),s=e*a*r,i=n*zn,o=s/i;return Number(o)/1e6}calculateRequiredCollateral(e,t,n){let r=y.toBigInt(e,18),a=y.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(Yn,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 Vt={};T(Vt,{AssetClient:()=>te,BalanceClient:()=>M,ChainParams:()=>re,LiquidityMining:()=>ae});var te=class extends B{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:p}=await this.mapToken(a,t,n),d=Number(s),m=new Intl.DateTimeFormat("en-GB"),b=[c,"Bond",m.format(d)].join(" ");return{id:e,name:b,symbol:c+"b",decimals:p,icon:c,type:i.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:a,maturity:d}}async mapShares(e,t,n,r){let{assets:a}=r,{name:s,symbol:i,asset_type:o,is_sufficient:l,existential_deposit:c}=t,p=await Promise.all(a.map(async b=>{let{symbol:h}=await this.mapToken(b,t,n);return[b,h]})),d=Object.fromEntries(p),m=Object.values(d);return{id:e,name:m.join(", "),symbol:i?.asText()||s?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:d}}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 p=r.get(l),{asset_type:d}=c,m;switch(d.type){case"Bond":let b=s.get(l);m=await this.mapBond(l,c,i,b);break;case"StableSwap":let h=a.get(l);m=await this.mapShares(l,c,i,h);break;case"External":m=await this.mapExternal(l,c,t,p);break;default:m=await this.mapToken(l,c,i,p)}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)}};import{Subject as jn,bufferCount as Qn,combineLatest as $n,debounceTime as Jn,distinctUntilChanged as Lt,finalize as Zn,map as ne,pairwise as er,shareReplay as tr,startWith as nr}from"rxjs";var M=class extends B{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 $n([t,n,r]).pipe(Jn(250),ne(a=>a.flat()),nr([]),Qn(2,1),ne(([a,s],i)=>{if(i===0)return s;let o=a.reduce((c,p)=>(c.set(p.id,p.balance),c),new Map);return s.filter(c=>!qt(c.balance,o.get(c.id)))}))}subscribeSystemBalance(e){return this.api.query.System.Account.watchValue(e,"best").pipe(ne(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(e,t){return this.api.query.Tokens.Accounts.watchValue(e,t,"best").pipe(ne(r=>({id:t,balance:r})))}subscribeTokensBalance(e){return this.api.query.Tokens.Accounts.watchEntries(e,{at:"best"}).pipe(Lt((n,r)=>!r.deltas),ne(({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 jn,r=n.pipe(tr(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 d=(await Promise.all(o.map(async m=>{let b=await this.getTokenBalanceData(e,m);return[m,b]}))).map(([m,b])=>({id:m,balance:b}));n.next(d)};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(Zn(()=>i?.()),er(),ne(([o,l],c)=>{if(c===0)return l;let p=o.reduce((m,b)=>(m.set(b.id,b.balance),m),new Map);return l.filter(m=>!qt(m.balance,p.get(m.id)))}),Lt((o,l)=>l.length===0))}async getTokenBalanceData(e,t){let n=await this.api.apis.CurrenciesApi.account(t,e);return this.calculateBalance(n)}},qt=(u,e)=>u!==void 0&&e!==void 0&&u.transferable===e.transferable&&u.total===e.total;var re=class extends B{_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}};import{AccountId as lr,Binary as cr,Enum as ur}from"polkadot-api";import{fixed_from_rational as Gt}from"@galacticcouncil/math-liquidity-mining";import F from"big.js";import $ from"big.js";import{calculate_accumulated_rps as rr,calculate_global_farm_rewards as ar,calculate_loyalty_multiplier as sr,calculate_user_reward as Nt,calculate_yield_farm_delta_rpvs as ir}from"@galacticcouncil/math-liquidity-mining";var or="1000000000000000000",Ue=class{constructor(e,t,n){this.get_account=e;this.multiCurrency=t;this.getAsset=n}async sync_global_farm(e,t,n){if(e.state.type!=="Active"||e.updated_at===t)return null;if(e.total_shares_z===0n)return e;let r=await this.getAsset(e.reward_currency),a=t-e.updated_at,s=this.get_account(e.id),i=r?.existential_deposit;if(!i)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.free_balance(e.reward_currency,s),l=$(i.toString()),c=$(o.toString()).minus(l.lt(o.toString())?i.toString():o.toString()),p=$(ar(e.total_shares_z.toString(),n.toString(),$(e.yield_per_period.toString()).mul(it).round(0,$.roundDown).toFixed(),e.max_reward_per_period.toString(),a.toFixed()));if(c.lt(p)&&(p=c),p.eq(0))return e;let d=this.get_account(0);return this.multiCurrency.transfer(e.reward_currency,s,d,BigInt(p.toFixed())),{...e,accumulated_rpz:BigInt(rr(e.accumulated_rpz.toString(),e.total_shares_z.toString(),p.toFixed()))}}sync_yield_farm(e,t,n){if(e.state.type!=="Active"||e.updated_at===n)return null;if(e.total_valued_shares===0n)return{...e,updated_at:n};let r=ir(e.accumulated_rpz.toString(),t.accumulated_rpz.toString(),e.multiplier.toString(),e.total_valued_shares.toString());return{...e,accumulated_rpvs:e.accumulated_rpvs+BigInt(r),updated_at:n}}get_loyalty_multiplier(e,t){let n=$(1).mul(it).round(0,$.roundDown).toString();if(!t)return n;let{initial_reward_percentage:r,scale_coef:a}=t;return sr(e.toFixed(),r.toString(),a.toFixed())}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(n.updated_at===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,s);if(!o)return null;let l=o.total_stopped-n.stopped_at_creation,c=o.updated_at-n.entered_at-l,p=this.get_loyalty_multiplier(c,o.loyalty_curve),d=BigInt(Nt(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),m=BigInt(Nt(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),or));return{reward:d,maxReward:m,assetId:i.reward_currency}}};var pr=BigInt(F(1).pow(18).toString()),mr=6,ae=class extends B{balanceClient;omnipoolAssetIds=[];secondsInYear=F(365.2425).times(24).times(60).times(60);constructor(e){super(e),this.balanceClient=new M(e)}async getOraclePrice(e,t){let n=[e,t].sort((a,s)=>a-s);if(e===t)return pr;let r=await this.api.query.EmaOracle.Oracles.getValue(cr.fromText("omnipool"),n,ur("TenMinutes"));if(r){let{n:a,d:s}=r[0].price,i;return e<t?i=Gt(a.toString(),s.toString()):i=Gt(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 lr(63).dec(o)};getGlobalRewardPerPeriod(e,t,n,r){let a=F(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=F(e.toString()).times(t),s=F(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:p,total_shares_z:d,max_reward_per_period:m,pending_rewards:b,accumulated_paid_rewards:h,planned_yielding_periods:g,updated_at:f,incentivized_asset:S,reward_currency:w,price_adjustment:x}=a,k=ye(s??x,18),C=ye(o,18),R=ye(l?.initial_reward_percentage??0,18),N=this.secondsInYear.div(F(mr).times(c)).toString(),G;if(d<0)G=F(C).times(p.toString()).times(N).toString();else{let mn=this.getGlobalRewardPerPeriod(d,p,m,k),dn=this.getPoolYieldPerPeriod(mn,C,d,k);G=F(dn).times(N).toString()}let Y=b+h,ge=m*BigInt(g),K=i.transferable+Y,ze=K-Y,be=F(ze.toString()).div(m.toString()),wt=F(t).div(c.toString()).toString(),cn=(d>=0?be.plus(f):be.plus(wt)).toString(),un=F(d.toString()).div(F(m.toString()).div(p.toString())).div(Math.pow(10,18)).times(100).times(k).toFixed(2),Tt=F(Y.toString()).div(K.toString()).gte(.999);G=Tt?"0":F(G).div(n?2:1).times(100).toString();let pn=R?F(G).times(R).toString():void 0;return{apr:G,minApr:pn,isDistributed:Tt,estimatedEndPeriod:cn,maxRewards:ge,incentivizedAsset:S,rewardCurrency:w,loyaltyCurve:l,currentPeriod:wt,potMaxRewards:K,fullness:un}}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),p=await this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(Number(e),o,l);if(!c||!p)return;let d=c.reward_currency,m=c.incentivized_asset,b=this.getFarmAddress(o),h=await this.getOraclePrice(d,m),g=await this.balanceClient.getTokenBalance(b,d);return{id:e,globalFarm:c,yieldFarm:p,priceAdjustment:h,balance:g}}));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),p=await this.api.query.XYKWarehouseLM.YieldFarm.getValue(e,o,l);if(!c||!p)return;let d=c.reward_currency,m=c.incentivized_asset,b=this.getFarmAddress(o,!0),h=await this.getOraclePrice(d,m),g=await this.balanceClient.getBalance(b,d);return{id:e,globalFarm:c,yieldFarm:p,priceAdjustment:h,balance:g,farmAddress:b}}));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,p=[[this.getFarmAddress(0,n),o.reward_currency],[this.getFarmAddress(o.id,n),o.reward_currency]],d=await dr(this.api,p)(),m=await this.getOraclePrice(l,c),b=new lt(p,d),g=await new Ue(S=>this.getFarmAddress(S),b,S=>this.api.query.AssetRegistry.Assets.getValue(S)).claim_rewards(o,i,t,r,m??o.price_adjustment);if(!g)return;let f=await this.api.query.AssetRegistry.Assets.getValue(g.assetId);if(f&&!(g.reward<=f.existential_deposit))return g}},it=F(10).pow(18),ot="0",dr=(u,e)=>async()=>{let[t,n]=await Promise.all([u.query.Tokens.Accounts.getValues(e.filter(([a,s])=>s.toString()!==ot)),u.query.System.Account.getValues(e.filter(([a,s])=>s.toString()===ot).map(([a])=>[a]))]),r=[];for(let a=0,s=0;a+s<e.length;){let i=a+s,[,o]=e[i];o.toString()===ot?(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 Ht={};T(Ht,{AssetNotFound:()=>ct,PoolNotFound:()=>fe,RouteNotFound:()=>Se});var ct=class extends Error{constructor(e){super(),this.message=`${e} not found`,this.name="AssetNotFound"}},fe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Se=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in current configuration`,this.name="RouteNotFound"}};var Qt={};T(Qt,{PoolContextProvider:()=>oe,PoolError:()=>J,PoolFactory:()=>ie,PoolType:()=>O,aave:()=>gt,lbp:()=>ut,omni:()=>pt,stable:()=>mt,xyk:()=>dt});var ut={};T(ut,{LbpMath:()=>H,LbpPool:()=>we,LbpPoolClient:()=>Te});import{calculate_in_given_out as gr,calculate_out_given_in as br,calculate_linear_weights as hr,calculate_pool_trade_fee as yr,get_spot_price as Pr}from"@galacticcouncil/math-lbp";var H=class{static getSpotPrice(e,t,n,r,a){return Pr(e,t,n,r,a)}static calculateInGivenOut(e,t,n,r,a){return gr(e,t,n,r,a)}static calculateOutGivenIn(e,t,n,r,a){return br(e,t,n,r,a)}static calculateLinearWeights(e,t,n,r,a){return hr(e,t,n,r,a)}static calculatePoolTradeFee(e,t,n){return yr(e,t,n)}};var O=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a))(O||{}),J=(a=>(a.InsufficientTradingAmount="InsufficientTradingAmount",a.MaxInRatioExceeded="MaxInRatioExceeded",a.MaxOutRatioExceeded="MaxOutRatioExceeded",a.TradeNotAllowed="TradeNotAllowed",a.UnknownError="UnknownError",a))(J||{});var we=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),p=e.balanceIn/this.maxInRatio;return c>p&&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,p=e.balanceOut/this.maxOutRatio;return c>p&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:c,feePct:l,errors:a}}}calculateInGivenOut(e,t){let n=H.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=H.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=H.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),this.maxOutRatio.toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=H.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),this.maxInRatio.toString());return BigInt(t)}calculateTradeFee(e,t){let n=H.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as vr}from"polkadot-api";import{map as Or,of as Kt,switchMap as Ar}from"rxjs";import{memoize1 as fr}from"@thi.ng/memoize";import{combineLatest as Ut,combineLatestAll as Sr,debounceTime as wr,firstValueFrom as Tr,from as Wt,map as Yt,mergeAll as xr,of as Ir,switchMap as Xt}from"rxjs";var L=class extends M{override=[];mem=0;memPools=fr(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=Wt(this.getPoolsMem()).pipe(Xt(t=>this.subscribe(t)),Sr());return Tr(e)}getSubscriber(){return Wt(this.getPoolsMem()).pipe(Xt(e=>this.subscribe(e)),xr())}subscribe(e){return e.filter(t=>this.hasValidAssets(t)).map(t=>Ut([this.subscribePoolChange(t),this.subscribePoolBalance(t)]).pipe(wr(250),Yt(([n,r])=>this.updatePool(n,r))))}subscribePoolBalance(e){if(e.type==="Aave")return Ir([]);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 Ut(t).pipe(Yt(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 Te=class extends L{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,p=H.calculateLinearWeights(r?r.toString():"0",a?a.toString():"0",i.toString(),o.toString(),n.toString()),[d,m]=s,b=BigInt(p),h=this.MAX_FINAL_WEIGHT-BigInt(b),[g,f,S,w,x]=await Promise.all([this.isRepayFeeApplied(d,l,c.toString()),this.getBalance(e,d),this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(e,m),this.api.query.AssetRegistry.Assets.getValue(m)]);return{repayFeeApply:g,tokens:[{id:d,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:f.transferable,weight:b,type:S?.asset_type.type},{id:m,decimals:x?.decimals,existentialDeposit:x?.existential_deposit,balance:w.transferable,weight:h,type:x?.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(vr.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(e.address);return n?t.watchValue("best").pipe(Ar(r=>r?this.getPoolDelta(e.address,n,r.relay_parent_number):Kt(e)),Or(r=>Object.assign({},e,r))):Kt(e)}};var pt={};T(pt,{OmniMath:()=>I,OmniPool:()=>xe,OmniPoolClient:()=>Ie});import{calculate_in_given_out as _r,calculate_lrna_in_given_out as Br,calculate_out_given_in as Rr,calculate_out_given_lrna_in as Fr,calculate_spot_price as kr,calculate_lrna_spot_price as Er,calculate_shares as Dr,calculate_liquidity_out as Cr,calculate_liquidity_lrna_out as Mr,verify_asset_cap as Lr,calculate_liquidity_hub_in as qr,is_sell_allowed as Nr,is_buy_allowed as Gr,is_add_liquidity_allowed as Vr,is_remove_liquidity_allowed as Hr}from"@galacticcouncil/math-omnipool";import se from"big.js";var I=class{static calculateSpotPrice(e,t,n,r){return kr(e,t,n,r)}static calculateLrnaSpotPrice(e,t){return Er(e,t)}static calculateInGivenOut(e,t,n,r,a,s,i,o,l){return _r(e,t,n,r,a,s,i,o,l)}static calculateLrnaInGivenOut(e,t,n,r,a){return Br(e,t,n,r,a)}static calculateOutGivenIn(e,t,n,r,a,s,i,o,l){return Rr(e,t,n,r,a,s,i,o,l)}static calculateOutGivenLrnaIn(e,t,n,r,a){return Fr(e,t,n,r,a)}static calculateShares(e,t,n,r){return Dr(e,t,n,r)}static calculateLiquidityOut(e,t,n,r,a,s,i,o){return Cr(e,t,n,r,a,s,i,o)}static calculateLiquidityLRNAOut(e,t,n,r,a,s,i,o){return Mr(e,t,n,r,a,s,i,o)}static calculateCapDifference(e,t,n,r){let a=se(t),s=se(e),i=se(r),o=se(n),l=se(10).pow(18),c=o.div(l);if(a.div(i).lt(c)){let d=c.times(i).minus(a).times(s),m=a.times(se(1).minus(c));return d.div(m).toFixed(0)}else return"0"}static verifyAssetCap(e,t,n,r){return Lr(e,t,n,r)}static calculateLimitHubIn(e,t,n,r){return qr(e,t,n,r)}static isSellAllowed(e){return Nr(e)}static isBuyAllowed(e){return Gr(e)}static isAddLiquidityAllowed(e){return Vr(e)}static isRemoveLiquidityAllowed(e){return Hr(e)}};var xe=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:v.calculateDiffToRef(a,r),i=[],o=I.isSellAllowed(e.tradeableIn),l=I.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 p=e.balanceIn/this.maxInRatio;return a>p&&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=v.calculateDiffToRef(r,a),i=[],o=I.isSellAllowed(e.tradeableIn),l=I.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 p=e.balanceOut/this.maxOutRatio;return a>p&&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=I.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=I.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=I.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=I.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=I.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=I.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=I.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=I.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}};import{AccountId as Ur,CompatibilityLevel as Wr}from"polkadot-api";import{toHex as Yr}from"@polkadot-api/utils";import{distinctUntilChanged as Xr,map as zt}from"rxjs";var Ie=class extends L{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:p})=>{let[d]=c,{hub_reserve:m,shares:b,tradable:h,cap:g,protocol_shares:f}=p,[S,w]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(t,d)]);return{id:d,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:w.transferable,cap:g,hubReserves:m,protocolShares:f,shares:b,tradeable:h,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=Yr(t);return Ur(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(Wr.BackwardsCompatible,t)}subscribePoolChange(e){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(Xr((n,r)=>!r.deltas),zt(({entries:n})=>n.map(r=>{let[a]=r.args,{hub_reserve:s,shares:i,tradable:o,cap:l,protocol_shares:c}=r.value,p=e.tokens.findIndex(m=>m.id===a);return{...e.tokens[p],cap:l,hubReserves:s,protocolShares:c,shares:i,tradeable:o}})),zt(n=>{let r=e.tokens.find(a=>a.id===1);return{...e,tokens:[...n,r]}}))}};var mt={};T(mt,{StableMath:()=>_,StableSwap:()=>ve,StableSwapClient:()=>Oe});import{calculate_in_given_out as Kr,calculate_out_given_in as zr,calculate_amplification as jr,calculate_add_one_asset as Qr,calculate_liquidity_out_one_asset as $r,calculate_shares as Jr,calculate_shares_for_amount as Zr,calculate_spot_price_with_fee as ea,pool_account_name as ta,recalculate_peg as na}from"@galacticcouncil/math-stableswap";var _=class{static getPoolAddress(e){return ta(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 jr(e,t,n,r,a)}static calculateInGivenOut(e,t,n,r,a,s,i){return Kr(e,t,n,r,a,s,i)}static calculateAddOneAsset(e,t,n,r,a,s,i){return Qr(e,t,n,r,a,s,i)}static calculateSharesForAmount(e,t,n,r,a,s,i){return Zr(e,t,n,r,a,s,i)}static calculateOutGivenIn(e,t,n,r,a,s,i){return zr(e,t,n,r,a,s,i)}static calculateLiquidityOutOneAsset(e,t,n,r,a,s,i){return $r(e,t,n,r,a,s,i)}static calculateShares(e,t,n,r,a,s){return Jr(e,t,n,r,a,s)}static calculateSpotPriceWithFee(e,t,n,r,a,s,i,o){return ea(e,t,n,r,a,s,i,o)}static recalculatePegs(e,t,n,r,a){let s=na(e,t,n,r,a);return JSON.parse(s)}};var ve=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=I.isSellAllowed(e.tradeableIn),l=I.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=I.isSellAllowed(e.tradeableIn),l=I.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=_.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=_.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=_.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=_.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=_.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=_.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=_.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=_.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=_.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,j.jsonFormatter)}getAssets(e,t){let n={asset_id:Number(e),amount:t.toString()};return JSON.stringify([n],j.jsonFormatter)}};import{AccountId as ra,CompatibilityLevel as aa}from"polkadot-api";import{toHex as sa}from"@polkadot-api/utils";import{blake2b as ia}from"@noble/hashes/blake2b";import{map as oa,of as la,switchMap as ca}from"rxjs";var ua=340282366920938463463374607431768211455n,Oe=class extends L{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,p]=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,...p,...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=_.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:ua,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]=_.recalculatePegs(JSON.stringify(s),JSON.stringify(a),n.toString(),P.toDecimals(i).toString(),P.toDecimals(o).toString()),p=Number(l)*1e6;return{pegsFee:P.fromPermill(p),pegs:c}}getDefaultPegs(e){let t=e.fee,n=_.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,p]=i.value,d=[p,a[o]].sort((S,w)=>S-w),m=await this.api.query.EmaOracle.Oracles.getValue(l,d,c);if(!m)return;let[{price:b,updated_at:h}]=m,g=b.n.toString(),f=b.d.toString();return p.toString()===d[0].toString()?[[g,f],h.toString()]:[[f,g],h.toString()]}else return[i.value.map(l=>l.toString()),n]});return Promise.all(s)}getPoolAddress(e){let t=_.getPoolAddress(e),n=ia(t,{dkLen:32}),r=sa(n);return ra(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(aa.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.System.Number,n=this.poolsData.get(e.address);return!n||!e.id?la(e):t.watchValue("best").pipe(ca(r=>this.getPoolDelta(e.id,n,r)),oa(r=>Object.assign({},e,r)))}};var dt={};T(dt,{XykMath:()=>W,XykPool:()=>Ae,XykPoolClient:()=>_e});import{calculate_in_given_out as pa,calculate_out_given_in as ma,calculate_pool_trade_fee as da,get_spot_price as ga,calculate_liquidity_in as ba,calculate_shares as ha,calculate_spot_price as ya,calculate_spot_price_with_fee as Pa,calculate_liquidity_out_asset_a as fa,calculate_liquidity_out_asset_b as Sa}from"@galacticcouncil/math-xyk";var W=class{static getSpotPrice(e,t,n){return ga(e,t,n)}static calculateInGivenOut(e,t,n){return pa(e,t,n)}static calculateOutGivenIn(e,t,n){return ma(e,t,n)}static calculatePoolTradeFee(e,t,n){return da(e,t,n)}static calculateLiquidityIn(e,t,n){return ba(e,t,n)}static calculateSpotPrice(e,t){return ya(e,t)}static calculateSpotPriceWithFee(e,t,n,r){return Pa(e,t,n,r)}static calculateShares(e,t,n){return ha(e,t,n)}static calculateLiquidityOutAssetA(e,t,n,r){return fa(e,t,n,r)}static calculateLiquidityOutAssetB(e,t,n,r){return Sa(e,t,n,r)}};var Ae=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=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(e,t){let n=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(e){let t=W.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){let t=W.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateTradeFee(e,t){let n=W.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as wa}from"polkadot-api";import{of as Ta}from"rxjs";var _e=class extends L{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,p,d,m]=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:p?.decimals,existentialDeposit:p?.existential_deposit,balance:c.transferable,type:p?.asset_type.type},{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,type:m?.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(wa.BackwardsCompatible,t)}subscribePoolChange(e){return Ta(e)}};var gt={};T(gt,{AavePool:()=>Be,AavePoolClient:()=>Re});var Be=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}};import{AccountId as xa}from"polkadot-api";import{toHex as Ia}from"@polkadot-api/utils";import{map as va,merge as Oa,switchMap as Aa}from"rxjs";import{decodeEventLog as _a}from"viem";var jt=[{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:Ba}=Z,Ra=["Supply","Withdraw","Repay","Borrow"],Re=class extends L{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=Ia(r);return xa(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(b=>b.asHex()),p=l.asHex(),{eventName:d,args:m}=_a({abi:jt,topics:c,data:p});return Ra.includes(d)&&m.reserve.toLowerCase()===r.toLowerCase()});return Oa([a,s]).pipe(Aa(()=>this.getPoolDelta(e)),va(i=>({...e,tokens:[...i]})))}getReserveH160Id(e){return e.type==="Erc20"?j.findNestedKey(e.location,"AccountKey20").AccountKey20.key:Ba.fromAssetId(e.id)}};var ie=class{static get(e){switch(e.type){case"Aave":return Be.fromPool(e);case"XYK":return Ae.fromPool(e);case"Omnipool":return xe.fromPool(e);case"LBP":return we.fromPool(e);case"Stableswap":return ve.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{Subject as Fa,Subscription as Fe,takeUntil as ka}from"rxjs";var oe=class extends B{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=Fe.EMPTY;omniSub=Fe.EMPTY;stableSub=Fe.EMPTY;xykSub=Fe.EMPTY;aaveSub=Fe.EMPTY;isReady=!1;isDestroyed=new Fa;constructor(e){super(e),this.lbpClient=new Te(e),this.omniClient=new Ie(e),this.stableClient=new Oe(e),this.xykClient=new _e(e),this.aaveClient=new Re(e),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(e){return e.getSubscriber().pipe(ka(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 fe(e.type)}};var en={};T(en,{DEFAULT_BLOCK_TIME:()=>$t,DEFAULT_MIN_BUDGET:()=>yt,ORDER_MIN_BLOCK_PERIOD:()=>Jt,Router:()=>le,TWAP_BLOCK_PERIOD:()=>Ce,TWAP_MAX_DURATION:()=>ft,TWAP_MAX_PRICE_IMPACT:()=>Pt,TWAP_TX_MULTIPLIER:()=>Ou,TradeOrderError:()=>ht,TradeOrderType:()=>Ye,TradeRouteBuilder:()=>q,TradeRouter:()=>ce,TradeScheduler:()=>ue,TradeType:()=>We});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 Ea=8,Ee=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 ke,s=[];for(s.push([t,""]),a.enqueue(s);a.size()>0;){let i=a.dequeue();if(!i||i.length>Ea)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 p=[...i];p.push(c),a.enqueue(p)}})}return r}findShortestPaths(e,t,n){let r=[],a=new ke,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 p of c??[])this.isNotVisited(p,o)&&a.enqueue([...o,p])}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 bt(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 De=class{getProposals(e,t,n){let r=n.filter(g=>g.type==="XYK"),a=n.filter(g=>g.type!=="XYK"),s=new Set(a.map(g=>g.tokens).flat().map(g=>g.id)),i=s.has(e),o=s.has(t),l=new Ee,c=g=>{let f=bt(g),S=Object.keys(f),w=S.flatMap(x=>f[x]);return l.buildAndPopulateGraph(S,w)};if(!i&&!o){let g=r.filter(w=>w.tokens.find(x=>x.id===e)||w.tokens.find(x=>x.id===t)),f=c(g),S=l.findPaths(f,e,t);return this.parsePaths(S)}if(i&&o){let g=c(a),f=l.findPaths(g,e,t);return this.parsePaths(f)}let p=i?t:e,d=r.filter(g=>g.tokens.some(f=>f.id===p));if(d.length===0)return[];let m=[...a,...d],b=c(m),h=l.findPaths(b,e,t);return this.parsePaths(h)}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 le=class{routeSuggester;routeProposals;routerOptions;ctx;constructor(e,t={}){this.ctx=e,this.routeSuggester=new De,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,ie.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 We=(t=>(t.Buy="Buy",t.Sell="Sell",t))(We||{}),Ye=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Ye||{}),ht=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(ht||{});var ce=class extends le{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 Se(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),p=a?r.tradeFeePct:v.calculateSellFee(o,i),d=Math.pow(10,n.assetInDecimals),m=n.amountIn*s/BigInt(d),b=v.calculateDiffToRef(o,m);return{type:"Sell",amountIn:n.amountIn,amountOut:r.amountOut,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:t,toHuman(){return{type:"Sell",amountIn:y.toDecimal(n.amountIn,n.assetInDecimals),amountOut:y.toDecimal(r.amountOut,r.assetOutDecimals),spotPrice:y.toDecimal(s,r.assetOutDecimals),tradeFee:y.toDecimal(l,r.assetOutDecimals),tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:t.map(h=>h.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(h=>h.tokens.some(g=>g.id===e)).map(h=>h.type==="Aave"?h.tokens:h.tokens.filter(g=>g.id===e)).map(h=>h.map(g=>g.balance).reduce((g,f)=>g+f)).sort((h,g)=>g<h?-1:1)[0],c=v.getFraction(l,.1),p=await Promise.all(r.map(h=>this.toSellSwaps(c,h,s))),m=this.findBestSellRoute(p).map(h=>({poolAddress:h.poolAddress,poolId:h?.poolId,pool:h.pool,assetIn:h.assetIn,assetOut:h.assetOut})),b=this.buildRouteKey(e,t,a);return this.mlr.set(b,m),m}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"?y.toBigInt(e,o.decimalsIn):e;let c=await this.ctx.getPoolFees(i,o.assetOut),{amountOut:p,calculatedOut:d,feePct:m,errors:b}=i.validateAndSell(o,l,c),h=this.getPoolFeeRange(c),g=i.spotPriceOutGivenIn(o),f=Math.pow(10,o.decimalsIn),S=l*g/BigInt(f),w=v.calculateDiffToRef(d,S);r.push({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:h,priceImpactPct:w,errors:b,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:y.toDecimal(l,o.decimalsIn),amountOut:y.toDecimal(p,o.decimalsOut),calculatedOut:y.toDecimal(d,o.decimalsOut),spotPrice:y.toDecimal(g,o.decimalsOut),tradeFeePct:m,tradeFeeRange:h,priceImpactPct:w,errors:b}}})}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),p=a?r.tradeFeePct:v.calculateBuyFee(o,i),d=Math.pow(10,n.assetOutDecimals),m=n.amountOut*s/BigInt(d),b;return o===0n?b=-100:b=v.calculateDiffToRef(m,o),{type:"Buy",amountOut:n.amountOut,amountIn:r.amountIn,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:t,toHuman(){return{type:"Buy",amountOut:y.toDecimal(n.amountOut,n.assetOutDecimals),amountIn:y.toDecimal(r.amountIn,r.assetInDecimals),spotPrice:y.toDecimal(s,r.assetInDecimals),tradeFee:y.toDecimal(l,r.assetInDecimals),tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:t.map(h=>h.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"?y.toBigInt(e,o.decimalsOut):e:l=r[0].amountIn;let c=await this.ctx.getPoolFees(i,o.assetOut),{amountIn:p,calculatedIn:d,feePct:m,errors:b}=i.validateAndBuy(o,l,c),h=this.getPoolFeeRange(c),g=i.spotPriceInGivenOut(o),f=Math.pow(10,o.decimalsOut),S=l*g/BigInt(f),w;d===0n?w=-100:w=v.calculateDiffToRef(S,d),r.unshift({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:h,priceImpactPct:w,errors:b,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:y.toDecimal(l,o.decimalsOut),amountIn:y.toDecimal(p,o.decimalsIn),calculatedIn:y.toDecimal(d,o.decimalsIn),spotPrice:y.toDecimal(g,o.decimalsIn),tradeFeePct:m,tradeFeeRange:h,priceImpactPct:w,errors:b}}})}return r}};var $t=6e3,yt=1000000000000000n,Ce=6,Pt=-5,ft=216e5,Ou=3,Jt=6;import{Enum as Zt}from"polkadot-api";var q=class{static build(e){return e.map(({assetIn:t,assetOut:n,pool:r,poolId:a})=>r==="Stableswap"?{pool:Zt("Stableswap",a),asset_in:t,asset_out:n}:{pool:Zt(r),asset_in:t,asset_out:n})}};var ue=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??6e3,minBudgetInNative:t.minBudgetInNative??yt})}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,p=l[0],d=l[l.length-1],{assetInDecimals:m}=p,{assetOutDecimals:b}=d,h=Math.abs(c),g=this.getMinimumTradeCount(o,s),f=this.getOptimalTradeCount(h),S=a?Math.round(r/a):f,w=Math.ceil(r/g),x=Math.round(r/f),k=Math.round(r/S),C=o/BigInt(S),R=await this.router.getBestSell(e,t,C),N=o<s,G=[];N&&G.push("OrderTooSmall");let Y=R.amountOut*BigInt(S),ge=this.toBlockPeriod(k),K=R.tradeFee*BigInt(S),ze=q.build(l),be={assetIn:e,assetOut:t,errors:G,frequencyMin:w,frequencyOpt:x,frequency:k,tradeCount:S,tradeFee:K,tradeImpactPct:R.priceImpactPct,tradePeriod:ge,tradeRoute:ze,type:"Dca"};return{...be,amountIn:o,amountOut:Y,tradeAmountIn:R.amountIn,tradeAmountOut:R.amountOut,toHuman(){return{...be,amountIn:y.toDecimal(o,m),amountOut:y.toDecimal(Y,b),tradeAmountIn:y.toDecimal(R.amountIn,m),tradeAmountOut:y.toDecimal(R.amountOut,b)}}}}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:p}=l,{assetOutDecimals:d}=c,m=Math.abs(o),b=this.getTwapTradeCount(m),h=s/BigInt(b),g=await this.router.getBestSell(l.assetIn,c.assetOut,h),f=b===1,S=s<r,w=g.priceImpactPct<-5,x=[];S||f?x.push("OrderTooSmall"):w&&x.push("OrderImpactTooBig");let k=g.amountOut*BigInt(b),C=g.tradeFee*BigInt(b),R=q.build(i),N={assetIn:e,assetOut:t,errors:x,tradeCount:b,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapSell"};return{...N,amountIn:s,amountOut:k,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:C,toHuman(){return{...N,amountIn:y.toDecimal(s,p),amountOut:y.toDecimal(k,d),tradeAmountIn:y.toDecimal(g.amountIn,p),tradeAmountOut:y.toDecimal(g.amountOut,d),tradeFee:y.toDecimal(C,d)}}}}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:p}=l,{assetOutDecimals:d}=c,m=Math.abs(o),b=this.getTwapTradeCount(m),h=s/BigInt(b),g=await this.router.getBestBuy(l.assetIn,c.assetOut,h),f=g.amountIn*BigInt(b),S=b===1,w=f<r,x=g.priceImpactPct<-5,k=[];w||S?k.push("OrderTooSmall"):x&&k.push("OrderImpactTooBig");let C=g.tradeFee*BigInt(b),R=q.build(i),N={assetIn:e,assetOut:t,errors:k,tradeCount:b,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapBuy"};return{...N,amountIn:f,amountOut:s,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:C,toHuman(){return{...N,amountIn:y.toDecimal(f,p),amountOut:y.toDecimal(s,d),tradeAmountIn:y.toDecimal(g.amountIn,p),tradeAmountOut:y.toDecimal(g.amountOut,d),tradeFee:y.toDecimal(C,p)}}}}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 an={};T(an,{BIG_10:()=>nn,BIG_BILL:()=>rn,StakingApi:()=>Me,StakingClient:()=>Le});import{encodeAddress as Da}from"@polkadot/util-crypto";import{stringToU8a as Ca}from"@polkadot/util";import{calculate_accumulated_rps as Ma,calculate_period_number as tn,calculate_rewards as La}from"@galacticcouncil/math-staking";import pe from"big.js";var nn=pe(10),rn=pe(nn.pow(12));function qa(u){return Da(Ca(("modl"+u).padEnd(32,"\0")),63)}var Me=class{client;balanceClient;constructor(e,t){this.client=e,this.balanceClient=t}async getTransferablePotBalance(){let e=await this.client.getPalletId(),t=qa(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,p=o.amount,d=o.conviction.toString(),m=await this.client.getReferendumInfo(c);return m&&(m.type==="Approved"||m.type==="Rejected")&&l.push({id:c,amount:p,conviction:d}),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,p]=await Promise.all([this.getTransferablePotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getSixBlockSince()]),d=pe(o.toString()).minus(r.toString()),m=a.toString(),b=pe(t).plus(1).toString();d.gt(0)&&s>0&&(m=Ma(a.toString(),d.toString(),s.toString()));let h=tn(l.toString(),t,p??b),g=tn(l.toString(),i.createdAt?.toString()??"",p??b),f=La(m,i.rewardPerStake?.toString()??"",i.stake?.toString()??""),S=pe(f).plus(i.accumulatedUnpaidRewards?.toString()||"0").plus(i.accumulatedLockedRewards?.toString()||"0");if(!pe(h).minus(g).lte(c.toString()))return S.div(rn).toString()}};var Le=class extends B{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 ln={};T(ln,{TxBuilderFactory:()=>de});import{Enum as on}from"polkadot-api";function sn(u){let e=[],t=u;for(;t&&typeof t=="object"&&"type"in t;)e.push(t.type),t=t.value;return e.join(".")}var me=class extends B{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new D,this.balanceClient=new M(e),this.aaveUtils=new Q(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:$e})}async dryRun(e,t){let n=on("Signed",e),r=on("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=sn(i.value);throw new Error("Dry run execution error!",{cause:o})}return s}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Xe=class extends me{_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=v.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:q.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=v.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:q.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=v.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:q.build(t)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as St}from"polkadot-api";var Ke=class extends me{_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:St("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=v.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:St("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=v.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:St("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 de=class{client;evmClient;constructor(e,t){this.client=e,this.evmClient=t??new D}trade(e){return new Xe(this.client,this.evmClient).setTrade(e)}order(e){return new Ke(this.client,this.evmClient).setOrder(e)}};async function Mp(u,e){let t=new re(u),[n,r]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),a=e??new D,s=new oe(u).withAave().withOmnipool().withStableswap().withXyk(),i=new Q(a),o=new ce(s),l=new ue(o,{blockTime:n,minBudgetInNative:r}),c=new M(u),p=new Le(u),d=new Me(p,c);return{api:{aave:i,router:o,scheduler:l,staking:d},client:{asset:new te(u),balance:c,evm:a,mining:new ae(u)},ctx:{pool:s},tx:new de(u,a),destroy:()=>{s.destroy()}}}export{Mt as aave,It as api,y as big,Vt as client,Rt as const,Mp as createSdkContext,Z as erc20,Ht as error,_t as evm,P as fmt,Ve as h160,j as json,v as math,Qt as pool,en as sor,an as staking,ln as tx,Ct as xc};
|
|
1
|
+
var gn=Object.defineProperty;var T=(u,e)=>{for(var t in e)gn(u,t,{get:e[t],enumerable:!0})};var It={};T(It,{Papi:()=>B,getWs:()=>Pn});import{hydration as bn}from"@galacticcouncil/descriptors";function xt(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var B=class{client;api;constructor(e){this.client=e,this.api=this.client.getTypedApi(bn)}log(e,...t){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");xt(n)&&console.log(e,...t)}};import{createClient as hn}from"polkadot-api";import{withPolkadotSdkCompat as yn}from"polkadot-api/polkadot-sdk-compat";var Pn=async u=>{let e=typeof u=="string"?u.split(","):u,r=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(e);return hn(yn(r))};var Mt={};T(Mt,{AAVE_GAS_LIMIT:()=>$e,AAVE_LENDING_POOL_ADDRESS:()=>Ge,AAVE_POOL_ABI:()=>je,AAVE_POOL_DATA_PROVIDER:()=>Ne,AAVE_POOL_DATA_PROVIDER_ABI:()=>qe,AAVE_POOL_PROXY:()=>Qe,AAVE_ROUNDING_THRESHOLD:()=>ts,AAVE_UINT_256_MAX:()=>fn,AaveClient:()=>he,AaveUtils:()=>Q});var je=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var qe=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Qe="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ne="0x112b087b60C1a166130d59266363C45F8aa99db0",Ge="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",$e=1000000n,ts=5,fn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var _t={};T(_t,{EvmClient:()=>D,evmMainnet:()=>Je});import{defineChain as Sn}from"viem";var vt=["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"],Ot=["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"],Je=Sn({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:vt,webSocket:Ot},default:{http:vt,webSocket:Ot}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as At,createWalletClient as wn,custom as Tn,http as xn,webSocket as In}from"viem";var D=class{chain;constructor(e){this.chain=e||Je}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 At({chain:this.chain,transport:xn()})}getWsProvider(){return At({chain:this.chain,transport:In()})}getSigner(e){return wn({account:e,chain:this.chain,transport:Tn(window.ethereum)})}};var he=class{evmClient;constructor(e){this.evmClient=e??new D}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:qe,address:Ne,args:[Ge],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:qe,address:Ne,args:[Ge,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:je,address:Qe,args:[e],functionName:"getUserAccountData"})}};var y={};T(y,{asBigInt:()=>An,toBigInt:()=>On,toDecimal:()=>vn});import z from"big.js";z.NE=-18;function vn(u,e,t=6,n){let r=z(u.toString()),a=z(10).pow(e);return r.div(a).round(t,n).toString()}function On(u,e){let t=z(10).pow(e),r=z(u).mul(t).toFixed(0,z.roundDown);return BigInt(r)}function An(u){return BigInt(u.round(0,z.roundDown).toFixed(0))}var Z={};T(Z,{ERC20:()=>Ze});var Ze=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={};T(P,{fromPermill:()=>Fn,shiftNeg:()=>ye,toDecimals:()=>Rn,toPct:()=>Bn});import _n from"big.js";var Bt=1e3;function Bn(u){let[e,t]=u;return e/t*100}function Rn(u){let[e,t]=u;return e/t}function Fn(u){return[u/Bt,Bt]}function ye(u,e){let t=_n(typeof u=="bigint"?u.toString():u);return e===0?t.toString():t.div(Math.pow(10,e)).toString()}var Ve={};T(Ve,{H160:()=>at,isEvmAccount:()=>kt,isEvmAddress:()=>Et,isSs58Address:()=>Dt});import{AccountId as Pe}from"polkadot-api";import{toHex as Ft}from"@polkadot-api/utils";import{Buffer as X}from"buffer";var Rt={};T(Rt,{HUB_ASSET_ID:()=>nt,HYDRATION_OMNIPOOL_ADDRESS:()=>Dn,HYDRATION_PARACHAIN_ID:()=>En,HYDRATION_SS58_PREFIX:()=>E,PERBILL_DENOMINATOR:()=>kn,PERMILL_DENOMINATOR:()=>et,RUNTIME_DECIMALS:()=>A,SYSTEM_ASSET_DECIMALS:()=>tt,SYSTEM_ASSET_ID:()=>V,TRADEABLE_DEFAULT:()=>ee});var A=18,et=1e6,kn=1e9,V=0,tt=12,En=2034,E=63,Dn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",nt=1,ee=15;var rt="ETH\0";function kt(u){if(!u)return!1;try{let e=Pe().enc(u),t=X.from(rt);return X.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Et(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Dt(u){try{return Pe(63).enc(u),!0}catch{return!1}}var at=class u{static toAccount=e=>{let t=X.from(e.slice(2),"hex"),n=X.from(rt),r=Uint8Array.from(X.concat([n,t,X.alloc(8)])),a=Ft(r);return Pe(63).dec(a)};static fromAccount=e=>{let t=Pe().enc(e),n=X.from(rt),r=t.slice(n.length,-8);return"0x"+X.from(r).toString("hex")};static fromSS58=e=>{let n=Pe().enc(e).slice(0,20);return Ft(n)};static fromAny=e=>{if(Et(e))return e;if(kt(e))return u.fromAccount(e);if(Dt(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var j={};T(j,{findNestedKey:()=>Cn,findNestedObj:()=>Mn,jsonFormatter:()=>Ln});var Cn=(u,e)=>{let t=[];return JSON.stringify(u,(n,r)=>(r&&r[e]&&t.push(r),r)),t[0]},Mn=(u,e,t)=>{let n;return JSON.stringify(u,(r,a)=>(a&&a[e]===t&&(n=a),a)),n},Ln=(u,e)=>typeof e=="bigint"?e.toString():e;var v={};T(v,{calculateBuyFee:()=>Vn,calculateDiffToAvg:()=>qn,calculateDiffToRef:()=>Nn,calculateSellFee:()=>Gn,getFraction:()=>Hn});import U from"big.js";function qn(u,e){let t=U(u.toString()),n=U(e.toString());return t.minus(n).abs().div(t.plus(n).div(2)).mul(100).round(2).toNumber()}function Nn(u,e){if(e===0n)return 0;let t=U(u.toString()),n=U(e.toString());return t.minus(n).div(n).mul(100).round(2).toNumber()}function Gn(u,e){let t=U(u.toString()),n=U(e.toString());return U(1).minus(n.div(t)).mul(100).round(2).toNumber()}function Vn(u,e){let t=U(u.toString());return U(e.toString()).div(t).minus(1).mul(100).round(2).toNumber()}function Hn(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 Ct={};T(Ct,{convertToId:()=>Wn});import{Buffer as Un}from"buffer";function Wn(u){let t=Un.from(u.replace("0x",""),"hex").subarray(16);return t.readUIntBE(0,t.length)}var{ERC20:He}=Z,{H160:st}=Ve,Yn=1.01,Xn=99999,Kn=10n**27n,zn=10n**18n,Q=class{client;constructor(e){let t=e??new D;this.client=new he(t)}async getSummary(e){let t=st.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,p,d,m,b]=a,h=y.toDecimal(b,18),g=[];for(let f of i){let S=f.underlyingAsset.toLowerCase(),w=s.find(({underlyingAsset:K})=>K.toLowerCase()===S);if(!w)throw new Error("Missing pool reserve for "+S);let x=f.scaledATokenBalance,k=w.liquidityIndex,C=w.priceInMarketReferenceCurrency,R=x*k/Kn,G=Number(o===w.eModeCategoryId?w.eModeLiquidationThreshold:w.reserveLiquidationThreshold)/1e4,Y=w.usageAsCollateralEnabled&&f.usageAsCollateralEnabledOnUser&&f.scaledATokenBalance>0n,ge=He.toAssetId(S);g.push({aTokenBalance:R,decimals:Number(w.decimals),isCollateral:Y,priceInRef:C,reserveId:ge,reserveAsset:S,reserveLiquidationThreshold:G})}return{healthFactor:Number(h),totalCollateral:l,totalDebt:c,reserves:g}}async hasBorrowPositions(e){let t=st.fromAny(e),n=await this.client.getUserAccountData(t),[r,a]=n;return a>0n}async getHealthFactor(e){let t=st.fromAny(e),n=await this.client.getUserAccountData(t),[r,a,s,i,o,l]=n,c=y.toDecimal(l,18);return Number(c)}async getHealthFactorAfterWithdraw(e,t,n){let{totalCollateral:r,totalDebt:a,reserves:s}=await this.getSummary(e),i=He.fromAssetId(t),o=s.find(g=>g.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:c,priceInRef:p,reserveLiquidationThreshold:d}=o,m=y.toBigInt(n,l),b=c?m*p/10n**BigInt(l):0n,h=r-b;return h<=0n?0:this.calculateHealthFactor(h,d,a)}async getHealthFactorAfterSupply(e,t,n){let{totalCollateral:r,totalDebt:a,reserves:s}=await this.getSummary(e),i=He.fromAssetId(t),o=s.find(h=>h.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:p}=o,m=y.toBigInt(n,l)*c/10n**BigInt(l),b=r+m;return b<=0n?0:this.calculateHealthFactor(b,p,a)}async getMaxWithdraw(e,t){let{totalCollateral:n,totalDebt:r,reserves:a}=await this.getSummary(e),s=He.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 Xn;let r=10n**6n,a=y.toBigInt(t,18),s=e*a*r,i=n*zn,o=s/i;return Number(o)/1e6}calculateRequiredCollateral(e,t,n){let r=y.toBigInt(e,18),a=y.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(Yn,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 Vt={};T(Vt,{AssetClient:()=>te,BalanceClient:()=>M,ChainParams:()=>re,LiquidityMining:()=>ae});var te=class extends B{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:p}=await this.mapToken(a,t,n),d=Number(s),m=new Intl.DateTimeFormat("en-GB"),b=[c,"Bond",m.format(d)].join(" ");return{id:e,name:b,symbol:c+"b",decimals:p,icon:c,type:i.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:a,maturity:d}}async mapShares(e,t,n,r){let{assets:a}=r,{name:s,symbol:i,asset_type:o,is_sufficient:l,existential_deposit:c}=t,p=await Promise.all(a.map(async b=>{let{symbol:h}=await this.mapToken(b,t,n);return[b,h]})),d=Object.fromEntries(p),m=Object.values(d);return{id:e,name:m.join(", "),symbol:i?.asText()||s?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:d}}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 p=r.get(l),{asset_type:d}=c,m;switch(d.type){case"Bond":let b=s.get(l);m=await this.mapBond(l,c,i,b);break;case"StableSwap":let h=a.get(l);m=await this.mapShares(l,c,i,h);break;case"External":m=await this.mapExternal(l,c,t,p);break;default:m=await this.mapToken(l,c,i,p)}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)}};import{Subject as jn,bufferCount as Qn,combineLatest as $n,debounceTime as Jn,distinctUntilChanged as Lt,finalize as Zn,map as ne,pairwise as er,shareReplay as tr,startWith as nr}from"rxjs";var M=class extends B{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 $n([t,n,r]).pipe(Jn(250),ne(a=>a.flat()),nr([]),Qn(2,1),ne(([a,s],i)=>{if(i===0)return s;let o=a.reduce((c,p)=>(c.set(p.id,p.balance),c),new Map);return s.filter(c=>!qt(c.balance,o.get(c.id)))}))}subscribeSystemBalance(e){return this.api.query.System.Account.watchValue(e,"best").pipe(ne(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(e,t){return this.api.query.Tokens.Accounts.watchValue(e,t,"best").pipe(ne(r=>({id:t,balance:r})))}subscribeTokensBalance(e){return this.api.query.Tokens.Accounts.watchEntries(e,{at:"best"}).pipe(Lt((n,r)=>!r.deltas),ne(({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 jn,r=n.pipe(tr(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 d=(await Promise.all(o.map(async m=>{let b=await this.getTokenBalanceData(e,m);return[m,b]}))).map(([m,b])=>({id:m,balance:b}));n.next(d)};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(Zn(()=>i?.()),er(),ne(([o,l],c)=>{if(c===0)return l;let p=o.reduce((m,b)=>(m.set(b.id,b.balance),m),new Map);return l.filter(m=>!qt(m.balance,p.get(m.id)))}),Lt((o,l)=>l.length===0))}async getTokenBalanceData(e,t){let n=await this.api.apis.CurrenciesApi.account(t,e);return this.calculateBalance(n)}},qt=(u,e)=>u!==void 0&&e!==void 0&&u.transferable===e.transferable&&u.total===e.total;var re=class extends B{_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}};import{AccountId as lr,Binary as cr,Enum as ur}from"polkadot-api";import{fixed_from_rational as Gt}from"@galacticcouncil/math-liquidity-mining";import F from"big.js";import $ from"big.js";import{calculate_accumulated_rps as rr,calculate_global_farm_rewards as ar,calculate_loyalty_multiplier as sr,calculate_user_reward as Nt,calculate_yield_farm_delta_rpvs as ir}from"@galacticcouncil/math-liquidity-mining";var or="1000000000000000000",Ue=class{constructor(e,t,n){this.get_account=e;this.multiCurrency=t;this.getAsset=n}async sync_global_farm(e,t,n){if(e.state.type!=="Active"||e.updated_at===t)return null;if(e.total_shares_z===0n)return e;let r=await this.getAsset(e.reward_currency),a=t-e.updated_at,s=this.get_account(e.id),i=r?.existential_deposit;if(!i)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.free_balance(e.reward_currency,s),l=$(i.toString()),c=$(o.toString()).minus(l.lt(o.toString())?i.toString():o.toString()),p=$(ar(e.total_shares_z.toString(),n.toString(),$(e.yield_per_period.toString()).mul(it).round(0,$.roundDown).toFixed(),e.max_reward_per_period.toString(),a.toFixed()));if(c.lt(p)&&(p=c),p.eq(0))return e;let d=this.get_account(0);return this.multiCurrency.transfer(e.reward_currency,s,d,BigInt(p.toFixed())),{...e,accumulated_rpz:BigInt(rr(e.accumulated_rpz.toString(),e.total_shares_z.toString(),p.toFixed()))}}sync_yield_farm(e,t,n){if(e.state.type!=="Active"||e.updated_at===n)return null;if(e.total_valued_shares===0n)return{...e,updated_at:n};let r=ir(e.accumulated_rpz.toString(),t.accumulated_rpz.toString(),e.multiplier.toString(),e.total_valued_shares.toString());return{...e,accumulated_rpvs:e.accumulated_rpvs+BigInt(r),updated_at:n}}get_loyalty_multiplier(e,t){let n=$(1).mul(it).round(0,$.roundDown).toString();if(!t)return n;let{initial_reward_percentage:r,scale_coef:a}=t;return sr(e.toFixed(),r.toString(),a.toFixed())}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(n.updated_at===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,s);if(!o)return null;let l=o.total_stopped-n.stopped_at_creation,c=o.updated_at-n.entered_at-l,p=this.get_loyalty_multiplier(c,o.loyalty_curve),d=BigInt(Nt(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),m=BigInt(Nt(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),or));return{reward:d,maxReward:m,assetId:i.reward_currency}}};var pr=BigInt(F(1).pow(18).toString()),mr=6,ae=class extends B{balanceClient;omnipoolAssetIds=[];secondsInYear=F(365.2425).times(24).times(60).times(60);constructor(e){super(e),this.balanceClient=new M(e)}async getOraclePrice(e,t){let n=[e,t].sort((a,s)=>a-s);if(e===t)return pr;let r=await this.api.query.EmaOracle.Oracles.getValue(cr.fromText("omnipool"),n,ur("TenMinutes"));if(r){let{n:a,d:s}=r[0].price,i;return e<t?i=Gt(a.toString(),s.toString()):i=Gt(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 lr(63).dec(o)};getGlobalRewardPerPeriod(e,t,n,r){let a=F(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=F(e.toString()).times(t),s=F(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:p,total_shares_z:d,max_reward_per_period:m,pending_rewards:b,accumulated_paid_rewards:h,planned_yielding_periods:g,updated_at:f,incentivized_asset:S,reward_currency:w,price_adjustment:x}=a,k=ye(s??x,18),C=ye(o,18),R=ye(l?.initial_reward_percentage??0,18),N=this.secondsInYear.div(F(mr).times(c)).toString(),G;if(d<0)G=F(C).times(p.toString()).times(N).toString();else{let mn=this.getGlobalRewardPerPeriod(d,p,m,k),dn=this.getPoolYieldPerPeriod(mn,C,d,k);G=F(dn).times(N).toString()}let Y=b+h,ge=m*BigInt(g),K=i.transferable+Y,ze=K-Y,be=F(ze.toString()).div(m.toString()),wt=F(t).div(c.toString()).toString(),cn=(d>=0?be.plus(f):be.plus(wt)).toString(),un=F(d.toString()).div(F(m.toString()).div(p.toString())).div(Math.pow(10,18)).times(100).times(k).toFixed(2),Tt=F(Y.toString()).div(K.toString()).gte(.999);G=Tt?"0":F(G).div(n?2:1).times(100).toString();let pn=R?F(G).times(R).toString():void 0;return{apr:G,minApr:pn,isDistributed:Tt,estimatedEndPeriod:cn,maxRewards:ge,incentivizedAsset:S,rewardCurrency:w,loyaltyCurve:l,currentPeriod:wt,potMaxRewards:K,fullness:un}}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),p=await this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(Number(e),o,l);if(!c||!p)return;let d=c.reward_currency,m=c.incentivized_asset,b=this.getFarmAddress(o),h=await this.getOraclePrice(d,m),g=await this.balanceClient.getTokenBalance(b,d);return{id:e,globalFarm:c,yieldFarm:p,priceAdjustment:h,balance:g}}));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),p=await this.api.query.XYKWarehouseLM.YieldFarm.getValue(e,o,l);if(!c||!p)return;let d=c.reward_currency,m=c.incentivized_asset,b=this.getFarmAddress(o,!0),h=await this.getOraclePrice(d,m),g=await this.balanceClient.getBalance(b,d);return{id:e,globalFarm:c,yieldFarm:p,priceAdjustment:h,balance:g,farmAddress:b}}));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,p=[[this.getFarmAddress(0,n),o.reward_currency],[this.getFarmAddress(o.id,n),o.reward_currency]],d=await dr(this.api,p)(),m=await this.getOraclePrice(l,c),b=new lt(p,d),g=await new Ue(S=>this.getFarmAddress(S),b,S=>this.api.query.AssetRegistry.Assets.getValue(S)).claim_rewards(o,i,t,r,m??o.price_adjustment);if(!g)return;let f=await this.api.query.AssetRegistry.Assets.getValue(g.assetId);if(f&&!(g.reward<=f.existential_deposit))return g}},it=F(10).pow(18),ot="0",dr=(u,e)=>async()=>{let[t,n]=await Promise.all([u.query.Tokens.Accounts.getValues(e.filter(([a,s])=>s.toString()!==ot)),u.query.System.Account.getValues(e.filter(([a,s])=>s.toString()===ot).map(([a])=>[a]))]),r=[];for(let a=0,s=0;a+s<e.length;){let i=a+s,[,o]=e[i];o.toString()===ot?(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 Ht={};T(Ht,{AssetNotFound:()=>ct,PoolNotFound:()=>fe,RouteNotFound:()=>Se});var ct=class extends Error{constructor(e){super(),this.message=`${e} not found`,this.name="AssetNotFound"}},fe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Se=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in current configuration`,this.name="RouteNotFound"}};var Qt={};T(Qt,{PoolContextProvider:()=>oe,PoolError:()=>J,PoolFactory:()=>ie,PoolType:()=>O,aave:()=>gt,lbp:()=>ut,omni:()=>pt,stable:()=>mt,xyk:()=>dt});var ut={};T(ut,{LbpMath:()=>H,LbpPool:()=>we,LbpPoolClient:()=>Te});import{calculate_in_given_out as gr,calculate_out_given_in as br,calculate_linear_weights as hr,calculate_pool_trade_fee as yr,get_spot_price as Pr}from"@galacticcouncil/math-lbp";var H=class{static getSpotPrice(e,t,n,r,a){return Pr(e,t,n,r,a)}static calculateInGivenOut(e,t,n,r,a){return gr(e,t,n,r,a)}static calculateOutGivenIn(e,t,n,r,a){return br(e,t,n,r,a)}static calculateLinearWeights(e,t,n,r,a){return hr(e,t,n,r,a)}static calculatePoolTradeFee(e,t,n){return yr(e,t,n)}};var O=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a))(O||{}),J=(a=>(a.InsufficientTradingAmount="InsufficientTradingAmount",a.MaxInRatioExceeded="MaxInRatioExceeded",a.MaxOutRatioExceeded="MaxOutRatioExceeded",a.TradeNotAllowed="TradeNotAllowed",a.UnknownError="UnknownError",a))(J||{});var we=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),p=e.balanceIn/this.maxInRatio;return c>p&&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,p=e.balanceOut/this.maxOutRatio;return c>p&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:c,feePct:l,errors:a}}}calculateInGivenOut(e,t){let n=H.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=H.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=H.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),this.maxOutRatio.toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=H.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),this.maxInRatio.toString());return BigInt(t)}calculateTradeFee(e,t){let n=H.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as vr}from"polkadot-api";import{map as Or,of as Kt,switchMap as Ar}from"rxjs";import{memoize1 as fr}from"@thi.ng/memoize";import{combineLatest as Ut,combineLatestAll as Sr,debounceTime as wr,firstValueFrom as Tr,from as Wt,map as Yt,mergeAll as xr,of as Ir,switchMap as Xt}from"rxjs";var L=class extends M{override=[];mem=0;memPools=fr(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=Wt(this.getPoolsMem()).pipe(Xt(t=>this.subscribe(t)),Sr());return Tr(e)}getSubscriber(){return Wt(this.getPoolsMem()).pipe(Xt(e=>this.subscribe(e)),xr())}subscribe(e){return e.filter(t=>this.hasValidAssets(t)).map(t=>Ut([this.subscribePoolChange(t),this.subscribePoolBalance(t)]).pipe(wr(250),Yt(([n,r])=>this.updatePool(n,r))))}subscribePoolBalance(e){if(e.type==="Aave")return Ir([]);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 Ut(t).pipe(Yt(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 Te=class extends L{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,p=H.calculateLinearWeights(r?r.toString():"0",a?a.toString():"0",i.toString(),o.toString(),n.toString()),[d,m]=s,b=BigInt(p),h=this.MAX_FINAL_WEIGHT-BigInt(b),[g,f,S,w,x]=await Promise.all([this.isRepayFeeApplied(d,l,c.toString()),this.getBalance(e,d),this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(e,m),this.api.query.AssetRegistry.Assets.getValue(m)]);return{repayFeeApply:g,tokens:[{id:d,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:f.transferable,weight:b,type:S?.asset_type.type},{id:m,decimals:x?.decimals,existentialDeposit:x?.existential_deposit,balance:w.transferable,weight:h,type:x?.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(vr.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(e.address);return n?t.watchValue("best").pipe(Ar(r=>r?this.getPoolDelta(e.address,n,r.relay_parent_number):Kt(e)),Or(r=>Object.assign({},e,r))):Kt(e)}};var pt={};T(pt,{OmniMath:()=>I,OmniPool:()=>xe,OmniPoolClient:()=>Ie});import{calculate_in_given_out as _r,calculate_lrna_in_given_out as Br,calculate_out_given_in as Rr,calculate_out_given_lrna_in as Fr,calculate_spot_price as kr,calculate_lrna_spot_price as Er,calculate_shares as Dr,calculate_liquidity_out as Cr,calculate_liquidity_lrna_out as Mr,verify_asset_cap as Lr,calculate_liquidity_hub_in as qr,is_sell_allowed as Nr,is_buy_allowed as Gr,is_add_liquidity_allowed as Vr,is_remove_liquidity_allowed as Hr}from"@galacticcouncil/math-omnipool";import se from"big.js";var I=class{static calculateSpotPrice(e,t,n,r){return kr(e,t,n,r)}static calculateLrnaSpotPrice(e,t){return Er(e,t)}static calculateInGivenOut(e,t,n,r,a,s,i,o,l){return _r(e,t,n,r,a,s,i,o,l)}static calculateLrnaInGivenOut(e,t,n,r,a){return Br(e,t,n,r,a)}static calculateOutGivenIn(e,t,n,r,a,s,i,o,l){return Rr(e,t,n,r,a,s,i,o,l)}static calculateOutGivenLrnaIn(e,t,n,r,a){return Fr(e,t,n,r,a)}static calculateShares(e,t,n,r){return Dr(e,t,n,r)}static calculateLiquidityOut(e,t,n,r,a,s,i,o){return Cr(e,t,n,r,a,s,i,o)}static calculateLiquidityLRNAOut(e,t,n,r,a,s,i,o){return Mr(e,t,n,r,a,s,i,o)}static calculateCapDifference(e,t,n,r){let a=se(t),s=se(e),i=se(r),o=se(n),l=se(10).pow(18),c=o.div(l);if(a.div(i).lt(c)){let d=c.times(i).minus(a).times(s),m=a.times(se(1).minus(c));return d.div(m).toFixed(0)}else return"0"}static verifyAssetCap(e,t,n,r){return Lr(e,t,n,r)}static calculateLimitHubIn(e,t,n,r){return qr(e,t,n,r)}static isSellAllowed(e){return Nr(e)}static isBuyAllowed(e){return Gr(e)}static isAddLiquidityAllowed(e){return Vr(e)}static isRemoveLiquidityAllowed(e){return Hr(e)}};var xe=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:v.calculateDiffToRef(a,r),i=[],o=I.isSellAllowed(e.tradeableIn),l=I.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 p=e.balanceIn/this.maxInRatio;return a>p&&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=v.calculateDiffToRef(r,a),i=[],o=I.isSellAllowed(e.tradeableIn),l=I.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 p=e.balanceOut/this.maxOutRatio;return a>p&&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=I.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=I.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=I.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=I.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=I.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=I.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=I.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=I.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}};import{AccountId as Ur,CompatibilityLevel as Wr}from"polkadot-api";import{toHex as Yr}from"@polkadot-api/utils";import{distinctUntilChanged as Xr,map as zt}from"rxjs";var Ie=class extends L{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:p})=>{let[d]=c,{hub_reserve:m,shares:b,tradable:h,cap:g,protocol_shares:f}=p,[S,w]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(t,d)]);return{id:d,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:w.transferable,cap:g,hubReserves:m,protocolShares:f,shares:b,tradeable:h,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=Yr(t);return Ur(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(Wr.BackwardsCompatible,t)}subscribePoolChange(e){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(Xr((n,r)=>!r.deltas),zt(({entries:n})=>n.map(r=>{let[a]=r.args,{hub_reserve:s,shares:i,tradable:o,cap:l,protocol_shares:c}=r.value,p=e.tokens.findIndex(m=>m.id===a);return{...e.tokens[p],cap:l,hubReserves:s,protocolShares:c,shares:i,tradeable:o}})),zt(n=>{let r=e.tokens.find(a=>a.id===1);return{...e,tokens:[...n,r]}}))}};var mt={};T(mt,{StableMath:()=>_,StableSwap:()=>ve,StableSwapClient:()=>Oe});import{calculate_in_given_out as Kr,calculate_out_given_in as zr,calculate_amplification as jr,calculate_add_one_asset as Qr,calculate_liquidity_out_one_asset as $r,calculate_shares as Jr,calculate_shares_for_amount as Zr,calculate_spot_price_with_fee as ea,pool_account_name as ta,recalculate_peg as na}from"@galacticcouncil/math-stableswap";var _=class{static getPoolAddress(e){return ta(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 jr(e,t,n,r,a)}static calculateInGivenOut(e,t,n,r,a,s,i){return Kr(e,t,n,r,a,s,i)}static calculateAddOneAsset(e,t,n,r,a,s,i){return Qr(e,t,n,r,a,s,i)}static calculateSharesForAmount(e,t,n,r,a,s,i){return Zr(e,t,n,r,a,s,i)}static calculateOutGivenIn(e,t,n,r,a,s,i){return zr(e,t,n,r,a,s,i)}static calculateLiquidityOutOneAsset(e,t,n,r,a,s,i){return $r(e,t,n,r,a,s,i)}static calculateShares(e,t,n,r,a,s){return Jr(e,t,n,r,a,s)}static calculateSpotPriceWithFee(e,t,n,r,a,s,i,o){return ea(e,t,n,r,a,s,i,o)}static recalculatePegs(e,t,n,r,a){let s=na(e,t,n,r,a);return JSON.parse(s)}};var ve=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=I.isSellAllowed(e.tradeableIn),l=I.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=I.isSellAllowed(e.tradeableIn),l=I.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=_.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=_.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=_.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=_.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=_.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=_.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=_.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=_.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=_.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,j.jsonFormatter)}getAssets(e,t){let n={asset_id:Number(e),amount:t.toString()};return JSON.stringify([n],j.jsonFormatter)}};import{AccountId as ra,CompatibilityLevel as aa}from"polkadot-api";import{toHex as sa}from"@polkadot-api/utils";import{blake2b as ia}from"@noble/hashes/blake2b";import{map as oa,of as la,switchMap as ca}from"rxjs";var ua=340282366920938463463374607431768211455n,Oe=class extends L{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,p]=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,...p,...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=_.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:ua,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]=_.recalculatePegs(JSON.stringify(s),JSON.stringify(a),n.toString(),P.toDecimals(i).toString(),P.toDecimals(o).toString()),p=Number(l)*1e6;return{pegsFee:P.fromPermill(p),pegs:c}}getDefaultPegs(e){let t=e.fee,n=_.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,p]=i.value,d=[p,a[o]].sort((S,w)=>S-w),m=await this.api.query.EmaOracle.Oracles.getValue(l,d,c);if(!m)return;let[{price:b,updated_at:h}]=m,g=b.n.toString(),f=b.d.toString();return p.toString()===d[0].toString()?[[g,f],h.toString()]:[[f,g],h.toString()]}else return[i.value.map(l=>l.toString()),n]});return Promise.all(s)}getPoolAddress(e){let t=_.getPoolAddress(e),n=ia(t,{dkLen:32}),r=sa(n);return ra(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(aa.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.System.Number,n=this.poolsData.get(e.address);return!n||!e.id?la(e):t.watchValue("best").pipe(ca(r=>this.getPoolDelta(e.id,n,r)),oa(r=>Object.assign({},e,r)))}};var dt={};T(dt,{XykMath:()=>W,XykPool:()=>Ae,XykPoolClient:()=>_e});import{calculate_in_given_out as pa,calculate_out_given_in as ma,calculate_pool_trade_fee as da,get_spot_price as ga,calculate_liquidity_in as ba,calculate_shares as ha,calculate_spot_price as ya,calculate_spot_price_with_fee as Pa,calculate_liquidity_out_asset_a as fa,calculate_liquidity_out_asset_b as Sa}from"@galacticcouncil/math-xyk";var W=class{static getSpotPrice(e,t,n){return ga(e,t,n)}static calculateInGivenOut(e,t,n){return pa(e,t,n)}static calculateOutGivenIn(e,t,n){return ma(e,t,n)}static calculatePoolTradeFee(e,t,n){return da(e,t,n)}static calculateLiquidityIn(e,t,n){return ba(e,t,n)}static calculateSpotPrice(e,t){return ya(e,t)}static calculateSpotPriceWithFee(e,t,n,r){return Pa(e,t,n,r)}static calculateShares(e,t,n){return ha(e,t,n)}static calculateLiquidityOutAssetA(e,t,n,r){return fa(e,t,n,r)}static calculateLiquidityOutAssetB(e,t,n,r){return Sa(e,t,n,r)}};var Ae=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=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(e,t){let n=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(e){let t=W.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){let t=W.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateTradeFee(e,t){let n=W.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as wa}from"polkadot-api";import{of as Ta}from"rxjs";var _e=class extends L{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,p,d,m]=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:p?.decimals,existentialDeposit:p?.existential_deposit,balance:c.transferable,type:p?.asset_type.type},{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,type:m?.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(wa.BackwardsCompatible,t)}subscribePoolChange(e){return Ta(e)}};var gt={};T(gt,{AavePool:()=>Be,AavePoolClient:()=>Re});var Be=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}};import{AccountId as xa}from"polkadot-api";import{toHex as Ia}from"@polkadot-api/utils";import{map as va,merge as Oa,switchMap as Aa}from"rxjs";import{decodeEventLog as _a}from"viem";var jt=[{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:Ba}=Z,Ra=["Supply","Withdraw","Repay","Borrow"],Re=class extends L{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=Ia(r);return xa(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(b=>b.asHex()),p=l.asHex(),{eventName:d,args:m}=_a({abi:jt,topics:c,data:p});return Ra.includes(d)&&m.reserve.toLowerCase()===r.toLowerCase()});return Oa([a,s]).pipe(Aa(()=>this.getPoolDelta(e)),va(i=>({...e,tokens:[...i]})))}getReserveH160Id(e){return e.type==="Erc20"?j.findNestedKey(e.location,"AccountKey20").AccountKey20.key:Ba.fromAssetId(e.id)}};var ie=class{static get(e){switch(e.type){case"Aave":return Be.fromPool(e);case"XYK":return Ae.fromPool(e);case"Omnipool":return xe.fromPool(e);case"LBP":return we.fromPool(e);case"Stableswap":return ve.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{Subject as Fa,Subscription as Fe,takeUntil as ka}from"rxjs";var oe=class extends B{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=Fe.EMPTY;omniSub=Fe.EMPTY;stableSub=Fe.EMPTY;xykSub=Fe.EMPTY;aaveSub=Fe.EMPTY;isReady=!1;isDestroyed=new Fa;constructor(e){super(e),this.lbpClient=new Te(e),this.omniClient=new Ie(e),this.stableClient=new Oe(e),this.xykClient=new _e(e),this.aaveClient=new Re(e),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(e){return e.getSubscriber().pipe(ka(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 fe(e.type)}};var en={};T(en,{DEFAULT_BLOCK_TIME:()=>$t,DEFAULT_MIN_BUDGET:()=>yt,ORDER_MIN_BLOCK_PERIOD:()=>Jt,Router:()=>le,TWAP_BLOCK_PERIOD:()=>Ce,TWAP_MAX_DURATION:()=>ft,TWAP_MAX_PRICE_IMPACT:()=>Pt,TWAP_TX_MULTIPLIER:()=>Au,TradeOrderError:()=>ht,TradeOrderType:()=>Ye,TradeRouteBuilder:()=>q,TradeRouter:()=>ce,TradeScheduler:()=>ue,TradeType:()=>We});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 Ea=8,Ee=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 ke,s=[];for(s.push([t,""]),a.enqueue(s);a.size()>0;){let i=a.dequeue();if(!i||i.length>Ea)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 p=[...i];p.push(c),a.enqueue(p)}})}return r}findShortestPaths(e,t,n){let r=[],a=new ke,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 p of c??[])this.isNotVisited(p,o)&&a.enqueue([...o,p])}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 bt(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 De=class{getProposals(e,t,n){let r=n.filter(g=>g.type==="XYK"),a=n.filter(g=>g.type!=="XYK"),s=new Set(a.map(g=>g.tokens).flat().map(g=>g.id)),i=s.has(e),o=s.has(t),l=new Ee,c=g=>{let f=bt(g),S=Object.keys(f),w=S.flatMap(x=>f[x]);return l.buildAndPopulateGraph(S,w)};if(!i&&!o){let g=r.filter(w=>w.tokens.find(x=>x.id===e)||w.tokens.find(x=>x.id===t)),f=c(g),S=l.findPaths(f,e,t);return this.parsePaths(S)}if(i&&o){let g=c(a),f=l.findPaths(g,e,t);return this.parsePaths(f)}let p=i?t:e,d=r.filter(g=>g.tokens.some(f=>f.id===p));if(d.length===0)return[];let m=[...a,...d],b=c(m),h=l.findPaths(b,e,t);return this.parsePaths(h)}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 le=class{routeSuggester;routeProposals;routerOptions;ctx;constructor(e,t={}){this.ctx=e,this.routeSuggester=new De,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,ie.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 We=(t=>(t.Buy="Buy",t.Sell="Sell",t))(We||{}),Ye=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Ye||{}),ht=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(ht||{});var ce=class extends le{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 Se(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),p=a?r.tradeFeePct:v.calculateSellFee(o,i),d=Math.pow(10,n.assetInDecimals),m=n.amountIn*s/BigInt(d),b=v.calculateDiffToRef(o,m);return{type:"Sell",amountIn:n.amountIn,amountOut:r.amountOut,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:t,toHuman(){return{type:"Sell",amountIn:y.toDecimal(n.amountIn,n.assetInDecimals),amountOut:y.toDecimal(r.amountOut,r.assetOutDecimals),spotPrice:y.toDecimal(s,r.assetOutDecimals),tradeFee:y.toDecimal(l,r.assetOutDecimals),tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:t.map(h=>h.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(h=>h.tokens.some(g=>g.id===e)).map(h=>h.type==="Aave"?h.tokens:h.tokens.filter(g=>g.id===e)).map(h=>h.map(g=>g.balance).reduce((g,f)=>g+f)).sort((h,g)=>g<h?-1:1)[0],c=v.getFraction(l,.1),p=await Promise.all(r.map(h=>this.toSellSwaps(c,h,s))),m=this.findBestSellRoute(p).map(h=>({poolAddress:h.poolAddress,poolId:h?.poolId,pool:h.pool,assetIn:h.assetIn,assetOut:h.assetOut})),b=this.buildRouteKey(e,t,a);return this.mlr.set(b,m),m}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"?y.toBigInt(e,o.decimalsIn):e;let c=await this.ctx.getPoolFees(i,o.assetOut),{amountOut:p,calculatedOut:d,feePct:m,errors:b}=i.validateAndSell(o,l,c),h=this.getPoolFeeRange(c),g=i.spotPriceOutGivenIn(o),f=Math.pow(10,o.decimalsIn),S=l*g/BigInt(f),w=v.calculateDiffToRef(d,S);r.push({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:h,priceImpactPct:w,errors:b,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:y.toDecimal(l,o.decimalsIn),amountOut:y.toDecimal(p,o.decimalsOut),calculatedOut:y.toDecimal(d,o.decimalsOut),spotPrice:y.toDecimal(g,o.decimalsOut),tradeFeePct:m,tradeFeeRange:h,priceImpactPct:w,errors:b}}})}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),p=a?r.tradeFeePct:v.calculateBuyFee(o,i),d=Math.pow(10,n.assetOutDecimals),m=n.amountOut*s/BigInt(d),b;return o===0n?b=-100:b=v.calculateDiffToRef(m,o),{type:"Buy",amountOut:n.amountOut,amountIn:r.amountIn,spotPrice:s,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:t,toHuman(){return{type:"Buy",amountOut:y.toDecimal(n.amountOut,n.assetOutDecimals),amountIn:y.toDecimal(r.amountIn,r.assetInDecimals),spotPrice:y.toDecimal(s,r.assetInDecimals),tradeFee:y.toDecimal(l,r.assetInDecimals),tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:t.map(h=>h.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"?y.toBigInt(e,o.decimalsOut):e:l=r[0].amountIn;let c=await this.ctx.getPoolFees(i,o.assetOut),{amountIn:p,calculatedIn:d,feePct:m,errors:b}=i.validateAndBuy(o,l,c),h=this.getPoolFeeRange(c),g=i.spotPriceInGivenOut(o),f=Math.pow(10,o.decimalsOut),S=l*g/BigInt(f),w;d===0n?w=-100:w=v.calculateDiffToRef(S,d),r.unshift({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:d,spotPrice:g,tradeFeePct:m,tradeFeeRange:h,priceImpactPct:w,errors:b,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:y.toDecimal(l,o.decimalsOut),amountIn:y.toDecimal(p,o.decimalsIn),calculatedIn:y.toDecimal(d,o.decimalsIn),spotPrice:y.toDecimal(g,o.decimalsIn),tradeFeePct:m,tradeFeeRange:h,priceImpactPct:w,errors:b}}})}return r}};var $t=6e3,yt=1000000000000000n,Ce=6,Pt=-5,ft=216e5,Au=3,Jt=6;import{Enum as Zt}from"polkadot-api";var q=class{static build(e){return e.map(({assetIn:t,assetOut:n,pool:r,poolId:a})=>r==="Stableswap"?{pool:Zt("Stableswap",a),asset_in:t,asset_out:n}:{pool:Zt(r),asset_in:t,asset_out:n})}};var ue=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??6e3,minBudgetInNative:t.minBudgetInNative??yt})}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,p=l[0],d=l[l.length-1],{assetInDecimals:m}=p,{assetOutDecimals:b}=d,h=Math.abs(c),g=this.getMinimumTradeCount(o,s),f=this.getOptimalTradeCount(h),S=a?Math.round(r/a):f,w=Math.ceil(r/g),x=Math.round(r/f),k=Math.round(r/S),C=o/BigInt(S),R=await this.router.getBestSell(e,t,C),N=o<s,G=[];N&&G.push("OrderTooSmall");let Y=R.amountOut*BigInt(S),ge=this.toBlockPeriod(k),K=R.tradeFee*BigInt(S),ze=q.build(l),be={assetIn:e,assetOut:t,errors:G,frequencyMin:w,frequencyOpt:x,frequency:k,tradeCount:S,tradeFee:K,tradeImpactPct:R.priceImpactPct,tradePeriod:ge,tradeRoute:ze,type:"Dca"};return{...be,amountIn:o,amountOut:Y,tradeAmountIn:R.amountIn,tradeAmountOut:R.amountOut,toHuman(){return{...be,amountIn:y.toDecimal(o,m),amountOut:y.toDecimal(Y,b),tradeAmountIn:y.toDecimal(R.amountIn,m),tradeAmountOut:y.toDecimal(R.amountOut,b)}}}}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:p}=l,{assetOutDecimals:d}=c,m=Math.abs(o),b=this.getTwapTradeCount(m),h=s/BigInt(b),g=await this.router.getBestSell(l.assetIn,c.assetOut,h),f=b===1,S=s<r,w=g.priceImpactPct<-5,x=[];S||f?x.push("OrderTooSmall"):w&&x.push("OrderImpactTooBig");let k=g.amountOut*BigInt(b),C=g.tradeFee*BigInt(b),R=q.build(i),N={assetIn:e,assetOut:t,errors:x,tradeCount:b,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapSell"};return{...N,amountIn:s,amountOut:k,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:C,toHuman(){return{...N,amountIn:y.toDecimal(s,p),amountOut:y.toDecimal(k,d),tradeAmountIn:y.toDecimal(g.amountIn,p),tradeAmountOut:y.toDecimal(g.amountOut,d),tradeFee:y.toDecimal(C,d)}}}}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:p}=l,{assetOutDecimals:d}=c,m=Math.abs(o),b=this.getTwapTradeCount(m),h=s/BigInt(b),g=await this.router.getBestBuy(l.assetIn,c.assetOut,h),f=g.amountIn*BigInt(b),S=b===1,w=f<r,x=g.priceImpactPct<-5,k=[];w||S?k.push("OrderTooSmall"):x&&k.push("OrderImpactTooBig");let C=g.tradeFee*BigInt(b),R=q.build(i),N={assetIn:e,assetOut:t,errors:k,tradeCount:b,tradeImpactPct:g.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapBuy"};return{...N,amountIn:f,amountOut:s,tradeAmountIn:g.amountIn,tradeAmountOut:g.amountOut,tradeFee:C,toHuman(){return{...N,amountIn:y.toDecimal(f,p),amountOut:y.toDecimal(s,d),tradeAmountIn:y.toDecimal(g.amountIn,p),tradeAmountOut:y.toDecimal(g.amountOut,d),tradeFee:y.toDecimal(C,p)}}}}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 an={};T(an,{BIG_10:()=>nn,BIG_BILL:()=>rn,StakingApi:()=>Me,StakingClient:()=>Le});import{encodeAddress as Da}from"@polkadot/util-crypto";import{stringToU8a as Ca}from"@polkadot/util";import{calculate_accumulated_rps as Ma,calculate_period_number as tn,calculate_rewards as La}from"@galacticcouncil/math-staking";import pe from"big.js";var nn=pe(10),rn=pe(nn.pow(12));function qa(u){return Da(Ca(("modl"+u).padEnd(32,"\0")),63)}var Me=class{client;balanceClient;constructor(e,t){this.client=e,this.balanceClient=t}async getTransferablePotBalance(){let e=await this.client.getPalletId(),t=qa(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,p=o.amount,d=o.conviction.toString(),m=await this.client.getReferendumInfo(c);return m&&(m.type==="Approved"||m.type==="Rejected")&&l.push({id:c,amount:p,conviction:d}),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,p]=await Promise.all([this.getTransferablePotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getSixBlockSince()]),d=pe(o.toString()).minus(r.toString()),m=a.toString(),b=pe(t).plus(1).toString();d.gt(0)&&s>0&&(m=Ma(a.toString(),d.toString(),s.toString()));let h=tn(l.toString(),t,p??b),g=tn(l.toString(),i.createdAt?.toString()??"",p??b),f=La(m,i.rewardPerStake?.toString()??"",i.stake?.toString()??""),S=pe(f).plus(i.accumulatedUnpaidRewards?.toString()||"0").plus(i.accumulatedLockedRewards?.toString()||"0");if(!pe(h).minus(g).lte(c.toString()))return S.div(rn).toString()}};var Le=class extends B{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 ln={};T(ln,{TxBuilderFactory:()=>de});import{Enum as on}from"polkadot-api";function sn(u){let e=[],t=u;for(;t&&typeof t=="object"&&"type"in t;)e.push(t.type),t=t.value;return e.join(".")}var me=class extends B{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new D,this.balanceClient=new M(e),this.aaveUtils=new Q(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:$e})}async dryRun(e,t){let n=on("Signed",e),r=on("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=sn(i.value);throw new Error("Dry run execution error!",{cause:o})}return s}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Xe=class extends me{_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=v.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:q.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=v.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:q.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=v.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:q.build(t)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as St}from"polkadot-api";var Ke=class extends me{_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:St("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=v.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:St("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=v.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:St("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 de=class{client;evmClient;constructor(e,t){this.client=e,this.evmClient=t??new D}trade(e){return new Xe(this.client,this.evmClient).setTrade(e)}order(e){return new Ke(this.client,this.evmClient).setOrder(e)}};async function Lp(u,e){let t=new re(u),[n,r]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),a=e??new D,s=new oe(u).withAave().withOmnipool().withStableswap().withXyk(),i=new Q(a),o=new ce(s),l=new ue(o,{blockTime:n,minBudgetInNative:r}),c=new M(u),p=new Le(u),d=new Me(p,c);return{api:{aave:i,router:o,scheduler:l,staking:d},client:{asset:new te(u),balance:c,evm:a,mining:new ae(u)},ctx:{pool:s},tx:new de(u,a),destroy:()=>{s.destroy()}}}export{Mt as aave,It as api,y as big,Vt as client,Rt as const,Lp as createSdkContext,Z as erc20,Ht as error,_t as evm,P as fmt,Ve as h160,j as json,v as math,Qt as pool,en as sor,an as staking,ln as tx,Ct as xc};
|
|
@@ -5,6 +5,11 @@ import { BalanceClient } from './BalanceClient';
|
|
|
5
5
|
import { hydration, HydrationQueries } from '@galacticcouncil/descriptors';
|
|
6
6
|
export type OmnipoolWarehouseLMDeposit = HydrationQueries['OmnipoolWarehouseLM']['Deposit']['Value'];
|
|
7
7
|
export type OmnipoolWarehouseLMDepositYieldFarmEntry = OmnipoolWarehouseLMDeposit['yield_farm_entries'][number];
|
|
8
|
+
export type FarmDepositReward = {
|
|
9
|
+
readonly reward: bigint;
|
|
10
|
+
readonly maxReward: bigint;
|
|
11
|
+
readonly assetId: number;
|
|
12
|
+
};
|
|
8
13
|
export declare class LiquidityMining extends Papi {
|
|
9
14
|
protected readonly balanceClient: BalanceClient;
|
|
10
15
|
protected omnipoolAssetIds: string[];
|
|
@@ -47,7 +52,7 @@ export declare class LiquidityMining extends Papi {
|
|
|
47
52
|
potMaxRewards: bigint;
|
|
48
53
|
fullness: string;
|
|
49
54
|
} | undefined)[]>;
|
|
50
|
-
getDepositReward(poolId: string, farmEntry: OmnipoolWarehouseLMDepositYieldFarmEntry, isXyk: boolean, relayChainBlockNumber: number): Promise<
|
|
55
|
+
getDepositReward(poolId: string, farmEntry: OmnipoolWarehouseLMDepositYieldFarmEntry, isXyk: boolean, relayChainBlockNumber: number): Promise<FarmDepositReward | undefined>;
|
|
51
56
|
}
|
|
52
57
|
export declare const BN_QUINTILL: Big.Big;
|
|
53
58
|
type Api = TypedApi<typeof hydration>;
|
|
@@ -1,15 +1,10 @@
|
|
|
1
1
|
import { TypedApi } from 'polkadot-api';
|
|
2
|
-
import { MultiCurrencyContainer, OmnipoolWarehouseLMDepositYieldFarmEntry } from './LiquidityMiningClient';
|
|
2
|
+
import { FarmDepositReward, MultiCurrencyContainer, OmnipoolWarehouseLMDepositYieldFarmEntry } from './LiquidityMiningClient';
|
|
3
3
|
import { hydration } from '@galacticcouncil/descriptors';
|
|
4
4
|
type Api = TypedApi<typeof hydration>;
|
|
5
5
|
type NotUndefined<T> = T extends undefined ? never : T;
|
|
6
6
|
type GlobalFarm = NotUndefined<Awaited<ReturnType<Api['query']['XYKWarehouseLM']['GlobalFarm']['getValue'] | Api['query']['OmnipoolWarehouseLM']['GlobalFarm']['getValue']>>>;
|
|
7
7
|
type YieldFarm = NotUndefined<Awaited<ReturnType<Api['query']['XYKWarehouseLM']['YieldFarm']['getValue'] | Api['query']['OmnipoolWarehouseLM']['YieldFarm']['getValue']>>>;
|
|
8
|
-
export type FarmDepositReward = {
|
|
9
|
-
readonly reward: bigint;
|
|
10
|
-
readonly maxReward: bigint;
|
|
11
|
-
readonly assetId: number;
|
|
12
|
-
};
|
|
13
8
|
export declare class OmnipoolLiquidityMiningClaimSim {
|
|
14
9
|
protected get_account: (sub: number) => string;
|
|
15
10
|
protected multiCurrency: MultiCurrencyContainer;
|