@galacticcouncil/sdk-next 0.6.0-pr190-5b3d616 → 0.6.0-pr192-eb1e3d2
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/client/BalanceClient.d.ts +10 -11
- package/build/types/consts.d.ts +2 -0
- package/build/types/pool/stable/StableMath.d.ts +1 -1
- package/build/types/pool/stable/StableSwap.d.ts +2 -0
- package/build/types/pool/stable/StableSwapClient.d.ts +4 -0
- package/build/types/types.d.ts +2 -9
- package/package.json +1 -1
package/build/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var hn=Object.create;var Ue=Object.defineProperty;var Pn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var Tn=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var Nt=(u,e)=>()=>(u&&(e=u(u=0)),e);var S=(u,e)=>{for(var t in e)Ue(u,t,{get:e[t],enumerable:!0})},Ge=(u,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fn(e))!xn.call(u,s)&&s!==t&&Ue(u,s,{get:()=>e[s],enumerable:!(n=Pn(e,s))||n.enumerable});return u},re=(u,e,t)=>(Ge(u,e,"default"),t&&Ge(t,e,"default")),st=(u,e,t)=>(t=u!=null?hn(Tn(u)):{},Ge(e||!u||!u.__esModule?Ue(t,"default",{value:u,enumerable:!0}):t,u)),In=u=>Ge(Ue({},"__esModule",{value:!0}),u);var Te={};var Ut=Nt(()=>{re(Te,require("@polkadot-api/ws-provider/node"))});var xe={};var Wt=Nt(()=>{re(xe,require("@polkadot-api/ws-provider/web"))});var Qn={};S(Qn,{aave:()=>ft,api:()=>at,big:()=>b,client:()=>Tt,const:()=>dt,createSdkContext:()=>$n,erc20:()=>ee,error:()=>It,evm:()=>ct,fmt:()=>h,h160:()=>we,json:()=>Z,math:()=>A,pool:()=>Bt,sor:()=>Ct,tx:()=>Lt,xc:()=>ht});module.exports=In(Qn);var at={};S(at,{Papi:()=>M,getWs:()=>wn});var Gt=require("@galacticcouncil/descriptors");function Ht(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var M=class{client;api;constructor(e){this.client=e,this.api=this.client.getTypedApi(Gt.hydration)}log(e,...t){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Ht(n)&&console.log(e,...t)}};var Vt=require("polkadot-api"),Xt=require("polkadot-api/polkadot-sdk-compat"),wn=async u=>{let e=typeof u=="string"?u.split(","):u,s=(typeof window>"u"?(await Promise.resolve().then(()=>(Ut(),Te))).getWsProvider:(await Promise.resolve().then(()=>(Wt(),xe))).getWsProvider)(e);return(0,Vt.createClient)((0,Xt.withPolkadotSdkCompat)(s))};var ft={};S(ft,{AAVE_GAS_LIMIT:()=>ot,AAVE_LENDING_POOL_ADDRESS:()=>Xe,AAVE_POOL_ABI:()=>rt,AAVE_POOL_DATA_PROVIDER:()=>Ve,AAVE_POOL_DATA_PROVIDER_ABI:()=>We,AAVE_POOL_PROXY:()=>it,AAVE_ROUNDING_THRESHOLD:()=>ds,AAVE_UINT_256_MAX:()=>Sn,AaveClient:()=>Ie,AaveUtils:()=>te});var rt=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var We=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var it="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ve="0x112b087b60C1a166130d59266363C45F8aa99db0",Xe="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ot=1000000n,ds=5,Sn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ct={};S(ct,{EvmClient:()=>L,evmMainnet:()=>lt});var Kt=require("viem"),Yt=["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"],jt=["wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],lt=(0,Kt.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:Yt,webSocket:jt},default:{http:Yt,webSocket:jt}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var G=require("viem");var L=class{chain;constructor(e){this.chain=e||lt}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}async getGasPrice(){return this.getProvider().getGasPrice()}getProvider(){return(0,G.createPublicClient)({chain:this.chain,transport:(0,G.http)()})}getWsProvider(){return(0,G.createPublicClient)({chain:this.chain,transport:(0,G.webSocket)()})}getSigner(e){return(0,G.createWalletClient)({account:e,chain:this.chain,transport:(0,G.custom)(window.ethereum)})}};var Ie=class{evmClient;constructor(e){this.evmClient=e??new L}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:We,address:Ve,args:[Xe],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:We,address:Ve,args:[Xe,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:rt,address:it,args:[e],functionName:"getUserAccountData"})}};var b={};S(b,{asBigInt:()=>An,toBigInt:()=>vn,toDecimal:()=>On});var J=st(require("big.js"));J.default.NE=-18;function On(u,e,t=6,n){let s=(0,J.default)(u.toString()),a=(0,J.default)(10).pow(e);return s.div(a).round(t,n).toString()}function vn(u,e){let t=(0,J.default)(10).pow(e),s=(0,J.default)(u).mul(t).toFixed(0,J.default.roundDown);return BigInt(s)}function An(u){return BigInt(u.round(0,J.default.roundDown).toFixed(0))}var ee={};S(ee,{ERC20:()=>ut});var ut=class{static fromAssetId(e){let t=Buffer.alloc(20,0);return t[15]=1,t.writeUInt32BE(e,16),"0x"+t.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(e.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(t.subarray(0,16))}};var h={};S(h,{fromPermill:()=>Rn,toDecimals:()=>_n,toPct:()=>Bn});var zt=1e3;function Bn(u){let[e,t]=u;return e/t*100}function _n(u){let[e,t]=u;return e/t}function Rn(u){return[u/zt,zt]}var we={};S(we,{H160:()=>yt,isEvmAccount:()=>$t,isEvmAddress:()=>Qt,isSs58Address:()=>Jt});var oe=require("polkadot-api"),gt=require("@polkadot-api/utils"),z=require("buffer");var dt={};S(dt,{HUB_ASSET_ID:()=>mt,HYDRATION_OMNIPOOL_ADDRESS:()=>Fn,HYDRATION_PARACHAIN_ID:()=>En,HYDRATION_SS58_PREFIX:()=>W,RUNTIME_DECIMALS:()=>q,SYSTEM_ASSET_DECIMALS:()=>pt,SYSTEM_ASSET_ID:()=>K,TRADEABLE_DEFAULT:()=>ie});var q=18,K=0,pt=12,En=2034,W=63,Fn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",mt=1,ie=15;var bt="ETH\0";function $t(u){if(!u)return!1;try{let e=(0,oe.AccountId)().enc(u),t=z.Buffer.from(bt);return z.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Qt(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Jt(u){try{return(0,oe.AccountId)(63).enc(u),!0}catch{return!1}}var yt=class u{static toAccount=e=>{let t=z.Buffer.from(e.slice(2),"hex"),n=z.Buffer.from(bt),s=Uint8Array.from(z.Buffer.concat([n,t,z.Buffer.alloc(8)])),a=(0,gt.toHex)(s);return(0,oe.AccountId)(63).dec(a)};static fromAccount=e=>{let t=(0,oe.AccountId)().enc(e),n=z.Buffer.from(bt),s=t.slice(n.length,-8);return"0x"+z.Buffer.from(s).toString("hex")};static fromSS58=e=>{let n=(0,oe.AccountId)().enc(e).slice(0,20);return(0,gt.toHex)(n)};static fromAny=e=>{if(Qt(e))return e;if($t(e))return u.fromAccount(e);if(Jt(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var Z={};S(Z,{findNestedKey:()=>Dn,findNestedObj:()=>kn,jsonFormatter:()=>Cn});var Dn=(u,e)=>{let t=[];return JSON.stringify(u,(n,s)=>(s&&s[e]&&t.push(s),s)),t[0]},kn=(u,e,t)=>{let n;return JSON.stringify(u,(s,a)=>(a&&a[e]===t&&(n=a),a)),n},Cn=(u,e)=>typeof e=="bigint"?e.toString():e;var A={};S(A,{calculateBuyFee:()=>Nn,calculateDiffToAvg:()=>Mn,calculateDiffToRef:()=>Ln,calculateSellFee:()=>qn,getFraction:()=>Hn});var V=st(require("big.js"));function Mn(u,e){let t=(0,V.default)(u.toString()),n=(0,V.default)(e.toString());return t.minus(n).abs().div(t.plus(n).div(2)).mul(100).round(2).toNumber()}function Ln(u,e){if(e===0n)return 0;let t=(0,V.default)(u.toString()),n=(0,V.default)(e.toString());return t.minus(n).div(n).mul(100).round(2).toNumber()}function qn(u,e){let t=(0,V.default)(u.toString()),n=(0,V.default)(e.toString());return(0,V.default)(1).minus(n.div(t)).mul(100).round(2).toNumber()}function Nn(u,e){let t=(0,V.default)(u.toString());return(0,V.default)(e.toString()).div(t).minus(1).mul(100).round(2).toNumber()}function Hn(u,e,t=2){(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,t),s=BigInt(e*n);return u*s/BigInt(100*n)}var ht={};S(ht,{convertToId:()=>Gn});var Zt=require("buffer");function Gn(u){let t=Zt.Buffer.from(u.replace("0x",""),"hex").subarray(16);return t.readUIntBE(0,t.length)}var{ERC20:Ye}=ee,{H160:Pt}=we,Un=1.01,Wn=99999,Vn=10n**27n,Xn=10n**18n,te=class{client;constructor(e){let t=e??new L;this.client=new Ie(t)}async getSummary(e){let t=Pt.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,d,p,m,g]=a,P=b.toDecimal(g,18),y=[];for(let I of r){let f=I.underlyingAsset.toLowerCase(),T=i.find(({underlyingAsset:nt})=>nt.toLowerCase()===f);if(!T)throw new Error("Missing pool reserve for "+f);let v=I.scaledATokenBalance,E=T.liquidityIndex,k=T.priceInMarketReferenceCurrency,C=v*E/Vn,Ne=Number(o===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,He=T.usageAsCollateralEnabled&&I.usageAsCollateralEnabledOnUser&&I.scaledATokenBalance>0n,tt=Ye.toAssetId(f);y.push({aTokenBalance:C,decimals:Number(T.decimals),isCollateral:He,priceInRef:k,reserveId:tt,reserveAsset:f,reserveLiquidationThreshold:Ne})}return{healthFactor:Number(P),totalCollateral:l,totalDebt:c,reserves:y}}async hasBorrowPositions(e){let t=Pt.fromAny(e),n=await this.client.getUserAccountData(t),[s,a]=n;return a>0n}async getHealthFactor(e){let t=Pt.fromAny(e),n=await this.client.getUserAccountData(t),[s,a,i,r,o,l]=n,c=b.toDecimal(l,18);return Number(c)}async getHealthFactorAfterWithdraw(e,t,n){let{totalCollateral:s,totalDebt:a,reserves:i}=await this.getSummary(e),r=Ye.fromAssetId(t),o=i.find(y=>y.reserveAsset===r);if(!o)throw new Error("Missing reserve ctx for "+r);let{decimals:l,isCollateral:c,priceInRef:d,reserveLiquidationThreshold:p}=o,m=b.toBigInt(n,l),g=c?m*d/10n**BigInt(l):0n,P=s-g;return P<=0n?0:this.calculateHealthFactor(P,p,a)}async getHealthFactorAfterSupply(e,t,n){let{totalCollateral:s,totalDebt:a,reserves:i}=await this.getSummary(e),r=Ye.fromAssetId(t),o=i.find(P=>P.reserveAsset===r);if(!o)throw new Error("Missing reserve ctx for "+r);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:d}=o,m=b.toBigInt(n,l)*c/10n**BigInt(l),g=s+m;return g<=0n?0:this.calculateHealthFactor(g,d,a)}async getMaxWithdraw(e,t){let{totalCollateral:n,totalDebt:s,reserves:a}=await this.getSummary(e),i=Ye.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 Wn;let s=10n**6n,a=b.toBigInt(t,18),i=e*a*s,r=n*Xn,o=i/r;return Number(o)/1e6}calculateRequiredCollateral(e,t,n){let s=b.toBigInt(e,18),a=b.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(Un,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 Tt={};S(Tt,{AssetClient:()=>le,BalanceClient:()=>X,ChainParams:()=>ce});var le=class extends M{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async queryShares(){let t=await this.api.query.Stableswap.Pools.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[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:d}=await this.mapToken(a,t,n),p=Number(i),m=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",m.format(p)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:d,icon:c,type:r.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:a,maturity:p}}async mapShares(e,t,n,s){let{assets:a}=s,{name:i,symbol:r,asset_type:o,is_sufficient:l,existential_deposit:c}=t,d=await Promise.all(a.map(async g=>{let{symbol:P}=await this.mapToken(g,t,n);return[g,P]})),p=Object.fromEntries(d),m=Object.values(p);return{id:e,name:m.join(", "),symbol:r?.asText()||i?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:p}}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 d=s.get(l),{asset_type:p}=c,m;switch(p.type){case"Bond":let g=i.get(l);m=await this.mapBond(l,c,r,g);break;case"StableSwap":let P=a.get(l);m=await this.mapShares(l,c,r,P);break;case"External":m=await this.mapExternal(l,c,t,d);break;default:m=await this.mapToken(l,c,r,d)}o.push(m)}return e?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};var w=require("rxjs");var X=class extends M{constructor(e){super(e)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getTokenBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data: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(0,w.combineLatest)([t,n,s]).pipe((0,w.debounceTime)(250),(0,w.map)(a=>a.flat()),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([a,i],r)=>{if(r===0)return i;let o=a.reduce((c,d)=>(c.set(d.id,d.balance),c),new Map);return i.filter(c=>!en(c.balance,o.get(c.id)))}))}subscribeSystemBalance(e){return this.api.query.System.Account.watchValue(e,"best").pipe((0,w.map)(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(e,t){return this.api.query.Tokens.Accounts.watchValue(e,t,"best").pipe((0,w.map)(s=>({id:t,balance:s})))}subscribeTokensBalance(e){return this.api.query.Tokens.Accounts.watchEntries(e,{at:"best"}).pipe((0,w.distinctUntilChanged)((n,s)=>!s.deltas),(0,w.map)(({deltas:n})=>{let s=[];return n?.deleted.forEach(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 w.Subject,s=n.pipe((0,w.shareReplay)(1)),a=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:c}=l;return c.type==="Erc20"}).map(({keyArgs:l})=>{let[c]=l;return c}),i=async()=>{let o=t||await a(),l=async()=>{let p=(await Promise.all(o.map(async m=>{let g=await this.getTokenBalanceData(e,m);return[m,g]}))).map(([m,g])=>({id:m,balance:g}));n.next(p)};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((0,w.finalize)(()=>r?.()),(0,w.pairwise)(),(0,w.map)(([o,l],c)=>{if(c===0)return l;let d=o.reduce((m,g)=>(m.set(g.id,g.balance),m),new Map);return l.filter(m=>!en(m.balance,d.get(m.id)))}),(0,w.distinctUntilChanged)((o,l)=>l.length===0))}async getTokenBalanceData(e,t){let n=await this.api.apis.CurrenciesApi.account(t,e);return this.calculateBalance(n)}},en=(u,e)=>u!==void 0&&e!==void 0&&u.transferable===e.transferable&&u.total===e.total;var ce=class extends M{_minOrderBudget;_blockTime;constructor(e){super(e)}async getBlockTime(){if(this._blockTime===void 0){let e=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(e)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var It={};S(It,{AssetNotFound:()=>xt,PoolNotFound:()=>Se,RouteNotFound:()=>ue});var xt=class extends Error{constructor(e){super(),this.message=`${e} not found`,this.name="AssetNotFound"}},Se=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},ue=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in current configuration`,this.name="RouteNotFound"}};var Bt={};S(Bt,{PoolContextProvider:()=>ge,PoolError:()=>ne,PoolFactory:()=>de,PoolType:()=>F,aave:()=>At,lbp:()=>wt,omni:()=>St,stable:()=>Ot,xyk:()=>vt});var wt={};S(wt,{LbpMath:()=>U,LbpPool:()=>Oe,LbpPoolClient:()=>ve});var Y=require("@galacticcouncil/math-lbp"),U=class{static getSpotPrice(e,t,n,s,a){return(0,Y.get_spot_price)(e,t,n,s,a)}static calculateInGivenOut(e,t,n,s,a){return(0,Y.calculate_in_given_out)(e,t,n,s,a)}static calculateOutGivenIn(e,t,n,s,a){return(0,Y.calculate_out_given_in)(e,t,n,s,a)}static calculateLinearWeights(e,t,n,s,a){return(0,Y.calculate_linear_weights)(e,t,n,s,a)}static calculatePoolTradeFee(e,t,n){return(0,Y.calculate_pool_trade_fee)(e,t,n)}};var F=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a))(F||{}),ne=(a=>(a.InsufficientTradingAmount="InsufficientTradingAmount",a.MaxInRatioExceeded="MaxInRatioExceeded",a.MaxOutRatioExceeded="MaxOutRatioExceeded",a.TradeNotAllowed="TradeNotAllowed",a.UnknownError="UnknownError",a))(ne||{});var Oe=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=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=t+r,c=this.calculateInGivenOut(e,l),d=e.balanceIn/this.maxInRatio;return c>d&&a.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:o,errors:a}}else{let 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=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),c=r-o,d=e.balanceOut/this.maxOutRatio;return c>d&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:l,errors:a}}}calculateInGivenOut(e,t){let n=U.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(e,t){let n=U.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(e){let t=U.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),this.maxOutRatio.toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=U.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),this.maxInRatio.toString());return BigInt(t)}calculateTradeFee(e,t){let n=U.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return BigInt(n)}};var nn=require("polkadot-api"),se=require("rxjs");var tn=(u,e=new Map)=>t=>{let n;return e.has(t)?e.get(t):(e.set(t,n=u(t)),n)};var O=require("rxjs");var N=class extends X{override=[];mem=0;memPools=tn(e=>(this.log(this.getPoolType(),"mem pools",e,"\u2705"),this.loadPools()));constructor(e){super(e)}async withOverride(e){this.override=e||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let e=(0,O.from)(this.getPoolsMem()).pipe((0,O.switchMap)(t=>this.subscribe(t)),(0,O.combineLatestAll)());return(0,O.firstValueFrom)(e)}getSubscriber(){return(0,O.from)(this.getPoolsMem()).pipe((0,O.switchMap)(e=>this.subscribe(e)),(0,O.mergeAll)())}subscribe(e){return e.filter(t=>this.hasValidAssets(t)).map(t=>(0,O.combineLatest)([this.subscribePoolChange(t),this.subscribePoolBalance(t)]).pipe((0,O.debounceTime)(250),(0,O.map)(([n,s])=>this.updatePool(n,s))))}subscribePoolBalance(e){if(e.type==="Aave")return(0,O.of)([]);let t=[this.subscribeTokensBalance(e.address)];if(this.hasSystemAsset(e)){let n=this.subscribeSystemBalance(e.address);t.push(n)}if(this.hasErc20Asset(e)){let n=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),s=this.subscribeErc20Balance(e.address,n);t.push(s)}return(0,O.combineLatest)(t).pipe((0,O.map)(n=>n.map(s=>Array.isArray(s)?s:[s]).flat()))}hasSystemAsset(e){return e.tokens.some(t=>t.id===0)}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}hasValidAssets(e){return e.tokens.every(({id:t,decimals:n,balance:s})=>{let 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 ve=class extends N{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[e,t,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),s=t?.relay_parent_number||0,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,d=U.calculateLinearWeights(s?s.toString():"0",a?a.toString():"0",r.toString(),o.toString(),n.toString()),[p,m]=i,g=BigInt(d),P=this.MAX_FINAL_WEIGHT-BigInt(g),[y,I,f,T,v]=await Promise.all([this.isRepayFeeApplied(p,l,c.toString()),this.getBalance(e,p),this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(e,m),this.api.query.AssetRegistry.Assets.getValue(m)]);return{repayFeeApply:y,tokens:[{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:I.transferable,weight:g,type:f?.asset_type.type},{id:m,decimals:v?.decimals,existentialDeposit:v?.existential_deposit,balance:T.transferable,weight:P,type:v?.asset_type.type}]}}isActivePool(e,t){let{start:n,end:s}=e;return n&&s?t>=n&&t<s:!1}async isRepayFeeApplied(e,t,n){if(t===0n)return!1;try{return(await this.getBalance(n,e)).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(nn.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(e.address);return n?t.watchValue("best").pipe((0,se.switchMap)(s=>s?this.getPoolDelta(e.address,n,s.relay_parent_number):(0,se.of)(e)),(0,se.map)(s=>Object.assign({},e,s))):(0,se.of)(e)}};var St={};S(St,{OmniMath:()=>B,OmniPool:()=>Ae,OmniPoolClient:()=>_e});var x=require("@galacticcouncil/math-omnipool"),ae=st(require("big.js")),B=class{static calculateSpotPrice(e,t,n,s){return(0,x.calculate_spot_price)(e,t,n,s)}static calculateLrnaSpotPrice(e,t){return(0,x.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,n,s,a,i,r,o,l){return(0,x.calculate_in_given_out)(e,t,n,s,a,i,r,o,l)}static calculateLrnaInGivenOut(e,t,n,s,a){return(0,x.calculate_lrna_in_given_out)(e,t,n,s,a)}static calculateOutGivenIn(e,t,n,s,a,i,r,o,l){return(0,x.calculate_out_given_in)(e,t,n,s,a,i,r,o,l)}static calculateOutGivenLrnaIn(e,t,n,s,a){return(0,x.calculate_out_given_lrna_in)(e,t,n,s,a)}static calculateShares(e,t,n,s){return(0,x.calculate_shares)(e,t,n,s)}static calculateLiquidityOut(e,t,n,s,a,i,r,o){return(0,x.calculate_liquidity_out)(e,t,n,s,a,i,r,o)}static calculateLiquidityLRNAOut(e,t,n,s,a,i,r,o){return(0,x.calculate_liquidity_lrna_out)(e,t,n,s,a,i,r,o)}static calculateCapDifference(e,t,n,s){let a=(0,ae.default)(t),i=(0,ae.default)(e),r=(0,ae.default)(s),o=(0,ae.default)(n),l=(0,ae.default)(10).pow(18),c=o.div(l);if(a.div(r).lt(c)){let p=c.times(r).minus(a).times(i),m=a.times((0,ae.default)(1).minus(c));return p.div(m).toFixed(0)}else return"0"}static verifyAssetCap(e,t,n,s){return(0,x.verify_asset_cap)(e,t,n,s)}static calculateLimitHubIn(e,t,n,s){return(0,x.calculate_liquidity_hub_in)(e,t,n,s)}static isSellAllowed(e){return(0,x.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,x.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,x.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,x.is_remove_liquidity_allowed)(e)}};var Ae=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:A.calculateDiffToRef(a,s),r=[],o=B.isSellAllowed(e.tradeableIn),l=B.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 d=e.balanceIn/this.maxInRatio;return a>d&&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=A.calculateDiffToRef(s,a),r=[],o=B.isSellAllowed(e.tradeableIn),l=B.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 d=e.balanceOut/this.maxOutRatio;return a>d&&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=B.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateLrnaInGivenOut(e,t,n){let s=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0"),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=B.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateOutGivenLrnaIn(e,t,n){let s=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=B.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceLrnaInGivenOut(e){let t=B.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=B.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}spotPriceOutGivenLrnaIn(e){let t=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}};var je=require("polkadot-api"),sn=require("@polkadot-api/utils"),Be=require("rxjs");var _e=class extends N{async loadPools(){let e=await this.api.constants.Omnipool.HubAssetId(),t=this.getPoolAddress(),[n,s,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:d})=>{let[p]=c,{hub_reserve:m,shares:g,tradable:P,cap:y,protocol_shares:I}=d,[f,T]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(t,p)]);return{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:T.transferable,cap:y,hubReserves:m,protocolShares:I,shares:g,tradeable:P,type:f?.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=(0,sn.toHex)(t);return(0,je.AccountId)(63).dec(n)}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(e,t){let[n,s,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:h.fromPermill(o),protocolFee:h.fromPermill(l),min:h.fromPermill(i),max:h.fromPermill(r)}}else return{assetFee:h.fromPermill(n.min_fee),protocolFee:h.fromPermill(s.min_fee),min:h.fromPermill(i),max:h.fromPermill(r)}}getPoolType(){return"Omnipool"}async isSupported(){let e=this.api.query.Omnipool.Assets,t=await this.api.compatibilityToken;return e.isCompatible(je.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,Be.distinctUntilChanged)((n,s)=>!s.deltas),(0,Be.map)(({entries:n})=>n.map(s=>{let[a]=s.args,{hub_reserve:i,shares:r,tradable:o,cap:l,protocol_shares:c}=s.value,d=e.tokens.findIndex(m=>m.id===a);return{...e.tokens[d],cap:l,hubReserves:i,protocolShares:c,shares:r,tradeable:o}})),(0,Be.map)(n=>{let s=e.tokens.find(a=>a.id===1);return{...e,tokens:[...n,s]}}))}};var Ot={};S(Ot,{StableMath:()=>D,StableSwap:()=>Re,StableSwapClient:()=>Ee});var _=require("@galacticcouncil/math-stableswap"),D=class{static getPoolAddress(e){return(0,_.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let n=0;n<e;n++)t.push(["1","1"]);return t}static calculateAmplification(e,t,n,s,a){return(0,_.calculate_amplification)(e,t,n,s,a)}static calculateInGivenOut(e,t,n,s,a,i,r){return(0,_.calculate_in_given_out)(e,t,n,s,a,i,r)}static calculateAddOneAsset(e,t,n,s,a,i,r){return(0,_.calculate_add_one_asset)(e,t,n,s,a,i,r)}static calculateSharesForAmount(e,t,n,s,a,i,r){return(0,_.calculate_shares_for_amount)(e,t,n,s,a,i,r)}static calculateOutGivenIn(e,t,n,s,a,i,r){return(0,_.calculate_out_given_in)(e,t,n,s,a,i,r)}static calculateLiquidityOutOneAsset(e,t,n,s,a,i,r){return(0,_.calculate_liquidity_out_one_asset)(e,t,n,s,a,i,r)}static calculateShares(e,t,n,s,a,i){return(0,_.calculate_shares)(e,t,n,s,a,i)}static calculateSpotPriceWithFee(e,t,n,s,a,i,r,o){return(0,_.calculate_spot_price_with_fee)(e,t,n,s,a,i,r,o)}static recalculatePegs(e,t,n,s,a){return(0,_.recalculate_peg)(e,t,n,s,a)}};var Re=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=h.toPct(n.fee),r=[],o=B.isSellAllowed(e.tradeableIn),l=B.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=h.toPct(n.fee),r=[],o=B.isSellAllowed(e.tradeableIn),l=B.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=D.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateAddOneAsset(e,t,n){let s=D.calculateAddOneAsset(this.getReserves(),t.toString(),Number(e.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateSharesForAmount(e,t,n){let s=D.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),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=D.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetOut.toString(),e.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(e.assetOut==this.id)return BigInt(t);if(e.assetIn==this.id){let s=Math.pow(10,e.decimalsIn-e.decimalsOut);return BigInt(t)/BigInt(s)}let n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateOut(e,t,n){let s=D.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateWithdrawOneAsset(e,t,n){let s=D.calculateLiquidityOutOneAsset(this.getReserves(),t.toString(),Number(e.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateShares(e,t,n){let s=D.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),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=D.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetIn.toString(),e.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(e.assetIn==this.id)return BigInt(t);if(e.assetOut==this.id){let s=Math.pow(10,e.decimalsOut-e.decimalsIn);return BigInt(t)/BigInt(s)}let n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}getPegs(){let e=D.defaultPegs(this.tokens.length-1);return JSON.stringify(e)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:n,decimals:s})=>({asset_id:t,amount:n,decimals:s}));return JSON.stringify(e,Z.jsonFormatter)}getAssets(e,t){let n={asset_id:Number(e),amount:t.toString()};return JSON.stringify([n],Z.jsonFormatter)}};var Ke=require("polkadot-api"),an=require("@polkadot-api/utils"),rn=require("@noble/hashes/blake2b"),pe=require("rxjs");var Yn=340282366920938463463374607431768211455n,Ee=class extends N{poolsData=new Map([]);async loadPools(){let[e,t,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),s=e.map(async({keyArgs:a,value:i})=>{let[r]=a,o=this.getPoolAddress(r),[l,c]=await Promise.all([this.getPoolDelta(r,i,t),this.getPoolTokens(r,i)]);return this.poolsData.set(o,i),{address:o,id:r,type:"Stableswap",fee:h.fromPermill(i.fee),tokens:c,...l,...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=D.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:Yn,tradeable:15,type:i?.asset_type.type}),a}getPoolAddress(e){let t=D.getPoolAddress(e),n=(0,rn.blake2b)(t,{dkLen:32}),s=(0,an.toHex)(n);return(0,Ke.AccountId)(63).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(e){return{fee:e.fee}}getPoolType(){return"Stableswap"}async isSupported(){let e=this.api.query.Stableswap.Pools,t=await this.api.compatibilityToken;return e.isCompatible(Ke.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.System.Number,n=this.poolsData.get(e.address);return!n||!e.id?(0,pe.of)(e):t.watchValue("best").pipe((0,pe.switchMap)(s=>this.getPoolDelta(e.id,n,s)),(0,pe.map)(s=>Object.assign({},e,s)))}};var vt={};S(vt,{XykMath:()=>$,XykPool:()=>Fe,XykPoolClient:()=>De});var R=require("@galacticcouncil/math-xyk"),$=class{static getSpotPrice(e,t,n){return(0,R.get_spot_price)(e,t,n)}static calculateInGivenOut(e,t,n){return(0,R.calculate_in_given_out)(e,t,n)}static calculateOutGivenIn(e,t,n){return(0,R.calculate_out_given_in)(e,t,n)}static calculatePoolTradeFee(e,t,n){return(0,R.calculate_pool_trade_fee)(e,t,n)}static calculateLiquidityIn(e,t,n){return(0,R.calculate_liquidity_in)(e,t,n)}static calculateSpotPrice(e,t){return(0,R.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,n,s){return(0,R.calculate_spot_price_with_fee)(e,t,n,s)}static calculateShares(e,t,n){return(0,R.calculate_shares)(e,t,n)}static calculateLiquidityOutAssetA(e,t,n,s){return(0,R.calculate_liquidity_out_asset_a)(e,t,n,s)}static calculateLiquidityOutAssetB(e,t,n,s){return(0,R.calculate_liquidity_out_asset_b)(e,t,n,s)}};var Fe=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=h.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=h.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=$.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(e,t){let n=$.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(e){let t=$.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){let t=$.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateTradeFee(e,t){let n=$.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return BigInt(n)}};var on=require("polkadot-api"),ln=require("rxjs");var De=class extends N{async loadPools(){let e=this.api.query.XYK.PoolAssets,[t,n]=await Promise.all([e.getEntries(),this.getPoolLimits()]),s=t.map(async({keyArgs:a,value:i})=>{let[r]=a,[o,l]=i,[c,d,p,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:d?.decimals,existentialDeposit:d?.existential_deposit,balance:c.transferable,type:d?.asset_type.type},{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:p.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(on.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){return(0,ln.of)(e)}};var At={};S(At,{AavePool:()=>ke,AavePoolClient:()=>Ce});var ke=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,n,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}};var un=require("polkadot-api"),pn=require("@polkadot-api/utils"),me=require("rxjs"),mn=require("viem");var cn=[{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:jn}=ee,Kn=["Supply","Withdraw","Repay","Borrow"],Ce=class extends N{async loadPools(){let t=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:s,liqudity_in: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=(0,pn.toHex)(s);return(0,un.AccountId)(63).dec(a)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(e){let[t,n]=e.tokens,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(g=>g.asHex()),d=l.asHex(),{eventName:p,args:m}=(0,mn.decodeEventLog)({abi:cn,topics:c,data:d});return Kn.includes(p)&&m.reserve.toLowerCase()===s.toLowerCase()});return(0,me.merge)([a,i]).pipe((0,me.switchMap)(()=>this.getPoolDelta(e)),(0,me.map)(r=>({...e,tokens:[...r]})))}getReserveH160Id(e){return e.type==="Erc20"?Z.findNestedKey(e.location,"AccountKey20").AccountKey20.key:jn.fromAssetId(e.id)}};var de=class{static get(e){switch(e.type){case"Aave":return ke.fromPool(e);case"XYK":return Fe.fromPool(e);case"Omnipool":return Ae.fromPool(e);case"LBP":return Oe.fromPool(e);case"Stableswap":return Re.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var j=require("rxjs");var ge=class extends M{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=j.Subscription.EMPTY;omniSub=j.Subscription.EMPTY;stableSub=j.Subscription.EMPTY;xykSub=j.Subscription.EMPTY;aaveSub=j.Subscription.EMPTY;isReady=!1;isDestroyed=new j.Subject;constructor(e){super(e),this.lbpClient=new ve(e),this.omniClient=new _e(e),this.stableClient=new Ee(e),this.xykClient=new De(e),this.aaveClient=new Ce(e),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(e){return e.getSubscriber().pipe((0,j.takeUntil)(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(e){return this.xykClient.withOverride(e),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let e=await Promise.all(this.clients.filter(t=>this.active.has(t.getPoolType())).map(t=>t.getPools()));return this.isReady=!0,e.flat()}async getPoolFees(e,t){let n=this.clients.find(s=>s.getPoolType()===e.type);if(n)return n.getPoolFees(e,t);throw new Se(e.type)}};var Ct={};S(Ct,{DEFAULT_BLOCK_TIME:()=>dn,DEFAULT_MIN_BUDGET:()=>Et,ORDER_MIN_BLOCK_PERIOD:()=>gn,Router:()=>be,TWAP_BLOCK_PERIOD:()=>qe,TWAP_MAX_DURATION:()=>Dt,TWAP_MAX_PRICE_IMPACT:()=>Ft,TWAP_TX_MULTIPLIER:()=>Do,TradeOrderError:()=>Rt,TradeOrderType:()=>Qe,TradeRouteBuilder:()=>H,TradeRouter:()=>ye,TradeScheduler:()=>he,TradeType:()=>$e});var ze=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 zn=5,Me=class{isNotVisited(e,t){let n=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(n=!1)}),n}findPaths(e,t,n){let s=[],a=new ze,i=[];for(i.push([t,""]),a.enqueue(i);a.size()>0;){let r=a.dequeue();if(r==null||r.length>zn)return s;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 d=[...r];d.push(c),a.enqueue(d)}})}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 _t(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 Le=class{getProposals(e,t,n){let s=_t(n),a=Object.keys(s),i=a.map(c=>s[c]).flat(),r=new Me,o=r.buildAndPopulateGraph(a,i),l=r.findPaths(o,e,t);return this.parsePaths(l)}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 be=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(e,t){this.ctx=e,this.routeSuggester=new Le,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=await this.ctx.getPools(),t=this.routerOptions.useOnly;return t.length===0?e:e.filter(n=>t.includes(n.type))}async getRoutes(e,t){let n=await this.getPools();return this.validateInput(e,t,n),this.getPaths(e,t,n)}async getTradeableAssets(){let e=await this.getPools(),t=this.getAssets(e);return Array.from(t)}validateInput(e,t,n){if(n.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(n);if(!s.has(e))throw new Error(e+" is not supported asset");if(!s.has(t))throw new Error(t+" is not supported asset");return this.toPoolsMap(n)}getAssets(e){let t=e.map(n=>n.tokens.map(s=>s.id)).flat().sort((n,s)=>n>s?1:-1);return new Set(t)}getPaths(e,t,n){let s=this.toPoolsMap(n);return this.routeSuggester.getProposals(e,t,n).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}validPath(e,t){return e.length>0&&e.map(n=>this.validEdge(n,t)).reduce((n,s)=>n&&s)}validEdge([e,t,n],s){return s.get(e)?.validatePair(t,n)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,de.get(t)]))}toHops(e,t){return e.map(([n,s,a])=>{let i=t.get(n);return{poolAddress:n,poolId:i?.id,pool:i?.type,assetIn:s,assetOut:a}})}};var $e=(t=>(t.Buy="Buy",t.Sell="Sell",t))($e||{}),Qe=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Qe||{}),Rt=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(Rt||{});var ye=class extends be{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?h.toPct(e.min):void 0,n=e.max?h.toPct(e.max):void 0;if(t&&n)return[t,n]}async getBestSell(e,t,n){return this.getSell(e,t,n)}async getSellSpot(e){let t=e[e.length-1];if(e.length===1)return t.spotPrice;let n=e.map(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){let a=await super.getPools(),i=super.validateInput(e,t,a),r=super.getPaths(e,t,a);if(r.length===0)throw new ue(e,t);let o;if(s)o=await this.toSellSwaps(n,s,i);else{let E=await Promise.all(r.map(k=>this.toSellSwaps(n,k,i)));o=this.findBestSellRoute(E)}let l=o[0],c=o[o.length-1],d=this.isDirectTrade(o),p=await this.getSellSpot(o),m=c.amountOut,g=d?c.calculatedOut:this.calculateDelta0Y(l.amountIn,o,i),P=g-m,y=this.getRouteFeeRange(o),I=d?c.tradeFeePct:A.calculateSellFee(g,m),f=Math.pow(10,l.assetInDecimals),T=l.amountIn*p/BigInt(f),v=A.calculateDiffToRef(g,T);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:p,tradeFee:P,tradeFeePct:I,tradeFeeRange:y,priceImpactPct:v,swaps:o,toHuman(){return{type:"Sell",amountIn:b.toDecimal(l.amountIn,l.assetInDecimals),amountOut:b.toDecimal(c.amountOut,c.assetOutDecimals),spotPrice:b.toDecimal(p,c.assetOutDecimals),tradeFee:b.toDecimal(P,c.assetOutDecimals),tradeFeePct:I,tradeFeeRange:y,priceImpactPct:v,swaps:o.map(E=>E.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 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"?b.toBigInt(e,o.decimalsIn):e;let c=await this.ctx.getPoolFees(r,o.assetOut),{amountOut:d,calculatedOut:p,feePct:m,errors:g}=r.validateAndSell(o,l,c),P=this.getPoolFeeRange(c),y=r.spotPriceOutGivenIn(o),I=Math.pow(10,o.decimalsIn),f=l*y/BigInt(I),T=A.calculateDiffToRef(p,f);s.push({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:d,calculatedOut:p,spotPrice:y,tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g,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:b.toDecimal(l,o.decimalsIn),amountOut:b.toDecimal(d,o.decimalsOut),calculatedOut:b.toDecimal(p,o.decimalsOut),spotPrice:b.toDecimal(y,o.decimalsOut),tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}async getMostLiquidRoute(e,t){let n=await super.getPools(),s=super.validateInput(e,t,n),a=super.getPaths(e,t,n),o=n.filter(p=>p.tokens.some(m=>m.id===e&&m.id!==p.id)).map(p=>p.type==="Aave"?p.tokens:p.tokens.filter(m=>m.id===e)).map(p=>p.map(m=>m.balance).reduce((m,g)=>m+g)).sort((p,m)=>m<p?-1:1)[0],l=A.getFraction(o,.1),c=await Promise.all(a.map(p=>this.toSellSwaps(l,p,s)));return this.findBestSellRoute(c).map(p=>({poolAddress:p.poolAddress,poolId:p?.poolId,pool:p.pool,assetIn:p.assetIn,assetOut:p.assetOut}))}async getSpotPrice(e,t){let n=await super.getPools(),s=super.validateInput(e,t,n),a=await this.getMostLiquidRoute(e,t),i=await this.toSellSwaps("1",a,s),r=await this.getSellSpot(i),o=i[i.length-1].assetOutDecimals;return{amount:r,decimals:o}}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)}async 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){let a=await super.getPools(),i=super.validateInput(e,t,a),r=super.getPaths(e,t,a);if(r.length===0)throw new ue(e,t);let o;if(s)o=await this.toBuySwaps(n,s,i);else{let E=await Promise.all(r.map(k=>this.toBuySwaps(n,k,i)));o=this.findBestBuyRoute(E)}let l=o[o.length-1],c=o[0],d=this.isDirectTrade(o),p=await this.getBuySpot(o),m=c.amountIn,g=d?c.calculatedIn:this.calculateDelta0X(l.amountOut,o,i),P=m-g,y=this.getRouteFeeRange(o),I=d?c.tradeFeePct:A.calculateBuyFee(g,m),f=Math.pow(10,l.assetOutDecimals),T=l.amountOut*p/BigInt(f),v;return g===0n?v=-100:v=A.calculateDiffToRef(T,g),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:p,tradeFee:P,tradeFeePct:I,tradeFeeRange:y,priceImpactPct:v,swaps:o,toHuman(){return{type:"Buy",amountOut:b.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:b.toDecimal(c.amountIn,c.assetInDecimals),spotPrice:b.toDecimal(p,c.assetInDecimals),tradeFee:b.toDecimal(P,c.assetInDecimals),tradeFeePct:I,tradeFeeRange:y,priceImpactPct:v,swaps:o.map(E=>E.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"?b.toBigInt(e,o.decimalsOut):e:l=s[0].amountIn;let c=await this.ctx.getPoolFees(r,o.assetOut),{amountIn:d,calculatedIn:p,feePct:m,errors:g}=r.validateAndBuy(o,l,c),P=this.getPoolFeeRange(c),y=r.spotPriceInGivenOut(o),I=Math.pow(10,o.decimalsOut),f=l*y/BigInt(I),T;p===0n?T=-100:T=A.calculateDiffToRef(f,p),s.unshift({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:d,calculatedIn:p,spotPrice:y,tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g,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:b.toDecimal(l,o.decimalsOut),amountIn:b.toDecimal(d,o.decimalsIn),calculatedIn:b.toDecimal(p,o.decimalsIn),spotPrice:b.toDecimal(y,o.decimalsIn),tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}};var dn=6e3,Et=1000000000000000n,qe=6,Ft=-5,Dt=216e5,Do=3,gn=6;var kt=require("polkadot-api");var H=class{static build(e){return e.map(({assetIn:t,assetOut:n,pool:s,poolId:a})=>s==="Stableswap"?{pool:(0,kt.Enum)("Stableswap",a),asset_in:t,asset_out:n}:{pool:(0,kt.Enum)(s),asset_in:t,asset_out:n})}};var he=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??6e3,minBudgetInNative:t.minBudgetInNative??Et})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,n,s,a){let[i,r]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:o,swaps:l,priceImpactPct:c}=r,d=l[0],p=l[l.length-1],{assetInDecimals:m}=d,{assetOutDecimals:g}=p,P=Math.abs(c),y=this.getMinimumTradeCount(o,i),I=this.getOptimalTradeCount(P),f=a?Math.round(s/a):I,T=Math.ceil(s/y),v=Math.round(s/I),E=Math.round(s/f),k=o/BigInt(f),C=await this.router.getBestSell(e,t,k),Q=o<i,Ne=[];Q&&Ne.push("OrderTooSmall");let He=C.amountOut*BigInt(f),tt=this.toBlockPeriod(E),nt=C.tradeFee*BigInt(f),yn=H.build(l),qt={assetIn:e,assetOut:t,errors:Ne,frequencyMin:T,frequencyOpt:v,frequency:E,tradeCount:f,tradeFee:nt,tradeImpactPct:C.priceImpactPct,tradePeriod:tt,tradeRoute:yn,type:"Dca"};return{...qt,amountIn:o,amountOut:He,tradeAmountIn:C.amountIn,tradeAmountOut:C.amountOut,toHuman(){return{...qt,amountIn:b.toDecimal(o,m),amountOut:b.toDecimal(He,g),tradeAmountIn:b.toDecimal(C.amountIn,m),tradeAmountOut:b.toDecimal(C.amountOut,g)}}}}async getMinimumOrderBudget(e){if(0===e)return this.minOrderBudget;let t=await this.router.getSpotPrice(0,e),n=10n**BigInt(12);if(t)return this.minOrderBudget*t.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let n=t*2n/10n;if(n===0n)return 0;let s=e+n/2n;return Number(s/n)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,n){let[s,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:d}=l,{assetOutDecimals:p}=c,m=Math.abs(o),g=this.getTwapTradeCount(m),P=i/BigInt(g),y=await this.router.getBestSell(l.assetIn,c.assetOut,P),I=g===1,f=i<s,T=y.priceImpactPct<-5,v=[];f||I?v.push("OrderTooSmall"):T&&v.push("OrderImpactTooBig");let E=y.amountOut*BigInt(g),k=y.tradeFee*BigInt(g),C=H.build(r),Q={assetIn:e,assetOut:t,errors:v,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:6,tradeRoute:C,type:"TwapSell"};return{...Q,amountIn:i,amountOut:E,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:k,toHuman(){return{...Q,amountIn:b.toDecimal(i,d),amountOut:b.toDecimal(E,p),tradeAmountIn:b.toDecimal(y.amountIn,d),tradeAmountOut:b.toDecimal(y.amountOut,p),tradeFee:b.toDecimal(k,p)}}}}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:d}=l,{assetOutDecimals:p}=c,m=Math.abs(o),g=this.getTwapTradeCount(m),P=i/BigInt(g),y=await this.router.getBestBuy(l.assetIn,c.assetOut,P),I=y.amountIn*BigInt(g),f=g===1,T=I<s,v=y.priceImpactPct<-5,E=[];T||f?E.push("OrderTooSmall"):v&&E.push("OrderImpactTooBig");let k=y.tradeFee*BigInt(g),C=H.build(r),Q={assetIn:e,assetOut:t,errors:E,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:6,tradeRoute:C,type:"TwapBuy"};return{...Q,amountIn:I,amountOut:i,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:k,toHuman(){return{...Q,amountIn:b.toDecimal(I,d),amountOut:b.toDecimal(i,p),tradeAmountIn:b.toDecimal(y.amountIn,d),tradeAmountOut:b.toDecimal(y.amountOut,p),tradeFee:b.toDecimal(k,d)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}return t}getTwapExecutionTime(e){return e*6*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,n=Math.round(t);return Math.max(n,6)}};var Lt={};S(Lt,{TxBuilderFactory:()=>fe});var Mt=require("polkadot-api");function bn(u){let e=[],t=u;for(;t&&typeof t=="object"&&"type"in t;)e.push(t.type),t=t.value;return e.join(".")}var Pe=class extends M{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new L,this.balanceClient=new X(e),this.aaveUtils=new te(this.evmClient)}wrapTx(e,t){return{name:e,get:()=>t,dryRun:n=>this.dryRun(n,t)}}async dispatchWithExtraGas(e){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:e.decodedCall,extra_gas:ot})}async dryRun(e,t){let n=(0,Mt.Enum)("Signed",e),s=(0,Mt.Enum)("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=bn(r.value);throw new Error("Dry run execution error!",{cause:o})}return i}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Je=class extends Pe{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:s}=t[0],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=A.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:H.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=A.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:H.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=A.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:H.build(t)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var Ze=require("polkadot-api");var et=class extends Pe{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:s,tradePeriod: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:(0,Ze.Enum)("Sell",{asset_in:t,asset_out:n,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",r)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:s,tradeAmountOut:a,tradePeriod:i,tradeRoute:r}=this.order,o=A.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:(0,Ze.Enum)("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=A.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:(0,Ze.Enum)("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 fe=class{client;evmClient;constructor(e,t){this.client=e,this.evmClient=t??new L}trade(e){return new Je(this.client,this.evmClient).setTrade(e)}order(e){return new et(this.client,this.evmClient).setOrder(e)}};async function $n(u,e){let t=new ce(u),[n,s]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),a=e??new L,i=new ge(u).withAave().withOmnipool().withStableswap().withXyk(),r=new te(a),o=new ye(i),l=new he(o,{blockTime:n,minBudgetInNative:s});return{api:{aave:r,router:o,scheduler:l},client:{asset:new le(u),balance:new X(u),evm:a},ctx:{pool:i},tx:new fe(u,a),destroy:()=>{i.destroy()}}}0&&(module.exports={aave,api,big,client,const:null,createSdkContext,erc20,error,evm,fmt,h160,json,math,pool,sor,tx,xc});
|
|
1
|
+
"use strict";var hn=Object.create;var Ue=Object.defineProperty;var Pn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var Tn=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty;var Ht=(c,e)=>()=>(c&&(e=c(c=0)),e);var I=(c,e)=>{for(var t in e)Ue(c,t,{get:e[t],enumerable:!0})},Ge=(c,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fn(e))!xn.call(c,s)&&s!==t&&Ue(c,s,{get:()=>e[s],enumerable:!(n=Pn(e,s))||n.enumerable});return c},ae=(c,e,t)=>(Ge(c,e,"default"),t&&Ge(t,e,"default")),st=(c,e,t)=>(t=c!=null?hn(Tn(c)):{},Ge(e||!c||!c.__esModule?Ue(t,"default",{value:c,enumerable:!0}):t,c)),Sn=c=>Ge(Ue({},"__esModule",{value:!0}),c);var Te={};var Wt=Ht(()=>{ae(Te,require("@polkadot-api/ws-provider/node"))});var xe={};var Vt=Ht(()=>{ae(xe,require("@polkadot-api/ws-provider/web"))});var Jn={};I(Jn,{aave:()=>Tt,api:()=>rt,big:()=>y,client:()=>xt,const:()=>gt,createSdkContext:()=>Qn,erc20:()=>ee,error:()=>wt,evm:()=>ut,fmt:()=>h,h160:()=>we,json:()=>Z,math:()=>A,pool:()=>_t,sor:()=>Mt,tx:()=>qt,xc:()=>Pt});module.exports=Sn(Jn);var rt={};I(rt,{Papi:()=>M,getWs:()=>wn});var Ut=require("@galacticcouncil/descriptors");function Gt(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var M=class{client;api;constructor(e){this.client=e,this.api=this.client.getTypedApi(Ut.hydration)}log(e,...t){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Gt(n)&&console.log(e,...t)}};var Xt=require("polkadot-api"),Yt=require("polkadot-api/polkadot-sdk-compat"),wn=async c=>{let e=typeof c=="string"?c.split(","):c,s=(typeof window>"u"?(await Promise.resolve().then(()=>(Wt(),Te))).getWsProvider:(await Promise.resolve().then(()=>(Vt(),xe))).getWsProvider)(e);return(0,Xt.createClient)((0,Yt.withPolkadotSdkCompat)(s))};var Tt={};I(Tt,{AAVE_GAS_LIMIT:()=>ot,AAVE_LENDING_POOL_ADDRESS:()=>Xe,AAVE_POOL_ABI:()=>at,AAVE_POOL_DATA_PROVIDER:()=>Ve,AAVE_POOL_DATA_PROVIDER_ABI:()=>We,AAVE_POOL_PROXY:()=>it,AAVE_ROUNDING_THRESHOLD:()=>gs,AAVE_UINT_256_MAX:()=>In,AaveClient:()=>Se,AaveUtils:()=>te});var at=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var We=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var it="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ve="0x112b087b60C1a166130d59266363C45F8aa99db0",Xe="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ot=1000000n,gs=5,In=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ut={};I(ut,{EvmClient:()=>L,evmMainnet:()=>lt});var Kt=require("viem"),jt=["https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],zt=["wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],lt=(0,Kt.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:jt,webSocket:zt},default:{http:jt,webSocket:zt}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var G=require("viem");var L=class{chain;constructor(e){this.chain=e||lt}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}async getGasPrice(){return this.getProvider().getGasPrice()}getProvider(){return(0,G.createPublicClient)({chain:this.chain,transport:(0,G.http)()})}getWsProvider(){return(0,G.createPublicClient)({chain:this.chain,transport:(0,G.webSocket)()})}getSigner(e){return(0,G.createWalletClient)({account:e,chain:this.chain,transport:(0,G.custom)(window.ethereum)})}};var Se=class{evmClient;constructor(e){this.evmClient=e??new L}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:We,address:Ve,args:[Xe],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:We,address:Ve,args:[Xe,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:at,address:it,args:[e],functionName:"getUserAccountData"})}};var y={};I(y,{asBigInt:()=>An,toBigInt:()=>vn,toDecimal:()=>On});var J=st(require("big.js"));J.default.NE=-18;function On(c,e,t=6,n){let s=(0,J.default)(c.toString()),r=(0,J.default)(10).pow(e);return s.div(r).round(t,n).toString()}function vn(c,e){let t=(0,J.default)(10).pow(e),s=(0,J.default)(c).mul(t).toFixed(0,J.default.roundDown);return BigInt(s)}function An(c){return BigInt(c.round(0,J.default.roundDown).toFixed(0))}var ee={};I(ee,{ERC20:()=>ct});var ct=class{static fromAssetId(e){let t=Buffer.alloc(20,0);return t[15]=1,t.writeUInt32BE(e,16),"0x"+t.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(e.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(t.subarray(0,16))}};var h={};I(h,{fromPermill:()=>Rn,toDecimals:()=>_n,toPct:()=>Bn});var $t=1e3;function Bn(c){let[e,t]=c;return e/t*100}function _n(c){let[e,t]=c;return e/t}function Rn(c){return[c/$t,$t]}var we={};I(we,{H160:()=>ht,isEvmAccount:()=>Qt,isEvmAddress:()=>Jt,isSs58Address:()=>Zt});var oe=require("polkadot-api"),bt=require("@polkadot-api/utils"),K=require("buffer");var gt={};I(gt,{HUB_ASSET_ID:()=>dt,HYDRATION_OMNIPOOL_ADDRESS:()=>Dn,HYDRATION_PARACHAIN_ID:()=>En,HYDRATION_SS58_PREFIX:()=>W,PERBILL_DENOMINATOR:()=>Fn,PERMILL_DENOMINATOR:()=>pt,RUNTIME_DECIMALS:()=>q,SYSTEM_ASSET_DECIMALS:()=>mt,SYSTEM_ASSET_ID:()=>z,TRADEABLE_DEFAULT:()=>ie});var q=18,pt=1e6,Fn=1e9,z=0,mt=12,En=2034,W=63,Dn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",dt=1,ie=15;var yt="ETH\0";function Qt(c){if(!c)return!1;try{let e=(0,oe.AccountId)().enc(c),t=K.Buffer.from(yt);return K.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Jt(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function Zt(c){try{return(0,oe.AccountId)(63).enc(c),!0}catch{return!1}}var ht=class c{static toAccount=e=>{let t=K.Buffer.from(e.slice(2),"hex"),n=K.Buffer.from(yt),s=Uint8Array.from(K.Buffer.concat([n,t,K.Buffer.alloc(8)])),r=(0,bt.toHex)(s);return(0,oe.AccountId)(63).dec(r)};static fromAccount=e=>{let t=(0,oe.AccountId)().enc(e),n=K.Buffer.from(yt),s=t.slice(n.length,-8);return"0x"+K.Buffer.from(s).toString("hex")};static fromSS58=e=>{let n=(0,oe.AccountId)().enc(e).slice(0,20);return(0,bt.toHex)(n)};static fromAny=e=>{if(Jt(e))return e;if(Qt(e))return c.fromAccount(e);if(Zt(e))return c.fromSS58(e);throw new Error("Unknown address type")}};var Z={};I(Z,{findNestedKey:()=>kn,findNestedObj:()=>Cn,jsonFormatter:()=>Mn});var kn=(c,e)=>{let t=[];return JSON.stringify(c,(n,s)=>(s&&s[e]&&t.push(s),s)),t[0]},Cn=(c,e,t)=>{let n;return JSON.stringify(c,(s,r)=>(r&&r[e]===t&&(n=r),r)),n},Mn=(c,e)=>typeof e=="bigint"?e.toString():e;var A={};I(A,{calculateBuyFee:()=>Hn,calculateDiffToAvg:()=>Ln,calculateDiffToRef:()=>qn,calculateSellFee:()=>Nn,getFraction:()=>Gn});var V=st(require("big.js"));function Ln(c,e){let t=(0,V.default)(c.toString()),n=(0,V.default)(e.toString());return t.minus(n).abs().div(t.plus(n).div(2)).mul(100).round(2).toNumber()}function qn(c,e){if(e===0n)return 0;let t=(0,V.default)(c.toString()),n=(0,V.default)(e.toString());return t.minus(n).div(n).mul(100).round(2).toNumber()}function Nn(c,e){let t=(0,V.default)(c.toString()),n=(0,V.default)(e.toString());return(0,V.default)(1).minus(n.div(t)).mul(100).round(2).toNumber()}function Hn(c,e){let t=(0,V.default)(c.toString());return(0,V.default)(e.toString()).div(t).minus(1).mul(100).round(2).toNumber()}function Gn(c,e,t=2){(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,t),s=BigInt(e*n);return c*s/BigInt(100*n)}var Pt={};I(Pt,{convertToId:()=>Un});var en=require("buffer");function Un(c){let t=en.Buffer.from(c.replace("0x",""),"hex").subarray(16);return t.readUIntBE(0,t.length)}var{ERC20:Ye}=ee,{H160:ft}=we,Wn=1.01,Vn=99999,Xn=10n**27n,Yn=10n**18n,te=class{client;constructor(e){let t=e??new L;this.client=new Se(t)}async getSummary(e){let t=ft.fromAny(e),[n,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t)]),[i]=n,[a,o]=s,[l,u,d,p,m,g]=r,P=y.toDecimal(g,18),b=[];for(let x of a){let f=x.underlyingAsset.toLowerCase(),T=i.find(({underlyingAsset:nt})=>nt.toLowerCase()===f);if(!T)throw new Error("Missing pool reserve for "+f);let v=x.scaledATokenBalance,F=T.liquidityIndex,k=T.priceInMarketReferenceCurrency,C=v*F/Xn,Ne=Number(o===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,He=T.usageAsCollateralEnabled&&x.usageAsCollateralEnabledOnUser&&x.scaledATokenBalance>0n,tt=Ye.toAssetId(f);b.push({aTokenBalance:C,decimals:Number(T.decimals),isCollateral:He,priceInRef:k,reserveId:tt,reserveAsset:f,reserveLiquidationThreshold:Ne})}return{healthFactor:Number(P),totalCollateral:l,totalDebt:u,reserves:b}}async hasBorrowPositions(e){let t=ft.fromAny(e),n=await this.client.getUserAccountData(t),[s,r]=n;return r>0n}async getHealthFactor(e){let t=ft.fromAny(e),n=await this.client.getUserAccountData(t),[s,r,i,a,o,l]=n,u=y.toDecimal(l,18);return Number(u)}async getHealthFactorAfterWithdraw(e,t,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(e),a=Ye.fromAssetId(t),o=i.find(b=>b.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,isCollateral:u,priceInRef:d,reserveLiquidationThreshold:p}=o,m=y.toBigInt(n,l),g=u?m*d/10n**BigInt(l):0n,P=s-g;return P<=0n?0:this.calculateHealthFactor(P,p,r)}async getHealthFactorAfterSupply(e,t,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(e),a=Ye.fromAssetId(t),o=i.find(P=>P.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:d}=o,m=y.toBigInt(n,l)*u/10n**BigInt(l),g=s+m;return g<=0n?0:this.calculateHealthFactor(g,d,r)}async getMaxWithdraw(e,t){let{totalCollateral:n,totalDebt:s,reserves:r}=await this.getSummary(e),i=Ye.fromAssetId(t),a=r.find(o=>o.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(a,n,s)}async getMaxWithdrawAll(e){let{totalCollateral:t,totalDebt:n,reserves:s}=await this.getSummary(e),r={};for(let i of s){let a=this.calculateWithdrawMax(i,t,n);i.reserveId&&(r[i.reserveId]=a)}return r}calculateHealthFactor(e,t,n){if(n===0n)return Vn;let s=10n**6n,r=y.toBigInt(t,18),i=e*r*s,a=n*Yn,o=i/a;return Number(o)/1e6}calculateRequiredCollateral(e,t,n){let s=y.toBigInt(e,18),r=y.toBigInt(t,18);return(s*n+r-1n)/r}calculateWithdrawMax(e,t,n){let{aTokenBalance:s,decimals:r,priceInRef:i,reserveLiquidationThreshold:a}=e,o=this.calculateRequiredCollateral(Wn,a,n),l=t-o;if(l<=0n)return{amount:0n,decimals:r};let u=l*10n**BigInt(r)/i;return{amount:s<u?s:u,decimals:r}}};var xt={};I(xt,{AssetClient:()=>le,BalanceClient:()=>X,ChainParams:()=>ue});var le=class extends M{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async queryShares(){let t=await this.api.query.Stableswap.Pools.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryBonds(){let t=await this.api.query.Bonds.Bonds.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssets(){let t=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(t.filter(({value:n})=>{let{asset_type:s}=n;return this.SUPPORTED_TYPES.includes(s.type)}).map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssetLocations(){let t=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async mapToken(e,t,n,s){let{name:r,asset_type:i,is_sufficient:a,existential_deposit:o}=t,{symbol:l,decimals:u}=n.get(e)??{};return{id:e,name:r?.asText(),symbol:l,decimals:u,icon:l,type:i.type,isSufficient:a,location:s,existentialDeposit:o}}async mapBond(e,t,n,s){let[r,i]=s,{asset_type:a,is_sufficient:o,existential_deposit:l}=t,{symbol:u,decimals:d}=await this.mapToken(r,t,n),p=Number(i),m=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",m.format(p)].join(" ");return{id:e,name:g,symbol:u+"b",decimals:d,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:r,maturity:p}}async mapShares(e,t,n,s){let{assets:r}=s,{name:i,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=t,d=await Promise.all(r.map(async g=>{let{symbol:P}=await this.mapToken(g,t,n);return[g,P]})),p=Object.fromEntries(d),m=Object.values(p);return{id:e,name:m.join(", "),symbol:a?.asText()||i?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:p}}async mapExternal(e,t,n,s){let r=await this.mapToken(e,t,new Map,s),i=n?.find(a=>a.internalId===r.id);return i?{...r,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:r}parseMetadata(e){return new Map(Array.from(e,([t,n])=>[t,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(e,t){let[n,s,r,i]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(n),o=[];for(let[l,u]of Array.from(n)){let d=s.get(l),{asset_type:p}=u,m;switch(p.type){case"Bond":let g=i.get(l);m=await this.mapBond(l,u,a,g);break;case"StableSwap":let P=r.get(l);m=await this.mapShares(l,u,a,P);break;case"External":m=await this.mapExternal(l,u,t,d);break;default:m=await this.mapToken(l,u,a,d)}o.push(m)}return e?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};var w=require("rxjs");var X=class extends M{constructor(e){super(e)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getTokenBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:{free:n,frozen:s}}=await t.getValue(e);return n-s}async getTokenBalance(e,t){let n=this.api.query.Tokens.Accounts,{free:s,frozen:r}=await n.getValue(e,t);return s-r}async getErc20Balance(e,t){return this.getTokenBalanceData(e,t)}subscribeBalance(e){let t=this.subscribeSystemBalance(e),n=this.subscribeTokensBalance(e),s=this.subscribeErc20Balance(e);return(0,w.combineLatest)([t,n,s]).pipe((0,w.debounceTime)(250),(0,w.map)(r=>r.flat()),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([r,i],a)=>{if(a===0)return i;let o=r.reduce((u,d)=>(u.set(d.id,d.amount),u),new Map);return i.filter(u=>u.amount!==o.get(u.id))}))}subscribeSystemBalance(e){return this.api.query.System.Account.watchValue(e,"best").pipe((0,w.map)(n=>{let{free:s,frozen:r}=n.data;return{id:0,amount:s-r}}))}subscribeTokenBalance(e,t){return this.api.query.Tokens.Accounts.watchValue(e,t,"best").pipe((0,w.map)(s=>{let{free:r,frozen:i}=s;return{id:t,amount:r-i}}))}subscribeTokensBalance(e){return this.api.query.Tokens.Accounts.watchEntries(e,{at:"best"}).pipe((0,w.distinctUntilChanged)((n,s)=>!s.deltas),(0,w.map)(({deltas:n})=>{let s=[];return n?.deleted.forEach(r=>{let[i,a]=r.args;s.push({id:a,amount:0n})}),n?.upserted.forEach(r=>{let[i,a]=r.args,{free:o,frozen:l}=r.value;s.push({id:a,amount:o-l})}),s}))}subscribeErc20Balance(e,t){let n=new w.Subject,s=n.pipe((0,w.shareReplay)(1)),r=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:u}=l;return u.type==="Erc20"}).map(({keyArgs:l})=>{let[u]=l;return u}),i=async()=>{let o=t||await r(),l=async()=>{let p=(await Promise.all(o.map(async m=>{let g=await this.getTokenBalanceData(e,m);return[m,g]}))).map(([m,g])=>({id:m,amount:g}));n.next(p)};await l();let u=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>u.unsubscribe()},a;return i().then(o=>a=o),s.pipe((0,w.finalize)(()=>a?.()),(0,w.pairwise)(),(0,w.map)(([o,l],u)=>{if(u===0)return l;let d=o.reduce((m,g)=>(m.set(g.id,g.amount),m),new Map);return l.filter(m=>m.amount!==d.get(m.id))}),(0,w.distinctUntilChanged)((o,l)=>l.length===0))}async getTokenBalanceData(e,t){let{free:n,frozen:s}=await this.api.apis.CurrenciesApi.account(t,e);return n-s}};var ue=class extends M{_minOrderBudget;_blockTime;constructor(e){super(e)}async getBlockTime(){if(this._blockTime===void 0){let e=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(e)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var wt={};I(wt,{AssetNotFound:()=>St,PoolNotFound:()=>Ie,RouteNotFound:()=>ce});var St=class extends Error{constructor(e){super(),this.message=`${e} not found`,this.name="AssetNotFound"}},Ie=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},ce=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in current configuration`,this.name="RouteNotFound"}};var _t={};I(_t,{PoolContextProvider:()=>ge,PoolError:()=>ne,PoolFactory:()=>de,PoolType:()=>E,aave:()=>Bt,lbp:()=>It,omni:()=>Ot,stable:()=>vt,xyk:()=>At});var It={};I(It,{LbpMath:()=>U,LbpPool:()=>Oe,LbpPoolClient:()=>ve});var Y=require("@galacticcouncil/math-lbp"),U=class{static getSpotPrice(e,t,n,s,r){return(0,Y.get_spot_price)(e,t,n,s,r)}static calculateInGivenOut(e,t,n,s,r){return(0,Y.calculate_in_given_out)(e,t,n,s,r)}static calculateOutGivenIn(e,t,n,s,r){return(0,Y.calculate_out_given_in)(e,t,n,s,r)}static calculateLinearWeights(e,t,n,s,r){return(0,Y.calculate_linear_weights)(e,t,n,s,r)}static calculatePoolTradeFee(e,t,n){return(0,Y.calculate_pool_trade_fee)(e,t,n)}};var E=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r))(E||{}),ne=(r=>(r.InsufficientTradingAmount="InsufficientTradingAmount",r.MaxInRatioExceeded="MaxInRatioExceeded",r.MaxOutRatioExceeded="MaxOutRatioExceeded",r.TradeNotAllowed="TradeNotAllowed",r.UnknownError="UnknownError",r))(ne||{});var Oe=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,n,s,r,i,a){this.type="LBP",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.fee=i,this.repayFeeApply=a}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,weightIn:s.weight,weightOut:r.weight}}validateAndBuy(e,t,n){let s=this.tokens[0].id,r=[];t<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=e.balanceOut/this.maxOutRatio;if(t>i&&r.push("MaxOutRatioExceeded"),s===e.assetOut){let a=this.calculateTradeFee(t,n),o=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=t+a,u=this.calculateInGivenOut(e,l),d=e.balanceIn/this.maxInRatio;return u>d&&r.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:t,feePct:o,errors:r}}else{let a=this.calculateInGivenOut(e,t),o=e.balanceIn/this.maxInRatio;return a>o&&r.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:t,feePct:0,errors:r}}}validateAndSell(e,t,n){let s=this.tokens[0].id,r=[];t<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=e.balanceIn/this.maxInRatio;if(t>i&&r.push("MaxInRatioExceeded"),s===e.assetIn){let a=this.calculateOutGivenIn(e,t),o=e.balanceOut/this.maxOutRatio;return a>o&&r.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:a,feePct:0,errors:r}}else{let a=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(a,n),l=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),u=a-o,d=e.balanceOut/this.maxOutRatio;return u>d&&r.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:u,feePct:l,errors:r}}}calculateInGivenOut(e,t){let n=U.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(e,t){let n=U.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(e){let t=U.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),this.maxOutRatio.toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=U.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),this.maxInRatio.toString());return BigInt(t)}calculateTradeFee(e,t){let n=U.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return BigInt(n)}};var nn=require("polkadot-api"),se=require("rxjs");var tn=(c,e=new Map)=>t=>{let n;return e.has(t)?e.get(t):(e.set(t,n=c(t)),n)};var O=require("rxjs");var N=class extends X{override=[];mem=0;memPools=tn(e=>(this.log(this.getPoolType(),"mem pools",e,"\u2705"),this.loadPools()));constructor(e){super(e)}async withOverride(e){this.override=e||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let e=(0,O.from)(this.getPoolsMem()).pipe((0,O.switchMap)(t=>this.subscribe(t)),(0,O.combineLatestAll)());return(0,O.firstValueFrom)(e)}getSubscriber(){return(0,O.from)(this.getPoolsMem()).pipe((0,O.switchMap)(e=>this.subscribe(e)),(0,O.mergeAll)())}subscribe(e){return e.filter(t=>this.hasValidAssets(t)).map(t=>(0,O.combineLatest)([this.subscribePoolChange(t),this.subscribePoolBalance(t)]).pipe((0,O.debounceTime)(250),(0,O.map)(([n,s])=>this.updatePool(n,s))))}subscribePoolBalance(e){if(e.type==="Aave")return(0,O.of)([]);let t=[this.subscribeTokensBalance(e.address)];if(this.hasSystemAsset(e)){let n=this.subscribeSystemBalance(e.address);t.push(n)}if(this.hasErc20Asset(e)){let n=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),s=this.subscribeErc20Balance(e.address,n);t.push(s)}return(0,O.combineLatest)(t).pipe((0,O.map)(n=>n.map(s=>Array.isArray(s)?s:[s]).flat()))}hasSystemAsset(e){return e.tokens.some(t=>t.id===0)}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}hasValidAssets(e){return e.tokens.every(({id:t,decimals:n,balance:s})=>{let r=this.override.find(a=>a.id===t),i=!!n||!!r?.decimals;return s>0n&&i})}updatePool=(e,t)=>{let n=e.tokens.map(s=>{let r=t.find(a=>a.id===s.id),i=this.override.find(a=>a.id===s.id);return r?{...s,balance:r.amount,decimals:s.decimals||i?.decimals}:{...s,decimals:s.decimals||i?.decimals}});return{...e,tokens:n}}};var ve=class extends N{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[e,t,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),s=t?.relay_parent_number||0,r=e.filter(({value:i})=>t&&this.isActivePool(i,s)).map(async({keyArgs:i,value:a})=>{let[o]=i,l=o.toString(),u=await this.getPoolDelta(l,a,s);return{address:l,type:"LBP",fee:a.fee,...u,...n}});return Promise.all(r)}async getPoolDelta(e,t,n){let{start:s,end:r,assets:i,initial_weight:a,final_weight:o,repay_target:l,fee_collector:u}=t,d=U.calculateLinearWeights(s?s.toString():"0",r?r.toString():"0",a.toString(),o.toString(),n.toString()),[p,m]=i,g=BigInt(d),P=this.MAX_FINAL_WEIGHT-BigInt(g),[b,x,f,T,v]=await Promise.all([this.isRepayFeeApplied(p,l,u.toString()),this.getBalance(e,p),this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(e,m),this.api.query.AssetRegistry.Assets.getValue(m)]);return{repayFeeApply:b,tokens:[{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:x,weight:g,type:f?.asset_type.type},{id:m,decimals:v?.decimals,existentialDeposit:v?.existential_deposit,balance:T,weight:P,type:v?.asset_type.type}]}}isActivePool(e,t){let{start:n,end:s}=e;return n&&s?t>=n&&t<s:!1}async isRepayFeeApplied(e,t,n){if(t===0n)return!1;try{return await this.getBalance(n,e)<t}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(e){return{repayFee:await this.getRepayFee(),exchangeFee:e.fee}}getPoolType(){return"LBP"}async isSupported(){let e=this.api.query.LBP.PoolData,t=await this.api.compatibilityToken;return e.isCompatible(nn.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(e.address);return n?t.watchValue("best").pipe((0,se.switchMap)(s=>s?this.getPoolDelta(e.address,n,s.relay_parent_number):(0,se.of)(e)),(0,se.map)(s=>Object.assign({},e,s))):(0,se.of)(e)}};var Ot={};I(Ot,{OmniMath:()=>B,OmniPool:()=>Ae,OmniPoolClient:()=>_e});var S=require("@galacticcouncil/math-omnipool"),re=st(require("big.js")),B=class{static calculateSpotPrice(e,t,n,s){return(0,S.calculate_spot_price)(e,t,n,s)}static calculateLrnaSpotPrice(e,t){return(0,S.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,n,s,r,i,a,o,l){return(0,S.calculate_in_given_out)(e,t,n,s,r,i,a,o,l)}static calculateLrnaInGivenOut(e,t,n,s,r){return(0,S.calculate_lrna_in_given_out)(e,t,n,s,r)}static calculateOutGivenIn(e,t,n,s,r,i,a,o,l){return(0,S.calculate_out_given_in)(e,t,n,s,r,i,a,o,l)}static calculateOutGivenLrnaIn(e,t,n,s,r){return(0,S.calculate_out_given_lrna_in)(e,t,n,s,r)}static calculateShares(e,t,n,s){return(0,S.calculate_shares)(e,t,n,s)}static calculateLiquidityOut(e,t,n,s,r,i,a,o){return(0,S.calculate_liquidity_out)(e,t,n,s,r,i,a,o)}static calculateLiquidityLRNAOut(e,t,n,s,r,i,a,o){return(0,S.calculate_liquidity_lrna_out)(e,t,n,s,r,i,a,o)}static calculateCapDifference(e,t,n,s){let r=(0,re.default)(t),i=(0,re.default)(e),a=(0,re.default)(s),o=(0,re.default)(n),l=(0,re.default)(10).pow(18),u=o.div(l);if(r.div(a).lt(u)){let p=u.times(a).minus(r).times(i),m=r.times((0,re.default)(1).minus(u));return p.div(m).toFixed(0)}else return"0"}static verifyAssetCap(e,t,n,s){return(0,S.verify_asset_cap)(e,t,n,s)}static calculateLimitHubIn(e,t,n,s){return(0,S.calculate_liquidity_hub_in)(e,t,n,s)}static isSellAllowed(e){return(0,S.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,S.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,S.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,S.is_remove_liquidity_allowed)(e)}};var Ae=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,n,s,r,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.hubAssetId=i}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:r.hubReserves,sharesIn:s.shares,sharesOut:r.shares,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,tradeableIn:s.tradeable,tradeableOut:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),r=this.calculateInGivenOut(e,t,n),i=s===0n?0:A.calculateDiffToRef(r,s),a=[],o=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetInEd)&&a.push("InsufficientTradingAmount");let u=e.balanceOut/this.maxOutRatio;t>u&&a.push("MaxOutRatioExceeded");let d=e.balanceIn/this.maxInRatio;return r>d&&a.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),r=this.calculateOutGivenIn(e,t,n),i=A.calculateDiffToRef(s,r),a=[],o=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetOutEd)&&a.push("InsufficientTradingAmount");let u=e.balanceIn/this.maxInRatio;t>u&&a.push("MaxInRatioExceeded");let d=e.balanceOut/this.maxOutRatio;return r>d&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateInGivenOut(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,n);let s=B.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateLrnaInGivenOut(e,t,n){let s=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,n);let s=B.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenLrnaIn(e,t,n){let s=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=B.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceLrnaInGivenOut(e){let t=B.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=B.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}spotPriceOutGivenLrnaIn(e){let t=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}};var je=require("polkadot-api"),sn=require("@polkadot-api/utils"),Be=require("rxjs");var _e=class extends N{async loadPools(){let e=await this.api.constants.Omnipool.HubAssetId(),t=this.getPoolAddress(),[n,s,r,i,a]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(e),this.getBalance(t,e),this.getPoolLimits()]),o=n.map(async({keyArgs:u,value:d})=>{let[p]=u,{hub_reserve:m,shares:g,tradable:P,cap:b,protocol_shares:x}=d,[f,T]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(t,p)]);return{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:T,cap:b,hubReserves:m,protocolShares:x,shares:g,tradeable:P,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:e,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:i,tradeable:s,type:r?.asset_type.type}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:l,...a}]}getPoolAddress(){let e="modlomnipool".padEnd(32,"\0"),t=new TextEncoder().encode(e),n=(0,sn.toHex)(t);return(0,je.AccountId)(63).dec(n)}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(e,t){let[n,s,r]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(t)]),i=n.min_fee+s.min_fee,a=n.max_fee+s.max_fee;if(r){let{asset_fee:o,protocol_fee:l}=r;return{assetFee:h.fromPermill(o),protocolFee:h.fromPermill(l),min:h.fromPermill(i),max:h.fromPermill(a)}}else return{assetFee:h.fromPermill(n.min_fee),protocolFee:h.fromPermill(s.min_fee),min:h.fromPermill(i),max:h.fromPermill(a)}}getPoolType(){return"Omnipool"}async isSupported(){let e=this.api.query.Omnipool.Assets,t=await this.api.compatibilityToken;return e.isCompatible(je.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,Be.distinctUntilChanged)((n,s)=>!s.deltas),(0,Be.map)(({entries:n})=>n.map(s=>{let[r]=s.args,{hub_reserve:i,shares:a,tradable:o,cap:l,protocol_shares:u}=s.value,d=e.tokens.findIndex(m=>m.id===r);return{...e.tokens[d],cap:l,hubReserves:i,protocolShares:u,shares:a,tradeable:o}})),(0,Be.map)(n=>{let s=e.tokens.find(r=>r.id===1);return{...e,tokens:[...n,s]}}))}};var vt={};I(vt,{StableMath:()=>D,StableSwap:()=>Re,StableSwapClient:()=>Fe});var _=require("@galacticcouncil/math-stableswap"),D=class{static getPoolAddress(e){return(0,_.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let n=0;n<e;n++)t.push(["1","1"]);return t}static calculateAmplification(e,t,n,s,r){return(0,_.calculate_amplification)(e,t,n,s,r)}static calculateInGivenOut(e,t,n,s,r,i,a){return(0,_.calculate_in_given_out)(e,t,n,s,r,i,a)}static calculateAddOneAsset(e,t,n,s,r,i,a){return(0,_.calculate_add_one_asset)(e,t,n,s,r,i,a)}static calculateSharesForAmount(e,t,n,s,r,i,a){return(0,_.calculate_shares_for_amount)(e,t,n,s,r,i,a)}static calculateOutGivenIn(e,t,n,s,r,i,a){return(0,_.calculate_out_given_in)(e,t,n,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,n,s,r,i,a){return(0,_.calculate_liquidity_out_one_asset)(e,t,n,s,r,i,a)}static calculateShares(e,t,n,s,r,i){return(0,_.calculate_shares)(e,t,n,s,r,i)}static calculateSpotPriceWithFee(e,t,n,s,r,i,a,o){return(0,_.calculate_spot_price_with_fee)(e,t,n,s,r,i,a,o)}static recalculatePegs(e,t,n,s,r){let i=(0,_.recalculate_peg)(e,t,n,s,r);return JSON.parse(i)}};var Re=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,n,s,r,i,a,o,l){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.amplification=i,this.id=a,this.fee=o,this.totalIssuance=l}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),r=this.calculateInGivenOut(e,t,n),i=h.toPct(n.fee),a=[],o=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:r,calculatedIn:s,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),r=this.calculateOutGivenIn(e,t,n),i=h.toPct(n.fee),a=[],o=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateIn(e,t,n){let s=D.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateAddOneAsset(e,t,n){let s=D.calculateAddOneAsset(this.getReserves(),t.toString(),Number(e.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateSharesForAmount(e,t,n){let s=D.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateInGivenOut(e,t,n){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,n):e.assetIn==this.id?this.calculateSharesForAmount(e,t,n):this.calculateIn(e,t,n)}spotPriceInGivenOut(e){let t=D.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetOut.toString(),e.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(e.assetOut==this.id)return BigInt(t);if(e.assetIn==this.id){let s=Math.pow(10,e.decimalsIn-e.decimalsOut);return BigInt(t)/BigInt(s)}let n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateOut(e,t,n){let s=D.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateWithdrawOneAsset(e,t,n){let s=D.calculateLiquidityOutOneAsset(this.getReserves(),t.toString(),Number(e.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateShares(e,t,n){let s=D.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(e,t,n){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,n):e.assetOut==this.id?this.calculateShares(e,t,n):this.calculateOut(e,t,n)}spotPriceOutGivenIn(e){let t=D.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetIn.toString(),e.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(e.assetIn==this.id)return BigInt(t);if(e.assetOut==this.id){let s=Math.pow(10,e.decimalsOut-e.decimalsIn);return BigInt(t)/BigInt(s)}let n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}getPegs(){let e=D.defaultPegs(this.tokens.length-1);return JSON.stringify(e)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:n,decimals:s})=>({asset_id:t,amount:n,decimals:s}));return JSON.stringify(e,Z.jsonFormatter)}getAssets(e,t){let n={asset_id:Number(e),amount:t.toString()};return JSON.stringify([n],Z.jsonFormatter)}};var ze=require("polkadot-api"),rn=require("@polkadot-api/utils"),an=require("@noble/hashes/blake2b"),pe=require("rxjs");var jn=340282366920938463463374607431768211455n,Fe=class extends N{poolsData=new Map([]);async loadPools(){let[e,t,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),s=e.map(async({keyArgs:r,value:i})=>{let[a]=r,o=this.getPoolAddress(a),[l,u,d]=await Promise.all([this.getPoolDelta(a,i,t),this.getPoolTokens(a,i),this.getPoolPegs(a,i,t)]);return this.poolsData.set(o,i),{address:o,id:a,type:"Stableswap",fee:h.fromPermill(i.fee),tokens:u,...l,...d,...n}});return Promise.all(s)}async getPoolDelta(e,t,n){let{initial_amplification:s,final_amplification:r,initial_block:i,final_block:a}=t,o=D.calculateAmplification(s.toString(),r.toString(),i.toString(),a.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(e);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(e,t){let n=this.getPoolAddress(e),s=t.assets.map(async a=>{let[o,l,u]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(e,a),this.api.query.AssetRegistry.Assets.getValue(a),this.getBalance(n,a)]);return{id:a,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:u,tradeable:o,type:l?.asset_type.type}}),r=await Promise.all(s),i=await this.api.query.AssetRegistry.Assets.getValue(e);return r.push({id:e,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:jn,tradeable:15,type:i?.asset_type.type}),r}async getPoolPegs(e,t,n){let s=await this.api.query.Stableswap.PoolPegs.getValue(e);if(!s)return this.getDefaultPegs(t);let r=await this.getLatestPegs(t,s,n),i=this.getRecentPegs(s),a=h.fromPermill(s.max_peg_update),o=h.fromPermill(t.fee),[l,u]=D.recalculatePegs(JSON.stringify(i),JSON.stringify(r),n.toString(),h.toDecimals(a).toString(),h.toDecimals(o).toString()),d=Number(l)*1e6;return{pegsFee:h.fromPermill(d),pegs:u}}getDefaultPegs(e){let t=e.fee,n=D.defaultPegs(e.assets.length);return{pegsFee:h.fromPermill(t),pegs:n}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([n,s])=>s.map(r=>r.toString()))}async getLatestPegs(e,t,n){let{source:s}=t,r=Array.from(e.assets.entries()).map(([a,o])=>o),i=s.map(async(a,o)=>{if(a.type==="Oracle"){let[l,u,d]=a.value,p=[d,r[o]].sort((f,T)=>f-T),m=await this.api.query.EmaOracle.Oracles.getValue(l,p,u);if(!m)return;let[{price:g,updated_at:P}]=m,b=g.n.toString(),x=g.d.toString();return d.toString()===p[0].toString()?[[b,x],P.toString()]:[[x,b],P.toString()]}else return[a.value.map(l=>l.toString()),n]});return Promise.all(i)}getPoolAddress(e){let t=D.getPoolAddress(e),n=(0,an.blake2b)(t,{dkLen:32}),s=(0,rn.toHex)(n);return(0,ze.AccountId)(63).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(e){return{fee:e.fee}}getPoolType(){return"Stableswap"}async isSupported(){let e=this.api.query.Stableswap.Pools,t=await this.api.compatibilityToken;return e.isCompatible(ze.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.System.Number,n=this.poolsData.get(e.address);return!n||!e.id?(0,pe.of)(e):t.watchValue("best").pipe((0,pe.switchMap)(s=>this.getPoolDelta(e.id,n,s)),(0,pe.map)(s=>Object.assign({},e,s)))}};var At={};I(At,{XykMath:()=>$,XykPool:()=>Ee,XykPoolClient:()=>De});var R=require("@galacticcouncil/math-xyk"),$=class{static getSpotPrice(e,t,n){return(0,R.get_spot_price)(e,t,n)}static calculateInGivenOut(e,t,n){return(0,R.calculate_in_given_out)(e,t,n)}static calculateOutGivenIn(e,t,n){return(0,R.calculate_out_given_in)(e,t,n)}static calculatePoolTradeFee(e,t,n){return(0,R.calculate_pool_trade_fee)(e,t,n)}static calculateLiquidityIn(e,t,n){return(0,R.calculate_liquidity_in)(e,t,n)}static calculateSpotPrice(e,t){return(0,R.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,n,s){return(0,R.calculate_spot_price_with_fee)(e,t,n,s)}static calculateShares(e,t,n){return(0,R.calculate_shares)(e,t,n)}static calculateLiquidityOutAssetA(e,t,n,s){return(0,R.calculate_liquidity_out_asset_a)(e,t,n,s)}static calculateLiquidityOutAssetB(e,t,n,s){return(0,R.calculate_liquidity_out_asset_b)(e,t,n,s)}};var Ee=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,n,s,r){this.type="XYK",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),r=this.calculateTradeFee(s,n),i=h.toPct(n.exchangeFee),a=s+r,o=[];(t<this.minTradingLimit||s<e.assetInEd)&&o.push("InsufficientTradingAmount");let l=e.balanceOut/this.maxOutRatio;t>l&&o.push("MaxOutRatioExceeded");let u=e.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:t,feePct:i,errors:o}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),r=this.calculateTradeFee(s,n),i=h.toPct(n.exchangeFee),a=s-r,o=[];(t<this.minTradingLimit||s<e.assetOutEd)&&o.push("InsufficientTradingAmount");let l=e.balanceIn/this.maxInRatio;t>l&&o.push("MaxInRatioExceeded");let u=e.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:a,feePct:i,errors:o}}calculateInGivenOut(e,t){let n=$.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(e,t){let n=$.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(e){let t=$.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}spotPriceOutGivenIn(e){let t=$.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateTradeFee(e,t){let n=$.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return BigInt(n)}};var on=require("polkadot-api"),ln=require("rxjs");var De=class extends N{async loadPools(){let e=this.api.query.XYK.PoolAssets,[t,n]=await Promise.all([e.getEntries(),this.getPoolLimits()]),s=t.map(async({keyArgs:r,value:i})=>{let[a]=r,[o,l]=i,[u,d,p,m]=await Promise.all([this.getBalance(a,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(a,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:a,type:"XYK",tokens:[{id:o,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:u,type:d?.asset_type.type},{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:p,type:m?.asset_type.type}],...n}});return Promise.all(s)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let e=this.api.query.XYK.PoolAssets,t=await this.api.compatibilityToken;return e.isCompatible(on.CompatibilityLevel.BackwardsCompatible,t)}subscribePoolChange(e){return(0,ln.of)(e)}};var Bt={};I(Bt,{AavePool:()=>ke,AavePoolClient:()=>Ce});var ke=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,n,s,r){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),r=[];return t>e.balanceOut&&r.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:r}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),r=[];return s>e.balanceOut&&r.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:r}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){let t=Math.pow(10,e.decimalsOut);return BigInt(t)}spotPriceOutGivenIn(e){let t=Math.pow(10,e.decimalsIn);return BigInt(t)}calculateTradeFee(e,t){return 0n}};var cn=require("polkadot-api"),pn=require("@polkadot-api/utils"),me=require("rxjs"),mn=require("viem");var un=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"}];var{ERC20:zn}=ee,Kn=["Supply","Withdraw","Repay","Borrow"],Ce=class extends N{async loadPools(){let t=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:s,liqudity_in:r,liqudity_out:i})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(n,s),type:"Aave",tokens:[{id:n,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:r,location:o,type:a?.asset_type.type},{id:s,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:i,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolDelta(e){let[t,n]=e.tokens,{liqudity_in:s,liqudity_out:r}=await this.api.apis.AaveTradeExecutor.pool(t.id,n.id);return e.tokens.map(i=>{let a=i.id===t.id?s:r;return{...i,balance:a}})}getPoolId(e,t){let n=e+"/"+t,s=new TextEncoder().encode(n.padEnd(32,"\0")),r=(0,pn.toHex)(s);return(0,cn.AccountId)(63).dec(r)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(e){let[t,n]=e.tokens,s=this.getReserveH160Id(t),r=this.api.event.Router.Executed.watch(({asset_in:a,asset_out:o})=>a===n.id||o===n.id),i=this.api.event.EVM.Log.watch(({log:a})=>{let{topics:o,data:l}=a,u=o.map(g=>g.asHex()),d=l.asHex(),{eventName:p,args:m}=(0,mn.decodeEventLog)({abi:un,topics:u,data:d});return Kn.includes(p)&&m.reserve.toLowerCase()===s.toLowerCase()});return(0,me.merge)([r,i]).pipe((0,me.switchMap)(()=>this.getPoolDelta(e)),(0,me.map)(a=>({...e,tokens:[...a]})))}getReserveH160Id(e){return e.type==="Erc20"?Z.findNestedKey(e.location,"AccountKey20").AccountKey20.key:zn.fromAssetId(e.id)}};var de=class{static get(e){switch(e.type){case"Aave":return ke.fromPool(e);case"XYK":return Ee.fromPool(e);case"Omnipool":return Ae.fromPool(e);case"LBP":return Oe.fromPool(e);case"Stableswap":return Re.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var j=require("rxjs");var ge=class extends M{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=j.Subscription.EMPTY;omniSub=j.Subscription.EMPTY;stableSub=j.Subscription.EMPTY;xykSub=j.Subscription.EMPTY;aaveSub=j.Subscription.EMPTY;isReady=!1;isDestroyed=new j.Subject;constructor(e){super(e),this.lbpClient=new ve(e),this.omniClient=new _e(e),this.stableClient=new Fe(e),this.xykClient=new De(e),this.aaveClient=new Ce(e),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(e){return e.getSubscriber().pipe((0,j.takeUntil)(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(e){return this.xykClient.withOverride(e),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let e=await Promise.all(this.clients.filter(t=>this.active.has(t.getPoolType())).map(t=>t.getPools()));return this.isReady=!0,e.flat()}async getPoolFees(e,t){let n=this.clients.find(s=>s.getPoolType()===e.type);if(n)return n.getPoolFees(e,t);throw new Ie(e.type)}};var Mt={};I(Mt,{DEFAULT_BLOCK_TIME:()=>dn,DEFAULT_MIN_BUDGET:()=>Et,ORDER_MIN_BLOCK_PERIOD:()=>gn,Router:()=>be,TWAP_BLOCK_PERIOD:()=>qe,TWAP_MAX_DURATION:()=>kt,TWAP_MAX_PRICE_IMPACT:()=>Dt,TWAP_TX_MULTIPLIER:()=>Co,TradeOrderError:()=>Ft,TradeOrderType:()=>Qe,TradeRouteBuilder:()=>H,TradeRouter:()=>ye,TradeScheduler:()=>he,TradeType:()=>$e});var Ke=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var $n=5,Me=class{isNotVisited(e,t){let n=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(n=!1)}),n}findPaths(e,t,n){let s=[],r=new Ke,i=[];for(i.push([t,""]),r.enqueue(i);r.size()>0;){let a=r.dequeue();if(a==null||a.length>$n)return s;let o=a[a.length-1];(n===null||o[0]===n)&&s.push(a),e.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let d=[...a];d.push(u),r.enqueue(d)}})}return s}buildAndPopulateGraph(e,t){let n=new Map;for(let s of e)n.set(parseInt(s),[]);for(let[s,r,i]of t)n.get(r)?.push([i,s]);return n}};function Rt(c){let e={};for(let t of c){let n=t.tokens.length;for(let s=0;s<n;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let r=0;r<n;r++){if(s==r)continue;let i=[t.address,t.tokens[s].id,t.tokens[r].id];e[t.tokens[s].id].push(i)}}}return e}var Le=class{getProposals(e,t,n){let s=Rt(n),r=Object.keys(s),i=r.map(u=>s[u]).flat(),a=new Me,o=a.buildAndPopulateGraph(r,i),l=a.findPaths(o,e,t);return this.parsePaths(l)}parsePaths(e){let t=[];for(let n of e){let s=[];for(let r=0;r<n.length;r++){let i=n[r],a=n[r+1];if(a==null)break;s.push(this.toEdge(i,a))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0],t[0]]}};var be=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(e,t){this.ctx=e,this.routeSuggester=new Le,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=await this.ctx.getPools(),t=this.routerOptions.useOnly;return t.length===0?e:e.filter(n=>t.includes(n.type))}async getRoutes(e,t){let n=await this.getPools();return this.validateInput(e,t,n),this.getPaths(e,t,n)}async getTradeableAssets(){let e=await this.getPools(),t=this.getAssets(e);return Array.from(t)}validateInput(e,t,n){if(n.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(n);if(!s.has(e))throw new Error(e+" is not supported asset");if(!s.has(t))throw new Error(t+" is not supported asset");return this.toPoolsMap(n)}getAssets(e){let t=e.map(n=>n.tokens.map(s=>s.id)).flat().sort((n,s)=>n>s?1:-1);return new Set(t)}getPaths(e,t,n){let s=this.toPoolsMap(n);return this.routeSuggester.getProposals(e,t,n).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}validPath(e,t){return e.length>0&&e.map(n=>this.validEdge(n,t)).reduce((n,s)=>n&&s)}validEdge([e,t,n],s){return s.get(e)?.validatePair(t,n)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,de.get(t)]))}toHops(e,t){return e.map(([n,s,r])=>{let i=t.get(n);return{poolAddress:n,poolId:i?.id,pool:i?.type,assetIn:s,assetOut:r}})}};var $e=(t=>(t.Buy="Buy",t.Sell="Sell",t))($e||{}),Qe=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Qe||{}),Ft=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(Ft||{});var ye=class extends be{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((n,s)=>{let r=n[n.length-1].amountOut,i=s[s.length-1].amountOut;return r>i?-1:1});return t.find(n=>n.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(n=>n.tradeFeeRange).length>0){let n=e.map(r=>r.tradeFeeRange?.[0]??r.tradeFeePct).reduce((r,i)=>r+i),s=e.map(r=>r.tradeFeeRange?.[1]??r.tradeFeePct).reduce((r,i)=>r+i);return[n,s]}}getPoolFeeRange(e){let t=e.min?h.toPct(e.min):void 0,n=e.max?h.toPct(e.max):void 0;if(t&&n)return[t,n]}async getBestSell(e,t,n){return this.getSell(e,t,n)}async getSellSpot(e){let t=e[e.length-1];if(e.length===1)return t.spotPrice;let n=e.map(a=>a.assetOutDecimals).reduce((a,o)=>a+o),s=e.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-t.assetOutDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getSell(e,t,n,s){let r=await super.getPools(),i=super.validateInput(e,t,r),a=super.getPaths(e,t,r);if(a.length===0)throw new ce(e,t);let o;if(s)o=await this.toSellSwaps(n,s,i);else{let F=await Promise.all(a.map(k=>this.toSellSwaps(n,k,i)));o=this.findBestSellRoute(F)}let l=o[0],u=o[o.length-1],d=this.isDirectTrade(o),p=await this.getSellSpot(o),m=u.amountOut,g=d?u.calculatedOut:this.calculateDelta0Y(l.amountIn,o,i),P=g-m,b=this.getRouteFeeRange(o),x=d?u.tradeFeePct:A.calculateSellFee(g,m),f=Math.pow(10,l.assetInDecimals),T=l.amountIn*p/BigInt(f),v=A.calculateDiffToRef(g,T);return{type:"Sell",amountIn:l.amountIn,amountOut:u.amountOut,spotPrice:p,tradeFee:P,tradeFeePct:x,tradeFeeRange:b,priceImpactPct:v,swaps:o,toHuman(){return{type:"Sell",amountIn:y.toDecimal(l.amountIn,l.assetInDecimals),amountOut:y.toDecimal(u.amountOut,u.assetOutDecimals),spotPrice:y.toDecimal(p,u.assetOutDecimals),tradeFee:y.toDecimal(P,u.assetOutDecimals),tradeFeePct:x,tradeFeeRange:b,priceImpactPct:v,swaps:o.map(F=>F.toHuman())}}}}calculateDelta0Y(e,t,n){let s=[];for(let r=0;r<t.length;r++){let i=t[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r>0?l=s[r-1]:l=e;let u=a.calculateOutGivenIn(o,l);s.push(u)}return s[s.length-1]}async toSellSwaps(e,t,n){let s=[];for(let r=0;r<t.length;r++){let i=t[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r>0?l=s[r-1].amountOut:l=typeof e=="string"?y.toBigInt(e,o.decimalsIn):e;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountOut:d,calculatedOut:p,feePct:m,errors:g}=a.validateAndSell(o,l,u),P=this.getPoolFeeRange(u),b=a.spotPriceOutGivenIn(o),x=Math.pow(10,o.decimalsIn),f=l*b/BigInt(x),T=A.calculateDiffToRef(p,f);s.push({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:d,calculatedOut:p,spotPrice:b,tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===i.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:y.toDecimal(l,o.decimalsIn),amountOut:y.toDecimal(d,o.decimalsOut),calculatedOut:y.toDecimal(p,o.decimalsOut),spotPrice:y.toDecimal(b,o.decimalsOut),tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}async getMostLiquidRoute(e,t){let n=await super.getPools(),s=super.validateInput(e,t,n),r=super.getPaths(e,t,n),o=n.filter(p=>p.tokens.some(m=>m.id===e&&m.id!==p.id)).map(p=>p.type==="Aave"?p.tokens:p.tokens.filter(m=>m.id===e)).map(p=>p.map(m=>m.balance).reduce((m,g)=>m+g)).sort((p,m)=>m<p?-1:1)[0],l=A.getFraction(o,.1),u=await Promise.all(r.map(p=>this.toSellSwaps(l,p,s)));return this.findBestSellRoute(u).map(p=>({poolAddress:p.poolAddress,poolId:p?.poolId,pool:p.pool,assetIn:p.assetIn,assetOut:p.assetOut}))}async getSpotPrice(e,t){let n=await super.getPools(),s=super.validateInput(e,t,n),r=await this.getMostLiquidRoute(e,t),i=await this.toSellSwaps("1",r,s),a=await this.getSellSpot(i),o=i[i.length-1].assetOutDecimals;return{amount:a,decimals:o}}findBestBuyRoute(e){let t=e.sort((n,s)=>{let r=n[0].amountIn,i=s[0].amountIn;return r>i?1:-1});return t.find(n=>n.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,n){return this.getBuy(e,t,n)}async getBuySpot(e){let t=e[0];if(e.length===1)return t.spotPrice;let n=e.map(a=>a.assetInDecimals).reduce((a,o)=>a+o),s=e.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-t.assetInDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getBuy(e,t,n,s){let r=await super.getPools(),i=super.validateInput(e,t,r),a=super.getPaths(e,t,r);if(a.length===0)throw new ce(e,t);let o;if(s)o=await this.toBuySwaps(n,s,i);else{let F=await Promise.all(a.map(k=>this.toBuySwaps(n,k,i)));o=this.findBestBuyRoute(F)}let l=o[o.length-1],u=o[0],d=this.isDirectTrade(o),p=await this.getBuySpot(o),m=u.amountIn,g=d?u.calculatedIn:this.calculateDelta0X(l.amountOut,o,i),P=m-g,b=this.getRouteFeeRange(o),x=d?u.tradeFeePct:A.calculateBuyFee(g,m),f=Math.pow(10,l.assetOutDecimals),T=l.amountOut*p/BigInt(f),v;return g===0n?v=-100:v=A.calculateDiffToRef(T,g),{type:"Buy",amountOut:l.amountOut,amountIn:u.amountIn,spotPrice:p,tradeFee:P,tradeFeePct:x,tradeFeeRange:b,priceImpactPct:v,swaps:o,toHuman(){return{type:"Buy",amountOut:y.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:y.toDecimal(u.amountIn,u.assetInDecimals),spotPrice:y.toDecimal(p,u.assetInDecimals),tradeFee:y.toDecimal(P,u.assetInDecimals),tradeFeePct:x,tradeFeeRange:b,priceImpactPct:v,swaps:o.map(F=>F.toHuman())}}}}calculateDelta0X(e,t,n){let s=[];for(let r=t.length-1;r>=0;r--){let i=t[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r==t.length-1?l=e:l=s[0];let u=a.calculateInGivenOut(o,l);s.unshift(u)}return s[0]}async toBuySwaps(e,t,n){let s=[];for(let r=t.length-1;r>=0;r--){let i=t[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r==t.length-1?l=typeof e=="string"?y.toBigInt(e,o.decimalsOut):e:l=s[0].amountIn;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountIn:d,calculatedIn:p,feePct:m,errors:g}=a.validateAndBuy(o,l,u),P=this.getPoolFeeRange(u),b=a.spotPriceInGivenOut(o),x=Math.pow(10,o.decimalsOut),f=l*b/BigInt(x),T;p===0n?T=-100:T=A.calculateDiffToRef(f,p),s.unshift({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:d,calculatedIn:p,spotPrice:b,tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===i.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:y.toDecimal(l,o.decimalsOut),amountIn:y.toDecimal(d,o.decimalsIn),calculatedIn:y.toDecimal(p,o.decimalsIn),spotPrice:y.toDecimal(b,o.decimalsIn),tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}};var dn=6e3,Et=1000000000000000n,qe=6,Dt=-5,kt=216e5,Co=3,gn=6;var Ct=require("polkadot-api");var H=class{static build(e){return e.map(({assetIn:t,assetOut:n,pool:s,poolId:r})=>s==="Stableswap"?{pool:(0,Ct.Enum)("Stableswap",r),asset_in:t,asset_out:n}:{pool:(0,Ct.Enum)(s),asset_in:t,asset_out:n})}};var he=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??6e3,minBudgetInNative:t.minBudgetInNative??Et})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,n,s,r){let[i,a]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:o,swaps:l,priceImpactPct:u}=a,d=l[0],p=l[l.length-1],{assetInDecimals:m}=d,{assetOutDecimals:g}=p,P=Math.abs(u),b=this.getMinimumTradeCount(o,i),x=this.getOptimalTradeCount(P),f=r?Math.round(s/r):x,T=Math.ceil(s/b),v=Math.round(s/x),F=Math.round(s/f),k=o/BigInt(f),C=await this.router.getBestSell(e,t,k),Q=o<i,Ne=[];Q&&Ne.push("OrderTooSmall");let He=C.amountOut*BigInt(f),tt=this.toBlockPeriod(F),nt=C.tradeFee*BigInt(f),yn=H.build(l),Nt={assetIn:e,assetOut:t,errors:Ne,frequencyMin:T,frequencyOpt:v,frequency:F,tradeCount:f,tradeFee:nt,tradeImpactPct:C.priceImpactPct,tradePeriod:tt,tradeRoute:yn,type:"Dca"};return{...Nt,amountIn:o,amountOut:He,tradeAmountIn:C.amountIn,tradeAmountOut:C.amountOut,toHuman(){return{...Nt,amountIn:y.toDecimal(o,m),amountOut:y.toDecimal(He,g),tradeAmountIn:y.toDecimal(C.amountIn,m),tradeAmountOut:y.toDecimal(C.amountOut,g)}}}}async getMinimumOrderBudget(e){if(0===e)return this.minOrderBudget;let t=await this.router.getSpotPrice(0,e),n=10n**BigInt(12);if(t)return this.minOrderBudget*t.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let n=t*2n/10n;if(n===0n)return 0;let s=e+n/2n;return Number(s/n)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:p}=u,m=Math.abs(o),g=this.getTwapTradeCount(m),P=i/BigInt(g),b=await this.router.getBestSell(l.assetIn,u.assetOut,P),x=g===1,f=i<s,T=b.priceImpactPct<-5,v=[];f||x?v.push("OrderTooSmall"):T&&v.push("OrderImpactTooBig");let F=b.amountOut*BigInt(g),k=b.tradeFee*BigInt(g),C=H.build(a),Q={assetIn:e,assetOut:t,errors:v,tradeCount:g,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:C,type:"TwapSell"};return{...Q,amountIn:i,amountOut:F,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:k,toHuman(){return{...Q,amountIn:y.toDecimal(i,d),amountOut:y.toDecimal(F,p),tradeAmountIn:y.toDecimal(b.amountIn,d),tradeAmountOut:y.toDecimal(b.amountOut,p),tradeFee:y.toDecimal(k,p)}}}}async getTwapBuyOrder(e,t,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,n)]),{amountOut:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:p}=u,m=Math.abs(o),g=this.getTwapTradeCount(m),P=i/BigInt(g),b=await this.router.getBestBuy(l.assetIn,u.assetOut,P),x=b.amountIn*BigInt(g),f=g===1,T=x<s,v=b.priceImpactPct<-5,F=[];T||f?F.push("OrderTooSmall"):v&&F.push("OrderImpactTooBig");let k=b.tradeFee*BigInt(g),C=H.build(a),Q={assetIn:e,assetOut:t,errors:F,tradeCount:g,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:C,type:"TwapBuy"};return{...Q,amountIn:x,amountOut:i,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:k,toHuman(){return{...Q,amountIn:y.toDecimal(x,d),amountOut:y.toDecimal(i,p),tradeAmountIn:y.toDecimal(b.amountIn,d),tradeAmountOut:y.toDecimal(b.amountOut,p),tradeFee:y.toDecimal(k,d)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}return t}getTwapExecutionTime(e){return e*6*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,n=Math.round(t);return Math.max(n,6)}};var qt={};I(qt,{TxBuilderFactory:()=>fe});var Lt=require("polkadot-api");function bn(c){let e=[],t=c;for(;t&&typeof t=="object"&&"type"in t;)e.push(t.type),t=t.value;return e.join(".")}var Pe=class extends M{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new L,this.balanceClient=new X(e),this.aaveUtils=new te(this.evmClient)}wrapTx(e,t){return{name:e,get:()=>t,dryRun:n=>this.dryRun(n,t)}}async dispatchWithExtraGas(e){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:e.decodedCall,extra_gas:ot})}async dryRun(e,t){let n=(0,Lt.Enum)("Signed",e),s=(0,Lt.Enum)("system",n),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,t.decodedCall),a=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(a){let o=bn(a.value);throw new Error("Dry run execution error!",{cause:o})}return i}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Je=class extends Pe{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:s}=t[0],r=await this.balanceClient.getBalance(this.beneficiary,s);return e>=r-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:e,amountOut:t,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=A.getFraction(e,this.slippagePct),a=s.assetIn,o=r.assetOut,l=e+i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:t,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:t,max_amount_in:l,route:H.build(n)}),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=A.getFraction(t,this.slippagePct),a=s.assetIn,o=r.assetOut,l=t-i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:e,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:e,min_amount_out:l,route:H.build(n)}),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,n=t[0],s=t[t.length-1],r=A.getFraction(e,this.slippagePct),i=n.assetIn,a=s.assetOut,o=e-r,l=this.api.tx.Router.sell_all({asset_in:i,asset_out:a,min_amount_out:o,route:H.build(t)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var Ze=require("polkadot-api");var et=class extends Pe{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:s,tradePeriod:r,tradeRoute:i}=this.order,a=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Ze.Enum)("Sell",{asset_in:t,asset_out:n,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=A.getFraction(r,this.slippagePct),l=r-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Ze.Enum)("Sell",{asset_in:t,asset_out:n,amount_in:s,min_amount_out:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=A.getFraction(s,this.slippagePct),l=s+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Ze.Enum)("Buy",{asset_in:t,asset_out:n,amount_out:r,max_amount_in:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var fe=class{client;evmClient;constructor(e,t){this.client=e,this.evmClient=t??new L}trade(e){return new Je(this.client,this.evmClient).setTrade(e)}order(e){return new et(this.client,this.evmClient).setOrder(e)}};async function Qn(c,e){let t=new ue(c),[n,s]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),r=e??new L,i=new ge(c).withAave().withOmnipool().withStableswap().withXyk(),a=new te(r),o=new ye(i),l=new he(o,{blockTime:n,minBudgetInNative:s});return{api:{aave:a,router:o,scheduler:l},client:{asset:new le(c),balance:new X(c),evm:r},ctx:{pool:i},tx:new fe(c,r),destroy:()=>{i.destroy()}}}0&&(module.exports={aave,api,big,client,const:null,createSdkContext,erc20,error,evm,fmt,h160,json,math,pool,sor,tx,xc});
|
package/build/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ut=Object.defineProperty;var w=(u,e)=>{for(var t in e)Ut(u,t,{get:e[t],enumerable:!0})};var ct={};w(ct,{Papi:()=>E,getWs:()=>Yt});import{hydration as Wt}from"@galacticcouncil/descriptors";function lt(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var E=class{client;api;constructor(e){this.client=e,this.api=this.client.getTypedApi(Wt)}log(e,...t){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");lt(n)&&console.log(e,...t)}};import{createClient as Vt}from"polkadot-api";import{withPolkadotSdkCompat as Xt}from"polkadot-api/polkadot-sdk-compat";var Yt=async u=>{let e=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)(e);return Vt(Xt(a))};var xt={};w(xt,{AAVE_GAS_LIMIT:()=>Ge,AAVE_LENDING_POOL_ADDRESS:()=>_e,AAVE_POOL_ABI:()=>Ne,AAVE_POOL_DATA_PROVIDER:()=>Be,AAVE_POOL_DATA_PROVIDER_ABI:()=>Ae,AAVE_POOL_PROXY:()=>He,AAVE_ROUNDING_THRESHOLD:()=>ms,AAVE_UINT_256_MAX:()=>jt,AaveClient:()=>le,AaveUtils:()=>Y});var Ne=[{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 Ae=[{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 He="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Be="0x112b087b60C1a166130d59266363C45F8aa99db0",_e="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Ge=1000000n,ms=5,jt=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var dt={};w(dt,{EvmClient:()=>F,evmMainnet:()=>Ue});import{defineChain as Kt}from"viem";var ut=["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"],pt=["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"],Ue=Kt({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:ut,webSocket:pt},default:{http:ut,webSocket:pt}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as mt,createWalletClient as zt,custom as $t,http as Qt,webSocket as Jt}from"viem";var F=class{chain;constructor(e){this.chain=e||Ue}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 mt({chain:this.chain,transport:Qt()})}getWsProvider(){return mt({chain:this.chain,transport:Jt()})}getSigner(e){return zt({account:e,chain:this.chain,transport:$t(window.ethereum)})}};var le=class{evmClient;constructor(e){this.evmClient=e??new F}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Ae,address:Be,args:[_e],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:Ae,address:Be,args:[_e,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:Ne,address:He,args:[e],functionName:"getUserAccountData"})}};var b={};w(b,{asBigInt:()=>tn,toBigInt:()=>en,toDecimal:()=>Zt});import V from"big.js";V.NE=-18;function Zt(u,e,t=6,n){let a=V(u.toString()),s=V(10).pow(e);return a.div(s).round(t,n).toString()}function en(u,e){let t=V(10).pow(e),a=V(u).mul(t).toFixed(0,V.roundDown);return BigInt(a)}function tn(u){return BigInt(u.round(0,V.roundDown).toFixed(0))}var K={};w(K,{ERC20:()=>We});var We=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 y={};w(y,{fromPermill:()=>sn,toDecimals:()=>an,toPct:()=>nn});var gt=1e3;function nn(u){let[e,t]=u;return e/t*100}function an(u){let[e,t]=u;return e/t}function sn(u){return[u/gt,gt]}var Re={};w(Re,{H160:()=>je,isEvmAccount:()=>yt,isEvmAddress:()=>Pt,isSs58Address:()=>ft});import{AccountId as ce}from"polkadot-api";import{toHex as ht}from"@polkadot-api/utils";import{Buffer as W}from"buffer";var bt={};w(bt,{HUB_ASSET_ID:()=>Xe,HYDRATION_OMNIPOOL_ADDRESS:()=>on,HYDRATION_PARACHAIN_ID:()=>rn,HYDRATION_SS58_PREFIX:()=>L,RUNTIME_DECIMALS:()=>D,SYSTEM_ASSET_DECIMALS:()=>Ve,SYSTEM_ASSET_ID:()=>N,TRADEABLE_DEFAULT:()=>z});var D=18,N=0,Ve=12,rn=2034,L=63,on="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Xe=1,z=15;var Ye="ETH\0";function yt(u){if(!u)return!1;try{let e=ce().enc(u),t=W.from(Ye);return W.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Pt(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function ft(u){try{return ce(63).enc(u),!0}catch{return!1}}var je=class u{static toAccount=e=>{let t=W.from(e.slice(2),"hex"),n=W.from(Ye),a=Uint8Array.from(W.concat([n,t,W.alloc(8)])),s=ht(a);return ce(63).dec(s)};static fromAccount=e=>{let t=ce().enc(e),n=W.from(Ye),a=t.slice(n.length,-8);return"0x"+W.from(a).toString("hex")};static fromSS58=e=>{let n=ce().enc(e).slice(0,20);return ht(n)};static fromAny=e=>{if(Pt(e))return e;if(yt(e))return u.fromAccount(e);if(ft(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var X={};w(X,{findNestedKey:()=>ln,findNestedObj:()=>cn,jsonFormatter:()=>un});var ln=(u,e)=>{let t=[];return JSON.stringify(u,(n,a)=>(a&&a[e]&&t.push(a),a)),t[0]},cn=(u,e,t)=>{let n;return JSON.stringify(u,(a,s)=>(s&&s[e]===t&&(n=s),s)),n},un=(u,e)=>typeof e=="bigint"?e.toString():e;var O={};w(O,{calculateBuyFee:()=>gn,calculateDiffToAvg:()=>pn,calculateDiffToRef:()=>mn,calculateSellFee:()=>dn,getFraction:()=>bn});import H from"big.js";function pn(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 mn(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 dn(u,e){let t=H(u.toString()),n=H(e.toString());return H(1).minus(n.div(t)).mul(100).round(2).toNumber()}function gn(u,e){let t=H(u.toString());return H(e.toString()).div(t).minus(1).mul(100).round(2).toNumber()}function bn(u,e,t=2){(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,t),a=BigInt(e*n);return u*a/BigInt(100*n)}var Tt={};w(Tt,{convertToId:()=>yn});import{Buffer as hn}from"buffer";function yn(u){let t=hn.from(u.replace("0x",""),"hex").subarray(16);return t.readUIntBE(0,t.length)}var{ERC20:Ee}=K,{H160:Ke}=Re,Pn=1.01,fn=99999,Tn=10n**27n,xn=10n**18n,Y=class{client;constructor(e){let t=e??new F;this.client=new le(t)}async getSummary(e){let t=Ke.fromAny(e),[n,a,s]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t)]),[i]=n,[r,o]=a,[l,c,d,p,m,g]=s,P=b.toDecimal(g,18),h=[];for(let x of r){let f=x.underlyingAsset.toLowerCase(),T=i.find(({underlyingAsset:qe})=>qe.toLowerCase()===f);if(!T)throw new Error("Missing pool reserve for "+f);let I=x.scaledATokenBalance,v=T.liquidityIndex,_=T.priceInMarketReferenceCurrency,R=I*v/Tn,Oe=Number(o===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,ve=T.usageAsCollateralEnabled&&x.usageAsCollateralEnabledOnUser&&x.scaledATokenBalance>0n,Le=Ee.toAssetId(f);h.push({aTokenBalance:R,decimals:Number(T.decimals),isCollateral:ve,priceInRef:_,reserveId:Le,reserveAsset:f,reserveLiquidationThreshold:Oe})}return{healthFactor:Number(P),totalCollateral:l,totalDebt:c,reserves:h}}async hasBorrowPositions(e){let t=Ke.fromAny(e),n=await this.client.getUserAccountData(t),[a,s]=n;return s>0n}async getHealthFactor(e){let t=Ke.fromAny(e),n=await this.client.getUserAccountData(t),[a,s,i,r,o,l]=n,c=b.toDecimal(l,18);return Number(c)}async getHealthFactorAfterWithdraw(e,t,n){let{totalCollateral:a,totalDebt:s,reserves:i}=await this.getSummary(e),r=Ee.fromAssetId(t),o=i.find(h=>h.reserveAsset===r);if(!o)throw new Error("Missing reserve ctx for "+r);let{decimals:l,isCollateral:c,priceInRef:d,reserveLiquidationThreshold:p}=o,m=b.toBigInt(n,l),g=c?m*d/10n**BigInt(l):0n,P=a-g;return P<=0n?0:this.calculateHealthFactor(P,p,s)}async getHealthFactorAfterSupply(e,t,n){let{totalCollateral:a,totalDebt:s,reserves:i}=await this.getSummary(e),r=Ee.fromAssetId(t),o=i.find(P=>P.reserveAsset===r);if(!o)throw new Error("Missing reserve ctx for "+r);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:d}=o,m=b.toBigInt(n,l)*c/10n**BigInt(l),g=a+m;return g<=0n?0:this.calculateHealthFactor(g,d,s)}async getMaxWithdraw(e,t){let{totalCollateral:n,totalDebt:a,reserves:s}=await this.getSummary(e),i=Ee.fromAssetId(t),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(e){let{totalCollateral:t,totalDebt:n,reserves:a}=await this.getSummary(e),s={};for(let i of a){let r=this.calculateWithdrawMax(i,t,n);i.reserveId&&(s[i.reserveId]=r)}return s}calculateHealthFactor(e,t,n){if(n===0n)return fn;let a=10n**6n,s=b.toBigInt(t,18),i=e*s*a,r=n*xn,o=i/r;return Number(o)/1e6}calculateRequiredCollateral(e,t,n){let a=b.toBigInt(e,18),s=b.toBigInt(t,18);return(a*n+s-1n)/s}calculateWithdrawMax(e,t,n){let{aTokenBalance:a,decimals:s,priceInRef:i,reserveLiquidationThreshold:r}=e,o=this.calculateRequiredCollateral(Pn,r,n),l=t-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 St={};w(St,{AssetClient:()=>$,BalanceClient:()=>q,ChainParams:()=>J});var $=class extends E{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:a})=>{let[s]=n;return[s,a]}))}async queryBonds(){let t=await this.api.query.Bonds.Bonds.getEntries();return new Map(t.map(({keyArgs:n,value:a})=>{let[s]=n;return[s,a]}))}async queryAssets(){let t=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(t.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 t=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(t.map(({keyArgs:n,value:a})=>{let[s]=n;return[s,a]}))}async mapToken(e,t,n,a){let{name:s,asset_type:i,is_sufficient:r,existential_deposit:o}=t,{symbol:l,decimals:c}=n.get(e)??{};return{id:e,name:s?.asText(),symbol:l,decimals:c,icon:l,type:i.type,isSufficient:r,location:a,existentialDeposit:o}}async mapBond(e,t,n,a){let[s,i]=a,{asset_type:r,is_sufficient:o,existential_deposit:l}=t,{symbol:c,decimals:d}=await this.mapToken(s,t,n),p=Number(i),m=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",m.format(p)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:d,icon:c,type:r.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:s,maturity:p}}async mapShares(e,t,n,a){let{assets:s}=a,{name:i,symbol:r,asset_type:o,is_sufficient:l,existential_deposit:c}=t,d=await Promise.all(s.map(async g=>{let{symbol:P}=await this.mapToken(g,t,n);return[g,P]})),p=Object.fromEntries(d),m=Object.values(p);return{id:e,name:m.join(", "),symbol:r?.asText()||i?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:p}}async mapExternal(e,t,n,a){let s=await this.mapToken(e,t,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(e){return new Map(Array.from(e,([t,n])=>[t,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(e,t){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 d=a.get(l),{asset_type:p}=c,m;switch(p.type){case"Bond":let g=i.get(l);m=await this.mapBond(l,c,r,g);break;case"StableSwap":let P=s.get(l);m=await this.mapShares(l,c,r,P);break;case"External":m=await this.mapExternal(l,c,t,d);break;default:m=await this.mapToken(l,c,r,d)}o.push(m)}return e?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};import{Subject as In,bufferCount as wn,combineLatest as Sn,debounceTime as On,distinctUntilChanged as It,finalize as vn,map as Q,pairwise as An,shareReplay as Bn,startWith as _n}from"rxjs";var q=class extends E{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 a=await this.api.query.Tokens.Accounts.getValue(e,t);return this.calculateBalance(a)}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),a=this.subscribeErc20Balance(e);return Sn([t,n,a]).pipe(On(250),Q(s=>s.flat()),_n([]),wn(2,1),Q(([s,i],r)=>{if(r===0)return i;let o=s.reduce((c,d)=>(c.set(d.id,d.balance),c),new Map);return i.filter(c=>!wt(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(a=>({id:t,balance:a})))}subscribeTokensBalance(e){return this.api.query.Tokens.Accounts.watchEntries(e,{at:"best"}).pipe(It((n,a)=>!a.deltas),Q(({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(e,t){let n=new In,a=n.pipe(Bn(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=t||await s(),l=async()=>{let p=(await Promise.all(o.map(async m=>{let g=await this.getTokenBalanceData(e,m);return[m,g]}))).map(([m,g])=>({id:m,balance:g}));n.next(p)};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(vn(()=>r?.()),An(),Q(([o,l],c)=>{if(c===0)return l;let d=o.reduce((m,g)=>(m.set(g.id,g.balance),m),new Map);return l.filter(m=>!wt(m.balance,d.get(m.id)))}),It((o,l)=>l.length===0))}async getTokenBalanceData(e,t){let n=await this.api.apis.CurrenciesApi.account(t,e);return this.calculateBalance(n)}},wt=(u,e)=>u!==void 0&&e!==void 0&&u.transferable===e.transferable&&u.total===e.total;var J=class extends E{_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 Ot={};w(Ot,{AssetNotFound:()=>ze,PoolNotFound:()=>ue,RouteNotFound:()=>Z});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"}},Z=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in current configuration`,this.name="RouteNotFound"}};var Dt={};w(Dt,{PoolContextProvider:()=>ne,PoolError:()=>j,PoolFactory:()=>te,PoolType:()=>A,aave:()=>et,lbp:()=>$e,omni:()=>Qe,stable:()=>Je,xyk:()=>Ze});var $e={};w($e,{LbpMath:()=>M,LbpPool:()=>pe,LbpPoolClient:()=>me});import{calculate_in_given_out as Rn,calculate_out_given_in as En,calculate_linear_weights as Fn,calculate_pool_trade_fee as Dn,get_spot_price as kn}from"@galacticcouncil/math-lbp";var M=class{static getSpotPrice(e,t,n,a,s){return kn(e,t,n,a,s)}static calculateInGivenOut(e,t,n,a,s){return Rn(e,t,n,a,s)}static calculateOutGivenIn(e,t,n,a,s){return En(e,t,n,a,s)}static calculateLinearWeights(e,t,n,a,s){return Fn(e,t,n,a,s)}static calculatePoolTradeFee(e,t,n){return Dn(e,t,n)}};var A=(s=>(s.Aave="Aave",s.LBP="LBP",s.Omni="Omnipool",s.Stable="Stableswap",s.XYK="XYK",s))(A||{}),j=(s=>(s.InsufficientTradingAmount="InsufficientTradingAmount",s.MaxInRatioExceeded="MaxInRatioExceeded",s.MaxOutRatioExceeded="MaxOutRatioExceeded",s.TradeNotAllowed="TradeNotAllowed",s.UnknownError="UnknownError",s))(j||{});var pe=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,a,s,i,r){this.type="LBP",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=a,this.minTradingLimit=s,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])),a=n.get(e),s=n.get(t);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:a.balance,balanceOut:s.balance,decimalsIn:a.decimals,decimalsOut:s.decimals,weightIn:a.weight,weightOut:s.weight}}validateAndBuy(e,t,n){let a=this.tokens[0].id,s=[];t<this.minTradingLimit&&s.push("InsufficientTradingAmount");let i=e.balanceOut/this.maxOutRatio;if(t>i&&s.push("MaxOutRatioExceeded"),a===e.assetOut){let r=this.calculateTradeFee(t,n),o=y.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=t+r,c=this.calculateInGivenOut(e,l),d=e.balanceIn/this.maxInRatio;return c>d&&s.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:o,errors:s}}else{let r=this.calculateInGivenOut(e,t),o=e.balanceIn/this.maxInRatio;return r>o&&s.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}}validateAndSell(e,t,n){let a=this.tokens[0].id,s=[];t<this.minTradingLimit&&s.push("InsufficientTradingAmount");let i=e.balanceIn/this.maxInRatio;if(t>i&&s.push("MaxInRatioExceeded"),a===e.assetIn){let r=this.calculateOutGivenIn(e,t),o=e.balanceOut/this.maxOutRatio;return r>o&&s.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}else{let r=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(r,n),l=y.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),c=r-o,d=e.balanceOut/this.maxOutRatio;return c>d&&s.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:c,feePct:l,errors:s}}}calculateInGivenOut(e,t){let n=M.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),a=BigInt(n);return a<0n?0n:a}calculateOutGivenIn(e,t){let n=M.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),a=BigInt(n);return a<0n?0n:a}spotPriceInGivenOut(e){let t=M.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),this.maxOutRatio.toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=M.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),this.maxInRatio.toString());return BigInt(t)}calculateTradeFee(e,t){let n=M.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 Gn}from"polkadot-api";import{map as Un,of as Rt,switchMap as Wn}from"rxjs";import{memoize1 as Cn}from"@thi.ng/memoize";import{combineLatest as vt,combineLatestAll as Mn,debounceTime as Ln,firstValueFrom as qn,from as At,map as Bt,mergeAll as Nn,of as Hn,switchMap as _t}from"rxjs";var k=class extends q{override=[];mem=0;memPools=Cn(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=At(this.getPoolsMem()).pipe(_t(t=>this.subscribe(t)),Mn());return qn(e)}getSubscriber(){return At(this.getPoolsMem()).pipe(_t(e=>this.subscribe(e)),Nn())}subscribe(e){return e.filter(t=>this.hasValidAssets(t)).map(t=>vt([this.subscribePoolChange(t),this.subscribePoolBalance(t)]).pipe(Ln(250),Bt(([n,a])=>this.updatePool(n,a))))}subscribePoolBalance(e){if(e.type==="Aave")return Hn([]);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(s=>s.type==="Erc20").map(s=>s.id),a=this.subscribeErc20Balance(e.address,n);t.push(a)}return vt(t).pipe(Bt(n=>n.map(a=>Array.isArray(a)?a:[a]).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:a})=>{let s=this.override.find(r=>r.id===t),i=!!n||!!s?.decimals;return a>0n&&i})}updatePool=(e,t)=>{let n=e.tokens.map(a=>{let s=t.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{...e,tokens:n}}};var me=class extends k{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()]),a=t?.relay_parent_number||0,s=e.filter(({value:i})=>t&&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(e,t,n){let{start:a,end:s,assets:i,initial_weight:r,final_weight:o,repay_target:l,fee_collector:c}=t,d=M.calculateLinearWeights(a?a.toString():"0",s?s.toString():"0",r.toString(),o.toString(),n.toString()),[p,m]=i,g=BigInt(d),P=this.MAX_FINAL_WEIGHT-BigInt(g),[h,x,f,T,I]=await Promise.all([this.isRepayFeeApplied(p,l,c.toString()),this.getBalance(e,p),this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(e,m),this.api.query.AssetRegistry.Assets.getValue(m)]);return{repayFeeApply:h,tokens:[{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:x.transferable,weight:g,type:f?.asset_type.type},{id:m,decimals:I?.decimals,existentialDeposit:I?.existential_deposit,balance:T.transferable,weight:P,type:I?.asset_type.type}]}}isActivePool(e,t){let{start:n,end:a}=e;return n&&a?t>=n&&t<a:!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(Gn.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(e.address);return n?t.watchValue("best").pipe(Wn(a=>a?this.getPoolDelta(e.address,n,a.relay_parent_number):Rt(e)),Un(a=>Object.assign({},e,a))):Rt(e)}};var Qe={};w(Qe,{OmniMath:()=>S,OmniPool:()=>de,OmniPoolClient:()=>ge});import{calculate_in_given_out as Vn,calculate_lrna_in_given_out as Xn,calculate_out_given_in as Yn,calculate_out_given_lrna_in as jn,calculate_spot_price as Kn,calculate_lrna_spot_price as zn,calculate_shares as $n,calculate_liquidity_out as Qn,calculate_liquidity_lrna_out as Jn,verify_asset_cap as Zn,calculate_liquidity_hub_in as ea,is_sell_allowed as ta,is_buy_allowed as na,is_add_liquidity_allowed as aa,is_remove_liquidity_allowed as sa}from"@galacticcouncil/math-omnipool";import ee from"big.js";var S=class{static calculateSpotPrice(e,t,n,a){return Kn(e,t,n,a)}static calculateLrnaSpotPrice(e,t){return zn(e,t)}static calculateInGivenOut(e,t,n,a,s,i,r,o,l){return Vn(e,t,n,a,s,i,r,o,l)}static calculateLrnaInGivenOut(e,t,n,a,s){return Xn(e,t,n,a,s)}static calculateOutGivenIn(e,t,n,a,s,i,r,o,l){return Yn(e,t,n,a,s,i,r,o,l)}static calculateOutGivenLrnaIn(e,t,n,a,s){return jn(e,t,n,a,s)}static calculateShares(e,t,n,a){return $n(e,t,n,a)}static calculateLiquidityOut(e,t,n,a,s,i,r,o){return Qn(e,t,n,a,s,i,r,o)}static calculateLiquidityLRNAOut(e,t,n,a,s,i,r,o){return Jn(e,t,n,a,s,i,r,o)}static calculateCapDifference(e,t,n,a){let s=ee(t),i=ee(e),r=ee(a),o=ee(n),l=ee(10).pow(18),c=o.div(l);if(s.div(r).lt(c)){let p=c.times(r).minus(s).times(i),m=s.times(ee(1).minus(c));return p.div(m).toFixed(0)}else return"0"}static verifyAssetCap(e,t,n,a){return Zn(e,t,n,a)}static calculateLimitHubIn(e,t,n,a){return ea(e,t,n,a)}static isSellAllowed(e){return ta(e)}static isBuyAllowed(e){return na(e)}static isAddLiquidityAllowed(e){return aa(e)}static isRemoveLiquidityAllowed(e){return sa(e)}};var de=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,a,s,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=a,this.minTradingLimit=s,this.hubAssetId=i}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),a=n.get(e),s=n.get(t);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,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(e,t,n){let a=this.calculateInGivenOut(e,t),s=this.calculateInGivenOut(e,t,n),i=a===0n?0:O.calculateDiffToRef(s,a),r=[],o=S.isSellAllowed(e.tradeableIn),l=S.isBuyAllowed(e.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||a<e.assetInEd)&&r.push("InsufficientTradingAmount");let c=e.balanceOut/this.maxOutRatio;t>c&&r.push("MaxOutRatioExceeded");let d=e.balanceIn/this.maxInRatio;return s>d&&r.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:a,amountOut:t,feePct:i,errors:r}}validateAndSell(e,t,n){let a=this.calculateOutGivenIn(e,t),s=this.calculateOutGivenIn(e,t,n),i=O.calculateDiffToRef(a,s),r=[],o=S.isSellAllowed(e.tradeableIn),l=S.isBuyAllowed(e.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||a<e.assetOutEd)&&r.push("InsufficientTradingAmount");let c=e.balanceIn/this.maxInRatio;t>c&&r.push("MaxInRatioExceeded");let d=e.balanceOut/this.maxOutRatio;return s>d&&r.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:s,feePct:i,errors:r}}calculateInGivenOut(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,n);let a=S.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?y.toDecimals(n.assetFee).toString():"0",n?y.toDecimals(n.protocolFee).toString():"0"),s=BigInt(a);return s<0n?0n:s}calculateLrnaInGivenOut(e,t,n){let a=S.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?y.toDecimals(n.assetFee).toString():"0"),s=BigInt(a);return s<0n?0n:s}calculateOutGivenIn(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,n);let a=S.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?y.toDecimals(n.assetFee).toString():"0",n?y.toDecimals(n.protocolFee).toString():"0"),s=BigInt(a);return s<0n?0n:s}calculateOutGivenLrnaIn(e,t,n){let a=S.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?y.toDecimals(n.assetFee).toString():"0"),s=BigInt(a);return s<0n?0n:s}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=S.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=S.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=S.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=S.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString()),n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}};import{AccountId as ra,CompatibilityLevel as ia}from"polkadot-api";import{toHex as oa}from"@polkadot-api/utils";import{distinctUntilChanged as la,map as Et}from"rxjs";var ge=class extends k{async loadPools(){let e=await this.api.constants.Omnipool.HubAssetId(),t=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(e),this.getBalance(t,e),this.getPoolLimits()]),o=n.map(async({keyArgs:c,value:d})=>{let[p]=c,{hub_reserve:m,shares:g,tradable:P,cap:h,protocol_shares:x}=d,[f,T]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(t,p)]);return{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:T.transferable,cap:h,hubReserves:m,protocolShares:x,shares:g,tradeable:P,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:e,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:i.transferable,tradeable:a,type:s?.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=oa(t);return ra(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,a,s]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(t)]),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:y.fromPermill(o),protocolFee:y.fromPermill(l),min:y.fromPermill(i),max:y.fromPermill(r)}}else return{assetFee:y.fromPermill(n.min_fee),protocolFee:y.fromPermill(a.min_fee),min:y.fromPermill(i),max:y.fromPermill(r)}}getPoolType(){return"Omnipool"}async isSupported(){let e=this.api.query.Omnipool.Assets,t=await this.api.compatibilityToken;return e.isCompatible(ia.BackwardsCompatible,t)}subscribePoolChange(e){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(la((n,a)=>!a.deltas),Et(({entries:n})=>n.map(a=>{let[s]=a.args,{hub_reserve:i,shares:r,tradable:o,cap:l,protocol_shares:c}=a.value,d=e.tokens.findIndex(m=>m.id===s);return{...e.tokens[d],cap:l,hubReserves:i,protocolShares:c,shares:r,tradeable:o}})),Et(n=>{let a=e.tokens.find(s=>s.id===1);return{...e,tokens:[...n,a]}}))}};var Je={};w(Je,{StableMath:()=>B,StableSwap:()=>be,StableSwapClient:()=>he});import{calculate_in_given_out as ca,calculate_out_given_in as ua,calculate_amplification as pa,calculate_add_one_asset as ma,calculate_liquidity_out_one_asset as da,calculate_shares as ga,calculate_shares_for_amount as ba,calculate_spot_price_with_fee as ha,pool_account_name as ya,recalculate_peg as Pa}from"@galacticcouncil/math-stableswap";var B=class{static getPoolAddress(e){return ya(e)}static defaultPegs(e){let t=[];for(let n=0;n<e;n++)t.push(["1","1"]);return t}static calculateAmplification(e,t,n,a,s){return pa(e,t,n,a,s)}static calculateInGivenOut(e,t,n,a,s,i,r){return ca(e,t,n,a,s,i,r)}static calculateAddOneAsset(e,t,n,a,s,i,r){return ma(e,t,n,a,s,i,r)}static calculateSharesForAmount(e,t,n,a,s,i,r){return ba(e,t,n,a,s,i,r)}static calculateOutGivenIn(e,t,n,a,s,i,r){return ua(e,t,n,a,s,i,r)}static calculateLiquidityOutOneAsset(e,t,n,a,s,i,r){return da(e,t,n,a,s,i,r)}static calculateShares(e,t,n,a,s,i){return ga(e,t,n,a,s,i)}static calculateSpotPriceWithFee(e,t,n,a,s,i,r,o){return ha(e,t,n,a,s,i,r,o)}static recalculatePegs(e,t,n,a,s){return Pa(e,t,n,a,s)}};var be=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,a,s,i,r,o,l){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=a,this.minTradingLimit=s,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])),a=n.get(e),s=n.get(t);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:a.balance,balanceOut:s.balance,decimalsIn:a.decimals,decimalsOut:s.decimals,tradeableIn:this.id===e?15:a.tradeable,tradeableOut:this.id===t?15:s.tradeable,assetInEd:a.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(e,t,n){let a=this.calculateInGivenOut(e,t),s=this.calculateInGivenOut(e,t,n),i=y.toPct(n.fee),r=[],o=S.isSellAllowed(e.tradeableIn),l=S.isBuyAllowed(e.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||a<e.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:s,calculatedIn:a,amountOut:t,feePct:i,errors:r}}validateAndSell(e,t,n){let a=this.calculateOutGivenIn(e,t),s=this.calculateOutGivenIn(e,t,n),i=y.toPct(n.fee),r=[],o=S.isSellAllowed(e.tradeableIn),l=S.isBuyAllowed(e.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||a<e.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:a,amountOut:s,feePct:i,errors:r}}calculateIn(e,t,n){let a=B.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}calculateAddOneAsset(e,t,n){let a=B.calculateAddOneAsset(this.getReserves(),t.toString(),Number(e.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}calculateSharesForAmount(e,t,n){let a=B.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}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=B.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 a=Math.pow(10,e.decimalsIn-e.decimalsOut);return BigInt(t)/BigInt(a)}let n=Math.pow(10,18-e.decimalsIn);return BigInt(t)/BigInt(n)}calculateOut(e,t,n){let a=B.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}calculateWithdrawOneAsset(e,t,n){let a=B.calculateLiquidityOutOneAsset(this.getReserves(),t.toString(),Number(e.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}calculateShares(e,t,n){let a=B.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification.toString(),this.totalIssuance.toString(),n?y.toDecimals(n.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}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=B.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 a=Math.pow(10,e.decimalsOut-e.decimalsIn);return BigInt(t)/BigInt(a)}let n=Math.pow(10,18-e.decimalsOut);return BigInt(t)/BigInt(n)}getPegs(){let e=B.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:a})=>({asset_id:t,amount:n,decimals:a}));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 fa,CompatibilityLevel as Ta}from"polkadot-api";import{toHex as xa}from"@polkadot-api/utils";import{blake2b as Ia}from"@noble/hashes/blake2b";import{map as wa,of as Sa,switchMap as Oa}from"rxjs";var va=340282366920938463463374607431768211455n,he=class extends k{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()]),a=e.map(async({keyArgs:s,value:i})=>{let[r]=s,o=this.getPoolAddress(r),[l,c]=await Promise.all([this.getPoolDelta(r,i,t),this.getPoolTokens(r,i)]);return this.poolsData.set(o,i),{address:o,id:r,type:"Stableswap",fee:y.fromPermill(i.fee),tokens:c,...l,...n}});return Promise.all(a)}async getPoolDelta(e,t,n){let{initial_amplification:a,final_amplification:s,initial_block:i,final_block:r}=t,o=B.calculateAmplification(a.toString(),s.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),a=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}}),s=await Promise.all(a),i=await this.api.query.AssetRegistry.Assets.getValue(e);return s.push({id:e,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:va,tradeable:15,type:i?.asset_type.type}),s}getPoolAddress(e){let t=B.getPoolAddress(e),n=Ia(t,{dkLen:32}),a=xa(n);return fa(63).dec(a)}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(Ta.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.System.Number,n=this.poolsData.get(e.address);return!n||!e.id?Sa(e):t.watchValue("best").pipe(Oa(a=>this.getPoolDelta(e.id,n,a)),wa(a=>Object.assign({},e,a)))}};var Ze={};w(Ze,{XykMath:()=>G,XykPool:()=>ye,XykPoolClient:()=>Pe});import{calculate_in_given_out as Aa,calculate_out_given_in as Ba,calculate_pool_trade_fee as _a,get_spot_price as Ra,calculate_liquidity_in as Ea,calculate_shares as Fa,calculate_spot_price as Da,calculate_spot_price_with_fee as ka,calculate_liquidity_out_asset_a as Ca,calculate_liquidity_out_asset_b as Ma}from"@galacticcouncil/math-xyk";var G=class{static getSpotPrice(e,t,n){return Ra(e,t,n)}static calculateInGivenOut(e,t,n){return Aa(e,t,n)}static calculateOutGivenIn(e,t,n){return Ba(e,t,n)}static calculatePoolTradeFee(e,t,n){return _a(e,t,n)}static calculateLiquidityIn(e,t,n){return Ea(e,t,n)}static calculateSpotPrice(e,t){return Da(e,t)}static calculateSpotPriceWithFee(e,t,n,a){return ka(e,t,n,a)}static calculateShares(e,t,n){return Fa(e,t,n)}static calculateLiquidityOutAssetA(e,t,n,a){return Ca(e,t,n,a)}static calculateLiquidityOutAssetB(e,t,n,a){return Ma(e,t,n,a)}};var ye=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,a,s){this.type="XYK",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=a,this.minTradingLimit=s}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),a=n.get(e),s=n.get(t);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,decimalsIn:a.decimals,decimalsOut:s.decimals,balanceIn:a.balance,balanceOut:s.balance,assetInEd:a.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(e,t,n){let a=this.calculateInGivenOut(e,t),s=this.calculateTradeFee(a,n),i=y.toPct(n.exchangeFee),r=a+s,o=[];(t<this.minTradingLimit||a<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:a,amountOut:t,feePct:i,errors:o}}validateAndSell(e,t,n){let a=this.calculateOutGivenIn(e,t),s=this.calculateTradeFee(a,n),i=y.toPct(n.exchangeFee),r=a-s,o=[];(t<this.minTradingLimit||a<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:a,amountOut:r,feePct:i,errors:o}}calculateInGivenOut(e,t){let n=G.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),a=BigInt(n);return a<0n?0n:a}calculateOutGivenIn(e,t){let n=G.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),a=BigInt(n);return a<0n?0n:a}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 La}from"polkadot-api";import{of as qa}from"rxjs";var Pe=class extends k{async loadPools(){let e=this.api.query.XYK.PoolAssets,[t,n]=await Promise.all([e.getEntries(),this.getPoolLimits()]),a=t.map(async({keyArgs:s,value:i})=>{let[r]=s,[o,l]=i,[c,d,p,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:d?.decimals,existentialDeposit:d?.existential_deposit,balance:c.transferable,type:d?.asset_type.type},{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:p.transferable,type:m?.asset_type.type}],...n}});return Promise.all(a)}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(La.BackwardsCompatible,t)}subscribePoolChange(e){return qa(e)}};var et={};w(et,{AavePool:()=>fe,AavePoolClient:()=>Te});var fe=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,a,s){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=a,this.minTradingLimit=s}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),a=n.get(e),s=n.get(t);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:a.balance,balanceOut:s.balance,decimalsIn:a.decimals,decimalsOut:s.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(e,t,n){let a=this.calculateInGivenOut(e,t),s=[];return t>e.balanceOut&&s.push("TradeNotAllowed"),{amountIn:a,calculatedIn:a,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t,n){let a=this.calculateOutGivenIn(e,t),s=[];return a>e.balanceOut&&s.push("TradeNotAllowed"),{amountIn:t,calculatedOut:a,amountOut:a,feePct:0,errors:s}}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 Na}from"polkadot-api";import{toHex as Ha}from"@polkadot-api/utils";import{map as Ga,merge as Ua,switchMap as Wa}from"rxjs";import{decodeEventLog as Va}from"viem";var Ft=[{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:Xa}=K,Ya=["Supply","Withdraw","Repay","Borrow"],Te=class extends k{async loadPools(){let t=(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(t)}async getPoolDelta(e){let[t,n]=e.tokens,{liqudity_in:a,liqudity_out:s}=await this.api.apis.AaveTradeExecutor.pool(t.id,n.id);return e.tokens.map(i=>{let r=i.id===t.id?a:s;return{...i,balance:r}})}getPoolId(e,t){let n=e+"/"+t,a=new TextEncoder().encode(n.padEnd(32,"\0")),s=Ha(a);return Na(63).dec(s)}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,a=this.getReserveH160Id(t),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(g=>g.asHex()),d=l.asHex(),{eventName:p,args:m}=Va({abi:Ft,topics:c,data:d});return Ya.includes(p)&&m.reserve.toLowerCase()===a.toLowerCase()});return Ua([s,i]).pipe(Wa(()=>this.getPoolDelta(e)),Ga(r=>({...e,tokens:[...r]})))}getReserveH160Id(e){return e.type==="Erc20"?X.findNestedKey(e.location,"AccountKey20").AccountKey20.key:Xa.fromAssetId(e.id)}};var te=class{static get(e){switch(e.type){case"Aave":return fe.fromPool(e);case"XYK":return ye.fromPool(e);case"Omnipool":return de.fromPool(e);case"LBP":return pe.fromPool(e);case"Stableswap":return be.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{Subject as ja,Subscription as xe,takeUntil as Ka}from"rxjs";var ne=class extends E{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 ja;constructor(e){super(e),this.lbpClient=new me(e),this.omniClient=new ge(e),this.stableClient=new he(e),this.xykClient=new Pe(e),this.aaveClient=new Te(e),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(e){return e.getSubscriber().pipe(Ka(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(e){return this.xykClient.withOverride(e),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let e=await Promise.all(this.clients.filter(t=>this.active.has(t.getPoolType())).map(t=>t.getPools()));return this.isReady=!0,e.flat()}async getPoolFees(e,t){let n=this.clients.find(a=>a.getPoolType()===e.type);if(n)return n.getPoolFees(e,t);throw new ue(e.type)}};var Lt={};w(Lt,{DEFAULT_BLOCK_TIME:()=>kt,DEFAULT_MIN_BUDGET:()=>at,ORDER_MIN_BLOCK_PERIOD:()=>Ct,Router:()=>ae,TWAP_BLOCK_PERIOD:()=>Se,TWAP_MAX_DURATION:()=>rt,TWAP_MAX_PRICE_IMPACT:()=>st,TWAP_TX_MULTIPLIER:()=>lc,TradeOrderError:()=>nt,TradeOrderType:()=>ke,TradeRouteBuilder:()=>C,TradeRouter:()=>se,TradeScheduler:()=>re,TradeType:()=>De});var Fe=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 za=5,Ie=class{isNotVisited(e,t){let n=!0;return t.forEach(a=>{(a[0]===e[0]||a[1]===e[1])&&(n=!1)}),n}findPaths(e,t,n){let a=[],s=new Fe,i=[];for(i.push([t,""]),s.enqueue(i);s.size()>0;){let r=s.dequeue();if(r==null||r.length>za)return a;let o=r[r.length-1];(n===null||o[0]===n)&&a.push(r),e.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,r)){let d=[...r];d.push(c),s.enqueue(d)}})}return a}buildAndPopulateGraph(e,t){let n=new Map;for(let a of e)n.set(parseInt(a),[]);for(let[a,s,i]of t)n.get(s)?.push([i,a]);return n}};function tt(u){let e={};for(let t of u){let n=t.tokens.length;for(let a=0;a<n;a++){e[t.tokens[a].id]||(e[t.tokens[a].id]=[]);for(let s=0;s<n;s++){if(a==s)continue;let i=[t.address,t.tokens[a].id,t.tokens[s].id];e[t.tokens[a].id].push(i)}}}return e}var we=class{getProposals(e,t,n){let a=tt(n),s=Object.keys(a),i=s.map(c=>a[c]).flat(),r=new Ie,o=r.buildAndPopulateGraph(s,i),l=r.findPaths(o,e,t);return this.parsePaths(l)}parsePaths(e){let t=[];for(let n of e){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))}t.push(a)}return t}toEdge(e,t){return[t[1],e[0],t[0]]}};var ae=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(e,t){this.ctx=e,this.routeSuggester=new we,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=await this.ctx.getPools(),t=this.routerOptions.useOnly;return t.length===0?e:e.filter(n=>t.includes(n.type))}async getRoutes(e,t){let n=await this.getPools();return this.validateInput(e,t,n),this.getPaths(e,t,n)}async getTradeableAssets(){let e=await this.getPools(),t=this.getAssets(e);return Array.from(t)}validateInput(e,t,n){if(n.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let a=this.getAssets(n);if(!a.has(e))throw new Error(e+" is not supported asset");if(!a.has(t))throw new Error(t+" is not supported asset");return this.toPoolsMap(n)}getAssets(e){let t=e.map(n=>n.tokens.map(a=>a.id)).flat().sort((n,a)=>n>a?1:-1);return new Set(t)}getPaths(e,t,n){let a=this.toPoolsMap(n);return this.routeSuggester.getProposals(e,t,n).filter(i=>this.validPath(i,a)).map(i=>this.toHops(i,a))}validPath(e,t){return e.length>0&&e.map(n=>this.validEdge(n,t)).reduce((n,a)=>n&&a)}validEdge([e,t,n],a){return a.get(e)?.validatePair(t,n)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,te.get(t)]))}toHops(e,t){return e.map(([n,a,s])=>{let i=t.get(n);return{poolAddress:n,poolId:i?.id,pool:i?.type,assetIn:a,assetOut:s}})}};var De=(t=>(t.Buy="Buy",t.Sell="Sell",t))(De||{}),ke=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(ke||{}),nt=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(nt||{});var se=class extends ae{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((n,a)=>{let s=n[n.length-1].amountOut,i=a[a.length-1].amountOut;return s>i?-1:1});return t.find(n=>n.every(a=>a.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(n=>n.tradeFeeRange).length>0){let n=e.map(s=>s.tradeFeeRange?.[0]??s.tradeFeePct).reduce((s,i)=>s+i),a=e.map(s=>s.tradeFeeRange?.[1]??s.tradeFeePct).reduce((s,i)=>s+i);return[n,a]}}getPoolFeeRange(e){let t=e.min?y.toPct(e.min):void 0,n=e.max?y.toPct(e.max):void 0;if(t&&n)return[t,n]}async getBestSell(e,t,n){return this.getSell(e,t,n)}async getSellSpot(e){let t=e[e.length-1];if(e.length===1)return t.spotPrice;let n=e.map(r=>r.assetOutDecimals).reduce((r,o)=>r+o),a=e.map(r=>r.spotPrice).reduce((r,o)=>r*o),s=n-t.assetOutDecimals,i=Math.pow(10,s);return a/BigInt(i)}async getSell(e,t,n,a){let s=await super.getPools(),i=super.validateInput(e,t,s),r=super.getPaths(e,t,s);if(r.length===0)throw new Z(e,t);let o;if(a)o=await this.toSellSwaps(n,a,i);else{let v=await Promise.all(r.map(_=>this.toSellSwaps(n,_,i)));o=this.findBestSellRoute(v)}let l=o[0],c=o[o.length-1],d=this.isDirectTrade(o),p=await this.getSellSpot(o),m=c.amountOut,g=d?c.calculatedOut:this.calculateDelta0Y(l.amountIn,o,i),P=g-m,h=this.getRouteFeeRange(o),x=d?c.tradeFeePct:O.calculateSellFee(g,m),f=Math.pow(10,l.assetInDecimals),T=l.amountIn*p/BigInt(f),I=O.calculateDiffToRef(g,T);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:p,tradeFee:P,tradeFeePct:x,tradeFeeRange:h,priceImpactPct:I,swaps:o,toHuman(){return{type:"Sell",amountIn:b.toDecimal(l.amountIn,l.assetInDecimals),amountOut:b.toDecimal(c.amountOut,c.assetOutDecimals),spotPrice:b.toDecimal(p,c.assetOutDecimals),tradeFee:b.toDecimal(P,c.assetOutDecimals),tradeFeePct:x,tradeFeeRange:h,priceImpactPct:I,swaps:o.map(v=>v.toHuman())}}}}calculateDelta0Y(e,t,n){let a=[];for(let s=0;s<t.length;s++){let i=t[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=e;let c=r.calculateOutGivenIn(o,l);a.push(c)}return a[a.length-1]}async toSellSwaps(e,t,n){let a=[];for(let s=0;s<t.length;s++){let i=t[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 e=="string"?b.toBigInt(e,o.decimalsIn):e;let c=await this.ctx.getPoolFees(r,o.assetOut),{amountOut:d,calculatedOut:p,feePct:m,errors:g}=r.validateAndSell(o,l,c),P=this.getPoolFeeRange(c),h=r.spotPriceOutGivenIn(o),x=Math.pow(10,o.decimalsIn),f=l*h/BigInt(x),T=O.calculateDiffToRef(p,f);a.push({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:d,calculatedOut:p,spotPrice:h,tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return r.type==="Aave"&&r.tokens[0].id===i.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:b.toDecimal(l,o.decimalsIn),amountOut:b.toDecimal(d,o.decimalsOut),calculatedOut:b.toDecimal(p,o.decimalsOut),spotPrice:b.toDecimal(h,o.decimalsOut),tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return a}async getMostLiquidRoute(e,t){let n=await super.getPools(),a=super.validateInput(e,t,n),s=super.getPaths(e,t,n),o=n.filter(p=>p.tokens.some(m=>m.id===e&&m.id!==p.id)).map(p=>p.type==="Aave"?p.tokens:p.tokens.filter(m=>m.id===e)).map(p=>p.map(m=>m.balance).reduce((m,g)=>m+g)).sort((p,m)=>m<p?-1:1)[0],l=O.getFraction(o,.1),c=await Promise.all(s.map(p=>this.toSellSwaps(l,p,a)));return this.findBestSellRoute(c).map(p=>({poolAddress:p.poolAddress,poolId:p?.poolId,pool:p.pool,assetIn:p.assetIn,assetOut:p.assetOut}))}async getSpotPrice(e,t){let n=await super.getPools(),a=super.validateInput(e,t,n),s=await this.getMostLiquidRoute(e,t),i=await this.toSellSwaps("1",s,a),r=await this.getSellSpot(i),o=i[i.length-1].assetOutDecimals;return{amount:r,decimals:o}}findBestBuyRoute(e){let t=e.sort((n,a)=>{let s=n[0].amountIn,i=a[0].amountIn;return s>i?1:-1});return t.find(n=>n.every(a=>a.errors.length==0))||t[0]}async getBestBuy(e,t,n){return this.getBuy(e,t,n)}async getBuySpot(e){let t=e[0];if(e.length===1)return t.spotPrice;let n=e.map(r=>r.assetInDecimals).reduce((r,o)=>r+o),a=e.map(r=>r.spotPrice).reduce((r,o)=>r*o),s=n-t.assetInDecimals,i=Math.pow(10,s);return a/BigInt(i)}async getBuy(e,t,n,a){let s=await super.getPools(),i=super.validateInput(e,t,s),r=super.getPaths(e,t,s);if(r.length===0)throw new Z(e,t);let o;if(a)o=await this.toBuySwaps(n,a,i);else{let v=await Promise.all(r.map(_=>this.toBuySwaps(n,_,i)));o=this.findBestBuyRoute(v)}let l=o[o.length-1],c=o[0],d=this.isDirectTrade(o),p=await this.getBuySpot(o),m=c.amountIn,g=d?c.calculatedIn:this.calculateDelta0X(l.amountOut,o,i),P=m-g,h=this.getRouteFeeRange(o),x=d?c.tradeFeePct:O.calculateBuyFee(g,m),f=Math.pow(10,l.assetOutDecimals),T=l.amountOut*p/BigInt(f),I;return g===0n?I=-100:I=O.calculateDiffToRef(T,g),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:p,tradeFee:P,tradeFeePct:x,tradeFeeRange:h,priceImpactPct:I,swaps:o,toHuman(){return{type:"Buy",amountOut:b.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:b.toDecimal(c.amountIn,c.assetInDecimals),spotPrice:b.toDecimal(p,c.assetInDecimals),tradeFee:b.toDecimal(P,c.assetInDecimals),tradeFeePct:x,tradeFeeRange:h,priceImpactPct:I,swaps:o.map(v=>v.toHuman())}}}}calculateDelta0X(e,t,n){let a=[];for(let s=t.length-1;s>=0;s--){let i=t[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==t.length-1?l=e:l=a[0];let c=r.calculateInGivenOut(o,l);a.unshift(c)}return a[0]}async toBuySwaps(e,t,n){let a=[];for(let s=t.length-1;s>=0;s--){let i=t[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==t.length-1?l=typeof e=="string"?b.toBigInt(e,o.decimalsOut):e:l=a[0].amountIn;let c=await this.ctx.getPoolFees(r,o.assetOut),{amountIn:d,calculatedIn:p,feePct:m,errors:g}=r.validateAndBuy(o,l,c),P=this.getPoolFeeRange(c),h=r.spotPriceInGivenOut(o),x=Math.pow(10,o.decimalsOut),f=l*h/BigInt(x),T;p===0n?T=-100:T=O.calculateDiffToRef(f,p),a.unshift({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:d,calculatedIn:p,spotPrice:h,tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return r.type==="Aave"&&r.tokens[0].id===i.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:b.toDecimal(l,o.decimalsOut),amountIn:b.toDecimal(d,o.decimalsIn),calculatedIn:b.toDecimal(p,o.decimalsIn),spotPrice:b.toDecimal(h,o.decimalsIn),tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return a}};var kt=6e3,at=1000000000000000n,Se=6,st=-5,rt=216e5,lc=3,Ct=6;import{Enum as Mt}from"polkadot-api";var C=class{static build(e){return e.map(({assetIn:t,assetOut:n,pool:a,poolId:s})=>a==="Stableswap"?{pool:Mt("Stableswap",s),asset_in:t,asset_out:n}:{pool:Mt(a),asset_in:t,asset_out:n})}};var re=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??6e3,minBudgetInNative:t.minBudgetInNative??at})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,n,a,s){let[i,r]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:o,swaps:l,priceImpactPct:c}=r,d=l[0],p=l[l.length-1],{assetInDecimals:m}=d,{assetOutDecimals:g}=p,P=Math.abs(c),h=this.getMinimumTradeCount(o,i),x=this.getOptimalTradeCount(P),f=s?Math.round(a/s):x,T=Math.ceil(a/h),I=Math.round(a/x),v=Math.round(a/f),_=o/BigInt(f),R=await this.router.getBestSell(e,t,_),U=o<i,Oe=[];U&&Oe.push("OrderTooSmall");let ve=R.amountOut*BigInt(f),Le=this.toBlockPeriod(v),qe=R.tradeFee*BigInt(f),Gt=C.build(l),ot={assetIn:e,assetOut:t,errors:Oe,frequencyMin:T,frequencyOpt:I,frequency:v,tradeCount:f,tradeFee:qe,tradeImpactPct:R.priceImpactPct,tradePeriod:Le,tradeRoute:Gt,type:"Dca"};return{...ot,amountIn:o,amountOut:ve,tradeAmountIn:R.amountIn,tradeAmountOut:R.amountOut,toHuman(){return{...ot,amountIn:b.toDecimal(o,m),amountOut:b.toDecimal(ve,g),tradeAmountIn:b.toDecimal(R.amountIn,m),tradeAmountOut:b.toDecimal(R.amountOut,g)}}}}async getMinimumOrderBudget(e){if(0===e)return this.minOrderBudget;let t=await this.router.getSpotPrice(0,e),n=10n**BigInt(12);if(t)return this.minOrderBudget*t.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let n=t*2n/10n;if(n===0n)return 0;let a=e+n/2n;return Number(a/n)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,n){let[a,s]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:i,swaps:r,priceImpactPct:o}=s,l=r[0],c=r[r.length-1],{assetInDecimals:d}=l,{assetOutDecimals:p}=c,m=Math.abs(o),g=this.getTwapTradeCount(m),P=i/BigInt(g),h=await this.router.getBestSell(l.assetIn,c.assetOut,P),x=g===1,f=i<a,T=h.priceImpactPct<-5,I=[];f||x?I.push("OrderTooSmall"):T&&I.push("OrderImpactTooBig");let v=h.amountOut*BigInt(g),_=h.tradeFee*BigInt(g),R=C.build(r),U={assetIn:e,assetOut:t,errors:I,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapSell"};return{...U,amountIn:i,amountOut:v,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:_,toHuman(){return{...U,amountIn:b.toDecimal(i,d),amountOut:b.toDecimal(v,p),tradeAmountIn:b.toDecimal(h.amountIn,d),tradeAmountOut:b.toDecimal(h.amountOut,p),tradeFee:b.toDecimal(_,p)}}}}async getTwapBuyOrder(e,t,n){let[a,s]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,n)]),{amountOut:i,swaps:r,priceImpactPct:o}=s,l=r[0],c=r[r.length-1],{assetInDecimals:d}=l,{assetOutDecimals:p}=c,m=Math.abs(o),g=this.getTwapTradeCount(m),P=i/BigInt(g),h=await this.router.getBestBuy(l.assetIn,c.assetOut,P),x=h.amountIn*BigInt(g),f=g===1,T=x<a,I=h.priceImpactPct<-5,v=[];T||f?v.push("OrderTooSmall"):I&&v.push("OrderImpactTooBig");let _=h.tradeFee*BigInt(g),R=C.build(r),U={assetIn:e,assetOut:t,errors:v,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapBuy"};return{...U,amountIn:x,amountOut:i,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:_,toHuman(){return{...U,amountIn:b.toDecimal(x,d),amountOut:b.toDecimal(i,p),tradeAmountIn:b.toDecimal(h.amountIn,d),tradeAmountOut:b.toDecimal(h.amountOut,p),tradeFee:b.toDecimal(_,d)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>216e5){let a=216e5/(this.blockTime*6);return Math.round(a)}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 Ht={};w(Ht,{TxBuilderFactory:()=>oe});import{Enum as Nt}from"polkadot-api";function qt(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 E{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new F,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:Ge})}async dryRun(e,t){let n=Nt("Signed",e),a=Nt("system",n),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(a,t.decodedCall),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let o=qt(r.value);throw new Error("Dry run execution error!",{cause:o})}return i}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Ce=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:a}=t[0],s=await this.balanceClient.getBalance(this.beneficiary,a);return e>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:e,amountOut:t,swaps:n}=this.trade,a=n[0],s=n[n.length-1],i=O.getFraction(e,this.slippagePct),r=a.assetIn,o=s.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,a=n[0],s=n[n.length-1],i=O.getFraction(t,this.slippagePct),r=a.assetIn,o=s.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)}),a.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],a=t[t.length-1],s=O.getFraction(e,this.slippagePct),i=n.assetIn,r=a.assetOut,o=e-s,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 it}from"polkadot-api";var Me=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: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:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:it("Sell",{asset_in:t,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:e,assetIn:t,assetOut:n,tradeAmountIn:a,tradeAmountOut:s,tradePeriod:i,tradeRoute:r}=this.order,o=O.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:it("Sell",{asset_in:t,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:e,assetIn:t,assetOut:n,tradeAmountIn:a,tradeAmountOut:s,tradePeriod:i,tradeRoute:r}=this.order,o=O.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:it("Buy",{asset_in:t,asset_out:n,amount_out:s,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 F}trade(e){return new Ce(this.client,this.evmClient).setTrade(e)}order(e){return new Me(this.client,this.evmClient).setOrder(e)}};async function ou(u,e){let t=new J(u),[n,a]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),s=e??new F,i=new ne(u).withAave().withOmnipool().withStableswap().withXyk(),r=new Y(s),o=new se(i),l=new re(o,{blockTime:n,minBudgetInNative:a});return{api:{aave:r,router:o,scheduler:l},client:{asset:new $(u),balance:new q(u),evm:s},ctx:{pool:i},tx:new oe(u,s),destroy:()=>{i.destroy()}}}export{xt as aave,ct as api,b as big,St as client,bt as const,ou as createSdkContext,K as erc20,Ot as error,dt as evm,y as fmt,Re as h160,X as json,O as math,Dt as pool,Lt as sor,Ht as tx,Tt as xc};
|
|
1
|
+
var Ut=Object.defineProperty;var I=(c,e)=>{for(var t in e)Ut(c,t,{get:e[t],enumerable:!0})};var ct={};I(ct,{Papi:()=>F,getWs:()=>Yt});import{hydration as Wt}from"@galacticcouncil/descriptors";function ut(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var F=class{client;api;constructor(e){this.client=e,this.api=this.client.getTypedApi(Wt)}log(e,...t){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");ut(n)&&console.log(e,...t)}};import{createClient as Vt}from"polkadot-api";import{withPolkadotSdkCompat as Xt}from"polkadot-api/polkadot-sdk-compat";var Yt=async c=>{let e=typeof c=="string"?c.split(","):c,s=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(e);return Vt(Xt(s))};var St={};I(St,{AAVE_GAS_LIMIT:()=>Ge,AAVE_LENDING_POOL_ADDRESS:()=>_e,AAVE_POOL_ABI:()=>Ne,AAVE_POOL_DATA_PROVIDER:()=>Be,AAVE_POOL_DATA_PROVIDER_ABI:()=>Ae,AAVE_POOL_PROXY:()=>He,AAVE_ROUNDING_THRESHOLD:()=>dr,AAVE_UINT_256_MAX:()=>jt,AaveClient:()=>le,AaveUtils:()=>Y});var Ne=[{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 Ae=[{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 He="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Be="0x112b087b60C1a166130d59266363C45F8aa99db0",_e="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Ge=1000000n,dr=5,jt=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var gt={};I(gt,{EvmClient:()=>E,evmMainnet:()=>Ue});import{defineChain as Kt}from"viem";var pt=["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"],mt=["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"],Ue=Kt({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:pt,webSocket:mt},default:{http:pt,webSocket:mt}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as dt,createWalletClient as zt,custom as $t,http as Qt,webSocket as Jt}from"viem";var E=class{chain;constructor(e){this.chain=e||Ue}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 dt({chain:this.chain,transport:Qt()})}getWsProvider(){return dt({chain:this.chain,transport:Jt()})}getSigner(e){return zt({account:e,chain:this.chain,transport:$t(window.ethereum)})}};var le=class{evmClient;constructor(e){this.evmClient=e??new E}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Ae,address:Be,args:[_e],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:Ae,address:Be,args:[_e,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:Ne,address:He,args:[e],functionName:"getUserAccountData"})}};var y={};I(y,{asBigInt:()=>tn,toBigInt:()=>en,toDecimal:()=>Zt});import V from"big.js";V.NE=-18;function Zt(c,e,t=6,n){let s=V(c.toString()),r=V(10).pow(e);return s.div(r).round(t,n).toString()}function en(c,e){let t=V(10).pow(e),s=V(c).mul(t).toFixed(0,V.roundDown);return BigInt(s)}function tn(c){return BigInt(c.round(0,V.roundDown).toFixed(0))}var K={};I(K,{ERC20:()=>We});var We=class{static fromAssetId(e){let t=Buffer.alloc(20,0);return t[15]=1,t.writeUInt32BE(e,16),"0x"+t.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(e.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(t.subarray(0,16))}};var h={};I(h,{fromPermill:()=>rn,toDecimals:()=>sn,toPct:()=>nn});var bt=1e3;function nn(c){let[e,t]=c;return e/t*100}function sn(c){let[e,t]=c;return e/t}function rn(c){return[c/bt,bt]}var Re={};I(Re,{H160:()=>Ke,isEvmAccount:()=>Pt,isEvmAddress:()=>ft,isSs58Address:()=>Tt});import{AccountId as ue}from"polkadot-api";import{toHex as ht}from"@polkadot-api/utils";import{Buffer as W}from"buffer";var yt={};I(yt,{HUB_ASSET_ID:()=>Ye,HYDRATION_OMNIPOOL_ADDRESS:()=>ln,HYDRATION_PARACHAIN_ID:()=>on,HYDRATION_SS58_PREFIX:()=>L,PERBILL_DENOMINATOR:()=>an,PERMILL_DENOMINATOR:()=>Ve,RUNTIME_DECIMALS:()=>D,SYSTEM_ASSET_DECIMALS:()=>Xe,SYSTEM_ASSET_ID:()=>N,TRADEABLE_DEFAULT:()=>z});var D=18,Ve=1e6,an=1e9,N=0,Xe=12,on=2034,L=63,ln="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Ye=1,z=15;var je="ETH\0";function Pt(c){if(!c)return!1;try{let e=ue().enc(c),t=W.from(je);return W.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function ft(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function Tt(c){try{return ue(63).enc(c),!0}catch{return!1}}var Ke=class c{static toAccount=e=>{let t=W.from(e.slice(2),"hex"),n=W.from(je),s=Uint8Array.from(W.concat([n,t,W.alloc(8)])),r=ht(s);return ue(63).dec(r)};static fromAccount=e=>{let t=ue().enc(e),n=W.from(je),s=t.slice(n.length,-8);return"0x"+W.from(s).toString("hex")};static fromSS58=e=>{let n=ue().enc(e).slice(0,20);return ht(n)};static fromAny=e=>{if(ft(e))return e;if(Pt(e))return c.fromAccount(e);if(Tt(e))return c.fromSS58(e);throw new Error("Unknown address type")}};var X={};I(X,{findNestedKey:()=>un,findNestedObj:()=>cn,jsonFormatter:()=>pn});var un=(c,e)=>{let t=[];return JSON.stringify(c,(n,s)=>(s&&s[e]&&t.push(s),s)),t[0]},cn=(c,e,t)=>{let n;return JSON.stringify(c,(s,r)=>(r&&r[e]===t&&(n=r),r)),n},pn=(c,e)=>typeof e=="bigint"?e.toString():e;var O={};I(O,{calculateBuyFee:()=>bn,calculateDiffToAvg:()=>mn,calculateDiffToRef:()=>dn,calculateSellFee:()=>gn,getFraction:()=>yn});import H from"big.js";function mn(c,e){let t=H(c.toString()),n=H(e.toString());return t.minus(n).abs().div(t.plus(n).div(2)).mul(100).round(2).toNumber()}function dn(c,e){if(e===0n)return 0;let t=H(c.toString()),n=H(e.toString());return t.minus(n).div(n).mul(100).round(2).toNumber()}function gn(c,e){let t=H(c.toString()),n=H(e.toString());return H(1).minus(n.div(t)).mul(100).round(2).toNumber()}function bn(c,e){let t=H(c.toString());return H(e.toString()).div(t).minus(1).mul(100).round(2).toNumber()}function yn(c,e,t=2){(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,t),s=BigInt(e*n);return c*s/BigInt(100*n)}var xt={};I(xt,{convertToId:()=>Pn});import{Buffer as hn}from"buffer";function Pn(c){let t=hn.from(c.replace("0x",""),"hex").subarray(16);return t.readUIntBE(0,t.length)}var{ERC20:Fe}=K,{H160:ze}=Re,fn=1.01,Tn=99999,xn=10n**27n,Sn=10n**18n,Y=class{client;constructor(e){let t=e??new E;this.client=new le(t)}async getSummary(e){let t=ze.fromAny(e),[n,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t)]),[i]=n,[a,o]=s,[l,u,d,p,m,g]=r,P=y.toDecimal(g,18),b=[];for(let x of a){let f=x.underlyingAsset.toLowerCase(),T=i.find(({underlyingAsset:qe})=>qe.toLowerCase()===f);if(!T)throw new Error("Missing pool reserve for "+f);let S=x.scaledATokenBalance,v=T.liquidityIndex,_=T.priceInMarketReferenceCurrency,R=S*v/xn,Oe=Number(o===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,ve=T.usageAsCollateralEnabled&&x.usageAsCollateralEnabledOnUser&&x.scaledATokenBalance>0n,Le=Fe.toAssetId(f);b.push({aTokenBalance:R,decimals:Number(T.decimals),isCollateral:ve,priceInRef:_,reserveId:Le,reserveAsset:f,reserveLiquidationThreshold:Oe})}return{healthFactor:Number(P),totalCollateral:l,totalDebt:u,reserves:b}}async hasBorrowPositions(e){let t=ze.fromAny(e),n=await this.client.getUserAccountData(t),[s,r]=n;return r>0n}async getHealthFactor(e){let t=ze.fromAny(e),n=await this.client.getUserAccountData(t),[s,r,i,a,o,l]=n,u=y.toDecimal(l,18);return Number(u)}async getHealthFactorAfterWithdraw(e,t,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(e),a=Fe.fromAssetId(t),o=i.find(b=>b.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,isCollateral:u,priceInRef:d,reserveLiquidationThreshold:p}=o,m=y.toBigInt(n,l),g=u?m*d/10n**BigInt(l):0n,P=s-g;return P<=0n?0:this.calculateHealthFactor(P,p,r)}async getHealthFactorAfterSupply(e,t,n){let{totalCollateral:s,totalDebt:r,reserves:i}=await this.getSummary(e),a=Fe.fromAssetId(t),o=i.find(P=>P.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:d}=o,m=y.toBigInt(n,l)*u/10n**BigInt(l),g=s+m;return g<=0n?0:this.calculateHealthFactor(g,d,r)}async getMaxWithdraw(e,t){let{totalCollateral:n,totalDebt:s,reserves:r}=await this.getSummary(e),i=Fe.fromAssetId(t),a=r.find(o=>o.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(a,n,s)}async getMaxWithdrawAll(e){let{totalCollateral:t,totalDebt:n,reserves:s}=await this.getSummary(e),r={};for(let i of s){let a=this.calculateWithdrawMax(i,t,n);i.reserveId&&(r[i.reserveId]=a)}return r}calculateHealthFactor(e,t,n){if(n===0n)return Tn;let s=10n**6n,r=y.toBigInt(t,18),i=e*r*s,a=n*Sn,o=i/a;return Number(o)/1e6}calculateRequiredCollateral(e,t,n){let s=y.toBigInt(e,18),r=y.toBigInt(t,18);return(s*n+r-1n)/r}calculateWithdrawMax(e,t,n){let{aTokenBalance:s,decimals:r,priceInRef:i,reserveLiquidationThreshold:a}=e,o=this.calculateRequiredCollateral(fn,a,n),l=t-o;if(l<=0n)return{amount:0n,decimals:r};let u=l*10n**BigInt(r)/i;return{amount:s<u?s:u,decimals:r}}};var wt={};I(wt,{AssetClient:()=>$,BalanceClient:()=>q,ChainParams:()=>J});var $=class extends F{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async queryShares(){let t=await this.api.query.Stableswap.Pools.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryBonds(){let t=await this.api.query.Bonds.Bonds.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssets(){let t=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(t.filter(({value:n})=>{let{asset_type:s}=n;return this.SUPPORTED_TYPES.includes(s.type)}).map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async queryAssetLocations(){let t=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(t.map(({keyArgs:n,value:s})=>{let[r]=n;return[r,s]}))}async mapToken(e,t,n,s){let{name:r,asset_type:i,is_sufficient:a,existential_deposit:o}=t,{symbol:l,decimals:u}=n.get(e)??{};return{id:e,name:r?.asText(),symbol:l,decimals:u,icon:l,type:i.type,isSufficient:a,location:s,existentialDeposit:o}}async mapBond(e,t,n,s){let[r,i]=s,{asset_type:a,is_sufficient:o,existential_deposit:l}=t,{symbol:u,decimals:d}=await this.mapToken(r,t,n),p=Number(i),m=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",m.format(p)].join(" ");return{id:e,name:g,symbol:u+"b",decimals:d,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:r,maturity:p}}async mapShares(e,t,n,s){let{assets:r}=s,{name:i,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=t,d=await Promise.all(r.map(async g=>{let{symbol:P}=await this.mapToken(g,t,n);return[g,P]})),p=Object.fromEntries(d),m=Object.values(p);return{id:e,name:m.join(", "),symbol:a?.asText()||i?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:p}}async mapExternal(e,t,n,s){let r=await this.mapToken(e,t,new Map,s),i=n?.find(a=>a.internalId===r.id);return i?{...r,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:r}parseMetadata(e){return new Map(Array.from(e,([t,n])=>[t,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(e,t){let[n,s,r,i]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(n),o=[];for(let[l,u]of Array.from(n)){let d=s.get(l),{asset_type:p}=u,m;switch(p.type){case"Bond":let g=i.get(l);m=await this.mapBond(l,u,a,g);break;case"StableSwap":let P=r.get(l);m=await this.mapShares(l,u,a,P);break;case"External":m=await this.mapExternal(l,u,t,d);break;default:m=await this.mapToken(l,u,a,d)}o.push(m)}return e?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}};import{Subject as In,bufferCount as wn,combineLatest as On,debounceTime as vn,distinctUntilChanged as It,finalize as An,map as Q,pairwise as Bn,shareReplay as _n,startWith as Rn}from"rxjs";var q=class extends F{constructor(e){super(e)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getTokenBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:{free:n,frozen:s}}=await t.getValue(e);return n-s}async getTokenBalance(e,t){let n=this.api.query.Tokens.Accounts,{free:s,frozen:r}=await n.getValue(e,t);return s-r}async getErc20Balance(e,t){return this.getTokenBalanceData(e,t)}subscribeBalance(e){let t=this.subscribeSystemBalance(e),n=this.subscribeTokensBalance(e),s=this.subscribeErc20Balance(e);return On([t,n,s]).pipe(vn(250),Q(r=>r.flat()),Rn([]),wn(2,1),Q(([r,i],a)=>{if(a===0)return i;let o=r.reduce((u,d)=>(u.set(d.id,d.amount),u),new Map);return i.filter(u=>u.amount!==o.get(u.id))}))}subscribeSystemBalance(e){return this.api.query.System.Account.watchValue(e,"best").pipe(Q(n=>{let{free:s,frozen:r}=n.data;return{id:0,amount:s-r}}))}subscribeTokenBalance(e,t){return this.api.query.Tokens.Accounts.watchValue(e,t,"best").pipe(Q(s=>{let{free:r,frozen:i}=s;return{id:t,amount:r-i}}))}subscribeTokensBalance(e){return this.api.query.Tokens.Accounts.watchEntries(e,{at:"best"}).pipe(It((n,s)=>!s.deltas),Q(({deltas:n})=>{let s=[];return n?.deleted.forEach(r=>{let[i,a]=r.args;s.push({id:a,amount:0n})}),n?.upserted.forEach(r=>{let[i,a]=r.args,{free:o,frozen:l}=r.value;s.push({id:a,amount:o-l})}),s}))}subscribeErc20Balance(e,t){let n=new In,s=n.pipe(_n(1)),r=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:u}=l;return u.type==="Erc20"}).map(({keyArgs:l})=>{let[u]=l;return u}),i=async()=>{let o=t||await r(),l=async()=>{let p=(await Promise.all(o.map(async m=>{let g=await this.getTokenBalanceData(e,m);return[m,g]}))).map(([m,g])=>({id:m,amount:g}));n.next(p)};await l();let u=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>u.unsubscribe()},a;return i().then(o=>a=o),s.pipe(An(()=>a?.()),Bn(),Q(([o,l],u)=>{if(u===0)return l;let d=o.reduce((m,g)=>(m.set(g.id,g.amount),m),new Map);return l.filter(m=>m.amount!==d.get(m.id))}),It((o,l)=>l.length===0))}async getTokenBalanceData(e,t){let{free:n,frozen:s}=await this.api.apis.CurrenciesApi.account(t,e);return n-s}};var J=class extends F{_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 Ot={};I(Ot,{AssetNotFound:()=>$e,PoolNotFound:()=>ce,RouteNotFound:()=>Z});var $e=class extends Error{constructor(e){super(),this.message=`${e} not found`,this.name="AssetNotFound"}},ce=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Z=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in current configuration`,this.name="RouteNotFound"}};var Dt={};I(Dt,{PoolContextProvider:()=>ne,PoolError:()=>j,PoolFactory:()=>te,PoolType:()=>A,aave:()=>tt,lbp:()=>Qe,omni:()=>Je,stable:()=>Ze,xyk:()=>et});var Qe={};I(Qe,{LbpMath:()=>M,LbpPool:()=>pe,LbpPoolClient:()=>me});import{calculate_in_given_out as Fn,calculate_out_given_in as En,calculate_linear_weights as Dn,calculate_pool_trade_fee as kn,get_spot_price as Cn}from"@galacticcouncil/math-lbp";var M=class{static getSpotPrice(e,t,n,s,r){return Cn(e,t,n,s,r)}static calculateInGivenOut(e,t,n,s,r){return Fn(e,t,n,s,r)}static calculateOutGivenIn(e,t,n,s,r){return En(e,t,n,s,r)}static calculateLinearWeights(e,t,n,s,r){return Dn(e,t,n,s,r)}static calculatePoolTradeFee(e,t,n){return kn(e,t,n)}};var A=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r))(A||{}),j=(r=>(r.InsufficientTradingAmount="InsufficientTradingAmount",r.MaxInRatioExceeded="MaxInRatioExceeded",r.MaxOutRatioExceeded="MaxOutRatioExceeded",r.TradeNotAllowed="TradeNotAllowed",r.UnknownError="UnknownError",r))(j||{});var pe=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,n,s,r,i,a){this.type="LBP",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.fee=i,this.repayFeeApply=a}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,weightIn:s.weight,weightOut:r.weight}}validateAndBuy(e,t,n){let s=this.tokens[0].id,r=[];t<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=e.balanceOut/this.maxOutRatio;if(t>i&&r.push("MaxOutRatioExceeded"),s===e.assetOut){let a=this.calculateTradeFee(t,n),o=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=t+a,u=this.calculateInGivenOut(e,l),d=e.balanceIn/this.maxInRatio;return u>d&&r.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:t,feePct:o,errors:r}}else{let a=this.calculateInGivenOut(e,t),o=e.balanceIn/this.maxInRatio;return a>o&&r.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:t,feePct:0,errors:r}}}validateAndSell(e,t,n){let s=this.tokens[0].id,r=[];t<this.minTradingLimit&&r.push("InsufficientTradingAmount");let i=e.balanceIn/this.maxInRatio;if(t>i&&r.push("MaxInRatioExceeded"),s===e.assetIn){let a=this.calculateOutGivenIn(e,t),o=e.balanceOut/this.maxOutRatio;return a>o&&r.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:a,feePct:0,errors:r}}else{let a=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(a,n),l=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),u=a-o,d=e.balanceOut/this.maxOutRatio;return u>d&&r.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:u,feePct:l,errors:r}}}calculateInGivenOut(e,t){let n=M.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=M.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=M.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),this.maxOutRatio.toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=M.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),this.maxInRatio.toString());return BigInt(t)}calculateTradeFee(e,t){let n=M.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 Un}from"polkadot-api";import{map as Wn,of as Rt,switchMap as Vn}from"rxjs";import{memoize1 as Mn}from"@thi.ng/memoize";import{combineLatest as vt,combineLatestAll as Ln,debounceTime as qn,firstValueFrom as Nn,from as At,map as Bt,mergeAll as Hn,of as Gn,switchMap as _t}from"rxjs";var k=class extends q{override=[];mem=0;memPools=Mn(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=At(this.getPoolsMem()).pipe(_t(t=>this.subscribe(t)),Ln());return Nn(e)}getSubscriber(){return At(this.getPoolsMem()).pipe(_t(e=>this.subscribe(e)),Hn())}subscribe(e){return e.filter(t=>this.hasValidAssets(t)).map(t=>vt([this.subscribePoolChange(t),this.subscribePoolBalance(t)]).pipe(qn(250),Bt(([n,s])=>this.updatePool(n,s))))}subscribePoolBalance(e){if(e.type==="Aave")return Gn([]);let t=[this.subscribeTokensBalance(e.address)];if(this.hasSystemAsset(e)){let n=this.subscribeSystemBalance(e.address);t.push(n)}if(this.hasErc20Asset(e)){let n=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),s=this.subscribeErc20Balance(e.address,n);t.push(s)}return vt(t).pipe(Bt(n=>n.map(s=>Array.isArray(s)?s:[s]).flat()))}hasSystemAsset(e){return e.tokens.some(t=>t.id===0)}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}hasValidAssets(e){return e.tokens.every(({id:t,decimals:n,balance:s})=>{let r=this.override.find(a=>a.id===t),i=!!n||!!r?.decimals;return s>0n&&i})}updatePool=(e,t)=>{let n=e.tokens.map(s=>{let r=t.find(a=>a.id===s.id),i=this.override.find(a=>a.id===s.id);return r?{...s,balance:r.amount,decimals:s.decimals||i?.decimals}:{...s,decimals:s.decimals||i?.decimals}});return{...e,tokens:n}}};var me=class extends k{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[e,t,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),s=t?.relay_parent_number||0,r=e.filter(({value:i})=>t&&this.isActivePool(i,s)).map(async({keyArgs:i,value:a})=>{let[o]=i,l=o.toString(),u=await this.getPoolDelta(l,a,s);return{address:l,type:"LBP",fee:a.fee,...u,...n}});return Promise.all(r)}async getPoolDelta(e,t,n){let{start:s,end:r,assets:i,initial_weight:a,final_weight:o,repay_target:l,fee_collector:u}=t,d=M.calculateLinearWeights(s?s.toString():"0",r?r.toString():"0",a.toString(),o.toString(),n.toString()),[p,m]=i,g=BigInt(d),P=this.MAX_FINAL_WEIGHT-BigInt(g),[b,x,f,T,S]=await Promise.all([this.isRepayFeeApplied(p,l,u.toString()),this.getBalance(e,p),this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(e,m),this.api.query.AssetRegistry.Assets.getValue(m)]);return{repayFeeApply:b,tokens:[{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:x,weight:g,type:f?.asset_type.type},{id:m,decimals:S?.decimals,existentialDeposit:S?.existential_deposit,balance:T,weight:P,type:S?.asset_type.type}]}}isActivePool(e,t){let{start:n,end:s}=e;return n&&s?t>=n&&t<s:!1}async isRepayFeeApplied(e,t,n){if(t===0n)return!1;try{return await this.getBalance(n,e)<t}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(e){return{repayFee:await this.getRepayFee(),exchangeFee:e.fee}}getPoolType(){return"LBP"}async isSupported(){let e=this.api.query.LBP.PoolData,t=await this.api.compatibilityToken;return e.isCompatible(Un.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(e.address);return n?t.watchValue("best").pipe(Vn(s=>s?this.getPoolDelta(e.address,n,s.relay_parent_number):Rt(e)),Wn(s=>Object.assign({},e,s))):Rt(e)}};var Je={};I(Je,{OmniMath:()=>w,OmniPool:()=>de,OmniPoolClient:()=>ge});import{calculate_in_given_out as Xn,calculate_lrna_in_given_out as Yn,calculate_out_given_in as jn,calculate_out_given_lrna_in as Kn,calculate_spot_price as zn,calculate_lrna_spot_price as $n,calculate_shares as Qn,calculate_liquidity_out as Jn,calculate_liquidity_lrna_out as Zn,verify_asset_cap as es,calculate_liquidity_hub_in as ts,is_sell_allowed as ns,is_buy_allowed as ss,is_add_liquidity_allowed as rs,is_remove_liquidity_allowed as as}from"@galacticcouncil/math-omnipool";import ee from"big.js";var w=class{static calculateSpotPrice(e,t,n,s){return zn(e,t,n,s)}static calculateLrnaSpotPrice(e,t){return $n(e,t)}static calculateInGivenOut(e,t,n,s,r,i,a,o,l){return Xn(e,t,n,s,r,i,a,o,l)}static calculateLrnaInGivenOut(e,t,n,s,r){return Yn(e,t,n,s,r)}static calculateOutGivenIn(e,t,n,s,r,i,a,o,l){return jn(e,t,n,s,r,i,a,o,l)}static calculateOutGivenLrnaIn(e,t,n,s,r){return Kn(e,t,n,s,r)}static calculateShares(e,t,n,s){return Qn(e,t,n,s)}static calculateLiquidityOut(e,t,n,s,r,i,a,o){return Jn(e,t,n,s,r,i,a,o)}static calculateLiquidityLRNAOut(e,t,n,s,r,i,a,o){return Zn(e,t,n,s,r,i,a,o)}static calculateCapDifference(e,t,n,s){let r=ee(t),i=ee(e),a=ee(s),o=ee(n),l=ee(10).pow(18),u=o.div(l);if(r.div(a).lt(u)){let p=u.times(a).minus(r).times(i),m=r.times(ee(1).minus(u));return p.div(m).toFixed(0)}else return"0"}static verifyAssetCap(e,t,n,s){return es(e,t,n,s)}static calculateLimitHubIn(e,t,n,s){return ts(e,t,n,s)}static isSellAllowed(e){return ns(e)}static isBuyAllowed(e){return ss(e)}static isAddLiquidityAllowed(e){return rs(e)}static isRemoveLiquidityAllowed(e){return as(e)}};var de=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,n,s,r,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.hubAssetId=i}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:r.hubReserves,sharesIn:s.shares,sharesOut:r.shares,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,tradeableIn:s.tradeable,tradeableOut:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),r=this.calculateInGivenOut(e,t,n),i=s===0n?0:O.calculateDiffToRef(r,s),a=[],o=w.isSellAllowed(e.tradeableIn),l=w.isBuyAllowed(e.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetInEd)&&a.push("InsufficientTradingAmount");let u=e.balanceOut/this.maxOutRatio;t>u&&a.push("MaxOutRatioExceeded");let d=e.balanceIn/this.maxInRatio;return r>d&&a.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:s,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),r=this.calculateOutGivenIn(e,t,n),i=O.calculateDiffToRef(s,r),a=[],o=w.isSellAllowed(e.tradeableIn),l=w.isBuyAllowed(e.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetOutEd)&&a.push("InsufficientTradingAmount");let u=e.balanceIn/this.maxInRatio;t>u&&a.push("MaxInRatioExceeded");let d=e.balanceOut/this.maxOutRatio;return r>d&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateInGivenOut(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,n);let s=w.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateLrnaInGivenOut(e,t,n){let s=w.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(e,t,n){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,n);let s=w.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}calculateOutGivenLrnaIn(e,t,n){let s=w.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),n?h.toDecimals(n.assetFee).toString():"0"),r=BigInt(s);return r<0n?0n:r}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=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 is,CompatibilityLevel as os}from"polkadot-api";import{toHex as ls}from"@polkadot-api/utils";import{distinctUntilChanged as us,map as Ft}from"rxjs";var ge=class extends k{async loadPools(){let e=await this.api.constants.Omnipool.HubAssetId(),t=this.getPoolAddress(),[n,s,r,i,a]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(e),this.getBalance(t,e),this.getPoolLimits()]),o=n.map(async({keyArgs:u,value:d})=>{let[p]=u,{hub_reserve:m,shares:g,tradable:P,cap:b,protocol_shares:x}=d,[f,T]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(t,p)]);return{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:T,cap:b,hubReserves:m,protocolShares:x,shares:g,tradeable:P,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:e,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:i,tradeable:s,type:r?.asset_type.type}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:l,...a}]}getPoolAddress(){let e="modlomnipool".padEnd(32,"\0"),t=new TextEncoder().encode(e),n=ls(t);return is(63).dec(n)}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(e,t){let[n,s,r]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(t)]),i=n.min_fee+s.min_fee,a=n.max_fee+s.max_fee;if(r){let{asset_fee:o,protocol_fee:l}=r;return{assetFee:h.fromPermill(o),protocolFee:h.fromPermill(l),min:h.fromPermill(i),max:h.fromPermill(a)}}else return{assetFee:h.fromPermill(n.min_fee),protocolFee:h.fromPermill(s.min_fee),min:h.fromPermill(i),max:h.fromPermill(a)}}getPoolType(){return"Omnipool"}async isSupported(){let e=this.api.query.Omnipool.Assets,t=await this.api.compatibilityToken;return e.isCompatible(os.BackwardsCompatible,t)}subscribePoolChange(e){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(us((n,s)=>!s.deltas),Ft(({entries:n})=>n.map(s=>{let[r]=s.args,{hub_reserve:i,shares:a,tradable:o,cap:l,protocol_shares:u}=s.value,d=e.tokens.findIndex(m=>m.id===r);return{...e.tokens[d],cap:l,hubReserves:i,protocolShares:u,shares:a,tradeable:o}})),Ft(n=>{let s=e.tokens.find(r=>r.id===1);return{...e,tokens:[...n,s]}}))}};var Ze={};I(Ze,{StableMath:()=>B,StableSwap:()=>be,StableSwapClient:()=>ye});import{calculate_in_given_out as cs,calculate_out_given_in as ps,calculate_amplification as ms,calculate_add_one_asset as ds,calculate_liquidity_out_one_asset as gs,calculate_shares as bs,calculate_shares_for_amount as ys,calculate_spot_price_with_fee as hs,pool_account_name as Ps,recalculate_peg as fs}from"@galacticcouncil/math-stableswap";var B=class{static getPoolAddress(e){return Ps(e)}static defaultPegs(e){let t=[];for(let n=0;n<e;n++)t.push(["1","1"]);return t}static calculateAmplification(e,t,n,s,r){return ms(e,t,n,s,r)}static calculateInGivenOut(e,t,n,s,r,i,a){return cs(e,t,n,s,r,i,a)}static calculateAddOneAsset(e,t,n,s,r,i,a){return ds(e,t,n,s,r,i,a)}static calculateSharesForAmount(e,t,n,s,r,i,a){return ys(e,t,n,s,r,i,a)}static calculateOutGivenIn(e,t,n,s,r,i,a){return ps(e,t,n,s,r,i,a)}static calculateLiquidityOutOneAsset(e,t,n,s,r,i,a){return gs(e,t,n,s,r,i,a)}static calculateShares(e,t,n,s,r,i){return bs(e,t,n,s,r,i)}static calculateSpotPriceWithFee(e,t,n,s,r,i,a,o){return hs(e,t,n,s,r,i,a,o)}static recalculatePegs(e,t,n,s,r){let i=fs(e,t,n,s,r);return JSON.parse(i)}};var be=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,n,s,r,i,a,o,l){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r,this.amplification=i,this.id=a,this.fee=o,this.totalIssuance=l}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:r.tradeable,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),r=this.calculateInGivenOut(e,t,n),i=h.toPct(n.fee),a=[],o=w.isSellAllowed(e.tradeableIn),l=w.isBuyAllowed(e.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:r,calculatedIn:s,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),r=this.calculateOutGivenIn(e,t,n),i=h.toPct(n.fee),a=[],o=w.isSellAllowed(e.tradeableIn),l=w.isBuyAllowed(e.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(t<this.minTradingLimit||s<e.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:r,feePct:i,errors:a}}calculateIn(e,t,n){let s=B.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateAddOneAsset(e,t,n){let s=B.calculateAddOneAsset(this.getReserves(),t.toString(),Number(e.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateSharesForAmount(e,t,n){let s=B.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateInGivenOut(e,t,n){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,n):e.assetIn==this.id?this.calculateSharesForAmount(e,t,n):this.calculateIn(e,t,n)}spotPriceInGivenOut(e){let t=B.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=B.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateWithdrawOneAsset(e,t,n){let s=B.calculateLiquidityOutOneAsset(this.getReserves(),t.toString(),Number(e.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateShares(e,t,n){let s=B.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),r=BigInt(s);return r<0n?0n:r}calculateOutGivenIn(e,t,n){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,n):e.assetOut==this.id?this.calculateShares(e,t,n):this.calculateOut(e,t,n)}spotPriceOutGivenIn(e){let t=B.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=B.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 Ts,CompatibilityLevel as xs}from"polkadot-api";import{toHex as Ss}from"@polkadot-api/utils";import{blake2b as Is}from"@noble/hashes/blake2b";import{map as ws,of as Os,switchMap as vs}from"rxjs";var As=340282366920938463463374607431768211455n,ye=class extends k{poolsData=new Map([]);async loadPools(){let[e,t,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),s=e.map(async({keyArgs:r,value:i})=>{let[a]=r,o=this.getPoolAddress(a),[l,u,d]=await Promise.all([this.getPoolDelta(a,i,t),this.getPoolTokens(a,i),this.getPoolPegs(a,i,t)]);return this.poolsData.set(o,i),{address:o,id:a,type:"Stableswap",fee:h.fromPermill(i.fee),tokens:u,...l,...d,...n}});return Promise.all(s)}async getPoolDelta(e,t,n){let{initial_amplification:s,final_amplification:r,initial_block:i,final_block:a}=t,o=B.calculateAmplification(s.toString(),r.toString(),i.toString(),a.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(e);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(e,t){let n=this.getPoolAddress(e),s=t.assets.map(async a=>{let[o,l,u]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(e,a),this.api.query.AssetRegistry.Assets.getValue(a),this.getBalance(n,a)]);return{id:a,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:u,tradeable:o,type:l?.asset_type.type}}),r=await Promise.all(s),i=await this.api.query.AssetRegistry.Assets.getValue(e);return r.push({id:e,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:As,tradeable:15,type:i?.asset_type.type}),r}async getPoolPegs(e,t,n){let s=await this.api.query.Stableswap.PoolPegs.getValue(e);if(!s)return this.getDefaultPegs(t);let r=await this.getLatestPegs(t,s,n),i=this.getRecentPegs(s),a=h.fromPermill(s.max_peg_update),o=h.fromPermill(t.fee),[l,u]=B.recalculatePegs(JSON.stringify(i),JSON.stringify(r),n.toString(),h.toDecimals(a).toString(),h.toDecimals(o).toString()),d=Number(l)*1e6;return{pegsFee:h.fromPermill(d),pegs:u}}getDefaultPegs(e){let t=e.fee,n=B.defaultPegs(e.assets.length);return{pegsFee:h.fromPermill(t),pegs:n}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([n,s])=>s.map(r=>r.toString()))}async getLatestPegs(e,t,n){let{source:s}=t,r=Array.from(e.assets.entries()).map(([a,o])=>o),i=s.map(async(a,o)=>{if(a.type==="Oracle"){let[l,u,d]=a.value,p=[d,r[o]].sort((f,T)=>f-T),m=await this.api.query.EmaOracle.Oracles.getValue(l,p,u);if(!m)return;let[{price:g,updated_at:P}]=m,b=g.n.toString(),x=g.d.toString();return d.toString()===p[0].toString()?[[b,x],P.toString()]:[[x,b],P.toString()]}else return[a.value.map(l=>l.toString()),n]});return Promise.all(i)}getPoolAddress(e){let t=B.getPoolAddress(e),n=Is(t,{dkLen:32}),s=Ss(n);return Ts(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(xs.BackwardsCompatible,t)}subscribePoolChange(e){let t=this.api.query.System.Number,n=this.poolsData.get(e.address);return!n||!e.id?Os(e):t.watchValue("best").pipe(vs(s=>this.getPoolDelta(e.id,n,s)),ws(s=>Object.assign({},e,s)))}};var et={};I(et,{XykMath:()=>G,XykPool:()=>he,XykPoolClient:()=>Pe});import{calculate_in_given_out as Bs,calculate_out_given_in as _s,calculate_pool_trade_fee as Rs,get_spot_price as Fs,calculate_liquidity_in as Es,calculate_shares as Ds,calculate_spot_price as ks,calculate_spot_price_with_fee as Cs,calculate_liquidity_out_asset_a as Ms,calculate_liquidity_out_asset_b as Ls}from"@galacticcouncil/math-xyk";var G=class{static getSpotPrice(e,t,n){return Fs(e,t,n)}static calculateInGivenOut(e,t,n){return Bs(e,t,n)}static calculateOutGivenIn(e,t,n){return _s(e,t,n)}static calculatePoolTradeFee(e,t,n){return Rs(e,t,n)}static calculateLiquidityIn(e,t,n){return Es(e,t,n)}static calculateSpotPrice(e,t){return ks(e,t)}static calculateSpotPriceWithFee(e,t,n,s){return Cs(e,t,n,s)}static calculateShares(e,t,n){return Ds(e,t,n)}static calculateLiquidityOutAssetA(e,t,n,s){return Ms(e,t,n,s)}static calculateLiquidityOutAssetB(e,t,n,s){return Ls(e,t,n,s)}};var he=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,n,s,r){this.type="XYK",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:r.decimals,balanceIn:s.balance,balanceOut:r.balance,assetInEd:s.existentialDeposit,assetOutEd:r.existentialDeposit}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),r=this.calculateTradeFee(s,n),i=h.toPct(n.exchangeFee),a=s+r,o=[];(t<this.minTradingLimit||s<e.assetInEd)&&o.push("InsufficientTradingAmount");let l=e.balanceOut/this.maxOutRatio;t>l&&o.push("MaxOutRatioExceeded");let u=e.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:t,feePct:i,errors:o}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),r=this.calculateTradeFee(s,n),i=h.toPct(n.exchangeFee),a=s-r,o=[];(t<this.minTradingLimit||s<e.assetOutEd)&&o.push("InsufficientTradingAmount");let l=e.balanceIn/this.maxInRatio;t>l&&o.push("MaxInRatioExceeded");let u=e.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:a,feePct:i,errors:o}}calculateInGivenOut(e,t){let n=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 qs}from"polkadot-api";import{of as Ns}from"rxjs";var Pe=class extends k{async loadPools(){let e=this.api.query.XYK.PoolAssets,[t,n]=await Promise.all([e.getEntries(),this.getPoolLimits()]),s=t.map(async({keyArgs:r,value:i})=>{let[a]=r,[o,l]=i,[u,d,p,m]=await Promise.all([this.getBalance(a,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(a,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:a,type:"XYK",tokens:[{id:o,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:u,type:d?.asset_type.type},{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:p,type:m?.asset_type.type}],...n}});return Promise.all(s)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[e,t,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:n}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let e=this.api.query.XYK.PoolAssets,t=await this.api.compatibilityToken;return e.isCompatible(qs.BackwardsCompatible,t)}subscribePoolChange(e){return Ns(e)}};var tt={};I(tt,{AavePool:()=>fe,AavePoolClient:()=>Te});var fe=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new c(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,n,s,r){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=r}validatePair(e,t){return!0}parsePair(e,t){let n=new Map(this.tokens.map(i=>[i.id,i])),s=n.get(e),r=n.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(r==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:s.balance,balanceOut:r.balance,decimalsIn:s.decimals,decimalsOut:r.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(e,t,n){let s=this.calculateInGivenOut(e,t),r=[];return t>e.balanceOut&&r.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:r}}validateAndSell(e,t,n){let s=this.calculateOutGivenIn(e,t),r=[];return s>e.balanceOut&&r.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:r}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){let t=Math.pow(10,e.decimalsOut);return BigInt(t)}spotPriceOutGivenIn(e){let t=Math.pow(10,e.decimalsIn);return BigInt(t)}calculateTradeFee(e,t){return 0n}};import{AccountId as Hs}from"polkadot-api";import{toHex as Gs}from"@polkadot-api/utils";import{map as Us,merge as Ws,switchMap as Vs}from"rxjs";import{decodeEventLog as Xs}from"viem";var Et=[{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:Ys}=K,js=["Supply","Withdraw","Repay","Borrow"],Te=class extends k{async loadPools(){let t=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:s,liqudity_in:r,liqudity_out:i})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(n,s),type:"Aave",tokens:[{id:n,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:r,location:o,type:a?.asset_type.type},{id:s,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:i,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolDelta(e){let[t,n]=e.tokens,{liqudity_in:s,liqudity_out:r}=await this.api.apis.AaveTradeExecutor.pool(t.id,n.id);return e.tokens.map(i=>{let a=i.id===t.id?s:r;return{...i,balance:a}})}getPoolId(e,t){let n=e+"/"+t,s=new TextEncoder().encode(n.padEnd(32,"\0")),r=Gs(s);return Hs(63).dec(r)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(e){let[t,n]=e.tokens,s=this.getReserveH160Id(t),r=this.api.event.Router.Executed.watch(({asset_in:a,asset_out:o})=>a===n.id||o===n.id),i=this.api.event.EVM.Log.watch(({log:a})=>{let{topics:o,data:l}=a,u=o.map(g=>g.asHex()),d=l.asHex(),{eventName:p,args:m}=Xs({abi:Et,topics:u,data:d});return js.includes(p)&&m.reserve.toLowerCase()===s.toLowerCase()});return Ws([r,i]).pipe(Vs(()=>this.getPoolDelta(e)),Us(a=>({...e,tokens:[...a]})))}getReserveH160Id(e){return e.type==="Erc20"?X.findNestedKey(e.location,"AccountKey20").AccountKey20.key:Ys.fromAssetId(e.id)}};var te=class{static get(e){switch(e.type){case"Aave":return fe.fromPool(e);case"XYK":return he.fromPool(e);case"Omnipool":return de.fromPool(e);case"LBP":return pe.fromPool(e);case"Stableswap":return be.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{Subject as Ks,Subscription as xe,takeUntil as zs}from"rxjs";var ne=class extends F{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 Ks;constructor(e){super(e),this.lbpClient=new me(e),this.omniClient=new ge(e),this.stableClient=new ye(e),this.xykClient=new Pe(e),this.aaveClient=new Te(e),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(e){return e.getSubscriber().pipe(zs(this.isDestroyed)).subscribe(t=>{this.pools.set(t.address,t)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(e){return this.xykClient.withOverride(e),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let e=await Promise.all(this.clients.filter(t=>this.active.has(t.getPoolType())).map(t=>t.getPools()));return this.isReady=!0,e.flat()}async getPoolFees(e,t){let n=this.clients.find(s=>s.getPoolType()===e.type);if(n)return n.getPoolFees(e,t);throw new ce(e.type)}};var Lt={};I(Lt,{DEFAULT_BLOCK_TIME:()=>kt,DEFAULT_MIN_BUDGET:()=>rt,ORDER_MIN_BLOCK_PERIOD:()=>Ct,Router:()=>se,TWAP_BLOCK_PERIOD:()=>we,TWAP_MAX_DURATION:()=>it,TWAP_MAX_PRICE_IMPACT:()=>at,TWAP_TX_MULTIPLIER:()=>cu,TradeOrderError:()=>st,TradeOrderType:()=>ke,TradeRouteBuilder:()=>C,TradeRouter:()=>re,TradeScheduler:()=>ae,TradeType:()=>De});var Ee=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 $s=5,Se=class{isNotVisited(e,t){let n=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(n=!1)}),n}findPaths(e,t,n){let s=[],r=new Ee,i=[];for(i.push([t,""]),r.enqueue(i);r.size()>0;){let a=r.dequeue();if(a==null||a.length>$s)return s;let o=a[a.length-1];(n===null||o[0]===n)&&s.push(a),e.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let d=[...a];d.push(u),r.enqueue(d)}})}return s}buildAndPopulateGraph(e,t){let n=new Map;for(let s of e)n.set(parseInt(s),[]);for(let[s,r,i]of t)n.get(r)?.push([i,s]);return n}};function nt(c){let e={};for(let t of c){let n=t.tokens.length;for(let s=0;s<n;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let r=0;r<n;r++){if(s==r)continue;let i=[t.address,t.tokens[s].id,t.tokens[r].id];e[t.tokens[s].id].push(i)}}}return e}var Ie=class{getProposals(e,t,n){let s=nt(n),r=Object.keys(s),i=r.map(u=>s[u]).flat(),a=new Se,o=a.buildAndPopulateGraph(r,i),l=a.findPaths(o,e,t);return this.parsePaths(l)}parsePaths(e){let t=[];for(let n of e){let s=[];for(let r=0;r<n.length;r++){let i=n[r],a=n[r+1];if(a==null)break;s.push(this.toEdge(i,a))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0],t[0]]}};var se=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(e,t){this.ctx=e,this.routeSuggester=new Ie,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=await this.ctx.getPools(),t=this.routerOptions.useOnly;return t.length===0?e:e.filter(n=>t.includes(n.type))}async getRoutes(e,t){let n=await this.getPools();return this.validateInput(e,t,n),this.getPaths(e,t,n)}async getTradeableAssets(){let e=await this.getPools(),t=this.getAssets(e);return Array.from(t)}validateInput(e,t,n){if(n.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(n);if(!s.has(e))throw new Error(e+" is not supported asset");if(!s.has(t))throw new Error(t+" is not supported asset");return this.toPoolsMap(n)}getAssets(e){let t=e.map(n=>n.tokens.map(s=>s.id)).flat().sort((n,s)=>n>s?1:-1);return new Set(t)}getPaths(e,t,n){let s=this.toPoolsMap(n);return this.routeSuggester.getProposals(e,t,n).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}validPath(e,t){return e.length>0&&e.map(n=>this.validEdge(n,t)).reduce((n,s)=>n&&s)}validEdge([e,t,n],s){return s.get(e)?.validatePair(t,n)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,te.get(t)]))}toHops(e,t){return e.map(([n,s,r])=>{let i=t.get(n);return{poolAddress:n,poolId:i?.id,pool:i?.type,assetIn:s,assetOut:r}})}};var De=(t=>(t.Buy="Buy",t.Sell="Sell",t))(De||{}),ke=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(ke||{}),st=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(st||{});var re=class extends se{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((n,s)=>{let r=n[n.length-1].amountOut,i=s[s.length-1].amountOut;return r>i?-1:1});return t.find(n=>n.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(n=>n.tradeFeeRange).length>0){let n=e.map(r=>r.tradeFeeRange?.[0]??r.tradeFeePct).reduce((r,i)=>r+i),s=e.map(r=>r.tradeFeeRange?.[1]??r.tradeFeePct).reduce((r,i)=>r+i);return[n,s]}}getPoolFeeRange(e){let t=e.min?h.toPct(e.min):void 0,n=e.max?h.toPct(e.max):void 0;if(t&&n)return[t,n]}async getBestSell(e,t,n){return this.getSell(e,t,n)}async getSellSpot(e){let t=e[e.length-1];if(e.length===1)return t.spotPrice;let n=e.map(a=>a.assetOutDecimals).reduce((a,o)=>a+o),s=e.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-t.assetOutDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getSell(e,t,n,s){let r=await super.getPools(),i=super.validateInput(e,t,r),a=super.getPaths(e,t,r);if(a.length===0)throw new Z(e,t);let o;if(s)o=await this.toSellSwaps(n,s,i);else{let v=await Promise.all(a.map(_=>this.toSellSwaps(n,_,i)));o=this.findBestSellRoute(v)}let l=o[0],u=o[o.length-1],d=this.isDirectTrade(o),p=await this.getSellSpot(o),m=u.amountOut,g=d?u.calculatedOut:this.calculateDelta0Y(l.amountIn,o,i),P=g-m,b=this.getRouteFeeRange(o),x=d?u.tradeFeePct:O.calculateSellFee(g,m),f=Math.pow(10,l.assetInDecimals),T=l.amountIn*p/BigInt(f),S=O.calculateDiffToRef(g,T);return{type:"Sell",amountIn:l.amountIn,amountOut:u.amountOut,spotPrice:p,tradeFee:P,tradeFeePct:x,tradeFeeRange:b,priceImpactPct:S,swaps:o,toHuman(){return{type:"Sell",amountIn:y.toDecimal(l.amountIn,l.assetInDecimals),amountOut:y.toDecimal(u.amountOut,u.assetOutDecimals),spotPrice:y.toDecimal(p,u.assetOutDecimals),tradeFee:y.toDecimal(P,u.assetOutDecimals),tradeFeePct:x,tradeFeeRange:b,priceImpactPct:S,swaps:o.map(v=>v.toHuman())}}}}calculateDelta0Y(e,t,n){let s=[];for(let r=0;r<t.length;r++){let i=t[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r>0?l=s[r-1]:l=e;let u=a.calculateOutGivenIn(o,l);s.push(u)}return s[s.length-1]}async toSellSwaps(e,t,n){let s=[];for(let r=0;r<t.length;r++){let i=t[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r>0?l=s[r-1].amountOut:l=typeof e=="string"?y.toBigInt(e,o.decimalsIn):e;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountOut:d,calculatedOut:p,feePct:m,errors:g}=a.validateAndSell(o,l,u),P=this.getPoolFeeRange(u),b=a.spotPriceOutGivenIn(o),x=Math.pow(10,o.decimalsIn),f=l*b/BigInt(x),T=O.calculateDiffToRef(p,f);s.push({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:d,calculatedOut:p,spotPrice:b,tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===i.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:y.toDecimal(l,o.decimalsIn),amountOut:y.toDecimal(d,o.decimalsOut),calculatedOut:y.toDecimal(p,o.decimalsOut),spotPrice:y.toDecimal(b,o.decimalsOut),tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}async getMostLiquidRoute(e,t){let n=await super.getPools(),s=super.validateInput(e,t,n),r=super.getPaths(e,t,n),o=n.filter(p=>p.tokens.some(m=>m.id===e&&m.id!==p.id)).map(p=>p.type==="Aave"?p.tokens:p.tokens.filter(m=>m.id===e)).map(p=>p.map(m=>m.balance).reduce((m,g)=>m+g)).sort((p,m)=>m<p?-1:1)[0],l=O.getFraction(o,.1),u=await Promise.all(r.map(p=>this.toSellSwaps(l,p,s)));return this.findBestSellRoute(u).map(p=>({poolAddress:p.poolAddress,poolId:p?.poolId,pool:p.pool,assetIn:p.assetIn,assetOut:p.assetOut}))}async getSpotPrice(e,t){let n=await super.getPools(),s=super.validateInput(e,t,n),r=await this.getMostLiquidRoute(e,t),i=await this.toSellSwaps("1",r,s),a=await this.getSellSpot(i),o=i[i.length-1].assetOutDecimals;return{amount:a,decimals:o}}findBestBuyRoute(e){let t=e.sort((n,s)=>{let r=n[0].amountIn,i=s[0].amountIn;return r>i?1:-1});return t.find(n=>n.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,n){return this.getBuy(e,t,n)}async getBuySpot(e){let t=e[0];if(e.length===1)return t.spotPrice;let n=e.map(a=>a.assetInDecimals).reduce((a,o)=>a+o),s=e.map(a=>a.spotPrice).reduce((a,o)=>a*o),r=n-t.assetInDecimals,i=Math.pow(10,r);return s/BigInt(i)}async getBuy(e,t,n,s){let r=await super.getPools(),i=super.validateInput(e,t,r),a=super.getPaths(e,t,r);if(a.length===0)throw new Z(e,t);let o;if(s)o=await this.toBuySwaps(n,s,i);else{let v=await Promise.all(a.map(_=>this.toBuySwaps(n,_,i)));o=this.findBestBuyRoute(v)}let l=o[o.length-1],u=o[0],d=this.isDirectTrade(o),p=await this.getBuySpot(o),m=u.amountIn,g=d?u.calculatedIn:this.calculateDelta0X(l.amountOut,o,i),P=m-g,b=this.getRouteFeeRange(o),x=d?u.tradeFeePct:O.calculateBuyFee(g,m),f=Math.pow(10,l.assetOutDecimals),T=l.amountOut*p/BigInt(f),S;return g===0n?S=-100:S=O.calculateDiffToRef(T,g),{type:"Buy",amountOut:l.amountOut,amountIn:u.amountIn,spotPrice:p,tradeFee:P,tradeFeePct:x,tradeFeeRange:b,priceImpactPct:S,swaps:o,toHuman(){return{type:"Buy",amountOut:y.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:y.toDecimal(u.amountIn,u.assetInDecimals),spotPrice:y.toDecimal(p,u.assetInDecimals),tradeFee:y.toDecimal(P,u.assetInDecimals),tradeFeePct:x,tradeFeeRange:b,priceImpactPct:S,swaps:o.map(v=>v.toHuman())}}}}calculateDelta0X(e,t,n){let s=[];for(let r=t.length-1;r>=0;r--){let i=t[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r==t.length-1?l=e:l=s[0];let u=a.calculateInGivenOut(o,l);s.unshift(u)}return s[0]}async toBuySwaps(e,t,n){let s=[];for(let r=t.length-1;r>=0;r--){let i=t[r],a=n.get(i.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(i.assetIn,i.assetOut),l;r==t.length-1?l=typeof e=="string"?y.toBigInt(e,o.decimalsOut):e:l=s[0].amountIn;let u=await this.ctx.getPoolFees(a,o.assetOut),{amountIn:d,calculatedIn:p,feePct:m,errors:g}=a.validateAndBuy(o,l,u),P=this.getPoolFeeRange(u),b=a.spotPriceInGivenOut(o),x=Math.pow(10,o.decimalsOut),f=l*b/BigInt(x),T;p===0n?T=-100:T=O.calculateDiffToRef(f,p),s.unshift({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:d,calculatedIn:p,spotPrice:b,tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===i.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:y.toDecimal(l,o.decimalsOut),amountIn:y.toDecimal(d,o.decimalsIn),calculatedIn:y.toDecimal(p,o.decimalsIn),spotPrice:y.toDecimal(b,o.decimalsIn),tradeFeePct:m,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}};var kt=6e3,rt=1000000000000000n,we=6,at=-5,it=216e5,cu=3,Ct=6;import{Enum as Mt}from"polkadot-api";var C=class{static build(e){return e.map(({assetIn:t,assetOut:n,pool:s,poolId:r})=>s==="Stableswap"?{pool:Mt("Stableswap",r),asset_in:t,asset_out:n}:{pool:Mt(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??rt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,n,s,r){let[i,a]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:o,swaps:l,priceImpactPct:u}=a,d=l[0],p=l[l.length-1],{assetInDecimals:m}=d,{assetOutDecimals:g}=p,P=Math.abs(u),b=this.getMinimumTradeCount(o,i),x=this.getOptimalTradeCount(P),f=r?Math.round(s/r):x,T=Math.ceil(s/b),S=Math.round(s/x),v=Math.round(s/f),_=o/BigInt(f),R=await this.router.getBestSell(e,t,_),U=o<i,Oe=[];U&&Oe.push("OrderTooSmall");let ve=R.amountOut*BigInt(f),Le=this.toBlockPeriod(v),qe=R.tradeFee*BigInt(f),Gt=C.build(l),lt={assetIn:e,assetOut:t,errors:Oe,frequencyMin:T,frequencyOpt:S,frequency:v,tradeCount:f,tradeFee:qe,tradeImpactPct:R.priceImpactPct,tradePeriod:Le,tradeRoute:Gt,type:"Dca"};return{...lt,amountIn:o,amountOut:ve,tradeAmountIn:R.amountIn,tradeAmountOut:R.amountOut,toHuman(){return{...lt,amountIn:y.toDecimal(o,m),amountOut:y.toDecimal(ve,g),tradeAmountIn:y.toDecimal(R.amountIn,m),tradeAmountOut:y.toDecimal(R.amountOut,g)}}}}async getMinimumOrderBudget(e){if(0===e)return this.minOrderBudget;let t=await this.router.getSpotPrice(0,e),n=10n**BigInt(12);if(t)return this.minOrderBudget*t.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let n=t*2n/10n;if(n===0n)return 0;let s=e+n/2n;return Number(s/n)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,n)]),{amountIn:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:p}=u,m=Math.abs(o),g=this.getTwapTradeCount(m),P=i/BigInt(g),b=await this.router.getBestSell(l.assetIn,u.assetOut,P),x=g===1,f=i<s,T=b.priceImpactPct<-5,S=[];f||x?S.push("OrderTooSmall"):T&&S.push("OrderImpactTooBig");let v=b.amountOut*BigInt(g),_=b.tradeFee*BigInt(g),R=C.build(a),U={assetIn:e,assetOut:t,errors:S,tradeCount:g,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapSell"};return{...U,amountIn:i,amountOut:v,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:_,toHuman(){return{...U,amountIn:y.toDecimal(i,d),amountOut:y.toDecimal(v,p),tradeAmountIn:y.toDecimal(b.amountIn,d),tradeAmountOut:y.toDecimal(b.amountOut,p),tradeFee:y.toDecimal(_,p)}}}}async getTwapBuyOrder(e,t,n){let[s,r]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,n)]),{amountOut:i,swaps:a,priceImpactPct:o}=r,l=a[0],u=a[a.length-1],{assetInDecimals:d}=l,{assetOutDecimals:p}=u,m=Math.abs(o),g=this.getTwapTradeCount(m),P=i/BigInt(g),b=await this.router.getBestBuy(l.assetIn,u.assetOut,P),x=b.amountIn*BigInt(g),f=g===1,T=x<s,S=b.priceImpactPct<-5,v=[];T||f?v.push("OrderTooSmall"):S&&v.push("OrderImpactTooBig");let _=b.tradeFee*BigInt(g),R=C.build(a),U={assetIn:e,assetOut:t,errors:v,tradeCount:g,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapBuy"};return{...U,amountIn:x,amountOut:i,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:_,toHuman(){return{...U,amountIn:y.toDecimal(x,d),amountOut:y.toDecimal(i,p),tradeAmountIn:y.toDecimal(b.amountIn,d),tradeAmountOut:y.toDecimal(b.amountOut,p),tradeFee:y.toDecimal(_,d)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}return t}getTwapExecutionTime(e){return e*6*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,n=Math.round(t);return Math.max(n,6)}};var Ht={};I(Ht,{TxBuilderFactory:()=>oe});import{Enum as Nt}from"polkadot-api";function qt(c){let e=[],t=c;for(;t&&typeof t=="object"&&"type"in t;)e.push(t.type),t=t.value;return e.join(".")}var ie=class extends F{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new E,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:Ge})}async dryRun(e,t){let n=Nt("Signed",e),s=Nt("system",n),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,t.decodedCall),a=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(a){let o=qt(a.value);throw new Error("Dry run execution error!",{cause:o})}return i}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Ce=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],r=await this.balanceClient.getBalance(this.beneficiary,s);return e>=r-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:e,amountOut:t,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=O.getFraction(e,this.slippagePct),a=s.assetIn,o=r.assetOut,l=e+i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:t,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:t,max_amount_in:l,route:C.build(n)}),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:n}=this.trade,s=n[0],r=n[n.length-1],i=O.getFraction(t,this.slippagePct),a=s.assetIn,o=r.assetOut,l=t-i,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:e,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:e,min_amount_out:l,route:C.build(n)}),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,n=t[0],s=t[t.length-1],r=O.getFraction(e,this.slippagePct),i=n.assetIn,a=s.assetOut,o=e-r,l=this.api.tx.Router.sell_all({asset_in:i,asset_out:a,min_amount_out:o,route:C.build(t)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as ot}from"polkadot-api";var Me=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:r,tradeRoute:i}=this.order,a=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ot("Sell",{asset_in:t,asset_out:n,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=O.getFraction(r,this.slippagePct),l=r-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ot("Sell",{asset_in:t,asset_out:n,amount_in:s,min_amount_out:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:n,tradeAmountIn:s,tradeAmountOut:r,tradePeriod:i,tradeRoute:a}=this.order,o=O.getFraction(s,this.slippagePct),l=s+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ot("Buy",{asset_in:t,asset_out:n,amount_out:r,max_amount_in:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var oe=class{client;evmClient;constructor(e,t){this.client=e,this.evmClient=t??new E}trade(e){return new Ce(this.client,this.evmClient).setTrade(e)}order(e){return new Me(this.client,this.evmClient).setOrder(e)}};async function uc(c,e){let t=new J(c),[n,s]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),r=e??new E,i=new ne(c).withAave().withOmnipool().withStableswap().withXyk(),a=new Y(r),o=new re(i),l=new ae(o,{blockTime:n,minBudgetInNative:s});return{api:{aave:a,router:o,scheduler:l},client:{asset:new $(c),balance:new q(c),evm:r},ctx:{pool:i},tx:new oe(c,r),destroy:()=>{i.destroy()}}}export{St as aave,ct as api,y as big,wt as client,yt as const,uc as createSdkContext,K as erc20,Ot as error,gt as evm,h as fmt,Re as h160,X as json,O as math,Dt as pool,Lt as sor,Ht as tx,xt as xc};
|
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
import { PolkadotClient } from 'polkadot-api';
|
|
2
2
|
import { type Observable } from 'rxjs';
|
|
3
3
|
import { Papi } from '../api';
|
|
4
|
-
import {
|
|
4
|
+
import { AssetAmount } from '../types';
|
|
5
5
|
export declare class BalanceClient extends Papi {
|
|
6
6
|
constructor(client: PolkadotClient);
|
|
7
|
-
getBalance(account: string, assetId: number): Promise<
|
|
8
|
-
getSystemBalance(account: string): Promise<
|
|
9
|
-
getTokenBalance(account: string, assetId: number): Promise<
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
subscribeErc20Balance(address: string, includeOnly?: number[]): Observable<AssetBalance[]>;
|
|
7
|
+
getBalance(account: string, assetId: number): Promise<bigint>;
|
|
8
|
+
getSystemBalance(account: string): Promise<bigint>;
|
|
9
|
+
getTokenBalance(account: string, assetId: number): Promise<bigint>;
|
|
10
|
+
getErc20Balance(account: string, assetId: number): Promise<bigint>;
|
|
11
|
+
subscribeBalance(address: string): Observable<AssetAmount[]>;
|
|
12
|
+
subscribeSystemBalance(address: string): Observable<AssetAmount>;
|
|
13
|
+
subscribeTokenBalance(address: string, assetId: number): Observable<AssetAmount>;
|
|
14
|
+
subscribeTokensBalance(address: string): Observable<AssetAmount[]>;
|
|
15
|
+
subscribeErc20Balance(address: string, includeOnly?: number[]): Observable<AssetAmount[]>;
|
|
17
16
|
private getTokenBalanceData;
|
|
18
17
|
}
|
package/build/types/consts.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export declare const RUNTIME_DECIMALS = 18;
|
|
2
|
+
export declare const PERMILL_DENOMINATOR = 1000000;
|
|
3
|
+
export declare const PERBILL_DENOMINATOR = 1000000000;
|
|
2
4
|
export declare const SYSTEM_ASSET_ID = 0;
|
|
3
5
|
export declare const SYSTEM_ASSET_DECIMALS = 12;
|
|
4
6
|
export declare const HYDRATION_PARACHAIN_ID = 2034;
|
|
@@ -9,5 +9,5 @@ export declare class StableMath {
|
|
|
9
9
|
static calculateLiquidityOutOneAsset(reserves: string, shares: string, assetOut: number, amplification: string, shareIssuance: string, withdrawFee: string, pegs: string): string;
|
|
10
10
|
static calculateShares(reserves: string, assets: string, amplification: string, shareIssuance: string, fee: string, pegs: string): string;
|
|
11
11
|
static calculateSpotPriceWithFee(poolId: string, reserves: string, amplification: string, assetIn: string, assetOut: string, shareIssuance: string, fee: string, pegs: string): string;
|
|
12
|
-
static recalculatePegs(currentPegs: string, targetPegs: string, currentBlock: string, maxPegUpdate: string, poolFee: string): string;
|
|
12
|
+
static recalculatePegs(currentPegs: string, targetPegs: string, currentBlock: string, maxPegUpdate: string, poolFee: string): [string, string[][]];
|
|
13
13
|
}
|
|
@@ -7,6 +7,10 @@ export declare class StableSwapClient extends PoolClient<StableSwapBase> {
|
|
|
7
7
|
protected loadPools(): Promise<StableSwapBase[]>;
|
|
8
8
|
private getPoolDelta;
|
|
9
9
|
private getPoolTokens;
|
|
10
|
+
private getPoolPegs;
|
|
11
|
+
private getDefaultPegs;
|
|
12
|
+
private getRecentPegs;
|
|
13
|
+
private getLatestPegs;
|
|
10
14
|
private getPoolAddress;
|
|
11
15
|
private getPoolLimits;
|
|
12
16
|
getPoolFees(pool: StableSwapBase): Promise<PoolFees>;
|
package/build/types/types.d.ts
CHANGED
|
@@ -3,9 +3,9 @@ export type Amount = {
|
|
|
3
3
|
amount: bigint;
|
|
4
4
|
decimals: number;
|
|
5
5
|
};
|
|
6
|
-
export interface
|
|
6
|
+
export interface AssetAmount {
|
|
7
7
|
id: number;
|
|
8
|
-
|
|
8
|
+
amount: bigint;
|
|
9
9
|
}
|
|
10
10
|
export interface AssetMetadata {
|
|
11
11
|
decimals: number;
|
|
@@ -34,13 +34,6 @@ export interface ExternalAsset extends AssetMetadata {
|
|
|
34
34
|
internalId: number;
|
|
35
35
|
isWhiteListed?: boolean;
|
|
36
36
|
}
|
|
37
|
-
export interface Balance {
|
|
38
|
-
free: bigint;
|
|
39
|
-
total: bigint;
|
|
40
|
-
transferable: bigint;
|
|
41
|
-
reserved: bigint;
|
|
42
|
-
frozen: bigint;
|
|
43
|
-
}
|
|
44
37
|
export type XcmV3Multilocation = {
|
|
45
38
|
parents: number;
|
|
46
39
|
interior: XcmV3Junctions;
|