@galacticcouncil/sdk-next 0.6.0-pr188-4957e24 → 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/consts.d.ts +2 -0
- package/build/types/factory.d.ts +1 -3
- package/build/types/index.d.ts +0 -1
- 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/package.json +1 -1
- package/build/types/staking/StakingApi.d.ts +0 -44
- package/build/types/staking/StakingClient.d.ts +0 -122
- package/build/types/staking/index.d.ts +0 -2
package/build/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var vn=Object.create;var Yt=Object.defineProperty;var On=Object.getOwnPropertyDescriptor;var An=Object.getOwnPropertyNames;var Bn=Object.getPrototypeOf,_n=Object.prototype.hasOwnProperty;var We=(c,t)=>()=>(c&&(t=c(c=0)),t);var I=(c,t)=>{for(var e in t)Yt(c,e,{get:t[e],enumerable:!0})},Xt=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of An(t))!_n.call(c,s)&&s!==e&&Yt(c,s,{get:()=>t[s],enumerable:!(n=On(t,s))||n.enumerable});return c},ot=(c,t,e)=>(Xt(c,t,"default"),e&&Xt(e,t,"default")),jt=(c,t,e)=>(e=c!=null?vn(Bn(c)):{},Xt(t||!c||!c.__esModule?Yt(e,"default",{value:c,enumerable:!0}):e,c)),Rn=c=>Xt(Yt({},"__esModule",{value:!0}),c);var St={};var je=We(()=>{ot(St,require("@polkadot-api/ws-provider/node"))});var wt={};var Ke=We(()=>{ot(wt,require("@polkadot-api/ws-provider/web"))});var rs={};I(rs,{aave:()=>we,api:()=>le,big:()=>b,client:()=>Ie,const:()=>he,createSdkContext:()=>is,erc20:()=>tt,error:()=>Oe,evm:()=>de,fmt:()=>h,h160:()=>vt,json:()=>Z,math:()=>A,pool:()=>Fe,sor:()=>Ne,staking:()=>He,tx:()=>Ue,xc:()=>xe});module.exports=Rn(rs);var le={};I(le,{Papi:()=>D,getWs:()=>kn});var Ye=require("@galacticcouncil/descriptors");function Xe(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var D=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(Ye.hydration)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Xe(n)&&console.log(t,...e)}};var ze=require("polkadot-api"),$e=require("polkadot-api/polkadot-sdk-compat"),kn=async c=>{let t=typeof c=="string"?c.split(","):c,s=(typeof window>"u"?(await Promise.resolve().then(()=>(je(),St))).getWsProvider:(await Promise.resolve().then(()=>(Ke(),wt))).getWsProvider)(t);return(0,ze.createClient)((0,$e.withPolkadotSdkCompat)(s))};var we={};I(we,{AAVE_GAS_LIMIT:()=>me,AAVE_LENDING_POOL_ADDRESS:()=>$t,AAVE_POOL_ABI:()=>ue,AAVE_POOL_DATA_PROVIDER:()=>zt,AAVE_POOL_DATA_PROVIDER_ABI:()=>Kt,AAVE_POOL_PROXY:()=>ce,AAVE_ROUNDING_THRESHOLD:()=>Ss,AAVE_UINT_256_MAX:()=>Fn,AaveClient:()=>It,AaveUtils:()=>et});var ue=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var Kt=[{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 ce="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",zt="0x112b087b60C1a166130d59266363C45F8aa99db0",$t="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",me=1000000n,Ss=5,Fn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var de={};I(de,{EvmClient:()=>L,evmMainnet:()=>pe});var Ze=require("viem"),Qe=["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"],Je=["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"],pe=(0,Ze.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:Qe,webSocket:Je},default:{http:Qe,webSocket:Je}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var U=require("viem");var L=class{chain;constructor(t){this.chain=t||pe}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,U.createPublicClient)({chain:this.chain,transport:(0,U.http)()})}getWsProvider(){return(0,U.createPublicClient)({chain:this.chain,transport:(0,U.webSocket)()})}getSigner(t){return(0,U.createWalletClient)({account:t,chain:this.chain,transport:(0,U.custom)(window.ethereum)})}};var It=class{evmClient;constructor(t){this.evmClient=t??new L}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Kt,address:zt,args:[$t],functionName:"getReservesData"})}async getUserReservesData(t){return await this.evmClient.getProvider().readContract({abi:Kt,address:zt,args:[$t,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.evmClient.getProvider().readContract({abi:ue,address:ce,args:[t],functionName:"getUserAccountData"})}};var b={};I(b,{asBigInt:()=>Cn,toBigInt:()=>Dn,toDecimal:()=>En});var J=jt(require("big.js"));J.default.NE=-18;function En(c,t,e=6,n){let s=(0,J.default)(c.toString()),a=(0,J.default)(10).pow(t);return s.div(a).round(e,n).toString()}function Dn(c,t){let e=(0,J.default)(10).pow(t),s=(0,J.default)(c).mul(e).toFixed(0,J.default.roundDown);return BigInt(s)}function Cn(c){return BigInt(c.round(0,J.default.roundDown).toFixed(0))}var tt={};I(tt,{ERC20:()=>ge});var ge=class{static fromAssetId(t){let e=Buffer.alloc(20,0);return e[15]=1,e.writeUInt32BE(t,16),"0x"+e.toString("hex")}static toAssetId(t){let e=Buffer.from(t.replace("0x",""),"hex");return e.length!==20||!this.isAssetAddress(t)?null:e.readUInt32BE(16)}static isAssetAddress(t){let e=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(e.subarray(0,16))}};var h={};I(h,{fromPermill:()=>qn,toDecimals:()=>Ln,toPct:()=>Mn});var tn=1e3;function Mn(c){let[t,e]=c;return t/e*100}function Ln(c){let[t,e]=c;return t/e}function qn(c){return[c/tn,tn]}var vt={};I(vt,{H160:()=>Te,isEvmAccount:()=>en,isEvmAddress:()=>nn,isSs58Address:()=>sn});var ut=require("polkadot-api"),Pe=require("@polkadot-api/utils"),z=require("buffer");var he={};I(he,{HUB_ASSET_ID:()=>ye,HYDRATION_OMNIPOOL_ADDRESS:()=>Hn,HYDRATION_PARACHAIN_ID:()=>Nn,HYDRATION_SS58_PREFIX:()=>N,RUNTIME_DECIMALS:()=>q,SYSTEM_ASSET_DECIMALS:()=>be,SYSTEM_ASSET_ID:()=>K,TRADEABLE_DEFAULT:()=>lt});var q=18,K=0,be=12,Nn=2034,N=63,Hn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",ye=1,lt=15;var fe="ETH\0";function en(c){if(!c)return!1;try{let t=(0,ut.AccountId)().enc(c),e=z.Buffer.from(fe);return z.Buffer.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function nn(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function sn(c){try{return(0,ut.AccountId)(63).enc(c),!0}catch{return!1}}var Te=class c{static toAccount=t=>{let e=z.Buffer.from(t.slice(2),"hex"),n=z.Buffer.from(fe),s=Uint8Array.from(z.Buffer.concat([n,e,z.Buffer.alloc(8)])),a=(0,Pe.toHex)(s);return(0,ut.AccountId)(63).dec(a)};static fromAccount=t=>{let e=(0,ut.AccountId)().enc(t),n=z.Buffer.from(fe),s=e.slice(n.length,-8);return"0x"+z.Buffer.from(s).toString("hex")};static fromSS58=t=>{let n=(0,ut.AccountId)().enc(t).slice(0,20);return(0,Pe.toHex)(n)};static fromAny=t=>{if(nn(t))return t;if(en(t))return c.fromAccount(t);if(sn(t))return c.fromSS58(t);throw new Error("Unknown address type")}};var Z={};I(Z,{findNestedKey:()=>Gn,findNestedObj:()=>Un,jsonFormatter:()=>Vn});var Gn=(c,t)=>{let e=[];return JSON.stringify(c,(n,s)=>(s&&s[t]&&e.push(s),s)),e[0]},Un=(c,t,e)=>{let n;return JSON.stringify(c,(s,a)=>(a&&a[t]===e&&(n=a),a)),n},Vn=(c,t)=>typeof t=="bigint"?t.toString():t;var A={};I(A,{calculateBuyFee:()=>jn,calculateDiffToAvg:()=>Wn,calculateDiffToRef:()=>Xn,calculateSellFee:()=>Yn,getFraction:()=>Kn});var W=jt(require("big.js"));function Wn(c,t){let e=(0,W.default)(c.toString()),n=(0,W.default)(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function Xn(c,t){if(t===0n)return 0;let e=(0,W.default)(c.toString()),n=(0,W.default)(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function Yn(c,t){let e=(0,W.default)(c.toString()),n=(0,W.default)(t.toString());return(0,W.default)(1).minus(n.div(e)).mul(100).round(2).toNumber()}function jn(c,t){let e=(0,W.default)(c.toString());return(0,W.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function Kn(c,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),s=BigInt(t*n);return c*s/BigInt(100*n)}var xe={};I(xe,{convertToId:()=>zn});var an=require("buffer");function zn(c){let e=an.Buffer.from(c.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var{ERC20:Qt}=tt,{H160:Se}=vt,$n=1.01,Qn=99999,Jn=10n**27n,Zn=10n**18n,et=class{client;constructor(t){let e=t??new L;this.client=new It(e)}async getSummary(t){let e=Se.fromAny(t),[n,s,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e)]),[r]=n,[i,o]=s,[l,u,d,m,p,g]=a,P=b.toDecimal(g,18),y=[];for(let S of i){let f=S.underlyingAsset.toLowerCase(),T=r.find(({underlyingAsset:oe})=>oe.toLowerCase()===f);if(!T)throw new Error("Missing pool reserve for "+f);let O=S.scaledATokenBalance,k=T.liquidityIndex,C=T.priceInMarketReferenceCurrency,M=O*k/Jn,Vt=Number(o===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,Wt=T.usageAsCollateralEnabled&&S.usageAsCollateralEnabledOnUser&&S.scaledATokenBalance>0n,re=Qt.toAssetId(f);y.push({aTokenBalance:M,decimals:Number(T.decimals),isCollateral:Wt,priceInRef:C,reserveId:re,reserveAsset:f,reserveLiquidationThreshold:Vt})}return{healthFactor:Number(P),totalCollateral:l,totalDebt:u,reserves:y}}async hasBorrowPositions(t){let e=Se.fromAny(t),n=await this.client.getUserAccountData(e),[s,a]=n;return a>0n}async getHealthFactor(t){let e=Se.fromAny(t),n=await this.client.getUserAccountData(e),[s,a,r,i,o,l]=n,u=b.toDecimal(l,18);return Number(u)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:s,totalDebt:a,reserves:r}=await this.getSummary(t),i=Qt.fromAssetId(e),o=r.find(y=>y.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:u,priceInRef:d,reserveLiquidationThreshold:m}=o,p=b.toBigInt(n,l),g=u?p*d/10n**BigInt(l):0n,P=s-g;return P<=0n?0:this.calculateHealthFactor(P,m,a)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:s,totalDebt:a,reserves:r}=await this.getSummary(t),i=Qt.fromAssetId(e),o=r.find(P=>P.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:d}=o,p=b.toBigInt(n,l)*u/10n**BigInt(l),g=s+p;return g<=0n?0:this.calculateHealthFactor(g,d,a)}async getMaxWithdraw(t,e){let{totalCollateral:n,totalDebt:s,reserves:a}=await this.getSummary(t),r=Qt.fromAssetId(e),i=a.find(o=>o.reserveAsset===r);if(!i)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(i,n,s)}async getMaxWithdrawAll(t){let{totalCollateral:e,totalDebt:n,reserves:s}=await this.getSummary(t),a={};for(let r of s){let i=this.calculateWithdrawMax(r,e,n);r.reserveId&&(a[r.reserveId]=i)}return a}calculateHealthFactor(t,e,n){if(n===0n)return Qn;let s=10n**6n,a=b.toBigInt(e,18),r=t*a*s,i=n*Zn,o=r/i;return Number(o)/1e6}calculateRequiredCollateral(t,e,n){let s=b.toBigInt(t,18),a=b.toBigInt(e,18);return(s*n+a-1n)/a}calculateWithdrawMax(t,e,n){let{aTokenBalance:s,decimals:a,priceInRef:r,reserveLiquidationThreshold:i}=t,o=this.calculateRequiredCollateral($n,i,n),l=e-o;if(l<=0n)return{amount:0n,decimals:a};let u=l*10n**BigInt(a)/r;return{amount:s<u?s:u,decimals:a}}};var Ie={};I(Ie,{AssetClient:()=>ct,BalanceClient:()=>X,ChainParams:()=>mt});var ct=class extends D{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[a]=n;return[a,s]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[a]=n;return[a,s]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:s}=n;return this.SUPPORTED_TYPES.includes(s.type)}).map(({keyArgs:n,value:s})=>{let[a]=n;return[a,s]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[a]=n;return[a,s]}))}async mapToken(t,e,n,s){let{name:a,asset_type:r,is_sufficient:i,existential_deposit:o}=e,{symbol:l,decimals:u}=n.get(t)??{};return{id:t,name:a?.asText(),symbol:l,decimals:u,icon:l,type:r.type,isSufficient:i,location:s,existentialDeposit:o}}async mapBond(t,e,n,s){let[a,r]=s,{asset_type:i,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:d}=await this.mapToken(a,e,n),m=Number(r),p=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",p.format(m)].join(" ");return{id:t,name:g,symbol:u+"b",decimals:d,icon:u,type:i.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:a,maturity:m}}async mapShares(t,e,n,s){let{assets:a}=s,{name:r,symbol:i,asset_type:o,is_sufficient:l,existential_deposit:u}=e,d=await Promise.all(a.map(async g=>{let{symbol:P}=await this.mapToken(g,e,n);return[g,P]})),m=Object.fromEntries(d),p=Object.values(m);return{id:t,name:p.join(", "),symbol:i?.asText()||r?.asText(),decimals:18,icon:p.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:m}}async mapExternal(t,e,n,s){let a=await this.mapToken(t,e,new Map,s),r=n?.find(i=>i.internalId===a.id);return r?{...a,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.isWhiteListed}:a}parseMetadata(t){return new Map(Array.from(t,([e,n])=>[e,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(t,e){let[n,s,a,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),i=this.parseMetadata(n),o=[];for(let[l,u]of Array.from(n)){let d=s.get(l),{asset_type:m}=u,p;switch(m.type){case"Bond":let g=r.get(l);p=await this.mapBond(l,u,i,g);break;case"StableSwap":let P=a.get(l);p=await this.mapShares(l,u,i,P);break;case"External":p=await this.mapExternal(l,u,e,d);break;default:p=await this.mapToken(l,u,i,d)}o.push(p)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var w=require("rxjs");var X=class extends D{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:{free:n,frozen:s}}=await e.getValue(t);return n-s}async getTokenBalance(t,e){let n=this.api.query.Tokens.Accounts,{free:s,frozen:a}=await n.getValue(t,e);return s-a}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),s=this.subscribeErc20Balance(t);return(0,w.combineLatest)([e,n,s]).pipe((0,w.debounceTime)(250),(0,w.map)(a=>a.flat()),(0,w.startWith)([]),(0,w.bufferCount)(2,1),(0,w.map)(([a,r],i)=>{if(i===0)return r;let o=a.reduce((u,d)=>(u.set(d.id,d.amount),u),new Map);return r.filter(u=>u.amount!==o.get(u.id))}))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe((0,w.map)(n=>{let{free:s,frozen:a}=n.data;return{id:0,amount:s-a}}))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe((0,w.map)(s=>{let{free:a,frozen:r}=s;return{id:e,amount:a-r}}))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe((0,w.distinctUntilChanged)((n,s)=>!s.deltas),(0,w.map)(({deltas:n})=>{let s=[];return n?.deleted.forEach(a=>{let[r,i]=a.args;s.push({id:i,amount:0n})}),n?.upserted.forEach(a=>{let[r,i]=a.args,{free:o,frozen:l}=a.value;s.push({id:i,amount:o-l})}),s}))}subscribeErc20Balance(t,e){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:u}=l;return u.type==="Erc20"}).map(({keyArgs:l})=>{let[u]=l;return u}),r=async()=>{let o=e||await a(),l=async()=>{let m=(await Promise.all(o.map(async p=>{let g=await this.getTokenBalanceData(t,p);return[p,g]}))).map(([p,g])=>({id:p,amount:g}));n.next(m)};await l();let u=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>u.unsubscribe()},i;return r().then(o=>i=o),s.pipe((0,w.finalize)(()=>i?.()),(0,w.pairwise)(),(0,w.map)(([o,l],u)=>{if(u===0)return l;let d=o.reduce((p,g)=>(p.set(g.id,g.amount),p),new Map);return l.filter(p=>p.amount!==d.get(p.id))}),(0,w.distinctUntilChanged)((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let{free:n,frozen:s}=await this.api.apis.CurrenciesApi.account(e,t);return n-s}};var mt=class extends D{_minOrderBudget;_blockTime;constructor(t){super(t)}async getBlockTime(){if(this._blockTime===void 0){let t=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(t)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var Oe={};I(Oe,{AssetNotFound:()=>ve,PoolNotFound:()=>Ot,RouteNotFound:()=>pt});var ve=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},Ot=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},pt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Fe={};I(Fe,{PoolContextProvider:()=>yt,PoolError:()=>nt,PoolFactory:()=>bt,PoolType:()=>F,aave:()=>ke,lbp:()=>Ae,omni:()=>Be,stable:()=>_e,xyk:()=>Re});var Ae={};I(Ae,{LbpMath:()=>V,LbpPool:()=>At,LbpPoolClient:()=>Bt});var Y=require("@galacticcouncil/math-lbp"),V=class{static getSpotPrice(t,e,n,s,a){return(0,Y.get_spot_price)(t,e,n,s,a)}static calculateInGivenOut(t,e,n,s,a){return(0,Y.calculate_in_given_out)(t,e,n,s,a)}static calculateOutGivenIn(t,e,n,s,a){return(0,Y.calculate_out_given_in)(t,e,n,s,a)}static calculateLinearWeights(t,e,n,s,a){return(0,Y.calculate_linear_weights)(t,e,n,s,a)}static calculatePoolTradeFee(t,e,n){return(0,Y.calculate_pool_trade_fee)(t,e,n)}};var F=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a))(F||{}),nt=(a=>(a.InsufficientTradingAmount="InsufficientTradingAmount",a.MaxInRatioExceeded="MaxInRatioExceeded",a.MaxOutRatioExceeded="MaxOutRatioExceeded",a.TradeNotAllowed="TradeNotAllowed",a.UnknownError="UnknownError",a))(nt||{});var At=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,n,s,a,r,i){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a,this.fee=r,this.repayFeeApply=i}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),a=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,weightIn:s.weight,weightOut:a.weight}}validateAndBuy(t,e,n){let s=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let r=t.balanceOut/this.maxOutRatio;if(e>r&&a.push("MaxOutRatioExceeded"),s===t.assetOut){let i=this.calculateTradeFee(e,n),o=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+i,u=this.calculateInGivenOut(t,l),d=t.balanceIn/this.maxInRatio;return u>d&&a.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:a}}else{let i=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return i>o&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:a}}}validateAndSell(t,e,n){let s=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let r=t.balanceIn/this.maxInRatio;if(e>r&&a.push("MaxInRatioExceeded"),s===t.assetIn){let i=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return i>o&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:a}}else{let i=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(i,n),l=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),u=i-o,d=t.balanceOut/this.maxOutRatio;return u>d&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:u,feePct:l,errors:a}}}calculateInGivenOut(t,e){let n=V.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=V.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=V.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=V.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let n=V.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(n)}};var on=require("polkadot-api"),st=require("rxjs");var rn=(c,t=new Map)=>e=>{let n;return t.has(e)?t.get(e):(t.set(e,n=c(e)),n)};var v=require("rxjs");var H=class extends X{override=[];mem=0;memPools=rn(t=>(this.log(this.getPoolType(),"mem pools",t,"\u2705"),this.loadPools()));constructor(t){super(t)}async withOverride(t){this.override=t||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let t=(0,v.from)(this.getPoolsMem()).pipe((0,v.switchMap)(e=>this.subscribe(e)),(0,v.combineLatestAll)());return(0,v.firstValueFrom)(t)}getSubscriber(){return(0,v.from)(this.getPoolsMem()).pipe((0,v.switchMap)(t=>this.subscribe(t)),(0,v.mergeAll)())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>(0,v.combineLatest)([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe((0,v.debounceTime)(250),(0,v.map)(([n,s])=>this.updatePool(n,s))))}subscribePoolBalance(t){if(t.type==="Aave")return(0,v.of)([]);let e=[this.subscribeTokensBalance(t.address)];if(this.hasSystemAsset(t)){let n=this.subscribeSystemBalance(t.address);e.push(n)}if(this.hasErc20Asset(t)){let n=t.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),s=this.subscribeErc20Balance(t.address,n);e.push(s)}return(0,v.combineLatest)(e).pipe((0,v.map)(n=>n.map(s=>Array.isArray(s)?s:[s]).flat()))}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({id:e,decimals:n,balance:s})=>{let a=this.override.find(i=>i.id===e),r=!!n||!!a?.decimals;return s>0n&&r})}updatePool=(t,e)=>{let n=t.tokens.map(s=>{let a=e.find(i=>i.id===s.id),r=this.override.find(i=>i.id===s.id);return a?{...s,balance:a.amount,decimals:s.decimals||r?.decimals}:{...s,decimals:s.decimals||r?.decimals}});return{...t,tokens:n}}};var Bt=class extends H{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),s=e?.relay_parent_number||0,a=t.filter(({value:r})=>e&&this.isActivePool(r,s)).map(async({keyArgs:r,value:i})=>{let[o]=r,l=o.toString(),u=await this.getPoolDelta(l,i,s);return{address:l,type:"LBP",fee:i.fee,...u,...n}});return Promise.all(a)}async getPoolDelta(t,e,n){let{start:s,end:a,assets:r,initial_weight:i,final_weight:o,repay_target:l,fee_collector:u}=e,d=V.calculateLinearWeights(s?s.toString():"0",a?a.toString():"0",i.toString(),o.toString(),n.toString()),[m,p]=r,g=BigInt(d),P=this.MAX_FINAL_WEIGHT-BigInt(g),[y,S,f,T,O]=await Promise.all([this.isRepayFeeApplied(m,l,u.toString()),this.getBalance(t,m),this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(t,p),this.api.query.AssetRegistry.Assets.getValue(p)]);return{repayFeeApply:y,tokens:[{id:m,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:S,weight:g,type:f?.asset_type.type},{id:p,decimals:O?.decimals,existentialDeposit:O?.existential_deposit,balance:T,weight:P,type:O?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:s}=t;return n&&s?e>=n&&e<s:!1}async isRepayFeeApplied(t,e,n){if(e===0n)return!1;try{return await this.getBalance(n,t)<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(t){return{repayFee:await this.getRepayFee(),exchangeFee:t.fee}}getPoolType(){return"LBP"}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(on.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(t.address);return n?e.watchValue("best").pipe((0,st.switchMap)(s=>s?this.getPoolDelta(t.address,n,s.relay_parent_number):(0,st.of)(t)),(0,st.map)(s=>Object.assign({},t,s))):(0,st.of)(t)}};var Be={};I(Be,{OmniMath:()=>B,OmniPool:()=>_t,OmniPoolClient:()=>kt});var x=require("@galacticcouncil/math-omnipool"),at=jt(require("big.js")),B=class{static calculateSpotPrice(t,e,n,s){return(0,x.calculate_spot_price)(t,e,n,s)}static calculateLrnaSpotPrice(t,e){return(0,x.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,n,s,a,r,i,o,l){return(0,x.calculate_in_given_out)(t,e,n,s,a,r,i,o,l)}static calculateLrnaInGivenOut(t,e,n,s,a){return(0,x.calculate_lrna_in_given_out)(t,e,n,s,a)}static calculateOutGivenIn(t,e,n,s,a,r,i,o,l){return(0,x.calculate_out_given_in)(t,e,n,s,a,r,i,o,l)}static calculateOutGivenLrnaIn(t,e,n,s,a){return(0,x.calculate_out_given_lrna_in)(t,e,n,s,a)}static calculateShares(t,e,n,s){return(0,x.calculate_shares)(t,e,n,s)}static calculateLiquidityOut(t,e,n,s,a,r,i,o){return(0,x.calculate_liquidity_out)(t,e,n,s,a,r,i,o)}static calculateLiquidityLRNAOut(t,e,n,s,a,r,i,o){return(0,x.calculate_liquidity_lrna_out)(t,e,n,s,a,r,i,o)}static calculateCapDifference(t,e,n,s){let a=(0,at.default)(e),r=(0,at.default)(t),i=(0,at.default)(s),o=(0,at.default)(n),l=(0,at.default)(10).pow(18),u=o.div(l);if(a.div(i).lt(u)){let m=u.times(i).minus(a).times(r),p=a.times((0,at.default)(1).minus(u));return m.div(p).toFixed(0)}else return"0"}static verifyAssetCap(t,e,n,s){return(0,x.verify_asset_cap)(t,e,n,s)}static calculateLimitHubIn(t,e,n,s){return(0,x.calculate_liquidity_hub_in)(t,e,n,s)}static isSellAllowed(t){return(0,x.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,x.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,x.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,x.is_remove_liquidity_allowed)(t)}};var _t=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,n,s,a,r){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a,this.hubAssetId=r}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),a=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,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(t,e,n){let s=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,n),r=s===0n?0:A.calculateDiffToRef(a,s),i=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);(!o||!l)&&i.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&i.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&i.push("MaxOutRatioExceeded");let d=t.balanceIn/this.maxInRatio;return a>d&&i.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:r,errors:i}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,n),r=A.calculateDiffToRef(s,a),i=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);(!o||!l)&&i.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&i.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&i.push("MaxInRatioExceeded");let d=t.balanceOut/this.maxOutRatio;return a>d&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:r,errors:i}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let s=B.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateLrnaInGivenOut(t,e,n){let s=B.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let s=B.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateOutGivenLrnaIn(t,e,n){let s=B.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=B.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceLrnaInGivenOut(t){let e=B.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=B.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}spotPriceOutGivenLrnaIn(t){let e=B.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};var Jt=require("polkadot-api"),ln=require("@polkadot-api/utils"),Rt=require("rxjs");var kt=class extends H{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,s,a,r,i]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.getBalance(e,t),this.getPoolLimits()]),o=n.map(async({keyArgs:u,value:d})=>{let[m]=u,{hub_reserve:p,shares:g,tradable:P,cap:y,protocol_shares:S}=d,[f,T]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,m)]);return{id:m,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:T,cap:y,hubReserves:p,protocolShares:S,shares:g,tradeable:P,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:r,tradeable:s,type:a?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...i}]}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=(0,ln.toHex)(e);return(0,Jt.AccountId)(63).dec(n)}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(t,e){let[n,s,a]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),r=n.min_fee+s.min_fee,i=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(r),max:h.fromPermill(i)}}else return{assetFee:h.fromPermill(n.min_fee),protocolFee:h.fromPermill(s.min_fee),min:h.fromPermill(r),max:h.fromPermill(i)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Jt.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,Rt.distinctUntilChanged)((n,s)=>!s.deltas),(0,Rt.map)(({entries:n})=>n.map(s=>{let[a]=s.args,{hub_reserve:r,shares:i,tradable:o,cap:l,protocol_shares:u}=s.value,d=t.tokens.findIndex(p=>p.id===a);return{...t.tokens[d],cap:l,hubReserves:r,protocolShares:u,shares:i,tradeable:o}})),(0,Rt.map)(n=>{let s=t.tokens.find(a=>a.id===1);return{...t,tokens:[...n,s]}}))}};var _e={};I(_e,{StableMath:()=>E,StableSwap:()=>Ft,StableSwapClient:()=>Et});var _=require("@galacticcouncil/math-stableswap"),E=class{static getPoolAddress(t){return(0,_.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,s,a){return(0,_.calculate_amplification)(t,e,n,s,a)}static calculateInGivenOut(t,e,n,s,a,r,i){return(0,_.calculate_in_given_out)(t,e,n,s,a,r,i)}static calculateAddOneAsset(t,e,n,s,a,r,i){return(0,_.calculate_add_one_asset)(t,e,n,s,a,r,i)}static calculateSharesForAmount(t,e,n,s,a,r,i){return(0,_.calculate_shares_for_amount)(t,e,n,s,a,r,i)}static calculateOutGivenIn(t,e,n,s,a,r,i){return(0,_.calculate_out_given_in)(t,e,n,s,a,r,i)}static calculateLiquidityOutOneAsset(t,e,n,s,a,r,i){return(0,_.calculate_liquidity_out_one_asset)(t,e,n,s,a,r,i)}static calculateShares(t,e,n,s,a,r){return(0,_.calculate_shares)(t,e,n,s,a,r)}static calculateSpotPriceWithFee(t,e,n,s,a,r,i,o){return(0,_.calculate_spot_price_with_fee)(t,e,n,s,a,r,i,o)}static recalculatePegs(t,e,n,s,a){return(0,_.recalculate_peg)(t,e,n,s,a)}};var Ft=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.id,t.fee,t.totalIssuance)}constructor(t,e,n,s,a,r,i,o,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a,this.amplification=r,this.id=i,this.fee=o,this.totalIssuance=l}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),a=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:a.tradeable,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,n),r=h.toPct(n.fee),i=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);return(!o||!l)&&i.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&i.push("InsufficientTradingAmount"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:r,errors:i}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,n),r=h.toPct(n.fee),i=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);return(!o||!l)&&i.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&i.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:r,errors:i}}calculateIn(t,e,n){let s=E.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateAddOneAsset(t,e,n){let s=E.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.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(t,e,n){let s=E.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.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(t,e,n){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,n):t.assetIn==this.id?this.calculateSharesForAmount(t,e,n):this.calculateIn(t,e,n)}spotPriceInGivenOut(t){let e=E.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetOut==this.id)return BigInt(e);if(t.assetIn==this.id){let s=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let s=E.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateWithdrawOneAsset(t,e,n){let s=E.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.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(t,e,n){let s=E.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e,n){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,n):t.assetOut==this.id?this.calculateShares(t,e,n):this.calculateOut(t,e,n)}spotPriceOutGivenIn(t){let e=E.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetIn==this.id)return BigInt(e);if(t.assetOut==this.id){let s=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}getPegs(){let t=E.defaultPegs(this.tokens.length-1);return JSON.stringify(t)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:n,decimals:s})=>({asset_id:e,amount:n,decimals:s}));return JSON.stringify(t,Z.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],Z.jsonFormatter)}};var Zt=require("polkadot-api"),un=require("@polkadot-api/utils"),cn=require("@noble/hashes/blake2b"),dt=require("rxjs");var ts=340282366920938463463374607431768211455n,Et=class extends H{poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),s=t.map(async({keyArgs:a,value:r})=>{let[i]=a,o=this.getPoolAddress(i),[l,u]=await Promise.all([this.getPoolDelta(i,r,e),this.getPoolTokens(i,r)]);return this.poolsData.set(o,r),{address:o,id:i,type:"Stableswap",fee:h.fromPermill(r.fee),tokens:u,...l,...n}});return Promise.all(s)}async getPoolDelta(t,e,n){let{initial_amplification:s,final_amplification:a,initial_block:r,final_block:i}=e,o=E.calculateAmplification(s.toString(),a.toString(),r.toString(),i.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(t);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),s=e.assets.map(async i=>{let[o,l,u]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,i),this.api.query.AssetRegistry.Assets.getValue(i),this.getBalance(n,i)]);return{id:i,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:u,tradeable:o,type:l?.asset_type.type}}),a=await Promise.all(s),r=await this.api.query.AssetRegistry.Assets.getValue(t);return a.push({id:t,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:ts,tradeable:15,type:r?.asset_type.type}),a}getPoolAddress(t){let e=E.getPoolAddress(t),n=(0,cn.blake2b)(e,{dkLen:32}),s=(0,un.toHex)(n);return(0,Zt.AccountId)(63).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(t){return{fee:t.fee}}getPoolType(){return"Stableswap"}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(Zt.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.System.Number,n=this.poolsData.get(t.address);return!n||!t.id?(0,dt.of)(t):e.watchValue("best").pipe((0,dt.switchMap)(s=>this.getPoolDelta(t.id,n,s)),(0,dt.map)(s=>Object.assign({},t,s)))}};var Re={};I(Re,{XykMath:()=>$,XykPool:()=>Dt,XykPoolClient:()=>Ct});var R=require("@galacticcouncil/math-xyk"),$=class{static getSpotPrice(t,e,n){return(0,R.get_spot_price)(t,e,n)}static calculateInGivenOut(t,e,n){return(0,R.calculate_in_given_out)(t,e,n)}static calculateOutGivenIn(t,e,n){return(0,R.calculate_out_given_in)(t,e,n)}static calculatePoolTradeFee(t,e,n){return(0,R.calculate_pool_trade_fee)(t,e,n)}static calculateLiquidityIn(t,e,n){return(0,R.calculate_liquidity_in)(t,e,n)}static calculateSpotPrice(t,e){return(0,R.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,n,s){return(0,R.calculate_spot_price_with_fee)(t,e,n,s)}static calculateShares(t,e,n){return(0,R.calculate_shares)(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,s){return(0,R.calculate_liquidity_out_asset_a)(t,e,n,s)}static calculateLiquidityOutAssetB(t,e,n,s){return(0,R.calculate_liquidity_out_asset_b)(t,e,n,s)}};var Dt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,a){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),a=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:s.decimals,decimalsOut:a.decimals,balanceIn:s.balance,balanceOut:a.balance,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),a=this.calculateTradeFee(s,n),r=h.toPct(n.exchangeFee),i=s+a,o=[];(e<this.minTradingLimit||s<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return i>u&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:e,feePct:r,errors:o}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),a=this.calculateTradeFee(s,n),r=h.toPct(n.exchangeFee),i=s-a,o=[];(e<this.minTradingLimit||s<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return i>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:i,feePct:r,errors:o}}calculateInGivenOut(t,e){let n=$.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=$.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=$.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=$.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=$.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};var mn=require("polkadot-api"),pn=require("rxjs");var Ct=class extends H{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,n]=await Promise.all([t.getEntries(),this.getPoolLimits()]),s=e.map(async({keyArgs:a,value:r})=>{let[i]=a,[o,l]=r,[u,d,m,p]=await Promise.all([this.getBalance(i,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(i,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:i,type:"XYK",tokens:[{id:o,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:u,type:d?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:m,type:p?.asset_type.type}],...n}});return Promise.all(s)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(mn.CompatibilityLevel.BackwardsCompatible,e)}subscribePoolChange(t){return(0,pn.of)(t)}};var ke={};I(ke,{AavePool:()=>Mt,AavePoolClient:()=>Lt});var Mt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,a){this.type="Aave",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),a=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),a=[];return e>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:a}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),a=[];return s>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:a}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){let e=Math.pow(10,t.decimalsOut);return BigInt(e)}spotPriceOutGivenIn(t){let e=Math.pow(10,t.decimalsIn);return BigInt(e)}calculateTradeFee(t,e){return 0n}};var gn=require("polkadot-api"),bn=require("@polkadot-api/utils"),gt=require("rxjs"),yn=require("viem");var dn=[{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:es}=tt,ns=["Supply","Withdraw","Repay","Borrow"],Lt=class extends H{async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:s,liqudity_in:a,liqudity_out:r})=>{let[i,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:i?.decimals,existentialDeposit:i?.existential_deposit,balance:a,location:o,type:i?.asset_type.type},{id:s,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:r,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:s,liqudity_out:a}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id);return t.tokens.map(r=>{let i=r.id===e.id?s:a;return{...r,balance:i}})}getPoolId(t,e){let n=t+"/"+e,s=new TextEncoder().encode(n.padEnd(32,"\0")),a=(0,bn.toHex)(s);return(0,gn.AccountId)(63).dec(a)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(t,e){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(t){let[e,n]=t.tokens,s=this.getReserveH160Id(e),a=this.api.event.Router.Executed.watch(({asset_in:i,asset_out:o})=>i===n.id||o===n.id),r=this.api.event.EVM.Log.watch(({log:i})=>{let{topics:o,data:l}=i,u=o.map(g=>g.asHex()),d=l.asHex(),{eventName:m,args:p}=(0,yn.decodeEventLog)({abi:dn,topics:u,data:d});return ns.includes(m)&&p.reserve.toLowerCase()===s.toLowerCase()});return(0,gt.merge)([a,r]).pipe((0,gt.switchMap)(()=>this.getPoolDelta(t)),(0,gt.map)(i=>({...t,tokens:[...i]})))}getReserveH160Id(t){return t.type==="Erc20"?Z.findNestedKey(t.location,"AccountKey20").AccountKey20.key:es.fromAssetId(t.id)}};var bt=class{static get(t){switch(t.type){case"Aave":return Mt.fromPool(t);case"XYK":return Dt.fromPool(t);case"Omnipool":return _t.fromPool(t);case"LBP":return At.fromPool(t);case"Stableswap":return Ft.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var j=require("rxjs");var yt=class extends D{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=j.Subscription.EMPTY;omniSub=j.Subscription.EMPTY;stableSub=j.Subscription.EMPTY;xykSub=j.Subscription.EMPTY;aaveSub=j.Subscription.EMPTY;isReady=!1;isDestroyed=new j.Subject;constructor(t){super(t),this.lbpClient=new Bt(t),this.omniClient=new kt(t),this.stableClient=new Et(t),this.xykClient=new Ct(t),this.aaveClient=new Lt(t),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(t){return t.getSubscriber().pipe((0,j.takeUntil)(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let n=this.clients.find(s=>s.getPoolType()===t.type);if(n)return n.getPoolFees(t,e);throw new Ot(t.type)}};var Ne={};I(Ne,{DEFAULT_BLOCK_TIME:()=>hn,DEFAULT_MIN_BUDGET:()=>Ce,ORDER_MIN_BLOCK_PERIOD:()=>Pn,Router:()=>ht,TWAP_BLOCK_PERIOD:()=>Ht,TWAP_MAX_DURATION:()=>Le,TWAP_MAX_PRICE_IMPACT:()=>Me,TWAP_TX_MULTIPLIER:()=>Uo,TradeOrderError:()=>De,TradeOrderType:()=>ne,TradeRouteBuilder:()=>G,TradeRouter:()=>Pt,TradeScheduler:()=>ft,TradeType:()=>ee});var te=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var ss=5,qt=class{isNotVisited(t,e){let n=!0;return e.forEach(s=>{(s[0]===t[0]||s[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let s=[],a=new te,r=[];for(r.push([e,""]),a.enqueue(r);a.size()>0;){let i=a.dequeue();if(i==null||i.length>ss)return s;let o=i[i.length-1];(n===null||o[0]===n)&&s.push(i),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,i)){let d=[...i];d.push(u),a.enqueue(d)}})}return s}buildAndPopulateGraph(t,e){let n=new Map;for(let s of t)n.set(parseInt(s),[]);for(let[s,a,r]of e)n.get(a)?.push([r,s]);return n}};function Ee(c){let t={};for(let e of c){let n=e.tokens.length;for(let s=0;s<n;s++){t[e.tokens[s].id]||(t[e.tokens[s].id]=[]);for(let a=0;a<n;a++){if(s==a)continue;let r=[e.address,e.tokens[s].id,e.tokens[a].id];t[e.tokens[s].id].push(r)}}}return t}var Nt=class{getProposals(t,e,n){let s=Ee(n),a=Object.keys(s),r=a.map(u=>s[u]).flat(),i=new qt,o=i.buildAndPopulateGraph(a,r),l=i.findPaths(o,t,e);return this.parsePaths(l)}parsePaths(t){let e=[];for(let n of t){let s=[];for(let a=0;a<n.length;a++){let r=n[a],i=n[a+1];if(i==null)break;s.push(this.toEdge(r,i))}e.push(s)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var ht=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(t,e){this.ctx=t,this.routeSuggester=new Nt,this.routerOptions={...this.defaultRouterOptions,...e}}async getPools(){let t=await this.ctx.getPools(),e=this.routerOptions.useOnly;return e.length===0?t:t.filter(n=>e.includes(n.type))}async getRoutes(t,e){let n=await this.getPools();return this.validateInput(t,e,n),this.getPaths(t,e,n)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}validateInput(t,e,n){if(n.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let s=this.getAssets(n);if(!s.has(t))throw new Error(t+" is not supported asset");if(!s.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(s=>s.id)).flat().sort((n,s)=>n>s?1:-1);return new Set(e)}getPaths(t,e,n){let s=this.toPoolsMap(n);return this.routeSuggester.getProposals(t,e,n).filter(r=>this.validPath(r,s)).map(r=>this.toHops(r,s))}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,s)=>n&&s)}validEdge([t,e,n],s){return s.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,bt.get(e)]))}toHops(t,e){return t.map(([n,s,a])=>{let r=e.get(n);return{poolAddress:n,poolId:r?.id,pool:r?.type,assetIn:s,assetOut:a}})}};var ee=(e=>(e.Buy="Buy",e.Sell="Sell",e))(ee||{}),ne=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(ne||{}),De=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(De||{});var Pt=class extends ht{isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,s)=>{let a=n[n.length-1].amountOut,r=s[s.length-1].amountOut;return a>r?-1:1});return e.find(n=>n.every(s=>s.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(n=>n.tradeFeeRange).length>0){let n=t.map(a=>a.tradeFeeRange?.[0]??a.tradeFeePct).reduce((a,r)=>a+r),s=t.map(a=>a.tradeFeeRange?.[1]??a.tradeFeePct).reduce((a,r)=>a+r);return[n,s]}}getPoolFeeRange(t){let e=t.min?h.toPct(t.min):void 0,n=t.max?h.toPct(t.max):void 0;if(e&&n)return[e,n]}async getBestSell(t,e,n){return this.getSell(t,e,n)}async getSellSpot(t){let e=t[t.length-1];if(t.length===1)return e.spotPrice;let n=t.map(i=>i.assetOutDecimals).reduce((i,o)=>i+o),s=t.map(i=>i.spotPrice).reduce((i,o)=>i*o),a=n-e.assetOutDecimals,r=Math.pow(10,a);return s/BigInt(r)}async getSell(t,e,n,s){let a=await super.getPools(),r=super.validateInput(t,e,a),i=super.getPaths(t,e,a);if(i.length===0)throw new pt(t,e);let o;if(s)o=await this.toSellSwaps(n,s,r);else{let k=await Promise.all(i.map(C=>this.toSellSwaps(n,C,r)));o=this.findBestSellRoute(k)}let l=o[0],u=o[o.length-1],d=this.isDirectTrade(o),m=await this.getSellSpot(o),p=u.amountOut,g=d?u.calculatedOut:this.calculateDelta0Y(l.amountIn,o,r),P=g-p,y=this.getRouteFeeRange(o),S=d?u.tradeFeePct:A.calculateSellFee(g,p),f=Math.pow(10,l.assetInDecimals),T=l.amountIn*m/BigInt(f),O=A.calculateDiffToRef(g,T);return{type:"Sell",amountIn:l.amountIn,amountOut:u.amountOut,spotPrice:m,tradeFee:P,tradeFeePct:S,tradeFeeRange:y,priceImpactPct:O,swaps:o,toHuman(){return{type:"Sell",amountIn:b.toDecimal(l.amountIn,l.assetInDecimals),amountOut:b.toDecimal(u.amountOut,u.assetOutDecimals),spotPrice:b.toDecimal(m,u.assetOutDecimals),tradeFee:b.toDecimal(P,u.assetOutDecimals),tradeFeePct:S,tradeFeeRange:y,priceImpactPct:O,swaps:o.map(k=>k.toHuman())}}}}calculateDelta0Y(t,e,n){let s=[];for(let a=0;a<e.length;a++){let r=e[a],i=n.get(r.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(r.assetIn,r.assetOut),l;a>0?l=s[a-1]:l=t;let u=i.calculateOutGivenIn(o,l);s.push(u)}return s[s.length-1]}async toSellSwaps(t,e,n){let s=[];for(let a=0;a<e.length;a++){let r=e[a],i=n.get(r.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(r.assetIn,r.assetOut),l;a>0?l=s[a-1].amountOut:l=typeof t=="string"?b.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(i,o.assetOut),{amountOut:d,calculatedOut:m,feePct:p,errors:g}=i.validateAndSell(o,l,u),P=this.getPoolFeeRange(u),y=i.spotPriceOutGivenIn(o),S=Math.pow(10,o.decimalsIn),f=l*y/BigInt(S),T=A.calculateDiffToRef(m,f);s.push({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:d,calculatedOut:m,spotPrice:y,tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===r.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===r.assetIn},toHuman(){return{...r,amountIn:b.toDecimal(l,o.decimalsIn),amountOut:b.toDecimal(d,o.decimalsOut),calculatedOut:b.toDecimal(m,o.decimalsOut),spotPrice:b.toDecimal(y,o.decimalsOut),tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}async getMostLiquidRoute(t,e){let n=await super.getPools(),s=super.validateInput(t,e,n),a=super.getPaths(t,e,n),o=n.filter(m=>m.tokens.some(p=>p.id===t&&p.id!==m.id)).map(m=>m.type==="Aave"?m.tokens:m.tokens.filter(p=>p.id===t)).map(m=>m.map(p=>p.balance).reduce((p,g)=>p+g)).sort((m,p)=>p<m?-1:1)[0],l=A.getFraction(o,.1),u=await Promise.all(a.map(m=>this.toSellSwaps(l,m,s)));return this.findBestSellRoute(u).map(m=>({poolAddress:m.poolAddress,poolId:m?.poolId,pool:m.pool,assetIn:m.assetIn,assetOut:m.assetOut}))}async getSpotPrice(t,e){let n=await super.getPools(),s=super.validateInput(t,e,n),a=await this.getMostLiquidRoute(t,e),r=await this.toSellSwaps("1",a,s),i=await this.getSellSpot(r),o=r[r.length-1].assetOutDecimals;return{amount:i,decimals:o}}findBestBuyRoute(t){let e=t.sort((n,s)=>{let a=n[0].amountIn,r=s[0].amountIn;return a>r?1:-1});return e.find(n=>n.every(s=>s.errors.length==0))||e[0]}async getBestBuy(t,e,n){return this.getBuy(t,e,n)}async getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let n=t.map(i=>i.assetInDecimals).reduce((i,o)=>i+o),s=t.map(i=>i.spotPrice).reduce((i,o)=>i*o),a=n-e.assetInDecimals,r=Math.pow(10,a);return s/BigInt(r)}async getBuy(t,e,n,s){let a=await super.getPools(),r=super.validateInput(t,e,a),i=super.getPaths(t,e,a);if(i.length===0)throw new pt(t,e);let o;if(s)o=await this.toBuySwaps(n,s,r);else{let k=await Promise.all(i.map(C=>this.toBuySwaps(n,C,r)));o=this.findBestBuyRoute(k)}let l=o[o.length-1],u=o[0],d=this.isDirectTrade(o),m=await this.getBuySpot(o),p=u.amountIn,g=d?u.calculatedIn:this.calculateDelta0X(l.amountOut,o,r),P=p-g,y=this.getRouteFeeRange(o),S=d?u.tradeFeePct:A.calculateBuyFee(g,p),f=Math.pow(10,l.assetOutDecimals),T=l.amountOut*m/BigInt(f),O;return g===0n?O=-100:O=A.calculateDiffToRef(T,g),{type:"Buy",amountOut:l.amountOut,amountIn:u.amountIn,spotPrice:m,tradeFee:P,tradeFeePct:S,tradeFeeRange:y,priceImpactPct:O,swaps:o,toHuman(){return{type:"Buy",amountOut:b.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:b.toDecimal(u.amountIn,u.assetInDecimals),spotPrice:b.toDecimal(m,u.assetInDecimals),tradeFee:b.toDecimal(P,u.assetInDecimals),tradeFeePct:S,tradeFeeRange:y,priceImpactPct:O,swaps:o.map(k=>k.toHuman())}}}}calculateDelta0X(t,e,n){let s=[];for(let a=e.length-1;a>=0;a--){let r=e[a],i=n.get(r.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(r.assetIn,r.assetOut),l;a==e.length-1?l=t:l=s[0];let u=i.calculateInGivenOut(o,l);s.unshift(u)}return s[0]}async toBuySwaps(t,e,n){let s=[];for(let a=e.length-1;a>=0;a--){let r=e[a],i=n.get(r.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(r.assetIn,r.assetOut),l;a==e.length-1?l=typeof t=="string"?b.toBigInt(t,o.decimalsOut):t:l=s[0].amountIn;let u=await this.ctx.getPoolFees(i,o.assetOut),{amountIn:d,calculatedIn:m,feePct:p,errors:g}=i.validateAndBuy(o,l,u),P=this.getPoolFeeRange(u),y=i.spotPriceInGivenOut(o),S=Math.pow(10,o.decimalsOut),f=l*y/BigInt(S),T;m===0n?T=-100:T=A.calculateDiffToRef(f,m),s.unshift({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:d,calculatedIn:m,spotPrice:y,tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===r.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===r.assetIn},toHuman(){return{...r,amountOut:b.toDecimal(l,o.decimalsOut),amountIn:b.toDecimal(d,o.decimalsIn),calculatedIn:b.toDecimal(m,o.decimalsIn),spotPrice:b.toDecimal(y,o.decimalsIn),tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}};var hn=6e3,Ce=1000000000000000n,Ht=6,Me=-5,Le=216e5,Uo=3,Pn=6;var qe=require("polkadot-api");var G=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:s,poolId:a})=>s==="Stableswap"?{pool:(0,qe.Enum)("Stableswap",a),asset_in:e,asset_out:n}:{pool:(0,qe.Enum)(s),asset_in:e,asset_out:n})}};var ft=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Ce})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,s,a){let[r,i]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:u}=i,d=l[0],m=l[l.length-1],{assetInDecimals:p}=d,{assetOutDecimals:g}=m,P=Math.abs(u),y=this.getMinimumTradeCount(o,r),S=this.getOptimalTradeCount(P),f=a?Math.round(s/a):S,T=Math.ceil(s/y),O=Math.round(s/S),k=Math.round(s/f),C=o/BigInt(f),M=await this.router.getBestSell(t,e,C),Q=o<r,Vt=[];Q&&Vt.push("OrderTooSmall");let Wt=M.amountOut*BigInt(f),re=this.toBlockPeriod(k),oe=M.tradeFee*BigInt(f),In=G.build(l),Ve={assetIn:t,assetOut:e,errors:Vt,frequencyMin:T,frequencyOpt:O,frequency:k,tradeCount:f,tradeFee:oe,tradeImpactPct:M.priceImpactPct,tradePeriod:re,tradeRoute:In,type:"Dca"};return{...Ve,amountIn:o,amountOut:Wt,tradeAmountIn:M.amountIn,tradeAmountOut:M.amountOut,toHuman(){return{...Ve,amountIn:b.toDecimal(o,p),amountOut:b.toDecimal(Wt,g),tradeAmountIn:b.toDecimal(M.amountIn,p),tradeAmountOut:b.toDecimal(M.amountOut,g)}}}}async getMinimumOrderBudget(t){if(0===t)return this.minOrderBudget;let e=await this.router.getSpotPrice(0,t),n=10n**BigInt(12);if(e)return this.minOrderBudget*e.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(t,e){let n=e*2n/10n;if(n===0n)return 0;let s=t+n/2n;return Number(s/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[s,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:r,swaps:i,priceImpactPct:o}=a,l=i[0],u=i[i.length-1],{assetInDecimals:d}=l,{assetOutDecimals:m}=u,p=Math.abs(o),g=this.getTwapTradeCount(p),P=r/BigInt(g),y=await this.router.getBestSell(l.assetIn,u.assetOut,P),S=g===1,f=r<s,T=y.priceImpactPct<-5,O=[];f||S?O.push("OrderTooSmall"):T&&O.push("OrderImpactTooBig");let k=y.amountOut*BigInt(g),C=y.tradeFee*BigInt(g),M=G.build(i),Q={assetIn:t,assetOut:e,errors:O,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:6,tradeRoute:M,type:"TwapSell"};return{...Q,amountIn:r,amountOut:k,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:C,toHuman(){return{...Q,amountIn:b.toDecimal(r,d),amountOut:b.toDecimal(k,m),tradeAmountIn:b.toDecimal(y.amountIn,d),tradeAmountOut:b.toDecimal(y.amountOut,m),tradeFee:b.toDecimal(C,m)}}}}async getTwapBuyOrder(t,e,n){let[s,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:r,swaps:i,priceImpactPct:o}=a,l=i[0],u=i[i.length-1],{assetInDecimals:d}=l,{assetOutDecimals:m}=u,p=Math.abs(o),g=this.getTwapTradeCount(p),P=r/BigInt(g),y=await this.router.getBestBuy(l.assetIn,u.assetOut,P),S=y.amountIn*BigInt(g),f=g===1,T=S<s,O=y.priceImpactPct<-5,k=[];T||f?k.push("OrderTooSmall"):O&&k.push("OrderImpactTooBig");let C=y.tradeFee*BigInt(g),M=G.build(i),Q={assetIn:t,assetOut:e,errors:k,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:6,tradeRoute:M,type:"TwapBuy"};return{...Q,amountIn:S,amountOut:r,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:C,toHuman(){return{...Q,amountIn:b.toDecimal(S,d),amountOut:b.toDecimal(r,m),tradeAmountIn:b.toDecimal(y.amountIn,d),tradeAmountOut:b.toDecimal(y.amountOut,m),tradeFee:b.toDecimal(C,d)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,n=Math.round(e);return Math.max(n,6)}};var He={};I(He,{BIG_10:()=>xn,BIG_BILL:()=>Sn,StakingApi:()=>Gt,StakingClient:()=>Ut});var fn=require("@polkadot/util-crypto"),Tn=require("@polkadot/util"),rt=require("@galacticcouncil/math-staking"),it=jt(require("big.js")),xn=(0,it.default)(10),Sn=(0,it.default)(xn.pow(12));function as(c){return(0,fn.encodeAddress)((0,Tn.stringToU8a)(("modl"+c).padEnd(32,"\0")),63)}var Gt=class{client;constructor(t){this.client=t}async getFreePotBalance(){let t=await this.client.getPalletId(),e=as(t);return this.client.getBalance(e)}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]),s=e?.created_at,a=await n.reduce(async(r,[i,o])=>{let l=await r,u=i,d=o.amount,m=o.conviction.toString(),p=await this.client.getReferendumInfo(u);return p&&(p.type==="Approved"||p.type==="Rejected")&&l.push({id:u,amount:d,conviction:m}),l},Promise.resolve([]));return{stake:e?.stake,rewardPerStake:e?.reward_per_stake,createdAt:s,actionPoints:e?.action_points,accumulatedUnpaidRewards:e?.accumulated_unpaid_rewards,accumulatedSlashPoints:e?.accumulated_slash_points,accumulatedLockedRewards:e?.accumulated_locked_rewards,votes:a}}async getStake(t){let e=await this.client.getNFTCollectionId(),[n,s]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),a=s.find(r=>r)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:a,stakePosition:a?await this.getStakingPosition(a):void 0}}async getRewards(t){let e=await this.getStake(t),{potReservedBalance:n,accumulatedRewardPerStake:s,totalStake:a,stakePosition:r}=e;if(!r)return;let[i,o,l,u,d]=await Promise.all([this.client.getBlockNumber(),this.getFreePotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getSixBlockSince()]),m=(0,it.default)(o.toString()).minus(n.toString()),p=s.toString(),g=i.toString(),P=(0,it.default)(g).plus(1).toString();m.gt(0)&&a>0&&(p=(0,rt.calculate_accumulated_rps)(s.toString(),m.toString(),a.toString()));let y=(0,rt.calculate_period_number)(l.toString(),g,d??P),S=(0,rt.calculate_period_number)(l.toString(),r.createdAt?.toString()??"",d??P),f=(0,rt.calculate_rewards)(p,r.rewardPerStake?.toString()??"",r.stake?.toString()??""),T=(0,it.default)(f).plus(r.accumulatedUnpaidRewards?.toString()||"0").plus(r.accumulatedLockedRewards?.toString()||"0");if(!(0,it.default)(y).minus(S).lte(u.toString()))return T.div(Sn).toString()}};var Ut=class extends D{async getBalance(t){return(await this.api.query.System.Account.getValue(t)).data.free}async getBlockNumber(){return await this.api.query.System.Number.getValue({at:"best"})}async getPalletId(){let t=this.api.constants.Staking.PalletId;return(await t()).asText()}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:r})=>{let[i,o,l]=r;return{address:i,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var Ue={};I(Ue,{TxBuilderFactory:()=>xt});var Ge=require("polkadot-api");function wn(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var Tt=class extends D{evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evmClient=e??new L,this.balanceClient=new X(t),this.aaveUtils=new et(this.evmClient)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:n=>this.dryRun(n,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:me})}async dryRun(t,e){let n=(0,Ge.Enum)("Signed",t),s=(0,Ge.Enum)("system",n),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall),i=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(i){let o=wn(i.value);throw new Error("Dry run execution error!",{cause:o})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var se=class extends Tt{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],a=await this.balanceClient.getBalance(this.beneficiary,s);return t>=a-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],a=n[n.length-1],r=A.getFraction(t,this.slippagePct),i=s.assetIn,o=a.assetOut,l=t+r,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.buy({asset_in:i,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:i,asset_out:o,amount_out:e,max_amount_in:l,route:G.build(n)}),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],a=n[n.length-1],r=A.getFraction(e,this.slippagePct),i=s.assetIn,o=a.assetOut,l=e-r,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.sell({asset_in:i,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:i,asset_out:o,amount_in:t,min_amount_out:l,route:G.build(n)}),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,n=e[0],s=e[e.length-1],a=A.getFraction(t,this.slippagePct),r=n.assetIn,i=s.assetOut,o=t-a,l=this.api.tx.Router.sell_all({asset_in:r,asset_out:i,min_amount_out:o,route:G.build(e)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var ae=require("polkadot-api");var ie=class extends Tt{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradePeriod:a,tradeRoute:r}=this.order,i=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:a,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ae.Enum)("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:0n,route:r})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",i)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:a,tradePeriod:r,tradeRoute:i}=this.order,o=A.getFraction(a,this.slippagePct),l=a-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ae.Enum)("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:l,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:a,tradePeriod:r,tradeRoute:i}=this.order,o=A.getFraction(s,this.slippagePct),l=s+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ae.Enum)("Buy",{asset_in:e,asset_out:n,amount_out:a,max_amount_in:l,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var xt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e??new L}trade(t){return new se(this.client,this.evmClient).setTrade(t)}order(t){return new ie(this.client,this.evmClient).setOrder(t)}};async function is(c,t,e){let n=new mt(c),[s,a]=await Promise.all([n.getBlockTime(),n.getMinOrderBudget()]),r=t??new L,i=new yt(c).withAave().withOmnipool().withStableswap().withXyk(),o=new et(r),l=new Pt(i),u=new ft(l,{blockTime:s,minBudgetInNative:a}),d=new Gt(e??new Ut(c));return{api:{aave:o,router:l,scheduler:u,staking:d},client:{asset:new ct(c),balance:new X(c),evm:r},ctx:{pool:i},tx:new xt(c,r),destroy:()=>{i.destroy()}}}0&&(module.exports={aave,api,big,client,const:null,createSdkContext,erc20,error,evm,fmt,h160,json,math,pool,sor,staking,tx,xc});
|
|
1
|
+
"use strict";var 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 Ke=Object.defineProperty;var S=(c,t)=>{for(var e in t)Ke(c,e,{get:t[e],enumerable:!0})};var pe={};S(pe,{Papi:()=>_,getWs:()=>Je});import{hydration as ze}from"@galacticcouncil/descriptors";function me(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var _=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(ze)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");me(n)&&console.log(t,...e)}};import{createClient as $e}from"polkadot-api";import{withPolkadotSdkCompat as Qe}from"polkadot-api/polkadot-sdk-compat";var Je=async c=>{let t=typeof c=="string"?c.split(","):c,s=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(t);return $e(Qe(s))};var Ie={};S(Ie,{AAVE_GAS_LIMIT:()=>Wt,AAVE_LENDING_POOL_ADDRESS:()=>Ft,AAVE_POOL_ABI:()=>Ut,AAVE_POOL_DATA_PROVIDER:()=>kt,AAVE_POOL_DATA_PROVIDER_ABI:()=>Rt,AAVE_POOL_PROXY:()=>Vt,AAVE_ROUNDING_THRESHOLD:()=>wa,AAVE_UINT_256_MAX:()=>Ze,AaveClient:()=>ut,AaveUtils:()=>Y});var Ut=[{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 Rt=[{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 Vt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",kt="0x112b087b60C1a166130d59266363C45F8aa99db0",Ft="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Wt=1000000n,wa=5,Ze=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ye={};S(ye,{EvmClient:()=>F,evmMainnet:()=>Xt});import{defineChain as tn}from"viem";var de=["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"],ge=["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"],Xt=tn({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:de,webSocket:ge},default:{http:de,webSocket:ge}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as be,createWalletClient as en,custom as nn,http as sn,webSocket as an}from"viem";var F=class{chain;constructor(t){this.chain=t||Xt}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 be({chain:this.chain,transport:sn()})}getWsProvider(){return be({chain:this.chain,transport:an()})}getSigner(t){return en({account:t,chain:this.chain,transport:nn(window.ethereum)})}};var ut=class{evmClient;constructor(t){this.evmClient=t??new F}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Rt,address:kt,args:[Ft],functionName:"getReservesData"})}async getUserReservesData(t){return await this.evmClient.getProvider().readContract({abi:Rt,address:kt,args:[Ft,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.evmClient.getProvider().readContract({abi:Ut,address:Vt,args:[t],functionName:"getUserAccountData"})}};var y={};S(y,{asBigInt:()=>ln,toBigInt:()=>on,toDecimal:()=>rn});import W from"big.js";W.NE=-18;function rn(c,t,e=6,n){let s=W(c.toString()),a=W(10).pow(t);return s.div(a).round(e,n).toString()}function on(c,t){let e=W(10).pow(t),s=W(c).mul(e).toFixed(0,W.roundDown);return BigInt(s)}function ln(c){return BigInt(c.round(0,W.roundDown).toFixed(0))}var K={};S(K,{ERC20:()=>Yt});var Yt=class{static fromAssetId(t){let e=Buffer.alloc(20,0);return e[15]=1,e.writeUInt32BE(t,16),"0x"+e.toString("hex")}static toAssetId(t){let e=Buffer.from(t.replace("0x",""),"hex");return e.length!==20||!this.isAssetAddress(t)?null:e.readUInt32BE(16)}static isAssetAddress(t){let e=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(e.subarray(0,16))}};var h={};S(h,{fromPermill:()=>mn,toDecimals:()=>cn,toPct:()=>un});var he=1e3;function un(c){let[t,e]=c;return t/e*100}function cn(c){let[t,e]=c;return t/e}function mn(c){return[c/he,he]}var Et={};S(Et,{H160:()=>$t,isEvmAccount:()=>Te,isEvmAddress:()=>xe,isSs58Address:()=>Se});import{AccountId as ct}from"polkadot-api";import{toHex as fe}from"@polkadot-api/utils";import{Buffer as V}from"buffer";var Pe={};S(Pe,{HUB_ASSET_ID:()=>Kt,HYDRATION_OMNIPOOL_ADDRESS:()=>dn,HYDRATION_PARACHAIN_ID:()=>pn,HYDRATION_SS58_PREFIX:()=>D,RUNTIME_DECIMALS:()=>E,SYSTEM_ASSET_DECIMALS:()=>jt,SYSTEM_ASSET_ID:()=>N,TRADEABLE_DEFAULT:()=>z});var E=18,N=0,jt=12,pn=2034,D=63,dn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Kt=1,z=15;var zt="ETH\0";function Te(c){if(!c)return!1;try{let t=ct().enc(c),e=V.from(zt);return V.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function xe(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function Se(c){try{return ct(63).enc(c),!0}catch{return!1}}var $t=class c{static toAccount=t=>{let e=V.from(t.slice(2),"hex"),n=V.from(zt),s=Uint8Array.from(V.concat([n,e,V.alloc(8)])),a=fe(s);return ct(63).dec(a)};static fromAccount=t=>{let e=ct().enc(t),n=V.from(zt),s=e.slice(n.length,-8);return"0x"+V.from(s).toString("hex")};static fromSS58=t=>{let n=ct().enc(t).slice(0,20);return fe(n)};static fromAny=t=>{if(xe(t))return t;if(Te(t))return c.fromAccount(t);if(Se(t))return c.fromSS58(t);throw new Error("Unknown address type")}};var X={};S(X,{findNestedKey:()=>gn,findNestedObj:()=>bn,jsonFormatter:()=>yn});var gn=(c,t)=>{let e=[];return JSON.stringify(c,(n,s)=>(s&&s[t]&&e.push(s),s)),e[0]},bn=(c,t,e)=>{let n;return JSON.stringify(c,(s,a)=>(a&&a[t]===e&&(n=a),a)),n},yn=(c,t)=>typeof t=="bigint"?t.toString():t;var v={};S(v,{calculateBuyFee:()=>Tn,calculateDiffToAvg:()=>hn,calculateDiffToRef:()=>Pn,calculateSellFee:()=>fn,getFraction:()=>xn});import H from"big.js";function hn(c,t){let e=H(c.toString()),n=H(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function Pn(c,t){if(t===0n)return 0;let e=H(c.toString()),n=H(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function fn(c,t){let e=H(c.toString()),n=H(t.toString());return H(1).minus(n.div(e)).mul(100).round(2).toNumber()}function Tn(c,t){let e=H(c.toString());return H(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function xn(c,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),s=BigInt(t*n);return c*s/BigInt(100*n)}var we={};S(we,{convertToId:()=>wn});import{Buffer as Sn}from"buffer";function wn(c){let e=Sn.from(c.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var{ERC20:Dt}=K,{H160:Qt}=Et,In=1.01,vn=99999,On=10n**27n,An=10n**18n,Y=class{client;constructor(t){let e=t??new F;this.client=new ut(e)}async getSummary(t){let e=Qt.fromAny(t),[n,s,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e)]),[r]=n,[i,o]=s,[l,u,d,m,p,g]=a,P=y.toDecimal(g,18),b=[];for(let x of i){let f=x.underlyingAsset.toLowerCase(),T=r.find(({underlyingAsset:Gt})=>Gt.toLowerCase()===f);if(!T)throw new Error("Missing pool reserve for "+f);let w=x.scaledATokenBalance,O=T.liquidityIndex,R=T.priceInMarketReferenceCurrency,k=w*O/On,Bt=Number(o===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,_t=T.usageAsCollateralEnabled&&x.usageAsCollateralEnabledOnUser&&x.scaledATokenBalance>0n,Ht=Dt.toAssetId(f);b.push({aTokenBalance:k,decimals:Number(T.decimals),isCollateral:_t,priceInRef:R,reserveId:Ht,reserveAsset:f,reserveLiquidationThreshold:Bt})}return{healthFactor:Number(P),totalCollateral:l,totalDebt:u,reserves:b}}async hasBorrowPositions(t){let e=Qt.fromAny(t),n=await this.client.getUserAccountData(e),[s,a]=n;return a>0n}async getHealthFactor(t){let e=Qt.fromAny(t),n=await this.client.getUserAccountData(e),[s,a,r,i,o,l]=n,u=y.toDecimal(l,18);return Number(u)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:s,totalDebt:a,reserves:r}=await this.getSummary(t),i=Dt.fromAssetId(e),o=r.find(b=>b.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:u,priceInRef:d,reserveLiquidationThreshold:m}=o,p=y.toBigInt(n,l),g=u?p*d/10n**BigInt(l):0n,P=s-g;return P<=0n?0:this.calculateHealthFactor(P,m,a)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:s,totalDebt:a,reserves:r}=await this.getSummary(t),i=Dt.fromAssetId(e),o=r.find(P=>P.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:d}=o,p=y.toBigInt(n,l)*u/10n**BigInt(l),g=s+p;return g<=0n?0:this.calculateHealthFactor(g,d,a)}async getMaxWithdraw(t,e){let{totalCollateral:n,totalDebt:s,reserves:a}=await this.getSummary(t),r=Dt.fromAssetId(e),i=a.find(o=>o.reserveAsset===r);if(!i)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(i,n,s)}async getMaxWithdrawAll(t){let{totalCollateral:e,totalDebt:n,reserves:s}=await this.getSummary(t),a={};for(let r of s){let i=this.calculateWithdrawMax(r,e,n);r.reserveId&&(a[r.reserveId]=i)}return a}calculateHealthFactor(t,e,n){if(n===0n)return vn;let s=10n**6n,a=y.toBigInt(e,18),r=t*a*s,i=n*An,o=r/i;return Number(o)/1e6}calculateRequiredCollateral(t,e,n){let s=y.toBigInt(t,18),a=y.toBigInt(e,18);return(s*n+a-1n)/a}calculateWithdrawMax(t,e,n){let{aTokenBalance:s,decimals:a,priceInRef:r,reserveLiquidationThreshold:i}=t,o=this.calculateRequiredCollateral(In,i,n),l=e-o;if(l<=0n)return{amount:0n,decimals:a};let u=l*10n**BigInt(a)/r;return{amount:s<u?s:u,decimals:a}}};var Oe={};S(Oe,{AssetClient:()=>$,BalanceClient:()=>q,ChainParams:()=>J});var $=class extends _{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[a]=n;return[a,s]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[a]=n;return[a,s]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:s}=n;return this.SUPPORTED_TYPES.includes(s.type)}).map(({keyArgs:n,value:s})=>{let[a]=n;return[a,s]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[a]=n;return[a,s]}))}async mapToken(t,e,n,s){let{name:a,asset_type:r,is_sufficient:i,existential_deposit:o}=e,{symbol:l,decimals:u}=n.get(t)??{};return{id:t,name:a?.asText(),symbol:l,decimals:u,icon:l,type:r.type,isSufficient:i,location:s,existentialDeposit:o}}async mapBond(t,e,n,s){let[a,r]=s,{asset_type:i,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:d}=await this.mapToken(a,e,n),m=Number(r),p=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",p.format(m)].join(" ");return{id:t,name:g,symbol:u+"b",decimals:d,icon:u,type:i.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:a,maturity:m}}async mapShares(t,e,n,s){let{assets:a}=s,{name:r,symbol:i,asset_type:o,is_sufficient:l,existential_deposit:u}=e,d=await Promise.all(a.map(async g=>{let{symbol:P}=await this.mapToken(g,e,n);return[g,P]})),m=Object.fromEntries(d),p=Object.values(m);return{id:t,name:p.join(", "),symbol:i?.asText()||r?.asText(),decimals:18,icon:p.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:m}}async mapExternal(t,e,n,s){let a=await this.mapToken(t,e,new Map,s),r=n?.find(i=>i.internalId===a.id);return r?{...a,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.isWhiteListed}:a}parseMetadata(t){return new Map(Array.from(t,([e,n])=>[e,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(t,e){let[n,s,a,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),i=this.parseMetadata(n),o=[];for(let[l,u]of Array.from(n)){let d=s.get(l),{asset_type:m}=u,p;switch(m.type){case"Bond":let g=r.get(l);p=await this.mapBond(l,u,i,g);break;case"StableSwap":let P=a.get(l);p=await this.mapShares(l,u,i,P);break;case"External":p=await this.mapExternal(l,u,e,d);break;default:p=await this.mapToken(l,u,i,d)}o.push(p)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};import{Subject as Bn,bufferCount as _n,combineLatest as Rn,debounceTime as kn,distinctUntilChanged as ve,finalize as Fn,map as Q,pairwise as En,shareReplay as Dn,startWith as Cn}from"rxjs";var q=class extends _{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:{free:n,frozen:s}}=await e.getValue(t);return n-s}async getTokenBalance(t,e){let n=this.api.query.Tokens.Accounts,{free:s,frozen:a}=await n.getValue(t,e);return s-a}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),s=this.subscribeErc20Balance(t);return Rn([e,n,s]).pipe(kn(250),Q(a=>a.flat()),Cn([]),_n(2,1),Q(([a,r],i)=>{if(i===0)return r;let o=a.reduce((u,d)=>(u.set(d.id,d.amount),u),new Map);return r.filter(u=>u.amount!==o.get(u.id))}))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe(Q(n=>{let{free:s,frozen:a}=n.data;return{id:0,amount:s-a}}))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe(Q(s=>{let{free:a,frozen:r}=s;return{id:e,amount:a-r}}))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe(ve((n,s)=>!s.deltas),Q(({deltas:n})=>{let s=[];return n?.deleted.forEach(a=>{let[r,i]=a.args;s.push({id:i,amount:0n})}),n?.upserted.forEach(a=>{let[r,i]=a.args,{free:o,frozen:l}=a.value;s.push({id:i,amount:o-l})}),s}))}subscribeErc20Balance(t,e){let n=new Bn,s=n.pipe(Dn(1)),a=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}),r=async()=>{let o=e||await a(),l=async()=>{let m=(await Promise.all(o.map(async p=>{let g=await this.getTokenBalanceData(t,p);return[p,g]}))).map(([p,g])=>({id:p,amount:g}));n.next(m)};await l();let u=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>u.unsubscribe()},i;return r().then(o=>i=o),s.pipe(Fn(()=>i?.()),En(),Q(([o,l],u)=>{if(u===0)return l;let d=o.reduce((p,g)=>(p.set(g.id,g.amount),p),new Map);return l.filter(p=>p.amount!==d.get(p.id))}),ve((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let{free:n,frozen:s}=await this.api.apis.CurrenciesApi.account(e,t);return n-s}};var J=class extends _{_minOrderBudget;_blockTime;constructor(t){super(t)}async getBlockTime(){if(this._blockTime===void 0){let t=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(t)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var Ae={};S(Ae,{AssetNotFound:()=>Jt,PoolNotFound:()=>mt,RouteNotFound:()=>Z});var Jt=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},mt=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},Z=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Ce={};S(Ce,{PoolContextProvider:()=>nt,PoolError:()=>j,PoolFactory:()=>et,PoolType:()=>A,aave:()=>se,lbp:()=>Zt,omni:()=>te,stable:()=>ee,xyk:()=>ne});var Zt={};S(Zt,{LbpMath:()=>L,LbpPool:()=>pt,LbpPoolClient:()=>dt});import{calculate_in_given_out as Mn,calculate_out_given_in as Ln,calculate_linear_weights as qn,calculate_pool_trade_fee as Nn,get_spot_price as Hn}from"@galacticcouncil/math-lbp";var L=class{static getSpotPrice(t,e,n,s,a){return Hn(t,e,n,s,a)}static calculateInGivenOut(t,e,n,s,a){return Mn(t,e,n,s,a)}static calculateOutGivenIn(t,e,n,s,a){return Ln(t,e,n,s,a)}static calculateLinearWeights(t,e,n,s,a){return qn(t,e,n,s,a)}static calculatePoolTradeFee(t,e,n){return Nn(t,e,n)}};var A=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a))(A||{}),j=(a=>(a.InsufficientTradingAmount="InsufficientTradingAmount",a.MaxInRatioExceeded="MaxInRatioExceeded",a.MaxOutRatioExceeded="MaxOutRatioExceeded",a.TradeNotAllowed="TradeNotAllowed",a.UnknownError="UnknownError",a))(j||{});var pt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,n,s,a,r,i){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a,this.fee=r,this.repayFeeApply=i}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),a=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,weightIn:s.weight,weightOut:a.weight}}validateAndBuy(t,e,n){let s=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let r=t.balanceOut/this.maxOutRatio;if(e>r&&a.push("MaxOutRatioExceeded"),s===t.assetOut){let i=this.calculateTradeFee(e,n),o=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+i,u=this.calculateInGivenOut(t,l),d=t.balanceIn/this.maxInRatio;return u>d&&a.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:a}}else{let i=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return i>o&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:a}}}validateAndSell(t,e,n){let s=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let r=t.balanceIn/this.maxInRatio;if(e>r&&a.push("MaxInRatioExceeded"),s===t.assetIn){let i=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return i>o&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:a}}else{let i=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(i,n),l=h.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),u=i-o,d=t.balanceOut/this.maxOutRatio;return u>d&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:u,feePct:l,errors:a}}}calculateInGivenOut(t,e){let n=L.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=L.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=L.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=L.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let n=L.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as jn}from"polkadot-api";import{map as Kn,of as Fe,switchMap as zn}from"rxjs";import{memoize1 as Gn}from"@thi.ng/memoize";import{combineLatest as Be,combineLatestAll as Un,debounceTime as Vn,firstValueFrom as Wn,from as _e,map as Re,mergeAll as Xn,of as Yn,switchMap as ke}from"rxjs";var C=class extends q{override=[];mem=0;memPools=Gn(t=>(this.log(this.getPoolType(),"mem pools",t,"\u2705"),this.loadPools()));constructor(t){super(t)}async withOverride(t){this.override=t||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let t=_e(this.getPoolsMem()).pipe(ke(e=>this.subscribe(e)),Un());return Wn(t)}getSubscriber(){return _e(this.getPoolsMem()).pipe(ke(t=>this.subscribe(t)),Xn())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>Be([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe(Vn(250),Re(([n,s])=>this.updatePool(n,s))))}subscribePoolBalance(t){if(t.type==="Aave")return Yn([]);let e=[this.subscribeTokensBalance(t.address)];if(this.hasSystemAsset(t)){let n=this.subscribeSystemBalance(t.address);e.push(n)}if(this.hasErc20Asset(t)){let n=t.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),s=this.subscribeErc20Balance(t.address,n);e.push(s)}return Be(e).pipe(Re(n=>n.map(s=>Array.isArray(s)?s:[s]).flat()))}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({id:e,decimals:n,balance:s})=>{let a=this.override.find(i=>i.id===e),r=!!n||!!a?.decimals;return s>0n&&r})}updatePool=(t,e)=>{let n=t.tokens.map(s=>{let a=e.find(i=>i.id===s.id),r=this.override.find(i=>i.id===s.id);return a?{...s,balance:a.amount,decimals:s.decimals||r?.decimals}:{...s,decimals:s.decimals||r?.decimals}});return{...t,tokens:n}}};var dt=class extends C{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),s=e?.relay_parent_number||0,a=t.filter(({value:r})=>e&&this.isActivePool(r,s)).map(async({keyArgs:r,value:i})=>{let[o]=r,l=o.toString(),u=await this.getPoolDelta(l,i,s);return{address:l,type:"LBP",fee:i.fee,...u,...n}});return Promise.all(a)}async getPoolDelta(t,e,n){let{start:s,end:a,assets:r,initial_weight:i,final_weight:o,repay_target:l,fee_collector:u}=e,d=L.calculateLinearWeights(s?s.toString():"0",a?a.toString():"0",i.toString(),o.toString(),n.toString()),[m,p]=r,g=BigInt(d),P=this.MAX_FINAL_WEIGHT-BigInt(g),[b,x,f,T,w]=await Promise.all([this.isRepayFeeApplied(m,l,u.toString()),this.getBalance(t,m),this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(t,p),this.api.query.AssetRegistry.Assets.getValue(p)]);return{repayFeeApply:b,tokens:[{id:m,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:x,weight:g,type:f?.asset_type.type},{id:p,decimals:w?.decimals,existentialDeposit:w?.existential_deposit,balance:T,weight:P,type:w?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:s}=t;return n&&s?e>=n&&e<s:!1}async isRepayFeeApplied(t,e,n){if(e===0n)return!1;try{return await this.getBalance(n,t)<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(t){return{repayFee:await this.getRepayFee(),exchangeFee:t.fee}}getPoolType(){return"LBP"}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(jn.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(t.address);return n?e.watchValue("best").pipe(zn(s=>s?this.getPoolDelta(t.address,n,s.relay_parent_number):Fe(t)),Kn(s=>Object.assign({},t,s))):Fe(t)}};var te={};S(te,{OmniMath:()=>I,OmniPool:()=>gt,OmniPoolClient:()=>bt});import{calculate_in_given_out as $n,calculate_lrna_in_given_out as Qn,calculate_out_given_in as Jn,calculate_out_given_lrna_in as Zn,calculate_spot_price as ts,calculate_lrna_spot_price as es,calculate_shares as ns,calculate_liquidity_out as ss,calculate_liquidity_lrna_out as as,verify_asset_cap as is,calculate_liquidity_hub_in as rs,is_sell_allowed as os,is_buy_allowed as ls,is_add_liquidity_allowed as us,is_remove_liquidity_allowed as cs}from"@galacticcouncil/math-omnipool";import tt from"big.js";var I=class{static calculateSpotPrice(t,e,n,s){return ts(t,e,n,s)}static calculateLrnaSpotPrice(t,e){return es(t,e)}static calculateInGivenOut(t,e,n,s,a,r,i,o,l){return $n(t,e,n,s,a,r,i,o,l)}static calculateLrnaInGivenOut(t,e,n,s,a){return Qn(t,e,n,s,a)}static calculateOutGivenIn(t,e,n,s,a,r,i,o,l){return Jn(t,e,n,s,a,r,i,o,l)}static calculateOutGivenLrnaIn(t,e,n,s,a){return Zn(t,e,n,s,a)}static calculateShares(t,e,n,s){return ns(t,e,n,s)}static calculateLiquidityOut(t,e,n,s,a,r,i,o){return ss(t,e,n,s,a,r,i,o)}static calculateLiquidityLRNAOut(t,e,n,s,a,r,i,o){return as(t,e,n,s,a,r,i,o)}static calculateCapDifference(t,e,n,s){let a=tt(e),r=tt(t),i=tt(s),o=tt(n),l=tt(10).pow(18),u=o.div(l);if(a.div(i).lt(u)){let m=u.times(i).minus(a).times(r),p=a.times(tt(1).minus(u));return m.div(p).toFixed(0)}else return"0"}static verifyAssetCap(t,e,n,s){return is(t,e,n,s)}static calculateLimitHubIn(t,e,n,s){return rs(t,e,n,s)}static isSellAllowed(t){return os(t)}static isBuyAllowed(t){return ls(t)}static isAddLiquidityAllowed(t){return us(t)}static isRemoveLiquidityAllowed(t){return cs(t)}};var gt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,n,s,a,r){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a,this.hubAssetId=r}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),a=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,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(t,e,n){let s=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,n),r=s===0n?0:v.calculateDiffToRef(a,s),i=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);(!o||!l)&&i.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&i.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&i.push("MaxOutRatioExceeded");let d=t.balanceIn/this.maxInRatio;return a>d&&i.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:r,errors:i}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,n),r=v.calculateDiffToRef(s,a),i=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);(!o||!l)&&i.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&i.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&i.push("MaxInRatioExceeded");let d=t.balanceOut/this.maxOutRatio;return a>d&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:r,errors:i}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let s=I.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateLrnaInGivenOut(t,e,n){let s=I.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let s=I.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0",n?h.toDecimals(n.protocolFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}calculateOutGivenLrnaIn(t,e,n){let s=I.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?h.toDecimals(n.assetFee).toString():"0"),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=I.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceLrnaInGivenOut(t){let e=I.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=I.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}spotPriceOutGivenLrnaIn(t){let e=I.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};import{AccountId as ms,CompatibilityLevel as ps}from"polkadot-api";import{toHex as ds}from"@polkadot-api/utils";import{distinctUntilChanged as gs,map as Ee}from"rxjs";var bt=class extends C{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,s,a,r,i]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.getBalance(e,t),this.getPoolLimits()]),o=n.map(async({keyArgs:u,value:d})=>{let[m]=u,{hub_reserve:p,shares:g,tradable:P,cap:b,protocol_shares:x}=d,[f,T]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,m)]);return{id:m,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:T,cap:b,hubReserves:p,protocolShares:x,shares:g,tradeable:P,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:r,tradeable:s,type:a?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...i}]}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=ds(e);return ms(63).dec(n)}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(t,e){let[n,s,a]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),r=n.min_fee+s.min_fee,i=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(r),max:h.fromPermill(i)}}else return{assetFee:h.fromPermill(n.min_fee),protocolFee:h.fromPermill(s.min_fee),min:h.fromPermill(r),max:h.fromPermill(i)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(ps.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(gs((n,s)=>!s.deltas),Ee(({entries:n})=>n.map(s=>{let[a]=s.args,{hub_reserve:r,shares:i,tradable:o,cap:l,protocol_shares:u}=s.value,d=t.tokens.findIndex(p=>p.id===a);return{...t.tokens[d],cap:l,hubReserves:r,protocolShares:u,shares:i,tradeable:o}})),Ee(n=>{let s=t.tokens.find(a=>a.id===1);return{...t,tokens:[...n,s]}}))}};var ee={};S(ee,{StableMath:()=>B,StableSwap:()=>yt,StableSwapClient:()=>ht});import{calculate_in_given_out as bs,calculate_out_given_in as ys,calculate_amplification as hs,calculate_add_one_asset as Ps,calculate_liquidity_out_one_asset as fs,calculate_shares as Ts,calculate_shares_for_amount as xs,calculate_spot_price_with_fee as Ss,pool_account_name as ws,recalculate_peg as Is}from"@galacticcouncil/math-stableswap";var B=class{static getPoolAddress(t){return ws(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,s,a){return hs(t,e,n,s,a)}static calculateInGivenOut(t,e,n,s,a,r,i){return bs(t,e,n,s,a,r,i)}static calculateAddOneAsset(t,e,n,s,a,r,i){return Ps(t,e,n,s,a,r,i)}static calculateSharesForAmount(t,e,n,s,a,r,i){return xs(t,e,n,s,a,r,i)}static calculateOutGivenIn(t,e,n,s,a,r,i){return ys(t,e,n,s,a,r,i)}static calculateLiquidityOutOneAsset(t,e,n,s,a,r,i){return fs(t,e,n,s,a,r,i)}static calculateShares(t,e,n,s,a,r){return Ts(t,e,n,s,a,r)}static calculateSpotPriceWithFee(t,e,n,s,a,r,i,o){return Ss(t,e,n,s,a,r,i,o)}static recalculatePegs(t,e,n,s,a){return Is(t,e,n,s,a)}};var yt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.id,t.fee,t.totalIssuance)}constructor(t,e,n,s,a,r,i,o,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a,this.amplification=r,this.id=i,this.fee=o,this.totalIssuance=l}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),a=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:a.tradeable,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,n),r=h.toPct(n.fee),i=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);return(!o||!l)&&i.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&i.push("InsufficientTradingAmount"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:r,errors:i}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,n),r=h.toPct(n.fee),i=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);return(!o||!l)&&i.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&i.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:r,errors:i}}calculateIn(t,e,n){let s=B.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateAddOneAsset(t,e,n){let s=B.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.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(t,e,n){let s=B.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.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(t,e,n){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,n):t.assetIn==this.id?this.calculateSharesForAmount(t,e,n):this.calculateIn(t,e,n)}spotPriceInGivenOut(t){let e=B.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetOut==this.id)return BigInt(e);if(t.assetIn==this.id){let s=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let s=B.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateWithdrawOneAsset(t,e,n){let s=B.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.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(t,e,n){let s=B.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?h.toDecimals(n.fee).toString():"0",this.getPegs()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e,n){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,n):t.assetOut==this.id?this.calculateShares(t,e,n):this.calculateOut(t,e,n)}spotPriceOutGivenIn(t){let e=B.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetIn==this.id)return BigInt(e);if(t.assetOut==this.id){let s=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}getPegs(){let t=B.defaultPegs(this.tokens.length-1);return JSON.stringify(t)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:n,decimals:s})=>({asset_id:e,amount:n,decimals:s}));return JSON.stringify(t,X.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],X.jsonFormatter)}};import{AccountId as vs,CompatibilityLevel as Os}from"polkadot-api";import{toHex as As}from"@polkadot-api/utils";import{blake2b as Bs}from"@noble/hashes/blake2b";import{map as _s,of as Rs,switchMap as ks}from"rxjs";var Fs=340282366920938463463374607431768211455n,ht=class extends C{poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),s=t.map(async({keyArgs:a,value:r})=>{let[i]=a,o=this.getPoolAddress(i),[l,u]=await Promise.all([this.getPoolDelta(i,r,e),this.getPoolTokens(i,r)]);return this.poolsData.set(o,r),{address:o,id:i,type:"Stableswap",fee:h.fromPermill(r.fee),tokens:u,...l,...n}});return Promise.all(s)}async getPoolDelta(t,e,n){let{initial_amplification:s,final_amplification:a,initial_block:r,final_block:i}=e,o=B.calculateAmplification(s.toString(),a.toString(),r.toString(),i.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(t);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),s=e.assets.map(async i=>{let[o,l,u]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,i),this.api.query.AssetRegistry.Assets.getValue(i),this.getBalance(n,i)]);return{id:i,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:u,tradeable:o,type:l?.asset_type.type}}),a=await Promise.all(s),r=await this.api.query.AssetRegistry.Assets.getValue(t);return a.push({id:t,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:Fs,tradeable:15,type:r?.asset_type.type}),a}getPoolAddress(t){let e=B.getPoolAddress(t),n=Bs(e,{dkLen:32}),s=As(n);return vs(63).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolFees(t){return{fee:t.fee}}getPoolType(){return"Stableswap"}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(Os.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.System.Number,n=this.poolsData.get(t.address);return!n||!t.id?Rs(t):e.watchValue("best").pipe(ks(s=>this.getPoolDelta(t.id,n,s)),_s(s=>Object.assign({},t,s)))}};var ne={};S(ne,{XykMath:()=>G,XykPool:()=>Pt,XykPoolClient:()=>ft});import{calculate_in_given_out as Es,calculate_out_given_in as Ds,calculate_pool_trade_fee as Cs,get_spot_price as Ms,calculate_liquidity_in as Ls,calculate_shares as qs,calculate_spot_price as Ns,calculate_spot_price_with_fee as Hs,calculate_liquidity_out_asset_a as Gs,calculate_liquidity_out_asset_b as Us}from"@galacticcouncil/math-xyk";var G=class{static getSpotPrice(t,e,n){return Ms(t,e,n)}static calculateInGivenOut(t,e,n){return Es(t,e,n)}static calculateOutGivenIn(t,e,n){return Ds(t,e,n)}static calculatePoolTradeFee(t,e,n){return Cs(t,e,n)}static calculateLiquidityIn(t,e,n){return Ls(t,e,n)}static calculateSpotPrice(t,e){return Ns(t,e)}static calculateSpotPriceWithFee(t,e,n,s){return Hs(t,e,n,s)}static calculateShares(t,e,n){return qs(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,s){return Gs(t,e,n,s)}static calculateLiquidityOutAssetB(t,e,n,s){return Us(t,e,n,s)}};var Pt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,a){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),a=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:s.decimals,decimalsOut:a.decimals,balanceIn:s.balance,balanceOut:a.balance,assetInEd:s.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),a=this.calculateTradeFee(s,n),r=h.toPct(n.exchangeFee),i=s+a,o=[];(e<this.minTradingLimit||s<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return i>u&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:e,feePct:r,errors:o}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),a=this.calculateTradeFee(s,n),r=h.toPct(n.exchangeFee),i=s-a,o=[];(e<this.minTradingLimit||s<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return i>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:i,feePct:r,errors:o}}calculateInGivenOut(t,e){let n=G.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=G.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=G.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=G.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=G.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as Vs}from"polkadot-api";import{of as Ws}from"rxjs";var ft=class extends C{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,n]=await Promise.all([t.getEntries(),this.getPoolLimits()]),s=e.map(async({keyArgs:a,value:r})=>{let[i]=a,[o,l]=r,[u,d,m,p]=await Promise.all([this.getBalance(i,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(i,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:i,type:"XYK",tokens:[{id:o,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:u,type:d?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:m,type:p?.asset_type.type}],...n}});return Promise.all(s)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(Vs.BackwardsCompatible,e)}subscribePoolChange(t){return Ws(t)}};var se={};S(se,{AavePool:()=>Tt,AavePoolClient:()=>xt});var Tt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,a){this.type="Aave",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=a}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),a=n.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:a.balance,decimalsIn:s.decimals,decimalsOut:a.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),a=[];return e>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:a}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),a=[];return s>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:a}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){let e=Math.pow(10,t.decimalsOut);return BigInt(e)}spotPriceOutGivenIn(t){let e=Math.pow(10,t.decimalsIn);return BigInt(e)}calculateTradeFee(t,e){return 0n}};import{AccountId as Xs}from"polkadot-api";import{toHex as Ys}from"@polkadot-api/utils";import{map as js,merge as Ks,switchMap as zs}from"rxjs";import{decodeEventLog as $s}from"viem";var De=[{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:Qs}=K,Js=["Supply","Withdraw","Repay","Borrow"],xt=class extends C{async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:s,liqudity_in:a,liqudity_out:r})=>{let[i,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:i?.decimals,existentialDeposit:i?.existential_deposit,balance:a,location:o,type:i?.asset_type.type},{id:s,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:r,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:s,liqudity_out:a}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id);return t.tokens.map(r=>{let i=r.id===e.id?s:a;return{...r,balance:i}})}getPoolId(t,e){let n=t+"/"+e,s=new TextEncoder().encode(n.padEnd(32,"\0")),a=Ys(s);return Xs(63).dec(a)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(t,e){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(t){let[e,n]=t.tokens,s=this.getReserveH160Id(e),a=this.api.event.Router.Executed.watch(({asset_in:i,asset_out:o})=>i===n.id||o===n.id),r=this.api.event.EVM.Log.watch(({log:i})=>{let{topics:o,data:l}=i,u=o.map(g=>g.asHex()),d=l.asHex(),{eventName:m,args:p}=$s({abi:De,topics:u,data:d});return Js.includes(m)&&p.reserve.toLowerCase()===s.toLowerCase()});return Ks([a,r]).pipe(zs(()=>this.getPoolDelta(t)),js(i=>({...t,tokens:[...i]})))}getReserveH160Id(t){return t.type==="Erc20"?X.findNestedKey(t.location,"AccountKey20").AccountKey20.key:Qs.fromAssetId(t.id)}};var et=class{static get(t){switch(t.type){case"Aave":return Tt.fromPool(t);case"XYK":return Pt.fromPool(t);case"Omnipool":return gt.fromPool(t);case"LBP":return pt.fromPool(t);case"Stableswap":return yt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{Subject as Zs,Subscription as St,takeUntil as ta}from"rxjs";var nt=class extends _{lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=St.EMPTY;omniSub=St.EMPTY;stableSub=St.EMPTY;xykSub=St.EMPTY;aaveSub=St.EMPTY;isReady=!1;isDestroyed=new Zs;constructor(t){super(t),this.lbpClient=new dt(t),this.omniClient=new bt(t),this.stableClient=new ht(t),this.xykClient=new ft(t),this.aaveClient=new xt(t),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(t){return t.getSubscriber().pipe(ta(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let n=this.clients.find(s=>s.getPoolType()===t.type);if(n)return n.getPoolFees(t,e);throw new mt(t.type)}};var Ne={};S(Ne,{DEFAULT_BLOCK_TIME:()=>Me,DEFAULT_MIN_BUDGET:()=>re,ORDER_MIN_BLOCK_PERIOD:()=>Le,Router:()=>st,TWAP_BLOCK_PERIOD:()=>vt,TWAP_MAX_DURATION:()=>le,TWAP_MAX_PRICE_IMPACT:()=>oe,TWAP_TX_MULTIPLIER:()=>fu,TradeOrderError:()=>ie,TradeOrderType:()=>Lt,TradeRouteBuilder:()=>M,TradeRouter:()=>at,TradeScheduler:()=>it,TradeType:()=>Mt});var Ct=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var ea=5,wt=class{isNotVisited(t,e){let n=!0;return e.forEach(s=>{(s[0]===t[0]||s[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let s=[],a=new Ct,r=[];for(r.push([e,""]),a.enqueue(r);a.size()>0;){let i=a.dequeue();if(i==null||i.length>ea)return s;let o=i[i.length-1];(n===null||o[0]===n)&&s.push(i),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,i)){let d=[...i];d.push(u),a.enqueue(d)}})}return s}buildAndPopulateGraph(t,e){let n=new Map;for(let s of t)n.set(parseInt(s),[]);for(let[s,a,r]of e)n.get(a)?.push([r,s]);return n}};function ae(c){let t={};for(let e of c){let n=e.tokens.length;for(let s=0;s<n;s++){t[e.tokens[s].id]||(t[e.tokens[s].id]=[]);for(let a=0;a<n;a++){if(s==a)continue;let r=[e.address,e.tokens[s].id,e.tokens[a].id];t[e.tokens[s].id].push(r)}}}return t}var It=class{getProposals(t,e,n){let s=ae(n),a=Object.keys(s),r=a.map(u=>s[u]).flat(),i=new wt,o=i.buildAndPopulateGraph(a,r),l=i.findPaths(o,t,e);return this.parsePaths(l)}parsePaths(t){let e=[];for(let n of t){let s=[];for(let a=0;a<n.length;a++){let r=n[a],i=n[a+1];if(i==null)break;s.push(this.toEdge(r,i))}e.push(s)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var st=class{routeSuggester;routerOptions;ctx;defaultRouterOptions={useOnly:[]};constructor(t,e){this.ctx=t,this.routeSuggester=new It,this.routerOptions={...this.defaultRouterOptions,...e}}async getPools(){let t=await this.ctx.getPools(),e=this.routerOptions.useOnly;return e.length===0?t:t.filter(n=>e.includes(n.type))}async getRoutes(t,e){let n=await this.getPools();return this.validateInput(t,e,n),this.getPaths(t,e,n)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}validateInput(t,e,n){if(n.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let s=this.getAssets(n);if(!s.has(t))throw new Error(t+" is not supported asset");if(!s.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(s=>s.id)).flat().sort((n,s)=>n>s?1:-1);return new Set(e)}getPaths(t,e,n){let s=this.toPoolsMap(n);return this.routeSuggester.getProposals(t,e,n).filter(r=>this.validPath(r,s)).map(r=>this.toHops(r,s))}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,s)=>n&&s)}validEdge([t,e,n],s){return s.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,et.get(e)]))}toHops(t,e){return t.map(([n,s,a])=>{let r=e.get(n);return{poolAddress:n,poolId:r?.id,pool:r?.type,assetIn:s,assetOut:a}})}};var Mt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Mt||{}),Lt=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Lt||{}),ie=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(ie||{});var at=class extends st{isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,s)=>{let a=n[n.length-1].amountOut,r=s[s.length-1].amountOut;return a>r?-1:1});return e.find(n=>n.every(s=>s.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(n=>n.tradeFeeRange).length>0){let n=t.map(a=>a.tradeFeeRange?.[0]??a.tradeFeePct).reduce((a,r)=>a+r),s=t.map(a=>a.tradeFeeRange?.[1]??a.tradeFeePct).reduce((a,r)=>a+r);return[n,s]}}getPoolFeeRange(t){let e=t.min?h.toPct(t.min):void 0,n=t.max?h.toPct(t.max):void 0;if(e&&n)return[e,n]}async getBestSell(t,e,n){return this.getSell(t,e,n)}async getSellSpot(t){let e=t[t.length-1];if(t.length===1)return e.spotPrice;let n=t.map(i=>i.assetOutDecimals).reduce((i,o)=>i+o),s=t.map(i=>i.spotPrice).reduce((i,o)=>i*o),a=n-e.assetOutDecimals,r=Math.pow(10,a);return s/BigInt(r)}async getSell(t,e,n,s){let a=await super.getPools(),r=super.validateInput(t,e,a),i=super.getPaths(t,e,a);if(i.length===0)throw new Z(t,e);let o;if(s)o=await this.toSellSwaps(n,s,r);else{let O=await Promise.all(i.map(R=>this.toSellSwaps(n,R,r)));o=this.findBestSellRoute(O)}let l=o[0],u=o[o.length-1],d=this.isDirectTrade(o),m=await this.getSellSpot(o),p=u.amountOut,g=d?u.calculatedOut:this.calculateDelta0Y(l.amountIn,o,r),P=g-p,b=this.getRouteFeeRange(o),x=d?u.tradeFeePct:v.calculateSellFee(g,p),f=Math.pow(10,l.assetInDecimals),T=l.amountIn*m/BigInt(f),w=v.calculateDiffToRef(g,T);return{type:"Sell",amountIn:l.amountIn,amountOut:u.amountOut,spotPrice:m,tradeFee:P,tradeFeePct:x,tradeFeeRange:b,priceImpactPct:w,swaps:o,toHuman(){return{type:"Sell",amountIn:y.toDecimal(l.amountIn,l.assetInDecimals),amountOut:y.toDecimal(u.amountOut,u.assetOutDecimals),spotPrice:y.toDecimal(m,u.assetOutDecimals),tradeFee:y.toDecimal(P,u.assetOutDecimals),tradeFeePct:x,tradeFeeRange:b,priceImpactPct:w,swaps:o.map(O=>O.toHuman())}}}}calculateDelta0Y(t,e,n){let s=[];for(let a=0;a<e.length;a++){let r=e[a],i=n.get(r.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(r.assetIn,r.assetOut),l;a>0?l=s[a-1]:l=t;let u=i.calculateOutGivenIn(o,l);s.push(u)}return s[s.length-1]}async toSellSwaps(t,e,n){let s=[];for(let a=0;a<e.length;a++){let r=e[a],i=n.get(r.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(r.assetIn,r.assetOut),l;a>0?l=s[a-1].amountOut:l=typeof t=="string"?y.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(i,o.assetOut),{amountOut:d,calculatedOut:m,feePct:p,errors:g}=i.validateAndSell(o,l,u),P=this.getPoolFeeRange(u),b=i.spotPriceOutGivenIn(o),x=Math.pow(10,o.decimalsIn),f=l*b/BigInt(x),T=v.calculateDiffToRef(m,f);s.push({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:d,calculatedOut:m,spotPrice:b,tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===r.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===r.assetIn},toHuman(){return{...r,amountIn:y.toDecimal(l,o.decimalsIn),amountOut:y.toDecimal(d,o.decimalsOut),calculatedOut:y.toDecimal(m,o.decimalsOut),spotPrice:y.toDecimal(b,o.decimalsOut),tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}async getMostLiquidRoute(t,e){let n=await super.getPools(),s=super.validateInput(t,e,n),a=super.getPaths(t,e,n),o=n.filter(m=>m.tokens.some(p=>p.id===t&&p.id!==m.id)).map(m=>m.type==="Aave"?m.tokens:m.tokens.filter(p=>p.id===t)).map(m=>m.map(p=>p.balance).reduce((p,g)=>p+g)).sort((m,p)=>p<m?-1:1)[0],l=v.getFraction(o,.1),u=await Promise.all(a.map(m=>this.toSellSwaps(l,m,s)));return this.findBestSellRoute(u).map(m=>({poolAddress:m.poolAddress,poolId:m?.poolId,pool:m.pool,assetIn:m.assetIn,assetOut:m.assetOut}))}async getSpotPrice(t,e){let n=await super.getPools(),s=super.validateInput(t,e,n),a=await this.getMostLiquidRoute(t,e),r=await this.toSellSwaps("1",a,s),i=await this.getSellSpot(r),o=r[r.length-1].assetOutDecimals;return{amount:i,decimals:o}}findBestBuyRoute(t){let e=t.sort((n,s)=>{let a=n[0].amountIn,r=s[0].amountIn;return a>r?1:-1});return e.find(n=>n.every(s=>s.errors.length==0))||e[0]}async getBestBuy(t,e,n){return this.getBuy(t,e,n)}async getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let n=t.map(i=>i.assetInDecimals).reduce((i,o)=>i+o),s=t.map(i=>i.spotPrice).reduce((i,o)=>i*o),a=n-e.assetInDecimals,r=Math.pow(10,a);return s/BigInt(r)}async getBuy(t,e,n,s){let a=await super.getPools(),r=super.validateInput(t,e,a),i=super.getPaths(t,e,a);if(i.length===0)throw new Z(t,e);let o;if(s)o=await this.toBuySwaps(n,s,r);else{let O=await Promise.all(i.map(R=>this.toBuySwaps(n,R,r)));o=this.findBestBuyRoute(O)}let l=o[o.length-1],u=o[0],d=this.isDirectTrade(o),m=await this.getBuySpot(o),p=u.amountIn,g=d?u.calculatedIn:this.calculateDelta0X(l.amountOut,o,r),P=p-g,b=this.getRouteFeeRange(o),x=d?u.tradeFeePct:v.calculateBuyFee(g,p),f=Math.pow(10,l.assetOutDecimals),T=l.amountOut*m/BigInt(f),w;return g===0n?w=-100:w=v.calculateDiffToRef(T,g),{type:"Buy",amountOut:l.amountOut,amountIn:u.amountIn,spotPrice:m,tradeFee:P,tradeFeePct:x,tradeFeeRange:b,priceImpactPct:w,swaps:o,toHuman(){return{type:"Buy",amountOut:y.toDecimal(l.amountOut,l.assetOutDecimals),amountIn:y.toDecimal(u.amountIn,u.assetInDecimals),spotPrice:y.toDecimal(m,u.assetInDecimals),tradeFee:y.toDecimal(P,u.assetInDecimals),tradeFeePct:x,tradeFeeRange:b,priceImpactPct:w,swaps:o.map(O=>O.toHuman())}}}}calculateDelta0X(t,e,n){let s=[];for(let a=e.length-1;a>=0;a--){let r=e[a],i=n.get(r.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(r.assetIn,r.assetOut),l;a==e.length-1?l=t:l=s[0];let u=i.calculateInGivenOut(o,l);s.unshift(u)}return s[0]}async toBuySwaps(t,e,n){let s=[];for(let a=e.length-1;a>=0;a--){let r=e[a],i=n.get(r.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(r.assetIn,r.assetOut),l;a==e.length-1?l=typeof t=="string"?y.toBigInt(t,o.decimalsOut):t:l=s[0].amountIn;let u=await this.ctx.getPoolFees(i,o.assetOut),{amountIn:d,calculatedIn:m,feePct:p,errors:g}=i.validateAndBuy(o,l,u),P=this.getPoolFeeRange(u),b=i.spotPriceInGivenOut(o),x=Math.pow(10,o.decimalsOut),f=l*b/BigInt(x),T;m===0n?T=-100:T=v.calculateDiffToRef(f,m),s.unshift({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:d,calculatedIn:m,spotPrice:b,tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===r.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===r.assetIn},toHuman(){return{...r,amountOut:y.toDecimal(l,o.decimalsOut),amountIn:y.toDecimal(d,o.decimalsIn),calculatedIn:y.toDecimal(m,o.decimalsIn),spotPrice:y.toDecimal(b,o.decimalsIn),tradeFeePct:p,tradeFeeRange:P,priceImpactPct:T,errors:g}}})}return s}};var Me=6e3,re=1000000000000000n,vt=6,oe=-5,le=216e5,fu=3,Le=6;import{Enum as qe}from"polkadot-api";var M=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:s,poolId:a})=>s==="Stableswap"?{pool:qe("Stableswap",a),asset_in:e,asset_out:n}:{pool:qe(s),asset_in:e,asset_out:n})}};var it=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??re})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,s,a){let[r,i]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:u}=i,d=l[0],m=l[l.length-1],{assetInDecimals:p}=d,{assetOutDecimals:g}=m,P=Math.abs(u),b=this.getMinimumTradeCount(o,r),x=this.getOptimalTradeCount(P),f=a?Math.round(s/a):x,T=Math.ceil(s/b),w=Math.round(s/x),O=Math.round(s/f),R=o/BigInt(f),k=await this.router.getBestSell(t,e,R),U=o<r,Bt=[];U&&Bt.push("OrderTooSmall");let _t=k.amountOut*BigInt(f),Ht=this.toBlockPeriod(O),Gt=k.tradeFee*BigInt(f),je=M.build(l),ce={assetIn:t,assetOut:e,errors:Bt,frequencyMin:T,frequencyOpt:w,frequency:O,tradeCount:f,tradeFee:Gt,tradeImpactPct:k.priceImpactPct,tradePeriod:Ht,tradeRoute:je,type:"Dca"};return{...ce,amountIn:o,amountOut:_t,tradeAmountIn:k.amountIn,tradeAmountOut:k.amountOut,toHuman(){return{...ce,amountIn:y.toDecimal(o,p),amountOut:y.toDecimal(_t,g),tradeAmountIn:y.toDecimal(k.amountIn,p),tradeAmountOut:y.toDecimal(k.amountOut,g)}}}}async getMinimumOrderBudget(t){if(0===t)return this.minOrderBudget;let e=await this.router.getSpotPrice(0,t),n=10n**BigInt(12);if(e)return this.minOrderBudget*e.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(t,e){let n=e*2n/10n;if(n===0n)return 0;let s=t+n/2n;return Number(s/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[s,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:r,swaps:i,priceImpactPct:o}=a,l=i[0],u=i[i.length-1],{assetInDecimals:d}=l,{assetOutDecimals:m}=u,p=Math.abs(o),g=this.getTwapTradeCount(p),P=r/BigInt(g),b=await this.router.getBestSell(l.assetIn,u.assetOut,P),x=g===1,f=r<s,T=b.priceImpactPct<-5,w=[];f||x?w.push("OrderTooSmall"):T&&w.push("OrderImpactTooBig");let O=b.amountOut*BigInt(g),R=b.tradeFee*BigInt(g),k=M.build(i),U={assetIn:t,assetOut:e,errors:w,tradeCount:g,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:k,type:"TwapSell"};return{...U,amountIn:r,amountOut:O,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:R,toHuman(){return{...U,amountIn:y.toDecimal(r,d),amountOut:y.toDecimal(O,m),tradeAmountIn:y.toDecimal(b.amountIn,d),tradeAmountOut:y.toDecimal(b.amountOut,m),tradeFee:y.toDecimal(R,m)}}}}async getTwapBuyOrder(t,e,n){let[s,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:r,swaps:i,priceImpactPct:o}=a,l=i[0],u=i[i.length-1],{assetInDecimals:d}=l,{assetOutDecimals:m}=u,p=Math.abs(o),g=this.getTwapTradeCount(p),P=r/BigInt(g),b=await this.router.getBestBuy(l.assetIn,u.assetOut,P),x=b.amountIn*BigInt(g),f=g===1,T=x<s,w=b.priceImpactPct<-5,O=[];T||f?O.push("OrderTooSmall"):w&&O.push("OrderImpactTooBig");let R=b.tradeFee*BigInt(g),k=M.build(i),U={assetIn:t,assetOut:e,errors:O,tradeCount:g,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:k,type:"TwapBuy"};return{...U,amountIn:x,amountOut:r,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:R,toHuman(){return{...U,amountIn:y.toDecimal(x,d),amountOut:y.toDecimal(r,m),tradeAmountIn:y.toDecimal(b.amountIn,d),tradeAmountOut:y.toDecimal(b.amountOut,m),tradeFee:y.toDecimal(R,d)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,n=Math.round(e);return Math.max(n,6)}};var Ve={};S(Ve,{BIG_10:()=>Ge,BIG_BILL:()=>Ue,StakingApi:()=>Ot,StakingClient:()=>At});import{encodeAddress as na}from"@polkadot/util-crypto";import{stringToU8a as sa}from"@polkadot/util";import{calculate_accumulated_rps as aa,calculate_period_number as He,calculate_rewards as ia}from"@galacticcouncil/math-staking";import rt from"big.js";var Ge=rt(10),Ue=rt(Ge.pow(12));function ra(c){return na(sa(("modl"+c).padEnd(32,"\0")),63)}var Ot=class{client;constructor(t){this.client=t}async getFreePotBalance(){let t=await this.client.getPalletId(),e=ra(t);return this.client.getBalance(e)}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]),s=e?.created_at,a=await n.reduce(async(r,[i,o])=>{let l=await r,u=i,d=o.amount,m=o.conviction.toString(),p=await this.client.getReferendumInfo(u);return p&&(p.type==="Approved"||p.type==="Rejected")&&l.push({id:u,amount:d,conviction:m}),l},Promise.resolve([]));return{stake:e?.stake,rewardPerStake:e?.reward_per_stake,createdAt:s,actionPoints:e?.action_points,accumulatedUnpaidRewards:e?.accumulated_unpaid_rewards,accumulatedSlashPoints:e?.accumulated_slash_points,accumulatedLockedRewards:e?.accumulated_locked_rewards,votes:a}}async getStake(t){let e=await this.client.getNFTCollectionId(),[n,s]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),a=s.find(r=>r)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:a,stakePosition:a?await this.getStakingPosition(a):void 0}}async getRewards(t){let e=await this.getStake(t),{potReservedBalance:n,accumulatedRewardPerStake:s,totalStake:a,stakePosition:r}=e;if(!r)return;let[i,o,l,u,d]=await Promise.all([this.client.getBlockNumber(),this.getFreePotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getSixBlockSince()]),m=rt(o.toString()).minus(n.toString()),p=s.toString(),g=i.toString(),P=rt(g).plus(1).toString();m.gt(0)&&a>0&&(p=aa(s.toString(),m.toString(),a.toString()));let b=He(l.toString(),g,d??P),x=He(l.toString(),r.createdAt?.toString()??"",d??P),f=ia(p,r.rewardPerStake?.toString()??"",r.stake?.toString()??""),T=rt(f).plus(r.accumulatedUnpaidRewards?.toString()||"0").plus(r.accumulatedLockedRewards?.toString()||"0");if(!rt(b).minus(x).lte(u.toString()))return T.div(Ue).toString()}};var At=class extends _{async getBalance(t){return(await this.api.query.System.Account.getValue(t)).data.free}async getBlockNumber(){return await this.api.query.System.Number.getValue({at:"best"})}async getPalletId(){let t=this.api.constants.Staking.PalletId;return(await t()).asText()}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:r})=>{let[i,o,l]=r;return{address:i,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var Ye={};S(Ye,{TxBuilderFactory:()=>lt});import{Enum as Xe}from"polkadot-api";function We(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var ot=class extends _{evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evmClient=e??new F,this.balanceClient=new q(t),this.aaveUtils=new Y(this.evmClient)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:n=>this.dryRun(n,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:Wt})}async dryRun(t,e){let n=Xe("Signed",t),s=Xe("system",n),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall),i=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(i){let o=We(i.value);throw new Error("Dry run execution error!",{cause:o})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var qt=class extends ot{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],a=await this.balanceClient.getBalance(this.beneficiary,s);return t>=a-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],a=n[n.length-1],r=v.getFraction(t,this.slippagePct),i=s.assetIn,o=a.assetOut,l=t+r,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.buy({asset_in:i,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:i,asset_out:o,amount_out:e,max_amount_in:l,route:M.build(n)}),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],a=n[n.length-1],r=v.getFraction(e,this.slippagePct),i=s.assetIn,o=a.assetOut,l=e-r,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.sell({asset_in:i,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:i,asset_out:o,amount_in:t,min_amount_out:l,route:M.build(n)}),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,n=e[0],s=e[e.length-1],a=v.getFraction(t,this.slippagePct),r=n.assetIn,i=s.assetOut,o=t-a,l=this.api.tx.Router.sell_all({asset_in:r,asset_out:i,min_amount_out:o,route:M.build(e)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as ue}from"polkadot-api";var Nt=class extends ot{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradePeriod:a,tradeRoute:r}=this.order,i=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:a,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ue("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:0n,route:r})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",i)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:a,tradePeriod:r,tradeRoute:i}=this.order,o=v.getFraction(a,this.slippagePct),l=a-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ue("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:l,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:a,tradePeriod:r,tradeRoute:i}=this.order,o=v.getFraction(s,this.slippagePct),l=s+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ue("Buy",{asset_in:e,asset_out:n,amount_out:a,max_amount_in:l,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var lt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e??new F}trade(t){return new qt(this.client,this.evmClient).setTrade(t)}order(t){return new Nt(this.client,this.evmClient).setOrder(t)}};async function _c(c,t,e){let n=new J(c),[s,a]=await Promise.all([n.getBlockTime(),n.getMinOrderBudget()]),r=t??new F,i=new nt(c).withAave().withOmnipool().withStableswap().withXyk(),o=new Y(r),l=new at(i),u=new it(l,{blockTime:s,minBudgetInNative:a}),d=new Ot(e??new At(c));return{api:{aave:o,router:l,scheduler:u,staking:d},client:{asset:new $(c),balance:new q(c),evm:r},ctx:{pool:i},tx:new lt(c,r),destroy:()=>{i.destroy()}}}export{Ie as aave,pe as api,y as big,Oe as client,Pe as const,_c as createSdkContext,K as erc20,Ae as error,ye as evm,h as fmt,Et as h160,X as json,v as math,Ce as pool,Ne as sor,Ve as staking,Ye as tx,we 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};
|
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;
|
package/build/types/factory.d.ts
CHANGED
|
@@ -5,13 +5,11 @@ import { EvmClient } from './evm';
|
|
|
5
5
|
import { PoolContextProvider } from './pool';
|
|
6
6
|
import { TradeRouter, TradeScheduler } from './sor';
|
|
7
7
|
import { TxBuilderFactory } from './tx';
|
|
8
|
-
import { StakingApi, StakingClient } from './staking';
|
|
9
8
|
export type SdkCtx = {
|
|
10
9
|
api: {
|
|
11
10
|
aave: AaveUtils;
|
|
12
11
|
router: TradeRouter;
|
|
13
12
|
scheduler: TradeScheduler;
|
|
14
|
-
staking: StakingApi;
|
|
15
13
|
};
|
|
16
14
|
client: {
|
|
17
15
|
asset: AssetClient;
|
|
@@ -24,4 +22,4 @@ export type SdkCtx = {
|
|
|
24
22
|
tx: TxBuilderFactory;
|
|
25
23
|
destroy: () => void;
|
|
26
24
|
};
|
|
27
|
-
export declare function createSdkContext(client: PolkadotClient, evmClient?: EvmClient
|
|
25
|
+
export declare function createSdkContext(client: PolkadotClient, evmClient?: EvmClient): Promise<SdkCtx>;
|
package/build/types/index.d.ts
CHANGED
|
@@ -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/package.json
CHANGED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import Big from 'big.js';
|
|
2
|
-
import { StakingClient } from './StakingClient';
|
|
3
|
-
export declare const BIG_10: Big.Big;
|
|
4
|
-
export declare const BIG_BILL: Big.Big;
|
|
5
|
-
export declare class StakingApi {
|
|
6
|
-
private readonly client;
|
|
7
|
-
constructor(client: StakingClient);
|
|
8
|
-
getFreePotBalance(): Promise<bigint>;
|
|
9
|
-
getStakingPosition(id: bigint): Promise<{
|
|
10
|
-
stake: bigint | undefined;
|
|
11
|
-
rewardPerStake: bigint | undefined;
|
|
12
|
-
createdAt: number | undefined;
|
|
13
|
-
actionPoints: bigint | undefined;
|
|
14
|
-
accumulatedUnpaidRewards: bigint | undefined;
|
|
15
|
-
accumulatedSlashPoints: bigint | undefined;
|
|
16
|
-
accumulatedLockedRewards: bigint | undefined;
|
|
17
|
-
votes: {
|
|
18
|
-
id: number;
|
|
19
|
-
amount: bigint;
|
|
20
|
-
conviction: string;
|
|
21
|
-
}[];
|
|
22
|
-
}>;
|
|
23
|
-
getStake(address: string): Promise<{
|
|
24
|
-
totalStake: bigint;
|
|
25
|
-
accumulatedRewardPerStake: bigint;
|
|
26
|
-
potReservedBalance: bigint;
|
|
27
|
-
positionId: bigint | undefined;
|
|
28
|
-
stakePosition: {
|
|
29
|
-
stake: bigint | undefined;
|
|
30
|
-
rewardPerStake: bigint | undefined;
|
|
31
|
-
createdAt: number | undefined;
|
|
32
|
-
actionPoints: bigint | undefined;
|
|
33
|
-
accumulatedUnpaidRewards: bigint | undefined;
|
|
34
|
-
accumulatedSlashPoints: bigint | undefined;
|
|
35
|
-
accumulatedLockedRewards: bigint | undefined;
|
|
36
|
-
votes: {
|
|
37
|
-
id: number;
|
|
38
|
-
amount: bigint;
|
|
39
|
-
conviction: string;
|
|
40
|
-
}[];
|
|
41
|
-
} | undefined;
|
|
42
|
-
}>;
|
|
43
|
-
getRewards(account: string): Promise<string | undefined>;
|
|
44
|
-
}
|
|
@@ -1,122 +0,0 @@
|
|
|
1
|
-
import { Papi } from '../api';
|
|
2
|
-
export declare class StakingClient extends Papi {
|
|
3
|
-
getBalance(address: string): Promise<bigint>;
|
|
4
|
-
getBlockNumber(): Promise<number>;
|
|
5
|
-
getPalletId(): Promise<string>;
|
|
6
|
-
getPeriodLength(): Promise<number>;
|
|
7
|
-
getUnclaimablePeriods(): Promise<bigint>;
|
|
8
|
-
getNFTCollectionId(): Promise<bigint>;
|
|
9
|
-
getStaking(): Promise<{
|
|
10
|
-
total_stake: bigint;
|
|
11
|
-
accumulated_reward_per_stake: bigint;
|
|
12
|
-
pot_reserved_balance: bigint;
|
|
13
|
-
}>;
|
|
14
|
-
getUniques(address: string, collectionId: bigint): Promise<{
|
|
15
|
-
address: import("polkadot-api").SS58String;
|
|
16
|
-
collectionId: bigint;
|
|
17
|
-
itemId: bigint;
|
|
18
|
-
}[]>;
|
|
19
|
-
getStakingPositionsValue(id: bigint): Promise<{
|
|
20
|
-
stake: bigint;
|
|
21
|
-
action_points: bigint;
|
|
22
|
-
reward_per_stake: bigint;
|
|
23
|
-
created_at: number;
|
|
24
|
-
accumulated_slash_points: bigint;
|
|
25
|
-
accumulated_unpaid_rewards: bigint;
|
|
26
|
-
accumulated_locked_rewards: bigint;
|
|
27
|
-
} | undefined>;
|
|
28
|
-
getStakingVotes(id: bigint): Promise<[number, {
|
|
29
|
-
amount: bigint;
|
|
30
|
-
conviction: import("@galacticcouncil/descriptors").VotingConviction;
|
|
31
|
-
}][]>;
|
|
32
|
-
getReferendumInfo(key: number): Promise<import("polkadot-api").Enum<{
|
|
33
|
-
Ongoing: {
|
|
34
|
-
"track": number;
|
|
35
|
-
"origin": import("polkadot-api").Enum<{
|
|
36
|
-
system: import("@galacticcouncil/descriptors").DispatchRawOrigin;
|
|
37
|
-
Council: import("polkadot-api").Enum<{
|
|
38
|
-
"Members": import("polkadot-api").FixedSizeArray<2, number>;
|
|
39
|
-
"Member": import("polkadot-api").SS58String;
|
|
40
|
-
"_Phantom": undefined;
|
|
41
|
-
}>;
|
|
42
|
-
TechnicalCommittee: import("polkadot-api").Enum<{
|
|
43
|
-
"Members": import("polkadot-api").FixedSizeArray<2, number>;
|
|
44
|
-
"Member": import("polkadot-api").SS58String;
|
|
45
|
-
"_Phantom": undefined;
|
|
46
|
-
}>;
|
|
47
|
-
Origins: import("polkadot-api").Enum<{
|
|
48
|
-
"WhitelistedCaller": undefined;
|
|
49
|
-
"ReferendumCanceller": undefined;
|
|
50
|
-
"ReferendumKiller": undefined;
|
|
51
|
-
"GeneralAdmin": undefined;
|
|
52
|
-
"OmnipoolAdmin": undefined;
|
|
53
|
-
"Treasurer": undefined;
|
|
54
|
-
"Spender": undefined;
|
|
55
|
-
"Tipper": undefined;
|
|
56
|
-
"EconomicParameters": undefined;
|
|
57
|
-
}>;
|
|
58
|
-
Ethereum: import("polkadot-api").Enum<{
|
|
59
|
-
"EthereumTransaction": import("polkadot-api").FixedSizeBinary<20>;
|
|
60
|
-
}>;
|
|
61
|
-
PolkadotXcm: import("@galacticcouncil/descriptors").XcmPalletOrigin;
|
|
62
|
-
CumulusXcm: import("polkadot-api").Enum<{
|
|
63
|
-
"Relay": undefined;
|
|
64
|
-
"SiblingParachain": number;
|
|
65
|
-
}>;
|
|
66
|
-
Void: undefined;
|
|
67
|
-
}>;
|
|
68
|
-
"proposal": import("@galacticcouncil/descriptors").PreimagesBounded;
|
|
69
|
-
"enactment": import("@galacticcouncil/descriptors").TraitsScheduleDispatchTime;
|
|
70
|
-
"submitted": number;
|
|
71
|
-
"submission_deposit": {
|
|
72
|
-
amount: bigint;
|
|
73
|
-
who: import("polkadot-api").SS58String;
|
|
74
|
-
};
|
|
75
|
-
"decision_deposit"?: {
|
|
76
|
-
amount: bigint;
|
|
77
|
-
who: import("polkadot-api").SS58String;
|
|
78
|
-
} | undefined;
|
|
79
|
-
"deciding"?: ({
|
|
80
|
-
"since": number;
|
|
81
|
-
"confirming"?: number | undefined;
|
|
82
|
-
}) | undefined;
|
|
83
|
-
"tally": {
|
|
84
|
-
ayes: bigint;
|
|
85
|
-
nays: bigint;
|
|
86
|
-
support: bigint;
|
|
87
|
-
};
|
|
88
|
-
"in_queue": boolean;
|
|
89
|
-
"alarm"?: ([number, import("polkadot-api").FixedSizeArray<2, number>]) | undefined;
|
|
90
|
-
};
|
|
91
|
-
Approved: [number, {
|
|
92
|
-
amount: bigint;
|
|
93
|
-
who: import("polkadot-api").SS58String;
|
|
94
|
-
} | undefined, {
|
|
95
|
-
amount: bigint;
|
|
96
|
-
who: import("polkadot-api").SS58String;
|
|
97
|
-
} | undefined];
|
|
98
|
-
Rejected: [number, {
|
|
99
|
-
amount: bigint;
|
|
100
|
-
who: import("polkadot-api").SS58String;
|
|
101
|
-
} | undefined, {
|
|
102
|
-
amount: bigint;
|
|
103
|
-
who: import("polkadot-api").SS58String;
|
|
104
|
-
} | undefined];
|
|
105
|
-
Cancelled: [number, {
|
|
106
|
-
amount: bigint;
|
|
107
|
-
who: import("polkadot-api").SS58String;
|
|
108
|
-
} | undefined, {
|
|
109
|
-
amount: bigint;
|
|
110
|
-
who: import("polkadot-api").SS58String;
|
|
111
|
-
} | undefined];
|
|
112
|
-
TimedOut: [number, {
|
|
113
|
-
amount: bigint;
|
|
114
|
-
who: import("polkadot-api").SS58String;
|
|
115
|
-
} | undefined, {
|
|
116
|
-
amount: bigint;
|
|
117
|
-
who: import("polkadot-api").SS58String;
|
|
118
|
-
} | undefined];
|
|
119
|
-
Killed: number;
|
|
120
|
-
}> | undefined>;
|
|
121
|
-
getSixBlockSince(): Promise<string>;
|
|
122
|
-
}
|