@galacticcouncil/sdk-next 0.3.0 → 0.4.1

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 gn=Object.create;var Gt=Object.defineProperty;var bn=Object.getOwnPropertyDescriptor;var yn=Object.getOwnPropertyNames;var hn=Object.getPrototypeOf,Pn=Object.prototype.hasOwnProperty;var Me=(c,t)=>()=>(c&&(t=c(c=0)),t);var S=(c,t)=>{for(var e in t)Gt(c,e,{get:t[e],enumerable:!0})},Ht=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of yn(t))!Pn.call(c,s)&&s!==e&&Gt(c,s,{get:()=>t[s],enumerable:!(n=bn(t,s))||n.enumerable});return c},at=(c,t,e)=>(Ht(c,t,"default"),e&&Ht(e,t,"default")),se=(c,t,e)=>(e=c!=null?gn(hn(c)):{},Ht(t||!c||!c.__esModule?Gt(e,"default",{value:c,enumerable:!0}):e,c)),fn=c=>Ht(Gt({},"__esModule",{value:!0}),c);var Tt={};var Ne=Me(()=>{at(Tt,require("@polkadot-api/ws-provider/node"))});var xt={};var He=Me(()=>{at(xt,require("@polkadot-api/ws-provider/web"))});var $n={};S($n,{aave:()=>fe,api:()=>re,big:()=>b,client:()=>Te,const:()=>de,createSdkContext:()=>zn,erc20:()=>tt,error:()=>Ie,evm:()=>ue,fmt:()=>h,h160:()=>wt,json:()=>Z,math:()=>B,pool:()=>Be,sor:()=>Ee,tx:()=>ke,xc:()=>he});module.exports=fn($n);var re={};S(re,{Papi:()=>M,getWs:()=>Tn});var qe=require("@galacticcouncil/descriptors");function Le(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var M=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(qe.hydration)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Le(n)&&console.log(t,...e)}};var Ge=require("polkadot-api"),Ue=require("polkadot-api/polkadot-sdk-compat"),Tn=async c=>{let t=typeof c=="string"?c.split(","):c,s=(typeof window>"u"?(await Promise.resolve().then(()=>(Ne(),Tt))).getWsProvider:(await Promise.resolve().then(()=>(He(),xt))).getWsProvider)(t);return(0,Ge.createClient)((0,Ue.withPolkadotSdkCompat)(s))};var fe={};S(fe,{AAVE_GAS_LIMIT:()=>oe,AAVE_LENDING_POOL_ADDRESS:()=>Vt,AAVE_POOL_ABI:()=>ae,AAVE_POOL_DATA_PROVIDER:()=>Wt,AAVE_POOL_DATA_PROVIDER_ABI:()=>Ut,AAVE_POOL_PROXY:()=>ie,AAVE_ROUNDING_THRESHOLD:()=>ps,AAVE_UINT_256_MAX:()=>xn,AaveClient:()=>It,AaveUtils:()=>et});var ae=[{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 Ut=[{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 ie="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Wt="0x112b087b60C1a166130d59266363C45F8aa99db0",Vt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",oe=1000000n,ps=5,xn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ue={};S(ue,{EvmClient:()=>L,evmMainnet:()=>le});var Xe=require("viem"),We=["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"],Ve=["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"],le=(0,Xe.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:We,webSocket:Ve},default:{http:We,webSocket:Ve}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var G=require("viem");var L=class{chain;constructor(t){this.chain=t||le}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}async getGasPrice(){return this.getProvider().getGasPrice()}getProvider(){return(0,G.createPublicClient)({chain:this.chain,transport:(0,G.http)()})}getWsProvider(){return(0,G.createPublicClient)({chain:this.chain,transport:(0,G.webSocket)()})}getSigner(t){return(0,G.createWalletClient)({account:t,chain:this.chain,transport:(0,G.custom)(window.ethereum)})}};var It=class{evmClient;constructor(t){this.evmClient=t??new L}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Ut,address:Wt,args:[Vt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.evmClient.getProvider().readContract({abi:Ut,address:Wt,args:[Vt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.evmClient.getProvider().readContract({abi:ae,address:ie,args:[t],functionName:"getUserAccountData"})}};var b={};S(b,{asBigInt:()=>Sn,toBigInt:()=>wn,toDecimal:()=>In});var J=se(require("big.js"));J.default.NE=-18;function In(c,t,e=6,n){let s=(0,J.default)(c.toString()),r=(0,J.default)(10).pow(t);return s.div(r).round(e,n).toString()}function wn(c,t){let e=(0,J.default)(10).pow(t),s=(0,J.default)(c).mul(e).toFixed(0,J.default.roundDown);return BigInt(s)}function Sn(c){return BigInt(c.round(0,J.default.roundDown).toFixed(0))}var tt={};S(tt,{ERC20:()=>ce});var ce=class{static fromAssetId(t){let e=Buffer.alloc(20,0);return e[15]=1,e.writeUInt32BE(t,16),"0x"+e.toString("hex")}static toAssetId(t){let e=Buffer.from(t.replace("0x",""),"hex");return e.length!==20||!this.isAssetAddress(t)?null:e.readUInt32BE(16)}static isAssetAddress(t){let e=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(e.subarray(0,16))}};var h={};S(h,{fromPermill:()=>An,toDecimals:()=>vn,toPct:()=>On});var Ye=1e3;function On(c){let[t,e]=c;return t/e*100}function vn(c){let[t,e]=c;return t/e}function An(c){return[c/Ye,Ye]}var wt={};S(wt,{H160:()=>ye,isEvmAccount:()=>je,isEvmAddress:()=>Ke,isSs58Address:()=>ze});var ot=require("polkadot-api"),ge=require("@polkadot-api/utils"),z=require("buffer");var de={};S(de,{HUB_ASSET_ID:()=>pe,HYDRATION_OMNIPOOL_ADDRESS:()=>_n,HYDRATION_PARACHAIN_ID:()=>Bn,HYDRATION_SS58_PREFIX:()=>W,RUNTIME_DECIMALS:()=>q,SYSTEM_ASSET_DECIMALS:()=>me,SYSTEM_ASSET_ID:()=>K,TRADEABLE_DEFAULT:()=>it});var q=18,K=0,me=12,Bn=2034,W=63,_n="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",pe=1,it=15;var be="ETH\0";function je(c){if(!c)return!1;try{let t=(0,ot.AccountId)().enc(c),e=z.Buffer.from(be);return z.Buffer.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function Ke(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function ze(c){try{return(0,ot.AccountId)(63).enc(c),!0}catch{return!1}}var ye=class c{static toAccount=t=>{let e=z.Buffer.from(t.slice(2),"hex"),n=z.Buffer.from(be),s=Uint8Array.from(z.Buffer.concat([n,e,z.Buffer.alloc(8)])),r=(0,ge.toHex)(s);return(0,ot.AccountId)(63).dec(r)};static fromAccount=t=>{let e=(0,ot.AccountId)().enc(t),n=z.Buffer.from(be),s=e.slice(n.length,-8);return"0x"+z.Buffer.from(s).toString("hex")};static fromSS58=t=>{let n=(0,ot.AccountId)().enc(t).slice(0,20);return(0,ge.toHex)(n)};static fromAny=t=>{if(Ke(t))return t;if(je(t))return c.fromAccount(t);if(ze(t))return c.fromSS58(t);throw new Error("Unknown address type")}};var Z={};S(Z,{findNestedKey:()=>Rn,findNestedObj:()=>Fn,jsonFormatter:()=>En});var Rn=(c,t)=>{let e=[];return JSON.stringify(c,(n,s)=>(s&&s[t]&&e.push(s),s)),e[0]},Fn=(c,t,e)=>{let n;return JSON.stringify(c,(s,r)=>(r&&r[t]===e&&(n=r),r)),n},En=(c,t)=>typeof t=="bigint"?t.toString():t;var B={};S(B,{calculateBuyFee:()=>Mn,calculateDiffToAvg:()=>Dn,calculateDiffToRef:()=>kn,calculateSellFee:()=>Cn,getFraction:()=>Ln});var V=se(require("big.js"));function Dn(c,t){let e=(0,V.default)(c.toString()),n=(0,V.default)(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function kn(c,t){if(t===0n)return 0;let e=(0,V.default)(c.toString()),n=(0,V.default)(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function Cn(c,t){let e=(0,V.default)(c.toString()),n=(0,V.default)(t.toString());return(0,V.default)(1).minus(n.div(e)).mul(100).round(2).toNumber()}function Mn(c,t){let e=(0,V.default)(c.toString());return(0,V.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function Ln(c,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),s=BigInt(t*n);return c*s/BigInt(100*n)}var he={};S(he,{convertToId:()=>qn});var $e=require("buffer");function qn(c){let e=$e.Buffer.from(c.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var{ERC20:Xt}=tt,{H160:Pe}=wt,Nn=1.01,Hn=99999,Gn=10n**27n,Un=10n**18n,et=class{client;constructor(t){let e=t??new L;this.client=new It(e)}async getSummary(t){let e=Pe.fromAny(t),[n,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e)]),[i]=n,[a,o]=s,[l,u,d,m,p,g]=r,P=b.toDecimal(g,18),y=[];for(let I of a){let T=I.underlyingAsset.toLowerCase(),x=i.find(({underlyingAsset:ne})=>ne.toLowerCase()===T);if(!x)throw new Error("Missing pool reserve for "+T);let A=I.scaledATokenBalance,F=x.liquidityIndex,k=x.priceInMarketReferenceCurrency,C=A*F/Gn,qt=Number(o===x.eModeCategoryId?x.eModeLiquidationThreshold:x.reserveLiquidationThreshold)/1e4,Nt=x.usageAsCollateralEnabled&&I.usageAsCollateralEnabledOnUser&&I.scaledATokenBalance>0n,ee=Xt.toAssetId(T);y.push({aTokenBalance:C,decimals:Number(x.decimals),isCollateral:Nt,priceInRef:k,reserveId:ee,reserveAsset:T,reserveLiquidationThreshold:qt})}return{healthFactor:Number(P),totalCollateral:l,totalDebt:u,reserves:y}}async hasBorrowPositions(t){let e=Pe.fromAny(t),n=await this.client.getUserAccountData(e),[s,r]=n;return r>0n}async getHealthFactor(t){let e=Pe.fromAny(t),n=await this.client.getUserAccountData(e),[s,r,i,a,o,l]=n,u=b.toDecimal(l,18);return Number(u)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(t),a=Xt.fromAssetId(e),o=i.find(y=>y.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,isCollateral:u,priceInRef:d,reserveLiquidationThreshold:m}=o,p=b.toBigInt(n,l),g=u?p*d/10n**BigInt(l):0n,P=s-g;return P<=0n?0:this.calculateHealthFactor(P,m,r)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(t),a=Xt.fromAssetId(e),o=i.find(P=>P.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:d}=o,p=b.toBigInt(n,l)*u/10n**BigInt(l),g=s+p;return g<=0n?0:this.calculateHealthFactor(g,d,r)}async getMaxWithdraw(t,e){let{totalCollateral:n,totalDebt:s,reserves:r}=await this.getSummary(t),i=Xt.fromAssetId(e),a=r.find(o=>o.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(a,n,s)}async getMaxWithdrawAll(t){let{totalCollateral:e,totalDebt:n,reserves:s}=await this.getSummary(t),r={};for(let i of s){let a=this.calculateWithdrawMax(i,e,n);i.reserveId&&(r[i.reserveId]=a)}return r}calculateHealthFactor(t,e,n){if(n===0n)return Hn;let s=10n**6n,r=b.toBigInt(e,18),i=t*r*s,a=n*Un,o=i/a;return Number(o)/1e6}calculateRequiredCollateral(t,e,n){let s=b.toBigInt(t,18),r=b.toBigInt(e,18);return(s*n+r-1n)/r}calculateWithdrawMax(t,e,n){let{aTokenBalance:s,decimals:r,priceInRef:i,reserveLiquidationThreshold:a}=t,o=this.calculateRequiredCollateral(Nn,a,n),l=e-o;if(l<=0n)return{amount:0n,decimals:r};let u=l*10n**BigInt(r)/i;return{amount:s<u?s:u,decimals:r}}};var Te={};S(Te,{AssetClient:()=>lt,BalanceClient:()=>X,ChainParams:()=>ut});var lt=class extends M{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:s}=n;return this.SUPPORTED_TYPES.includes(s.type)}).map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async mapToken(t,e,n,s){let{name:r,asset_type:i,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=n.get(t)??{};return{id:t,name:r?.asText(),symbol:l,decimals:u,icon:l,type:i.type,isSufficient:a,location:s,existentialDeposit:o}}async mapBond(t,e,n,s){let[r,i]=s,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:d}=await this.mapToken(r,e,n),m=Number(i),p=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",p.format(m)].join(" ");return{id:t,name:g,symbol:u+"b",decimals:d,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:r,maturity:m}}async mapShares(t,e,n,s){let{assets:r}=s,{name:i,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,d=await Promise.all(r.map(async g=>{let{symbol:P}=await this.mapToken(g,e,n);return[g,P]})),m=Object.fromEntries(d),p=Object.values(m);return{id:t,name:p.join(", "),symbol:a?.asText()||i?.asText(),decimals:18,icon:p.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:m}}async mapExternal(t,e,n,s){let r=await this.mapToken(t,e,new Map,s),i=n?.find(a=>a.internalId===r.id);return i?{...r,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:r}parseMetadata(t){return new Map(Array.from(t,([e,n])=>[e,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(t,e){let[n,s,r,i]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(n),o=[];for(let[l,u]of Array.from(n)){let d=s.get(l),{asset_type:m}=u,p;switch(m.type){case"Bond":let g=i.get(l);p=await this.mapBond(l,u,a,g);break;case"StableSwap":let P=r.get(l);p=await this.mapShares(l,u,a,P);break;case"External":p=await this.mapExternal(l,u,e,d);break;default:p=await this.mapToken(l,u,a,d)}o.push(p)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var w=require("rxjs");var X=class extends M{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:{free:n,frozen:s}}=await e.getValue(t);return n-s}async getTokenBalance(t,e){let n=this.api.query.Tokens.Accounts,{free:s,frozen:r}=await n.getValue(t,e);return s-r}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),s=this.subscribeErc20Balance(t);return(0,w.combineLatest)([e,n,s]).pipe((0,w.debounceTime)(250),(0,w.map)(r=>r.flat()),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([r,i],a)=>{if(a===0)return i;let o=r.reduce((u,d)=>(u.set(d.id,d.amount),u),new Map);return i.filter(u=>u.amount!==o.get(u.id))}))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe((0,w.map)(n=>{let{free:s,frozen:r}=n.data;return{id:0,amount:s-r}}))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe((0,w.map)(s=>{let{free:r,frozen:i}=s;return{id:e,amount:r-i}}))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe((0,w.distinctUntilChanged)((n,s)=>!s.deltas),(0,w.map)(({deltas:n})=>{let s=[];return n?.deleted.forEach(r=>{let[i,a]=r.args;s.push({id:a,amount:0n})}),n?.upserted.forEach(r=>{let[i,a]=r.args,{free:o,frozen:l}=r.value;s.push({id:a,amount:o-l})}),s}))}subscribeErc20Balance(t,e){let n=new w.Subject,s=n.pipe((0,w.shareReplay)(1)),r=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:u}=l;return u.type==="Erc20"}).map(({keyArgs:l})=>{let[u]=l;return u}),i=async()=>{let o=e||await r(),l=async()=>{let m=(await Promise.all(o.map(async p=>{let g=await this.getTokenBalanceData(t,p);return[p,g]}))).map(([p,g])=>({id:p,amount:g}));n.next(m)};await l();let u=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>u.unsubscribe()},a;return i().then(o=>a=o),s.pipe((0,w.finalize)(()=>a?.()),(0,w.pairwise)(),(0,w.map)(([o,l],u)=>{if(u===0)return l;let d=o.reduce((p,g)=>(p.set(g.id,g.amount),p),new Map);return l.filter(p=>p.amount!==d.get(p.id))}),(0,w.distinctUntilChanged)((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let{free:n,frozen:s}=await this.api.apis.CurrenciesApi.account(e,t);return n-s}};var ut=class extends M{_minOrderBudget;_blockTime;constructor(t){super(t)}async getBlockTime(){if(this._blockTime===void 0){let t=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(t)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var Ie={};S(Ie,{AssetNotFound:()=>xe,PoolNotFound:()=>St,RouteNotFound:()=>ct});var xe=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},St=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},ct=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Be={};S(Be,{PoolContextProvider:()=>gt,PoolError:()=>nt,PoolFactory:()=>dt,PoolType:()=>E,aave:()=>Ae,lbp:()=>we,omni:()=>Se,stable:()=>Oe,xyk:()=>ve});var we={};S(we,{LbpMath:()=>U,LbpPool:()=>Ot,LbpPoolClient:()=>vt});var Y=require("@galacticcouncil/math-lbp"),U=class{static getSpotPrice(t,e,n,s,r){return(0,Y.get_spot_price)(t,e,n,s,r)}static calculateInGivenOut(t,e,n,s,r){return(0,Y.calculate_in_given_out)(t,e,n,s,r)}static calculateOutGivenIn(t,e,n,s,r){return(0,Y.calculate_out_given_in)(t,e,n,s,r)}static calculateLinearWeights(t,e,n,s,r){return(0,Y.calculate_linear_weights)(t,e,n,s,r)}static calculatePoolTradeFee(t,e,n){return(0,Y.calculate_pool_trade_fee)(t,e,n)}};var E=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r))(E||{}),nt=(r=>(r.InsufficientTradingAmount="InsufficientTradingAmount",r.MaxInRatioExceeded="MaxInRatioExceeded",r.MaxOutRatioExceeded="MaxOutRatioExceeded",r.TradeNotAllowed="TradeNotAllowed",r.UnknownError="UnknownError",r))(nt||{});var Ot=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,n,s,r,i,a){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.fee=i,this.repayFeeApply=a}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,weightIn:s.weight,weightOut:r.weight}}validateAndBuy(t,e,n){let s=this.tokens[0].id,r=[];e<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=t.balanceOut/this.maxOutRatio;if(e>i&&r.push("MaxOutRatioExceeded"),s===t.assetOut){let a=this.calculateTradeFee(e,n),o=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),d=t.balanceIn/this.maxInRatio;return u>d&&r.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:r}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&r.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:r}}}validateAndSell(t,e,n){let s=this.tokens[0].id,r=[];e<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=t.balanceIn/this.maxInRatio;if(e>i&&r.push("MaxInRatioExceeded"),s===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:r}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,n),l=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),u=a-o,d=t.balanceOut/this.maxOutRatio;return u>d&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:r}}}calculateInGivenOut(t,e){let n=U.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=U.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=U.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=U.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let n=U.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(n)}};var Je=require("polkadot-api"),st=require("rxjs");var Qe=(c,t=new Map)=>e=>{let n;return t.has(e)?t.get(e):(t.set(e,n=c(e)),n)};var O=require("rxjs");var N=class extends X{override=[];mem=0;memPools=Qe(t=>(this.log(this.getPoolType(),"mem pools",t,"\u2705"),this.loadPools()));constructor(t){super(t)}async withOverride(t){this.override=t||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let t=(0,O.from)(this.getPoolsMem()).pipe((0,O.switchMap)(e=>this.subscribe(e)),(0,O.combineLatestAll)());return(0,O.firstValueFrom)(t)}getSubscriber(){return(0,O.from)(this.getPoolsMem()).pipe((0,O.switchMap)(t=>this.subscribe(t)),(0,O.mergeAll)())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>(0,O.combineLatest)([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe((0,O.debounceTime)(250),(0,O.map)(([n,s])=>this.updatePool(n,s))))}subscribePoolBalance(t){if(t.type==="Aave")return(0,O.of)([]);let e=[this.subscribeTokensBalance(t.address)];if(this.hasSystemAsset(t)){let n=this.subscribeSystemBalance(t.address);e.push(n)}if(this.hasErc20Asset(t)){let n=t.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),s=this.subscribeErc20Balance(t.address,n);e.push(s)}return(0,O.combineLatest)(e).pipe((0,O.map)(n=>n.map(s=>Array.isArray(s)?s:[s]).flat()))}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({id:e,decimals:n,balance:s})=>{let r=this.override.find(a=>a.id===e),i=!!n||!!r?.decimals;return s>0n&&i})}updatePool=(t,e)=>{let n=t.tokens.map(s=>{let r=e.find(a=>a.id===s.id),i=this.override.find(a=>a.id===s.id);return r?{...s,balance:r.amount,decimals:s.decimals||i?.decimals}:{...s,decimals:s.decimals||i?.decimals}});return{...t,tokens:n}}};var vt=class extends N{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),s=e?.relay_parent_number||0,r=t.filter(({value:i})=>e&&this.isActivePool(i,s)).map(async({keyArgs:i,value:a})=>{let[o]=i,l=o.toString(),u=await this.getPoolDelta(l,a,s);return{address:l,type:"LBP",fee:a.fee,...u,...n}});return Promise.all(r)}async getPoolDelta(t,e,n){let{start:s,end:r,assets:i,initial_weight:a,final_weight:o,repay_target:l,fee_collector:u}=e,d=U.calculateLinearWeights(s?s.toString():"0",r?r.toString():"0",a.toString(),o.toString(),n.toString()),[m,p]=i,g=BigInt(d),P=this.MAX_FINAL_WEIGHT-BigInt(g),[y,I,T,x,A]=await Promise.all([this.isRepayFeeApplied(m,l,u.toString()),this.getBalance(t,m),this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(t,p),this.api.query.AssetRegistry.Assets.getValue(p)]);return{repayFeeApply:y,tokens:[{id:m,decimals:T?.decimals,existentialDeposit:T?.existential_deposit,balance:I,weight:g,type:T?.asset_type.type},{id:p,decimals:A?.decimals,existentialDeposit:A?.existential_deposit,balance:x,weight:P,type:A?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:s}=t;return n&&s?e>=n&&e<s:!1}async isRepayFeeApplied(t,e,n){if(e===0n)return!1;try{return await this.getBalance(n,t)<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(t){return{repayFee:await this.getRepayFee(),exchangeFee:t.fee}}getPoolType(){return"LBP"}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Je.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(t.address);return n?e.watchValue("best").pipe((0,st.switchMap)(s=>s?this.getPoolDelta(t.address,n,s.relay_parent_number):(0,st.of)(t)),(0,st.map)(s=>Object.assign({},t,s))):(0,st.of)(t)}};var Se={};S(Se,{OmniMath:()=>_,OmniPool:()=>At,OmniPoolClient:()=>_t});var f=require("@galacticcouncil/math-omnipool"),rt=se(require("big.js")),_=class{static calculateSpotPrice(t,e,n,s){return(0,f.calculate_spot_price)(t,e,n,s)}static calculateLrnaSpotPrice(t,e){return(0,f.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,n,s,r,i,a,o,l){return(0,f.calculate_in_given_out)(t,e,n,s,r,i,a,o,l)}static calculateLrnaInGivenOut(t,e,n,s,r){return(0,f.calculate_lrna_in_given_out)(t,e,n,s,r)}static calculateOutGivenIn(t,e,n,s,r,i,a,o,l){return(0,f.calculate_out_given_in)(t,e,n,s,r,i,a,o,l)}static calculateOutGivenLrnaIn(t,e,n,s,r){return(0,f.calculate_out_given_lrna_in)(t,e,n,s,r)}static calculatePoolTradeFee(t,e,n){return(0,f.calculate_pool_trade_fee)(t,e,n)}static calculateShares(t,e,n,s){return(0,f.calculate_shares)(t,e,n,s)}static calculateLiquidityOut(t,e,n,s,r,i,a,o){return(0,f.calculate_liquidity_out)(t,e,n,s,r,i,a,o)}static calculateLiquidityLRNAOut(t,e,n,s,r,i,a,o){return(0,f.calculate_liquidity_lrna_out)(t,e,n,s,r,i,a,o)}static calculateCapDifference(t,e,n,s){let r=(0,rt.default)(e),i=(0,rt.default)(t),a=(0,rt.default)(s),o=(0,rt.default)(n),l=(0,rt.default)(10).pow(18),u=o.div(l);if(r.div(a).lt(u)){let m=u.times(a).minus(r).times(i),p=r.times((0,rt.default)(1).minus(u));return m.div(p).toFixed(0)}else return"0"}static verifyAssetCap(t,e,n,s){return(0,f.verify_asset_cap)(t,e,n,s)}static calculateLimitHubIn(t,e,n,s){return(0,f.calculate_liquidity_hub_in)(t,e,n,s)}static isSellAllowed(t){return(0,f.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,f.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,f.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,f.is_remove_liquidity_allowed)(t)}};var At=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,n,s,r,i){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.hubAssetId=i}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:s.hubReserves,hubReservesOut:r.hubReserves,sharesIn:s.shares,sharesOut:r.shares,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,tradeableIn:s.tradeable,tradeableOut:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=this.calculateInGivenOut(t,e,n),i=s===0n?0:B.calculateDiffToRef(r,s),a=[],o=_.isSellAllowed(t.tradeableIn),l=_.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let d=t.balanceIn/this.maxInRatio;return r>d&&a.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:i,errors:a}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=this.calculateOutGivenIn(t,e,n),i=B.calculateDiffToRef(s,r),a=[],o=_.isSellAllowed(t.tradeableIn),l=_.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let d=t.balanceOut/this.maxOutRatio;return r>d&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let s=_.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateLrnaInGivenOut(t,e,n){let s=_.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let s=_.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenLrnaIn(t,e,n){let s=_.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=_.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceLrnaInGivenOut(t){let e=_.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=_.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}spotPriceOutGivenLrnaIn(t){let e=_.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};var Yt=require("polkadot-api"),Ze=require("@polkadot-api/utils"),Bt=require("rxjs");var _t=class extends N{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,s,r,i,a]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.getBalance(e,t),this.getPoolLimits()]),o=n.map(async({keyArgs:u,value:d})=>{let[m]=u,{hub_reserve:p,shares:g,tradable:P,cap:y,protocol_shares:I}=d,[T,x]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,m)]);return{id:m,decimals:T?.decimals,existentialDeposit:T?.existential_deposit,balance:x,cap:y,hubReserves:p,protocolShares:I,shares:g,tradeable:P,type:T?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:i,tradeable:s,type:r?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...a}]}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=(0,Ze.toHex)(e);return(0,Yt.AccountId)(63).dec(n)}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(t,e){let[n,s,r]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),i=n.min_fee+s.min_fee,a=n.max_fee+s.max_fee;if(r){let{asset_fee:o,protocol_fee:l}=r;return{assetFee:h.fromPermill(o),protocolFee:h.fromPermill(l),min:h.fromPermill(i),max:h.fromPermill(a)}}else return{assetFee:h.fromPermill(n.min_fee),protocolFee:h.fromPermill(s.min_fee),min:h.fromPermill(i),max:h.fromPermill(a)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Yt.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,Bt.distinctUntilChanged)((n,s)=>!s.deltas),(0,Bt.map)(({entries:n})=>n.map(s=>{let[r]=s.args,{hub_reserve:i,shares:a,tradable:o,cap:l,protocol_shares:u}=s.value,d=t.tokens.findIndex(p=>p.id===r);return{...t.tokens[d],cap:l,hubReserves:i,protocolShares:u,shares:a,tradeable:o}})),(0,Bt.map)(n=>{let s=t.tokens.find(r=>r.id===1);return{...t,tokens:[...n,s]}}))}};var Oe={};S(Oe,{StableMath:()=>D,StableSwap:()=>Rt,StableSwapClient:()=>Ft});var v=require("@galacticcouncil/math-stableswap"),D=class{static getPoolAddress(t){return(0,v.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,s,r){return(0,v.calculate_amplification)(t,e,n,s,r)}static calculateInGivenOut(t,e,n,s,r,i,a){return(0,v.calculate_in_given_out)(t,e,n,s,r,i,a)}static calculateAddOneAsset(t,e,n,s,r,i,a){return(0,v.calculate_add_one_asset)(t,e,n,s,r,i,a)}static calculateSharesForAmount(t,e,n,s,r,i,a){return(0,v.calculate_shares_for_amount)(t,e,n,s,r,i,a)}static calculateOutGivenIn(t,e,n,s,r,i,a){return(0,v.calculate_out_given_in)(t,e,n,s,r,i,a)}static calculateLiquidityOutOneAsset(t,e,n,s,r,i,a){return(0,v.calculate_liquidity_out_one_asset)(t,e,n,s,r,i,a)}static calculateShares(t,e,n,s,r,i){return(0,v.calculate_shares)(t,e,n,s,r,i)}static calculateSpotPriceWithFee(t,e,n,s,r,i,a,o){return(0,v.calculate_spot_price_with_fee)(t,e,n,s,r,i,a,o)}static calculatePoolTradeFee(t,e,n){return(0,v.calculate_pool_trade_fee)(t,e,n)}static recalculatePegs(t,e,n,s,r){return(0,v.recalculate_peg)(t,e,n,s,r)}};var Rt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.id,t.fee,t.totalIssuance)}constructor(t,e,n,s,r,i,a,o,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.amplification=i,this.id=a,this.fee=o,this.totalIssuance=l}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=this.calculateInGivenOut(t,e,n),i=h.toPct(n.fee),a=[],o=_.isSellAllowed(t.tradeableIn),l=_.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:i,errors:a}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=this.calculateOutGivenIn(t,e,n),i=h.toPct(n.fee),a=[],o=_.isSellAllowed(t.tradeableIn),l=_.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateIn(t,e,n){let s=D.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateAddOneAsset(t,e,n){let s=D.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateSharesForAmount(t,e,n){let s=D.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateInGivenOut(t,e,n){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,n):t.assetIn==this.id?this.calculateSharesForAmount(t,e,n):this.calculateIn(t,e,n)}spotPriceInGivenOut(t){let e=D.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetOut==this.id)return BigInt(e);if(t.assetIn==this.id){let s=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let s=D.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateWithdrawOneAsset(t,e,n){let s=D.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateShares(t,e,n){let s=D.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(t,e,n){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,n):t.assetOut==this.id?this.calculateShares(t,e,n):this.calculateOut(t,e,n)}spotPriceOutGivenIn(t){let e=D.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetIn==this.id)return BigInt(e);if(t.assetOut==this.id){let s=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let[n,s]=e.fee,r=D.calculatePoolTradeFee(t.toString(),n,s);return BigInt(r)}getPegs(){let t=D.defaultPegs(this.tokens.length-1);return JSON.stringify(t)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:n,decimals:s})=>({asset_id:e,amount:n,decimals:s}));return JSON.stringify(t,Z.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],Z.jsonFormatter)}};var jt=require("polkadot-api"),tn=require("@polkadot-api/utils"),en=require("@noble/hashes/blake2b"),mt=require("rxjs");var Wn=340282366920938463463374607431768211455n,Ft=class extends N{poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),s=t.map(async({keyArgs:r,value:i})=>{let[a]=r,o=this.getPoolAddress(a),[l,u]=await Promise.all([this.getPoolDelta(a,i,e),this.getPoolTokens(a,i)]);return this.poolsData.set(o,i),{address:o,id:a,type:"Stableswap",fee:h.fromPermill(i.fee),tokens:u,...l,...n}});return Promise.all(s)}async getPoolDelta(t,e,n){let{initial_amplification:s,final_amplification:r,initial_block:i,final_block:a}=e,o=D.calculateAmplification(s.toString(),r.toString(),i.toString(),a.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(t);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),s=e.assets.map(async a=>{let[o,l,u]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,a),this.api.query.AssetRegistry.Assets.getValue(a),this.getBalance(n,a)]);return{id:a,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:u,tradeable:o,type:l?.asset_type.type}}),r=await Promise.all(s),i=await this.api.query.AssetRegistry.Assets.getValue(t);return r.push({id:t,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:Wn,tradeable:15,type:i?.asset_type.type}),r}getPoolAddress(t){let e=D.getPoolAddress(t),n=(0,en.blake2b)(e,{dkLen:32}),s=(0,tn.toHex)(n);return(0,jt.AccountId)(63).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(t){return{fee:t.fee}}getPoolType(){return"Stableswap"}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(jt.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.System.Number,n=this.poolsData.get(t.address);return!n||!t.id?(0,mt.of)(t):e.watchValue("best").pipe((0,mt.switchMap)(s=>this.getPoolDelta(t.id,n,s)),(0,mt.map)(s=>Object.assign({},t,s)))}};var ve={};S(ve,{XykMath:()=>$,XykPool:()=>Et,XykPoolClient:()=>Dt});var R=require("@galacticcouncil/math-xyk"),$=class{static getSpotPrice(t,e,n){return(0,R.get_spot_price)(t,e,n)}static calculateInGivenOut(t,e,n){return(0,R.calculate_in_given_out)(t,e,n)}static calculateOutGivenIn(t,e,n){return(0,R.calculate_out_given_in)(t,e,n)}static calculatePoolTradeFee(t,e,n){return(0,R.calculate_pool_trade_fee)(t,e,n)}static calculateLiquidityIn(t,e,n){return(0,R.calculate_liquidity_in)(t,e,n)}static calculateSpotPrice(t,e){return(0,R.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,n,s){return(0,R.calculate_spot_price_with_fee)(t,e,n,s)}static calculateShares(t,e,n){return(0,R.calculate_shares)(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,s){return(0,R.calculate_liquidity_out_asset_a)(t,e,n,s)}static calculateLiquidityOutAssetB(t,e,n,s){return(0,R.calculate_liquidity_out_asset_b)(t,e,n,s)}};var Et=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,r){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=this.calculateTradeFee(s,n),i=h.toPct(n.exchangeFee),a=s+r,o=[];(e<this.minTradingLimit||s<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:i,errors:o}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=this.calculateTradeFee(s,n),i=h.toPct(n.exchangeFee),a=s-r,o=[];(e<this.minTradingLimit||s<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:i,errors:o}}calculateInGivenOut(t,e){let n=$.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=$.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=$.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=$.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=$.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};var nn=require("polkadot-api"),sn=require("rxjs");var Dt=class extends N{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,n]=await Promise.all([t.getEntries(),this.getPoolLimits()]),s=e.map(async({keyArgs:r,value:i})=>{let[a]=r,[o,l]=i,[u,d,m,p]=await Promise.all([this.getBalance(a,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(a,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:a,type:"XYK",tokens:[{id:o,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:u,type:d?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:m,type:p?.asset_type.type}],...n}});return Promise.all(s)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(nn.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){return(0,sn.of)(t)}};var Ae={};S(Ae,{AavePool:()=>kt,AavePoolClient:()=>Ct});var kt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,r){this.type="Aave",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=[];return e>t.balanceOut&&r.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:r}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=[];return s>t.balanceOut&&r.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:r}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){let e=Math.pow(10,t.decimalsOut);return BigInt(e)}spotPriceOutGivenIn(t){let e=Math.pow(10,t.decimalsIn);return BigInt(e)}calculateTradeFee(t,e){return 0n}};var an=require("polkadot-api"),on=require("@polkadot-api/utils"),pt=require("rxjs"),ln=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:Vn}=tt,Xn=["Supply","Withdraw","Repay","Borrow"],Ct=class extends N{async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:s,liqudity_in:r,liqudity_out:i})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(n,s),type:"Aave",tokens:[{id:n,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:r,location:o,type:a?.asset_type.type},{id:s,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:i,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:s,liqudity_out:r}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id);return t.tokens.map(i=>{let a=i.id===e.id?s:r;return{...i,balance:a}})}getPoolId(t,e){let n=t+"/"+e,s=new TextEncoder().encode(n.padEnd(32,"\0")),r=(0,on.toHex)(s);return(0,an.AccountId)(63).dec(r)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(t,e){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(t){let[e,n]=t.tokens,s=this.getReserveH160Id(e),r=this.api.event.Router.Executed.watch(({asset_in:a,asset_out:o})=>a===n.id||o===n.id),i=this.api.event.EVM.Log.watch(({log:a})=>{let{topics:o,data:l}=a,u=o.map(g=>g.asHex()),d=l.asHex(),{eventName:m,args:p}=(0,ln.decodeEventLog)({abi:rn,topics:u,data:d});return Xn.includes(m)&&p.reserve.toLowerCase()===s.toLowerCase()});return(0,pt.merge)([r,i]).pipe((0,pt.switchMap)(()=>this.getPoolDelta(t)),(0,pt.map)(a=>({...t,tokens:[...a]})))}getReserveH160Id(t){return t.type==="Erc20"?Z.findNestedKey(t.location,"AccountKey20").AccountKey20.key:Vn.fromAssetId(t.id)}};var dt=class{static get(t){switch(t.type){case"Aave":return kt.fromPool(t);case"XYK":return Et.fromPool(t);case"Omnipool":return At.fromPool(t);case"LBP":return Ot.fromPool(t);case"Stableswap":return Rt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var j=require("rxjs");var gt=class extends M{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=j.Subscription.EMPTY;omniSub=j.Subscription.EMPTY;stableSub=j.Subscription.EMPTY;xykSub=j.Subscription.EMPTY;aaveSub=j.Subscription.EMPTY;isReady=!1;isDestroyed=new j.Subject;constructor(t){super(t),this.lbpClient=new vt(t),this.omniClient=new _t(t),this.stableClient=new Ft(t),this.xykClient=new Dt(t),this.aaveClient=new Ct(t),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(t){return t.getSubscriber().pipe((0,j.takeUntil)(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)})}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(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let n=this.clients.find(s=>s.getPoolType()===t.type);if(n)return n.getPoolFees(t,e);throw new St(t.type)}};var Ee={};S(Ee,{Router:()=>bt,TradeOrderError:()=>Re,TradeOrderType:()=>$t,TradeRouteBuilder:()=>H,TradeRouter:()=>yt,TradeScheduler:()=>ht,TradeType:()=>zt});var Kt=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Yn=5,Mt=class{isNotVisited(t,e){let n=!0;return e.forEach(s=>{(s[0]===t[0]||s[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let s=[],r=new Kt,i=[];for(i.push([e,""]),r.enqueue(i);r.size()>0;){let a=r.dequeue();if(a==null||a.length>Yn)return s;let o=a[a.length-1];(n===null||o[0]===n)&&s.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let d=[...a];d.push(u),r.enqueue(d)}})}return s}buildAndPopulateGraph(t,e){let n=new Map;for(let s of t)n.set(parseInt(s),[]);for(let[s,r,i]of e)n.get(r)?.push([i,s]);return n}};function _e(c){let t={};for(let e of c){let n=e.tokens.length;for(let s=0;s<n;s++){t[e.tokens[s].id]||(t[e.tokens[s].id]=[]);for(let r=0;r<n;r++){if(s==r)continue;let i=[e.address,e.tokens[s].id,e.tokens[r].id];t[e.tokens[s].id].push(i)}}}return t}var Lt=class{getProposals(t,e,n){let s=_e(n),r=Object.keys(s),i=r.map(u=>s[u]).flat(),a=new Mt,o=a.buildAndPopulateGraph(r,i),l=a.findPaths(o,t,e);return this.parsePaths(l)}parsePaths(t){let e=[];for(let n of t){let s=[];for(let r=0;r<n.length;r++){let i=n[r],a=n[r+1];if(a==null)break;s.push(this.toEdge(i,a))}e.push(s)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var bt=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(t,e){this.ctx=t,this.routeSuggester=new Lt,this.routerOptions={...this.defaultRouterOptions,...e}}async getPools(){let t=await this.ctx.getPools(),e=this.routerOptions.useOnly;return e.length===0?t:t.filter(n=>e.includes(n.type))}async getRoutes(t,e){let n=await this.getPools();return this.validateInput(t,e,n),this.getPaths(t,e,n)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}validateInput(t,e,n){if(n.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let s=this.getAssets(n);if(!s.has(t))throw new Error(t+" is not supported asset");if(!s.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(s=>s.id)).flat().sort((n,s)=>n>s?1:-1);return new Set(e)}getPaths(t,e,n){let s=this.toPoolsMap(n);return this.routeSuggester.getProposals(t,e,n).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,s)=>n&&s)}validEdge([t,e,n],s){return s.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,dt.get(e)]))}toHops(t,e){return t.map(([n,s,r])=>{let i=e.get(n);return{poolAddress:n,poolId:i?.id,pool:i?.type,assetIn:s,assetOut:r}})}};var zt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(zt||{}),$t=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))($t||{}),Re=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(Re||{});var yt=class extends bt{isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,s)=>{let r=n[n.length-1].amountOut,i=s[s.length-1].amountOut;return r>i?-1:1});return e.find(n=>n.every(s=>s.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(n=>n.tradeFeeRange).length>0){let n=t.map(r=>r.tradeFeeRange?.[0]??r.tradeFeePct).reduce((r,i)=>r+i),s=t.map(r=>r.tradeFeeRange?.[1]??r.tradeFeePct).reduce((r,i)=>r+i);return[n,s]}}getPoolFeeRange(t){let e=t.min?h.toPct(t.min):void 0,n=t.max?h.toPct(t.max):void 0;if(e&&n)return[e,n]}async getBestSell(t,e,n){return this.getSell(t,e,n)}async getSellSpot(t){let e=t[t.length-1];if(t.length===1)return e.spotPrice;let n=t.map(a=>a.assetOutDecimals).reduce((a,o)=>a+o),s=t.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-e.assetOutDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getSell(t,e,n,s){let r=await super.getPools(),i=super.validateInput(t,e,r),a=super.getPaths(t,e,r);if(a.length===0)throw new ct(t,e);let o;if(s)o=await this.toSellSwaps(n,s,i);else{let F=await Promise.all(a.map(k=>this.toSellSwaps(n,k,i)));o=this.findBestSellRoute(F)}let l=o[0],u=o[o.length-1],d=this.isDirectTrade(o),m=await this.getSellSpot(o),p=u.amountOut,g=d?u.calculatedOut:this.calculateDelta0Y(l.amountIn,o,i),P=g-p,y=this.getRouteFeeRange(o),I=d?u.tradeFeePct:B.calculateSellFee(g,p),T=Math.pow(10,l.assetInDecimals),x=l.amountIn*m/BigInt(T),A=B.calculateDiffToRef(g,x);return{type:"Sell",amountIn:l.amountIn,amountOut:u.amountOut,spotPrice:m,tradeFee:P,tradeFeePct:I,tradeFeeRange:y,priceImpactPct:A,swaps:o,toHuman(){return{type:"Sell",amountIn:b.toDecimal(l.amountIn,l.assetInDecimals),amountOut:b.toDecimal(u.amountOut,u.assetOutDecimals),spotPrice:b.toDecimal(m,u.assetOutDecimals),tradeFee:b.toDecimal(P,u.assetOutDecimals),tradeFeePct:I,tradeFeeRange:y,priceImpactPct:A,swaps:o.map(F=>F.toHuman())}}}}calculateDelta0Y(t,e,n){let s=[];for(let r=0;r<e.length;r++){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r>0?l=s[r-1]:l=t;let u=a.calculateOutGivenIn(o,l);s.push(u)}return s[s.length-1]}async toSellSwaps(t,e,n){let s=[];for(let r=0;r<e.length;r++){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r>0?l=s[r-1].amountOut:l=typeof t=="string"?b.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountOut:d,calculatedOut:m,feePct:p,errors:g}=a.validateAndSell(o,l,u),P=this.getPoolFeeRange(u),y=a.spotPriceOutGivenIn(o),I=Math.pow(10,o.decimalsIn),T=l*y/BigInt(I),x=B.calculateDiffToRef(m,T);s.push({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:d,calculatedOut:m,spotPrice:y,tradeFeePct:p,tradeFeeRange:P,priceImpactPct:x,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===i.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:b.toDecimal(l,o.decimalsIn),amountOut:b.toDecimal(d,o.decimalsOut),calculatedOut:b.toDecimal(m,o.decimalsOut),spotPrice:b.toDecimal(y,o.decimalsOut),tradeFeePct:p,tradeFeeRange:P,priceImpactPct:x,errors:g}}})}return s}async getMostLiquidRoute(t,e){let n=await super.getPools(),s=super.validateInput(t,e,n),r=super.getPaths(t,e,n),o=n.filter(m=>m.tokens.some(p=>p.id===t&&p.id!==m.id)).map(m=>m.type==="Aave"?m.tokens:m.tokens.filter(p=>p.id===t)).map(m=>m.map(p=>p.balance).reduce((p,g)=>p+g)).sort((m,p)=>p<m?-1:1)[0],l=B.getFraction(o,.1),u=await Promise.all(r.map(m=>this.toSellSwaps(l,m,s)));return this.findBestSellRoute(u).map(m=>({poolAddress:m.poolAddress,poolId:m?.poolId,pool:m.pool,assetIn:m.assetIn,assetOut:m.assetOut}))}async getSpotPrice(t,e){let n=await super.getPools(),s=super.validateInput(t,e,n),r=await this.getMostLiquidRoute(t,e),i=await this.toSellSwaps("1",r,s),a=await this.getSellSpot(i),o=i[i.length-1].assetOutDecimals;return{amount:a,decimals:o}}findBestBuyRoute(t){let e=t.sort((n,s)=>{let r=n[0].amountIn,i=s[0].amountIn;return r>i?1:-1});return e.find(n=>n.every(s=>s.errors.length==0))||e[0]}async getBestBuy(t,e,n){return this.getBuy(t,e,n)}async getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let n=t.map(a=>a.assetInDecimals).reduce((a,o)=>a+o),s=t.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-e.assetInDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getBuy(t,e,n,s){let r=await super.getPools(),i=super.validateInput(t,e,r),a=super.getPaths(t,e,r);if(a.length===0)throw new ct(t,e);let o;if(s)o=await this.toBuySwaps(n,s,i);else{let F=await Promise.all(a.map(k=>this.toBuySwaps(n,k,i)));o=this.findBestBuyRoute(F)}let l=o[o.length-1],u=o[0],d=this.isDirectTrade(o),m=await this.getBuySpot(o),p=u.amountIn,g=d?u.calculatedIn:this.calculateDelta0X(l.amountOut,o,i),P=p-g,y=this.getRouteFeeRange(o),I=d?u.tradeFeePct:B.calculateBuyFee(g,p),T=Math.pow(10,l.assetOutDecimals),x=l.amountOut*m/BigInt(T),A;return g===0n?A=-100:A=B.calculateDiffToRef(x,g),{type:"Buy",amountOut:l.amountOut,amountIn:u.amountIn,spotPrice:m,tradeFee:P,tradeFeePct:I,tradeFeeRange:y,priceImpactPct:A,swaps:o,toHuman(){return{type:"Buy",amountOut:b.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:b.toDecimal(u.amountIn,u.assetInDecimals),spotPrice:b.toDecimal(m,u.assetInDecimals),tradeFee:b.toDecimal(P,u.assetInDecimals),tradeFeePct:I,tradeFeeRange:y,priceImpactPct:A,swaps:o.map(F=>F.toHuman())}}}}calculateDelta0X(t,e,n){let s=[];for(let r=e.length-1;r>=0;r--){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r==e.length-1?l=t:l=s[0];let u=a.calculateInGivenOut(o,l);s.unshift(u)}return s[0]}async toBuySwaps(t,e,n){let s=[];for(let r=e.length-1;r>=0;r--){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r==e.length-1?l=typeof t=="string"?b.toBigInt(t,o.decimalsOut):t:l=s[0].amountIn;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountIn:d,calculatedIn:m,feePct:p,errors:g}=a.validateAndBuy(o,l,u),P=this.getPoolFeeRange(u),y=a.spotPriceInGivenOut(o),I=Math.pow(10,o.decimalsOut),T=l*y/BigInt(I),x;m===0n?x=-100:x=B.calculateDiffToRef(T,m),s.unshift({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:d,calculatedIn:m,spotPrice:y,tradeFeePct:p,tradeFeeRange:P,priceImpactPct:x,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===i.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:b.toDecimal(l,o.decimalsOut),amountIn:b.toDecimal(d,o.decimalsIn),calculatedIn:b.toDecimal(m,o.decimalsIn),spotPrice:b.toDecimal(y,o.decimalsIn),tradeFeePct:p,tradeFeeRange:P,priceImpactPct:x,errors:g}}})}return s}};var un=1000000000000000n;var Fe=require("polkadot-api");var H=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:s,poolId:r})=>s==="Stableswap"?{pool:(0,Fe.Enum)("Stableswap",r),asset_in:e,asset_out:n}:{pool:(0,Fe.Enum)(s),asset_in:e,asset_out:n})}};var ht=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??un})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,s,r){let[i,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:u}=a,d=l[0],m=l[l.length-1],{assetInDecimals:p}=d,{assetOutDecimals:g}=m,P=Math.abs(u),y=this.getMinimumTradeCount(o,i),I=this.getOptimalTradeCount(P),T=r?Math.round(s/r):I,x=Math.ceil(s/y),A=Math.round(s/I),F=Math.round(s/T),k=o/BigInt(T),C=await this.router.getBestSell(t,e,k),Q=o<i,qt=[];Q&&qt.push("OrderTooSmall");let Nt=C.amountOut*BigInt(T),ee=this.toBlockPeriod(F),ne=C.tradeFee*BigInt(T),dn=H.build(l),Ce={assetIn:t,assetOut:e,errors:qt,frequencyMin:x,frequencyOpt:A,frequency:F,tradeCount:T,tradeFee:ne,tradeImpactPct:C.priceImpactPct,tradePeriod:ee,tradeRoute:dn,type:"Dca"};return{...Ce,amountIn:o,amountOut:Nt,tradeAmountIn:C.amountIn,tradeAmountOut:C.amountOut,toHuman(){return{...Ce,amountIn:b.toDecimal(o,p),amountOut:b.toDecimal(Nt,g),tradeAmountIn:b.toDecimal(C.amountIn,p),tradeAmountOut:b.toDecimal(C.amountOut,g)}}}}async getMinimumOrderBudget(t){if(0===t)return this.minOrderBudget;let e=await this.router.getSpotPrice(0,t),n=10n**BigInt(12);if(e)return this.minOrderBudget*e.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(t,e){let n=e*2n/10n;if(n===0n)return 0;let s=t+n/2n;return Number(s/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:m}=u,p=Math.abs(o),g=this.getTwapTradeCount(p),P=i/BigInt(g),y=await this.router.getBestSell(l.assetIn,u.assetOut,P),I=g===1,T=i<s,x=y.priceImpactPct<-5,A=[];T||I?A.push("OrderTooSmall"):x&&A.push("OrderImpactTooBig");let F=y.amountOut*BigInt(g),k=y.tradeFee*BigInt(g),C=H.build(a),Q={assetIn:t,assetOut:e,errors:A,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:6,tradeRoute:C,type:"TwapSell"};return{...Q,amountIn:i,amountOut:F,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:k,toHuman(){return{...Q,amountIn:b.toDecimal(i,d),amountOut:b.toDecimal(F,m),tradeAmountIn:b.toDecimal(y.amountIn,d),tradeAmountOut:b.toDecimal(y.amountOut,m),tradeFee:b.toDecimal(k,m)}}}}async getTwapBuyOrder(t,e,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:m}=u,p=Math.abs(o),g=this.getTwapTradeCount(p),P=i/BigInt(g),y=await this.router.getBestBuy(l.assetIn,u.assetOut,P),I=y.amountIn*BigInt(g),T=g===1,x=I<s,A=y.priceImpactPct<-5,F=[];x||T?F.push("OrderTooSmall"):A&&F.push("OrderImpactTooBig");let k=y.tradeFee*BigInt(g),C=H.build(a),Q={assetIn:t,assetOut:e,errors:F,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:6,tradeRoute:C,type:"TwapBuy"};return{...Q,amountIn:I,amountOut:i,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:k,toHuman(){return{...Q,amountIn:b.toDecimal(I,d),amountOut:b.toDecimal(i,m),tradeAmountIn:b.toDecimal(y.amountIn,d),tradeAmountOut:b.toDecimal(y.amountOut,m),tradeFee:b.toDecimal(k,d)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,n=Math.round(e);return Math.max(n,6)}};var ke={};S(ke,{TxBuilderFactory:()=>ft});var De=require("polkadot-api");function pn(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var Pt=class extends M{evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evmClient=e??new L,this.balanceClient=new X(t),this.aaveUtils=new et(this.evmClient)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:n=>this.dryRun(n,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:oe})}async dryRun(t,e){let n=(0,De.Enum)("Signed",t),s=(0,De.Enum)("system",n),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall),a=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(a){let o=pn(a.value);throw new Error("Dry run execution error!",{cause:o})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var Jt=class extends Pt{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],r=await this.balanceClient.getBalance(this.beneficiary,s);return t>=r-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=B.getFraction(t,this.slippagePct),a=s.assetIn,o=r.assetOut,l=t+i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:H.build(n)}),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=B.getFraction(e,this.slippagePct),a=s.assetIn,o=r.assetOut,l=e-i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:H.build(n)}),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,n=e[0],s=e[e.length-1],r=B.getFraction(t,this.slippagePct),i=n.assetIn,a=s.assetOut,o=t-r,l=this.api.tx.Router.sell_all({asset_in:i,asset_out:a,min_amount_out:o,route:H.build(e)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var Zt=require("polkadot-api");var te=class extends Pt{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradePeriod:r,tradeRoute:i}=this.order,a=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,order:(0,Zt.Enum)("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=B.getFraction(r,this.slippagePct),l=r-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,order:(0,Zt.Enum)("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=B.getFraction(s,this.slippagePct),l=s+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,order:(0,Zt.Enum)("Buy",{asset_in:e,asset_out:n,amount_out:r,max_amount_in:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var ft=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e??new L}trade(t){return new Jt(this.client,this.evmClient).setTrade(t)}order(t){return new te(this.client,this.evmClient).setOrder(t)}};async function zn(c,t){let e=new ut(c),[n,s]=await Promise.all([e.getBlockTime(),e.getMinOrderBudget()]),r=t??new L,i=new gt(c).withAave().withOmnipool().withStableswap().withXyk(),a=new et(r),o=new yt(i),l=new ht(o,{blockTime:n,minBudgetInNative:s});return{api:{aave:a,router:o,scheduler:l},client:{asset:new lt(c),balance:new X(c),evm:r},ctx:{pool:i},tx:new ft(c,r),destroy:()=>{i.destroy()}}}0&&(module.exports={aave,api,big,client,const:null,createSdkContext,erc20,error,evm,fmt,h160,json,math,pool,sor,tx,xc});
1
+ "use strict";var gn=Object.create;var Gt=Object.defineProperty;var bn=Object.getOwnPropertyDescriptor;var yn=Object.getOwnPropertyNames;var hn=Object.getPrototypeOf,Pn=Object.prototype.hasOwnProperty;var Me=(c,t)=>()=>(c&&(t=c(c=0)),t);var S=(c,t)=>{for(var e in t)Gt(c,e,{get:t[e],enumerable:!0})},Ht=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of yn(t))!Pn.call(c,s)&&s!==e&&Gt(c,s,{get:()=>t[s],enumerable:!(n=bn(t,s))||n.enumerable});return c},at=(c,t,e)=>(Ht(c,t,"default"),e&&Ht(e,t,"default")),se=(c,t,e)=>(e=c!=null?gn(hn(c)):{},Ht(t||!c||!c.__esModule?Gt(e,"default",{value:c,enumerable:!0}):e,c)),fn=c=>Ht(Gt({},"__esModule",{value:!0}),c);var Tt={};var Ne=Me(()=>{at(Tt,require("@polkadot-api/ws-provider/node"))});var xt={};var He=Me(()=>{at(xt,require("@polkadot-api/ws-provider/web"))});var $n={};S($n,{aave:()=>fe,api:()=>re,big:()=>b,client:()=>Te,const:()=>de,createSdkContext:()=>zn,erc20:()=>tt,error:()=>Ie,evm:()=>ue,fmt:()=>h,h160:()=>wt,json:()=>Z,math:()=>A,pool:()=>Be,sor:()=>Ee,tx:()=>ke,xc:()=>he});module.exports=fn($n);var re={};S(re,{Papi:()=>M,getWs:()=>Tn});var qe=require("@galacticcouncil/descriptors");function Le(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var M=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(qe.hydration)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Le(n)&&console.log(t,...e)}};var Ge=require("polkadot-api"),Ue=require("polkadot-api/polkadot-sdk-compat"),Tn=async c=>{let t=typeof c=="string"?c.split(","):c,s=(typeof window>"u"?(await Promise.resolve().then(()=>(Ne(),Tt))).getWsProvider:(await Promise.resolve().then(()=>(He(),xt))).getWsProvider)(t);return(0,Ge.createClient)((0,Ue.withPolkadotSdkCompat)(s))};var fe={};S(fe,{AAVE_GAS_LIMIT:()=>oe,AAVE_LENDING_POOL_ADDRESS:()=>Vt,AAVE_POOL_ABI:()=>ae,AAVE_POOL_DATA_PROVIDER:()=>Wt,AAVE_POOL_DATA_PROVIDER_ABI:()=>Ut,AAVE_POOL_PROXY:()=>ie,AAVE_ROUNDING_THRESHOLD:()=>ps,AAVE_UINT_256_MAX:()=>xn,AaveClient:()=>It,AaveUtils:()=>et});var ae=[{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 Ut=[{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 ie="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Wt="0x112b087b60C1a166130d59266363C45F8aa99db0",Vt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",oe=1000000n,ps=5,xn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ue={};S(ue,{EvmClient:()=>L,evmMainnet:()=>le});var Xe=require("viem"),We=["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"],Ve=["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"],le=(0,Xe.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:We,webSocket:Ve},default:{http:We,webSocket:Ve}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var G=require("viem");var L=class{chain;constructor(t){this.chain=t||le}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}async getGasPrice(){return this.getProvider().getGasPrice()}getProvider(){return(0,G.createPublicClient)({chain:this.chain,transport:(0,G.http)()})}getWsProvider(){return(0,G.createPublicClient)({chain:this.chain,transport:(0,G.webSocket)()})}getSigner(t){return(0,G.createWalletClient)({account:t,chain:this.chain,transport:(0,G.custom)(window.ethereum)})}};var It=class{evmClient;constructor(t){this.evmClient=t??new L}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Ut,address:Wt,args:[Vt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.evmClient.getProvider().readContract({abi:Ut,address:Wt,args:[Vt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.evmClient.getProvider().readContract({abi:ae,address:ie,args:[t],functionName:"getUserAccountData"})}};var b={};S(b,{asBigInt:()=>Sn,toBigInt:()=>wn,toDecimal:()=>In});var J=se(require("big.js"));J.default.NE=-18;function In(c,t,e=6,n){let s=(0,J.default)(c.toString()),r=(0,J.default)(10).pow(t);return s.div(r).round(e,n).toString()}function wn(c,t){let e=(0,J.default)(10).pow(t),s=(0,J.default)(c).mul(e).toFixed(0,J.default.roundDown);return BigInt(s)}function Sn(c){return BigInt(c.round(0,J.default.roundDown).toFixed(0))}var tt={};S(tt,{ERC20:()=>ce});var ce=class{static fromAssetId(t){let e=Buffer.alloc(20,0);return e[15]=1,e.writeUInt32BE(t,16),"0x"+e.toString("hex")}static toAssetId(t){let e=Buffer.from(t.replace("0x",""),"hex");return e.length!==20||!this.isAssetAddress(t)?null:e.readUInt32BE(16)}static isAssetAddress(t){let e=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(e.subarray(0,16))}};var h={};S(h,{fromPermill:()=>An,toDecimals:()=>vn,toPct:()=>On});var Ye=1e3;function On(c){let[t,e]=c;return t/e*100}function vn(c){let[t,e]=c;return t/e}function An(c){return[c/Ye,Ye]}var wt={};S(wt,{H160:()=>ye,isEvmAccount:()=>je,isEvmAddress:()=>Ke,isSs58Address:()=>ze});var ot=require("polkadot-api"),ge=require("@polkadot-api/utils"),z=require("buffer");var de={};S(de,{HUB_ASSET_ID:()=>pe,HYDRATION_OMNIPOOL_ADDRESS:()=>_n,HYDRATION_PARACHAIN_ID:()=>Bn,HYDRATION_SS58_PREFIX:()=>W,RUNTIME_DECIMALS:()=>q,SYSTEM_ASSET_DECIMALS:()=>me,SYSTEM_ASSET_ID:()=>K,TRADEABLE_DEFAULT:()=>it});var q=18,K=0,me=12,Bn=2034,W=63,_n="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",pe=1,it=15;var be="ETH\0";function je(c){if(!c)return!1;try{let t=(0,ot.AccountId)().enc(c),e=z.Buffer.from(be);return z.Buffer.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function Ke(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function ze(c){try{return(0,ot.AccountId)(63).enc(c),!0}catch{return!1}}var ye=class c{static toAccount=t=>{let e=z.Buffer.from(t.slice(2),"hex"),n=z.Buffer.from(be),s=Uint8Array.from(z.Buffer.concat([n,e,z.Buffer.alloc(8)])),r=(0,ge.toHex)(s);return(0,ot.AccountId)(63).dec(r)};static fromAccount=t=>{let e=(0,ot.AccountId)().enc(t),n=z.Buffer.from(be),s=e.slice(n.length,-8);return"0x"+z.Buffer.from(s).toString("hex")};static fromSS58=t=>{let n=(0,ot.AccountId)().enc(t).slice(0,20);return(0,ge.toHex)(n)};static fromAny=t=>{if(Ke(t))return t;if(je(t))return c.fromAccount(t);if(ze(t))return c.fromSS58(t);throw new Error("Unknown address type")}};var Z={};S(Z,{findNestedKey:()=>Rn,findNestedObj:()=>Fn,jsonFormatter:()=>En});var Rn=(c,t)=>{let e=[];return JSON.stringify(c,(n,s)=>(s&&s[t]&&e.push(s),s)),e[0]},Fn=(c,t,e)=>{let n;return JSON.stringify(c,(s,r)=>(r&&r[t]===e&&(n=r),r)),n},En=(c,t)=>typeof t=="bigint"?t.toString():t;var A={};S(A,{calculateBuyFee:()=>Mn,calculateDiffToAvg:()=>Dn,calculateDiffToRef:()=>kn,calculateSellFee:()=>Cn,getFraction:()=>Ln});var V=se(require("big.js"));function Dn(c,t){let e=(0,V.default)(c.toString()),n=(0,V.default)(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function kn(c,t){if(t===0n)return 0;let e=(0,V.default)(c.toString()),n=(0,V.default)(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function Cn(c,t){let e=(0,V.default)(c.toString()),n=(0,V.default)(t.toString());return(0,V.default)(1).minus(n.div(e)).mul(100).round(2).toNumber()}function Mn(c,t){let e=(0,V.default)(c.toString());return(0,V.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function Ln(c,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),s=BigInt(t*n);return c*s/BigInt(100*n)}var he={};S(he,{convertToId:()=>qn});var $e=require("buffer");function qn(c){let e=$e.Buffer.from(c.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var{ERC20:Xt}=tt,{H160:Pe}=wt,Nn=1.01,Hn=99999,Gn=10n**27n,Un=10n**18n,et=class{client;constructor(t){let e=t??new L;this.client=new It(e)}async getSummary(t){let e=Pe.fromAny(t),[n,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e)]),[i]=n,[a,o]=s,[l,u,d,m,p,g]=r,P=b.toDecimal(g,18),y=[];for(let I of a){let f=I.underlyingAsset.toLowerCase(),T=i.find(({underlyingAsset:ne})=>ne.toLowerCase()===f);if(!T)throw new Error("Missing pool reserve for "+f);let v=I.scaledATokenBalance,F=T.liquidityIndex,k=T.priceInMarketReferenceCurrency,C=v*F/Gn,qt=Number(o===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,Nt=T.usageAsCollateralEnabled&&I.usageAsCollateralEnabledOnUser&&I.scaledATokenBalance>0n,ee=Xt.toAssetId(f);y.push({aTokenBalance:C,decimals:Number(T.decimals),isCollateral:Nt,priceInRef:k,reserveId:ee,reserveAsset:f,reserveLiquidationThreshold:qt})}return{healthFactor:Number(P),totalCollateral:l,totalDebt:u,reserves:y}}async hasBorrowPositions(t){let e=Pe.fromAny(t),n=await this.client.getUserAccountData(e),[s,r]=n;return r>0n}async getHealthFactor(t){let e=Pe.fromAny(t),n=await this.client.getUserAccountData(e),[s,r,i,a,o,l]=n,u=b.toDecimal(l,18);return Number(u)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(t),a=Xt.fromAssetId(e),o=i.find(y=>y.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,isCollateral:u,priceInRef:d,reserveLiquidationThreshold:m}=o,p=b.toBigInt(n,l),g=u?p*d/10n**BigInt(l):0n,P=s-g;return P<=0n?0:this.calculateHealthFactor(P,m,r)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(t),a=Xt.fromAssetId(e),o=i.find(P=>P.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:d}=o,p=b.toBigInt(n,l)*u/10n**BigInt(l),g=s+p;return g<=0n?0:this.calculateHealthFactor(g,d,r)}async getMaxWithdraw(t,e){let{totalCollateral:n,totalDebt:s,reserves:r}=await this.getSummary(t),i=Xt.fromAssetId(e),a=r.find(o=>o.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(a,n,s)}async getMaxWithdrawAll(t){let{totalCollateral:e,totalDebt:n,reserves:s}=await this.getSummary(t),r={};for(let i of s){let a=this.calculateWithdrawMax(i,e,n);i.reserveId&&(r[i.reserveId]=a)}return r}calculateHealthFactor(t,e,n){if(n===0n)return Hn;let s=10n**6n,r=b.toBigInt(e,18),i=t*r*s,a=n*Un,o=i/a;return Number(o)/1e6}calculateRequiredCollateral(t,e,n){let s=b.toBigInt(t,18),r=b.toBigInt(e,18);return(s*n+r-1n)/r}calculateWithdrawMax(t,e,n){let{aTokenBalance:s,decimals:r,priceInRef:i,reserveLiquidationThreshold:a}=t,o=this.calculateRequiredCollateral(Nn,a,n),l=e-o;if(l<=0n)return{amount:0n,decimals:r};let u=l*10n**BigInt(r)/i;return{amount:s<u?s:u,decimals:r}}};var Te={};S(Te,{AssetClient:()=>lt,BalanceClient:()=>X,ChainParams:()=>ut});var lt=class extends M{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:s}=n;return this.SUPPORTED_TYPES.includes(s.type)}).map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async mapToken(t,e,n,s){let{name:r,asset_type:i,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=n.get(t)??{};return{id:t,name:r?.asText(),symbol:l,decimals:u,icon:l,type:i.type,isSufficient:a,location:s,existentialDeposit:o}}async mapBond(t,e,n,s){let[r,i]=s,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:d}=await this.mapToken(r,e,n),m=Number(i),p=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",p.format(m)].join(" ");return{id:t,name:g,symbol:u+"b",decimals:d,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:r,maturity:m}}async mapShares(t,e,n,s){let{assets:r}=s,{name:i,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,d=await Promise.all(r.map(async g=>{let{symbol:P}=await this.mapToken(g,e,n);return[g,P]})),m=Object.fromEntries(d),p=Object.values(m);return{id:t,name:p.join(", "),symbol:a?.asText()||i?.asText(),decimals:18,icon:p.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:m}}async mapExternal(t,e,n,s){let r=await this.mapToken(t,e,new Map,s),i=n?.find(a=>a.internalId===r.id);return i?{...r,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:r}parseMetadata(t){return new Map(Array.from(t,([e,n])=>[e,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(t,e){let[n,s,r,i]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(n),o=[];for(let[l,u]of Array.from(n)){let d=s.get(l),{asset_type:m}=u,p;switch(m.type){case"Bond":let g=i.get(l);p=await this.mapBond(l,u,a,g);break;case"StableSwap":let P=r.get(l);p=await this.mapShares(l,u,a,P);break;case"External":p=await this.mapExternal(l,u,e,d);break;default:p=await this.mapToken(l,u,a,d)}o.push(p)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var w=require("rxjs");var X=class extends M{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:{free:n,frozen:s}}=await e.getValue(t);return n-s}async getTokenBalance(t,e){let n=this.api.query.Tokens.Accounts,{free:s,frozen:r}=await n.getValue(t,e);return s-r}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),s=this.subscribeErc20Balance(t);return(0,w.combineLatest)([e,n,s]).pipe((0,w.debounceTime)(250),(0,w.map)(r=>r.flat()),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([r,i],a)=>{if(a===0)return i;let o=r.reduce((u,d)=>(u.set(d.id,d.amount),u),new Map);return i.filter(u=>u.amount!==o.get(u.id))}))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe((0,w.map)(n=>{let{free:s,frozen:r}=n.data;return{id:0,amount:s-r}}))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe((0,w.map)(s=>{let{free:r,frozen:i}=s;return{id:e,amount:r-i}}))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe((0,w.distinctUntilChanged)((n,s)=>!s.deltas),(0,w.map)(({deltas:n})=>{let s=[];return n?.deleted.forEach(r=>{let[i,a]=r.args;s.push({id:a,amount:0n})}),n?.upserted.forEach(r=>{let[i,a]=r.args,{free:o,frozen:l}=r.value;s.push({id:a,amount:o-l})}),s}))}subscribeErc20Balance(t,e){let n=new w.Subject,s=n.pipe((0,w.shareReplay)(1)),r=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:u}=l;return u.type==="Erc20"}).map(({keyArgs:l})=>{let[u]=l;return u}),i=async()=>{let o=e||await r(),l=async()=>{let m=(await Promise.all(o.map(async p=>{let g=await this.getTokenBalanceData(t,p);return[p,g]}))).map(([p,g])=>({id:p,amount:g}));n.next(m)};await l();let u=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>u.unsubscribe()},a;return i().then(o=>a=o),s.pipe((0,w.finalize)(()=>a?.()),(0,w.pairwise)(),(0,w.map)(([o,l],u)=>{if(u===0)return l;let d=o.reduce((p,g)=>(p.set(g.id,g.amount),p),new Map);return l.filter(p=>p.amount!==d.get(p.id))}),(0,w.distinctUntilChanged)((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let{free:n,frozen:s}=await this.api.apis.CurrenciesApi.account(e,t);return n-s}};var ut=class extends M{_minOrderBudget;_blockTime;constructor(t){super(t)}async getBlockTime(){if(this._blockTime===void 0){let t=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(t)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var Ie={};S(Ie,{AssetNotFound:()=>xe,PoolNotFound:()=>St,RouteNotFound:()=>ct});var xe=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},St=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},ct=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Be={};S(Be,{PoolContextProvider:()=>gt,PoolError:()=>nt,PoolFactory:()=>dt,PoolType:()=>E,aave:()=>Ae,lbp:()=>we,omni:()=>Se,stable:()=>Oe,xyk:()=>ve});var we={};S(we,{LbpMath:()=>U,LbpPool:()=>Ot,LbpPoolClient:()=>vt});var Y=require("@galacticcouncil/math-lbp"),U=class{static getSpotPrice(t,e,n,s,r){return(0,Y.get_spot_price)(t,e,n,s,r)}static calculateInGivenOut(t,e,n,s,r){return(0,Y.calculate_in_given_out)(t,e,n,s,r)}static calculateOutGivenIn(t,e,n,s,r){return(0,Y.calculate_out_given_in)(t,e,n,s,r)}static calculateLinearWeights(t,e,n,s,r){return(0,Y.calculate_linear_weights)(t,e,n,s,r)}static calculatePoolTradeFee(t,e,n){return(0,Y.calculate_pool_trade_fee)(t,e,n)}};var E=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r))(E||{}),nt=(r=>(r.InsufficientTradingAmount="InsufficientTradingAmount",r.MaxInRatioExceeded="MaxInRatioExceeded",r.MaxOutRatioExceeded="MaxOutRatioExceeded",r.TradeNotAllowed="TradeNotAllowed",r.UnknownError="UnknownError",r))(nt||{});var Ot=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,n,s,r,i,a){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.fee=i,this.repayFeeApply=a}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,weightIn:s.weight,weightOut:r.weight}}validateAndBuy(t,e,n){let s=this.tokens[0].id,r=[];e<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=t.balanceOut/this.maxOutRatio;if(e>i&&r.push("MaxOutRatioExceeded"),s===t.assetOut){let a=this.calculateTradeFee(e,n),o=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),d=t.balanceIn/this.maxInRatio;return u>d&&r.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:r}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&r.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:r}}}validateAndSell(t,e,n){let s=this.tokens[0].id,r=[];e<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=t.balanceIn/this.maxInRatio;if(e>i&&r.push("MaxInRatioExceeded"),s===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:r}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,n),l=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),u=a-o,d=t.balanceOut/this.maxOutRatio;return u>d&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:r}}}calculateInGivenOut(t,e){let n=U.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=U.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=U.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=U.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let n=U.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(n)}};var Je=require("polkadot-api"),st=require("rxjs");var Qe=(c,t=new Map)=>e=>{let n;return t.has(e)?t.get(e):(t.set(e,n=c(e)),n)};var O=require("rxjs");var N=class extends X{override=[];mem=0;memPools=Qe(t=>(this.log(this.getPoolType(),"mem pools",t,"\u2705"),this.loadPools()));constructor(t){super(t)}async withOverride(t){this.override=t||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let t=(0,O.from)(this.getPoolsMem()).pipe((0,O.switchMap)(e=>this.subscribe(e)),(0,O.combineLatestAll)());return(0,O.firstValueFrom)(t)}getSubscriber(){return(0,O.from)(this.getPoolsMem()).pipe((0,O.switchMap)(t=>this.subscribe(t)),(0,O.mergeAll)())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>(0,O.combineLatest)([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe((0,O.debounceTime)(250),(0,O.map)(([n,s])=>this.updatePool(n,s))))}subscribePoolBalance(t){if(t.type==="Aave")return(0,O.of)([]);let e=[this.subscribeTokensBalance(t.address)];if(this.hasSystemAsset(t)){let n=this.subscribeSystemBalance(t.address);e.push(n)}if(this.hasErc20Asset(t)){let n=t.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),s=this.subscribeErc20Balance(t.address,n);e.push(s)}return(0,O.combineLatest)(e).pipe((0,O.map)(n=>n.map(s=>Array.isArray(s)?s:[s]).flat()))}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({id:e,decimals:n,balance:s})=>{let r=this.override.find(a=>a.id===e),i=!!n||!!r?.decimals;return s>0n&&i})}updatePool=(t,e)=>{let n=t.tokens.map(s=>{let r=e.find(a=>a.id===s.id),i=this.override.find(a=>a.id===s.id);return r?{...s,balance:r.amount,decimals:s.decimals||i?.decimals}:{...s,decimals:s.decimals||i?.decimals}});return{...t,tokens:n}}};var vt=class extends N{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),s=e?.relay_parent_number||0,r=t.filter(({value:i})=>e&&this.isActivePool(i,s)).map(async({keyArgs:i,value:a})=>{let[o]=i,l=o.toString(),u=await this.getPoolDelta(l,a,s);return{address:l,type:"LBP",fee:a.fee,...u,...n}});return Promise.all(r)}async getPoolDelta(t,e,n){let{start:s,end:r,assets:i,initial_weight:a,final_weight:o,repay_target:l,fee_collector:u}=e,d=U.calculateLinearWeights(s?s.toString():"0",r?r.toString():"0",a.toString(),o.toString(),n.toString()),[m,p]=i,g=BigInt(d),P=this.MAX_FINAL_WEIGHT-BigInt(g),[y,I,f,T,v]=await Promise.all([this.isRepayFeeApplied(m,l,u.toString()),this.getBalance(t,m),this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(t,p),this.api.query.AssetRegistry.Assets.getValue(p)]);return{repayFeeApply:y,tokens:[{id:m,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:I,weight:g,type:f?.asset_type.type},{id:p,decimals:v?.decimals,existentialDeposit:v?.existential_deposit,balance:T,weight:P,type:v?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:s}=t;return n&&s?e>=n&&e<s:!1}async isRepayFeeApplied(t,e,n){if(e===0n)return!1;try{return await this.getBalance(n,t)<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(t){return{repayFee:await this.getRepayFee(),exchangeFee:t.fee}}getPoolType(){return"LBP"}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Je.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(t.address);return n?e.watchValue("best").pipe((0,st.switchMap)(s=>s?this.getPoolDelta(t.address,n,s.relay_parent_number):(0,st.of)(t)),(0,st.map)(s=>Object.assign({},t,s))):(0,st.of)(t)}};var Se={};S(Se,{OmniMath:()=>B,OmniPool:()=>At,OmniPoolClient:()=>_t});var x=require("@galacticcouncil/math-omnipool"),rt=se(require("big.js")),B=class{static calculateSpotPrice(t,e,n,s){return(0,x.calculate_spot_price)(t,e,n,s)}static calculateLrnaSpotPrice(t,e){return(0,x.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,n,s,r,i,a,o,l){return(0,x.calculate_in_given_out)(t,e,n,s,r,i,a,o,l)}static calculateLrnaInGivenOut(t,e,n,s,r){return(0,x.calculate_lrna_in_given_out)(t,e,n,s,r)}static calculateOutGivenIn(t,e,n,s,r,i,a,o,l){return(0,x.calculate_out_given_in)(t,e,n,s,r,i,a,o,l)}static calculateOutGivenLrnaIn(t,e,n,s,r){return(0,x.calculate_out_given_lrna_in)(t,e,n,s,r)}static calculateShares(t,e,n,s){return(0,x.calculate_shares)(t,e,n,s)}static calculateLiquidityOut(t,e,n,s,r,i,a,o){return(0,x.calculate_liquidity_out)(t,e,n,s,r,i,a,o)}static calculateLiquidityLRNAOut(t,e,n,s,r,i,a,o){return(0,x.calculate_liquidity_lrna_out)(t,e,n,s,r,i,a,o)}static calculateCapDifference(t,e,n,s){let r=(0,rt.default)(e),i=(0,rt.default)(t),a=(0,rt.default)(s),o=(0,rt.default)(n),l=(0,rt.default)(10).pow(18),u=o.div(l);if(r.div(a).lt(u)){let m=u.times(a).minus(r).times(i),p=r.times((0,rt.default)(1).minus(u));return m.div(p).toFixed(0)}else return"0"}static verifyAssetCap(t,e,n,s){return(0,x.verify_asset_cap)(t,e,n,s)}static calculateLimitHubIn(t,e,n,s){return(0,x.calculate_liquidity_hub_in)(t,e,n,s)}static isSellAllowed(t){return(0,x.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,x.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,x.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,x.is_remove_liquidity_allowed)(t)}};var At=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,n,s,r,i){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.hubAssetId=i}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:s.hubReserves,hubReservesOut:r.hubReserves,sharesIn:s.shares,sharesOut:r.shares,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,tradeableIn:s.tradeable,tradeableOut:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=this.calculateInGivenOut(t,e,n),i=s===0n?0:A.calculateDiffToRef(r,s),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let d=t.balanceIn/this.maxInRatio;return r>d&&a.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:i,errors:a}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=this.calculateOutGivenIn(t,e,n),i=A.calculateDiffToRef(s,r),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let d=t.balanceOut/this.maxOutRatio;return r>d&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let s=B.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateLrnaInGivenOut(t,e,n){let s=B.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let s=B.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenLrnaIn(t,e,n){let s=B.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=B.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceLrnaInGivenOut(t){let e=B.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=B.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}spotPriceOutGivenLrnaIn(t){let e=B.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};var Yt=require("polkadot-api"),Ze=require("@polkadot-api/utils"),Bt=require("rxjs");var _t=class extends N{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,s,r,i,a]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.getBalance(e,t),this.getPoolLimits()]),o=n.map(async({keyArgs:u,value:d})=>{let[m]=u,{hub_reserve:p,shares:g,tradable:P,cap:y,protocol_shares:I}=d,[f,T]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,m)]);return{id:m,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:T,cap:y,hubReserves:p,protocolShares:I,shares:g,tradeable:P,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:i,tradeable:s,type:r?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...a}]}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=(0,Ze.toHex)(e);return(0,Yt.AccountId)(63).dec(n)}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(t,e){let[n,s,r]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),i=n.min_fee+s.min_fee,a=n.max_fee+s.max_fee;if(r){let{asset_fee:o,protocol_fee:l}=r;return{assetFee:h.fromPermill(o),protocolFee:h.fromPermill(l),min:h.fromPermill(i),max:h.fromPermill(a)}}else return{assetFee:h.fromPermill(n.min_fee),protocolFee:h.fromPermill(s.min_fee),min:h.fromPermill(i),max:h.fromPermill(a)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Yt.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,Bt.distinctUntilChanged)((n,s)=>!s.deltas),(0,Bt.map)(({entries:n})=>n.map(s=>{let[r]=s.args,{hub_reserve:i,shares:a,tradable:o,cap:l,protocol_shares:u}=s.value,d=t.tokens.findIndex(p=>p.id===r);return{...t.tokens[d],cap:l,hubReserves:i,protocolShares:u,shares:a,tradeable:o}})),(0,Bt.map)(n=>{let s=t.tokens.find(r=>r.id===1);return{...t,tokens:[...n,s]}}))}};var Oe={};S(Oe,{StableMath:()=>D,StableSwap:()=>Rt,StableSwapClient:()=>Ft});var _=require("@galacticcouncil/math-stableswap"),D=class{static getPoolAddress(t){return(0,_.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,s,r){return(0,_.calculate_amplification)(t,e,n,s,r)}static calculateInGivenOut(t,e,n,s,r,i,a){return(0,_.calculate_in_given_out)(t,e,n,s,r,i,a)}static calculateAddOneAsset(t,e,n,s,r,i,a){return(0,_.calculate_add_one_asset)(t,e,n,s,r,i,a)}static calculateSharesForAmount(t,e,n,s,r,i,a){return(0,_.calculate_shares_for_amount)(t,e,n,s,r,i,a)}static calculateOutGivenIn(t,e,n,s,r,i,a){return(0,_.calculate_out_given_in)(t,e,n,s,r,i,a)}static calculateLiquidityOutOneAsset(t,e,n,s,r,i,a){return(0,_.calculate_liquidity_out_one_asset)(t,e,n,s,r,i,a)}static calculateShares(t,e,n,s,r,i){return(0,_.calculate_shares)(t,e,n,s,r,i)}static calculateSpotPriceWithFee(t,e,n,s,r,i,a,o){return(0,_.calculate_spot_price_with_fee)(t,e,n,s,r,i,a,o)}static recalculatePegs(t,e,n,s,r){return(0,_.recalculate_peg)(t,e,n,s,r)}};var Rt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.id,t.fee,t.totalIssuance)}constructor(t,e,n,s,r,i,a,o,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.amplification=i,this.id=a,this.fee=o,this.totalIssuance=l}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=this.calculateInGivenOut(t,e,n),i=h.toPct(n.fee),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:i,errors:a}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=this.calculateOutGivenIn(t,e,n),i=h.toPct(n.fee),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateIn(t,e,n){let s=D.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateAddOneAsset(t,e,n){let s=D.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateSharesForAmount(t,e,n){let s=D.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateInGivenOut(t,e,n){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,n):t.assetIn==this.id?this.calculateSharesForAmount(t,e,n):this.calculateIn(t,e,n)}spotPriceInGivenOut(t){let e=D.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetOut==this.id)return BigInt(e);if(t.assetIn==this.id){let s=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let s=D.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateWithdrawOneAsset(t,e,n){let s=D.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateShares(t,e,n){let s=D.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(t,e,n){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,n):t.assetOut==this.id?this.calculateShares(t,e,n):this.calculateOut(t,e,n)}spotPriceOutGivenIn(t){let e=D.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetIn==this.id)return BigInt(e);if(t.assetOut==this.id){let s=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}getPegs(){let t=D.defaultPegs(this.tokens.length-1);return JSON.stringify(t)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:n,decimals:s})=>({asset_id:e,amount:n,decimals:s}));return JSON.stringify(t,Z.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],Z.jsonFormatter)}};var jt=require("polkadot-api"),tn=require("@polkadot-api/utils"),en=require("@noble/hashes/blake2b"),mt=require("rxjs");var Wn=340282366920938463463374607431768211455n,Ft=class extends N{poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),s=t.map(async({keyArgs:r,value:i})=>{let[a]=r,o=this.getPoolAddress(a),[l,u]=await Promise.all([this.getPoolDelta(a,i,e),this.getPoolTokens(a,i)]);return this.poolsData.set(o,i),{address:o,id:a,type:"Stableswap",fee:h.fromPermill(i.fee),tokens:u,...l,...n}});return Promise.all(s)}async getPoolDelta(t,e,n){let{initial_amplification:s,final_amplification:r,initial_block:i,final_block:a}=e,o=D.calculateAmplification(s.toString(),r.toString(),i.toString(),a.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(t);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),s=e.assets.map(async a=>{let[o,l,u]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,a),this.api.query.AssetRegistry.Assets.getValue(a),this.getBalance(n,a)]);return{id:a,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:u,tradeable:o,type:l?.asset_type.type}}),r=await Promise.all(s),i=await this.api.query.AssetRegistry.Assets.getValue(t);return r.push({id:t,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:Wn,tradeable:15,type:i?.asset_type.type}),r}getPoolAddress(t){let e=D.getPoolAddress(t),n=(0,en.blake2b)(e,{dkLen:32}),s=(0,tn.toHex)(n);return(0,jt.AccountId)(63).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(t){return{fee:t.fee}}getPoolType(){return"Stableswap"}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(jt.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.System.Number,n=this.poolsData.get(t.address);return!n||!t.id?(0,mt.of)(t):e.watchValue("best").pipe((0,mt.switchMap)(s=>this.getPoolDelta(t.id,n,s)),(0,mt.map)(s=>Object.assign({},t,s)))}};var ve={};S(ve,{XykMath:()=>$,XykPool:()=>Et,XykPoolClient:()=>Dt});var R=require("@galacticcouncil/math-xyk"),$=class{static getSpotPrice(t,e,n){return(0,R.get_spot_price)(t,e,n)}static calculateInGivenOut(t,e,n){return(0,R.calculate_in_given_out)(t,e,n)}static calculateOutGivenIn(t,e,n){return(0,R.calculate_out_given_in)(t,e,n)}static calculatePoolTradeFee(t,e,n){return(0,R.calculate_pool_trade_fee)(t,e,n)}static calculateLiquidityIn(t,e,n){return(0,R.calculate_liquidity_in)(t,e,n)}static calculateSpotPrice(t,e){return(0,R.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,n,s){return(0,R.calculate_spot_price_with_fee)(t,e,n,s)}static calculateShares(t,e,n){return(0,R.calculate_shares)(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,s){return(0,R.calculate_liquidity_out_asset_a)(t,e,n,s)}static calculateLiquidityOutAssetB(t,e,n,s){return(0,R.calculate_liquidity_out_asset_b)(t,e,n,s)}};var Et=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,r){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=this.calculateTradeFee(s,n),i=h.toPct(n.exchangeFee),a=s+r,o=[];(e<this.minTradingLimit||s<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:i,errors:o}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=this.calculateTradeFee(s,n),i=h.toPct(n.exchangeFee),a=s-r,o=[];(e<this.minTradingLimit||s<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:i,errors:o}}calculateInGivenOut(t,e){let n=$.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=$.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=$.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=$.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=$.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};var nn=require("polkadot-api"),sn=require("rxjs");var Dt=class extends N{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,n]=await Promise.all([t.getEntries(),this.getPoolLimits()]),s=e.map(async({keyArgs:r,value:i})=>{let[a]=r,[o,l]=i,[u,d,m,p]=await Promise.all([this.getBalance(a,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(a,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:a,type:"XYK",tokens:[{id:o,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:u,type:d?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:m,type:p?.asset_type.type}],...n}});return Promise.all(s)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(nn.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){return(0,sn.of)(t)}};var Ae={};S(Ae,{AavePool:()=>kt,AavePoolClient:()=>Ct});var kt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,r){this.type="Aave",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=[];return e>t.balanceOut&&r.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:r}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=[];return s>t.balanceOut&&r.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:r}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){let e=Math.pow(10,t.decimalsOut);return BigInt(e)}spotPriceOutGivenIn(t){let e=Math.pow(10,t.decimalsIn);return BigInt(e)}calculateTradeFee(t,e){return 0n}};var an=require("polkadot-api"),on=require("@polkadot-api/utils"),pt=require("rxjs"),ln=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:Vn}=tt,Xn=["Supply","Withdraw","Repay","Borrow"],Ct=class extends N{async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:s,liqudity_in:r,liqudity_out:i})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(n,s),type:"Aave",tokens:[{id:n,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:r,location:o,type:a?.asset_type.type},{id:s,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:i,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:s,liqudity_out:r}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id);return t.tokens.map(i=>{let a=i.id===e.id?s:r;return{...i,balance:a}})}getPoolId(t,e){let n=t+"/"+e,s=new TextEncoder().encode(n.padEnd(32,"\0")),r=(0,on.toHex)(s);return(0,an.AccountId)(63).dec(r)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(t,e){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(t){let[e,n]=t.tokens,s=this.getReserveH160Id(e),r=this.api.event.Router.Executed.watch(({asset_in:a,asset_out:o})=>a===n.id||o===n.id),i=this.api.event.EVM.Log.watch(({log:a})=>{let{topics:o,data:l}=a,u=o.map(g=>g.asHex()),d=l.asHex(),{eventName:m,args:p}=(0,ln.decodeEventLog)({abi:rn,topics:u,data:d});return Xn.includes(m)&&p.reserve.toLowerCase()===s.toLowerCase()});return(0,pt.merge)([r,i]).pipe((0,pt.switchMap)(()=>this.getPoolDelta(t)),(0,pt.map)(a=>({...t,tokens:[...a]})))}getReserveH160Id(t){return t.type==="Erc20"?Z.findNestedKey(t.location,"AccountKey20").AccountKey20.key:Vn.fromAssetId(t.id)}};var dt=class{static get(t){switch(t.type){case"Aave":return kt.fromPool(t);case"XYK":return Et.fromPool(t);case"Omnipool":return At.fromPool(t);case"LBP":return Ot.fromPool(t);case"Stableswap":return Rt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var j=require("rxjs");var gt=class extends M{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=j.Subscription.EMPTY;omniSub=j.Subscription.EMPTY;stableSub=j.Subscription.EMPTY;xykSub=j.Subscription.EMPTY;aaveSub=j.Subscription.EMPTY;isReady=!1;isDestroyed=new j.Subject;constructor(t){super(t),this.lbpClient=new vt(t),this.omniClient=new _t(t),this.stableClient=new Ft(t),this.xykClient=new Dt(t),this.aaveClient=new Ct(t),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(t){return t.getSubscriber().pipe((0,j.takeUntil)(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)})}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(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let n=this.clients.find(s=>s.getPoolType()===t.type);if(n)return n.getPoolFees(t,e);throw new St(t.type)}};var Ee={};S(Ee,{Router:()=>bt,TradeOrderError:()=>Re,TradeOrderType:()=>$t,TradeRouteBuilder:()=>H,TradeRouter:()=>yt,TradeScheduler:()=>ht,TradeType:()=>zt});var Kt=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Yn=5,Mt=class{isNotVisited(t,e){let n=!0;return e.forEach(s=>{(s[0]===t[0]||s[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let s=[],r=new Kt,i=[];for(i.push([e,""]),r.enqueue(i);r.size()>0;){let a=r.dequeue();if(a==null||a.length>Yn)return s;let o=a[a.length-1];(n===null||o[0]===n)&&s.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let d=[...a];d.push(u),r.enqueue(d)}})}return s}buildAndPopulateGraph(t,e){let n=new Map;for(let s of t)n.set(parseInt(s),[]);for(let[s,r,i]of e)n.get(r)?.push([i,s]);return n}};function _e(c){let t={};for(let e of c){let n=e.tokens.length;for(let s=0;s<n;s++){t[e.tokens[s].id]||(t[e.tokens[s].id]=[]);for(let r=0;r<n;r++){if(s==r)continue;let i=[e.address,e.tokens[s].id,e.tokens[r].id];t[e.tokens[s].id].push(i)}}}return t}var Lt=class{getProposals(t,e,n){let s=_e(n),r=Object.keys(s),i=r.map(u=>s[u]).flat(),a=new Mt,o=a.buildAndPopulateGraph(r,i),l=a.findPaths(o,t,e);return this.parsePaths(l)}parsePaths(t){let e=[];for(let n of t){let s=[];for(let r=0;r<n.length;r++){let i=n[r],a=n[r+1];if(a==null)break;s.push(this.toEdge(i,a))}e.push(s)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var bt=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(t,e){this.ctx=t,this.routeSuggester=new Lt,this.routerOptions={...this.defaultRouterOptions,...e}}async getPools(){let t=await this.ctx.getPools(),e=this.routerOptions.useOnly;return e.length===0?t:t.filter(n=>e.includes(n.type))}async getRoutes(t,e){let n=await this.getPools();return this.validateInput(t,e,n),this.getPaths(t,e,n)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}validateInput(t,e,n){if(n.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let s=this.getAssets(n);if(!s.has(t))throw new Error(t+" is not supported asset");if(!s.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(s=>s.id)).flat().sort((n,s)=>n>s?1:-1);return new Set(e)}getPaths(t,e,n){let s=this.toPoolsMap(n);return this.routeSuggester.getProposals(t,e,n).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,s)=>n&&s)}validEdge([t,e,n],s){return s.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,dt.get(e)]))}toHops(t,e){return t.map(([n,s,r])=>{let i=e.get(n);return{poolAddress:n,poolId:i?.id,pool:i?.type,assetIn:s,assetOut:r}})}};var zt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(zt||{}),$t=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))($t||{}),Re=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(Re||{});var yt=class extends bt{isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,s)=>{let r=n[n.length-1].amountOut,i=s[s.length-1].amountOut;return r>i?-1:1});return e.find(n=>n.every(s=>s.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(n=>n.tradeFeeRange).length>0){let n=t.map(r=>r.tradeFeeRange?.[0]??r.tradeFeePct).reduce((r,i)=>r+i),s=t.map(r=>r.tradeFeeRange?.[1]??r.tradeFeePct).reduce((r,i)=>r+i);return[n,s]}}getPoolFeeRange(t){let e=t.min?h.toPct(t.min):void 0,n=t.max?h.toPct(t.max):void 0;if(e&&n)return[e,n]}async getBestSell(t,e,n){return this.getSell(t,e,n)}async getSellSpot(t){let e=t[t.length-1];if(t.length===1)return e.spotPrice;let n=t.map(a=>a.assetOutDecimals).reduce((a,o)=>a+o),s=t.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-e.assetOutDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getSell(t,e,n,s){let r=await super.getPools(),i=super.validateInput(t,e,r),a=super.getPaths(t,e,r);if(a.length===0)throw new ct(t,e);let o;if(s)o=await this.toSellSwaps(n,s,i);else{let F=await Promise.all(a.map(k=>this.toSellSwaps(n,k,i)));o=this.findBestSellRoute(F)}let l=o[0],u=o[o.length-1],d=this.isDirectTrade(o),m=await this.getSellSpot(o),p=u.amountOut,g=d?u.calculatedOut:this.calculateDelta0Y(l.amountIn,o,i),P=g-p,y=this.getRouteFeeRange(o),I=d?u.tradeFeePct:A.calculateSellFee(g,p),f=Math.pow(10,l.assetInDecimals),T=l.amountIn*m/BigInt(f),v=A.calculateDiffToRef(g,T);return{type:"Sell",amountIn:l.amountIn,amountOut:u.amountOut,spotPrice:m,tradeFee:P,tradeFeePct:I,tradeFeeRange:y,priceImpactPct:v,swaps:o,toHuman(){return{type:"Sell",amountIn:b.toDecimal(l.amountIn,l.assetInDecimals),amountOut:b.toDecimal(u.amountOut,u.assetOutDecimals),spotPrice:b.toDecimal(m,u.assetOutDecimals),tradeFee:b.toDecimal(P,u.assetOutDecimals),tradeFeePct:I,tradeFeeRange:y,priceImpactPct:v,swaps:o.map(F=>F.toHuman())}}}}calculateDelta0Y(t,e,n){let s=[];for(let r=0;r<e.length;r++){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r>0?l=s[r-1]:l=t;let u=a.calculateOutGivenIn(o,l);s.push(u)}return s[s.length-1]}async toSellSwaps(t,e,n){let s=[];for(let r=0;r<e.length;r++){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r>0?l=s[r-1].amountOut:l=typeof t=="string"?b.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountOut:d,calculatedOut:m,feePct:p,errors:g}=a.validateAndSell(o,l,u),P=this.getPoolFeeRange(u),y=a.spotPriceOutGivenIn(o),I=Math.pow(10,o.decimalsIn),f=l*y/BigInt(I),T=A.calculateDiffToRef(m,f);s.push({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:d,calculatedOut:m,spotPrice:y,tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===i.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:b.toDecimal(l,o.decimalsIn),amountOut:b.toDecimal(d,o.decimalsOut),calculatedOut:b.toDecimal(m,o.decimalsOut),spotPrice:b.toDecimal(y,o.decimalsOut),tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}async getMostLiquidRoute(t,e){let n=await super.getPools(),s=super.validateInput(t,e,n),r=super.getPaths(t,e,n),o=n.filter(m=>m.tokens.some(p=>p.id===t&&p.id!==m.id)).map(m=>m.type==="Aave"?m.tokens:m.tokens.filter(p=>p.id===t)).map(m=>m.map(p=>p.balance).reduce((p,g)=>p+g)).sort((m,p)=>p<m?-1:1)[0],l=A.getFraction(o,.1),u=await Promise.all(r.map(m=>this.toSellSwaps(l,m,s)));return this.findBestSellRoute(u).map(m=>({poolAddress:m.poolAddress,poolId:m?.poolId,pool:m.pool,assetIn:m.assetIn,assetOut:m.assetOut}))}async getSpotPrice(t,e){let n=await super.getPools(),s=super.validateInput(t,e,n),r=await this.getMostLiquidRoute(t,e),i=await this.toSellSwaps("1",r,s),a=await this.getSellSpot(i),o=i[i.length-1].assetOutDecimals;return{amount:a,decimals:o}}findBestBuyRoute(t){let e=t.sort((n,s)=>{let r=n[0].amountIn,i=s[0].amountIn;return r>i?1:-1});return e.find(n=>n.every(s=>s.errors.length==0))||e[0]}async getBestBuy(t,e,n){return this.getBuy(t,e,n)}async getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let n=t.map(a=>a.assetInDecimals).reduce((a,o)=>a+o),s=t.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-e.assetInDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getBuy(t,e,n,s){let r=await super.getPools(),i=super.validateInput(t,e,r),a=super.getPaths(t,e,r);if(a.length===0)throw new ct(t,e);let o;if(s)o=await this.toBuySwaps(n,s,i);else{let F=await Promise.all(a.map(k=>this.toBuySwaps(n,k,i)));o=this.findBestBuyRoute(F)}let l=o[o.length-1],u=o[0],d=this.isDirectTrade(o),m=await this.getBuySpot(o),p=u.amountIn,g=d?u.calculatedIn:this.calculateDelta0X(l.amountOut,o,i),P=p-g,y=this.getRouteFeeRange(o),I=d?u.tradeFeePct:A.calculateBuyFee(g,p),f=Math.pow(10,l.assetOutDecimals),T=l.amountOut*m/BigInt(f),v;return g===0n?v=-100:v=A.calculateDiffToRef(T,g),{type:"Buy",amountOut:l.amountOut,amountIn:u.amountIn,spotPrice:m,tradeFee:P,tradeFeePct:I,tradeFeeRange:y,priceImpactPct:v,swaps:o,toHuman(){return{type:"Buy",amountOut:b.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:b.toDecimal(u.amountIn,u.assetInDecimals),spotPrice:b.toDecimal(m,u.assetInDecimals),tradeFee:b.toDecimal(P,u.assetInDecimals),tradeFeePct:I,tradeFeeRange:y,priceImpactPct:v,swaps:o.map(F=>F.toHuman())}}}}calculateDelta0X(t,e,n){let s=[];for(let r=e.length-1;r>=0;r--){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r==e.length-1?l=t:l=s[0];let u=a.calculateInGivenOut(o,l);s.unshift(u)}return s[0]}async toBuySwaps(t,e,n){let s=[];for(let r=e.length-1;r>=0;r--){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r==e.length-1?l=typeof t=="string"?b.toBigInt(t,o.decimalsOut):t:l=s[0].amountIn;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountIn:d,calculatedIn:m,feePct:p,errors:g}=a.validateAndBuy(o,l,u),P=this.getPoolFeeRange(u),y=a.spotPriceInGivenOut(o),I=Math.pow(10,o.decimalsOut),f=l*y/BigInt(I),T;m===0n?T=-100:T=A.calculateDiffToRef(f,m),s.unshift({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:d,calculatedIn:m,spotPrice:y,tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===i.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:b.toDecimal(l,o.decimalsOut),amountIn:b.toDecimal(d,o.decimalsIn),calculatedIn:b.toDecimal(m,o.decimalsIn),spotPrice:b.toDecimal(y,o.decimalsIn),tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}};var un=1000000000000000n;var Fe=require("polkadot-api");var H=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:s,poolId:r})=>s==="Stableswap"?{pool:(0,Fe.Enum)("Stableswap",r),asset_in:e,asset_out:n}:{pool:(0,Fe.Enum)(s),asset_in:e,asset_out:n})}};var ht=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??un})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,s,r){let[i,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:u}=a,d=l[0],m=l[l.length-1],{assetInDecimals:p}=d,{assetOutDecimals:g}=m,P=Math.abs(u),y=this.getMinimumTradeCount(o,i),I=this.getOptimalTradeCount(P),f=r?Math.round(s/r):I,T=Math.ceil(s/y),v=Math.round(s/I),F=Math.round(s/f),k=o/BigInt(f),C=await this.router.getBestSell(t,e,k),Q=o<i,qt=[];Q&&qt.push("OrderTooSmall");let Nt=C.amountOut*BigInt(f),ee=this.toBlockPeriod(F),ne=C.tradeFee*BigInt(f),dn=H.build(l),Ce={assetIn:t,assetOut:e,errors:qt,frequencyMin:T,frequencyOpt:v,frequency:F,tradeCount:f,tradeFee:ne,tradeImpactPct:C.priceImpactPct,tradePeriod:ee,tradeRoute:dn,type:"Dca"};return{...Ce,amountIn:o,amountOut:Nt,tradeAmountIn:C.amountIn,tradeAmountOut:C.amountOut,toHuman(){return{...Ce,amountIn:b.toDecimal(o,p),amountOut:b.toDecimal(Nt,g),tradeAmountIn:b.toDecimal(C.amountIn,p),tradeAmountOut:b.toDecimal(C.amountOut,g)}}}}async getMinimumOrderBudget(t){if(0===t)return this.minOrderBudget;let e=await this.router.getSpotPrice(0,t),n=10n**BigInt(12);if(e)return this.minOrderBudget*e.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(t,e){let n=e*2n/10n;if(n===0n)return 0;let s=t+n/2n;return Number(s/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:m}=u,p=Math.abs(o),g=this.getTwapTradeCount(p),P=i/BigInt(g),y=await this.router.getBestSell(l.assetIn,u.assetOut,P),I=g===1,f=i<s,T=y.priceImpactPct<-5,v=[];f||I?v.push("OrderTooSmall"):T&&v.push("OrderImpactTooBig");let F=y.amountOut*BigInt(g),k=y.tradeFee*BigInt(g),C=H.build(a),Q={assetIn:t,assetOut:e,errors:v,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:6,tradeRoute:C,type:"TwapSell"};return{...Q,amountIn:i,amountOut:F,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:k,toHuman(){return{...Q,amountIn:b.toDecimal(i,d),amountOut:b.toDecimal(F,m),tradeAmountIn:b.toDecimal(y.amountIn,d),tradeAmountOut:b.toDecimal(y.amountOut,m),tradeFee:b.toDecimal(k,m)}}}}async getTwapBuyOrder(t,e,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:m}=u,p=Math.abs(o),g=this.getTwapTradeCount(p),P=i/BigInt(g),y=await this.router.getBestBuy(l.assetIn,u.assetOut,P),I=y.amountIn*BigInt(g),f=g===1,T=I<s,v=y.priceImpactPct<-5,F=[];T||f?F.push("OrderTooSmall"):v&&F.push("OrderImpactTooBig");let k=y.tradeFee*BigInt(g),C=H.build(a),Q={assetIn:t,assetOut:e,errors:F,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:6,tradeRoute:C,type:"TwapBuy"};return{...Q,amountIn:I,amountOut:i,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:k,toHuman(){return{...Q,amountIn:b.toDecimal(I,d),amountOut:b.toDecimal(i,m),tradeAmountIn:b.toDecimal(y.amountIn,d),tradeAmountOut:b.toDecimal(y.amountOut,m),tradeFee:b.toDecimal(k,d)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,n=Math.round(e);return Math.max(n,6)}};var ke={};S(ke,{TxBuilderFactory:()=>ft});var De=require("polkadot-api");function pn(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var Pt=class extends M{evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evmClient=e??new L,this.balanceClient=new X(t),this.aaveUtils=new et(this.evmClient)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:n=>this.dryRun(n,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:oe})}async dryRun(t,e){let n=(0,De.Enum)("Signed",t),s=(0,De.Enum)("system",n),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall),a=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(a){let o=pn(a.value);throw new Error("Dry run execution error!",{cause:o})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var Jt=class extends Pt{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],r=await this.balanceClient.getBalance(this.beneficiary,s);return t>=r-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=A.getFraction(t,this.slippagePct),a=s.assetIn,o=r.assetOut,l=t+i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:H.build(n)}),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=A.getFraction(e,this.slippagePct),a=s.assetIn,o=r.assetOut,l=e-i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:H.build(n)}),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,n=e[0],s=e[e.length-1],r=A.getFraction(t,this.slippagePct),i=n.assetIn,a=s.assetOut,o=t-r,l=this.api.tx.Router.sell_all({asset_in:i,asset_out:a,min_amount_out:o,route:H.build(e)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var Zt=require("polkadot-api");var te=class extends Pt{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradePeriod:r,tradeRoute:i}=this.order,a=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,order:(0,Zt.Enum)("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=A.getFraction(r,this.slippagePct),l=r-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,order:(0,Zt.Enum)("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=A.getFraction(s,this.slippagePct),l=s+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,order:(0,Zt.Enum)("Buy",{asset_in:e,asset_out:n,amount_out:r,max_amount_in:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var ft=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e??new L}trade(t){return new Jt(this.client,this.evmClient).setTrade(t)}order(t){return new te(this.client,this.evmClient).setOrder(t)}};async function zn(c,t){let e=new ut(c),[n,s]=await Promise.all([e.getBlockTime(),e.getMinOrderBudget()]),r=t??new L,i=new gt(c).withAave().withOmnipool().withStableswap().withXyk(),a=new et(r),o=new yt(i),l=new ht(o,{blockTime:n,minBudgetInNative:s});return{api:{aave:a,router:o,scheduler:l},client:{asset:new lt(c),balance:new X(c),evm:r},ctx:{pool:i},tx:new ft(c,r),destroy:()=>{i.destroy()}}}0&&(module.exports={aave,api,big,client,const:null,createSdkContext,erc20,error,evm,fmt,h160,json,math,pool,sor,tx,xc});
package/build/index.mjs CHANGED
@@ -1 +1 @@
1
- var Ne=Object.defineProperty;var w=(c,t)=>{for(var e in t)Ne(c,e,{get:t[e],enumerable:!0})};var ie={};w(ie,{Papi:()=>F,getWs:()=>We});import{hydration as He}from"@galacticcouncil/descriptors";function ae(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var F=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(He)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");ae(n)&&console.log(t,...e)}};import{createClient as Ge}from"polkadot-api";import{withPolkadotSdkCompat as Ue}from"polkadot-api/polkadot-sdk-compat";var We=async c=>{let t=typeof c=="string"?c.split(","):c,s=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(t);return Ge(Ue(s))};var Pe={};w(Pe,{AAVE_GAS_LIMIT:()=>Gt,AAVE_LENDING_POOL_ADDRESS:()=>Bt,AAVE_POOL_ABI:()=>Nt,AAVE_POOL_DATA_PROVIDER:()=>At,AAVE_POOL_DATA_PROVIDER_ABI:()=>vt,AAVE_POOL_PROXY:()=>Ht,AAVE_ROUNDING_THRESHOLD:()=>dr,AAVE_UINT_256_MAX:()=>Ve,AaveClient:()=>lt,AaveUtils:()=>Y});var Nt=[{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 vt=[{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 Ht="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",At="0x112b087b60C1a166130d59266363C45F8aa99db0",Bt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Gt=1000000n,dr=5,Ve=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ce={};w(ce,{EvmClient:()=>E,evmMainnet:()=>Ut});import{defineChain as Xe}from"viem";var oe=["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"],le=["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"],Ut=Xe({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:oe,webSocket:le},default:{http:oe,webSocket:le}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as ue,createWalletClient as Ye,custom as je,http as Ke,webSocket as ze}from"viem";var E=class{chain;constructor(t){this.chain=t||Ut}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 ue({chain:this.chain,transport:Ke()})}getWsProvider(){return ue({chain:this.chain,transport:ze()})}getSigner(t){return Ye({account:t,chain:this.chain,transport:je(window.ethereum)})}};var lt=class{evmClient;constructor(t){this.evmClient=t??new E}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:vt,address:At,args:[Bt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.evmClient.getProvider().readContract({abi:vt,address:At,args:[Bt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.evmClient.getProvider().readContract({abi:Nt,address:Ht,args:[t],functionName:"getUserAccountData"})}};var b={};w(b,{asBigInt:()=>Je,toBigInt:()=>Qe,toDecimal:()=>$e});import V from"big.js";V.NE=-18;function $e(c,t,e=6,n){let s=V(c.toString()),r=V(10).pow(t);return s.div(r).round(e,n).toString()}function Qe(c,t){let e=V(10).pow(t),s=V(c).mul(e).toFixed(0,V.roundDown);return BigInt(s)}function Je(c){return BigInt(c.round(0,V.roundDown).toFixed(0))}var K={};w(K,{ERC20:()=>Wt});var Wt=class{static fromAssetId(t){let e=Buffer.alloc(20,0);return e[15]=1,e.writeUInt32BE(t,16),"0x"+e.toString("hex")}static toAssetId(t){let e=Buffer.from(t.replace("0x",""),"hex");return e.length!==20||!this.isAssetAddress(t)?null:e.readUInt32BE(16)}static isAssetAddress(t){let e=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(e.subarray(0,16))}};var y={};w(y,{fromPermill:()=>en,toDecimals:()=>tn,toPct:()=>Ze});var me=1e3;function Ze(c){let[t,e]=c;return t/e*100}function tn(c){let[t,e]=c;return t/e}function en(c){return[c/me,me]}var _t={};w(_t,{H160:()=>jt,isEvmAccount:()=>ge,isEvmAddress:()=>be,isSs58Address:()=>he});import{AccountId as ut}from"polkadot-api";import{toHex as de}from"@polkadot-api/utils";import{Buffer as W}from"buffer";var pe={};w(pe,{HUB_ASSET_ID:()=>Xt,HYDRATION_OMNIPOOL_ADDRESS:()=>sn,HYDRATION_PARACHAIN_ID:()=>nn,HYDRATION_SS58_PREFIX:()=>L,RUNTIME_DECIMALS:()=>D,SYSTEM_ASSET_DECIMALS:()=>Vt,SYSTEM_ASSET_ID:()=>N,TRADEABLE_DEFAULT:()=>z});var D=18,N=0,Vt=12,nn=2034,L=63,sn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Xt=1,z=15;var Yt="ETH\0";function ge(c){if(!c)return!1;try{let t=ut().enc(c),e=W.from(Yt);return W.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function be(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function he(c){try{return ut(63).enc(c),!0}catch{return!1}}var jt=class c{static toAccount=t=>{let e=W.from(t.slice(2),"hex"),n=W.from(Yt),s=Uint8Array.from(W.concat([n,e,W.alloc(8)])),r=de(s);return ut(63).dec(r)};static fromAccount=t=>{let e=ut().enc(t),n=W.from(Yt),s=e.slice(n.length,-8);return"0x"+W.from(s).toString("hex")};static fromSS58=t=>{let n=ut().enc(t).slice(0,20);return de(n)};static fromAny=t=>{if(be(t))return t;if(ge(t))return c.fromAccount(t);if(he(t))return c.fromSS58(t);throw new Error("Unknown address type")}};var X={};w(X,{findNestedKey:()=>rn,findNestedObj:()=>an,jsonFormatter:()=>on});var rn=(c,t)=>{let e=[];return JSON.stringify(c,(n,s)=>(s&&s[t]&&e.push(s),s)),e[0]},an=(c,t,e)=>{let n;return JSON.stringify(c,(s,r)=>(r&&r[t]===e&&(n=r),r)),n},on=(c,t)=>typeof t=="bigint"?t.toString():t;var O={};w(O,{calculateBuyFee:()=>mn,calculateDiffToAvg:()=>ln,calculateDiffToRef:()=>un,calculateSellFee:()=>cn,getFraction:()=>pn});import H from"big.js";function ln(c,t){let e=H(c.toString()),n=H(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function un(c,t){if(t===0n)return 0;let e=H(c.toString()),n=H(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function cn(c,t){let e=H(c.toString()),n=H(t.toString());return H(1).minus(n.div(e)).mul(100).round(2).toNumber()}function mn(c,t){let e=H(c.toString());return H(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function pn(c,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),s=BigInt(t*n);return c*s/BigInt(100*n)}var ye={};w(ye,{convertToId:()=>gn});import{Buffer as dn}from"buffer";function gn(c){let e=dn.from(c.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var{ERC20:Rt}=K,{H160:Kt}=_t,bn=1.01,hn=99999,yn=10n**27n,Pn=10n**18n,Y=class{client;constructor(t){let e=t??new E;this.client=new lt(e)}async getSummary(t){let e=Kt.fromAny(t),[n,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e)]),[i]=n,[a,o]=s,[l,u,d,m,p,g]=r,P=b.toDecimal(g,18),h=[];for(let x of a){let f=x.underlyingAsset.toLowerCase(),T=i.find(({underlyingAsset:qt})=>qt.toLowerCase()===f);if(!T)throw new Error("Missing pool reserve for "+f);let I=x.scaledATokenBalance,v=T.liquidityIndex,_=T.priceInMarketReferenceCurrency,R=I*v/yn,St=Number(o===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,Ot=T.usageAsCollateralEnabled&&x.usageAsCollateralEnabledOnUser&&x.scaledATokenBalance>0n,Lt=Rt.toAssetId(f);h.push({aTokenBalance:R,decimals:Number(T.decimals),isCollateral:Ot,priceInRef:_,reserveId:Lt,reserveAsset:f,reserveLiquidationThreshold:St})}return{healthFactor:Number(P),totalCollateral:l,totalDebt:u,reserves:h}}async hasBorrowPositions(t){let e=Kt.fromAny(t),n=await this.client.getUserAccountData(e),[s,r]=n;return r>0n}async getHealthFactor(t){let e=Kt.fromAny(t),n=await this.client.getUserAccountData(e),[s,r,i,a,o,l]=n,u=b.toDecimal(l,18);return Number(u)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(t),a=Rt.fromAssetId(e),o=i.find(h=>h.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,isCollateral:u,priceInRef:d,reserveLiquidationThreshold:m}=o,p=b.toBigInt(n,l),g=u?p*d/10n**BigInt(l):0n,P=s-g;return P<=0n?0:this.calculateHealthFactor(P,m,r)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(t),a=Rt.fromAssetId(e),o=i.find(P=>P.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:d}=o,p=b.toBigInt(n,l)*u/10n**BigInt(l),g=s+p;return g<=0n?0:this.calculateHealthFactor(g,d,r)}async getMaxWithdraw(t,e){let{totalCollateral:n,totalDebt:s,reserves:r}=await this.getSummary(t),i=Rt.fromAssetId(e),a=r.find(o=>o.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(a,n,s)}async getMaxWithdrawAll(t){let{totalCollateral:e,totalDebt:n,reserves:s}=await this.getSummary(t),r={};for(let i of s){let a=this.calculateWithdrawMax(i,e,n);i.reserveId&&(r[i.reserveId]=a)}return r}calculateHealthFactor(t,e,n){if(n===0n)return hn;let s=10n**6n,r=b.toBigInt(e,18),i=t*r*s,a=n*Pn,o=i/a;return Number(o)/1e6}calculateRequiredCollateral(t,e,n){let s=b.toBigInt(t,18),r=b.toBigInt(e,18);return(s*n+r-1n)/r}calculateWithdrawMax(t,e,n){let{aTokenBalance:s,decimals:r,priceInRef:i,reserveLiquidationThreshold:a}=t,o=this.calculateRequiredCollateral(bn,a,n),l=e-o;if(l<=0n)return{amount:0n,decimals:r};let u=l*10n**BigInt(r)/i;return{amount:s<u?s:u,decimals:r}}};var Te={};w(Te,{AssetClient:()=>$,BalanceClient:()=>q,ChainParams:()=>J});var $=class extends F{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:s}=n;return this.SUPPORTED_TYPES.includes(s.type)}).map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async mapToken(t,e,n,s){let{name:r,asset_type:i,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=n.get(t)??{};return{id:t,name:r?.asText(),symbol:l,decimals:u,icon:l,type:i.type,isSufficient:a,location:s,existentialDeposit:o}}async mapBond(t,e,n,s){let[r,i]=s,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:d}=await this.mapToken(r,e,n),m=Number(i),p=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",p.format(m)].join(" ");return{id:t,name:g,symbol:u+"b",decimals:d,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:r,maturity:m}}async mapShares(t,e,n,s){let{assets:r}=s,{name:i,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,d=await Promise.all(r.map(async g=>{let{symbol:P}=await this.mapToken(g,e,n);return[g,P]})),m=Object.fromEntries(d),p=Object.values(m);return{id:t,name:p.join(", "),symbol:a?.asText()||i?.asText(),decimals:18,icon:p.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:m}}async mapExternal(t,e,n,s){let r=await this.mapToken(t,e,new Map,s),i=n?.find(a=>a.internalId===r.id);return i?{...r,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:r}parseMetadata(t){return new Map(Array.from(t,([e,n])=>[e,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(t,e){let[n,s,r,i]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(n),o=[];for(let[l,u]of Array.from(n)){let d=s.get(l),{asset_type:m}=u,p;switch(m.type){case"Bond":let g=i.get(l);p=await this.mapBond(l,u,a,g);break;case"StableSwap":let P=r.get(l);p=await this.mapShares(l,u,a,P);break;case"External":p=await this.mapExternal(l,u,e,d);break;default:p=await this.mapToken(l,u,a,d)}o.push(p)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};import{Subject as fn,bufferCount as Tn,combineLatest as xn,debounceTime as In,distinctUntilChanged as fe,finalize as wn,map as Q,pairwise as Sn,shareReplay as On,startWith as vn}from"rxjs";var q=class extends F{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:{free:n,frozen:s}}=await e.getValue(t);return n-s}async getTokenBalance(t,e){let n=this.api.query.Tokens.Accounts,{free:s,frozen:r}=await n.getValue(t,e);return s-r}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),s=this.subscribeErc20Balance(t);return xn([e,n,s]).pipe(In(250),Q(r=>r.flat()),vn([]),Tn(2,1),Q(([r,i],a)=>{if(a===0)return i;let o=r.reduce((u,d)=>(u.set(d.id,d.amount),u),new Map);return i.filter(u=>u.amount!==o.get(u.id))}))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe(Q(n=>{let{free:s,frozen:r}=n.data;return{id:0,amount:s-r}}))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe(Q(s=>{let{free:r,frozen:i}=s;return{id:e,amount:r-i}}))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe(fe((n,s)=>!s.deltas),Q(({deltas:n})=>{let s=[];return n?.deleted.forEach(r=>{let[i,a]=r.args;s.push({id:a,amount:0n})}),n?.upserted.forEach(r=>{let[i,a]=r.args,{free:o,frozen:l}=r.value;s.push({id:a,amount:o-l})}),s}))}subscribeErc20Balance(t,e){let n=new fn,s=n.pipe(On(1)),r=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:u}=l;return u.type==="Erc20"}).map(({keyArgs:l})=>{let[u]=l;return u}),i=async()=>{let o=e||await r(),l=async()=>{let m=(await Promise.all(o.map(async p=>{let g=await this.getTokenBalanceData(t,p);return[p,g]}))).map(([p,g])=>({id:p,amount:g}));n.next(m)};await l();let u=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>u.unsubscribe()},a;return i().then(o=>a=o),s.pipe(wn(()=>a?.()),Sn(),Q(([o,l],u)=>{if(u===0)return l;let d=o.reduce((p,g)=>(p.set(g.id,g.amount),p),new Map);return l.filter(p=>p.amount!==d.get(p.id))}),fe((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let{free:n,frozen:s}=await this.api.apis.CurrenciesApi.account(e,t);return n-s}};var J=class extends F{_minOrderBudget;_blockTime;constructor(t){super(t)}async getBlockTime(){if(this._blockTime===void 0){let t=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(t)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var xe={};w(xe,{AssetNotFound:()=>zt,PoolNotFound:()=>ct,RouteNotFound:()=>Z});var zt=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},ct=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},Z=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var _e={};w(_e,{PoolContextProvider:()=>nt,PoolError:()=>j,PoolFactory:()=>et,PoolType:()=>A,aave:()=>te,lbp:()=>$t,omni:()=>Qt,stable:()=>Jt,xyk:()=>Zt});var $t={};w($t,{LbpMath:()=>M,LbpPool:()=>mt,LbpPoolClient:()=>pt});import{calculate_in_given_out as An,calculate_out_given_in as Bn,calculate_linear_weights as _n,calculate_pool_trade_fee as Rn,get_spot_price as Fn}from"@galacticcouncil/math-lbp";var M=class{static getSpotPrice(t,e,n,s,r){return Fn(t,e,n,s,r)}static calculateInGivenOut(t,e,n,s,r){return An(t,e,n,s,r)}static calculateOutGivenIn(t,e,n,s,r){return Bn(t,e,n,s,r)}static calculateLinearWeights(t,e,n,s,r){return _n(t,e,n,s,r)}static calculatePoolTradeFee(t,e,n){return Rn(t,e,n)}};var A=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r))(A||{}),j=(r=>(r.InsufficientTradingAmount="InsufficientTradingAmount",r.MaxInRatioExceeded="MaxInRatioExceeded",r.MaxOutRatioExceeded="MaxOutRatioExceeded",r.TradeNotAllowed="TradeNotAllowed",r.UnknownError="UnknownError",r))(j||{});var mt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,n,s,r,i,a){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.fee=i,this.repayFeeApply=a}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,weightIn:s.weight,weightOut:r.weight}}validateAndBuy(t,e,n){let s=this.tokens[0].id,r=[];e<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=t.balanceOut/this.maxOutRatio;if(e>i&&r.push("MaxOutRatioExceeded"),s===t.assetOut){let a=this.calculateTradeFee(e,n),o=y.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),d=t.balanceIn/this.maxInRatio;return u>d&&r.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:r}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&r.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:r}}}validateAndSell(t,e,n){let s=this.tokens[0].id,r=[];e<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=t.balanceIn/this.maxInRatio;if(e>i&&r.push("MaxInRatioExceeded"),s===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:r}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,n),l=y.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),u=a-o,d=t.balanceOut/this.maxOutRatio;return u>d&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:r}}}calculateInGivenOut(t,e){let n=M.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=M.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=M.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=M.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let n=M.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as qn}from"polkadot-api";import{map as Nn,of as ve,switchMap as Hn}from"rxjs";import{memoize1 as En}from"@thi.ng/memoize";import{combineLatest as Ie,combineLatestAll as Dn,debounceTime as kn,firstValueFrom as Cn,from as we,map as Se,mergeAll as Mn,of as Ln,switchMap as Oe}from"rxjs";var k=class extends q{override=[];mem=0;memPools=En(t=>(this.log(this.getPoolType(),"mem pools",t,"\u2705"),this.loadPools()));constructor(t){super(t)}async withOverride(t){this.override=t||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let t=we(this.getPoolsMem()).pipe(Oe(e=>this.subscribe(e)),Dn());return Cn(t)}getSubscriber(){return we(this.getPoolsMem()).pipe(Oe(t=>this.subscribe(t)),Mn())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>Ie([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe(kn(250),Se(([n,s])=>this.updatePool(n,s))))}subscribePoolBalance(t){if(t.type==="Aave")return Ln([]);let e=[this.subscribeTokensBalance(t.address)];if(this.hasSystemAsset(t)){let n=this.subscribeSystemBalance(t.address);e.push(n)}if(this.hasErc20Asset(t)){let n=t.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),s=this.subscribeErc20Balance(t.address,n);e.push(s)}return Ie(e).pipe(Se(n=>n.map(s=>Array.isArray(s)?s:[s]).flat()))}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({id:e,decimals:n,balance:s})=>{let r=this.override.find(a=>a.id===e),i=!!n||!!r?.decimals;return s>0n&&i})}updatePool=(t,e)=>{let n=t.tokens.map(s=>{let r=e.find(a=>a.id===s.id),i=this.override.find(a=>a.id===s.id);return r?{...s,balance:r.amount,decimals:s.decimals||i?.decimals}:{...s,decimals:s.decimals||i?.decimals}});return{...t,tokens:n}}};var pt=class extends k{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),s=e?.relay_parent_number||0,r=t.filter(({value:i})=>e&&this.isActivePool(i,s)).map(async({keyArgs:i,value:a})=>{let[o]=i,l=o.toString(),u=await this.getPoolDelta(l,a,s);return{address:l,type:"LBP",fee:a.fee,...u,...n}});return Promise.all(r)}async getPoolDelta(t,e,n){let{start:s,end:r,assets:i,initial_weight:a,final_weight:o,repay_target:l,fee_collector:u}=e,d=M.calculateLinearWeights(s?s.toString():"0",r?r.toString():"0",a.toString(),o.toString(),n.toString()),[m,p]=i,g=BigInt(d),P=this.MAX_FINAL_WEIGHT-BigInt(g),[h,x,f,T,I]=await Promise.all([this.isRepayFeeApplied(m,l,u.toString()),this.getBalance(t,m),this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(t,p),this.api.query.AssetRegistry.Assets.getValue(p)]);return{repayFeeApply:h,tokens:[{id:m,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:x,weight:g,type:f?.asset_type.type},{id:p,decimals:I?.decimals,existentialDeposit:I?.existential_deposit,balance:T,weight:P,type:I?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:s}=t;return n&&s?e>=n&&e<s:!1}async isRepayFeeApplied(t,e,n){if(e===0n)return!1;try{return await this.getBalance(n,t)<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(t){return{repayFee:await this.getRepayFee(),exchangeFee:t.fee}}getPoolType(){return"LBP"}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(qn.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(t.address);return n?e.watchValue("best").pipe(Hn(s=>s?this.getPoolDelta(t.address,n,s.relay_parent_number):ve(t)),Nn(s=>Object.assign({},t,s))):ve(t)}};var Qt={};w(Qt,{OmniMath:()=>S,OmniPool:()=>dt,OmniPoolClient:()=>gt});import{calculate_in_given_out as Gn,calculate_lrna_in_given_out as Un,calculate_out_given_in as Wn,calculate_out_given_lrna_in as Vn,calculate_pool_trade_fee as Xn,calculate_spot_price as Yn,calculate_lrna_spot_price as jn,calculate_shares as Kn,calculate_liquidity_out as zn,calculate_liquidity_lrna_out as $n,verify_asset_cap as Qn,calculate_liquidity_hub_in as Jn,is_sell_allowed as Zn,is_buy_allowed as ts,is_add_liquidity_allowed as es,is_remove_liquidity_allowed as ns}from"@galacticcouncil/math-omnipool";import tt from"big.js";var S=class{static calculateSpotPrice(t,e,n,s){return Yn(t,e,n,s)}static calculateLrnaSpotPrice(t,e){return jn(t,e)}static calculateInGivenOut(t,e,n,s,r,i,a,o,l){return Gn(t,e,n,s,r,i,a,o,l)}static calculateLrnaInGivenOut(t,e,n,s,r){return Un(t,e,n,s,r)}static calculateOutGivenIn(t,e,n,s,r,i,a,o,l){return Wn(t,e,n,s,r,i,a,o,l)}static calculateOutGivenLrnaIn(t,e,n,s,r){return Vn(t,e,n,s,r)}static calculatePoolTradeFee(t,e,n){return Xn(t,e,n)}static calculateShares(t,e,n,s){return Kn(t,e,n,s)}static calculateLiquidityOut(t,e,n,s,r,i,a,o){return zn(t,e,n,s,r,i,a,o)}static calculateLiquidityLRNAOut(t,e,n,s,r,i,a,o){return $n(t,e,n,s,r,i,a,o)}static calculateCapDifference(t,e,n,s){let r=tt(e),i=tt(t),a=tt(s),o=tt(n),l=tt(10).pow(18),u=o.div(l);if(r.div(a).lt(u)){let m=u.times(a).minus(r).times(i),p=r.times(tt(1).minus(u));return m.div(p).toFixed(0)}else return"0"}static verifyAssetCap(t,e,n,s){return Qn(t,e,n,s)}static calculateLimitHubIn(t,e,n,s){return Jn(t,e,n,s)}static isSellAllowed(t){return Zn(t)}static isBuyAllowed(t){return ts(t)}static isAddLiquidityAllowed(t){return es(t)}static isRemoveLiquidityAllowed(t){return ns(t)}};var dt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,n,s,r,i){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.hubAssetId=i}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:s.hubReserves,hubReservesOut:r.hubReserves,sharesIn:s.shares,sharesOut:r.shares,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,tradeableIn:s.tradeable,tradeableOut:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=this.calculateInGivenOut(t,e,n),i=s===0n?0:O.calculateDiffToRef(r,s),a=[],o=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let d=t.balanceIn/this.maxInRatio;return r>d&&a.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:i,errors:a}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=this.calculateOutGivenIn(t,e,n),i=O.calculateDiffToRef(s,r),a=[],o=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let d=t.balanceOut/this.maxOutRatio;return r>d&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let s=S.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?y.toDecimals(n.assetFee).toString():"0",n?y.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateLrnaInGivenOut(t,e,n){let s=S.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?y.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let s=S.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?y.toDecimals(n.assetFee).toString():"0",n?y.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenLrnaIn(t,e,n){let s=S.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?y.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=S.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceLrnaInGivenOut(t){let e=S.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=S.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}spotPriceOutGivenLrnaIn(t){let e=S.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};import{AccountId as ss,CompatibilityLevel as rs}from"polkadot-api";import{toHex as as}from"@polkadot-api/utils";import{distinctUntilChanged as is,map as Ae}from"rxjs";var gt=class extends k{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,s,r,i,a]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.getBalance(e,t),this.getPoolLimits()]),o=n.map(async({keyArgs:u,value:d})=>{let[m]=u,{hub_reserve:p,shares:g,tradable:P,cap:h,protocol_shares:x}=d,[f,T]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,m)]);return{id:m,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:T,cap:h,hubReserves:p,protocolShares:x,shares:g,tradeable:P,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:i,tradeable:s,type:r?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...a}]}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=as(e);return ss(63).dec(n)}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(t,e){let[n,s,r]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),i=n.min_fee+s.min_fee,a=n.max_fee+s.max_fee;if(r){let{asset_fee:o,protocol_fee:l}=r;return{assetFee:y.fromPermill(o),protocolFee:y.fromPermill(l),min:y.fromPermill(i),max:y.fromPermill(a)}}else return{assetFee:y.fromPermill(n.min_fee),protocolFee:y.fromPermill(s.min_fee),min:y.fromPermill(i),max:y.fromPermill(a)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(rs.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(is((n,s)=>!s.deltas),Ae(({entries:n})=>n.map(s=>{let[r]=s.args,{hub_reserve:i,shares:a,tradable:o,cap:l,protocol_shares:u}=s.value,d=t.tokens.findIndex(p=>p.id===r);return{...t.tokens[d],cap:l,hubReserves:i,protocolShares:u,shares:a,tradeable:o}})),Ae(n=>{let s=t.tokens.find(r=>r.id===1);return{...t,tokens:[...n,s]}}))}};var Jt={};w(Jt,{StableMath:()=>B,StableSwap:()=>bt,StableSwapClient:()=>ht});import{calculate_in_given_out as os,calculate_out_given_in as ls,calculate_amplification as us,calculate_add_one_asset as cs,calculate_liquidity_out_one_asset as ms,calculate_pool_trade_fee as ps,calculate_shares as ds,calculate_shares_for_amount as gs,calculate_spot_price_with_fee as bs,pool_account_name as hs,recalculate_peg as ys}from"@galacticcouncil/math-stableswap";var B=class{static getPoolAddress(t){return hs(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,s,r){return us(t,e,n,s,r)}static calculateInGivenOut(t,e,n,s,r,i,a){return os(t,e,n,s,r,i,a)}static calculateAddOneAsset(t,e,n,s,r,i,a){return cs(t,e,n,s,r,i,a)}static calculateSharesForAmount(t,e,n,s,r,i,a){return gs(t,e,n,s,r,i,a)}static calculateOutGivenIn(t,e,n,s,r,i,a){return ls(t,e,n,s,r,i,a)}static calculateLiquidityOutOneAsset(t,e,n,s,r,i,a){return ms(t,e,n,s,r,i,a)}static calculateShares(t,e,n,s,r,i){return ds(t,e,n,s,r,i)}static calculateSpotPriceWithFee(t,e,n,s,r,i,a,o){return bs(t,e,n,s,r,i,a,o)}static calculatePoolTradeFee(t,e,n){return ps(t,e,n)}static recalculatePegs(t,e,n,s,r){return ys(t,e,n,s,r)}};var bt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.id,t.fee,t.totalIssuance)}constructor(t,e,n,s,r,i,a,o,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.amplification=i,this.id=a,this.fee=o,this.totalIssuance=l}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=this.calculateInGivenOut(t,e,n),i=y.toPct(n.fee),a=[],o=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:i,errors:a}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=this.calculateOutGivenIn(t,e,n),i=y.toPct(n.fee),a=[],o=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateIn(t,e,n){let s=B.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateAddOneAsset(t,e,n){let s=B.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateSharesForAmount(t,e,n){let s=B.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateInGivenOut(t,e,n){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,n):t.assetIn==this.id?this.calculateSharesForAmount(t,e,n):this.calculateIn(t,e,n)}spotPriceInGivenOut(t){let e=B.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetOut==this.id)return BigInt(e);if(t.assetIn==this.id){let s=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let s=B.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateWithdrawOneAsset(t,e,n){let s=B.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateShares(t,e,n){let s=B.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(t,e,n){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,n):t.assetOut==this.id?this.calculateShares(t,e,n):this.calculateOut(t,e,n)}spotPriceOutGivenIn(t){let e=B.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetIn==this.id)return BigInt(e);if(t.assetOut==this.id){let s=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let[n,s]=e.fee,r=B.calculatePoolTradeFee(t.toString(),n,s);return BigInt(r)}getPegs(){let t=B.defaultPegs(this.tokens.length-1);return JSON.stringify(t)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:n,decimals:s})=>({asset_id:e,amount:n,decimals:s}));return JSON.stringify(t,X.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],X.jsonFormatter)}};import{AccountId as Ps,CompatibilityLevel as fs}from"polkadot-api";import{toHex as Ts}from"@polkadot-api/utils";import{blake2b as xs}from"@noble/hashes/blake2b";import{map as Is,of as ws,switchMap as Ss}from"rxjs";var Os=340282366920938463463374607431768211455n,ht=class extends k{poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),s=t.map(async({keyArgs:r,value:i})=>{let[a]=r,o=this.getPoolAddress(a),[l,u]=await Promise.all([this.getPoolDelta(a,i,e),this.getPoolTokens(a,i)]);return this.poolsData.set(o,i),{address:o,id:a,type:"Stableswap",fee:y.fromPermill(i.fee),tokens:u,...l,...n}});return Promise.all(s)}async getPoolDelta(t,e,n){let{initial_amplification:s,final_amplification:r,initial_block:i,final_block:a}=e,o=B.calculateAmplification(s.toString(),r.toString(),i.toString(),a.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(t);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),s=e.assets.map(async a=>{let[o,l,u]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,a),this.api.query.AssetRegistry.Assets.getValue(a),this.getBalance(n,a)]);return{id:a,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:u,tradeable:o,type:l?.asset_type.type}}),r=await Promise.all(s),i=await this.api.query.AssetRegistry.Assets.getValue(t);return r.push({id:t,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:Os,tradeable:15,type:i?.asset_type.type}),r}getPoolAddress(t){let e=B.getPoolAddress(t),n=xs(e,{dkLen:32}),s=Ts(n);return Ps(63).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(t){return{fee:t.fee}}getPoolType(){return"Stableswap"}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(fs.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.System.Number,n=this.poolsData.get(t.address);return!n||!t.id?ws(t):e.watchValue("best").pipe(Ss(s=>this.getPoolDelta(t.id,n,s)),Is(s=>Object.assign({},t,s)))}};var Zt={};w(Zt,{XykMath:()=>G,XykPool:()=>yt,XykPoolClient:()=>Pt});import{calculate_in_given_out as vs,calculate_out_given_in as As,calculate_pool_trade_fee as Bs,get_spot_price as _s,calculate_liquidity_in as Rs,calculate_shares as Fs,calculate_spot_price as Es,calculate_spot_price_with_fee as Ds,calculate_liquidity_out_asset_a as ks,calculate_liquidity_out_asset_b as Cs}from"@galacticcouncil/math-xyk";var G=class{static getSpotPrice(t,e,n){return _s(t,e,n)}static calculateInGivenOut(t,e,n){return vs(t,e,n)}static calculateOutGivenIn(t,e,n){return As(t,e,n)}static calculatePoolTradeFee(t,e,n){return Bs(t,e,n)}static calculateLiquidityIn(t,e,n){return Rs(t,e,n)}static calculateSpotPrice(t,e){return Es(t,e)}static calculateSpotPriceWithFee(t,e,n,s){return Ds(t,e,n,s)}static calculateShares(t,e,n){return Fs(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,s){return ks(t,e,n,s)}static calculateLiquidityOutAssetB(t,e,n,s){return Cs(t,e,n,s)}};var yt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,r){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=this.calculateTradeFee(s,n),i=y.toPct(n.exchangeFee),a=s+r,o=[];(e<this.minTradingLimit||s<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:i,errors:o}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=this.calculateTradeFee(s,n),i=y.toPct(n.exchangeFee),a=s-r,o=[];(e<this.minTradingLimit||s<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:i,errors:o}}calculateInGivenOut(t,e){let n=G.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=G.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=G.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=G.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=G.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as Ms}from"polkadot-api";import{of as Ls}from"rxjs";var Pt=class extends k{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,n]=await Promise.all([t.getEntries(),this.getPoolLimits()]),s=e.map(async({keyArgs:r,value:i})=>{let[a]=r,[o,l]=i,[u,d,m,p]=await Promise.all([this.getBalance(a,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(a,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:a,type:"XYK",tokens:[{id:o,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:u,type:d?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:m,type:p?.asset_type.type}],...n}});return Promise.all(s)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(Ms.BackwardsCompatible,e)}subscribePoolChange(t){return Ls(t)}};var te={};w(te,{AavePool:()=>ft,AavePoolClient:()=>Tt});var ft=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,r){this.type="Aave",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=[];return e>t.balanceOut&&r.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:r}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=[];return s>t.balanceOut&&r.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:r}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){let e=Math.pow(10,t.decimalsOut);return BigInt(e)}spotPriceOutGivenIn(t){let e=Math.pow(10,t.decimalsIn);return BigInt(e)}calculateTradeFee(t,e){return 0n}};import{AccountId as qs}from"polkadot-api";import{toHex as Ns}from"@polkadot-api/utils";import{map as Hs,merge as Gs,switchMap as Us}from"rxjs";import{decodeEventLog as Ws}from"viem";var Be=[{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:Vs}=K,Xs=["Supply","Withdraw","Repay","Borrow"],Tt=class extends k{async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:s,liqudity_in:r,liqudity_out:i})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(n,s),type:"Aave",tokens:[{id:n,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:r,location:o,type:a?.asset_type.type},{id:s,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:i,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:s,liqudity_out:r}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id);return t.tokens.map(i=>{let a=i.id===e.id?s:r;return{...i,balance:a}})}getPoolId(t,e){let n=t+"/"+e,s=new TextEncoder().encode(n.padEnd(32,"\0")),r=Ns(s);return qs(63).dec(r)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(t,e){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(t){let[e,n]=t.tokens,s=this.getReserveH160Id(e),r=this.api.event.Router.Executed.watch(({asset_in:a,asset_out:o})=>a===n.id||o===n.id),i=this.api.event.EVM.Log.watch(({log:a})=>{let{topics:o,data:l}=a,u=o.map(g=>g.asHex()),d=l.asHex(),{eventName:m,args:p}=Ws({abi:Be,topics:u,data:d});return Xs.includes(m)&&p.reserve.toLowerCase()===s.toLowerCase()});return Gs([r,i]).pipe(Us(()=>this.getPoolDelta(t)),Hs(a=>({...t,tokens:[...a]})))}getReserveH160Id(t){return t.type==="Erc20"?X.findNestedKey(t.location,"AccountKey20").AccountKey20.key:Vs.fromAssetId(t.id)}};var et=class{static get(t){switch(t.type){case"Aave":return ft.fromPool(t);case"XYK":return yt.fromPool(t);case"Omnipool":return dt.fromPool(t);case"LBP":return mt.fromPool(t);case"Stableswap":return bt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{Subject as Ys,Subscription as xt,takeUntil as js}from"rxjs";var nt=class extends F{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=xt.EMPTY;omniSub=xt.EMPTY;stableSub=xt.EMPTY;xykSub=xt.EMPTY;aaveSub=xt.EMPTY;isReady=!1;isDestroyed=new Ys;constructor(t){super(t),this.lbpClient=new pt(t),this.omniClient=new gt(t),this.stableClient=new ht(t),this.xykClient=new Pt(t),this.aaveClient=new Tt(t),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(t){return t.getSubscriber().pipe(js(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)})}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(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let n=this.clients.find(s=>s.getPoolType()===t.type);if(n)return n.getPoolFees(t,e);throw new ct(t.type)}};var ke={};w(ke,{Router:()=>st,TradeOrderError:()=>ne,TradeOrderType:()=>Dt,TradeRouteBuilder:()=>C,TradeRouter:()=>rt,TradeScheduler:()=>at,TradeType:()=>Et});var Ft=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Ks=5,It=class{isNotVisited(t,e){let n=!0;return e.forEach(s=>{(s[0]===t[0]||s[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let s=[],r=new Ft,i=[];for(i.push([e,""]),r.enqueue(i);r.size()>0;){let a=r.dequeue();if(a==null||a.length>Ks)return s;let o=a[a.length-1];(n===null||o[0]===n)&&s.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let d=[...a];d.push(u),r.enqueue(d)}})}return s}buildAndPopulateGraph(t,e){let n=new Map;for(let s of t)n.set(parseInt(s),[]);for(let[s,r,i]of e)n.get(r)?.push([i,s]);return n}};function ee(c){let t={};for(let e of c){let n=e.tokens.length;for(let s=0;s<n;s++){t[e.tokens[s].id]||(t[e.tokens[s].id]=[]);for(let r=0;r<n;r++){if(s==r)continue;let i=[e.address,e.tokens[s].id,e.tokens[r].id];t[e.tokens[s].id].push(i)}}}return t}var wt=class{getProposals(t,e,n){let s=ee(n),r=Object.keys(s),i=r.map(u=>s[u]).flat(),a=new It,o=a.buildAndPopulateGraph(r,i),l=a.findPaths(o,t,e);return this.parsePaths(l)}parsePaths(t){let e=[];for(let n of t){let s=[];for(let r=0;r<n.length;r++){let i=n[r],a=n[r+1];if(a==null)break;s.push(this.toEdge(i,a))}e.push(s)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var st=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(t,e){this.ctx=t,this.routeSuggester=new wt,this.routerOptions={...this.defaultRouterOptions,...e}}async getPools(){let t=await this.ctx.getPools(),e=this.routerOptions.useOnly;return e.length===0?t:t.filter(n=>e.includes(n.type))}async getRoutes(t,e){let n=await this.getPools();return this.validateInput(t,e,n),this.getPaths(t,e,n)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}validateInput(t,e,n){if(n.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let s=this.getAssets(n);if(!s.has(t))throw new Error(t+" is not supported asset");if(!s.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(s=>s.id)).flat().sort((n,s)=>n>s?1:-1);return new Set(e)}getPaths(t,e,n){let s=this.toPoolsMap(n);return this.routeSuggester.getProposals(t,e,n).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,s)=>n&&s)}validEdge([t,e,n],s){return s.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,et.get(e)]))}toHops(t,e){return t.map(([n,s,r])=>{let i=e.get(n);return{poolAddress:n,poolId:i?.id,pool:i?.type,assetIn:s,assetOut:r}})}};var Et=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Et||{}),Dt=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Dt||{}),ne=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(ne||{});var rt=class extends st{isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,s)=>{let r=n[n.length-1].amountOut,i=s[s.length-1].amountOut;return r>i?-1:1});return e.find(n=>n.every(s=>s.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(n=>n.tradeFeeRange).length>0){let n=t.map(r=>r.tradeFeeRange?.[0]??r.tradeFeePct).reduce((r,i)=>r+i),s=t.map(r=>r.tradeFeeRange?.[1]??r.tradeFeePct).reduce((r,i)=>r+i);return[n,s]}}getPoolFeeRange(t){let e=t.min?y.toPct(t.min):void 0,n=t.max?y.toPct(t.max):void 0;if(e&&n)return[e,n]}async getBestSell(t,e,n){return this.getSell(t,e,n)}async getSellSpot(t){let e=t[t.length-1];if(t.length===1)return e.spotPrice;let n=t.map(a=>a.assetOutDecimals).reduce((a,o)=>a+o),s=t.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-e.assetOutDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getSell(t,e,n,s){let r=await super.getPools(),i=super.validateInput(t,e,r),a=super.getPaths(t,e,r);if(a.length===0)throw new Z(t,e);let o;if(s)o=await this.toSellSwaps(n,s,i);else{let v=await Promise.all(a.map(_=>this.toSellSwaps(n,_,i)));o=this.findBestSellRoute(v)}let l=o[0],u=o[o.length-1],d=this.isDirectTrade(o),m=await this.getSellSpot(o),p=u.amountOut,g=d?u.calculatedOut:this.calculateDelta0Y(l.amountIn,o,i),P=g-p,h=this.getRouteFeeRange(o),x=d?u.tradeFeePct:O.calculateSellFee(g,p),f=Math.pow(10,l.assetInDecimals),T=l.amountIn*m/BigInt(f),I=O.calculateDiffToRef(g,T);return{type:"Sell",amountIn:l.amountIn,amountOut:u.amountOut,spotPrice:m,tradeFee:P,tradeFeePct:x,tradeFeeRange:h,priceImpactPct:I,swaps:o,toHuman(){return{type:"Sell",amountIn:b.toDecimal(l.amountIn,l.assetInDecimals),amountOut:b.toDecimal(u.amountOut,u.assetOutDecimals),spotPrice:b.toDecimal(m,u.assetOutDecimals),tradeFee:b.toDecimal(P,u.assetOutDecimals),tradeFeePct:x,tradeFeeRange:h,priceImpactPct:I,swaps:o.map(v=>v.toHuman())}}}}calculateDelta0Y(t,e,n){let s=[];for(let r=0;r<e.length;r++){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r>0?l=s[r-1]:l=t;let u=a.calculateOutGivenIn(o,l);s.push(u)}return s[s.length-1]}async toSellSwaps(t,e,n){let s=[];for(let r=0;r<e.length;r++){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r>0?l=s[r-1].amountOut:l=typeof t=="string"?b.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountOut:d,calculatedOut:m,feePct:p,errors:g}=a.validateAndSell(o,l,u),P=this.getPoolFeeRange(u),h=a.spotPriceOutGivenIn(o),x=Math.pow(10,o.decimalsIn),f=l*h/BigInt(x),T=O.calculateDiffToRef(m,f);s.push({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:d,calculatedOut:m,spotPrice:h,tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===i.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:b.toDecimal(l,o.decimalsIn),amountOut:b.toDecimal(d,o.decimalsOut),calculatedOut:b.toDecimal(m,o.decimalsOut),spotPrice:b.toDecimal(h,o.decimalsOut),tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}async getMostLiquidRoute(t,e){let n=await super.getPools(),s=super.validateInput(t,e,n),r=super.getPaths(t,e,n),o=n.filter(m=>m.tokens.some(p=>p.id===t&&p.id!==m.id)).map(m=>m.type==="Aave"?m.tokens:m.tokens.filter(p=>p.id===t)).map(m=>m.map(p=>p.balance).reduce((p,g)=>p+g)).sort((m,p)=>p<m?-1:1)[0],l=O.getFraction(o,.1),u=await Promise.all(r.map(m=>this.toSellSwaps(l,m,s)));return this.findBestSellRoute(u).map(m=>({poolAddress:m.poolAddress,poolId:m?.poolId,pool:m.pool,assetIn:m.assetIn,assetOut:m.assetOut}))}async getSpotPrice(t,e){let n=await super.getPools(),s=super.validateInput(t,e,n),r=await this.getMostLiquidRoute(t,e),i=await this.toSellSwaps("1",r,s),a=await this.getSellSpot(i),o=i[i.length-1].assetOutDecimals;return{amount:a,decimals:o}}findBestBuyRoute(t){let e=t.sort((n,s)=>{let r=n[0].amountIn,i=s[0].amountIn;return r>i?1:-1});return e.find(n=>n.every(s=>s.errors.length==0))||e[0]}async getBestBuy(t,e,n){return this.getBuy(t,e,n)}async getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let n=t.map(a=>a.assetInDecimals).reduce((a,o)=>a+o),s=t.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-e.assetInDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getBuy(t,e,n,s){let r=await super.getPools(),i=super.validateInput(t,e,r),a=super.getPaths(t,e,r);if(a.length===0)throw new Z(t,e);let o;if(s)o=await this.toBuySwaps(n,s,i);else{let v=await Promise.all(a.map(_=>this.toBuySwaps(n,_,i)));o=this.findBestBuyRoute(v)}let l=o[o.length-1],u=o[0],d=this.isDirectTrade(o),m=await this.getBuySpot(o),p=u.amountIn,g=d?u.calculatedIn:this.calculateDelta0X(l.amountOut,o,i),P=p-g,h=this.getRouteFeeRange(o),x=d?u.tradeFeePct:O.calculateBuyFee(g,p),f=Math.pow(10,l.assetOutDecimals),T=l.amountOut*m/BigInt(f),I;return g===0n?I=-100:I=O.calculateDiffToRef(T,g),{type:"Buy",amountOut:l.amountOut,amountIn:u.amountIn,spotPrice:m,tradeFee:P,tradeFeePct:x,tradeFeeRange:h,priceImpactPct:I,swaps:o,toHuman(){return{type:"Buy",amountOut:b.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:b.toDecimal(u.amountIn,u.assetInDecimals),spotPrice:b.toDecimal(m,u.assetInDecimals),tradeFee:b.toDecimal(P,u.assetInDecimals),tradeFeePct:x,tradeFeeRange:h,priceImpactPct:I,swaps:o.map(v=>v.toHuman())}}}}calculateDelta0X(t,e,n){let s=[];for(let r=e.length-1;r>=0;r--){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r==e.length-1?l=t:l=s[0];let u=a.calculateInGivenOut(o,l);s.unshift(u)}return s[0]}async toBuySwaps(t,e,n){let s=[];for(let r=e.length-1;r>=0;r--){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r==e.length-1?l=typeof t=="string"?b.toBigInt(t,o.decimalsOut):t:l=s[0].amountIn;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountIn:d,calculatedIn:m,feePct:p,errors:g}=a.validateAndBuy(o,l,u),P=this.getPoolFeeRange(u),h=a.spotPriceInGivenOut(o),x=Math.pow(10,o.decimalsOut),f=l*h/BigInt(x),T;m===0n?T=-100:T=O.calculateDiffToRef(f,m),s.unshift({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:d,calculatedIn:m,spotPrice:h,tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===i.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:b.toDecimal(l,o.decimalsOut),amountIn:b.toDecimal(d,o.decimalsIn),calculatedIn:b.toDecimal(m,o.decimalsIn),spotPrice:b.toDecimal(h,o.decimalsIn),tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}};var Re=1000000000000000n;import{Enum as Fe}from"polkadot-api";var C=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:s,poolId:r})=>s==="Stableswap"?{pool:Fe("Stableswap",r),asset_in:e,asset_out:n}:{pool:Fe(s),asset_in:e,asset_out:n})}};var at=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Re})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,s,r){let[i,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:u}=a,d=l[0],m=l[l.length-1],{assetInDecimals:p}=d,{assetOutDecimals:g}=m,P=Math.abs(u),h=this.getMinimumTradeCount(o,i),x=this.getOptimalTradeCount(P),f=r?Math.round(s/r):x,T=Math.ceil(s/h),I=Math.round(s/x),v=Math.round(s/f),_=o/BigInt(f),R=await this.router.getBestSell(t,e,_),U=o<i,St=[];U&&St.push("OrderTooSmall");let Ot=R.amountOut*BigInt(f),Lt=this.toBlockPeriod(v),qt=R.tradeFee*BigInt(f),qe=C.build(l),re={assetIn:t,assetOut:e,errors:St,frequencyMin:T,frequencyOpt:I,frequency:v,tradeCount:f,tradeFee:qt,tradeImpactPct:R.priceImpactPct,tradePeriod:Lt,tradeRoute:qe,type:"Dca"};return{...re,amountIn:o,amountOut:Ot,tradeAmountIn:R.amountIn,tradeAmountOut:R.amountOut,toHuman(){return{...re,amountIn:b.toDecimal(o,p),amountOut:b.toDecimal(Ot,g),tradeAmountIn:b.toDecimal(R.amountIn,p),tradeAmountOut:b.toDecimal(R.amountOut,g)}}}}async getMinimumOrderBudget(t){if(0===t)return this.minOrderBudget;let e=await this.router.getSpotPrice(0,t),n=10n**BigInt(12);if(e)return this.minOrderBudget*e.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(t,e){let n=e*2n/10n;if(n===0n)return 0;let s=t+n/2n;return Number(s/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:m}=u,p=Math.abs(o),g=this.getTwapTradeCount(p),P=i/BigInt(g),h=await this.router.getBestSell(l.assetIn,u.assetOut,P),x=g===1,f=i<s,T=h.priceImpactPct<-5,I=[];f||x?I.push("OrderTooSmall"):T&&I.push("OrderImpactTooBig");let v=h.amountOut*BigInt(g),_=h.tradeFee*BigInt(g),R=C.build(a),U={assetIn:t,assetOut:e,errors:I,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapSell"};return{...U,amountIn:i,amountOut:v,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:_,toHuman(){return{...U,amountIn:b.toDecimal(i,d),amountOut:b.toDecimal(v,m),tradeAmountIn:b.toDecimal(h.amountIn,d),tradeAmountOut:b.toDecimal(h.amountOut,m),tradeFee:b.toDecimal(_,m)}}}}async getTwapBuyOrder(t,e,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:m}=u,p=Math.abs(o),g=this.getTwapTradeCount(p),P=i/BigInt(g),h=await this.router.getBestBuy(l.assetIn,u.assetOut,P),x=h.amountIn*BigInt(g),f=g===1,T=x<s,I=h.priceImpactPct<-5,v=[];T||f?v.push("OrderTooSmall"):I&&v.push("OrderImpactTooBig");let _=h.tradeFee*BigInt(g),R=C.build(a),U={assetIn:t,assetOut:e,errors:v,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapBuy"};return{...U,amountIn:x,amountOut:i,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:_,toHuman(){return{...U,amountIn:b.toDecimal(x,d),amountOut:b.toDecimal(i,m),tradeAmountIn:b.toDecimal(h.amountIn,d),tradeAmountOut:b.toDecimal(h.amountOut,m),tradeFee:b.toDecimal(_,d)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,n=Math.round(e);return Math.max(n,6)}};var Le={};w(Le,{TxBuilderFactory:()=>ot});import{Enum as Me}from"polkadot-api";function Ce(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var it=class extends F{evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evmClient=e??new E,this.balanceClient=new q(t),this.aaveUtils=new Y(this.evmClient)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:n=>this.dryRun(n,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:Gt})}async dryRun(t,e){let n=Me("Signed",t),s=Me("system",n),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall),a=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(a){let o=Ce(a.value);throw new Error("Dry run execution error!",{cause:o})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var Ct=class extends it{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],r=await this.balanceClient.getBalance(this.beneficiary,s);return t>=r-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=O.getFraction(t,this.slippagePct),a=s.assetIn,o=r.assetOut,l=t+i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:C.build(n)}),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=O.getFraction(e,this.slippagePct),a=s.assetIn,o=r.assetOut,l=e-i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:C.build(n)}),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,n=e[0],s=e[e.length-1],r=O.getFraction(t,this.slippagePct),i=n.assetIn,a=s.assetOut,o=t-r,l=this.api.tx.Router.sell_all({asset_in:i,asset_out:a,min_amount_out:o,route:C.build(e)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as se}from"polkadot-api";var Mt=class extends it{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradePeriod:r,tradeRoute:i}=this.order,a=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,order:se("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=O.getFraction(r,this.slippagePct),l=r-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,order:se("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=O.getFraction(s,this.slippagePct),l=s+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,order:se("Buy",{asset_in:e,asset_out:n,amount_out:r,max_amount_in:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var ot=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e??new E}trade(t){return new Ct(this.client,this.evmClient).setTrade(t)}order(t){return new Mt(this.client,this.evmClient).setOrder(t)}};async function ic(c,t){let e=new J(c),[n,s]=await Promise.all([e.getBlockTime(),e.getMinOrderBudget()]),r=t??new E,i=new nt(c).withAave().withOmnipool().withStableswap().withXyk(),a=new Y(r),o=new rt(i),l=new at(o,{blockTime:n,minBudgetInNative:s});return{api:{aave:a,router:o,scheduler:l},client:{asset:new $(c),balance:new q(c),evm:r},ctx:{pool:i},tx:new ot(c,r),destroy:()=>{i.destroy()}}}export{Pe as aave,ie as api,b as big,Te as client,pe as const,ic as createSdkContext,K as erc20,xe as error,ce as evm,y as fmt,_t as h160,X as json,O as math,_e as pool,ke as sor,Le as tx,ye as xc};
1
+ var Ne=Object.defineProperty;var w=(c,t)=>{for(var e in t)Ne(c,e,{get:t[e],enumerable:!0})};var ie={};w(ie,{Papi:()=>F,getWs:()=>We});import{hydration as He}from"@galacticcouncil/descriptors";function ae(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var F=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(He)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");ae(n)&&console.log(t,...e)}};import{createClient as Ge}from"polkadot-api";import{withPolkadotSdkCompat as Ue}from"polkadot-api/polkadot-sdk-compat";var We=async c=>{let t=typeof c=="string"?c.split(","):c,s=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(t);return Ge(Ue(s))};var Pe={};w(Pe,{AAVE_GAS_LIMIT:()=>Gt,AAVE_LENDING_POOL_ADDRESS:()=>Bt,AAVE_POOL_ABI:()=>Nt,AAVE_POOL_DATA_PROVIDER:()=>At,AAVE_POOL_DATA_PROVIDER_ABI:()=>vt,AAVE_POOL_PROXY:()=>Ht,AAVE_ROUNDING_THRESHOLD:()=>pr,AAVE_UINT_256_MAX:()=>Ve,AaveClient:()=>lt,AaveUtils:()=>Y});var Nt=[{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 vt=[{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 Ht="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",At="0x112b087b60C1a166130d59266363C45F8aa99db0",Bt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Gt=1000000n,pr=5,Ve=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ce={};w(ce,{EvmClient:()=>E,evmMainnet:()=>Ut});import{defineChain as Xe}from"viem";var oe=["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"],le=["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"],Ut=Xe({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:oe,webSocket:le},default:{http:oe,webSocket:le}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as ue,createWalletClient as Ye,custom as je,http as Ke,webSocket as ze}from"viem";var E=class{chain;constructor(t){this.chain=t||Ut}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 ue({chain:this.chain,transport:Ke()})}getWsProvider(){return ue({chain:this.chain,transport:ze()})}getSigner(t){return Ye({account:t,chain:this.chain,transport:je(window.ethereum)})}};var lt=class{evmClient;constructor(t){this.evmClient=t??new E}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:vt,address:At,args:[Bt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.evmClient.getProvider().readContract({abi:vt,address:At,args:[Bt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.evmClient.getProvider().readContract({abi:Nt,address:Ht,args:[t],functionName:"getUserAccountData"})}};var b={};w(b,{asBigInt:()=>Je,toBigInt:()=>Qe,toDecimal:()=>$e});import V from"big.js";V.NE=-18;function $e(c,t,e=6,n){let s=V(c.toString()),r=V(10).pow(t);return s.div(r).round(e,n).toString()}function Qe(c,t){let e=V(10).pow(t),s=V(c).mul(e).toFixed(0,V.roundDown);return BigInt(s)}function Je(c){return BigInt(c.round(0,V.roundDown).toFixed(0))}var K={};w(K,{ERC20:()=>Wt});var Wt=class{static fromAssetId(t){let e=Buffer.alloc(20,0);return e[15]=1,e.writeUInt32BE(t,16),"0x"+e.toString("hex")}static toAssetId(t){let e=Buffer.from(t.replace("0x",""),"hex");return e.length!==20||!this.isAssetAddress(t)?null:e.readUInt32BE(16)}static isAssetAddress(t){let e=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(e.subarray(0,16))}};var y={};w(y,{fromPermill:()=>en,toDecimals:()=>tn,toPct:()=>Ze});var pe=1e3;function Ze(c){let[t,e]=c;return t/e*100}function tn(c){let[t,e]=c;return t/e}function en(c){return[c/pe,pe]}var _t={};w(_t,{H160:()=>jt,isEvmAccount:()=>ge,isEvmAddress:()=>be,isSs58Address:()=>he});import{AccountId as ut}from"polkadot-api";import{toHex as de}from"@polkadot-api/utils";import{Buffer as W}from"buffer";var me={};w(me,{HUB_ASSET_ID:()=>Xt,HYDRATION_OMNIPOOL_ADDRESS:()=>sn,HYDRATION_PARACHAIN_ID:()=>nn,HYDRATION_SS58_PREFIX:()=>L,RUNTIME_DECIMALS:()=>D,SYSTEM_ASSET_DECIMALS:()=>Vt,SYSTEM_ASSET_ID:()=>N,TRADEABLE_DEFAULT:()=>z});var D=18,N=0,Vt=12,nn=2034,L=63,sn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Xt=1,z=15;var Yt="ETH\0";function ge(c){if(!c)return!1;try{let t=ut().enc(c),e=W.from(Yt);return W.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function be(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function he(c){try{return ut(63).enc(c),!0}catch{return!1}}var jt=class c{static toAccount=t=>{let e=W.from(t.slice(2),"hex"),n=W.from(Yt),s=Uint8Array.from(W.concat([n,e,W.alloc(8)])),r=de(s);return ut(63).dec(r)};static fromAccount=t=>{let e=ut().enc(t),n=W.from(Yt),s=e.slice(n.length,-8);return"0x"+W.from(s).toString("hex")};static fromSS58=t=>{let n=ut().enc(t).slice(0,20);return de(n)};static fromAny=t=>{if(be(t))return t;if(ge(t))return c.fromAccount(t);if(he(t))return c.fromSS58(t);throw new Error("Unknown address type")}};var X={};w(X,{findNestedKey:()=>rn,findNestedObj:()=>an,jsonFormatter:()=>on});var rn=(c,t)=>{let e=[];return JSON.stringify(c,(n,s)=>(s&&s[t]&&e.push(s),s)),e[0]},an=(c,t,e)=>{let n;return JSON.stringify(c,(s,r)=>(r&&r[t]===e&&(n=r),r)),n},on=(c,t)=>typeof t=="bigint"?t.toString():t;var O={};w(O,{calculateBuyFee:()=>pn,calculateDiffToAvg:()=>ln,calculateDiffToRef:()=>un,calculateSellFee:()=>cn,getFraction:()=>mn});import H from"big.js";function ln(c,t){let e=H(c.toString()),n=H(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function un(c,t){if(t===0n)return 0;let e=H(c.toString()),n=H(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function cn(c,t){let e=H(c.toString()),n=H(t.toString());return H(1).minus(n.div(e)).mul(100).round(2).toNumber()}function pn(c,t){let e=H(c.toString());return H(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function mn(c,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),s=BigInt(t*n);return c*s/BigInt(100*n)}var ye={};w(ye,{convertToId:()=>gn});import{Buffer as dn}from"buffer";function gn(c){let e=dn.from(c.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var{ERC20:Rt}=K,{H160:Kt}=_t,bn=1.01,hn=99999,yn=10n**27n,Pn=10n**18n,Y=class{client;constructor(t){let e=t??new E;this.client=new lt(e)}async getSummary(t){let e=Kt.fromAny(t),[n,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e)]),[i]=n,[a,o]=s,[l,u,d,p,m,g]=r,P=b.toDecimal(g,18),h=[];for(let x of a){let f=x.underlyingAsset.toLowerCase(),T=i.find(({underlyingAsset:qt})=>qt.toLowerCase()===f);if(!T)throw new Error("Missing pool reserve for "+f);let I=x.scaledATokenBalance,v=T.liquidityIndex,_=T.priceInMarketReferenceCurrency,R=I*v/yn,St=Number(o===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,Ot=T.usageAsCollateralEnabled&&x.usageAsCollateralEnabledOnUser&&x.scaledATokenBalance>0n,Lt=Rt.toAssetId(f);h.push({aTokenBalance:R,decimals:Number(T.decimals),isCollateral:Ot,priceInRef:_,reserveId:Lt,reserveAsset:f,reserveLiquidationThreshold:St})}return{healthFactor:Number(P),totalCollateral:l,totalDebt:u,reserves:h}}async hasBorrowPositions(t){let e=Kt.fromAny(t),n=await this.client.getUserAccountData(e),[s,r]=n;return r>0n}async getHealthFactor(t){let e=Kt.fromAny(t),n=await this.client.getUserAccountData(e),[s,r,i,a,o,l]=n,u=b.toDecimal(l,18);return Number(u)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(t),a=Rt.fromAssetId(e),o=i.find(h=>h.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,isCollateral:u,priceInRef:d,reserveLiquidationThreshold:p}=o,m=b.toBigInt(n,l),g=u?m*d/10n**BigInt(l):0n,P=s-g;return P<=0n?0:this.calculateHealthFactor(P,p,r)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(t),a=Rt.fromAssetId(e),o=i.find(P=>P.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:d}=o,m=b.toBigInt(n,l)*u/10n**BigInt(l),g=s+m;return g<=0n?0:this.calculateHealthFactor(g,d,r)}async getMaxWithdraw(t,e){let{totalCollateral:n,totalDebt:s,reserves:r}=await this.getSummary(t),i=Rt.fromAssetId(e),a=r.find(o=>o.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(a,n,s)}async getMaxWithdrawAll(t){let{totalCollateral:e,totalDebt:n,reserves:s}=await this.getSummary(t),r={};for(let i of s){let a=this.calculateWithdrawMax(i,e,n);i.reserveId&&(r[i.reserveId]=a)}return r}calculateHealthFactor(t,e,n){if(n===0n)return hn;let s=10n**6n,r=b.toBigInt(e,18),i=t*r*s,a=n*Pn,o=i/a;return Number(o)/1e6}calculateRequiredCollateral(t,e,n){let s=b.toBigInt(t,18),r=b.toBigInt(e,18);return(s*n+r-1n)/r}calculateWithdrawMax(t,e,n){let{aTokenBalance:s,decimals:r,priceInRef:i,reserveLiquidationThreshold:a}=t,o=this.calculateRequiredCollateral(bn,a,n),l=e-o;if(l<=0n)return{amount:0n,decimals:r};let u=l*10n**BigInt(r)/i;return{amount:s<u?s:u,decimals:r}}};var Te={};w(Te,{AssetClient:()=>$,BalanceClient:()=>q,ChainParams:()=>J});var $=class extends F{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:s}=n;return this.SUPPORTED_TYPES.includes(s.type)}).map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async mapToken(t,e,n,s){let{name:r,asset_type:i,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=n.get(t)??{};return{id:t,name:r?.asText(),symbol:l,decimals:u,icon:l,type:i.type,isSufficient:a,location:s,existentialDeposit:o}}async mapBond(t,e,n,s){let[r,i]=s,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:d}=await this.mapToken(r,e,n),p=Number(i),m=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",m.format(p)].join(" ");return{id:t,name:g,symbol:u+"b",decimals:d,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:r,maturity:p}}async mapShares(t,e,n,s){let{assets:r}=s,{name:i,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,d=await Promise.all(r.map(async g=>{let{symbol:P}=await this.mapToken(g,e,n);return[g,P]})),p=Object.fromEntries(d),m=Object.values(p);return{id:t,name:m.join(", "),symbol:a?.asText()||i?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:p}}async mapExternal(t,e,n,s){let r=await this.mapToken(t,e,new Map,s),i=n?.find(a=>a.internalId===r.id);return i?{...r,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:r}parseMetadata(t){return new Map(Array.from(t,([e,n])=>[e,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(t,e){let[n,s,r,i]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(n),o=[];for(let[l,u]of Array.from(n)){let d=s.get(l),{asset_type:p}=u,m;switch(p.type){case"Bond":let g=i.get(l);m=await this.mapBond(l,u,a,g);break;case"StableSwap":let P=r.get(l);m=await this.mapShares(l,u,a,P);break;case"External":m=await this.mapExternal(l,u,e,d);break;default:m=await this.mapToken(l,u,a,d)}o.push(m)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};import{Subject as fn,bufferCount as Tn,combineLatest as xn,debounceTime as In,distinctUntilChanged as fe,finalize as wn,map as Q,pairwise as Sn,shareReplay as On,startWith as vn}from"rxjs";var q=class extends F{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:{free:n,frozen:s}}=await e.getValue(t);return n-s}async getTokenBalance(t,e){let n=this.api.query.Tokens.Accounts,{free:s,frozen:r}=await n.getValue(t,e);return s-r}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),s=this.subscribeErc20Balance(t);return xn([e,n,s]).pipe(In(250),Q(r=>r.flat()),vn([]),Tn(2,1),Q(([r,i],a)=>{if(a===0)return i;let o=r.reduce((u,d)=>(u.set(d.id,d.amount),u),new Map);return i.filter(u=>u.amount!==o.get(u.id))}))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe(Q(n=>{let{free:s,frozen:r}=n.data;return{id:0,amount:s-r}}))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe(Q(s=>{let{free:r,frozen:i}=s;return{id:e,amount:r-i}}))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe(fe((n,s)=>!s.deltas),Q(({deltas:n})=>{let s=[];return n?.deleted.forEach(r=>{let[i,a]=r.args;s.push({id:a,amount:0n})}),n?.upserted.forEach(r=>{let[i,a]=r.args,{free:o,frozen:l}=r.value;s.push({id:a,amount:o-l})}),s}))}subscribeErc20Balance(t,e){let n=new fn,s=n.pipe(On(1)),r=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:u}=l;return u.type==="Erc20"}).map(({keyArgs:l})=>{let[u]=l;return u}),i=async()=>{let o=e||await r(),l=async()=>{let p=(await Promise.all(o.map(async m=>{let g=await this.getTokenBalanceData(t,m);return[m,g]}))).map(([m,g])=>({id:m,amount:g}));n.next(p)};await l();let u=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>u.unsubscribe()},a;return i().then(o=>a=o),s.pipe(wn(()=>a?.()),Sn(),Q(([o,l],u)=>{if(u===0)return l;let d=o.reduce((m,g)=>(m.set(g.id,g.amount),m),new Map);return l.filter(m=>m.amount!==d.get(m.id))}),fe((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let{free:n,frozen:s}=await this.api.apis.CurrenciesApi.account(e,t);return n-s}};var J=class extends F{_minOrderBudget;_blockTime;constructor(t){super(t)}async getBlockTime(){if(this._blockTime===void 0){let t=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(t)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var xe={};w(xe,{AssetNotFound:()=>zt,PoolNotFound:()=>ct,RouteNotFound:()=>Z});var zt=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},ct=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},Z=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var _e={};w(_e,{PoolContextProvider:()=>nt,PoolError:()=>j,PoolFactory:()=>et,PoolType:()=>A,aave:()=>te,lbp:()=>$t,omni:()=>Qt,stable:()=>Jt,xyk:()=>Zt});var $t={};w($t,{LbpMath:()=>M,LbpPool:()=>pt,LbpPoolClient:()=>mt});import{calculate_in_given_out as An,calculate_out_given_in as Bn,calculate_linear_weights as _n,calculate_pool_trade_fee as Rn,get_spot_price as Fn}from"@galacticcouncil/math-lbp";var M=class{static getSpotPrice(t,e,n,s,r){return Fn(t,e,n,s,r)}static calculateInGivenOut(t,e,n,s,r){return An(t,e,n,s,r)}static calculateOutGivenIn(t,e,n,s,r){return Bn(t,e,n,s,r)}static calculateLinearWeights(t,e,n,s,r){return _n(t,e,n,s,r)}static calculatePoolTradeFee(t,e,n){return Rn(t,e,n)}};var A=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r))(A||{}),j=(r=>(r.InsufficientTradingAmount="InsufficientTradingAmount",r.MaxInRatioExceeded="MaxInRatioExceeded",r.MaxOutRatioExceeded="MaxOutRatioExceeded",r.TradeNotAllowed="TradeNotAllowed",r.UnknownError="UnknownError",r))(j||{});var pt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,n,s,r,i,a){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.fee=i,this.repayFeeApply=a}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,weightIn:s.weight,weightOut:r.weight}}validateAndBuy(t,e,n){let s=this.tokens[0].id,r=[];e<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=t.balanceOut/this.maxOutRatio;if(e>i&&r.push("MaxOutRatioExceeded"),s===t.assetOut){let a=this.calculateTradeFee(e,n),o=y.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),d=t.balanceIn/this.maxInRatio;return u>d&&r.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:r}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&r.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:r}}}validateAndSell(t,e,n){let s=this.tokens[0].id,r=[];e<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=t.balanceIn/this.maxInRatio;if(e>i&&r.push("MaxInRatioExceeded"),s===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:r}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,n),l=y.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),u=a-o,d=t.balanceOut/this.maxOutRatio;return u>d&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:r}}}calculateInGivenOut(t,e){let n=M.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=M.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=M.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=M.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let n=M.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as qn}from"polkadot-api";import{map as Nn,of as ve,switchMap as Hn}from"rxjs";import{memoize1 as En}from"@thi.ng/memoize";import{combineLatest as Ie,combineLatestAll as Dn,debounceTime as kn,firstValueFrom as Cn,from as we,map as Se,mergeAll as Mn,of as Ln,switchMap as Oe}from"rxjs";var k=class extends q{override=[];mem=0;memPools=En(t=>(this.log(this.getPoolType(),"mem pools",t,"\u2705"),this.loadPools()));constructor(t){super(t)}async withOverride(t){this.override=t||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let t=we(this.getPoolsMem()).pipe(Oe(e=>this.subscribe(e)),Dn());return Cn(t)}getSubscriber(){return we(this.getPoolsMem()).pipe(Oe(t=>this.subscribe(t)),Mn())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>Ie([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe(kn(250),Se(([n,s])=>this.updatePool(n,s))))}subscribePoolBalance(t){if(t.type==="Aave")return Ln([]);let e=[this.subscribeTokensBalance(t.address)];if(this.hasSystemAsset(t)){let n=this.subscribeSystemBalance(t.address);e.push(n)}if(this.hasErc20Asset(t)){let n=t.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),s=this.subscribeErc20Balance(t.address,n);e.push(s)}return Ie(e).pipe(Se(n=>n.map(s=>Array.isArray(s)?s:[s]).flat()))}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({id:e,decimals:n,balance:s})=>{let r=this.override.find(a=>a.id===e),i=!!n||!!r?.decimals;return s>0n&&i})}updatePool=(t,e)=>{let n=t.tokens.map(s=>{let r=e.find(a=>a.id===s.id),i=this.override.find(a=>a.id===s.id);return r?{...s,balance:r.amount,decimals:s.decimals||i?.decimals}:{...s,decimals:s.decimals||i?.decimals}});return{...t,tokens:n}}};var mt=class extends k{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),s=e?.relay_parent_number||0,r=t.filter(({value:i})=>e&&this.isActivePool(i,s)).map(async({keyArgs:i,value:a})=>{let[o]=i,l=o.toString(),u=await this.getPoolDelta(l,a,s);return{address:l,type:"LBP",fee:a.fee,...u,...n}});return Promise.all(r)}async getPoolDelta(t,e,n){let{start:s,end:r,assets:i,initial_weight:a,final_weight:o,repay_target:l,fee_collector:u}=e,d=M.calculateLinearWeights(s?s.toString():"0",r?r.toString():"0",a.toString(),o.toString(),n.toString()),[p,m]=i,g=BigInt(d),P=this.MAX_FINAL_WEIGHT-BigInt(g),[h,x,f,T,I]=await Promise.all([this.isRepayFeeApplied(p,l,u.toString()),this.getBalance(t,p),this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(t,m),this.api.query.AssetRegistry.Assets.getValue(m)]);return{repayFeeApply:h,tokens:[{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:x,weight:g,type:f?.asset_type.type},{id:m,decimals:I?.decimals,existentialDeposit:I?.existential_deposit,balance:T,weight:P,type:I?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:s}=t;return n&&s?e>=n&&e<s:!1}async isRepayFeeApplied(t,e,n){if(e===0n)return!1;try{return await this.getBalance(n,t)<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(t){return{repayFee:await this.getRepayFee(),exchangeFee:t.fee}}getPoolType(){return"LBP"}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(qn.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(t.address);return n?e.watchValue("best").pipe(Hn(s=>s?this.getPoolDelta(t.address,n,s.relay_parent_number):ve(t)),Nn(s=>Object.assign({},t,s))):ve(t)}};var Qt={};w(Qt,{OmniMath:()=>S,OmniPool:()=>dt,OmniPoolClient:()=>gt});import{calculate_in_given_out as Gn,calculate_lrna_in_given_out as Un,calculate_out_given_in as Wn,calculate_out_given_lrna_in as Vn,calculate_spot_price as Xn,calculate_lrna_spot_price as Yn,calculate_shares as jn,calculate_liquidity_out as Kn,calculate_liquidity_lrna_out as zn,verify_asset_cap as $n,calculate_liquidity_hub_in as Qn,is_sell_allowed as Jn,is_buy_allowed as Zn,is_add_liquidity_allowed as ts,is_remove_liquidity_allowed as es}from"@galacticcouncil/math-omnipool";import tt from"big.js";var S=class{static calculateSpotPrice(t,e,n,s){return Xn(t,e,n,s)}static calculateLrnaSpotPrice(t,e){return Yn(t,e)}static calculateInGivenOut(t,e,n,s,r,i,a,o,l){return Gn(t,e,n,s,r,i,a,o,l)}static calculateLrnaInGivenOut(t,e,n,s,r){return Un(t,e,n,s,r)}static calculateOutGivenIn(t,e,n,s,r,i,a,o,l){return Wn(t,e,n,s,r,i,a,o,l)}static calculateOutGivenLrnaIn(t,e,n,s,r){return Vn(t,e,n,s,r)}static calculateShares(t,e,n,s){return jn(t,e,n,s)}static calculateLiquidityOut(t,e,n,s,r,i,a,o){return Kn(t,e,n,s,r,i,a,o)}static calculateLiquidityLRNAOut(t,e,n,s,r,i,a,o){return zn(t,e,n,s,r,i,a,o)}static calculateCapDifference(t,e,n,s){let r=tt(e),i=tt(t),a=tt(s),o=tt(n),l=tt(10).pow(18),u=o.div(l);if(r.div(a).lt(u)){let p=u.times(a).minus(r).times(i),m=r.times(tt(1).minus(u));return p.div(m).toFixed(0)}else return"0"}static verifyAssetCap(t,e,n,s){return $n(t,e,n,s)}static calculateLimitHubIn(t,e,n,s){return Qn(t,e,n,s)}static isSellAllowed(t){return Jn(t)}static isBuyAllowed(t){return Zn(t)}static isAddLiquidityAllowed(t){return ts(t)}static isRemoveLiquidityAllowed(t){return es(t)}};var dt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,n,s,r,i){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.hubAssetId=i}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:s.hubReserves,hubReservesOut:r.hubReserves,sharesIn:s.shares,sharesOut:r.shares,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,tradeableIn:s.tradeable,tradeableOut:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=this.calculateInGivenOut(t,e,n),i=s===0n?0:O.calculateDiffToRef(r,s),a=[],o=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let d=t.balanceIn/this.maxInRatio;return r>d&&a.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:i,errors:a}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=this.calculateOutGivenIn(t,e,n),i=O.calculateDiffToRef(s,r),a=[],o=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let d=t.balanceOut/this.maxOutRatio;return r>d&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let s=S.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?y.toDecimals(n.assetFee).toString():"0",n?y.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateLrnaInGivenOut(t,e,n){let s=S.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?y.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let s=S.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?y.toDecimals(n.assetFee).toString():"0",n?y.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenLrnaIn(t,e,n){let s=S.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?y.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=S.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceLrnaInGivenOut(t){let e=S.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=S.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}spotPriceOutGivenLrnaIn(t){let e=S.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};import{AccountId as ns,CompatibilityLevel as ss}from"polkadot-api";import{toHex as rs}from"@polkadot-api/utils";import{distinctUntilChanged as as,map as Ae}from"rxjs";var gt=class extends k{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,s,r,i,a]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.getBalance(e,t),this.getPoolLimits()]),o=n.map(async({keyArgs:u,value:d})=>{let[p]=u,{hub_reserve:m,shares:g,tradable:P,cap:h,protocol_shares:x}=d,[f,T]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(e,p)]);return{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:T,cap:h,hubReserves:m,protocolShares:x,shares:g,tradeable:P,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:i,tradeable:s,type:r?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...a}]}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=rs(e);return ns(63).dec(n)}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(t,e){let[n,s,r]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),i=n.min_fee+s.min_fee,a=n.max_fee+s.max_fee;if(r){let{asset_fee:o,protocol_fee:l}=r;return{assetFee:y.fromPermill(o),protocolFee:y.fromPermill(l),min:y.fromPermill(i),max:y.fromPermill(a)}}else return{assetFee:y.fromPermill(n.min_fee),protocolFee:y.fromPermill(s.min_fee),min:y.fromPermill(i),max:y.fromPermill(a)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(ss.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(as((n,s)=>!s.deltas),Ae(({entries:n})=>n.map(s=>{let[r]=s.args,{hub_reserve:i,shares:a,tradable:o,cap:l,protocol_shares:u}=s.value,d=t.tokens.findIndex(m=>m.id===r);return{...t.tokens[d],cap:l,hubReserves:i,protocolShares:u,shares:a,tradeable:o}})),Ae(n=>{let s=t.tokens.find(r=>r.id===1);return{...t,tokens:[...n,s]}}))}};var Jt={};w(Jt,{StableMath:()=>B,StableSwap:()=>bt,StableSwapClient:()=>ht});import{calculate_in_given_out as is,calculate_out_given_in as os,calculate_amplification as ls,calculate_add_one_asset as us,calculate_liquidity_out_one_asset as cs,calculate_shares as ps,calculate_shares_for_amount as ms,calculate_spot_price_with_fee as ds,pool_account_name as gs,recalculate_peg as bs}from"@galacticcouncil/math-stableswap";var B=class{static getPoolAddress(t){return gs(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,s,r){return ls(t,e,n,s,r)}static calculateInGivenOut(t,e,n,s,r,i,a){return is(t,e,n,s,r,i,a)}static calculateAddOneAsset(t,e,n,s,r,i,a){return us(t,e,n,s,r,i,a)}static calculateSharesForAmount(t,e,n,s,r,i,a){return ms(t,e,n,s,r,i,a)}static calculateOutGivenIn(t,e,n,s,r,i,a){return os(t,e,n,s,r,i,a)}static calculateLiquidityOutOneAsset(t,e,n,s,r,i,a){return cs(t,e,n,s,r,i,a)}static calculateShares(t,e,n,s,r,i){return ps(t,e,n,s,r,i)}static calculateSpotPriceWithFee(t,e,n,s,r,i,a,o){return ds(t,e,n,s,r,i,a,o)}static recalculatePegs(t,e,n,s,r){return bs(t,e,n,s,r)}};var bt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.id,t.fee,t.totalIssuance)}constructor(t,e,n,s,r,i,a,o,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.amplification=i,this.id=a,this.fee=o,this.totalIssuance=l}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=this.calculateInGivenOut(t,e,n),i=y.toPct(n.fee),a=[],o=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:r,calculatedIn:s,amountOut:e,feePct:i,errors:a}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=this.calculateOutGivenIn(t,e,n),i=y.toPct(n.fee),a=[],o=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateIn(t,e,n){let s=B.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateAddOneAsset(t,e,n){let s=B.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateSharesForAmount(t,e,n){let s=B.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateInGivenOut(t,e,n){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,n):t.assetIn==this.id?this.calculateSharesForAmount(t,e,n):this.calculateIn(t,e,n)}spotPriceInGivenOut(t){let e=B.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetOut==this.id)return BigInt(e);if(t.assetIn==this.id){let s=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let s=B.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateWithdrawOneAsset(t,e,n){let s=B.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateShares(t,e,n){let s=B.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(t,e,n){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,n):t.assetOut==this.id?this.calculateShares(t,e,n):this.calculateOut(t,e,n)}spotPriceOutGivenIn(t){let e=B.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetIn==this.id)return BigInt(e);if(t.assetOut==this.id){let s=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}getPegs(){let t=B.defaultPegs(this.tokens.length-1);return JSON.stringify(t)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:n,decimals:s})=>({asset_id:e,amount:n,decimals:s}));return JSON.stringify(t,X.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],X.jsonFormatter)}};import{AccountId as hs,CompatibilityLevel as ys}from"polkadot-api";import{toHex as Ps}from"@polkadot-api/utils";import{blake2b as fs}from"@noble/hashes/blake2b";import{map as Ts,of as xs,switchMap as Is}from"rxjs";var ws=340282366920938463463374607431768211455n,ht=class extends k{poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),s=t.map(async({keyArgs:r,value:i})=>{let[a]=r,o=this.getPoolAddress(a),[l,u]=await Promise.all([this.getPoolDelta(a,i,e),this.getPoolTokens(a,i)]);return this.poolsData.set(o,i),{address:o,id:a,type:"Stableswap",fee:y.fromPermill(i.fee),tokens:u,...l,...n}});return Promise.all(s)}async getPoolDelta(t,e,n){let{initial_amplification:s,final_amplification:r,initial_block:i,final_block:a}=e,o=B.calculateAmplification(s.toString(),r.toString(),i.toString(),a.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(t);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),s=e.assets.map(async a=>{let[o,l,u]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,a),this.api.query.AssetRegistry.Assets.getValue(a),this.getBalance(n,a)]);return{id:a,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:u,tradeable:o,type:l?.asset_type.type}}),r=await Promise.all(s),i=await this.api.query.AssetRegistry.Assets.getValue(t);return r.push({id:t,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:ws,tradeable:15,type:i?.asset_type.type}),r}getPoolAddress(t){let e=B.getPoolAddress(t),n=fs(e,{dkLen:32}),s=Ps(n);return hs(63).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(t){return{fee:t.fee}}getPoolType(){return"Stableswap"}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(ys.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.System.Number,n=this.poolsData.get(t.address);return!n||!t.id?xs(t):e.watchValue("best").pipe(Is(s=>this.getPoolDelta(t.id,n,s)),Ts(s=>Object.assign({},t,s)))}};var Zt={};w(Zt,{XykMath:()=>G,XykPool:()=>yt,XykPoolClient:()=>Pt});import{calculate_in_given_out as Ss,calculate_out_given_in as Os,calculate_pool_trade_fee as vs,get_spot_price as As,calculate_liquidity_in as Bs,calculate_shares as _s,calculate_spot_price as Rs,calculate_spot_price_with_fee as Fs,calculate_liquidity_out_asset_a as Es,calculate_liquidity_out_asset_b as Ds}from"@galacticcouncil/math-xyk";var G=class{static getSpotPrice(t,e,n){return As(t,e,n)}static calculateInGivenOut(t,e,n){return Ss(t,e,n)}static calculateOutGivenIn(t,e,n){return Os(t,e,n)}static calculatePoolTradeFee(t,e,n){return vs(t,e,n)}static calculateLiquidityIn(t,e,n){return Bs(t,e,n)}static calculateSpotPrice(t,e){return Rs(t,e)}static calculateSpotPriceWithFee(t,e,n,s){return Fs(t,e,n,s)}static calculateShares(t,e,n){return _s(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,s){return Es(t,e,n,s)}static calculateLiquidityOutAssetB(t,e,n,s){return Ds(t,e,n,s)}};var yt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,r){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=this.calculateTradeFee(s,n),i=y.toPct(n.exchangeFee),a=s+r,o=[];(e<this.minTradingLimit||s<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:i,errors:o}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=this.calculateTradeFee(s,n),i=y.toPct(n.exchangeFee),a=s-r,o=[];(e<this.minTradingLimit||s<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:i,errors:o}}calculateInGivenOut(t,e){let n=G.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=G.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=G.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=G.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=G.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as ks}from"polkadot-api";import{of as Cs}from"rxjs";var Pt=class extends k{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,n]=await Promise.all([t.getEntries(),this.getPoolLimits()]),s=e.map(async({keyArgs:r,value:i})=>{let[a]=r,[o,l]=i,[u,d,p,m]=await Promise.all([this.getBalance(a,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(a,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:a,type:"XYK",tokens:[{id:o,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:u,type:d?.asset_type.type},{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:p,type:m?.asset_type.type}],...n}});return Promise.all(s)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(ks.BackwardsCompatible,e)}subscribePoolChange(t){return Cs(t)}};var te={};w(te,{AavePool:()=>ft,AavePoolClient:()=>Tt});var ft=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,r){this.type="Aave",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(t),r=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),r=[];return e>t.balanceOut&&r.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:r}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),r=[];return s>t.balanceOut&&r.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:r}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){let e=Math.pow(10,t.decimalsOut);return BigInt(e)}spotPriceOutGivenIn(t){let e=Math.pow(10,t.decimalsIn);return BigInt(e)}calculateTradeFee(t,e){return 0n}};import{AccountId as Ms}from"polkadot-api";import{toHex as Ls}from"@polkadot-api/utils";import{map as qs,merge as Ns,switchMap as Hs}from"rxjs";import{decodeEventLog as Gs}from"viem";var Be=[{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:Us}=K,Ws=["Supply","Withdraw","Repay","Borrow"],Tt=class extends k{async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:s,liqudity_in:r,liqudity_out:i})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(n,s),type:"Aave",tokens:[{id:n,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:r,location:o,type:a?.asset_type.type},{id:s,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:i,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:s,liqudity_out:r}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id);return t.tokens.map(i=>{let a=i.id===e.id?s:r;return{...i,balance:a}})}getPoolId(t,e){let n=t+"/"+e,s=new TextEncoder().encode(n.padEnd(32,"\0")),r=Ls(s);return Ms(63).dec(r)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(t,e){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(t){let[e,n]=t.tokens,s=this.getReserveH160Id(e),r=this.api.event.Router.Executed.watch(({asset_in:a,asset_out:o})=>a===n.id||o===n.id),i=this.api.event.EVM.Log.watch(({log:a})=>{let{topics:o,data:l}=a,u=o.map(g=>g.asHex()),d=l.asHex(),{eventName:p,args:m}=Gs({abi:Be,topics:u,data:d});return Ws.includes(p)&&m.reserve.toLowerCase()===s.toLowerCase()});return Ns([r,i]).pipe(Hs(()=>this.getPoolDelta(t)),qs(a=>({...t,tokens:[...a]})))}getReserveH160Id(t){return t.type==="Erc20"?X.findNestedKey(t.location,"AccountKey20").AccountKey20.key:Us.fromAssetId(t.id)}};var et=class{static get(t){switch(t.type){case"Aave":return ft.fromPool(t);case"XYK":return yt.fromPool(t);case"Omnipool":return dt.fromPool(t);case"LBP":return pt.fromPool(t);case"Stableswap":return bt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{Subject as Vs,Subscription as xt,takeUntil as Xs}from"rxjs";var nt=class extends F{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=xt.EMPTY;omniSub=xt.EMPTY;stableSub=xt.EMPTY;xykSub=xt.EMPTY;aaveSub=xt.EMPTY;isReady=!1;isDestroyed=new Vs;constructor(t){super(t),this.lbpClient=new mt(t),this.omniClient=new gt(t),this.stableClient=new ht(t),this.xykClient=new Pt(t),this.aaveClient=new Tt(t),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(t){return t.getSubscriber().pipe(Xs(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)})}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(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let n=this.clients.find(s=>s.getPoolType()===t.type);if(n)return n.getPoolFees(t,e);throw new ct(t.type)}};var ke={};w(ke,{Router:()=>st,TradeOrderError:()=>ne,TradeOrderType:()=>Dt,TradeRouteBuilder:()=>C,TradeRouter:()=>rt,TradeScheduler:()=>at,TradeType:()=>Et});var Ft=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Ys=5,It=class{isNotVisited(t,e){let n=!0;return e.forEach(s=>{(s[0]===t[0]||s[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let s=[],r=new Ft,i=[];for(i.push([e,""]),r.enqueue(i);r.size()>0;){let a=r.dequeue();if(a==null||a.length>Ys)return s;let o=a[a.length-1];(n===null||o[0]===n)&&s.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let d=[...a];d.push(u),r.enqueue(d)}})}return s}buildAndPopulateGraph(t,e){let n=new Map;for(let s of t)n.set(parseInt(s),[]);for(let[s,r,i]of e)n.get(r)?.push([i,s]);return n}};function ee(c){let t={};for(let e of c){let n=e.tokens.length;for(let s=0;s<n;s++){t[e.tokens[s].id]||(t[e.tokens[s].id]=[]);for(let r=0;r<n;r++){if(s==r)continue;let i=[e.address,e.tokens[s].id,e.tokens[r].id];t[e.tokens[s].id].push(i)}}}return t}var wt=class{getProposals(t,e,n){let s=ee(n),r=Object.keys(s),i=r.map(u=>s[u]).flat(),a=new It,o=a.buildAndPopulateGraph(r,i),l=a.findPaths(o,t,e);return this.parsePaths(l)}parsePaths(t){let e=[];for(let n of t){let s=[];for(let r=0;r<n.length;r++){let i=n[r],a=n[r+1];if(a==null)break;s.push(this.toEdge(i,a))}e.push(s)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var st=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(t,e){this.ctx=t,this.routeSuggester=new wt,this.routerOptions={...this.defaultRouterOptions,...e}}async getPools(){let t=await this.ctx.getPools(),e=this.routerOptions.useOnly;return e.length===0?t:t.filter(n=>e.includes(n.type))}async getRoutes(t,e){let n=await this.getPools();return this.validateInput(t,e,n),this.getPaths(t,e,n)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}validateInput(t,e,n){if(n.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let s=this.getAssets(n);if(!s.has(t))throw new Error(t+" is not supported asset");if(!s.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(s=>s.id)).flat().sort((n,s)=>n>s?1:-1);return new Set(e)}getPaths(t,e,n){let s=this.toPoolsMap(n);return this.routeSuggester.getProposals(t,e,n).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,s)=>n&&s)}validEdge([t,e,n],s){return s.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,et.get(e)]))}toHops(t,e){return t.map(([n,s,r])=>{let i=e.get(n);return{poolAddress:n,poolId:i?.id,pool:i?.type,assetIn:s,assetOut:r}})}};var Et=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Et||{}),Dt=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Dt||{}),ne=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(ne||{});var rt=class extends st{isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,s)=>{let r=n[n.length-1].amountOut,i=s[s.length-1].amountOut;return r>i?-1:1});return e.find(n=>n.every(s=>s.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(n=>n.tradeFeeRange).length>0){let n=t.map(r=>r.tradeFeeRange?.[0]??r.tradeFeePct).reduce((r,i)=>r+i),s=t.map(r=>r.tradeFeeRange?.[1]??r.tradeFeePct).reduce((r,i)=>r+i);return[n,s]}}getPoolFeeRange(t){let e=t.min?y.toPct(t.min):void 0,n=t.max?y.toPct(t.max):void 0;if(e&&n)return[e,n]}async getBestSell(t,e,n){return this.getSell(t,e,n)}async getSellSpot(t){let e=t[t.length-1];if(t.length===1)return e.spotPrice;let n=t.map(a=>a.assetOutDecimals).reduce((a,o)=>a+o),s=t.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-e.assetOutDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getSell(t,e,n,s){let r=await super.getPools(),i=super.validateInput(t,e,r),a=super.getPaths(t,e,r);if(a.length===0)throw new Z(t,e);let o;if(s)o=await this.toSellSwaps(n,s,i);else{let v=await Promise.all(a.map(_=>this.toSellSwaps(n,_,i)));o=this.findBestSellRoute(v)}let l=o[0],u=o[o.length-1],d=this.isDirectTrade(o),p=await this.getSellSpot(o),m=u.amountOut,g=d?u.calculatedOut:this.calculateDelta0Y(l.amountIn,o,i),P=g-m,h=this.getRouteFeeRange(o),x=d?u.tradeFeePct:O.calculateSellFee(g,m),f=Math.pow(10,l.assetInDecimals),T=l.amountIn*p/BigInt(f),I=O.calculateDiffToRef(g,T);return{type:"Sell",amountIn:l.amountIn,amountOut:u.amountOut,spotPrice:p,tradeFee:P,tradeFeePct:x,tradeFeeRange:h,priceImpactPct:I,swaps:o,toHuman(){return{type:"Sell",amountIn:b.toDecimal(l.amountIn,l.assetInDecimals),amountOut:b.toDecimal(u.amountOut,u.assetOutDecimals),spotPrice:b.toDecimal(p,u.assetOutDecimals),tradeFee:b.toDecimal(P,u.assetOutDecimals),tradeFeePct:x,tradeFeeRange:h,priceImpactPct:I,swaps:o.map(v=>v.toHuman())}}}}calculateDelta0Y(t,e,n){let s=[];for(let r=0;r<e.length;r++){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r>0?l=s[r-1]:l=t;let u=a.calculateOutGivenIn(o,l);s.push(u)}return s[s.length-1]}async toSellSwaps(t,e,n){let s=[];for(let r=0;r<e.length;r++){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r>0?l=s[r-1].amountOut:l=typeof t=="string"?b.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountOut:d,calculatedOut:p,feePct:m,errors:g}=a.validateAndSell(o,l,u),P=this.getPoolFeeRange(u),h=a.spotPriceOutGivenIn(o),x=Math.pow(10,o.decimalsIn),f=l*h/BigInt(x),T=O.calculateDiffToRef(p,f);s.push({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:d,calculatedOut:p,spotPrice:h,tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===i.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:b.toDecimal(l,o.decimalsIn),amountOut:b.toDecimal(d,o.decimalsOut),calculatedOut:b.toDecimal(p,o.decimalsOut),spotPrice:b.toDecimal(h,o.decimalsOut),tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}async getMostLiquidRoute(t,e){let n=await super.getPools(),s=super.validateInput(t,e,n),r=super.getPaths(t,e,n),o=n.filter(p=>p.tokens.some(m=>m.id===t&&m.id!==p.id)).map(p=>p.type==="Aave"?p.tokens:p.tokens.filter(m=>m.id===t)).map(p=>p.map(m=>m.balance).reduce((m,g)=>m+g)).sort((p,m)=>m<p?-1:1)[0],l=O.getFraction(o,.1),u=await Promise.all(r.map(p=>this.toSellSwaps(l,p,s)));return this.findBestSellRoute(u).map(p=>({poolAddress:p.poolAddress,poolId:p?.poolId,pool:p.pool,assetIn:p.assetIn,assetOut:p.assetOut}))}async getSpotPrice(t,e){let n=await super.getPools(),s=super.validateInput(t,e,n),r=await this.getMostLiquidRoute(t,e),i=await this.toSellSwaps("1",r,s),a=await this.getSellSpot(i),o=i[i.length-1].assetOutDecimals;return{amount:a,decimals:o}}findBestBuyRoute(t){let e=t.sort((n,s)=>{let r=n[0].amountIn,i=s[0].amountIn;return r>i?1:-1});return e.find(n=>n.every(s=>s.errors.length==0))||e[0]}async getBestBuy(t,e,n){return this.getBuy(t,e,n)}async getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let n=t.map(a=>a.assetInDecimals).reduce((a,o)=>a+o),s=t.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-e.assetInDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getBuy(t,e,n,s){let r=await super.getPools(),i=super.validateInput(t,e,r),a=super.getPaths(t,e,r);if(a.length===0)throw new Z(t,e);let o;if(s)o=await this.toBuySwaps(n,s,i);else{let v=await Promise.all(a.map(_=>this.toBuySwaps(n,_,i)));o=this.findBestBuyRoute(v)}let l=o[o.length-1],u=o[0],d=this.isDirectTrade(o),p=await this.getBuySpot(o),m=u.amountIn,g=d?u.calculatedIn:this.calculateDelta0X(l.amountOut,o,i),P=m-g,h=this.getRouteFeeRange(o),x=d?u.tradeFeePct:O.calculateBuyFee(g,m),f=Math.pow(10,l.assetOutDecimals),T=l.amountOut*p/BigInt(f),I;return g===0n?I=-100:I=O.calculateDiffToRef(T,g),{type:"Buy",amountOut:l.amountOut,amountIn:u.amountIn,spotPrice:p,tradeFee:P,tradeFeePct:x,tradeFeeRange:h,priceImpactPct:I,swaps:o,toHuman(){return{type:"Buy",amountOut:b.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:b.toDecimal(u.amountIn,u.assetInDecimals),spotPrice:b.toDecimal(p,u.assetInDecimals),tradeFee:b.toDecimal(P,u.assetInDecimals),tradeFeePct:x,tradeFeeRange:h,priceImpactPct:I,swaps:o.map(v=>v.toHuman())}}}}calculateDelta0X(t,e,n){let s=[];for(let r=e.length-1;r>=0;r--){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r==e.length-1?l=t:l=s[0];let u=a.calculateInGivenOut(o,l);s.unshift(u)}return s[0]}async toBuySwaps(t,e,n){let s=[];for(let r=e.length-1;r>=0;r--){let i=e[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r==e.length-1?l=typeof t=="string"?b.toBigInt(t,o.decimalsOut):t:l=s[0].amountIn;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountIn:d,calculatedIn:p,feePct:m,errors:g}=a.validateAndBuy(o,l,u),P=this.getPoolFeeRange(u),h=a.spotPriceInGivenOut(o),x=Math.pow(10,o.decimalsOut),f=l*h/BigInt(x),T;p===0n?T=-100:T=O.calculateDiffToRef(f,p),s.unshift({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:d,calculatedIn:p,spotPrice:h,tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===i.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:b.toDecimal(l,o.decimalsOut),amountIn:b.toDecimal(d,o.decimalsIn),calculatedIn:b.toDecimal(p,o.decimalsIn),spotPrice:b.toDecimal(h,o.decimalsIn),tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}};var Re=1000000000000000n;import{Enum as Fe}from"polkadot-api";var C=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:s,poolId:r})=>s==="Stableswap"?{pool:Fe("Stableswap",r),asset_in:e,asset_out:n}:{pool:Fe(s),asset_in:e,asset_out:n})}};var at=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Re})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,s,r){let[i,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:u}=a,d=l[0],p=l[l.length-1],{assetInDecimals:m}=d,{assetOutDecimals:g}=p,P=Math.abs(u),h=this.getMinimumTradeCount(o,i),x=this.getOptimalTradeCount(P),f=r?Math.round(s/r):x,T=Math.ceil(s/h),I=Math.round(s/x),v=Math.round(s/f),_=o/BigInt(f),R=await this.router.getBestSell(t,e,_),U=o<i,St=[];U&&St.push("OrderTooSmall");let Ot=R.amountOut*BigInt(f),Lt=this.toBlockPeriod(v),qt=R.tradeFee*BigInt(f),qe=C.build(l),re={assetIn:t,assetOut:e,errors:St,frequencyMin:T,frequencyOpt:I,frequency:v,tradeCount:f,tradeFee:qt,tradeImpactPct:R.priceImpactPct,tradePeriod:Lt,tradeRoute:qe,type:"Dca"};return{...re,amountIn:o,amountOut:Ot,tradeAmountIn:R.amountIn,tradeAmountOut:R.amountOut,toHuman(){return{...re,amountIn:b.toDecimal(o,m),amountOut:b.toDecimal(Ot,g),tradeAmountIn:b.toDecimal(R.amountIn,m),tradeAmountOut:b.toDecimal(R.amountOut,g)}}}}async getMinimumOrderBudget(t){if(0===t)return this.minOrderBudget;let e=await this.router.getSpotPrice(0,t),n=10n**BigInt(12);if(e)return this.minOrderBudget*e.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(t,e){let n=e*2n/10n;if(n===0n)return 0;let s=t+n/2n;return Number(s/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:p}=u,m=Math.abs(o),g=this.getTwapTradeCount(m),P=i/BigInt(g),h=await this.router.getBestSell(l.assetIn,u.assetOut,P),x=g===1,f=i<s,T=h.priceImpactPct<-5,I=[];f||x?I.push("OrderTooSmall"):T&&I.push("OrderImpactTooBig");let v=h.amountOut*BigInt(g),_=h.tradeFee*BigInt(g),R=C.build(a),U={assetIn:t,assetOut:e,errors:I,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapSell"};return{...U,amountIn:i,amountOut:v,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:_,toHuman(){return{...U,amountIn:b.toDecimal(i,d),amountOut:b.toDecimal(v,p),tradeAmountIn:b.toDecimal(h.amountIn,d),tradeAmountOut:b.toDecimal(h.amountOut,p),tradeFee:b.toDecimal(_,p)}}}}async getTwapBuyOrder(t,e,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:p}=u,m=Math.abs(o),g=this.getTwapTradeCount(m),P=i/BigInt(g),h=await this.router.getBestBuy(l.assetIn,u.assetOut,P),x=h.amountIn*BigInt(g),f=g===1,T=x<s,I=h.priceImpactPct<-5,v=[];T||f?v.push("OrderTooSmall"):I&&v.push("OrderImpactTooBig");let _=h.tradeFee*BigInt(g),R=C.build(a),U={assetIn:t,assetOut:e,errors:v,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapBuy"};return{...U,amountIn:x,amountOut:i,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:_,toHuman(){return{...U,amountIn:b.toDecimal(x,d),amountOut:b.toDecimal(i,p),tradeAmountIn:b.toDecimal(h.amountIn,d),tradeAmountOut:b.toDecimal(h.amountOut,p),tradeFee:b.toDecimal(_,d)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,n=Math.round(e);return Math.max(n,6)}};var Le={};w(Le,{TxBuilderFactory:()=>ot});import{Enum as Me}from"polkadot-api";function Ce(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var it=class extends F{evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evmClient=e??new E,this.balanceClient=new q(t),this.aaveUtils=new Y(this.evmClient)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:n=>this.dryRun(n,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:Gt})}async dryRun(t,e){let n=Me("Signed",t),s=Me("system",n),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall),a=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(a){let o=Ce(a.value);throw new Error("Dry run execution error!",{cause:o})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var Ct=class extends it{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],r=await this.balanceClient.getBalance(this.beneficiary,s);return t>=r-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=O.getFraction(t,this.slippagePct),a=s.assetIn,o=r.assetOut,l=t+i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:C.build(n)}),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=O.getFraction(e,this.slippagePct),a=s.assetIn,o=r.assetOut,l=e-i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:C.build(n)}),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,n=e[0],s=e[e.length-1],r=O.getFraction(t,this.slippagePct),i=n.assetIn,a=s.assetOut,o=t-r,l=this.api.tx.Router.sell_all({asset_in:i,asset_out:a,min_amount_out:o,route:C.build(e)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as se}from"polkadot-api";var Mt=class extends it{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradePeriod:r,tradeRoute:i}=this.order,a=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,order:se("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=O.getFraction(r,this.slippagePct),l=r-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,order:se("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=O.getFraction(s,this.slippagePct),l=s+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,order:se("Buy",{asset_in:e,asset_out:n,amount_out:r,max_amount_in:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var ot=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e??new E}trade(t){return new Ct(this.client,this.evmClient).setTrade(t)}order(t){return new Mt(this.client,this.evmClient).setOrder(t)}};async function rc(c,t){let e=new J(c),[n,s]=await Promise.all([e.getBlockTime(),e.getMinOrderBudget()]),r=t??new E,i=new nt(c).withAave().withOmnipool().withStableswap().withXyk(),a=new Y(r),o=new rt(i),l=new at(o,{blockTime:n,minBudgetInNative:s});return{api:{aave:a,router:o,scheduler:l},client:{asset:new $(c),balance:new q(c),evm:r},ctx:{pool:i},tx:new ot(c,r),destroy:()=>{i.destroy()}}}export{Pe as aave,ie as api,b as big,Te as client,me as const,rc as createSdkContext,K as erc20,xe as error,ce as evm,y as fmt,_t as h160,X as json,O as math,_e as pool,ke as sor,Le as tx,ye as xc};
@@ -5,7 +5,6 @@ export declare class OmniMath {
5
5
  static calculateLrnaInGivenOut(assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string): string;
6
6
  static calculateOutGivenIn(assetInBalance: string, assetInHubReserve: string, assetInShares: string, assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountIn: string, assetFee: string, protocolFee: string): string;
7
7
  static calculateOutGivenLrnaIn(assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string): string;
8
- static calculatePoolTradeFee(amount: string, feeNumerator: number, feeDenominator: number): string;
9
8
  static calculateShares(assetReserve: string, assetHubReserve: string, assetShares: string, amountIn: string): string;
10
9
  static calculateLiquidityOut(assetReserve: string, assetHubReserve: string, assetShares: string, positionAmount: string, positionShares: string, positionPrice: string, sharesToRemove: string, withdrawalFee: string): string;
11
10
  static calculateLiquidityLRNAOut(assetReserve: string, assetHubReserve: string, assetShares: string, positionAmount: string, positionShares: string, positionPrice: string, sharesToRemove: string, withdrawalFee: string): string;
@@ -9,6 +9,5 @@ export declare class StableMath {
9
9
  static calculateLiquidityOutOneAsset(reserves: string, shares: string, assetOut: number, amplification: string, shareIssuance: string, withdrawFee: string, pegs: string): string;
10
10
  static calculateShares(reserves: string, assets: string, amplification: string, shareIssuance: string, fee: string, pegs: string): string;
11
11
  static calculateSpotPriceWithFee(poolId: string, reserves: string, amplification: string, assetIn: string, assetOut: string, shareIssuance: string, fee: string, pegs: string): string;
12
- static calculatePoolTradeFee(amount: string, feeNumerator: number, feeDenominator: number): string;
13
12
  static recalculatePegs(currentPegs: string, targetPegs: string, currentBlock: string, maxPegUpdate: string, poolFee: string): string;
14
13
  }
@@ -39,7 +39,6 @@ export declare class StableSwap implements Pool {
39
39
  private calculateShares;
40
40
  calculateOutGivenIn(poolPair: PoolPair, amountIn: bigint, fees?: StableSwapFees): bigint;
41
41
  spotPriceOutGivenIn(poolPair: PoolPair): bigint;
42
- calculateTradeFee(amount: bigint, fees: StableSwapFees): bigint;
43
42
  private getPegs;
44
43
  private getReserves;
45
44
  private getAssets;
@@ -77,14 +77,14 @@ export declare class TradeScheduler {
77
77
  * @param priceImpact - price impact of swap execution (via single trade)
78
78
  * @returns optimal number of trades to execute the order
79
79
  */
80
- private getTwapTradeCount;
80
+ getTwapTradeCount(priceImpact: number): number;
81
81
  /**
82
82
  * Calculate approx. execution time for twap order.
83
83
  *
84
84
  * @param tradeCount - number of trades per order
85
85
  * @returns unix representation of execution time
86
86
  */
87
- private getTwapExecutionTime;
87
+ getTwapExecutionTime(tradeCount: number): number;
88
88
  /**
89
89
  * Convert unix execution period to block period
90
90
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk-next",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Galactic next gen sdk (papi)",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {
@@ -36,11 +36,11 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "@galacticcouncil/descriptors": "^1.2.0",
39
- "@galacticcouncil/math-lbp": "^1.1.0",
40
- "@galacticcouncil/math-liquidity-mining": "^1.1.0",
41
- "@galacticcouncil/math-omnipool": "^1.2.0",
42
- "@galacticcouncil/math-stableswap": "^2.1.0",
43
- "@galacticcouncil/math-xyk": "^1.1.0",
39
+ "@galacticcouncil/math-lbp": "^1.2.0",
40
+ "@galacticcouncil/math-liquidity-mining": "^1.2.0",
41
+ "@galacticcouncil/math-omnipool": "^1.3.0",
42
+ "@galacticcouncil/math-stableswap": "^2.2.0",
43
+ "@galacticcouncil/math-xyk": "^1.2.0",
44
44
  "@noble/hashes": "^1.6.1",
45
45
  "@thi.ng/cache": "^2.1.35",
46
46
  "@thi.ng/memoize": "^4.0.2",