@galacticcouncil/sdk-next 0.6.0-pr194-1c1c0d6 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.cjs +1 -1
- package/build/index.mjs +1 -1
- package/build/types/aave/AaveClient.d.ts +2 -2
- package/build/types/aave/AaveUtils.d.ts +1 -1
- package/build/types/evm/chain.d.ts +1 -1
- package/build/types/evm/client.d.ts +3 -2
- package/build/types/evm/index.d.ts +1 -0
- package/build/types/evm/types.d.ts +7 -0
- package/build/types/factory.d.ts +1 -1
- package/build/types/oracle/MmOracleClient.d.ts +7 -0
- package/build/types/oracle/abi.d.ts +87 -0
- package/build/types/oracle/index.d.ts +2 -0
- package/build/types/oracle/types.d.ts +5 -0
- package/build/types/pool/PoolClient.d.ts +5 -1
- package/build/types/pool/PoolContextProvider.d.ts +3 -1
- package/build/types/pool/stable/StableSwapClient.d.ts +6 -6
- package/build/types/staking/StakingApi.d.ts +1 -1
- package/build/types/staking/StakingClient.d.ts +0 -5
- package/build/types/tx/TxBuilder.d.ts +4 -2
- package/build/types/tx/TxBuilderFactory.d.ts +1 -1
- package/build/types/utils/format.d.ts +9 -3
- package/package.json +3 -3
package/build/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var $t=Object.defineProperty;var x=(u,e)=>{for(var t in e)$t(u,t,{get:e[t],enumerable:!0})};var dt={};x(dt,{Papi:()=>B,getWs:()=>en});import{hydration as Qt}from"@galacticcouncil/descriptors";function mt(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var B=class{client;api;constructor(e){this.client=e,this.api=this.client.getTypedApi(Qt)}log(e,...t){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");mt(n)&&console.log(e,...t)}};import{createClient as Jt}from"polkadot-api";import{withPolkadotSdkCompat as Zt}from"polkadot-api/polkadot-sdk-compat";var en=async u=>{let e=typeof u=="string"?u.split(","):u,s=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(e);return Jt(Zt(s))};var vt={};x(vt,{AAVE_GAS_LIMIT:()=>We,AAVE_LENDING_POOL_ADDRESS:()=>Ee,AAVE_POOL_ABI:()=>Ue,AAVE_POOL_DATA_PROVIDER:()=>ke,AAVE_POOL_DATA_PROVIDER_ABI:()=>Fe,AAVE_POOL_PROXY:()=>Ve,AAVE_ROUNDING_THRESHOLD:()=>Oa,AAVE_UINT_256_MAX:()=>tn,AaveClient:()=>le,AaveUtils:()=>Y});var Ue=[{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 Fe=[{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 Ve="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",ke="0x112b087b60C1a166130d59266363C45F8aa99db0",Ee="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",We=1000000n,Oa=5,tn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var yt={};x(yt,{EvmClient:()=>R,evmMainnet:()=>Xe});import{defineChain as nn}from"viem";var gt=["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"],bt=["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"],Xe=nn({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:gt,webSocket:bt},default:{http:gt,webSocket:bt}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as ht,createWalletClient as sn,custom as an,http as rn,webSocket as on}from"viem";var R=class{chain;constructor(e){this.chain=e||Xe}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 ht({chain:this.chain,transport:rn()})}getWsProvider(){return ht({chain:this.chain,transport:on()})}getSigner(e){return sn({account:e,chain:this.chain,transport:an(window.ethereum)})}};var le=class{evmClient;constructor(e){this.evmClient=e??new R}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Fe,address:ke,args:[Ee],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:Fe,address:ke,args:[Ee,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:Ue,address:Ve,args:[e],functionName:"getUserAccountData"})}};var y={};x(y,{asBigInt:()=>un,toBigInt:()=>cn,toDecimal:()=>ln});import W from"big.js";W.NE=-18;function ln(u,e,t=6,n){let s=W(u.toString()),a=W(10).pow(e);return s.div(a).round(t,n).toString()}function cn(u,e){let t=W(10).pow(e),s=W(u).mul(t).toFixed(0,W.roundDown);return BigInt(s)}function un(u){return BigInt(u.round(0,W.roundDown).toFixed(0))}var j={};x(j,{ERC20:()=>Ye});var Ye=class{static fromAssetId(e){let t=Buffer.alloc(20,0);return t[15]=1,t.writeUInt32BE(e,16),"0x"+t.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(e.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(t.subarray(0,16))}};var P={};x(P,{fromPermill:()=>dn,toDecimals:()=>mn,toPct:()=>pn});var Pt=1e3;function pn(u){let[e,t]=u;return e/t*100}function mn(u){let[e,t]=u;return e/t}function dn(u){return[u/Pt,Pt]}var Ce={};x(Ce,{H160:()=>Qe,isEvmAccount:()=>St,isEvmAddress:()=>xt,isSs58Address:()=>wt});import{AccountId as ce}from"polkadot-api";import{toHex as Tt}from"@polkadot-api/utils";import{Buffer as V}from"buffer";var ft={};x(ft,{HUB_ASSET_ID:()=>ze,HYDRATION_OMNIPOOL_ADDRESS:()=>hn,HYDRATION_PARACHAIN_ID:()=>bn,HYDRATION_SS58_PREFIX:()=>k,PERBILL_DENOMINATOR:()=>gn,PERMILL_DENOMINATOR:()=>Ke,RUNTIME_DECIMALS:()=>F,SYSTEM_ASSET_DECIMALS:()=>je,SYSTEM_ASSET_ID:()=>M,TRADEABLE_DEFAULT:()=>z});var F=18,Ke=1e6,gn=1e9,M=0,je=12,bn=2034,k=63,hn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",ze=1,z=15;var $e="ETH\0";function St(u){if(!u)return!1;try{let e=ce().enc(u),t=V.from($e);return V.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function xt(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function wt(u){try{return ce(63).enc(u),!0}catch{return!1}}var Qe=class u{static toAccount=e=>{let t=V.from(e.slice(2),"hex"),n=V.from($e),s=Uint8Array.from(V.concat([n,t,V.alloc(8)])),a=Tt(s);return ce(63).dec(a)};static fromAccount=e=>{let t=ce().enc(e),n=V.from($e),s=t.slice(n.length,-8);return"0x"+V.from(s).toString("hex")};static fromSS58=e=>{let n=ce().enc(e).slice(0,20);return Tt(n)};static fromAny=e=>{if(xt(e))return e;if(St(e))return u.fromAccount(e);if(wt(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var X={};x(X,{findNestedKey:()=>yn,findNestedObj:()=>Pn,jsonFormatter:()=>fn});var yn=(u,e)=>{let t=[];return JSON.stringify(u,(n,s)=>(s&&s[e]&&t.push(s),s)),t[0]},Pn=(u,e,t)=>{let n;return JSON.stringify(u,(s,a)=>(a&&a[e]===t&&(n=a),a)),n},fn=(u,e)=>typeof e=="bigint"?e.toString():e;var I={};x(I,{calculateBuyFee:()=>wn,calculateDiffToAvg:()=>Tn,calculateDiffToRef:()=>Sn,calculateSellFee:()=>xn,getFraction:()=>In});import H from"big.js";function Tn(u,e){let t=H(u.toString()),n=H(e.toString());return t.minus(n).abs().div(t.plus(n).div(2)).mul(100).round(2).toNumber()}function Sn(u,e){if(e===0n)return 0;let t=H(u.toString()),n=H(e.toString());return t.minus(n).div(n).mul(100).round(2).toNumber()}function xn(u,e){let t=H(u.toString()),n=H(e.toString());return H(1).minus(n.div(t)).mul(100).round(2).toNumber()}function wn(u,e){let t=H(u.toString());return H(e.toString()).div(t).minus(1).mul(100).round(2).toNumber()}function In(u,e,t=2){(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,t),s=BigInt(e*n);return u*s/BigInt(100*n)}var It={};x(It,{convertToId:()=>On});import{Buffer as vn}from"buffer";function On(u){let t=vn.from(u.replace("0x",""),"hex").subarray(16);return t.readUIntBE(0,t.length)}var{ERC20:De}=j,{H160:Je}=Ce,An=1.01,Bn=99999,_n=10n**27n,Rn=10n**18n,Y=class{client;constructor(e){let t=e??new R;this.client=new le(t)}async getSummary(e){let t=Je.fromAny(e),[n,s,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t)]),[i]=n,[r,o]=s,[l,c,p,g,m,b]=a,h=y.toDecimal(b,18),d=[];for(let f of r){let T=f.underlyingAsset.toLowerCase(),S=i.find(({underlyingAsset:Ge})=>Ge.toLowerCase()===T);if(!S)throw new Error("Missing pool reserve for "+T);let v=f.scaledATokenBalance,D=S.liquidityIndex,N=S.priceInMarketReferenceCurrency,_=v*D/_n,_e=Number(o===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,Re=S.usageAsCollateralEnabled&&f.usageAsCollateralEnabledOnUser&&f.scaledATokenBalance>0n,He=De.toAssetId(T);d.push({aTokenBalance:_,decimals:Number(S.decimals),isCollateral:Re,priceInRef:N,reserveId:He,reserveAsset:T,reserveLiquidationThreshold:_e})}return{healthFactor:Number(h),totalCollateral:l,totalDebt:c,reserves:d}}async hasBorrowPositions(e){let t=Je.fromAny(e),n=await this.client.getUserAccountData(t),[s,a]=n;return a>0n}async getHealthFactor(e){let t=Je.fromAny(e),n=await this.client.getUserAccountData(t),[s,a,i,r,o,l]=n,c=y.toDecimal(l,18);return Number(c)}async getHealthFactorAfterWithdraw(e,t,n){let{totalCollateral:s,totalDebt:a,reserves:i}=await this.getSummary(e),r=De.fromAssetId(t),o=i.find(d=>d.reserveAsset===r);if(!o)throw new Error("Missing reserve ctx for "+r);let{decimals:l,isCollateral:c,priceInRef:p,reserveLiquidationThreshold:g}=o,m=y.toBigInt(n,l),b=c?m*p/10n**BigInt(l):0n,h=s-b;return h<=0n?0:this.calculateHealthFactor(h,g,a)}async getHealthFactorAfterSupply(e,t,n){let{totalCollateral:s,totalDebt:a,reserves:i}=await this.getSummary(e),r=De.fromAssetId(t),o=i.find(h=>h.reserveAsset===r);if(!o)throw new Error("Missing reserve ctx for "+r);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:p}=o,m=y.toBigInt(n,l)*c/10n**BigInt(l),b=s+m;return b<=0n?0:this.calculateHealthFactor(b,p,a)}async getMaxWithdraw(e,t){let{totalCollateral:n,totalDebt:s,reserves:a}=await this.getSummary(e),i=De.fromAssetId(t),r=a.find(o=>o.reserveAsset===i);if(!r)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(r,n,s)}async getMaxWithdrawAll(e){let{totalCollateral:t,totalDebt:n,reserves:s}=await this.getSummary(e),a={};for(let i of s){let r=this.calculateWithdrawMax(i,t,n);i.reserveId&&(a[i.reserveId]=r)}return a}calculateHealthFactor(e,t,n){if(n===0n)return Bn;let s=10n**6n,a=y.toBigInt(t,18),i=e*a*s,r=n*Rn,o=i/r;return Number(o)/1e6}calculateRequiredCollateral(e,t,n){let s=y.toBigInt(e,18),a=y.toBigInt(t,18);return(s*n+a-1n)/a}calculateWithdrawMax(e,t,n){let{aTokenBalance:s,decimals:a,priceInRef:i,reserveLiquidationThreshold:r}=e,o=this.calculateRequiredCollateral(An,r,n),l=t-o;if(l<=0n)return{amount:0n,decimals:a};let c=l*10n**BigInt(a)/i;return{amount:s<c?s:c,decimals:a}}};var Bt={};x(Bt,{AssetClient:()=>$,BalanceClient:()=>q,ChainParams:()=>J});var $=class extends B{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async queryShares(){let t=await this.api.query.Stableswap.Pools.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[a]=n;return[a,s]}))}async queryBonds(){let t=await this.api.query.Bonds.Bonds.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[a]=n;return[a,s]}))}async queryAssets(){let t=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(t.filter(({value:n})=>{let{asset_type:s}=n;return this.SUPPORTED_TYPES.includes(s.type)}).map(({keyArgs:n,value:s})=>{let[a]=n;return[a,s]}))}async queryAssetLocations(){let t=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[a]=n;return[a,s]}))}async mapToken(e,t,n,s){let{name:a,asset_type:i,is_sufficient:r,existential_deposit:o}=t,{symbol:l,decimals:c}=n.get(e)??{};return{id:e,name:a?.asText(),symbol:l,decimals:c,icon:l,type:i.type,isSufficient:r,location:s,existentialDeposit:o}}async mapBond(e,t,n,s){let[a,i]=s,{asset_type:r,is_sufficient:o,existential_deposit:l}=t,{symbol:c,decimals:p}=await this.mapToken(a,t,n),g=Number(i),m=new Intl.DateTimeFormat("en-GB"),b=[c,"Bond",m.format(g)].join(" ");return{id:e,name:b,symbol:c+"b",decimals:p,icon:c,type:r.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:a,maturity:g}}async mapShares(e,t,n,s){let{assets:a}=s,{name:i,symbol:r,asset_type:o,is_sufficient:l,existential_deposit:c}=t,p=await Promise.all(a.map(async b=>{let{symbol:h}=await this.mapToken(b,t,n);return[b,h]})),g=Object.fromEntries(p),m=Object.values(g);return{id:e,name:m.join(", "),symbol:r?.asText()||i?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:g}}async mapExternal(e,t,n,s){let a=await this.mapToken(e,t,new Map,s),i=n?.find(r=>r.internalId===a.id);return i?{...a,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:a}parseMetadata(e){return new Map(Array.from(e,([t,n])=>[t,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(e,t){let[n,s,a,i]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),r=this.parseMetadata(n),o=[];for(let[l,c]of Array.from(n)){let p=s.get(l),{asset_type:g}=c,m;switch(g.type){case"Bond":let b=i.get(l);m=await this.mapBond(l,c,r,b);break;case"StableSwap":let h=a.get(l);m=await this.mapShares(l,c,r,h);break;case"External":m=await this.mapExternal(l,c,t,p);break;default:m=await this.mapToken(l,c,r,p)}o.push(m)}return e?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};import{Subject as Fn,bufferCount as kn,combineLatest as En,debounceTime as Cn,distinctUntilChanged as Ot,finalize as Dn,map as Q,pairwise as Mn,shareReplay as Ln,startWith as qn}from"rxjs";var q=class extends B{constructor(e){super(e)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getTokenBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:n}=await t.getValue(e);return this.calculateBalance(n)}async getTokenBalance(e,t){let s=await this.api.query.Tokens.Accounts.getValue(e,t);return this.calculateBalance(s)}calculateBalance(e){let t=e.free>=e.frozen?e.free-e.frozen:0n,n=e.free+e.reserved;return{free:e.free,reserved:e.reserved,frozen:e.frozen,total:n,transferable:t}}async getErc20Balance(e,t){return this.getTokenBalanceData(e,t)}subscribeBalance(e){let t=this.subscribeSystemBalance(e),n=this.subscribeTokensBalance(e),s=this.subscribeErc20Balance(e);return En([t,n,s]).pipe(Cn(250),Q(a=>a.flat()),qn([]),kn(2,1),Q(([a,i],r)=>{if(r===0)return i;let o=a.reduce((c,p)=>(c.set(p.id,p.balance),c),new Map);return i.filter(c=>!At(c.balance,o.get(c.id)))}))}subscribeSystemBalance(e){return this.api.query.System.Account.watchValue(e,"best").pipe(Q(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(e,t){return this.api.query.Tokens.Accounts.watchValue(e,t,"best").pipe(Q(s=>({id:t,balance:s})))}subscribeTokensBalance(e){return this.api.query.Tokens.Accounts.watchEntries(e,{at:"best"}).pipe(Ot((n,s)=>!s.deltas),Q(({deltas:n})=>{let s=[];return n?.deleted.forEach(a=>{let[i,r]=a.args;s.push({id:r,balance:this.calculateBalance({free:0n,reserved:0n,frozen:0n})})}),n?.upserted.forEach(a=>{let[i,r]=a.args;s.push({id:r,balance:this.calculateBalance(a.value)})}),s}))}subscribeErc20Balance(e,t){let n=new Fn,s=n.pipe(Ln(1)),a=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:c}=l;return c.type==="Erc20"}).map(({keyArgs:l})=>{let[c]=l;return c}),i=async()=>{let o=t||await a(),l=async()=>{let g=(await Promise.all(o.map(async m=>{let b=await this.getTokenBalanceData(e,m);return[m,b]}))).map(([m,b])=>({id:m,balance:b}));n.next(g)};await l();let c=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>c.unsubscribe()},r;return i().then(o=>r=o),s.pipe(Dn(()=>r?.()),Mn(),Q(([o,l],c)=>{if(c===0)return l;let p=o.reduce((m,b)=>(m.set(b.id,b.balance),m),new Map);return l.filter(m=>!At(m.balance,p.get(m.id)))}),Ot((o,l)=>l.length===0))}async getTokenBalanceData(e,t){let n=await this.api.apis.CurrenciesApi.account(t,e);return this.calculateBalance(n)}},At=(u,e)=>u!==void 0&&e!==void 0&&u.transferable===e.transferable&&u.total===e.total;var J=class extends B{_minOrderBudget;_blockTime;constructor(e){super(e)}async getBlockTime(){if(this._blockTime===void 0){let e=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(e)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var _t={};x(_t,{AssetNotFound:()=>Ze,PoolNotFound:()=>ue,RouteNotFound:()=>pe});var Ze=class extends Error{constructor(e){super(),this.message=`${e} not found`,this.name="AssetNotFound"}},ue=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},pe=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in current configuration`,this.name="RouteNotFound"}};var Lt={};x(Lt,{PoolContextProvider:()=>te,PoolError:()=>K,PoolFactory:()=>ee,PoolType:()=>O,aave:()=>at,lbp:()=>et,omni:()=>tt,stable:()=>nt,xyk:()=>st});var et={};x(et,{LbpMath:()=>L,LbpPool:()=>me,LbpPoolClient:()=>de});import{calculate_in_given_out as Nn,calculate_out_given_in as Hn,calculate_linear_weights as Gn,calculate_pool_trade_fee as Un,get_spot_price as Vn}from"@galacticcouncil/math-lbp";var L=class{static getSpotPrice(e,t,n,s,a){return Vn(e,t,n,s,a)}static calculateInGivenOut(e,t,n,s,a){return Nn(e,t,n,s,a)}static calculateOutGivenIn(e,t,n,s,a){return Hn(e,t,n,s,a)}static calculateLinearWeights(e,t,n,s,a){return Gn(e,t,n,s,a)}static calculatePoolTradeFee(e,t,n){return Un(e,t,n)}};var O=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a))(O||{}),K=(a=>(a.InsufficientTradingAmount="InsufficientTradingAmount",a.MaxInRatioExceeded="MaxInRatioExceeded",a.MaxOutRatioExceeded="MaxOutRatioExceeded",a.TradeNotAllowed="TradeNotAllowed",a.UnknownError="UnknownError",a))(K||{});var me=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,n,s,a,i,r){this.type="LBP",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a,this.fee=i,this.repayFeeApply=r}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),a=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,weightIn:s.weight,weightOut:a.weight}}validateAndBuy(e,t,n){let s=this.tokens[0].id,a=[];t<this.minTradingLimit&&a.push("InsufficientTradingAmount");let i=e.balanceOut/this.maxOutRatio;if(t>i&&a.push("MaxOutRatioExceeded"),s===e.assetOut){let r=this.calculateTradeFee(t,n),o=P.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=t+r,c=this.calculateInGivenOut(e,l),p=e.balanceIn/this.maxInRatio;return c>p&&a.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:o,errors:a}}else{let r=this.calculateInGivenOut(e,t),o=e.balanceIn/this.maxInRatio;return r>o&&a.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:a}}}validateAndSell(e,t,n){let s=this.tokens[0].id,a=[];t<this.minTradingLimit&&a.push("InsufficientTradingAmount");let i=e.balanceIn/this.maxInRatio;if(t>i&&a.push("MaxInRatioExceeded"),s===e.assetIn){let r=this.calculateOutGivenIn(e,t),o=e.balanceOut/this.maxOutRatio;return r>o&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:a}}else{let r=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(r,n),l=P.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),c=r-o,p=e.balanceOut/this.maxOutRatio;return c>p&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:l,errors:a}}}calculateInGivenOut(e,t){let n=L.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(e,t){let n=L.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(e){let t=L.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),this.maxOutRatio.toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=L.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),this.maxInRatio.toString());return BigInt(t)}calculateTradeFee(e,t){let n=L.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as $n}from"polkadot-api";import{map as Qn,of as Ct,switchMap as Jn}from"rxjs";import{memoize1 as Wn}from"@thi.ng/memoize";import{combineLatest as Rt,combineLatestAll as Xn,debounceTime as Yn,firstValueFrom as Kn,from as Ft,map as kt,mergeAll as jn,of as zn,switchMap as Et}from"rxjs";var E=class extends q{override=[];mem=0;memPools=Wn(e=>(this.log(this.getPoolType(),"mem pools",e,"\u2705"),this.loadPools()));constructor(e){super(e)}async withOverride(e){this.override=e||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let e=Ft(this.getPoolsMem()).pipe(Et(t=>this.subscribe(t)),Xn());return Kn(e)}getSubscriber(){return Ft(this.getPoolsMem()).pipe(Et(e=>this.subscribe(e)),jn())}subscribe(e){return e.filter(t=>this.hasValidAssets(t)).map(t=>Rt([this.subscribePoolChange(t),this.subscribePoolBalance(t)]).pipe(Yn(250),kt(([n,s])=>this.updatePool(n,s))))}subscribePoolBalance(e){if(e.type==="Aave")return zn([]);let t=[this.subscribeTokensBalance(e.address)];if(this.hasSystemAsset(e)){let n=this.subscribeSystemBalance(e.address);t.push(n)}if(this.hasErc20Asset(e)){let n=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),s=this.subscribeErc20Balance(e.address,n);t.push(s)}return Rt(t).pipe(kt(n=>n.map(s=>Array.isArray(s)?s:[s]).flat()))}hasSystemAsset(e){return e.tokens.some(t=>t.id===0)}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}hasValidAssets(e){return e.tokens.every(({id:t,decimals:n,balance:s})=>{let a=this.override.find(r=>r.id===t),i=!!n||!!a?.decimals;return s>0n&&i})}updatePool=(e,t)=>{let n=e.tokens.map(s=>{let a=t.find(r=>r.id===s.id),i=this.override.find(r=>r.id===s.id);return a?{...s,balance:a.balance.transferable,decimals:s.decimals||i?.decimals}:{...s,decimals:s.decimals||i?.decimals}});return{...e,tokens:n}}};var de=class extends E{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[e,t,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),s=t?.relay_parent_number||0,a=e.filter(({value:i})=>t&&this.isActivePool(i,s)).map(async({keyArgs:i,value:r})=>{let[o]=i,l=o.toString(),c=await this.getPoolDelta(l,r,s);return{address:l,type:"LBP",fee:r.fee,...c,...n}});return Promise.all(a)}async getPoolDelta(e,t,n){let{start:s,end:a,assets:i,initial_weight:r,final_weight:o,repay_target:l,fee_collector:c}=t,p=L.calculateLinearWeights(s?s.toString():"0",a?a.toString():"0",r.toString(),o.toString(),n.toString()),[g,m]=i,b=BigInt(p),h=this.MAX_FINAL_WEIGHT-BigInt(b),[d,f,T,S,v]=await Promise.all([this.isRepayFeeApplied(g,l,c.toString()),this.getBalance(e,g),this.api.query.AssetRegistry.Assets.getValue(g),this.getBalance(e,m),this.api.query.AssetRegistry.Assets.getValue(m)]);return{repayFeeApply:d,tokens:[{id:g,decimals:T?.decimals,existentialDeposit:T?.existential_deposit,balance:f.transferable,weight:b,type:T?.asset_type.type},{id:m,decimals:v?.decimals,existentialDeposit:v?.existential_deposit,balance:S.transferable,weight:h,type:v?.asset_type.type}]}}isActivePool(e,t){let{start:n,end:s}=e;return n&&s?t>=n&&t<s:!1}async isRepayFeeApplied(e,t,n){if(t===0n)return!1;try{return(await this.getBalance(n,e)).transferable<t}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(e){return{repayFee:await this.getRepayFee(),exchangeFee:e.fee}}getPoolType(){return"LBP"}async isSupported(){let e=this.api.query.LBP.PoolData,t=await this.api.compatibilityToken;return e.isCompatible($n.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(e.address);return n?t.watchValue("best").pipe(Jn(s=>s?this.getPoolDelta(e.address,n,s.relay_parent_number):Ct(e)),Qn(s=>Object.assign({},e,s))):Ct(e)}};var tt={};x(tt,{OmniMath:()=>w,OmniPool:()=>ge,OmniPoolClient:()=>be});import{calculate_in_given_out as Zn,calculate_lrna_in_given_out as es,calculate_out_given_in as ts,calculate_out_given_lrna_in as ns,calculate_spot_price as ss,calculate_lrna_spot_price as as,calculate_shares as rs,calculate_liquidity_out as is,calculate_liquidity_lrna_out as os,verify_asset_cap as ls,calculate_liquidity_hub_in as cs,is_sell_allowed as us,is_buy_allowed as ps,is_add_liquidity_allowed as ms,is_remove_liquidity_allowed as ds}from"@galacticcouncil/math-omnipool";import Z from"big.js";var w=class{static calculateSpotPrice(e,t,n,s){return ss(e,t,n,s)}static calculateLrnaSpotPrice(e,t){return as(e,t)}static calculateInGivenOut(e,t,n,s,a,i,r,o,l){return Zn(e,t,n,s,a,i,r,o,l)}static calculateLrnaInGivenOut(e,t,n,s,a){return es(e,t,n,s,a)}static calculateOutGivenIn(e,t,n,s,a,i,r,o,l){return ts(e,t,n,s,a,i,r,o,l)}static calculateOutGivenLrnaIn(e,t,n,s,a){return ns(e,t,n,s,a)}static calculateShares(e,t,n,s){return rs(e,t,n,s)}static calculateLiquidityOut(e,t,n,s,a,i,r,o){return is(e,t,n,s,a,i,r,o)}static calculateLiquidityLRNAOut(e,t,n,s,a,i,r,o){return os(e,t,n,s,a,i,r,o)}static calculateCapDifference(e,t,n,s){let a=Z(t),i=Z(e),r=Z(s),o=Z(n),l=Z(10).pow(18),c=o.div(l);if(a.div(r).lt(c)){let g=c.times(r).minus(a).times(i),m=a.times(Z(1).minus(c));return g.div(m).toFixed(0)}else return"0"}static verifyAssetCap(e,t,n,s){return ls(e,t,n,s)}static calculateLimitHubIn(e,t,n,s){return cs(e,t,n,s)}static isSellAllowed(e){return us(e)}static isBuyAllowed(e){return ps(e)}static isAddLiquidityAllowed(e){return ms(e)}static isRemoveLiquidityAllowed(e){return ds(e)}};var ge=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,n,s,a,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a,this.hubAssetId=i}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),a=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:a.hubReserves,sharesIn:s.shares,sharesOut:a.shares,decimalsIn:s.decimals,decimalsOut:a.decimals,balanceIn:s.balance,balanceOut:a.balance,tradeableIn:s.tradeable,tradeableOut:a.tradeable,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),a=this.calculateInGivenOut(e,t,n),i=s===0n?0:I.calculateDiffToRef(a,s),r=[],o=w.isSellAllowed(e.tradeableIn),l=w.isBuyAllowed(e.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetInEd)&&r.push("InsufficientTradingAmount");let c=e.balanceOut/this.maxOutRatio;t>c&&r.push("MaxOutRatioExceeded");let p=e.balanceIn/this.maxInRatio;return a>p&&r.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:t,feePct:i,errors:r}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),a=this.calculateOutGivenIn(e,t,n),i=I.calculateDiffToRef(s,a),r=[],o=w.isSellAllowed(e.tradeableIn),l=w.isBuyAllowed(e.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetOutEd)&&r.push("InsufficientTradingAmount");let c=e.balanceIn/this.maxInRatio;t>c&&r.push("MaxInRatioExceeded");let p=e.balanceOut/this.maxOutRatio;return a>p&&r.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:a,feePct:i,errors:r}}calculateInGivenOut(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,n);let s=w.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?P.toDecimals(n.assetFee).toString():"0",n?P.toDecimals(n.protocolFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateLrnaInGivenOut(e,t,n){let s=w.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?P.toDecimals(n.assetFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,n);let s=w.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?P.toDecimals(n.assetFee).toString():"0",n?P.toDecimals(n.protocolFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateOutGivenLrnaIn(e,t,n){let s=w.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?P.toDecimals(n.assetFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=w.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceLrnaInGivenOut(e){let t=w.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=w.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}spotPriceOutGivenLrnaIn(e){let t=w.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}};import{AccountId as gs,CompatibilityLevel as bs}from"polkadot-api";import{toHex as hs}from"@polkadot-api/utils";import{distinctUntilChanged as ys,map as Dt}from"rxjs";var be=class extends E{async loadPools(){let e=await this.api.constants.Omnipool.HubAssetId(),t=this.getPoolAddress(),[n,s,a,i,r]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(e),this.getBalance(t,e),this.getPoolLimits()]),o=n.map(async({keyArgs:c,value:p})=>{let[g]=c,{hub_reserve:m,shares:b,tradable:h,cap:d,protocol_shares:f}=p,[T,S]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(g),this.getBalance(t,g)]);return{id:g,decimals:T?.decimals,existentialDeposit:T?.existential_deposit,balance:S.transferable,cap:d,hubReserves:m,protocolShares:f,shares:b,tradeable:h,type:T?.asset_type.type}}),l=await Promise.all(o);return l.push({id:e,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:i.transferable,tradeable:s,type:a?.asset_type.type}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:l,...r}]}getPoolAddress(){let e="modlomnipool".padEnd(32,"\0"),t=new TextEncoder().encode(e),n=hs(t);return gs(63).dec(n)}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(e,t){let[n,s,a]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(t)]),i=n.min_fee+s.min_fee,r=n.max_fee+s.max_fee;if(a){let{asset_fee:o,protocol_fee:l}=a;return{assetFee:P.fromPermill(o),protocolFee:P.fromPermill(l),min:P.fromPermill(i),max:P.fromPermill(r)}}else return{assetFee:P.fromPermill(n.min_fee),protocolFee:P.fromPermill(s.min_fee),min:P.fromPermill(i),max:P.fromPermill(r)}}getPoolType(){return"Omnipool"}async isSupported(){let e=this.api.query.Omnipool.Assets,t=await this.api.compatibilityToken;return e.isCompatible(bs.BackwardsCompatible,t)}subscribePoolChange(e){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(ys((n,s)=>!s.deltas),Dt(({entries:n})=>n.map(s=>{let[a]=s.args,{hub_reserve:i,shares:r,tradable:o,cap:l,protocol_shares:c}=s.value,p=e.tokens.findIndex(m=>m.id===a);return{...e.tokens[p],cap:l,hubReserves:i,protocolShares:c,shares:r,tradeable:o}})),Dt(n=>{let s=e.tokens.find(a=>a.id===1);return{...e,tokens:[...n,s]}}))}};var nt={};x(nt,{StableMath:()=>A,StableSwap:()=>he,StableSwapClient:()=>ye});import{calculate_in_given_out as Ps,calculate_out_given_in as fs,calculate_amplification as Ts,calculate_add_one_asset as Ss,calculate_liquidity_out_one_asset as xs,calculate_shares as ws,calculate_shares_for_amount as Is,calculate_spot_price_with_fee as vs,pool_account_name as Os,recalculate_peg as As}from"@galacticcouncil/math-stableswap";var A=class{static getPoolAddress(e){return Os(e)}static defaultPegs(e){let t=[];for(let n=0;n<e;n++)t.push(["1","1"]);return t}static calculateAmplification(e,t,n,s,a){return Ts(e,t,n,s,a)}static calculateInGivenOut(e,t,n,s,a,i,r){return Ps(e,t,n,s,a,i,r)}static calculateAddOneAsset(e,t,n,s,a,i,r){return Ss(e,t,n,s,a,i,r)}static calculateSharesForAmount(e,t,n,s,a,i,r){return Is(e,t,n,s,a,i,r)}static calculateOutGivenIn(e,t,n,s,a,i,r){return fs(e,t,n,s,a,i,r)}static calculateLiquidityOutOneAsset(e,t,n,s,a,i,r){return xs(e,t,n,s,a,i,r)}static calculateShares(e,t,n,s,a,i){return ws(e,t,n,s,a,i)}static calculateSpotPriceWithFee(e,t,n,s,a,i,r,o){return vs(e,t,n,s,a,i,r,o)}static recalculatePegs(e,t,n,s,a){let i=As(e,t,n,s,a);return JSON.parse(i)}};var he=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,n,s,a,i,r,o,l){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a,this.amplification=i,this.id=r,this.fee=o,this.totalIssuance=l}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),a=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:a.tradeable,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),a=this.calculateInGivenOut(e,t,n),i=P.toPct(n.fee),r=[],o=w.isSellAllowed(e.tradeableIn),l=w.isBuyAllowed(e.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:a,calculatedIn:s,amountOut:t,feePct:i,errors:r}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),a=this.calculateOutGivenIn(e,t,n),i=P.toPct(n.fee),r=[],o=w.isSellAllowed(e.tradeableIn),l=w.isBuyAllowed(e.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:a,feePct:i,errors:r}}calculateIn(e,t,n){let s=A.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?P.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateAddOneAsset(e,t,n){let s=A.calculateAddOneAsset(this.getReserves(),t.toString(),Number(e.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?P.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateSharesForAmount(e,t,n){let s=A.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?P.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateInGivenOut(e,t,n){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,n):e.assetIn==this.id?this.calculateSharesForAmount(e,t,n):this.calculateIn(e,t,n)}spotPriceInGivenOut(e){let t=A.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetOut.toString(),e.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(e.assetOut==this.id)return BigInt(t);if(e.assetIn==this.id){let s=Math.pow(10,e.decimalsIn-e.decimalsOut);return BigInt(t)/BigInt(s)}let n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateOut(e,t,n){let s=A.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?P.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateWithdrawOneAsset(e,t,n){let s=A.calculateLiquidityOutOneAsset(this.getReserves(),t.toString(),Number(e.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?P.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateShares(e,t,n){let s=A.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification.toString(),this.totalIssuance.toString(),n?P.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(e,t,n){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,n):e.assetOut==this.id?this.calculateShares(e,t,n):this.calculateOut(e,t,n)}spotPriceOutGivenIn(e){let t=A.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetIn.toString(),e.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(e.assetIn==this.id)return BigInt(t);if(e.assetOut==this.id){let s=Math.pow(10,e.decimalsOut-e.decimalsIn);return BigInt(t)/BigInt(s)}let n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}getPegs(){let e=A.defaultPegs(this.tokens.length-1);return JSON.stringify(e)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:n,decimals:s})=>({asset_id:t,amount:n,decimals:s}));return JSON.stringify(e,X.jsonFormatter)}getAssets(e,t){let n={asset_id:Number(e),amount:t.toString()};return JSON.stringify([n],X.jsonFormatter)}};import{AccountId as Bs,CompatibilityLevel as _s}from"polkadot-api";import{toHex as Rs}from"@polkadot-api/utils";import{blake2b as Fs}from"@noble/hashes/blake2b";import{map as ks,of as Es,switchMap as Cs}from"rxjs";var Ds=340282366920938463463374607431768211455n,ye=class extends E{poolsData=new Map([]);async loadPools(){let[e,t,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),s=e.map(async({keyArgs:a,value:i})=>{let[r]=a,o=this.getPoolAddress(r),[l,c,p]=await Promise.all([this.getPoolDelta(r,i,t),this.getPoolTokens(r,i),this.getPoolPegs(r,i,t)]);return this.poolsData.set(o,i),{address:o,id:r,type:"Stableswap",fee:P.fromPermill(i.fee),tokens:c,...l,...p,...n}});return Promise.all(s)}async getPoolDelta(e,t,n){let{initial_amplification:s,final_amplification:a,initial_block:i,final_block:r}=t,o=A.calculateAmplification(s.toString(),a.toString(),i.toString(),r.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(e);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(e,t){let n=this.getPoolAddress(e),s=t.assets.map(async r=>{let[o,l,c]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(e,r),this.api.query.AssetRegistry.Assets.getValue(r),this.getBalance(n,r)]);return{id:r,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:c.transferable,tradeable:o,type:l?.asset_type.type}}),a=await Promise.all(s),i=await this.api.query.AssetRegistry.Assets.getValue(e);return a.push({id:e,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:Ds,tradeable:15,type:i?.asset_type.type}),a}async getPoolPegs(e,t,n){let s=await this.api.query.Stableswap.PoolPegs.getValue(e);if(!s)return this.getDefaultPegs(t);let a=await this.getLatestPegs(t,s,n),i=this.getRecentPegs(s),r=P.fromPermill(s.max_peg_update),o=P.fromPermill(t.fee),[l,c]=A.recalculatePegs(JSON.stringify(i),JSON.stringify(a),n.toString(),P.toDecimals(r).toString(),P.toDecimals(o).toString()),p=Number(l)*1e6;return{pegsFee:P.fromPermill(p),pegs:c}}getDefaultPegs(e){let t=e.fee,n=A.defaultPegs(e.assets.length);return{pegsFee:P.fromPermill(t),pegs:n}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([n,s])=>s.map(a=>a.toString()))}async getLatestPegs(e,t,n){let{source:s}=t,a=Array.from(e.assets.entries()).map(([r,o])=>o),i=s.map(async(r,o)=>{if(r.type==="Oracle"){let[l,c,p]=r.value,g=[p,a[o]].sort((T,S)=>T-S),m=await this.api.query.EmaOracle.Oracles.getValue(l,g,c);if(!m)return;let[{price:b,updated_at:h}]=m,d=b.n.toString(),f=b.d.toString();return p.toString()===g[0].toString()?[[d,f],h.toString()]:[[f,d],h.toString()]}else return[r.value.map(l=>l.toString()),n]});return Promise.all(i)}getPoolAddress(e){let t=A.getPoolAddress(e),n=Fs(t,{dkLen:32}),s=Rs(n);return Bs(63).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(e){return{fee:e.fee}}getPoolType(){return"Stableswap"}async isSupported(){let e=this.api.query.Stableswap.Pools,t=await this.api.compatibilityToken;return e.isCompatible(_s.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.System.Number,n=this.poolsData.get(e.address);return!n||!e.id?Es(e):t.watchValue("best").pipe(Cs(s=>this.getPoolDelta(e.id,n,s)),ks(s=>Object.assign({},e,s)))}};var st={};x(st,{XykMath:()=>G,XykPool:()=>Pe,XykPoolClient:()=>fe});import{calculate_in_given_out as Ms,calculate_out_given_in as Ls,calculate_pool_trade_fee as qs,get_spot_price as Ns,calculate_liquidity_in as Hs,calculate_shares as Gs,calculate_spot_price as Us,calculate_spot_price_with_fee as Vs,calculate_liquidity_out_asset_a as Ws,calculate_liquidity_out_asset_b as Xs}from"@galacticcouncil/math-xyk";var G=class{static getSpotPrice(e,t,n){return Ns(e,t,n)}static calculateInGivenOut(e,t,n){return Ms(e,t,n)}static calculateOutGivenIn(e,t,n){return Ls(e,t,n)}static calculatePoolTradeFee(e,t,n){return qs(e,t,n)}static calculateLiquidityIn(e,t,n){return Hs(e,t,n)}static calculateSpotPrice(e,t){return Us(e,t)}static calculateSpotPriceWithFee(e,t,n,s){return Vs(e,t,n,s)}static calculateShares(e,t,n){return Gs(e,t,n)}static calculateLiquidityOutAssetA(e,t,n,s){return Ws(e,t,n,s)}static calculateLiquidityOutAssetB(e,t,n,s){return Xs(e,t,n,s)}};var Pe=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,n,s,a){this.type="XYK",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),a=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:a.decimals,balanceIn:s.balance,balanceOut:a.balance,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),a=this.calculateTradeFee(s,n),i=P.toPct(n.exchangeFee),r=s+a,o=[];(t<this.minTradingLimit||s<e.assetInEd)&&o.push("InsufficientTradingAmount");let l=e.balanceOut/this.maxOutRatio;t>l&&o.push("MaxOutRatioExceeded");let c=e.balanceIn/this.maxInRatio;return r>c&&o.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:t,feePct:i,errors:o}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(s,n),i=P.toPct(n.exchangeFee),r=s-a,o=[];(t<this.minTradingLimit||s<e.assetOutEd)&&o.push("InsufficientTradingAmount");let l=e.balanceIn/this.maxInRatio;t>l&&o.push("MaxInRatioExceeded");let c=e.balanceOut/this.maxOutRatio;return r>c&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:r,feePct:i,errors:o}}calculateInGivenOut(e,t){let n=G.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(e,t){let n=G.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(e){let t=G.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){let t=G.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateTradeFee(e,t){let n=G.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as Ys}from"polkadot-api";import{of as Ks}from"rxjs";var fe=class extends E{async loadPools(){let e=this.api.query.XYK.PoolAssets,[t,n]=await Promise.all([e.getEntries(),this.getPoolLimits()]),s=t.map(async({keyArgs:a,value:i})=>{let[r]=a,[o,l]=i,[c,p,g,m]=await Promise.all([this.getBalance(r,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(r,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:r,type:"XYK",tokens:[{id:o,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:c.transferable,type:p?.asset_type.type},{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:g.transferable,type:m?.asset_type.type}],...n}});return Promise.all(s)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let e=this.api.query.XYK.PoolAssets,t=await this.api.compatibilityToken;return e.isCompatible(Ys.BackwardsCompatible,t)}subscribePoolChange(e){return Ks(e)}};var at={};x(at,{AavePool:()=>Te,AavePoolClient:()=>Se});var Te=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,n,s,a){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),a=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),a=[];return t>e.balanceOut&&a.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:a}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),a=[];return s>e.balanceOut&&a.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:a}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){let t=Math.pow(10,e.decimalsOut);return BigInt(t)}spotPriceOutGivenIn(e){let t=Math.pow(10,e.decimalsIn);return BigInt(t)}calculateTradeFee(e,t){return 0n}};import{AccountId as js}from"polkadot-api";import{toHex as zs}from"@polkadot-api/utils";import{map as $s,merge as Qs,switchMap as Js}from"rxjs";import{decodeEventLog as Zs}from"viem";var Mt=[{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:ea}=j,ta=["Supply","Withdraw","Repay","Borrow"],Se=class extends E{async loadPools(){let t=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:s,liqudity_in:a,liqudity_out:i})=>{let[r,o,l,c]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(n,s),type:"Aave",tokens:[{id:n,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:a,location:o,type:r?.asset_type.type},{id:s,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:i,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolDelta(e){let[t,n]=e.tokens,{liqudity_in:s,liqudity_out:a}=await this.api.apis.AaveTradeExecutor.pool(t.id,n.id);return e.tokens.map(i=>{let r=i.id===t.id?s:a;return{...i,balance:r}})}getPoolId(e,t){let n=e+"/"+t,s=new TextEncoder().encode(n.padEnd(32,"\0")),a=zs(s);return js(63).dec(a)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(e){let[t,n]=e.tokens,s=this.getReserveH160Id(t),a=this.api.event.Router.Executed.watch(({asset_in:r,asset_out:o})=>r===n.id||o===n.id),i=this.api.event.EVM.Log.watch(({log:r})=>{let{topics:o,data:l}=r,c=o.map(b=>b.asHex()),p=l.asHex(),{eventName:g,args:m}=Zs({abi:Mt,topics:c,data:p});return ta.includes(g)&&m.reserve.toLowerCase()===s.toLowerCase()});return Qs([a,i]).pipe(Js(()=>this.getPoolDelta(e)),$s(r=>({...e,tokens:[...r]})))}getReserveH160Id(e){return e.type==="Erc20"?X.findNestedKey(e.location,"AccountKey20").AccountKey20.key:ea.fromAssetId(e.id)}};var ee=class{static get(e){switch(e.type){case"Aave":return Te.fromPool(e);case"XYK":return Pe.fromPool(e);case"Omnipool":return ge.fromPool(e);case"LBP":return me.fromPool(e);case"Stableswap":return he.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{Subject as na,Subscription as xe,takeUntil as sa}from"rxjs";var te=class extends B{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=xe.EMPTY;omniSub=xe.EMPTY;stableSub=xe.EMPTY;xykSub=xe.EMPTY;aaveSub=xe.EMPTY;isReady=!1;isDestroyed=new na;constructor(e){super(e),this.lbpClient=new de(e),this.omniClient=new be(e),this.stableClient=new ye(e),this.xykClient=new fe(e),this.aaveClient=new Se(e),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(e){return e.getSubscriber().pipe(sa(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(e){return this.xykClient.withOverride(e),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(e={}){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let{useOnly:t=[],exclude:n=[]}=e,s=new Set(t),a=new Set(n),i=async r=>{let o=r.getPoolType();return s.size>0?s.has(o):a.size>0?!a.has(o):r.isSupported()};return this.getFilteredPools(i)}async getFilteredPools(e){let t=await Promise.all(this.clients.map(e)),n=this.clients.filter((a,i)=>t[i]);return(await Promise.all(n.map(a=>a.getPoolsMem()))).flat()}async getPoolFees(e,t){let n=this.clients.find(s=>s.getPoolType()===e.type);if(n)return n.getPoolFees(e,t);throw new ue(e.type)}};var Gt={};x(Gt,{DEFAULT_BLOCK_TIME:()=>qt,DEFAULT_MIN_BUDGET:()=>ot,ORDER_MIN_BLOCK_PERIOD:()=>Nt,Router:()=>ne,TWAP_BLOCK_PERIOD:()=>Oe,TWAP_MAX_DURATION:()=>ct,TWAP_MAX_PRICE_IMPACT:()=>lt,TWAP_TX_MULTIPLIER:()=>Fc,TradeOrderError:()=>it,TradeOrderType:()=>Le,TradeRouteBuilder:()=>C,TradeRouter:()=>se,TradeScheduler:()=>ae,TradeType:()=>Me});var we=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var aa=8,Ie=class{isNotVisited(e,t){let n=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(n=!1)}),n}findPaths(e,t,n){let s=[],a=new we,i=[];for(i.push([t,""]),a.enqueue(i);a.size()>0;){let r=a.dequeue();if(!r||r.length>aa)continue;let o=r[r.length-1];(n===null||o[0]===n)&&s.push(r),e.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,r)){let p=[...r];p.push(c),a.enqueue(p)}})}return s}findShortestPaths(e,t,n){let s=[],a=new we,i=[];i.push([t,""]),a.enqueue(i);let r=1/0;for(;a.size()>0;){let o=a.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===n){o.length<r?(r=o.length,s.length=0,s.push(o)):o.length===r&&s.push(o);continue}let c=e.get(l[0]);for(let p of c??[])this.isNotVisited(p,o)&&a.enqueue([...o,p])}return s}buildAndPopulateGraph(e,t){let n=new Map;for(let s of e)n.set(parseInt(s),[]);for(let[s,a,i]of t)n.get(a)?.push([i,s]);return n}};function rt(u){let e={};for(let t of u){let n=t.tokens.length;for(let s=0;s<n;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let a=0;a<n;a++){if(s==a)continue;let i=[t.address,t.tokens[s].id,t.tokens[a].id];e[t.tokens[s].id].push(i)}}}return e}var ve=class{getProposals(e,t,n){let s=n.filter(d=>d.type==="XYK"),a=n.filter(d=>d.type!=="XYK"),i=new Set(a.map(d=>d.tokens).flat().map(d=>d.id)),r=i.has(e),o=i.has(t),l=new Ie,c=d=>{let f=rt(d),T=Object.keys(f),S=T.flatMap(v=>f[v]);return l.buildAndPopulateGraph(T,S)};if(!r&&!o){let d=s.filter(S=>S.tokens.find(v=>v.id===e)||S.tokens.find(v=>v.id===t)),f=c(d),T=l.findPaths(f,e,t);return this.parsePaths(T)}if(r&&o){let d=c(a),f=l.findPaths(d,e,t);return this.parsePaths(f)}let p=r?t:e,g=s.filter(d=>d.tokens.some(f=>f.id===p));if(g.length===0)return[];let m=[...a,...g],b=c(m),h=l.findPaths(b,e,t);return this.parsePaths(h)}parsePaths(e){let t=[];for(let n of e){let s=[];for(let a=0;a<n.length;a++){let i=n[a],r=n[a+1];if(r==null)break;s.push(this.toEdge(i,r))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0],t[0]]}};var ne=class{routeSuggester;routeProposals;routerOptions;ctx;constructor(e,t={}){this.ctx=e,this.routeSuggester=new ve,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}buildRouteKey(e,t,n){return`${e}->${t}::${n.length}`}async getPools(){return this.ctx.getPools(this.routerOptions)}async getRoutes(e,t){let n=await this.getPools();return this.validateInput(e,t,n),this.getPaths(e,t,n)}async getTradeableAssets(){let e=await this.getPools(),t=this.getAssets(e);return Array.from(t)}async getRouteableAssets(e){let t=await this.getTradeableAssets();return(await Promise.all(t.filter(s=>s!==e).map(s=>this.getRoutes(s,e)))).filter(s=>s.length>0).map(([s])=>s[0].assetIn).sort()}validateInput(e,t,n){if(n.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(n);if(!s.has(e))throw new Error(e+" is not supported asset");if(!s.has(t))throw new Error(t+" is not supported asset");return this.toPoolsMap(n)}getAssets(e){let t=e.map(n=>n.tokens.map(s=>s.id)).flat().sort((n,s)=>n>s?1:-1);return new Set(t)}getPaths(e,t,n){let s=this.toPoolsMap(n);return this.getProposals(e,t,n).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}getProposals(e,t,n){let s=this.buildRouteKey(e,t,n);if(this.routeProposals.has(s))return this.routeProposals.get(s);let a=this.routeSuggester.getProposals(e,t,n);return this.routeProposals.set(s,a),a}validPath(e,t){return e.length>0&&e.map(n=>this.validEdge(n,t)).reduce((n,s)=>n&&s)}validEdge([e,t,n],s){return s.get(e)?.validatePair(t,n)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,ee.get(t)]))}toHops(e,t){return e.map(([n,s,a])=>{let i=t.get(n);return{poolAddress:n,poolId:i?.id,pool:i?.type,assetIn:s,assetOut:a}})}};var Me=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Me||{}),Le=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Le||{}),it=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(it||{});var se=class extends ne{mlr;poolsSnapshot;constructor(e,t={}){super(e,t),this.mlr=new Map}buildCtxSync(e,t){let n=this.poolsSnapshot,s=super.validateInput(e,t,n),a=super.getPaths(e,t,n);if(!a.length)throw new pe(e,t);return{paths:a,pools:n,poolsMap:s}}async withCtx(e,t,n){this.poolsSnapshot||(this.poolsSnapshot=await super.getPools());let s=this.buildCtxSync(e,t);return n(s)}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((n,s)=>{let a=n[n.length-1].amountOut,i=s[s.length-1].amountOut;return a>i?-1:1});return t.find(n=>n.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(n=>n.tradeFeeRange).length>0){let n=e.map(a=>a.tradeFeeRange?.[0]??a.tradeFeePct).reduce((a,i)=>a+i),s=e.map(a=>a.tradeFeeRange?.[1]??a.tradeFeePct).reduce((a,i)=>a+i);return[n,s]}}getPoolFeeRange(e){let t=e.min?P.toPct(e.min):void 0,n=e.max?P.toPct(e.max):void 0;if(t&&n)return[t,n]}async getBestSell(e,t,n){return this.getSell(e,t,n)}getSellSpot(e){let t=e[e.length-1];if(e.length===1)return t.spotPrice;let n=e.map(r=>r.assetOutDecimals).reduce((r,o)=>r+o),s=e.map(r=>r.spotPrice).reduce((r,o)=>r*o),a=n-t.assetOutDecimals,i=Math.pow(10,a);return s/BigInt(i)}async getSell(e,t,n,s){return this.withCtx(e,t,async({paths:a,poolsMap:i})=>{let r;if(s)r=await this.toSellSwaps(n,s,i);else{let o=a.map(c=>this.toSellSwaps(n,c,i)),l=await Promise.all(o);r=this.findBestSellRoute(l)}return this.buildSell(i,r)})}buildSell(e,t){let n=t[0],s=t[t.length-1],a=this.isDirectTrade(t),i=this.getSellSpot(t),r=s.amountOut,o=a?s.calculatedOut:this.calculateDelta0Y(n.amountIn,t,e),l=o-r,c=this.getRouteFeeRange(t),p=a?s.tradeFeePct:I.calculateSellFee(o,r),g=Math.pow(10,n.assetInDecimals),m=n.amountIn*i/BigInt(g),b=I.calculateDiffToRef(o,m);return{type:"Sell",amountIn:n.amountIn,amountOut:s.amountOut,spotPrice:i,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:t,toHuman(){return{type:"Sell",amountIn:y.toDecimal(n.amountIn,n.assetInDecimals),amountOut:y.toDecimal(s.amountOut,s.assetOutDecimals),spotPrice:y.toDecimal(i,s.assetOutDecimals),tradeFee:y.toDecimal(l,s.assetOutDecimals),tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:t.map(h=>h.toHuman())}}}}calculateDelta0Y(e,t,n){let s=[];for(let a=0;a<t.length;a++){let i=t[a],r=n.get(i.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(i.assetIn,i.assetOut),l;a>0?l=s[a-1]:l=e;let c=r.calculateOutGivenIn(o,l);s.push(c)}return s[s.length-1]}async calculateMostLiquidRoute(e,t,n){let{paths:s,pools:a,poolsMap:i}=n,l=a.filter(h=>h.tokens.some(d=>d.id===e)).map(h=>h.type==="Aave"?h.tokens:h.tokens.filter(d=>d.id===e)).map(h=>h.map(d=>d.balance).reduce((d,f)=>d+f)).sort((h,d)=>d<h?-1:1)[0],c=I.getFraction(l,.1),p=await Promise.all(s.map(h=>this.toSellSwaps(c,h,i))),m=this.findBestSellRoute(p).map(h=>({poolAddress:h.poolAddress,poolId:h?.poolId,pool:h.pool,assetIn:h.assetIn,assetOut:h.assetOut})),b=this.buildRouteKey(e,t,a);return this.mlr.set(b,m),m}async toSellSwaps(e,t,n){let s=[];for(let a=0;a<t.length;a++){let i=t[a],r=n.get(i.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(i.assetIn,i.assetOut),l;a>0?l=s[a-1].amountOut:l=typeof e=="string"?y.toBigInt(e,o.decimalsIn):e;let c=await this.ctx.getPoolFees(r,o.assetOut),{amountOut:p,calculatedOut:g,feePct:m,errors:b}=r.validateAndSell(o,l,c),h=this.getPoolFeeRange(c),d=r.spotPriceOutGivenIn(o),f=Math.pow(10,o.decimalsIn),T=l*d/BigInt(f),S=I.calculateDiffToRef(g,T);s.push({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:g,spotPrice:d,tradeFeePct:m,tradeFeeRange:h,priceImpactPct:S,errors:b,isSupply(){return r.type==="Aave"&&r.tokens[0].id===i.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:y.toDecimal(l,o.decimalsIn),amountOut:y.toDecimal(p,o.decimalsOut),calculatedOut:y.toDecimal(g,o.decimalsOut),spotPrice:y.toDecimal(d,o.decimalsOut),tradeFeePct:m,tradeFeeRange:h,priceImpactPct:S,errors:b}}})}return s}async getMostLiquidRoute(e,t){return this.withCtx(e,t,async n=>{let s=this.buildRouteKey(e,t,n.pools),a=this.mlr.get(s);return a||this.calculateMostLiquidRoute(e,t,n)})}async getSpotPrice(e,t){return this.withCtx(e,t,async n=>{let{pools:s,poolsMap:a}=n,i=this.buildRouteKey(e,t,s),r=this.mlr.get(i);r||(r=await this.calculateMostLiquidRoute(e,t,n));let o=await this.toSellSwaps("1",r,a),l=this.getSellSpot(o),c=o[o.length-1].assetOutDecimals;return{amount:l,decimals:c}})}findBestBuyRoute(e){let t=e.sort((n,s)=>{let a=n[0].amountIn,i=s[0].amountIn;return a>i?1:-1});return t.find(n=>n.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,n){return this.getBuy(e,t,n)}getBuySpot(e){let t=e[0];if(e.length===1)return t.spotPrice;let n=e.map(r=>r.assetInDecimals).reduce((r,o)=>r+o),s=e.map(r=>r.spotPrice).reduce((r,o)=>r*o),a=n-t.assetInDecimals,i=Math.pow(10,a);return s/BigInt(i)}async getBuy(e,t,n,s){return this.withCtx(e,t,async({paths:a,poolsMap:i})=>{let r;if(s)r=await this.toBuySwaps(n,s,i);else{let o=a.map(c=>this.toBuySwaps(n,c,i)),l=await Promise.all(o);r=this.findBestBuyRoute(l)}return this.buildBuy(i,r)})}buildBuy(e,t){let n=t[t.length-1],s=t[0],a=this.isDirectTrade(t),i=this.getBuySpot(t),r=s.amountIn,o=a?s.calculatedIn:this.calculateDelta0X(n.amountOut,t,e),l=r-o,c=this.getRouteFeeRange(t),p=a?s.tradeFeePct:I.calculateBuyFee(o,r),g=Math.pow(10,n.assetOutDecimals),m=n.amountOut*i/BigInt(g),b;return o===0n?b=-100:b=I.calculateDiffToRef(m,o),{type:"Buy",amountOut:n.amountOut,amountIn:s.amountIn,spotPrice:i,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:t,toHuman(){return{type:"Buy",amountOut:y.toDecimal(n.amountOut,n.assetOutDecimals),amountIn:y.toDecimal(s.amountIn,s.assetInDecimals),spotPrice:y.toDecimal(i,s.assetInDecimals),tradeFee:y.toDecimal(l,s.assetInDecimals),tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:t.map(h=>h.toHuman())}}}}calculateDelta0X(e,t,n){let s=[];for(let a=t.length-1;a>=0;a--){let i=t[a],r=n.get(i.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(i.assetIn,i.assetOut),l;a==t.length-1?l=e:l=s[0];let c=r.calculateInGivenOut(o,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,n){let s=[];for(let a=t.length-1;a>=0;a--){let i=t[a],r=n.get(i.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(i.assetIn,i.assetOut),l;a==t.length-1?l=typeof e=="string"?y.toBigInt(e,o.decimalsOut):e:l=s[0].amountIn;let c=await this.ctx.getPoolFees(r,o.assetOut),{amountIn:p,calculatedIn:g,feePct:m,errors:b}=r.validateAndBuy(o,l,c),h=this.getPoolFeeRange(c),d=r.spotPriceInGivenOut(o),f=Math.pow(10,o.decimalsOut),T=l*d/BigInt(f),S;g===0n?S=-100:S=I.calculateDiffToRef(T,g),s.unshift({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:g,spotPrice:d,tradeFeePct:m,tradeFeeRange:h,priceImpactPct:S,errors:b,isSupply(){return r.type==="Aave"&&r.tokens[0].id===i.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:y.toDecimal(l,o.decimalsOut),amountIn:y.toDecimal(p,o.decimalsIn),calculatedIn:y.toDecimal(g,o.decimalsIn),spotPrice:y.toDecimal(d,o.decimalsIn),tradeFeePct:m,tradeFeeRange:h,priceImpactPct:S,errors:b}}})}return s}};var qt=6e3,ot=1000000000000000n,Oe=6,lt=-5,ct=216e5,Fc=3,Nt=6;import{Enum as Ht}from"polkadot-api";var C=class{static build(e){return e.map(({assetIn:t,assetOut:n,pool:s,poolId:a})=>s==="Stableswap"?{pool:Ht("Stableswap",a),asset_in:t,asset_out:n}:{pool:Ht(s),asset_in:t,asset_out:n})}};var ae=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??6e3,minBudgetInNative:t.minBudgetInNative??ot})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,n,s,a){let[i,r]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:o,swaps:l,priceImpactPct:c}=r,p=l[0],g=l[l.length-1],{assetInDecimals:m}=p,{assetOutDecimals:b}=g,h=Math.abs(c),d=this.getMinimumTradeCount(o,i),f=this.getOptimalTradeCount(h),T=a?Math.round(s/a):f,S=Math.ceil(s/d),v=Math.round(s/f),D=Math.round(s/T),N=o/BigInt(T),_=await this.router.getBestSell(e,t,N),U=o<i,_e=[];U&&_e.push("OrderTooSmall");let Re=_.amountOut*BigInt(T),He=this.toBlockPeriod(D),Ge=_.tradeFee*BigInt(T),zt=C.build(l),pt={assetIn:e,assetOut:t,errors:_e,frequencyMin:S,frequencyOpt:v,frequency:D,tradeCount:T,tradeFee:Ge,tradeImpactPct:_.priceImpactPct,tradePeriod:He,tradeRoute:zt,type:"Dca"};return{...pt,amountIn:o,amountOut:Re,tradeAmountIn:_.amountIn,tradeAmountOut:_.amountOut,toHuman(){return{...pt,amountIn:y.toDecimal(o,m),amountOut:y.toDecimal(Re,b),tradeAmountIn:y.toDecimal(_.amountIn,m),tradeAmountOut:y.toDecimal(_.amountOut,b)}}}}async getMinimumOrderBudget(e){if(0===e)return this.minOrderBudget;let t=await this.router.getSpotPrice(0,e),n=10n**BigInt(12);if(t)return this.minOrderBudget*t.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let n=t*2n/10n;if(n===0n)return 0;let s=e+n/2n;return Number(s/n)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,n){let[s,a]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:i,swaps:r,priceImpactPct:o}=a,l=r[0],c=r[r.length-1],{assetInDecimals:p}=l,{assetOutDecimals:g}=c,m=Math.abs(o),b=this.getTwapTradeCount(m),h=i/BigInt(b),d=await this.router.getBestSell(l.assetIn,c.assetOut,h),f=b===1,T=i<s,S=d.priceImpactPct<-5,v=[];T||f?v.push("OrderTooSmall"):S&&v.push("OrderImpactTooBig");let D=d.amountOut*BigInt(b),N=d.tradeFee*BigInt(b),_=C.build(r),U={assetIn:e,assetOut:t,errors:v,tradeCount:b,tradeImpactPct:d.priceImpactPct,tradePeriod:6,tradeRoute:_,type:"TwapSell"};return{...U,amountIn:i,amountOut:D,tradeAmountIn:d.amountIn,tradeAmountOut:d.amountOut,tradeFee:N,toHuman(){return{...U,amountIn:y.toDecimal(i,p),amountOut:y.toDecimal(D,g),tradeAmountIn:y.toDecimal(d.amountIn,p),tradeAmountOut:y.toDecimal(d.amountOut,g),tradeFee:y.toDecimal(N,g)}}}}async getTwapBuyOrder(e,t,n){let[s,a]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,n)]),{amountOut:i,swaps:r,priceImpactPct:o}=a,l=r[0],c=r[r.length-1],{assetInDecimals:p}=l,{assetOutDecimals:g}=c,m=Math.abs(o),b=this.getTwapTradeCount(m),h=i/BigInt(b),d=await this.router.getBestBuy(l.assetIn,c.assetOut,h),f=d.amountIn*BigInt(b),T=b===1,S=f<s,v=d.priceImpactPct<-5,D=[];S||T?D.push("OrderTooSmall"):v&&D.push("OrderImpactTooBig");let N=d.tradeFee*BigInt(b),_=C.build(r),U={assetIn:e,assetOut:t,errors:D,tradeCount:b,tradeImpactPct:d.priceImpactPct,tradePeriod:6,tradeRoute:_,type:"TwapBuy"};return{...U,amountIn:f,amountOut:i,tradeAmountIn:d.amountIn,tradeAmountOut:d.amountOut,tradeFee:N,toHuman(){return{...U,amountIn:y.toDecimal(f,p),amountOut:y.toDecimal(i,g),tradeAmountIn:y.toDecimal(d.amountIn,p),tradeAmountOut:y.toDecimal(d.amountOut,g),tradeFee:y.toDecimal(N,p)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}return t}getTwapExecutionTime(e){return e*6*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,n=Math.round(t);return Math.max(n,6)}};var Xt={};x(Xt,{BIG_10:()=>Vt,BIG_BILL:()=>Wt,StakingApi:()=>Ae,StakingClient:()=>Be});import{encodeAddress as ra}from"@polkadot/util-crypto";import{stringToU8a as ia}from"@polkadot/util";import{calculate_accumulated_rps as oa,calculate_period_number as Ut,calculate_rewards as la}from"@galacticcouncil/math-staking";import re from"big.js";var Vt=re(10),Wt=re(Vt.pow(12));function ca(u){return ra(ia(("modl"+u).padEnd(32,"\0")),63)}var Ae=class{client;balanceClient;constructor(e,t){this.client=e,this.balanceClient=t}async getTransferablePotBalance(){let e=await this.client.getPalletId(),t=ca(e);return(await this.balanceClient.getBalance(t,0)).transferable}async getStakingPosition(e){let[t,n]=await Promise.all([this.client.getStakingPositionsValue(e),this.client.getStakingVotes(e)]),s=t?.created_at,a=await n.reduce(async(i,[r,o])=>{let l=await i,c=r,p=o.amount,g=o.conviction.toString(),m=await this.client.getReferendumInfo(c);return m&&(m.type==="Approved"||m.type==="Rejected")&&l.push({id:c,amount:p,conviction:g}),l},Promise.resolve([]));return{stake:t?.stake,rewardPerStake:t?.reward_per_stake,createdAt:s,actionPoints:t?.action_points,accumulatedUnpaidRewards:t?.accumulated_unpaid_rewards,accumulatedSlashPoints:t?.accumulated_slash_points,accumulatedLockedRewards:t?.accumulated_locked_rewards,votes:a}}async getStake(e){let t=await this.client.getNFTCollectionId(),[n,s]=await Promise.all([this.client.getStaking(),this.client.getUniques(e,t)]),a=s.find(i=>i)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:a,stakePosition:a?await this.getStakingPosition(a):void 0}}async getRewards(e,t){let n=await this.getStake(e),{potReservedBalance:s,accumulatedRewardPerStake:a,totalStake:i,stakePosition:r}=n;if(!r)return;let[o,l,c,p]=await Promise.all([this.getTransferablePotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getSixBlockSince()]),g=re(o.toString()).minus(s.toString()),m=a.toString(),b=re(t).plus(1).toString();g.gt(0)&&i>0&&(m=oa(a.toString(),g.toString(),i.toString()));let h=Ut(l.toString(),t,p??b),d=Ut(l.toString(),r.createdAt?.toString()??"",p??b),f=la(m,r.rewardPerStake?.toString()??"",r.stake?.toString()??""),T=re(f).plus(r.accumulatedUnpaidRewards?.toString()||"0").plus(r.accumulatedLockedRewards?.toString()||"0");if(!re(h).minus(d).lte(c.toString()))return T.div(Wt).toString()}};var Be=class extends B{async getPalletId(){let e=this.api.constants.Staking.PalletId;return(await e()).asText()}async getPeriodLength(){let e=this.api.constants.Staking.PeriodLength;return await e()}async getUnclaimablePeriods(){let e=this.api.constants.Staking.UnclaimablePeriods;return await e()}async getNFTCollectionId(){let e=this.api.constants.Staking.NFTCollectionId;return await e()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(e,t){return(await this.api.query.Uniques.Account.getEntries(e,t)).map(({keyArgs:i})=>{let[r,o,l]=i;return{address:r,collectionId:o,itemId:l}})}async getStakingPositionsValue(e){return await this.api.query.Staking.Positions.getValue(e)}async getStakingVotes(e){return await this.api.query.Staking.Votes.getValue(e)}async getReferendumInfo(e){return await this.api.query.Referenda.ReferendumInfoFor.getValue(e)}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var jt={};x(jt,{TxBuilderFactory:()=>oe});import{Enum as Kt}from"polkadot-api";function Yt(u){let e=[],t=u;for(;t&&typeof t=="object"&&"type"in t;)e.push(t.type),t=t.value;return e.join(".")}var ie=class extends B{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new R,this.balanceClient=new q(e),this.aaveUtils=new Y(this.evmClient)}wrapTx(e,t){return{name:e,get:()=>t,dryRun:n=>this.dryRun(n,t)}}async dispatchWithExtraGas(e){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:e.decodedCall,extra_gas:We})}async dryRun(e,t){let n=Kt("Signed",e),s=Kt("system",n),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,t.decodedCall),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let o=Yt(r.value);throw new Error("Dry run execution error!",{cause:o})}return i}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var qe=class extends ie{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:s}=t[0],a=await this.balanceClient.getBalance(this.beneficiary,s);return e>=a.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:e,amountOut:t,swaps:n}=this.trade,s=n[0],a=n[n.length-1],i=I.getFraction(e,this.slippagePct),r=s.assetIn,o=a.assetOut,l=e+i,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.buy({asset_in:r,asset_out:o,amount:t,max_sell_amount:l}):c=this.api.tx.Router.buy({asset_in:r,asset_out:o,amount_out:t,max_amount_in:l,route:C.build(n)}),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:n}=this.trade,s=n[0],a=n[n.length-1],i=I.getFraction(t,this.slippagePct),r=s.assetIn,o=a.assetOut,l=t-i,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.sell({asset_in:r,asset_out:o,amount:e,min_buy_amount:l}):c=this.api.tx.Router.sell({asset_in:r,asset_out:o,amount_in:e,min_amount_out:l,route:C.build(n)}),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,n=t[0],s=t[t.length-1],a=I.getFraction(e,this.slippagePct),i=n.assetIn,r=s.assetOut,o=e-a,l=this.api.tx.Router.sell_all({asset_in:i,asset_out:r,min_amount_out:o,route:C.build(t)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as ut}from"polkadot-api";var Ne=class extends ie{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:s,tradePeriod:a,tradeRoute:i}=this.order,r=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:a,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ut("Sell",{asset_in:t,asset_out:n,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",r)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:s,tradeAmountOut:a,tradePeriod:i,tradeRoute:r}=this.order,o=I.getFraction(a,this.slippagePct),l=a-o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ut("Sell",{asset_in:t,asset_out:n,amount_in:s,min_amount_out:l,route:r})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:s,tradeAmountOut:a,tradePeriod:i,tradeRoute:r}=this.order,o=I.getFraction(s,this.slippagePct),l=s+o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ut("Buy",{asset_in:t,asset_out:n,amount_out:a,max_amount_in:l,route:r})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",c)}};var oe=class{client;evmClient;constructor(e,t){this.client=e,this.evmClient=t??new R}trade(e){return new qe(this.client,this.evmClient).setTrade(e)}order(e){return new Ne(this.client,this.evmClient).setOrder(e)}};async function Gu(u,e){let t=new J(u),[n,s]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),a=e??new R,i=new te(u).withAave().withOmnipool().withStableswap().withXyk(),r=new Y(a),o=new se(i),l=new ae(o,{blockTime:n,minBudgetInNative:s}),c=new q(u),p=new Be(u),g=new Ae(p,c);return{api:{aave:r,router:o,scheduler:l,staking:g},client:{asset:new $(u),balance:c,evm:a},ctx:{pool:i},tx:new oe(u,a),destroy:()=>{i.destroy()}}}export{vt as aave,dt as api,y as big,Bt as client,ft as const,Gu as createSdkContext,j as erc20,_t as error,yt as evm,P as fmt,Ce as h160,X as json,I as math,Lt as pool,Gt as sor,Xt as staking,jt as tx,It as xc};
|
|
1
|
+
var rn=Object.defineProperty;var S=(u,t)=>{for(var e in t)rn(u,e,{get:t[e],enumerable:!0})};var Se={};S(Se,{Papi:()=>B,getWs:()=>un});import{hydration as on}from"@galacticcouncil/descriptors";function Te(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var B=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(on)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Te(n)&&console.log(t,...e)}};import{createClient as ln}from"polkadot-api";import{withPolkadotSdkCompat as cn}from"polkadot-api/polkadot-sdk-compat";var un=async u=>{let t=typeof u=="string"?u.split(","):u,a=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(t);return ln(cn(a))};var Be={};S(Be,{AAVE_GAS_LIMIT:()=>$t,AAVE_LENDING_POOL_ADDRESS:()=>Nt,AAVE_POOL_ABI:()=>jt,AAVE_POOL_DATA_PROVIDER:()=>qt,AAVE_POOL_DATA_PROVIDER_ABI:()=>Lt,AAVE_POOL_PROXY:()=>zt,AAVE_ROUNDING_THRESHOLD:()=>_s,AAVE_UINT_256_MAX:()=>pn,AaveClient:()=>pt,AaveUtils:()=>K});var jt=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{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 Lt=[{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 zt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",qt="0x112b087b60C1a166130d59266363C45F8aa99db0",Nt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",$t=1000000n,_s=5,pn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var pt=class{client;constructor(t){this.client=t.getWsProvider()}async getReservesData(){return await this.client.readContract({abi:Lt,address:qt,args:[Nt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:Lt,address:qt,args:[Nt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:jt,address:zt,args:[t],functionName:"getUserAccountData"})}};var h={};S(h,{asBigInt:()=>gn,toBigInt:()=>dn,toDecimal:()=>mn});import X from"big.js";X.NE=-18;function mn(u,t,e=6,n){let a=X(u.toString()),s=X(10).pow(t);return a.div(s).round(e,n).toString()}function dn(u,t){let e=X(10).pow(t),a=X(u).mul(e).toFixed(0,X.roundDown);return BigInt(a)}function gn(u){return BigInt(u.round(0,X.roundDown).toFixed(0))}var $={};S($,{ERC20:()=>Qt});var Qt=class{static fromAssetId(t){let e=Buffer.alloc(20,0);return e[15]=1,e.writeUInt32BE(t,16),"0x"+e.toString("hex")}static toAssetId(t){let e=Buffer.from(t.replace("0x",""),"hex");return e.length!==20||!this.isAssetAddress(t)?null:e.readUInt32BE(16)}static isAssetAddress(t){let e=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(e.subarray(0,16))}};var A={};S(A,{FeeUtils:()=>ee});var xe={};S(xe,{HUB_ASSET_ID:()=>te,HYDRATION_OMNIPOOL_ADDRESS:()=>yn,HYDRATION_PARACHAIN_ID:()=>bn,HYDRATION_SS58_PREFIX:()=>F,PERBILL_DENOMINATOR:()=>Jt,PERMILL_DENOMINATOR:()=>mt,RUNTIME_DECIMALS:()=>_,SYSTEM_ASSET_DECIMALS:()=>Zt,SYSTEM_ASSET_ID:()=>D,TRADEABLE_DEFAULT:()=>Q});var _=18,mt=1e6,Jt=1e9,D=0,Zt=12,bn=2034,F=63,yn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",te=1,Q=15;var ee=class u{static toPct(t){let[e,n]=t;return u.safeDivide(e*100,n)}static toRaw(t){let[e,n]=t;return u.safeDivide(e,n)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,n=12){let a=10**n;return Math.round(t*a/e)/a}static safeRound(t){return parseFloat(t.toPrecision(15))}};var Ht={};S(Ht,{H160:()=>ae,isEvmAccount:()=>Ie,isEvmAddress:()=>ve,isSs58Address:()=>Oe});import{AccountId as dt}from"polkadot-api";import{toHex as we}from"@polkadot-api/utils";import{Buffer as U}from"buffer";var ne="ETH\0";function Ie(u){if(!u)return!1;try{let t=dt().enc(u),e=U.from(ne);return U.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function ve(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Oe(u){try{return dt(63).enc(u),!0}catch{return!1}}var ae=class u{static toAccount=t=>{let e=U.from(t.slice(2),"hex"),n=U.from(ne),a=Uint8Array.from(U.concat([n,e,U.alloc(8)])),s=we(a);return dt(63).dec(s)};static fromAccount=t=>{let e=dt().enc(t),n=U.from(ne),a=e.slice(n.length,-8);return"0x"+U.from(a).toString("hex")};static fromSS58=t=>{let n=dt().enc(t).slice(0,20);return we(n)};static fromAny=t=>{if(ve(t))return t;if(Ie(t))return u.fromAccount(t);if(Oe(t))return u.fromSS58(t);throw new Error("Unknown address type")}};var Y={};S(Y,{findNestedKey:()=>hn,findNestedObj:()=>Pn,jsonFormatter:()=>fn});var hn=(u,t)=>{let e=[];return JSON.stringify(u,(n,a)=>(a&&a[t]&&e.push(a),a)),e[0]},Pn=(u,t,e)=>{let n;return JSON.stringify(u,(a,s)=>(s&&s[t]===e&&(n=s),s)),n},fn=(u,t)=>typeof t=="bigint"?t.toString():t;var w={};S(w,{calculateBuyFee:()=>wn,calculateDiffToAvg:()=>Tn,calculateDiffToRef:()=>Sn,calculateSellFee:()=>xn,getFraction:()=>In});import N from"big.js";function Tn(u,t){let e=N(u.toString()),n=N(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function Sn(u,t){if(t===0n)return 0;let e=N(u.toString()),n=N(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function xn(u,t){let e=N(u.toString()),n=N(t.toString());return N(1).minus(n.div(e)).mul(100).round(2).toNumber()}function wn(u,t){let e=N(u.toString());return N(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function In(u,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),a=BigInt(t*n);return u*a/BigInt(100*n)}var Ae={};S(Ae,{convertToId:()=>On});import{Buffer as vn}from"buffer";function On(u){let e=vn.from(u.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var{ERC20:Gt}=$,{H160:se}=Ht,An=1.01,Bn=99999,_n=10n**27n,Rn=10n**18n,K=class{client;constructor(t){this.client=new pt(t)}async getSummary(t){let e=se.fromAny(t),[n,a,s]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e)]),[i]=n,[r,o]=a,[l,c,p,g,m,b]=s,y=h.toDecimal(b,18),d=[];for(let P of r){let f=P.underlyingAsset.toLowerCase(),T=i.find(({underlyingAsset:Kt})=>Kt.toLowerCase()===f);if(!T)throw new Error("Missing pool reserve for "+f);let I=P.scaledATokenBalance,C=T.liquidityIndex,q=T.priceInMarketReferenceCurrency,R=I*C/_n,Dt=Number(o===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,Mt=T.usageAsCollateralEnabled&&P.usageAsCollateralEnabledOnUser&&P.scaledATokenBalance>0n,Yt=Gt.toAssetId(f);d.push({aTokenBalance:R,decimals:Number(T.decimals),isCollateral:Mt,priceInRef:q,reserveId:Yt,reserveAsset:f,reserveLiquidationThreshold:Dt})}return{healthFactor:Number(y),totalCollateral:l,totalDebt:c,reserves:d}}async hasBorrowPositions(t){let e=se.fromAny(t),n=await this.client.getUserAccountData(e),[a,s]=n;return s>0n}async getHealthFactor(t){let e=se.fromAny(t),n=await this.client.getUserAccountData(e),[a,s,i,r,o,l]=n,c=h.toDecimal(l,18);return Number(c)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:a,totalDebt:s,reserves:i}=await this.getSummary(t),r=Gt.fromAssetId(e),o=i.find(d=>d.reserveAsset===r);if(!o)throw new Error("Missing reserve ctx for "+r);let{decimals:l,isCollateral:c,priceInRef:p,reserveLiquidationThreshold:g}=o,m=h.toBigInt(n,l),b=c?m*p/10n**BigInt(l):0n,y=a-b;return y<=0n?0:this.calculateHealthFactor(y,g,s)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:a,totalDebt:s,reserves:i}=await this.getSummary(t),r=Gt.fromAssetId(e),o=i.find(y=>y.reserveAsset===r);if(!o)throw new Error("Missing reserve ctx for "+r);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:p}=o,m=h.toBigInt(n,l)*c/10n**BigInt(l),b=a+m;return b<=0n?0:this.calculateHealthFactor(b,p,s)}async getMaxWithdraw(t,e){let{totalCollateral:n,totalDebt:a,reserves:s}=await this.getSummary(t),i=Gt.fromAssetId(e),r=s.find(o=>o.reserveAsset===i);if(!r)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(r,n,a)}async getMaxWithdrawAll(t){let{totalCollateral:e,totalDebt:n,reserves:a}=await this.getSummary(t),s={};for(let i of a){let r=this.calculateWithdrawMax(i,e,n);i.reserveId&&(s[i.reserveId]=r)}return s}calculateHealthFactor(t,e,n){if(n===0n)return Bn;let a=10n**6n,s=h.toBigInt(e,18),i=t*s*a,r=n*Rn,o=i/r;return Number(o)/1e6}calculateRequiredCollateral(t,e,n){let a=h.toBigInt(t,18),s=h.toBigInt(e,18);return(a*n+s-1n)/s}calculateWithdrawMax(t,e,n){let{aTokenBalance:a,decimals:s,priceInRef:i,reserveLiquidationThreshold:r}=t,o=this.calculateRequiredCollateral(An,r,n),l=e-o;if(l<=0n)return{amount:0n,decimals:s};let c=l*10n**BigInt(s)/i;return{amount:a<c?a:c,decimals:s}}};var Fe={};S(Fe,{AssetClient:()=>J,BalanceClient:()=>L,ChainParams:()=>tt});var J=class extends B{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:a})=>{let[s]=n;return[s,a]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:a})=>{let[s]=n;return[s,a]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:a}=n;return this.SUPPORTED_TYPES.includes(a.type)}).map(({keyArgs:n,value:a})=>{let[s]=n;return[s,a]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:a})=>{let[s]=n;return[s,a]}))}async mapToken(t,e,n,a){let{name:s,asset_type:i,is_sufficient:r,existential_deposit:o}=e,{symbol:l,decimals:c}=n.get(t)??{};return{id:t,name:s?.asText(),symbol:l,decimals:c,icon:l,type:i.type,isSufficient:r,location:a,existentialDeposit:o}}async mapBond(t,e,n,a){let[s,i]=a,{asset_type:r,is_sufficient:o,existential_deposit:l}=e,{symbol:c,decimals:p}=await this.mapToken(s,e,n),g=Number(i),m=new Intl.DateTimeFormat("en-GB"),b=[c,"Bond",m.format(g)].join(" ");return{id:t,name:b,symbol:c+"b",decimals:p,icon:c,type:r.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:s,maturity:g}}async mapShares(t,e,n,a){let{assets:s}=a,{name:i,symbol:r,asset_type:o,is_sufficient:l,existential_deposit:c}=e,p=await Promise.all(s.map(async b=>{let{symbol:y}=await this.mapToken(b,e,n);return[b,y]})),g=Object.fromEntries(p),m=Object.values(g);return{id:t,name:m.join(", "),symbol:r?.asText()||i?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:g}}async mapExternal(t,e,n,a){let s=await this.mapToken(t,e,new Map,a),i=n?.find(r=>r.internalId===s.id);return i?{...s,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:s}parseMetadata(t){return new Map(Array.from(t,([e,n])=>[e,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(t,e){let[n,a,s,i]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),r=this.parseMetadata(n),o=[];for(let[l,c]of Array.from(n)){let p=a.get(l),{asset_type:g}=c,m;switch(g.type){case"Bond":let b=i.get(l);m=await this.mapBond(l,c,r,b);break;case"StableSwap":let y=s.get(l);m=await this.mapShares(l,c,r,y);break;case"External":m=await this.mapExternal(l,c,e,p);break;default:m=await this.mapToken(l,c,r,p)}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 En,combineLatest as kn,debounceTime as Cn,distinctUntilChanged as _e,finalize as Dn,map as Z,pairwise as Mn,shareReplay as Ln,startWith as qn}from"rxjs";var L=class extends B{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:n}=await e.getValue(t);return this.calculateBalance(n)}async getTokenBalance(t,e){let a=await this.api.query.Tokens.Accounts.getValue(t,e);return this.calculateBalance(a)}calculateBalance(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,n=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:n,transferable:e}}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),a=this.subscribeErc20Balance(t);return kn([e,n,a]).pipe(Cn(250),Z(s=>s.flat()),qn([]),En(2,1),Z(([s,i],r)=>{if(r===0)return i;let o=s.reduce((c,p)=>(c.set(p.id,p.balance),c),new Map);return i.filter(c=>!Re(c.balance,o.get(c.id)))}))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe(Z(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe(Z(a=>({id:e,balance:a})))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe(_e((n,a)=>!a.deltas),Z(({deltas:n})=>{let a=[];return n?.deleted.forEach(s=>{let[i,r]=s.args;a.push({id:r,balance:this.calculateBalance({free:0n,reserved:0n,frozen:0n})})}),n?.upserted.forEach(s=>{let[i,r]=s.args;a.push({id:r,balance:this.calculateBalance(s.value)})}),a}))}subscribeErc20Balance(t,e){let n=new Fn,a=n.pipe(Ln(1)),s=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:c}=l;return c.type==="Erc20"}).map(({keyArgs:l})=>{let[c]=l;return c}),i=async()=>{let o=e||await s(),l=async()=>{let g=(await Promise.all(o.map(async m=>{let b=await this.getTokenBalanceData(t,m);return[m,b]}))).map(([m,b])=>({id:m,balance:b}));n.next(g)};await l();let c=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>c.unsubscribe()},r;return i().then(o=>r=o),a.pipe(Dn(()=>r?.()),Mn(),Z(([o,l],c)=>{if(c===0)return l;let p=o.reduce((m,b)=>(m.set(b.id,b.balance),m),new Map);return l.filter(m=>!Re(m.balance,p.get(m.id)))}),_e((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let n=await this.api.apis.CurrenciesApi.account(e,t);return this.calculateBalance(n)}},Re=(u,t)=>u!==void 0&&t!==void 0&&u.transferable===t.transferable&&u.total===t.total;var tt=class extends B{_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 Ee={};S(Ee,{AssetNotFound:()=>re,PoolNotFound:()=>gt,RouteNotFound:()=>bt});var re=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},gt=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},bt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var De={};S(De,{EvmClient:()=>yt,createChain:()=>ie});import{defineChain as Nn}from"viem";var Hn=["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"],ie=()=>Nn({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:Hn}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as ke,createWalletClient as Gn,custom as Ce,http as Un}from"viem";var yt=class{client;chain;constructor(t){this.client=t,this.chain=ie()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return ke({chain:this.chain,transport:Un()})}getWsProvider(){return ke({transport:Ce({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return Gn({account:t,chain:this.chain,transport:Ce(window.ethereum)})}};var Xe={};S(Xe,{PoolContextProvider:()=>st,PoolError:()=>j,PoolFactory:()=>at,PoolType:()=>v,aave:()=>me,lbp:()=>le,omni:()=>ce,stable:()=>ue,xyk:()=>pe});var le={};S(le,{LbpMath:()=>M,LbpPool:()=>ht,LbpPoolClient:()=>ft});import{calculate_in_given_out as Vn,calculate_out_given_in as Wn,calculate_linear_weights as Xn,calculate_pool_trade_fee as Yn,get_spot_price as Kn}from"@galacticcouncil/math-lbp";var M=class{static getSpotPrice(t,e,n,a,s){return Kn(t,e,n,a,s)}static calculateInGivenOut(t,e,n,a,s){return Vn(t,e,n,a,s)}static calculateOutGivenIn(t,e,n,a,s){return Wn(t,e,n,a,s)}static calculateLinearWeights(t,e,n,a,s){return Xn(t,e,n,a,s)}static calculatePoolTradeFee(t,e,n){return Yn(t,e,n)}};var v=(s=>(s.Aave="Aave",s.LBP="LBP",s.Omni="Omnipool",s.Stable="Stableswap",s.XYK="XYK",s))(v||{}),j=(s=>(s.InsufficientTradingAmount="InsufficientTradingAmount",s.MaxInRatioExceeded="MaxInRatioExceeded",s.MaxOutRatioExceeded="MaxOutRatioExceeded",s.TradeNotAllowed="TradeNotAllowed",s.UnknownError="UnknownError",s))(j||{});var{FeeUtils:Me}=A,ht=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,n,a,s,i,r){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=a,this.minTradingLimit=s,this.fee=i,this.repayFeeApply=r}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),a=n.get(t),s=n.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:s.balance,decimalsIn:a.decimals,decimalsOut:s.decimals,weightIn:a.weight,weightOut:s.weight}}validateAndBuy(t,e,n){let a=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let i=t.balanceOut/this.maxOutRatio;if(e>i&&s.push("MaxOutRatioExceeded"),a===t.assetOut){let r=this.calculateTradeFee(e,n),o=Me.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+r,c=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return c>p&&s.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:s}}else{let r=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return r>o&&s.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:s}}}validateAndSell(t,e,n){let a=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let i=t.balanceIn/this.maxInRatio;if(e>i&&s.push("MaxInRatioExceeded"),a===t.assetIn){let r=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return r>o&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:s}}else{let r=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(r,n),l=Me.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),c=r-o,p=t.balanceOut/this.maxOutRatio;return c>p&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:c,feePct:l,errors:s}}}calculateInGivenOut(t,e){let n=M.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),a=BigInt(n);return a<0n?0n:a}calculateOutGivenIn(t,e){let n=M.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),a=BigInt(n);return a<0n?0n:a}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 ta}from"polkadot-api";import{map as ea,of as Ge,switchMap as na}from"rxjs";import{memoize1 as jn}from"@thi.ng/memoize";import{combineLatest as Le,combineLatestAll as zn,debounceTime as $n,firstValueFrom as Qn,from as qe,map as Ne,mergeAll as Jn,of as Zn,switchMap as He}from"rxjs";var oe=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var Pt=class{client;constructor(t){this.client=t.getWsProvider()}async getData(t,e=6){let[n,a,s]=await Promise.all([this.client.readContract({abi:oe,address:t,functionName:"latestRoundData"}),this.client.readContract({abi:oe,address:t,functionName:"decimals"}),this.client.getBlock()]),[i,r,o,l]=n,c=s.number-(s.timestamp-l)/BigInt(e),p=Number(c);return{price:r,decimals:a,updatedAt:p<0?0:p}}};var E=class extends L{evm;mmOracle;override=[];mem=0;memPools=jn(t=>(this.log(this.getPoolType(),"mem pools",t,"\u2705"),this.loadPools()));constructor(t,e){super(t),this.evm=e,this.mmOracle=new Pt(e)}async withOverride(t){this.override=t||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let t=qe(this.getPoolsMem()).pipe(He(e=>this.subscribe(e)),zn());return Qn(t)}getSubscriber(){return qe(this.getPoolsMem()).pipe(He(t=>this.subscribe(t)),Jn())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>Le([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe($n(250),Ne(([n,a])=>this.updatePool(n,a))))}subscribePoolBalance(t){if(t.type==="Aave")return Zn([]);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(s=>s.type==="Erc20").map(s=>s.id),a=this.subscribeErc20Balance(t.address,n);e.push(a)}return Le(e).pipe(Ne(n=>n.map(a=>Array.isArray(a)?a:[a]).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:a})=>{let s=this.override.find(r=>r.id===e),i=!!n||!!s?.decimals;return a>0n&&i})}updatePool=(t,e)=>{let n=t.tokens.map(a=>{let s=e.find(r=>r.id===a.id),i=this.override.find(r=>r.id===a.id);return s?{...a,balance:s.balance.transferable,decimals:a.decimals||i?.decimals}:{...a,decimals:a.decimals||i?.decimals}});return{...t,tokens:n}}};var ft=class extends E{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()]),a=e?.relay_parent_number||0,s=t.filter(({value:i})=>e&&this.isActivePool(i,a)).map(async({keyArgs:i,value:r})=>{let[o]=i,l=o.toString(),c=await this.getPoolDelta(l,r,a);return{address:l,type:"LBP",fee:r.fee,...c,...n}});return Promise.all(s)}async getPoolDelta(t,e,n){let{start:a,end:s,assets:i,initial_weight:r,final_weight:o,repay_target:l,fee_collector:c}=e,p=M.calculateLinearWeights(a?a.toString():"0",s?s.toString():"0",r.toString(),o.toString(),n.toString()),[g,m]=i,b=BigInt(p),y=this.MAX_FINAL_WEIGHT-BigInt(b),[d,P,f,T,I]=await Promise.all([this.isRepayFeeApplied(g,l,c.toString()),this.getBalance(t,g),this.api.query.AssetRegistry.Assets.getValue(g),this.getBalance(t,m),this.api.query.AssetRegistry.Assets.getValue(m)]);return{repayFeeApply:d,tokens:[{id:g,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:P.transferable,weight:b,type:f?.asset_type.type},{id:m,decimals:I?.decimals,existentialDeposit:I?.existential_deposit,balance:T.transferable,weight:y,type:I?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:a}=t;return n&&a?e>=n&&e<a:!1}async isRepayFeeApplied(t,e,n){if(e===0n)return!1;try{return(await this.getBalance(n,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async 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(ta.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(t.address);return n?e.watchValue("best").pipe(na(a=>a?this.getPoolDelta(t.address,n,a.relay_parent_number):Ge(t)),ea(a=>Object.assign({},t,a))):Ge(t)}};var ce={};S(ce,{OmniMath:()=>x,OmniPool:()=>Tt,OmniPoolClient:()=>St});import{calculate_in_given_out as aa,calculate_lrna_in_given_out as sa,calculate_out_given_in as ra,calculate_out_given_lrna_in as ia,calculate_spot_price as oa,calculate_lrna_spot_price as la,calculate_shares as ca,calculate_liquidity_out as ua,calculate_liquidity_lrna_out as pa,verify_asset_cap as ma,calculate_liquidity_hub_in as da,is_sell_allowed as ga,is_buy_allowed as ba,is_add_liquidity_allowed as ya,is_remove_liquidity_allowed as ha}from"@galacticcouncil/math-omnipool";import et from"big.js";var x=class{static calculateSpotPrice(t,e,n,a){return oa(t,e,n,a)}static calculateLrnaSpotPrice(t,e){return la(t,e)}static calculateInGivenOut(t,e,n,a,s,i,r,o,l){return aa(t,e,n,a,s,i,r,o,l)}static calculateLrnaInGivenOut(t,e,n,a,s){return sa(t,e,n,a,s)}static calculateOutGivenIn(t,e,n,a,s,i,r,o,l){return ra(t,e,n,a,s,i,r,o,l)}static calculateOutGivenLrnaIn(t,e,n,a,s){return ia(t,e,n,a,s)}static calculateShares(t,e,n,a){return ca(t,e,n,a)}static calculateLiquidityOut(t,e,n,a,s,i,r,o){return ua(t,e,n,a,s,i,r,o)}static calculateLiquidityLRNAOut(t,e,n,a,s,i,r,o){return pa(t,e,n,a,s,i,r,o)}static calculateCapDifference(t,e,n,a){let s=et(e),i=et(t),r=et(a),o=et(n),l=et(10).pow(18),c=o.div(l);if(s.div(r).lt(c)){let g=c.times(r).minus(s).times(i),m=s.times(et(1).minus(c));return g.div(m).toFixed(0)}else return"0"}static verifyAssetCap(t,e,n,a){return ma(t,e,n,a)}static calculateLimitHubIn(t,e,n,a){return da(t,e,n,a)}static isSellAllowed(t){return ga(t)}static isBuyAllowed(t){return ba(t)}static isAddLiquidityAllowed(t){return ya(t)}static isRemoveLiquidityAllowed(t){return ha(t)}};var{FeeUtils:nt}=A,Tt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,n,a,s,i){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=a,this.minTradingLimit=s,this.hubAssetId=i}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),a=n.get(t),s=n.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:a.hubReserves,hubReservesOut:s.hubReserves,sharesIn:a.shares,sharesOut:s.shares,decimalsIn:a.decimals,decimalsOut:s.decimals,balanceIn:a.balance,balanceOut:s.balance,tradeableIn:a.tradeable,tradeableOut:s.tradeable,assetInEd:a.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,n){let a=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,n),i=a===0n?0:w.calculateDiffToRef(s,a),r=[],o=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&r.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&r.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return s>p&&r.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:a,amountOut:e,feePct:i,errors:r}}validateAndSell(t,e,n){let a=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,n),i=w.calculateDiffToRef(a,s),r=[],o=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&r.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&r.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return s>p&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:s,feePct:i,errors:r}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let a=x.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?nt.toRaw(n.assetFee).toString():"0",n?nt.toRaw(n.protocolFee).toString():"0"),s=BigInt(a);return s<0n?0n:s}calculateLrnaInGivenOut(t,e,n){let a=x.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?nt.toRaw(n.assetFee).toString():"0"),s=BigInt(a);return s<0n?0n:s}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let a=x.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?nt.toRaw(n.assetFee).toString():"0",n?nt.toRaw(n.protocolFee).toString():"0"),s=BigInt(a);return s<0n?0n:s}calculateOutGivenLrnaIn(t,e,n){let a=x.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?nt.toRaw(n.assetFee).toString():"0"),s=BigInt(a);return s<0n?0n:s}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=x.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=x.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=x.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=x.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};import{AccountId as Pa,CompatibilityLevel as fa}from"polkadot-api";import{toHex as Ta}from"@polkadot-api/utils";import{distinctUntilChanged as Sa,map as Ue}from"rxjs";var{FeeUtils:V}=A,St=class extends E{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,a,s,i,r]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.getBalance(e,t),this.getPoolLimits()]),o=n.map(async({keyArgs:c,value:p})=>{let[g]=c,{hub_reserve:m,shares:b,tradable:y,cap:d,protocol_shares:P}=p,[f,T]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(g),this.getBalance(e,g)]);return{id:g,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:T.transferable,cap:d,hubReserves:m,protocolShares:P,shares:b,tradeable:y,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:i.transferable,tradeable:a,type:s?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...r}]}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=Ta(e);return Pa(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,a,s]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),i=n.min_fee+a.min_fee,r=n.max_fee+a.max_fee;if(s){let{asset_fee:o,protocol_fee:l}=s;return{assetFee:V.fromPermill(o),protocolFee:V.fromPermill(l),min:V.fromPermill(i),max:V.fromPermill(r)}}else return{assetFee:V.fromPermill(n.min_fee),protocolFee:V.fromPermill(a.min_fee),min:V.fromPermill(i),max:V.fromPermill(r)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(fa.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(Sa((n,a)=>!a.deltas),Ue(({entries:n})=>n.map(a=>{let[s]=a.args,{hub_reserve:i,shares:r,tradable:o,cap:l,protocol_shares:c}=a.value,p=t.tokens.findIndex(m=>m.id===s);return{...t.tokens[p],cap:l,hubReserves:i,protocolShares:c,shares:r,tradeable:o}})),Ue(n=>{let a=t.tokens.find(s=>s.id===1);return{...t,tokens:[...n,a]}}))}};var ue={};S(ue,{StableMath:()=>O,StableSwap:()=>xt,StableSwapClient:()=>wt});import{calculate_in_given_out as xa,calculate_out_given_in as wa,calculate_amplification as Ia,calculate_add_one_asset as va,calculate_liquidity_out_one_asset as Oa,calculate_shares as Aa,calculate_shares_for_amount as Ba,calculate_spot_price_with_fee as _a,pool_account_name as Ra,recalculate_peg as Fa}from"@galacticcouncil/math-stableswap";var O=class{static getPoolAddress(t){return Ra(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,a,s){return Ia(t,e,n,a,s)}static calculateInGivenOut(t,e,n,a,s,i,r){return xa(t,e,n,a,s,i,r)}static calculateAddOneAsset(t,e,n,a,s,i,r){return va(t,e,n,a,s,i,r)}static calculateSharesForAmount(t,e,n,a,s,i,r){return Ba(t,e,n,a,s,i,r)}static calculateOutGivenIn(t,e,n,a,s,i,r){return wa(t,e,n,a,s,i,r)}static calculateLiquidityOutOneAsset(t,e,n,a,s,i,r){return Oa(t,e,n,a,s,i,r)}static calculateShares(t,e,n,a,s,i){return Aa(t,e,n,a,s,i)}static calculateSpotPriceWithFee(t,e,n,a,s,i,r,o){return _a(t,e,n,a,s,i,r,o)}static recalculatePegs(t,e,n,a,s){let i=Fa(t,e,n,a,s);return JSON.parse(i)}};var{FeeUtils:W}=A,xt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.id,t.fee,t.totalIssuance)}constructor(t,e,n,a,s,i,r,o,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=a,this.minTradingLimit=s,this.amplification=i,this.id=r,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])),a=n.get(t),s=n.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:s.balance,decimalsIn:a.decimals,decimalsOut:s.decimals,tradeableIn:this.id===t?15:a.tradeable,tradeableOut:this.id===e?15:s.tradeable,assetInEd:a.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,n){let a=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,n),i=W.toPct(n.fee),r=[],o=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:s,calculatedIn:a,amountOut:e,feePct:i,errors:r}}validateAndSell(t,e,n){let a=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,n),i=W.toPct(n.fee),r=[],o=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:a,amountOut:s,feePct:i,errors:r}}calculateIn(t,e,n){let a=O.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?W.toRaw(n.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}calculateAddOneAsset(t,e,n){let a=O.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?W.toRaw(n.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}calculateSharesForAmount(t,e,n){let a=O.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?W.toRaw(n.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}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=O.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 a=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(a)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let a=O.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?W.toRaw(n.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}calculateWithdrawOneAsset(t,e,n){let a=O.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?W.toRaw(n.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}calculateShares(t,e,n){let a=O.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?W.toRaw(n.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}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=O.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 a=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(a)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}getPegs(){let t=O.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:a})=>({asset_id:e,amount:n,decimals:a}));return JSON.stringify(t,Y.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],Y.jsonFormatter)}};import{AccountId as Ea,CompatibilityLevel as ka}from"polkadot-api";import{toHex as Ca}from"@polkadot-api/utils";import{blake2b as Da}from"@noble/hashes/blake2b";import{map as Ma,of as La,switchMap as qa}from"rxjs";var{FeeUtils:z}=A,wt=class extends E{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=O.getPoolAddress(t),n=Da(e,{dkLen:32}),a=Ca(n);return Ea(63).dec(a)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolDelta(t,e,n){let{initial_amplification:a,final_amplification:s,initial_block:i,final_block:r}=e,o=O.calculateAmplification(a.toString(),s.toString(),i.toString(),r.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),a=e.assets.map(async s=>{let[i,r,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,s),this.api.query.AssetRegistry.Assets.getValue(s),this.getBalance(n,s)]);return{id:s,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:o.transferable,tradeable:i,type:r?.asset_type.type}});return Promise.all(a)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(ka.BackwardsCompatible,e)}async loadPools(){let[t,e,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),a=t.map(async({keyArgs:s,value:i})=>{let[r]=s,o=this.getPoolAddress(r),[l,c,p]=await Promise.all([this.getPoolDelta(r,i,e),this.getPoolTokens(r,i),this.getPoolPegs(r,i,e)]);return c.push({id:r,tradeable:15,balance:l.totalIssuance,decimals:18}),this.poolsData.set(o,i),{address:o,id:r,type:"Stableswap",fee:z.fromPermill(i.fee),tokens:c,...l,...p,...n}});return Promise.all(a)}async getPoolFees(t){return{fee:t.fee}}async getPoolPegs(t,e,n){let a=await this.api.query.Stableswap.PoolPegs.getValue(t);if(!a)return this.getDefaultPegs(e);let s=await this.getLatestPegs(e,a,n),i=this.getRecentPegs(a),r=z.fromPermill(a.max_peg_update),o=z.fromPermill(e.fee),[l,c]=O.recalculatePegs(JSON.stringify(i),JSON.stringify(s),n.toString(),z.toRaw(r).toString(),z.toRaw(o).toString()),p=Number(l)*1e6;return{pegsFee:z.fromPermill(p),pegs:c}}getDefaultPegs(t){let e=t.fee,n=O.defaultPegs(t.assets.length);return{pegsFee:z.fromPermill(e),pegs:n}}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([n,a])=>a.map(s=>s.toString()))}async getLatestPegs(t,e,n){let{source:a}=e,s=Array.from(t.assets.entries()).map(([r,o])=>o),i=a.map(async(r,o)=>{if(r.type==="Oracle"){let[l,c,p]=r.value,g=[p,s[o]].sort((f,T)=>f-T),m=await this.api.query.EmaOracle.Oracles.getValue(l,g,c);if(!m)return;let[{price:b,updated_at:y}]=m,d=b.n.toString(),P=b.d.toString();return p.toString()===g[0].toString()?[[d,P],y.toString()]:[[P,d],y.toString()]}else if(r.type==="MMOracle"){let l=r.value.asHex(),{price:c,decimals:p,updatedAt:g}=await this.mmOracle.getData(l),m=10**p;return[[c.toString(),m.toString()],g.toString()]}else return[r.value.map(l=>l.toString()),n.toString()]});return Promise.all(i)}subscribePoolChange(t){let e=this.api.query.System.Number,n=this.poolsData.get(t.address);return!n||!t.id?La(t):e.watchValue("best").pipe(qa(a=>Promise.all([this.getPoolDelta(t.id,n,a),this.getPoolPegs(t.id,n,a)])),Ma(([a,s])=>{let i=t.tokens.map(r=>r.id===t.id?{...r,balance:a.totalIssuance}:r);return Object.assign(t,{tokens:i},a,s)}))}};var pe={};S(pe,{XykMath:()=>H,XykPool:()=>It,XykPoolClient:()=>vt});import{calculate_in_given_out as Na,calculate_out_given_in as Ha,calculate_pool_trade_fee as Ga,get_spot_price as Ua,calculate_liquidity_in as Va,calculate_shares as Wa,calculate_spot_price as Xa,calculate_spot_price_with_fee as Ya,calculate_liquidity_out_asset_a as Ka,calculate_liquidity_out_asset_b as ja}from"@galacticcouncil/math-xyk";var H=class{static getSpotPrice(t,e,n){return Ua(t,e,n)}static calculateInGivenOut(t,e,n){return Na(t,e,n)}static calculateOutGivenIn(t,e,n){return Ha(t,e,n)}static calculatePoolTradeFee(t,e,n){return Ga(t,e,n)}static calculateLiquidityIn(t,e,n){return Va(t,e,n)}static calculateSpotPrice(t,e){return Xa(t,e)}static calculateSpotPriceWithFee(t,e,n,a){return Ya(t,e,n,a)}static calculateShares(t,e,n){return Wa(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,a){return Ka(t,e,n,a)}static calculateLiquidityOutAssetB(t,e,n,a){return ja(t,e,n,a)}};var{FeeUtils:Ve}=A,It=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,a,s){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=a,this.minTradingLimit=s}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),a=n.get(t),s=n.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:a.decimals,decimalsOut:s.decimals,balanceIn:a.balance,balanceOut:s.balance,assetInEd:a.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,n){let a=this.calculateInGivenOut(t,e),s=this.calculateTradeFee(a,n),i=Ve.toPct(n.exchangeFee),r=a+s,o=[];(e<this.minTradingLimit||a<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return r>c&&o.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:a,amountOut:e,feePct:i,errors:o}}validateAndSell(t,e,n){let a=this.calculateOutGivenIn(t,e),s=this.calculateTradeFee(a,n),i=Ve.toPct(n.exchangeFee),r=a-s,o=[];(e<this.minTradingLimit||a<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return r>c&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:r,feePct:i,errors:o}}calculateInGivenOut(t,e){let n=H.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(n);return a<0n?0n:a}calculateOutGivenIn(t,e){let n=H.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(n);return a<0n?0n:a}spotPriceInGivenOut(t){let e=H.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=H.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=H.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as za}from"polkadot-api";import{of as $a}from"rxjs";var vt=class extends E{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,n]=await Promise.all([t.getEntries(),this.getPoolLimits()]),a=e.map(async({keyArgs:s,value:i})=>{let[r]=s,[o,l]=i,[c,p,g,m]=await Promise.all([this.getBalance(r,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(r,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:r,type:"XYK",tokens:[{id:o,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:c.transferable,type:p?.asset_type.type},{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:g.transferable,type:m?.asset_type.type}],...n}});return Promise.all(a)}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(za.BackwardsCompatible,e)}subscribePoolChange(t){return $a(t)}};var me={};S(me,{AavePool:()=>Ot,AavePoolClient:()=>At});var Ot=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,a,s){this.type="Aave",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=a,this.minTradingLimit=s}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(i=>[i.id,i])),a=n.get(t),s=n.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:s.balance,decimalsIn:a.decimals,decimalsOut:s.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let a=this.calculateInGivenOut(t,e),s=[];return e>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e,n){let a=this.calculateOutGivenIn(t,e),s=[];return a>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:s}}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 Qa}from"polkadot-api";import{toHex as Ja}from"@polkadot-api/utils";import{map as Za,merge as ts,switchMap as es}from"rxjs";import{decodeEventLog as ns}from"viem";var We=[{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:as}=$,ss=["Supply","Withdraw","Repay","Borrow"],At=class extends E{async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:a,liqudity_in:s,liqudity_out:i})=>{let[r,o,l,c]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(a),this.api.query.AssetRegistry.AssetLocations.getValue(a)]);return{address:this.getPoolId(n,a),type:"Aave",tokens:[{id:n,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:s,location:o,type:r?.asset_type.type},{id:a,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:i,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:a,liqudity_out:s}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id);return t.tokens.map(i=>{let r=i.id===e.id?a:s;return{...i,balance:r}})}getPoolId(t,e){let n=t+"/"+e,a=new TextEncoder().encode(n.padEnd(32,"\0")),s=Ja(a);return Qa(63).dec(s)}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,a=this.getReserveH160Id(e),s=this.api.event.Router.Executed.watch(({asset_in:r,asset_out:o})=>r===n.id||o===n.id),i=this.api.event.EVM.Log.watch(({log:r})=>{let{topics:o,data:l}=r,c=o.map(b=>b.asHex()),p=l.asHex(),{eventName:g,args:m}=ns({abi:We,topics:c,data:p});return ss.includes(g)&&m.reserve.toLowerCase()===a.toLowerCase()});return ts([s,i]).pipe(es(()=>this.getPoolDelta(t)),Za(r=>({...t,tokens:[...r]})))}getReserveH160Id(t){return t.type==="Erc20"?Y.findNestedKey(t.location,"AccountKey20").AccountKey20.key:as.fromAssetId(t.id)}};var at=class{static get(t){switch(t.type){case"Aave":return Ot.fromPool(t);case"XYK":return It.fromPool(t);case"Omnipool":return Tt.fromPool(t);case"LBP":return ht.fromPool(t);case"Stableswap":return xt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{Subject as rs,Subscription as Bt,takeUntil as is}from"rxjs";var st=class extends B{evm;lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=Bt.EMPTY;omniSub=Bt.EMPTY;stableSub=Bt.EMPTY;xykSub=Bt.EMPTY;aaveSub=Bt.EMPTY;isReady=!1;isDestroyed=new rs;constructor(t,e){super(t),this.evm=e,this.lbpClient=new ft(t,e),this.omniClient=new St(t,e),this.stableClient=new wt(t,e),this.xykClient=new vt(t,e),this.aaveClient=new At(t,e),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(t){return t.getSubscriber().pipe(is(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(t={}){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let{useOnly:e=[],exclude:n=[]}=t,a=new Set(e),s=new Set(n),i=async r=>{let o=r.getPoolType();return a.size>0?a.has(o):s.size>0?!s.has(o):r.isSupported()};return this.getFilteredPools(i)}async getFilteredPools(t){let e=await Promise.all(this.clients.map(t)),n=this.clients.filter((s,i)=>e[i]);return(await Promise.all(n.map(s=>s.getPoolsMem()))).flat()}async getPoolFees(t,e){let n=this.clients.find(a=>a.getPoolType()===t.type);if(n)return n.getPoolFees(t,e);throw new gt(t.type)}};var $e={};S($e,{DEFAULT_BLOCK_TIME:()=>Ke,DEFAULT_MIN_BUDGET:()=>be,ORDER_MIN_BLOCK_PERIOD:()=>je,Router:()=>rt,TWAP_BLOCK_PERIOD:()=>Et,TWAP_MAX_DURATION:()=>he,TWAP_MAX_PRICE_IMPACT:()=>ye,TWAP_TX_MULTIPLIER:()=>Gc,TradeOrderError:()=>ge,TradeOrderType:()=>Vt,TradeRouteBuilder:()=>k,TradeRouter:()=>it,TradeScheduler:()=>ot,TradeType:()=>Ut});var _t=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 os=8,Rt=class{isNotVisited(t,e){let n=!0;return e.forEach(a=>{(a[0]===t[0]||a[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let a=[],s=new _t,i=[];for(i.push([e,""]),s.enqueue(i);s.size()>0;){let r=s.dequeue();if(!r||r.length>os)continue;let o=r[r.length-1];(n===null||o[0]===n)&&a.push(r),t.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,r)){let p=[...r];p.push(c),s.enqueue(p)}})}return a}findShortestPaths(t,e,n){let a=[],s=new _t,i=[];i.push([e,""]),s.enqueue(i);let r=1/0;for(;s.size()>0;){let o=s.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===n){o.length<r?(r=o.length,a.length=0,a.push(o)):o.length===r&&a.push(o);continue}let c=t.get(l[0]);for(let p of c??[])this.isNotVisited(p,o)&&s.enqueue([...o,p])}return a}buildAndPopulateGraph(t,e){let n=new Map;for(let a of t)n.set(parseInt(a),[]);for(let[a,s,i]of e)n.get(s)?.push([i,a]);return n}};function de(u){let t={};for(let e of u){let n=e.tokens.length;for(let a=0;a<n;a++){t[e.tokens[a].id]||(t[e.tokens[a].id]=[]);for(let s=0;s<n;s++){if(a==s)continue;let i=[e.address,e.tokens[a].id,e.tokens[s].id];t[e.tokens[a].id].push(i)}}}return t}var Ft=class{getProposals(t,e,n){let a=n.filter(d=>d.type==="XYK"),s=n.filter(d=>d.type!=="XYK"),i=new Set(s.map(d=>d.tokens).flat().map(d=>d.id)),r=i.has(t),o=i.has(e),l=new Rt,c=d=>{let P=de(d),f=Object.keys(P),T=f.flatMap(I=>P[I]);return l.buildAndPopulateGraph(f,T)};if(!r&&!o){let d=a.filter(T=>T.tokens.find(I=>I.id===t)||T.tokens.find(I=>I.id===e)),P=c(d),f=l.findPaths(P,t,e);return this.parsePaths(f)}if(r&&o){let d=c(s),P=l.findPaths(d,t,e);return this.parsePaths(P)}let p=r?e:t,g=a.filter(d=>d.tokens.some(P=>P.id===p));if(g.length===0)return[];let m=[...s,...g],b=c(m),y=l.findPaths(b,t,e);return this.parsePaths(y)}parsePaths(t){let e=[];for(let n of t){let a=[];for(let s=0;s<n.length;s++){let i=n[s],r=n[s+1];if(r==null)break;a.push(this.toEdge(i,r))}e.push(a)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var rt=class{routeSuggester;routeProposals;routerOptions;ctx;constructor(t,e={}){this.ctx=t,this.routeSuggester=new Ft,this.routeProposals=new Map,this.routerOptions=Object.freeze(e)}buildRouteKey(t,e,n){return`${t}->${e}::${n.length}`}async getPools(){return this.ctx.getPools(this.routerOptions)}async getRoutes(t,e){let n=await this.getPools();return this.validateInput(t,e,n),this.getPaths(t,e,n)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(a=>a!==t).map(a=>this.getRoutes(a,t)))).filter(a=>a.length>0).map(([a])=>a[0].assetIn).sort()}validateInput(t,e,n){if(n.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let a=this.getAssets(n);if(!a.has(t))throw new Error(t+" is not supported asset");if(!a.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(a=>a.id)).flat().sort((n,a)=>n>a?1:-1);return new Set(e)}getPaths(t,e,n){let a=this.toPoolsMap(n);return this.getProposals(t,e,n).filter(i=>this.validPath(i,a)).map(i=>this.toHops(i,a))}getProposals(t,e,n){let a=this.buildRouteKey(t,e,n);if(this.routeProposals.has(a))return this.routeProposals.get(a);let s=this.routeSuggester.getProposals(t,e,n);return this.routeProposals.set(a,s),s}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,a)=>n&&a)}validEdge([t,e,n],a){return a.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,at.get(e)]))}toHops(t,e){return t.map(([n,a,s])=>{let i=e.get(n);return{poolAddress:n,poolId:i?.id,pool:i?.type,assetIn:a,assetOut:s}})}};var Ut=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Ut||{}),Vt=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Vt||{}),ge=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(ge||{});var{FeeUtils:Ye}=A,it=class extends rt{mlr;poolsSnapshot;constructor(t,e={}){super(t,e),this.mlr=new Map}buildCtxSync(t,e){let n=this.poolsSnapshot,a=super.validateInput(t,e,n),s=super.getPaths(t,e,n);if(!s.length)throw new bt(t,e);return{paths:s,pools:n,poolsMap:a}}async withCtx(t,e,n){this.poolsSnapshot||(this.poolsSnapshot=await super.getPools());let a=this.buildCtxSync(t,e);return n(a)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,a)=>{let s=n[n.length-1].amountOut,i=a[a.length-1].amountOut;return s>i?-1:1});return e.find(n=>n.every(a=>a.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(n=>n.tradeFeeRange).length>0){let n=t.map(s=>s.tradeFeeRange?.[0]??s.tradeFeePct).reduce((s,i)=>s+i),a=t.map(s=>s.tradeFeeRange?.[1]??s.tradeFeePct).reduce((s,i)=>s+i);return[n,a]}}getPoolFeeRange(t){let e=t.min?Ye.toPct(t.min):void 0,n=t.max?Ye.toPct(t.max):void 0;if(e&&n)return[e,n]}async getBestSell(t,e,n){return this.getSell(t,e,n)}getSellSpot(t){let e=t[t.length-1];if(t.length===1)return e.spotPrice;let n=t.map(r=>r.assetOutDecimals).reduce((r,o)=>r+o),a=t.map(r=>r.spotPrice).reduce((r,o)=>r*o),s=n-e.assetOutDecimals,i=Math.pow(10,s);return a/BigInt(i)}async getSell(t,e,n,a){return this.withCtx(t,e,async({paths:s,poolsMap:i})=>{let r;if(a)r=await this.toSellSwaps(n,a,i);else{let o=s.map(c=>this.toSellSwaps(n,c,i)),l=await Promise.all(o);r=this.findBestSellRoute(l)}return this.buildSell(i,r)})}buildSell(t,e){let n=e[0],a=e[e.length-1],s=this.isDirectTrade(e),i=this.getSellSpot(e),r=a.amountOut,o=s?a.calculatedOut:this.calculateDelta0Y(n.amountIn,e,t),l=o-r,c=this.getRouteFeeRange(e),p=s?a.tradeFeePct:w.calculateSellFee(o,r),g=Math.pow(10,n.assetInDecimals),m=n.amountIn*i/BigInt(g),b=w.calculateDiffToRef(o,m);return{type:"Sell",amountIn:n.amountIn,amountOut:a.amountOut,spotPrice:i,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:e,toHuman(){return{type:"Sell",amountIn:h.toDecimal(n.amountIn,n.assetInDecimals),amountOut:h.toDecimal(a.amountOut,a.assetOutDecimals),spotPrice:h.toDecimal(i,a.assetOutDecimals),tradeFee:h.toDecimal(l,a.assetOutDecimals),tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:e.map(y=>y.toHuman())}}}}calculateDelta0Y(t,e,n){let a=[];for(let s=0;s<e.length;s++){let i=e[s],r=n.get(i.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(i.assetIn,i.assetOut),l;s>0?l=a[s-1]:l=t;let c=r.calculateOutGivenIn(o,l);a.push(c)}return a[a.length-1]}async calculateMostLiquidRoute(t,e,n){let{paths:a,pools:s,poolsMap:i}=n,l=s.filter(y=>y.tokens.some(d=>d.id===t)).map(y=>y.type==="Aave"?y.tokens:y.tokens.filter(d=>d.id===t)).map(y=>y.map(d=>d.balance).reduce((d,P)=>d+P)).sort((y,d)=>d<y?-1:1)[0],c=w.getFraction(l,.1),p=await Promise.all(a.map(y=>this.toSellSwaps(c,y,i))),m=this.findBestSellRoute(p).map(y=>({poolAddress:y.poolAddress,poolId:y?.poolId,pool:y.pool,assetIn:y.assetIn,assetOut:y.assetOut})),b=this.buildRouteKey(t,e,s);return this.mlr.set(b,m),m}async toSellSwaps(t,e,n){let a=[];for(let s=0;s<e.length;s++){let i=e[s],r=n.get(i.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(i.assetIn,i.assetOut),l;s>0?l=a[s-1].amountOut:l=typeof t=="string"?h.toBigInt(t,o.decimalsIn):t;let c=await this.ctx.getPoolFees(r,o.assetOut),{amountOut:p,calculatedOut:g,feePct:m,errors:b}=r.validateAndSell(o,l,c),y=this.getPoolFeeRange(c),d=r.spotPriceOutGivenIn(o),P=Math.pow(10,o.decimalsIn),f=l*d/BigInt(P),T=w.calculateDiffToRef(g,f);a.push({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:g,spotPrice:d,tradeFeePct:m,tradeFeeRange:y,priceImpactPct:T,errors:b,isSupply(){return r.type==="Aave"&&r.tokens[0].id===i.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:h.toDecimal(l,o.decimalsIn),amountOut:h.toDecimal(p,o.decimalsOut),calculatedOut:h.toDecimal(g,o.decimalsOut),spotPrice:h.toDecimal(d,o.decimalsOut),tradeFeePct:m,tradeFeeRange:y,priceImpactPct:T,errors:b}}})}return a}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async n=>{let a=this.buildRouteKey(t,e,n.pools),s=this.mlr.get(a);return s||this.calculateMostLiquidRoute(t,e,n)})}async getSpotPrice(t,e){return this.withCtx(t,e,async n=>{let{pools:a,poolsMap:s}=n,i=this.buildRouteKey(t,e,a),r=this.mlr.get(i);r||(r=await this.calculateMostLiquidRoute(t,e,n));let o=await this.toSellSwaps("1",r,s),l=this.getSellSpot(o),c=o[o.length-1].assetOutDecimals;return{amount:l,decimals:c}})}findBestBuyRoute(t){let e=t.sort((n,a)=>{let s=n[0].amountIn,i=a[0].amountIn;return s>i?1:-1});return e.find(n=>n.every(a=>a.errors.length==0))||e[0]}async getBestBuy(t,e,n){return this.getBuy(t,e,n)}getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let n=t.map(r=>r.assetInDecimals).reduce((r,o)=>r+o),a=t.map(r=>r.spotPrice).reduce((r,o)=>r*o),s=n-e.assetInDecimals,i=Math.pow(10,s);return a/BigInt(i)}async getBuy(t,e,n,a){return this.withCtx(t,e,async({paths:s,poolsMap:i})=>{let r;if(a)r=await this.toBuySwaps(n,a,i);else{let o=s.map(c=>this.toBuySwaps(n,c,i)),l=await Promise.all(o);r=this.findBestBuyRoute(l)}return this.buildBuy(i,r)})}buildBuy(t,e){let n=e[e.length-1],a=e[0],s=this.isDirectTrade(e),i=this.getBuySpot(e),r=a.amountIn,o=s?a.calculatedIn:this.calculateDelta0X(n.amountOut,e,t),l=r-o,c=this.getRouteFeeRange(e),p=s?a.tradeFeePct:w.calculateBuyFee(o,r),g=Math.pow(10,n.assetOutDecimals),m=n.amountOut*i/BigInt(g),b;return o===0n?b=-100:b=w.calculateDiffToRef(m,o),{type:"Buy",amountOut:n.amountOut,amountIn:a.amountIn,spotPrice:i,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:e,toHuman(){return{type:"Buy",amountOut:h.toDecimal(n.amountOut,n.assetOutDecimals),amountIn:h.toDecimal(a.amountIn,a.assetInDecimals),spotPrice:h.toDecimal(i,a.assetInDecimals),tradeFee:h.toDecimal(l,a.assetInDecimals),tradeFeePct:p,tradeFeeRange:c,priceImpactPct:b,swaps:e.map(y=>y.toHuman())}}}}calculateDelta0X(t,e,n){let a=[];for(let s=e.length-1;s>=0;s--){let i=e[s],r=n.get(i.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(i.assetIn,i.assetOut),l;s==e.length-1?l=t:l=a[0];let c=r.calculateInGivenOut(o,l);a.unshift(c)}return a[0]}async toBuySwaps(t,e,n){let a=[];for(let s=e.length-1;s>=0;s--){let i=e[s],r=n.get(i.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(i.assetIn,i.assetOut),l;s==e.length-1?l=typeof t=="string"?h.toBigInt(t,o.decimalsOut):t:l=a[0].amountIn;let c=await this.ctx.getPoolFees(r,o.assetOut),{amountIn:p,calculatedIn:g,feePct:m,errors:b}=r.validateAndBuy(o,l,c),y=this.getPoolFeeRange(c),d=r.spotPriceInGivenOut(o),P=Math.pow(10,o.decimalsOut),f=l*d/BigInt(P),T;g===0n?T=-100:T=w.calculateDiffToRef(f,g),a.unshift({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:g,spotPrice:d,tradeFeePct:m,tradeFeeRange:y,priceImpactPct:T,errors:b,isSupply(){return r.type==="Aave"&&r.tokens[0].id===i.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:h.toDecimal(l,o.decimalsOut),amountIn:h.toDecimal(p,o.decimalsIn),calculatedIn:h.toDecimal(g,o.decimalsIn),spotPrice:h.toDecimal(d,o.decimalsIn),tradeFeePct:m,tradeFeeRange:y,priceImpactPct:T,errors:b}}})}return a}};var Ke=6e3,be=1000000000000000n,Et=6,ye=-5,he=216e5,Gc=3,je=6;import{Enum as ze}from"polkadot-api";var k=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:a,poolId:s})=>a==="Stableswap"?{pool:ze("Stableswap",s),asset_in:e,asset_out:n}:{pool:ze(a),asset_in:e,asset_out:n})}};var ot=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??be})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,a,s){let[i,r]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:c}=r,p=l[0],g=l[l.length-1],{assetInDecimals:m}=p,{assetOutDecimals:b}=g,y=Math.abs(c),d=this.getMinimumTradeCount(o,i),P=this.getOptimalTradeCount(y),f=s?Math.round(a/s):P,T=Math.ceil(a/d),I=Math.round(a/P),C=Math.round(a/f),q=o/BigInt(f),R=await this.router.getBestSell(t,e,q),G=o<i,Dt=[];G&&Dt.push("OrderTooSmall");let Mt=R.amountOut*BigInt(f),Yt=this.toBlockPeriod(C),Kt=R.tradeFee*BigInt(f),sn=k.build(l),fe={assetIn:t,assetOut:e,errors:Dt,frequencyMin:T,frequencyOpt:I,frequency:C,tradeCount:f,tradeFee:Kt,tradeImpactPct:R.priceImpactPct,tradePeriod:Yt,tradeRoute:sn,type:"Dca"};return{...fe,amountIn:o,amountOut:Mt,tradeAmountIn:R.amountIn,tradeAmountOut:R.amountOut,toHuman(){return{...fe,amountIn:h.toDecimal(o,m),amountOut:h.toDecimal(Mt,b),tradeAmountIn:h.toDecimal(R.amountIn,m),tradeAmountOut:h.toDecimal(R.amountOut,b)}}}}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 a=t+n/2n;return Number(a/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[a,s]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:i,swaps:r,priceImpactPct:o}=s,l=r[0],c=r[r.length-1],{assetInDecimals:p}=l,{assetOutDecimals:g}=c,m=Math.abs(o),b=this.getTwapTradeCount(m),y=i/BigInt(b),d=await this.router.getBestSell(l.assetIn,c.assetOut,y),P=b===1,f=i<a,T=d.priceImpactPct<-5,I=[];f||P?I.push("OrderTooSmall"):T&&I.push("OrderImpactTooBig");let C=d.amountOut*BigInt(b),q=d.tradeFee*BigInt(b),R=k.build(r),G={assetIn:t,assetOut:e,errors:I,tradeCount:b,tradeImpactPct:d.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapSell"};return{...G,amountIn:i,amountOut:C,tradeAmountIn:d.amountIn,tradeAmountOut:d.amountOut,tradeFee:q,toHuman(){return{...G,amountIn:h.toDecimal(i,p),amountOut:h.toDecimal(C,g),tradeAmountIn:h.toDecimal(d.amountIn,p),tradeAmountOut:h.toDecimal(d.amountOut,g),tradeFee:h.toDecimal(q,g)}}}}async getTwapBuyOrder(t,e,n){let[a,s]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:i,swaps:r,priceImpactPct:o}=s,l=r[0],c=r[r.length-1],{assetInDecimals:p}=l,{assetOutDecimals:g}=c,m=Math.abs(o),b=this.getTwapTradeCount(m),y=i/BigInt(b),d=await this.router.getBestBuy(l.assetIn,c.assetOut,y),P=d.amountIn*BigInt(b),f=b===1,T=P<a,I=d.priceImpactPct<-5,C=[];T||f?C.push("OrderTooSmall"):I&&C.push("OrderImpactTooBig");let q=d.tradeFee*BigInt(b),R=k.build(r),G={assetIn:t,assetOut:e,errors:C,tradeCount:b,tradeImpactPct:d.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapBuy"};return{...G,amountIn:P,amountOut:i,tradeAmountIn:d.amountIn,tradeAmountOut:d.amountOut,tradeFee:q,toHuman(){return{...G,amountIn:h.toDecimal(P,p),amountOut:h.toDecimal(i,g),tradeAmountIn:h.toDecimal(d.amountIn,p),tradeAmountOut:h.toDecimal(d.amountOut,g),tradeFee:h.toDecimal(q,p)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let a=216e5/(this.blockTime*6);return Math.round(a)}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 tn={};S(tn,{BIG_10:()=>Je,BIG_BILL:()=>Ze,StakingApi:()=>kt,StakingClient:()=>Ct});import{encodeAddress as ls}from"@polkadot/util-crypto";import{stringToU8a as cs}from"@polkadot/util";import{calculate_accumulated_rps as us,calculate_period_number as Qe,calculate_rewards as ps}from"@galacticcouncil/math-staking";import lt from"big.js";var Je=lt(10),Ze=lt(Je.pow(12));function ms(u){return ls(cs(("modl"+u).padEnd(32,"\0")),63)}var kt=class{client;balanceClient;constructor(t,e){this.client=t,this.balanceClient=e}async getFreePotBalance(){let t=await this.client.getPalletId(),e=ms(t);return(await this.balanceClient.getBalance(e,0)).transferable}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]),a=e?.created_at,s=await n.reduce(async(i,[r,o])=>{let l=await i,c=r,p=o.amount,g=o.conviction.toString(),m=await this.client.getReferendumInfo(c);return m&&(m.type==="Approved"||m.type==="Rejected")&&l.push({id:c,amount:p,conviction:g}),l},Promise.resolve([]));return{stake:e?.stake,rewardPerStake:e?.reward_per_stake,createdAt:a,actionPoints:e?.action_points,accumulatedUnpaidRewards:e?.accumulated_unpaid_rewards,accumulatedSlashPoints:e?.accumulated_slash_points,accumulatedLockedRewards:e?.accumulated_locked_rewards,votes:s}}async getStake(t){let e=await this.client.getNFTCollectionId(),[n,a]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),s=a.find(i=>i)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:s,stakePosition:s?await this.getStakingPosition(s):void 0}}async getRewards(t,e){let n=await this.getStake(t),{potReservedBalance:a,accumulatedRewardPerStake:s,totalStake:i,stakePosition:r}=n;if(!r)return;let[o,l,c,p]=await Promise.all([this.getFreePotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getSixBlockSince()]),g=lt(o.toString()).minus(a.toString()),m=s.toString(),b=lt(e).plus(1).toString();g.gt(0)&&i>0&&(m=us(s.toString(),g.toString(),i.toString()));let y=Qe(l.toString(),e,p??b),d=Qe(l.toString(),r.createdAt?.toString()??"",p??b),P=ps(m,r.rewardPerStake?.toString()??"",r.stake?.toString()??""),f=lt(P).plus(r.accumulatedUnpaidRewards?.toString()||"0").plus(r.accumulatedLockedRewards?.toString()||"0");if(!lt(y).minus(d).lte(c.toString()))return f.div(Ze).toString()}};var Ct=class extends B{async getPalletId(){let t=this.api.constants.Staking.PalletId;return(await t()).asText()}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:i})=>{let[r,o,l]=i;return{address:r,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var an={};S(an,{TxBuilderFactory:()=>ut});import{Enum as nn}from"polkadot-api";function en(u){let t=[],e=u;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var ct=class extends B{evm;evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balanceClient=new L(t),this.aaveUtils=new K(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:n=>this.dryRun(n,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:$t})}async dryRun(t,e){let n=nn("Signed",t),a=nn("system",n),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(a,e.decodedCall),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let o=en(r.value);throw new Error("Dry run execution error!",{cause:o})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var Wt=class extends ct{_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:a}=e[0],s=await this.balanceClient.getBalance(this.beneficiary,a);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,a=n[0],s=n[n.length-1],i=w.getFraction(t,this.slippagePct),r=a.assetIn,o=s.assetOut,l=t+i,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.buy({asset_in:r,asset_out:o,amount:e,max_sell_amount:l}):c=this.api.tx.Router.buy({asset_in:r,asset_out:o,amount_out:e,max_amount_in:l,route:k.build(n)}),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,a=n[0],s=n[n.length-1],i=w.getFraction(e,this.slippagePct),r=a.assetIn,o=s.assetOut,l=e-i,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.sell({asset_in:r,asset_out:o,amount:t,min_buy_amount:l}):c=this.api.tx.Router.sell({asset_in:r,asset_out:o,amount_in:t,min_amount_out:l,route:k.build(n)}),a.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,n=e[0],a=e[e.length-1],s=w.getFraction(t,this.slippagePct),i=n.assetIn,r=a.assetOut,o=t-s,l=this.api.tx.Router.sell_all({asset_in:i,asset_out:r,min_amount_out:o,route:k.build(e)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as Pe}from"polkadot-api";var Xt=class extends ct{_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:a,tradePeriod:s,tradeRoute:i}=this.order,r=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:Pe("Sell",{asset_in:e,asset_out:n,amount_in:a,min_amount_out:0n,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",r)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:a,tradeAmountOut:s,tradePeriod:i,tradeRoute:r}=this.order,o=w.getFraction(s,this.slippagePct),l=s-o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:Pe("Sell",{asset_in:e,asset_out:n,amount_in:a,min_amount_out:l,route:r})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:a,tradeAmountOut:s,tradePeriod:i,tradeRoute:r}=this.order,o=w.getFraction(a,this.slippagePct),l=a+o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:Pe("Buy",{asset_in:e,asset_out:n,amount_out:s,max_amount_in:l,route:r})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",c)}};var ut=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new Wt(this.client,this.evmClient).setTrade(t)}order(t){return new Xt(this.client,this.evmClient).setOrder(t)}};async function zu(u){let t=new tt(u),e=new yt(u),[n,a]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),s=new st(u,e).withAave().withOmnipool().withStableswap().withXyk(),i=new K(e),r=new it(s),o=new ot(r,{blockTime:n,minBudgetInNative:a}),l=new L(u),c=new Ct(u),p=new kt(c,l);return{api:{aave:i,router:r,scheduler:o,staking:p},client:{asset:new J(u),balance:l,evm:e},ctx:{pool:s},tx:new ut(u,e),destroy:()=>{s.destroy()}}}export{Be as aave,Se as api,h as big,Fe as client,xe as const,zu as createSdkContext,$ as erc20,Ee as error,De as evm,A as fmt,Ht as h160,Y as json,w as math,Xe as pool,$e as sor,tn as staking,an as tx,Ae as xc};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { EvmClient } from '../evm';
|
|
2
2
|
export declare class AaveClient {
|
|
3
|
-
private
|
|
4
|
-
constructor(
|
|
3
|
+
private client;
|
|
4
|
+
constructor(evm: EvmClient);
|
|
5
5
|
getReservesData(): Promise<readonly [readonly {
|
|
6
6
|
underlyingAsset: `0x${string}`;
|
|
7
7
|
name: string;
|
|
@@ -3,7 +3,7 @@ import { EvmClient } from '../evm';
|
|
|
3
3
|
import { Amount } from '../types';
|
|
4
4
|
export declare class AaveUtils {
|
|
5
5
|
private client;
|
|
6
|
-
constructor(
|
|
6
|
+
constructor(evm: EvmClient);
|
|
7
7
|
getSummary(user: string): Promise<AaveSummary>;
|
|
8
8
|
/**
|
|
9
9
|
* Check if user has active borrow positions
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { Chain } from 'viem';
|
|
2
|
-
export declare const
|
|
2
|
+
export declare const createChain: () => Chain;
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
+
import { PolkadotClient } from 'polkadot-api';
|
|
1
2
|
import { Chain, PublicClient, WalletClient } from 'viem';
|
|
2
3
|
export declare class EvmClient {
|
|
4
|
+
private client;
|
|
3
5
|
readonly chain: Chain;
|
|
4
|
-
constructor(
|
|
6
|
+
constructor(client: PolkadotClient);
|
|
5
7
|
get chainId(): number;
|
|
6
8
|
get chainCurrency(): string;
|
|
7
9
|
get chainDecimals(): number;
|
|
8
|
-
getGasPrice(): Promise<bigint>;
|
|
9
10
|
getProvider(): PublicClient;
|
|
10
11
|
getWsProvider(): PublicClient;
|
|
11
12
|
getSigner(address: string): WalletClient;
|
package/build/types/factory.d.ts
CHANGED
|
@@ -24,4 +24,4 @@ export type SdkCtx = {
|
|
|
24
24
|
tx: TxBuilderFactory;
|
|
25
25
|
destroy: () => void;
|
|
26
26
|
};
|
|
27
|
-
export declare function createSdkContext(client: PolkadotClient
|
|
27
|
+
export declare function createSdkContext(client: PolkadotClient): Promise<SdkCtx>;
|