@galacticcouncil/sdk 9.3.0 → 9.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var lt=Object.defineProperty;var mr=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var dr=Object.prototype.hasOwnProperty;var gr=(l,e)=>{for(var t in e)lt(l,t,{get:e[t],enumerable:!0})},hr=(l,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of pr(e))!dr.call(l,s)&&s!==t&&lt(l,s,{get:()=>e[s],enumerable:!(r=mr(e,s))||r.enumerable});return l};var fr=l=>hr(lt({},"__esModule",{value:!0}),l);var kr={};gr(kr,{AMOUNT_MAX:()=>rr,AaveClient:()=>se,AavePool:()=>Te,AavePoolClient:()=>Be,AaveUtils:()=>J,AssetClient:()=>Z,AssetNotFound:()=>Pt,BASILISK_PARACHAIN_ID:()=>Vr,BalanceClient:()=>q,BigNumber:()=>v.BigNumber,CachingPoolService:()=>ue,ChainParams:()=>ne,DECIMAL_PLACES:()=>Lt,DENOMINATOR:()=>pt,ERC20:()=>z,EvmClient:()=>ve,FarmClient:()=>He,H160:()=>ee,HUB_ASSET_ID:()=>Pe,HYDRADX_PARACHAIN_ID:()=>jr,HYDRADX_SS58_PREFIX:()=>j,INFINITY:()=>yr,LbpMath:()=>W,LbpPool:()=>Ie,LbpPoolClient:()=>Ae,ONE:()=>D,OmniMath:()=>N,OmniPool:()=>_e,OmniPoolClient:()=>Ne,PolkadotApiClient:()=>L,PoolConfigNotFound:()=>yt,PoolError:()=>re,PoolFactory:()=>ce,PoolNotFound:()=>xe,PoolService:()=>le,PoolType:()=>k,ProviderConfigNotFound:()=>xt,RUNTIME_DECIMALS:()=>be,RouteNotFound:()=>te,Router:()=>me,SYSTEM_ASSET_DECIMALS:()=>Dt,SYSTEM_ASSET_ID:()=>M,StableMath:()=>C,StableSwap:()=>Ee,StableSwapClient:()=>De,StorageConfigNotFound:()=>bt,SubscriptionNotSupported:()=>St,TRADEABLE_DEFAULT:()=>Se,TradeOrderError:()=>Nt,TradeOrderType:()=>rt,TradeRouteBuilder:()=>G,TradeRouter:()=>de,TradeScheduler:()=>ge,TradeType:()=>tt,TxBuilderFactory:()=>fe,XykMath:()=>V,XykPool:()=>Fe,XykPoolClient:()=>Re,ZERO:()=>S,bnFormatter:()=>_r,bnum:()=>p,calculateBuyFee:()=>_t,calculateDiffToAvg:()=>Er,calculateDiffToRef:()=>pe,calculateSellFee:()=>At,createChain:()=>vt,createSdkContext:()=>Dr,findNestedKey:()=>Ot,findNestedObj:()=>Ar,getFraction:()=>Q,isEvmAccount:()=>kt,isEvmAddress:()=>Ct,isSs58Address:()=>Mt,scale:()=>_,toBn:()=>Pr,toDecimals:()=>T});module.exports=fr(kr);var Ge=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var ut=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Et="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",ct="0x112b087b60C1a166130d59266363C45F8aa99db0",mt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ye=1000000n;var Hr=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var se=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:ut,address:ct,args:[mt],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:ut,address:ct,args:[mt,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:Ge,address:Et,args:[e],functionName:"getUserAccountData"})}};var K=require("@polkadot/util-crypto"),ie=require("@polkadot/util"),Y=require("buffer");var Vr=2090,pt=1e3,Pe="1",jr=2034,j=63,be=18,M="0",Dt=12,Se=15;var dt="ETH\0";function kt(l){if(!l)return!1;try{let e=(0,K.decodeAddress)(l,!0),t=Y.Buffer.from(dt);return Y.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Ct(l){return!!/^0x[a-fA-F0-9]{40}$/.test(l)}function Mt(l){try{let e=(0,ie.isHex)(l)?(0,ie.hexToU8a)(l):(0,K.decodeAddress)(l);return(0,K.encodeAddress)(e),!0}catch{return!1}}var ee=class l{static toAccount=e=>{let t=Y.Buffer.from(e.slice(2),"hex"),r=Y.Buffer.from(dt);return(0,K.encodeAddress)(new Uint8Array(Y.Buffer.concat([r,t,Y.Buffer.alloc(8)])),63)};static fromAccount=e=>{let t=(0,K.decodeAddress)(e),r=Y.Buffer.from(dt),s=t.slice(r.length,-8);return"0x"+Y.Buffer.from(s).toString("hex")};static fromSS58=e=>{let r=(0,K.decodeAddress)(e).slice(0,20);return(0,ie.u8aToHex)(r)};static fromAny=e=>{if(Ct(e))return e;if(kt(e))return l.fromAccount(e);if(Mt(e))return l.fromSS58(e);throw new Error("Unknown address type")}};var z=class{static fromAssetId(e){let t=Number(e),r=Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.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"),r=Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};var v=require("bignumber.js"),Lt=12;v.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Lt});var S=p(0),D=p(1),yr=p("Infinity");function _(l,e){let t=new v.BigNumber(e.toString()),r=new v.BigNumber(10).pow(t);return l.times(r)}function p(l){return new v.BigNumber(l.toString())}function Pr(l,e){let t=p(l);return _(t,e)}function T(l,e){return l.shiftedBy(-1*e).toString()}var We=p("1e27"),br=p("1.01"),Sr=p("31536000"),J=class{client;constructor(e){this.client=new se(e)}async getSummary(e){let t=ee.fromAny(e),[r,s,i,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[o]=r,[a,u]=s,[c,m,h,d,g,y]=i,f=p(y).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN),x=p(c),b=p(m),A=[];for(let B of a){let w=B.underlyingAsset.toLowerCase(),I=o.find(({underlyingAsset:cr})=>cr.toLowerCase()===w);if(!I)throw new Error("Missing pool reserve for "+w);let E=p(B.scaledATokenBalance),H=p(I.liquidityIndex),Le=p(I.liquidityRate),qe=p(I.availableLiquidity),nt=p(I.priceInMarketReferenceCurrency),ot=n+6,at=this.calculateLinearInterest(Le,I.lastUpdateTimestamp,ot),Ue=H.multipliedBy(at).dividedBy(We).decimalPlaces(0,v.BigNumber.ROUND_DOWN),or=E.multipliedBy(Ue).dividedBy(We).decimalPlaces(0,v.BigNumber.ROUND_DOWN),ar=p(u!==0&&u===I.eModeCategoryId?I.eModeLiquidationThreshold:I.reserveLiquidationThreshold).div(1e4),lr=I.usageAsCollateralEnabled&&B.usageAsCollateralEnabledOnUser&&p(B.scaledATokenBalance).gt(0),ur=z.toAssetId(w);A.push({aTokenBalance:or,availableLiquidity:qe,decimals:Number(I.decimals),isCollateral:lr,priceInRef:nt,reserveId:ur,reserveAsset:w,reserveLiquidationThreshold:ar})}return{healthFactor:f.toNumber(),totalCollateral:x,totalDebt:b,reserves:A}}async hasBorrowPositions(e){let t=ee.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=ee.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,n,o,a,u]=r;return p(u).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=z.fromAssetId(t),a=n.find(x=>x.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:u,isCollateral:c,priceInRef:m,reserveLiquidationThreshold:h}=a,d=_(p(r),u).decimalPlaces(0,1),g=c?d.multipliedBy(m).dividedBy(p(10).pow(u)).decimalPlaces(0,v.BigNumber.ROUND_DOWN):S,y=s.minus(g);return y.lte(0)?0:y.multipliedBy(h).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=z.fromAssetId(t),a=n.find(f=>f.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:u,priceInRef:c,reserveLiquidationThreshold:m}=a,d=_(p(r),u).decimalPlaces(0,1).multipliedBy(c).dividedBy(p(10).pow(u)).decimalPlaces(0,v.BigNumber.ROUND_DOWN),g=s.plus(d);return g.lte(0)?0:g.multipliedBy(m).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),n=z.fromAssetId(t),o=s.find(a=>a.reserveAsset===n);if(!o)throw new Error("Missing reserve data for "+n);return this.calculateWithdrawMax(o,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let n of r){let o=this.calculateWithdrawMax(n,t,s);n.reserveId&&(i[n.reserveId]=o)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:n,priceInRef:o,reserveLiquidationThreshold:a,isCollateral:u}=e,c=s;if(u&&t.gt(0)){let h=p(r).minus(br);if(h.gt(0)){let g=h.multipliedBy(t).dividedBy(a).decimalPlaces(0,v.BigNumber.ROUND_DOWN).dividedBy(o).multipliedBy(p(10).pow(n)).decimalPlaces(0,v.BigNumber.ROUND_DOWN);c=v.BigNumber.minimum(s,g)}else c=S}return{amount:v.BigNumber.minimum(c,i),decimals:n}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?We:e.multipliedBy(s).dividedBy(Sr).plus(We).decimalPlaces(0,v.BigNumber.ROUND_DOWN)}};function qt(l){switch(l){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var ds=require("@galacticcouncil/api-augment/hydradx"),gs=require("@galacticcouncil/api-augment/basilisk"),L=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");qt(r)&&console.log(e,...t)}};var Z=class extends L{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==M){let m=this.api.consts.balances.existentialDeposit;return{id:M,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:o,existentialDeposit:a}=t,{symbol:u,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:u,decimals:c,icon:u,type:n.toHuman(),isSufficient:o?o.toHuman():!0,location:s?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,r,s){let[i,n]=s,{assetType:o,isSufficient:a,existentialDeposit:u}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,r),h=n.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(h)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:m,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:u.toString(),underlyingAssetId:i.toString(),maturity:h}}getShares(e,t,r,s){let{assets:i}=s,{name:n,symbol:o,assetType:a,isSufficient:u,existentialDeposit:c}=t,h=i.map(y=>y.toString()).map(y=>{let{symbol:f}=this.getToken(y,t,r);return[y,f]}),d=Object.fromEntries(h),g=Object.values(d);return{id:e,name:g.join(", "),symbol:o?.isSome?o.toHuman():n.toHuman(),decimals:18,icon:g.join("/"),type:a.toString(),isSufficient:u.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),n=r?.find(o=>o.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:n}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,i,n,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(r),u=this.normalizeMetadata(a,o),c=a.map(([{args:[m]},h])=>{let d=h.unwrap(),g=s.get(m.toString()),{assetType:y}=d;switch(y.toString()){case"Bond":let f=n.get(m.toString());return this.getBond(m.toString(),d,u,f);case"StableSwap":let x=i.get(m.toString());return this.getShares(m.toString(),d,u,x);case"External":return this.getExternal(m.toString(),d,t,g);default:return this.getToken(m.toString(),d,u,g)}});return e?c:c.filter(m=>this.isValidAsset(m))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var q=class extends L{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===M?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:i})}async getErc20Balance(e,t){let{free:r,reserved:s,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:r,feeFrozen:0n,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(M,this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,o]})=>[n.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,u)=>{let c=this.calculateFreeBalance(a),m=i[u][1];o.push([m,c])}),t(o)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,u])=>{let{assetType:c}=u.unwrap();return c.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),n=async()=>{let o=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:i}=e,n=new v.BigNumber(t),o=new v.BigNumber(r||i),a=new v.BigNumber(s||0n),u=o.gt(a)?o:a;return n.minus(u)}};var ne=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),p(this._minOrderBudget)}};var gt=require("@galacticcouncil/math-liquidity-mining"),Ut=require("@polkadot/types"),ht=require("@polkadot/util"),ft=require("@polkadot/util-crypto");var He=class extends L{balanceClient;constructor(e){super(e),this.balanceClient=new q(e)}secondsInYear=new v.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),u=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),g=u.rewardCurrency.toString(),y=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:y.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),u=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),g=u.rewardCurrency.toString(),y=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:y.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new v.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),o=n.price.n.toString(),a=n.price.d.toString(),u;return Number(t)<Number(r)?u=(0,gt.fixed_from_rational)(o,a):u=(0,gt.fixed_from_rational)(a,o),u}getGlobalRewardPerPeriod(e,t,r,s){let n=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return n.gte(r)?r:n}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return(0,ht.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Ut.GenericAccountId32(e,this.padEndU8a((0,ht.u8aConcat)(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,ft.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,ft.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:o,globalFarm:a,priceAdjustment:u,potBalance:c})=>{let m=new v.BigNumber(a.totalSharesZ.toString()),h=a.plannedYieldingPeriods.toString(),d=new v.BigNumber(a.yieldPerPeriod.toString()),g=new v.BigNumber(a.maxRewardPerPeriod.toString()),y=a.blocksPerPeriod.toString(),f=new v.BigNumber(o.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new v.BigNumber(r).times(y)),b;if(m.isZero())b=d.times(f).times(x);else{let E=this.getGlobalRewardPerPeriod(m,d,g,u);b=this.getPoolYieldPerPeriod(E,f,m,u).times(x)}let A=new v.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),B=g.times(h),w=c?A.plus(c):B;return A.div(w).gte(.999)?S:b.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),S).toString():void 0}};var xe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},yt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},te=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Pt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},bt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},St=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},xt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Gt=require("viem"),xr=["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"],vt=l=>{let e=l.__internal__endpoints,t=e.some(s=>xr.includes(s)),r=e.map(s=>s.replace("wss://","https://").replace("ws://","http://"));return(0,Gt.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:t?"https://explorer.evm.hydration.cloud":"https://explorer.nice.hydration.cloud"}},testnet:!t})};var $=require("viem");function Wt(l){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return l.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var ve=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=vt(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,$.createPublicClient)({chain:this.chain,transport:(0,$.http)()})}getWsProvider(){return(0,$.createPublicClient)({chain:this.chain,transport:Wt(this.wsProvider)})}getSigner(e){return(0,$.createWalletClient)({account:e,chain:this.chain,transport:(0,$.custom)(window.ethereum)})}};var we=(l,e)=>l===e?0:l==null?e==null?0:-1:e==null?l==null?0:1:typeof l.compare=="function"?l.compare(e):typeof e.compare=="function"?-e.compare(l):l<e?-1:l>e?1:0;var ze=(l,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(l(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var vr=ze(()=>"illegal argument(s)"),Ht=l=>{throw new vr(l)};var wr=ze(()=>"index out of bounds"),wt=l=>{throw new wr(l)},Xe=(l,e,t)=>(l<e||l>=t)&&wt(l);var zt=23283064365386963e-26,Ye=class{float(e=1){return this.int()*zt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*zt-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var $e=class extends Ye{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var Xt=new $e(Math.random);var Yt=l=>l!=null&&typeof l!="function"&&l.length!==void 0;var $t=Object.getPrototypeOf({}),Ve="function",Vt="string",oe=(l,e)=>{let t;if(l===e)return!0;if(l!=null){if(typeof l.equiv===Ve)return l.equiv(e)}else return l==e;if(e!=null){if(typeof e.equiv===Ve)return e.equiv(l)}else return l==e;return typeof l===Vt||typeof e===Vt?!1:(t=Object.getPrototypeOf(l),(t==null||t===$t)&&(t=Object.getPrototypeOf(e),t==null||t===$t)?Ir(l,e):typeof l!==Ve&&l.length!==void 0&&typeof e!==Ve&&e.length!==void 0?Tr(l,e):l instanceof Set&&e instanceof Set?Or(l,e):l instanceof Map&&e instanceof Map?Br(l,e):l instanceof Date&&e instanceof Date?l.getTime()===e.getTime():l instanceof RegExp&&e instanceof RegExp?l.toString()===e.toString():l!==l&&e!==e)},Tr=(l,e,t=oe)=>{let r=l.length;if(r===e.length)for(;r-- >0&&t(l[r],e[r]););return r<0},Or=(l,e,t=oe)=>l.size===e.size&&t([...l.keys()].sort(),[...e.keys()].sort()),Br=(l,e,t=oe)=>l.size===e.size&&t([...l].sort(),[...e].sort()),Ir=(l,e,t=oe)=>{if(Object.keys(l).length!==Object.keys(e).length)return!1;for(let r in l)if(!e.hasOwnProperty(r)||!t(l[r],e[r]))return!1;return!0};var Tt=class{value;constructor(e){this.value=e}deref(){return this.value}};var jt=l=>l instanceof Tt;var je=class l{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Kt("next",this._head)}reverseIterator(){return Kt("prev",this.tail)}clear(){this.release()}compare(e,t=we){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,n=0;for(;r-- >0&&n===0;)n=t(s.value,i.value),s=s.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof l||Yt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!oe(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||we;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!jt(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&wt(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*Kt(l,e){for(;e;)yield e.value,e=e[l]}var Ke=class l extends je{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new l(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new l}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(Xe(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(Xe(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new l,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==s&&n.next?i(n.next):void 0}});return r?i(r):void 0}shuffle(e,t=Xt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&Ht("invalid indices: ${from} / ${to}");let i=new l,n=this.nthCell(r);for(;n&&++r<=s;)i.push(n.value),n=n.next;return i}sort(e=we){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,n=0;for(let a=0;a<t&&(n++,i=i.next,!!i);a++);let o=t;for(;n>0||o>0&&i;){let a;n===0?(a=i,i=i.next,o--):!i||o===0||e(r.value,i.value)<=0?(a=r,r=r.next,n--):(a=i,i=i.next,o--),this._tail?this._tail.next=a:this._head=a,a.prev=this._tail,this._tail=a}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),Xe(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new l;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let n of r)this.insertBefore(s,n);else for(let n of r)this.push(n);return i}};var ae=class l{map;items;opts;_size;constructor(e,t){let r={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=r.map(),this.items=new Ke,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new l(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e),i=Math.max(0,r-(s?s.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(s,e,t,r):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let r=this.map.get(e);return r?this.resetEntry(r):this.set(e,await t())}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let{release:e,maxsize:t,maxlen:r}=this.opts;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e?.(s.k,s.v),this._size-=s.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,r,s){e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var Je=class l extends ae{constructor(e,t){super(e,{ttl:60*60*1e3,autoExtend:!1,...t})}empty(){return new l(null,this.opts)}has(e){return this.get(e)!==void 0}get(e,t){let r=this.map.get(e);if(r){if(r.value.t>=Date.now())return this.resetEntry(r);this.removeEntry(r)}return t}set(e,t,r=this.opts.ttl){let s=this.opts.ksize(e)+this.opts.vsize(t),i=this.map.get(e),n=Math.max(0,s-(i?i.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(i,e,t,s,r):this._size-=n,t}async getSet(e,t,r=this.opts.ttl){let s=this.get(e);return s!==void 0?s:this.set(e,await t(),r)}prune(){let e=Date.now(),t=this.items.head,r=0;for(;t;)t.value.t<e&&(this.removeEntry(t),r++),t=t.next;return r}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,r=Date.now(),s=this.items.head;for(;s&&(this._size>t||this.length>=e);)s.value.t<r&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(e,t,r,s,i=this.opts.ttl){let n=Date.now()+i;e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,e.value.t=n,this.items.asTail(e)):(this.items.push({k:t,v:r,s,t:n,ttl:i}),this.map.set(t,this.items.tail))}resetEntry(e){return this.opts.autoExtend&&(e.value.t=Date.now()+e.value.ttl),super.resetEntry(e)}};var Ze=(l,e=new Map)=>t=>{let r;return e.has(t)?e.get(t):(e.set(t,r=l(t)),r)};var k=(i=>(i.Aave="Aave",i.LBP="Lbp",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="Xyk",i))(k||{}),re=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(re||{});var Te=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:S,assetOutED:S}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=[];return t.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=[];return s.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:i}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return _(D,e.decimalsOut)}spotPriceOutGivenIn(e){return _(D,e.decimalsIn)}calculateTradeFee(e,t){return S}};var Jt=require("@polkadot/util-crypto"),Zt=require("@polkadot/util"),Qt=require("viem");function Ot(l,e){let t=[];return JSON.stringify(l,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Ar(l,e,t){let r;return JSON.stringify(l,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var _r=(l,e)=>typeof e=="bigint"?e.toString():e;var Bt=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var Oe=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.client.readContract({abi:Bt,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:Bt,address:e,functionName:"decimals"}),this.client.getBlock()]),[n,o,a,u]=r,c=i.number-(i.timestamp-u)/BigInt(t),m=Number(c);return{price:o,decimals:s,updatedAt:m<0?0:m}}};var U=class extends q{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Je(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=Ze(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new Oe(t)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let r=[];try{let i=this.subscribePoolChange(t);r.push(i)}catch{}if(t.type==="Aave")return r;let s=this.subscribeTokensPoolBalance(t);if(r.push(s),this.hasSystemAsset(t)){let i=this.subscribeSystemPoolBalance(t);r.push(i)}if(this.hasErc20Asset(t)){let i=this.subscribeErc20PoolBalance(t);r.push(i)}return this.subscribeLog(t),r}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,i])=>{let n=e.tokens.findIndex(o=>o.id==s);n>=0&&t(e,s)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(i=>i.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};var Nr=["Supply","Withdraw","Repay","Borrow"],Be=class extends U{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:i})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let r=e+"/"+t;return(0,Jt.encodeAddress)((0,Zt.stringToU8a)(r.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,r]=e.tokens,s=this.getReserveH160Id(t);return this.api.query.system.events(i=>{i.forEach(n=>{let{event:o}=n,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:u,assetOut:c}=o.data.toHuman(),m=u.replace(/,/g,""),h=c.replace(/,/g,"");(m===r.id||h===r.id)&&(this.log(`Sync AAVE [router:Executed] :: ${m}:${h}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:u}=o.data.toHuman();try{let{eventName:c,args:m}=(0,Qt.decodeEventLog)({abi:Ge,topics:u.topics,data:u.data});Nr.includes(c)&&m.reserve.toLowerCase()===s.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(n=>{let o=n.id===t.id?s.toString():i.toString();return{...n,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?Ot(e.location,"accountKey20").accountKey20.key:z.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};var X=require("@galacticcouncil/math-lbp"),W=class{static getSpotPrice(e,t,r,s,i){return(0,X.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,X.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,X.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,X.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,X.calculate_pool_trade_fee)(e,t,r)}};var P=class{static toPct(e){return e[0]/e[1]*100}static toDecimals(e){return e[0]/e[1]}static fromPermill(e){return[e/1e3,1e3]}};var Ie=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,i,n,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=n,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let o=this.calculateTradeFee(t,r),a=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),u=t.plus(o),c=this.calculateInGivenOut(e,u),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:i}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,r),u=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:u,errors:i}}}calculateInGivenOut(e,t){let r=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=W.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),_(D,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=W.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),_(D,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=W.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var Ae=class extends U{MAX_FINAL_WEIGHT=_(p(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,n])=>this.isActivePool(n.unwrap(),r)).map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),u=await this.getPoolDelta(a,o,r.toString());return this.poolsData.set(i.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...u,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let n=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,n)}else{let n=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(n,1)}})}async getPoolDelta(e,t,r){let{start:s,end:i,assets:n,initialWeight:o,finalWeight:a,repayTarget:u,feeCollector:c}=t,m=W.calculateLinearWeights(s.toString(),i.toString(),o.toString(),a.toString(),r),[h,d]=n,g=h.toString(),y=p(m),f=d.toString(),x=this.MAX_FINAL_WEIGHT.minus(p(y)),[b,A,B]=await Promise.all([this.isRepayFeeApplied(g,u.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,f)]);return{repayFeeApply:b,tokens:[{id:g,weight:y,balance:A.toString()},{id:f,weight:x,balance:B.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=p(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var O=require("@galacticcouncil/math-omnipool");var N=class{static calculateSpotPrice(e,t,r,s){return(0,O.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,O.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,n,o,a,u){return(0,O.calculate_in_given_out)(e,t,r,s,i,n,o,a,u)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,O.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,n,o,a,u){return(0,O.calculate_out_given_in)(e,t,r,s,i,n,o,a,u)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,O.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,O.calculate_pool_trade_fee)(e,t,r)}static calculateShares(e,t,r,s){return(0,O.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,n,o,a){return(0,O.calculate_liquidity_out)(e,t,r,s,i,n,o,a)}static calculateLiquidityLRNAOut(e,t,r,s,i,n,o,a){return(0,O.calculate_liquidity_lrna_out)(e,t,r,s,i,n,o,a)}static calculateCapDifference(e,t,r,s){let i=(0,v.BigNumber)(t),n=(0,v.BigNumber)(e),o=(0,v.BigNumber)(s),u=(0,v.BigNumber)(r).shiftedBy(-18);if(i.div(o).lt(u)){let m=u.times(o).minus(i).times(n),h=i.times((0,v.BigNumber)(1).minus(u));return m.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return(0,O.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,O.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,O.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,O.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,O.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,r,s,i,n,o,a,u,c,m){return(0,O.recalculate_asset_fee)(e,t,r,s,i,n,o,a,u,c,m)}static recalculateProtocolFee(e,t,r,s,i,n,o,a,u,c,m){return(0,O.recalculate_protocol_fee)(e,t,r,s,i,n,o,a,u,c,m)}static verifyAssetCap(e,t,r,s){return(0,O.verify_asset_cap)(e,t,r,s)}};var _e=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,i,n){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.hubAssetId=n}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),o=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(2),a=[],u=N.isSellAllowed(e.tradeableIn),c=N.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&a.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(h)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),o=s.minus(i).div(s).multipliedBy(100).decimalPlaces(2),a=[],u=N.isSellAllowed(e.tradeableIn),c=N.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&a.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(h)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=N.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toDecimals(r.assetFee).toString():S.toString(),r?P.toDecimals(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateLrnaInGivenOut(e,t,r){let s=N.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toDecimals(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=N.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toDecimals(r.assetFee).toString():S.toString(),r?P.toDecimals(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenLrnaIn(e,t,r){let s=N.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toDecimals(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=N.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=N.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=N.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=N.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var er=require("@polkadot/util-crypto"),tr=require("@polkadot/util");var Ne=class extends U{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=r.map(async([{args:[a]},u])=>{let{hubReserve:c,shares:m,tradable:h,cap:d,protocolShares:g}=u.unwrap(),y=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:h.bits.toNumber(),balance:y.toString(),cap:p(d.toString()),protocolShares:p(g.toString())}}),o=await Promise.all(n);return o.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=e.assetOut,s=e.assetIn,i="omnipool",n="Short",o=B=>B===M?[M,Pe]:[Pe,B],[a,u,c,m]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(r),this.api.query.emaOracle.oracles(i,o(r),n),this.api.query.emaOracle.oracles(i,o(s),n)]),[h,d,g]=this.getAssetFee(e,a.toNumber(),u,c),[y,f,x]=s===Pe?[0,0,0]:this.getProtocolFee(e,a.toNumber(),u,m),b=h+y,A=g+x;return{assetFee:P.fromPermill(d),protocolFee:P.fromPermill(f),min:P.fromPermill(b),max:P.fromPermill(A)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,i)=>{let n=e.tokens[i];if(s.isNone)return n;let o=s.unwrap();return this.updateTokenState(n,o)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:n,protocolShares:o}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(n.toString()),protocolShares:p(o.toString()),tradeable:i.bits.toNumber()}}getAssetFee(e,t,r,s){let{assetOut:i,balanceOut:n}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,m=P.fromPermill(o.toNumber()),h=P.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=s.unwrap(),{assetFee:g,timestamp:y}=r.unwrap(),f=Math.max(1,t-y.toNumber()),x=d.volume.bIn.toString(),b=d.volume.bOut.toString(),A=d.liquidity.b.toString();i===M&&(x=d.volume.aIn.toString(),b=d.volume.aOut.toString(),A=d.liquidity.a.toString());let B=P.fromPermill(g.toNumber()),w=N.recalculateAssetFee(x,b,A,"9",n.toString(),P.toDecimals(B).toString(),f.toString(),P.toDecimals(m).toString(),P.toDecimals(h).toString(),u.toString(),c.toString());return[o.toNumber(),Number(w)*1e6,a.toNumber()]}getProtocolFee(e,t,r,s){let{assetIn:i,balanceIn:n}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,m=P.fromPermill(o.toNumber()),h=P.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=s.unwrap(),{protocolFee:g,timestamp:y}=r.unwrap(),f=Math.max(1,t-y.toNumber()),x=d.volume.bIn.toString(),b=d.volume.bOut.toString(),A=d.liquidity.b.toString();i===M&&(x=d.volume.aIn.toString(),b=d.volume.aOut.toString(),A=d.liquidity.a.toString());let B=P.fromPermill(g.toNumber()),w=N.recalculateProtocolFee(x,b,A,"9",n.toString(),P.toDecimals(B).toString(),f.toString(),P.toDecimals(m).toString(),P.toDecimals(h).toString(),u.toString(),c.toString());return[o.toNumber(),Number(w)*1e6,a.toNumber()]}getPoolId(){return(0,er.encodeAddress)((0,tr.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var R=require("@galacticcouncil/math-xyk"),V=class{static getSpotPrice(e,t,r){return(0,R.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,R.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,R.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,R.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,R.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,R.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,R.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,R.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,R.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,R.calculate_liquidity_out_asset_b)(e,t,r,s)}};var Fe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:a,assetOutED:u}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),n=P.toPct(r.exchangeFee),o=s.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:s,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),n=P.toPct(r.exchangeFee),o=s.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:o,feePct:n,errors:a}}calculateInGivenOut(e,t){let r=V.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=V.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=V.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=_(D,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=V.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=_(D,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=V.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var Re=class extends U{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[n,o]=s.unwrap(),[a,u]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,o.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:a.toString()},{id:o.toString(),balance:u.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var F=require("@galacticcouncil/math-stableswap"),C=class{static getPoolAddress(e){return(0,F.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,i){return(0,F.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,n,o){return(0,F.calculate_in_given_out)(e,t,r,s,i,n,o)}static calculateAddOneAsset(e,t,r,s,i,n,o){return(0,F.calculate_add_one_asset)(e,t,r,s,i,n,o)}static calculateSharesForAmount(e,t,r,s,i,n,o){return(0,F.calculate_shares_for_amount)(e,t,r,s,i,n,o)}static calculateOutGivenIn(e,t,r,s,i,n,o){return(0,F.calculate_out_given_in)(e,t,r,s,i,n,o)}static calculateLiquidityOutOneAsset(e,t,r,s,i,n,o){return(0,F.calculate_liquidity_out_one_asset)(e,t,r,s,i,n,o)}static calculateShares(e,t,r,s,i,n){return(0,F.calculate_shares)(e,t,r,s,i,n)}static calculateSpotPriceWithFee(e,t,r,s,i,n,o,a){return(0,F.calculate_spot_price_with_fee)(e,t,r,s,i,n,o,a)}static calculatePoolTradeFee(e,t,r){return(0,F.calculate_pool_trade_fee)(e,t,r)}static recalculatePegs(e,t,r,s,i){let n=(0,F.recalculate_peg)(e,t,r,s,i);return JSON.parse(n)}};var Ee=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,r,s,i,n,o,a,u,c,m){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.amplification=n,this.id=o,this.fee=a,this.totalIssuance=u,this.pegs=c,this.pegsFee=m}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=P.toPct(r.fee),o=[],a=N.isSellAllowed(e.tradeableIn),u=N.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),n=P.toPct(r.fee),o=[],a=N.isSellAllowed(e.tradeableIn),u=N.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:n,errors:o}}calculateIn(e,t,r){let s=C.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateAddOneAsset(e,t,r){let s=C.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?P.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateSharesForAmount(e,t,r){let s=C.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?P.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=C.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let s=_(D,e.decimalsIn-e.decimalsOut);return p(t).div(s)}let r=_(D,18-e.decimalsIn);return p(t).div(r)}calculateOut(e,t,r){let s=C.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateWithdrawOneAsset(e,t,r){let s=C.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?P.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateShares(e,t,r){let s=C.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?P.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=C.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let s=_(D,e.decimalsOut-e.decimalsIn);return p(t).div(s)}let r=_(D,18-e.decimalsOut);return p(t).div(r)}calculateTradeFee(e,t){let r=C.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return p(r)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};var Qe=require("@polkadot/util-crypto");var rr=340282366920938463463374607431768211455n,De=class extends U{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),u=this.getPoolAddress(a),[c,m,h]=await Promise.all([this.getPoolDelta(a,o,r.toString()),this.getPoolTokens(u,a,o),this.getPoolPegs(a,o,r.toString())]);return this.stablePools.set(u,o),{address:u,id:a,type:"Stableswap",fee:P.fromPermill(o.fee.toNumber()),tokens:m,...c,...h,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toString(),s=this.stablePools.get(e.address);if(s){let[i,n]=await Promise.all([this.getPoolDelta(e.id,s,r),this.getPoolPegs(e.id,s,r)]);Object.assign(e,i,n)}})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:n,finalBlock:o}=t,a=C.calculateAmplification(s.toString(),i.toString(),n.toString(),o.toString(),r),u=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:u.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async o=>{let[a,u]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:a.bits.toNumber(),balance:u.toString()}}),n=await Promise.all(i);return n.push({id:t,tradeable:15,balance:rr.toString()}),n}getPoolDefaultPegs(e){let t=e.fee,r=C.defaultPegs(e.assets.length);return{pegsFee:P.fromPermill(t.toNumber()),pegs:r}}async getPoolPegs(e,t,r){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getPoolDefaultPegs(t);let i=s.unwrap(),n=await this.getLatestPegs(t,i,r),o=this.getRecentPegs(i),a=i.maxPegUpdate.toHuman(),u=t.fee.toHuman(),[c,m]=C.recalculatePegs(JSON.stringify(o),JSON.stringify(n),r,a.replace(/%/g,""),u.replace(/%/g,"")),h=Number(c)*1e4;return{pegsFee:P.fromPermill(h),pegs:m}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(i=>i.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,i=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),n=s.map(async(o,a)=>{if(o.isOracle){let[u,c,m]=o.asOracle,h=[m.toString(),i[a]].map(b=>Number(b)).sort((b,A)=>b-A),d=await this.api.query.emaOracle.oracles(u,h,c),[{price:g,updatedAt:y}]=d.unwrap(),f=g.n.toString(),x=g.d.toString();return m.toString()===h[0].toString()?[[f,x],y.toString()]:[[x,f],y.toString()]}else if(o.isMmOracle){let u=o.asMmOracle,{price:c,decimals:m,updatedAt:h}=await this.mmOracle.getData(u.toString()),d=10**m;return[[c.toString(),d.toString()],h.toString()]}else return[o.asValue.map(u=>u.toString()),r]});return Promise.all(n)}getPoolAddress(e){let t=Number(e),r=C.getPoolAddress(t);return(0,Qe.encodeAddress)((0,Qe.blake2AsHex)(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var le=class extends L{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=Ze(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new Z(this.api),this.aaveClient=new Be(this.api,t),this.xykClient=new Re(this.api,t),this.omniClient=new Ne(this.api,t),this.lbpClient=new Ae(this.api,t),this.stableClient=new De(this.api,t),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(s=>s.isSupported()).map(s=>s.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(r=>e.some(s=>s===r.getPoolType())).map(r=>r.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new xe(t.type)}}};var ue=class extends le{feeCache;disconnectSubscribeNewHeads=null;constructor(e,t){super(e,t),this.feeCache=new ae(null),this.api.rpc.chain.subscribeNewHeads(async r=>{this.feeCache.release()}).then(r=>{this.disconnectSubscribeNewHeads=r})}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let i=await super.getPoolFees(e,t);return this.feeCache.set(r,i),i}}async destroy(){this.log(`Destroying pool cache!
2
- Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var ce=class{static get(e){switch(e.type){case"Aave":return Te.fromPool(e);case"Xyk":return Fe.fromPool(e);case"Omnipool":return _e.fromPool(e);case"Lbp":return Ie.fromPool(e);case"Stableswap":return Ee.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var et=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 Fr=5,ke=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new et,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let o=i.dequeue();if(o==null||o.length>Fr)return s;let a=o[o.length-1];(r===null||a[0]===r)&&s.push(o),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let m=[...o];m.push(c),i.enqueue(m)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,n]of t){let o=parseInt(i),a=parseInt(n);r.get(o)?.push([a,s])}return r}};function It(l){let e={};for(let t of l){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let n=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(n)}}}return e}var Ce=class{getProposals(e,t,r){let s=It(r),i=Object.keys(s),n=i.map(c=>s[c]).flat(),o=new ke,a=o.buildAndPopulateGraph(i,n),u=o.findPaths(a,parseInt(e),t?parseInt(t):null);return this.parsePaths(u)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let n=r[i],o=r[i+1];if(o==null)break;s.push(this.toEdge(n,o))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var me=class{routeSuggester;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new Ce,this.routerOptions=Object.freeze({includeOnly:t.includeOnly??[]})}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),n=this.getPaths(e,null,s,t).map(o=>o[o.length-1].assetOut);return this.toAssets([...new Set(n)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(o=>this.validPath(o,r)).map(o=>this.toHops(o,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(r);return{assets:s,poolsMap:i}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,ce.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,i])=>{let n=t.get(r);return{poolAddress:r,poolId:n?.id,pool:n?.type,assetIn:s,assetOut:i}})}toAssets(e,t){return e.map(r=>t.get(r))}};var Rr=p("100");function Er(l,e){return l.minus(e).abs().div(l.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function pe(l,e){return l.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function At(l,e){return D.minus(e.div(l)).multipliedBy(100).decimalPlaces(2)}function _t(l,e){return e.div(l).minus(D).multipliedBy(100).decimalPlaces(2)}function Q(l,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),l.div(Rr).multipliedBy(e).decimalPlaces(0,1)}var tt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(tt||{}),rt=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(rt||{}),Nt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(Nt||{});var de=class extends me{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,n=s[s.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[r,s]}}getPoolFeeRange(e){let t=e.min?P.toPct(e.min):void 0,r=e.max?P.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new te(e,t);let a;if(s)a=await this.toSellSwaps(r,s,n);else{let w=o.map(async E=>await this.toSellSwaps(r,E,n)),I=await Promise.all(w);a=this.findBestSellRoute(I)}let u=a[0],c=a[a.length-1],m=this.isDirectTrade(a),h=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,I)=>w.multipliedBy(I)),d=_(h,c.assetOutDecimals),g=m?c.calculatedOut:this.calculateDelta0Y(u.amountIn,a,n),y=c.amountOut,f=m?c.tradeFeePct:At(g,y).toNumber(),x=g.minus(y),b=this.getRouteFeeRange(a),A=u.amountIn.shiftedBy(-1*u.assetInDecimals).multipliedBy(d),B=pe(g,A);return{type:"Sell",amountIn:u.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:x,tradeFeePct:f,tradeFeeRange:b,priceImpactPct:B.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:T(u.amountIn,u.assetInDecimals),amountOut:T(c.amountOut,c.assetOutDecimals),spotPrice:T(d,c.assetOutDecimals),tradeFee:T(x,c.assetOutDecimals),tradeFeePct:f,tradeFeeRange:b,priceImpactPct:B.toNumber(),swaps:a.map(w=>w.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i>0?u=s[i-1]:u=e;let c=o.calculateOutGivenIn(a,u);s.push(c)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i>0?u=s[i-1].amountOut:u=_(p(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:m,calculatedOut:h,feePct:d,errors:g}=o.validateAndSell(a,u,c),y=this.getPoolFeeRange(c),f=o.spotPriceOutGivenIn(a),x=u.shiftedBy(-1*a.decimalsIn).multipliedBy(f),b=pe(h,x);s.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,amountOut:m,calculatedOut:h,spotPrice:f,tradeFeePct:d,tradeFeeRange:y,priceImpactPct:b.toNumber(),errors:g,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:T(u,a.decimalsIn),amountOut:T(m,a.decimalsOut),calculatedOut:T(h,a.decimalsOut),spotPrice:T(f,a.decimalsOut),tradeFeePct:d,tradeFeeRange:y,priceImpactPct:b.toNumber(),errors:g}}})}return s}async getMostLiquidRoute(e,t){let r=await super.getPools(),{poolsMap:s}=await super.validateTokenPair(e,t,r),i=super.getPaths(e,t,s,r);if(i.length===0)throw new te(e,t);let u=r.filter(d=>d.tokens.some(g=>g.id===e&&g.id!==d.id)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(g=>g.id===e)).map(d=>d.map(g=>p(g.balance).shiftedBy(-1*g.decimals)).reduce((g,y)=>g.plus(y))).sort((d,g)=>g.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=i.map(async d=>await this.toSellSwaps(u,d,s)),m=await Promise.all(c);return this.findBestSellRoute(m).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r);if(super.getPaths(e,t,s,r).length===0)return Promise.resolve(void 0);let n=await this.getMostLiquidRoute(e,t),o=await this.toSellSwaps("1",n,s),a=o.map(m=>m.spotPrice.shiftedBy(-1*m.assetOutDecimals)).reduce((m,h)=>m.multipliedBy(h)),u=o[o.length-1].assetOutDecimals;return{amount:_(a,u),decimals:u}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,n=s[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new te(e,t);let a;if(s)a=await this.toBuySwaps(r,s,n);else{let w=o.map(async E=>await this.toBuySwaps(r,E,n)),I=await Promise.all(w);a=this.findBestBuyRoute(I)}let u=a[a.length-1],c=a[0],m=this.isDirectTrade(a),h=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetInDecimals)).reduce((w,I)=>w.multipliedBy(I)),d=_(h,c.assetInDecimals),g=m?c.calculatedIn:this.calculateDelta0X(u.amountOut,a,n),y=c.amountIn,f=m?c.tradeFeePct:_t(g,y).toNumber(),x=y.minus(g),b=this.getRouteFeeRange(a),A=u.amountOut.shiftedBy(-1*u.assetOutDecimals).multipliedBy(d),B;return g.isZero()?B=-100:B=pe(A,g).toNumber(),{type:"Buy",amountOut:u.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:x,tradeFeePct:f,tradeFeeRange:b,priceImpactPct:B,swaps:a,toHuman(){return{type:"Buy",amountOut:T(u.amountOut,u.assetOutDecimals),amountIn:T(c.amountIn,c.assetInDecimals),spotPrice:T(d,c.assetInDecimals),tradeFee:T(x,c.assetInDecimals),tradeFeePct:f,tradeFeeRange:b,priceImpactPct:B,swaps:a.map(w=>w.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=e:u=s[0];let c=o.calculateInGivenOut(a,u);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=_(p(e),a.decimalsOut).decimalPlaces(0,1):u=s[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:m,calculatedIn:h,feePct:d,errors:g}=o.validateAndBuy(a,u,c),y=this.getPoolFeeRange(c),f=o.spotPriceInGivenOut(a),x=u.shiftedBy(-1*a.decimalsOut).multipliedBy(f),b;h.isZero()?b=-100:b=pe(x,h).toNumber(),s.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:m,amountOut:u,calculatedIn:h,spotPrice:f,tradeFeePct:d,tradeFeeRange:y,priceImpactPct:b,errors:g,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:T(m,a.decimalsIn),amountOut:T(u,a.decimalsOut),calculatedIn:T(h,a.decimalsIn),spotPrice:T(f,a.decimalsIn),tradeFeePct:d,tradeFeeRange:y,priceImpactPct:b,errors:g}}})}return s}};var sr=6e3,ir=p(1e15),Me=6,Ft=-5,Rt=6*60*60*1e3;var nr=6;var G=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:i})=>s==="Stableswap"?{pool:{Stableswap:i},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var ge=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??sr,minBudgetInNative:t.minBudgetInNative??ir})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[n,o]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:u,priceImpactPct:c}=o,m=u[0],h=u[u.length-1],{assetInDecimals:d}=m,{assetOutDecimals:g}=h,y=Math.abs(c),f=this.getMinimumTradeCount(a,n),x=this.getOptimalTradeCount(y),b=i?Math.round(s/i):x,A=Math.ceil(s/f),B=Math.round(s/x),w=Math.round(s/b),I=a.dividedBy(b).decimalPlaces(0,1),E=await this.router.getBestSell(e,t,T(I,d)),H=a.isLessThan(n),Le=[];H&&Le.push("OrderTooSmall");let qe=E.amountOut.multipliedBy(b),nt=this.toBlockPeriod(w),ot=E.tradeFee.multipliedBy(b),at=G.build(u),Ue={assetIn:e,assetOut:t,errors:Le,frequencyMin:A,frequencyOpt:B,frequency:w,tradeCount:b,tradeFee:ot,tradeImpactPct:E.priceImpactPct,tradePeriod:nt,tradeRoute:at,type:"Dca"};return{...Ue,amountIn:a,amountOut:qe,tradeAmountIn:E.amountIn,tradeAmountOut:E.amountOut,toHuman(){return{...Ue,amountIn:T(a,d),amountOut:T(qe,g),tradeAmountIn:T(E.amountIn,d),tradeAmountOut:T(E.amountOut,g)}}}}async getMinimumOrderBudget(e){if(M===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(M,e);if(t)return this.minOrderBudget.times(t.amount).div(p(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:o,priceImpactPct:a}=i,u=o[0],c=o[o.length-1],{assetInDecimals:m}=u,{assetOutDecimals:h}=c,d=Math.abs(a),g=this.getTwapTradeCount(d),y=n.dividedBy(g).decimalPlaces(0,1),f=await this.router.getBestSell(u.assetIn,c.assetOut,T(y,m)),x=g===1,b=n.isLessThan(s),A=f.priceImpactPct<Ft,B=[];b||x?B.push("OrderTooSmall"):A&&B.push("OrderImpactTooBig");let w=f.amountOut.multipliedBy(g),I=f.tradeFee.multipliedBy(g),E=G.build(o),H={assetIn:e,assetOut:t,errors:B,tradeCount:g,tradeImpactPct:f.priceImpactPct,tradePeriod:Me,tradeRoute:E,type:"TwapSell"};return{...H,amountIn:n,amountOut:w,tradeAmountIn:f.amountIn,tradeAmountOut:f.amountOut,tradeFee:I,toHuman(){return{...H,amountIn:T(n,m),amountOut:T(w,h),tradeAmountIn:T(f.amountIn,m),tradeAmountOut:T(f.amountOut,h),tradeFee:T(I,h)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:n,swaps:o,priceImpactPct:a}=i,u=o[0],c=o[o.length-1],{assetInDecimals:m}=u,{assetOutDecimals:h}=c,d=Math.abs(a),g=this.getTwapTradeCount(d),y=n.dividedBy(g).decimalPlaces(0,1),f=await this.router.getBestBuy(u.assetIn,c.assetOut,T(y,h)),x=f.amountIn.multipliedBy(g),b=g===1,A=x.isLessThan(s),B=f.priceImpactPct<Ft,w=[];A||b?w.push("OrderTooSmall"):B&&w.push("OrderImpactTooBig");let I=f.tradeFee.multipliedBy(g),E=G.build(o),H={assetIn:e,assetOut:t,errors:w,tradeCount:g,tradeImpactPct:f.priceImpactPct,tradePeriod:Me,tradeRoute:E,type:"TwapBuy"};return{...H,amountIn:x,amountOut:n,tradeAmountIn:f.amountIn,tradeAmountOut:f.amountOut,tradeFee:I,toHuman(){return{...H,amountIn:T(x,m),amountOut:T(n,h),tradeAmountIn:T(f.amountIn,m),tradeAmountOut:T(f.amountOut,h),tradeFee:T(I,m)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>Rt){let s=Rt/(this.blockTime*Me);return Math.round(s)}return t}getTwapExecutionTime(e){return e*Me*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,nr)}};var he=class extends L{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new q(e),this.aaveUtils=new J(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),ye)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var st=class extends he{_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:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:i,assetOut:n}=s,a=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),u=!0;return s.isWithdraw()&&(u=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,n)).amount.isGreaterThanOrEqualTo(a)),u&&e.isGreaterThanOrEqualTo(a)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=Q(e,this.slippagePct),o=s.assetIn,a=i.assetOut,u=e.plus(n),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(a,o,t.toFixed(),u.toFixed()):c=this.api.tx.router.buy(o,a,t.toFixed(),u.toFixed(),G.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=Q(t,this.slippagePct),o=s.assetIn,a=i.assetOut,u=t.minus(n),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(o,a,e.toFixed(),u.toFixed()):c=this.api.tx.router.sell(o,a,e.toFixed(),u.toFixed(),G.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let h=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSellAll",h,ye)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=Q(e,this.slippagePct),n=r.assetIn,o=s.assetOut,a=e.minus(i),u=this.api.tx.router.sellAll(n,o,a.toFixed(),G.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let m=this.dispatchWithExtraGas(u);return this.wrapTx("RouterSellAll",m,ye)}return this.wrapTx("RouterSellAll",u)}};var it=class extends he{_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:r,tradeAmountIn:s,tradePeriod:i,tradeRoute:n}=this.order,o=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:n}}},null);return this.wrapTx("DcaSchedule",o)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:o}=this.order,a=Q(i,this.slippagePct),u=i.minus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:u.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:o}=this.order,a=Q(s,this.slippagePct),u=s.plus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:i.toFixed(),maxAmountIn:u.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var fe=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new st(this.api,this.evm).setTrade(e)}order(e){return new it(this.api,this.evm).setOrder(e)}};function Dr(l){let e=new ne(l),t=new ve(l),r=new ue(l,t),s=new J(t),i=new de(r),n=new ge(i,{blockTime:e.blockTime,minBudgetInNative:e.minOrderBudget});return{api:{aave:s,router:i,scheduler:n},client:{asset:new Z(l),balance:new q(l)},ctx:{pool:r},evm:t,tx:new fe(l,t),destroy:()=>{r.destroy()}}}0&&(module.exports={AMOUNT_MAX,AaveClient,AavePool,AavePoolClient,AaveUtils,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,ChainParams,DECIMAL_PLACES,DENOMINATOR,ERC20,EvmClient,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,ONE,OmniMath,OmniPool,OmniPoolClient,PolkadotApiClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StableSwapClient,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeOrderError,TradeOrderType,TradeRouteBuilder,TradeRouter,TradeScheduler,TradeType,TxBuilderFactory,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,createChain,createSdkContext,findNestedKey,findNestedObj,getFraction,isEvmAccount,isEvmAddress,isSs58Address,scale,toBn,toDecimals});
1
+ "use strict";var ut=Object.defineProperty;var pr=Object.getOwnPropertyDescriptor;var dr=Object.getOwnPropertyNames;var gr=Object.prototype.hasOwnProperty;var hr=(l,e)=>{for(var t in e)ut(l,t,{get:e[t],enumerable:!0})},yr=(l,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of dr(e))!gr.call(l,s)&&s!==t&&ut(l,s,{get:()=>e[s],enumerable:!(r=pr(e,s))||r.enumerable});return l};var fr=l=>yr(ut({},"__esModule",{value:!0}),l);var Cr={};hr(Cr,{AMOUNT_MAX:()=>sr,AaveClient:()=>se,AavePool:()=>Oe,AavePoolClient:()=>Ie,AaveUtils:()=>J,AssetClient:()=>Z,AssetNotFound:()=>bt,BASILISK_PARACHAIN_ID:()=>jr,BalanceClient:()=>q,BigNumber:()=>v.BigNumber,CachingPoolService:()=>ue,ChainParams:()=>ne,DECIMAL_PLACES:()=>qt,DENOMINATOR:()=>dt,ERC20:()=>z,EvmClient:()=>we,FarmClient:()=>ze,H160:()=>ee,HUB_ASSET_ID:()=>Pe,HYDRADX_PARACHAIN_ID:()=>Kr,HYDRADX_SS58_PREFIX:()=>j,INFINITY:()=>Pr,LbpMath:()=>W,LbpPool:()=>Ae,LbpPoolClient:()=>_e,ONE:()=>D,OmniMath:()=>N,OmniPool:()=>Ne,OmniPoolClient:()=>Re,PolkadotApiClient:()=>L,PoolConfigNotFound:()=>Pt,PoolError:()=>re,PoolFactory:()=>ce,PoolNotFound:()=>ve,PoolService:()=>le,PoolType:()=>k,ProviderConfigNotFound:()=>vt,RUNTIME_DECIMALS:()=>be,RouteNotFound:()=>te,Router:()=>me,SYSTEM_ASSET_DECIMALS:()=>kt,SYSTEM_ASSET_ID:()=>M,StableMath:()=>C,StableSwap:()=>De,StableSwapClient:()=>ke,StorageConfigNotFound:()=>St,SubscriptionNotSupported:()=>xt,TRADEABLE_DEFAULT:()=>Se,TradeOrderError:()=>Rt,TradeOrderType:()=>st,TradeRouteBuilder:()=>G,TradeRouter:()=>de,TradeScheduler:()=>ge,TradeType:()=>rt,TxBuilderFactory:()=>ye,XykMath:()=>V,XykPool:()=>Fe,XykPoolClient:()=>Ee,ZERO:()=>S,bnFormatter:()=>Nr,bnum:()=>p,calculateBuyFee:()=>Nt,calculateDiffToAvg:()=>Dr,calculateDiffToRef:()=>pe,calculateSellFee:()=>_t,createChain:()=>wt,createSdkContext:()=>kr,findNestedKey:()=>Bt,findNestedObj:()=>_r,getFraction:()=>Q,isEvmAccount:()=>Ct,isEvmAddress:()=>Mt,isSs58Address:()=>Lt,scale:()=>_,toBn:()=>br,toDecimals:()=>T});module.exports=fr(Cr);var We=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{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 ct=[{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 Dt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",mt="0x112b087b60C1a166130d59266363C45F8aa99db0",pt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",fe=1000000n;var zr=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var se=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:ct,address:mt,args:[pt],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:ct,address:mt,args:[pt,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:We,address:Dt,args:[e],functionName:"getUserAccountData"})}};var K=require("@polkadot/util-crypto"),ie=require("@polkadot/util"),Y=require("buffer");var jr=2090,dt=1e3,Pe="1",Kr=2034,j=63,be=18,M="0",kt=12,Se=15;var gt="ETH\0";function Ct(l){if(!l)return!1;try{let e=(0,K.decodeAddress)(l,!0),t=Y.Buffer.from(gt);return Y.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Mt(l){return!!/^0x[a-fA-F0-9]{40}$/.test(l)}function Lt(l){try{let e=(0,ie.isHex)(l)?(0,ie.hexToU8a)(l):(0,K.decodeAddress)(l);return(0,K.encodeAddress)(e),!0}catch{return!1}}var ee=class l{static toAccount=e=>{let t=Y.Buffer.from(e.slice(2),"hex"),r=Y.Buffer.from(gt);return(0,K.encodeAddress)(new Uint8Array(Y.Buffer.concat([r,t,Y.Buffer.alloc(8)])),63)};static fromAccount=e=>{let t=(0,K.decodeAddress)(e),r=Y.Buffer.from(gt),s=t.slice(r.length,-8);return"0x"+Y.Buffer.from(s).toString("hex")};static fromSS58=e=>{let r=(0,K.decodeAddress)(e).slice(0,20);return(0,ie.u8aToHex)(r)};static fromAny=e=>{if(Mt(e))return e;if(Ct(e))return l.fromAccount(e);if(Lt(e))return l.fromSS58(e);throw new Error("Unknown address type")}};var xe=require("buffer"),z=class{static fromAssetId(e){let t=Number(e),r=xe.Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=xe.Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=xe.Buffer.from("0000000000000000000000000000000100000000","hex"),r=xe.Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};var v=require("bignumber.js"),qt=12;v.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:qt});var S=p(0),D=p(1),Pr=p("Infinity");function _(l,e){let t=new v.BigNumber(e.toString()),r=new v.BigNumber(10).pow(t);return l.times(r)}function p(l){return new v.BigNumber(l.toString())}function br(l,e){let t=p(l);return _(t,e)}function T(l,e){return l.shiftedBy(-1*e).toString()}var He=p("1e27"),Sr=p("1.01"),xr=p("31536000"),J=class{client;constructor(e){this.client=new se(e)}async getSummary(e){let t=ee.fromAny(e),[r,s,i,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[o]=r,[a,u]=s,[c,m,h,d,g,f]=i,y=p(f).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN),x=p(c),b=p(m),A=[];for(let B of a){let w=B.underlyingAsset.toLowerCase(),I=o.find(({underlyingAsset:mr})=>mr.toLowerCase()===w);if(!I)throw new Error("Missing pool reserve for "+w);let E=p(B.scaledATokenBalance),H=p(I.liquidityIndex),qe=p(I.liquidityRate),Ue=p(I.availableLiquidity),ot=p(I.priceInMarketReferenceCurrency),at=n+6,lt=this.calculateLinearInterest(qe,I.lastUpdateTimestamp,at),Ge=H.multipliedBy(lt).dividedBy(He).decimalPlaces(0,v.BigNumber.ROUND_DOWN),ar=E.multipliedBy(Ge).dividedBy(He).decimalPlaces(0,v.BigNumber.ROUND_DOWN),lr=p(u!==0&&u===I.eModeCategoryId?I.eModeLiquidationThreshold:I.reserveLiquidationThreshold).div(1e4),ur=I.usageAsCollateralEnabled&&B.usageAsCollateralEnabledOnUser&&p(B.scaledATokenBalance).gt(0),cr=z.toAssetId(w);A.push({aTokenBalance:ar,availableLiquidity:Ue,decimals:Number(I.decimals),isCollateral:ur,priceInRef:ot,reserveId:cr,reserveAsset:w,reserveLiquidationThreshold:lr})}return{healthFactor:y.toNumber(),totalCollateral:x,totalDebt:b,reserves:A}}async hasBorrowPositions(e){let t=ee.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=ee.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,n,o,a,u]=r;return p(u).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=z.fromAssetId(t),a=n.find(x=>x.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:u,isCollateral:c,priceInRef:m,reserveLiquidationThreshold:h}=a,d=_(p(r),u).decimalPlaces(0,1),g=c?d.multipliedBy(m).dividedBy(p(10).pow(u)).decimalPlaces(0,v.BigNumber.ROUND_DOWN):S,f=s.minus(g);return f.lte(0)?0:f.multipliedBy(h).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=z.fromAssetId(t),a=n.find(y=>y.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:u,priceInRef:c,reserveLiquidationThreshold:m}=a,d=_(p(r),u).decimalPlaces(0,1).multipliedBy(c).dividedBy(p(10).pow(u)).decimalPlaces(0,v.BigNumber.ROUND_DOWN),g=s.plus(d);return g.lte(0)?0:g.multipliedBy(m).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),n=z.fromAssetId(t),o=s.find(a=>a.reserveAsset===n);if(!o)throw new Error("Missing reserve data for "+n);return this.calculateWithdrawMax(o,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let n of r){let o=this.calculateWithdrawMax(n,t,s);n.reserveId&&(i[n.reserveId]=o)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:n,priceInRef:o,reserveLiquidationThreshold:a,isCollateral:u}=e,c=s;if(u&&t.gt(0)){let h=p(r).minus(Sr);if(h.gt(0)){let g=h.multipliedBy(t).dividedBy(a).decimalPlaces(0,v.BigNumber.ROUND_DOWN).dividedBy(o).multipliedBy(p(10).pow(n)).decimalPlaces(0,v.BigNumber.ROUND_DOWN);c=v.BigNumber.minimum(s,g)}else c=S}return{amount:v.BigNumber.minimum(c,i),decimals:n}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?He:e.multipliedBy(s).dividedBy(xr).plus(He).decimalPlaces(0,v.BigNumber.ROUND_DOWN)}};function Ut(l){switch(l){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var gs=require("@galacticcouncil/api-augment/hydradx"),hs=require("@galacticcouncil/api-augment/basilisk"),L=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Ut(r)&&console.log(e,...t)}};var Z=class extends L{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==M){let m=this.api.consts.balances.existentialDeposit;return{id:M,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:o,existentialDeposit:a}=t,{symbol:u,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:u,decimals:c,icon:u,type:n.toHuman(),isSufficient:o?o.toHuman():!0,location:s?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,r,s){let[i,n]=s,{assetType:o,isSufficient:a,existentialDeposit:u}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,r),h=n.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(h)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:m,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:u.toString(),underlyingAssetId:i.toString(),maturity:h}}getShares(e,t,r,s){let{assets:i}=s,{name:n,symbol:o,assetType:a,isSufficient:u,existentialDeposit:c}=t,h=i.map(f=>f.toString()).map(f=>{let{symbol:y}=this.getToken(f,t,r);return[f,y]}),d=Object.fromEntries(h),g=Object.values(d);return{id:e,name:g.join(", "),symbol:o?.isSome?o.toHuman():n.toHuman(),decimals:18,icon:g.join("/"),type:a.toString(),isSufficient:u.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),n=r?.find(o=>o.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:n}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,i,n,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(r),u=this.normalizeMetadata(a,o),c=a.map(([{args:[m]},h])=>{let d=h.unwrap(),g=s.get(m.toString()),{assetType:f}=d;switch(f.toString()){case"Bond":let y=n.get(m.toString());return this.getBond(m.toString(),d,u,y);case"StableSwap":let x=i.get(m.toString());return this.getShares(m.toString(),d,u,x);case"External":return this.getExternal(m.toString(),d,t,g);default:return this.getToken(m.toString(),d,u,g)}});return e?c:c.filter(m=>this.isValidAsset(m))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var q=class extends L{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===M?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:i})}async getErc20Balance(e,t){let{free:r,reserved:s,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:r,feeFrozen:0n,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(M,this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,o]})=>[n.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,u)=>{let c=this.calculateFreeBalance(a),m=i[u][1];o.push([m,c])}),t(o)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,u])=>{let{assetType:c}=u.unwrap();return c.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),n=async()=>{let o=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:i}=e,n=new v.BigNumber(t),o=new v.BigNumber(r||i),a=new v.BigNumber(s||0n),u=o.gt(a)?o:a;return n.minus(u)}};var ne=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),p(this._minOrderBudget)}};var ht=require("@galacticcouncil/math-liquidity-mining"),Gt=require("@polkadot/types"),yt=require("@polkadot/util"),ft=require("@polkadot/util-crypto");var ze=class extends L{balanceClient;constructor(e){super(e),this.balanceClient=new q(e)}secondsInYear=new v.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),u=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),g=u.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:f.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),u=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),g=u.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:f.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new v.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),o=n.price.n.toString(),a=n.price.d.toString(),u;return Number(t)<Number(r)?u=(0,ht.fixed_from_rational)(o,a):u=(0,ht.fixed_from_rational)(a,o),u}getGlobalRewardPerPeriod(e,t,r,s){let n=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return n.gte(r)?r:n}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return(0,yt.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Gt.GenericAccountId32(e,this.padEndU8a((0,yt.u8aConcat)(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,ft.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,ft.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:o,globalFarm:a,priceAdjustment:u,potBalance:c})=>{let m=new v.BigNumber(a.totalSharesZ.toString()),h=a.plannedYieldingPeriods.toString(),d=new v.BigNumber(a.yieldPerPeriod.toString()),g=new v.BigNumber(a.maxRewardPerPeriod.toString()),f=a.blocksPerPeriod.toString(),y=new v.BigNumber(o.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new v.BigNumber(r).times(f)),b;if(m.isZero())b=d.times(y).times(x);else{let E=this.getGlobalRewardPerPeriod(m,d,g,u);b=this.getPoolYieldPerPeriod(E,y,m,u).times(x)}let A=new v.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),B=g.times(h),w=c?A.plus(c):B;return A.div(w).gte(.999)?S:b.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),S).toString():void 0}};var ve=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Pt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},te=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},bt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},St=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},xt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},vt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Wt=require("viem"),vr=["wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],wt=l=>{let e=l.__internal__endpoints,t=e.some(s=>vr.includes(s)),r=e.map(s=>s.replace("wss://","https://").replace("ws://","http://"));return(0,Wt.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:t?"https://explorer.evm.hydration.cloud":"https://explorer.nice.hydration.cloud"}},testnet:!t})};var $=require("viem");function Ht(l){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return l.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var we=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=wt(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,$.createPublicClient)({chain:this.chain,transport:(0,$.http)()})}getWsProvider(){return(0,$.createPublicClient)({chain:this.chain,transport:Ht(this.wsProvider)})}getSigner(e){return(0,$.createWalletClient)({account:e,chain:this.chain,transport:(0,$.custom)(window.ethereum)})}};var Te=(l,e)=>l===e?0:l==null?e==null?0:-1:e==null?l==null?0:1:typeof l.compare=="function"?l.compare(e):typeof e.compare=="function"?-e.compare(l):l<e?-1:l>e?1:0;var Xe=(l,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(l(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var wr=Xe(()=>"illegal argument(s)"),zt=l=>{throw new wr(l)};var Tr=Xe(()=>"index out of bounds"),Tt=l=>{throw new Tr(l)},Ye=(l,e,t)=>(l<e||l>=t)&&Tt(l);var Xt=23283064365386963e-26,$e=class{float(e=1){return this.int()*Xt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Xt-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var Ve=class extends $e{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var Yt=new Ve(Math.random);var $t=l=>l!=null&&typeof l!="function"&&l.length!==void 0;var Vt=Object.getPrototypeOf({}),je="function",jt="string",oe=(l,e)=>{let t;if(l===e)return!0;if(l!=null){if(typeof l.equiv===je)return l.equiv(e)}else return l==e;if(e!=null){if(typeof e.equiv===je)return e.equiv(l)}else return l==e;return typeof l===jt||typeof e===jt?!1:(t=Object.getPrototypeOf(l),(t==null||t===Vt)&&(t=Object.getPrototypeOf(e),t==null||t===Vt)?Ar(l,e):typeof l!==je&&l.length!==void 0&&typeof e!==je&&e.length!==void 0?Or(l,e):l instanceof Set&&e instanceof Set?Br(l,e):l instanceof Map&&e instanceof Map?Ir(l,e):l instanceof Date&&e instanceof Date?l.getTime()===e.getTime():l instanceof RegExp&&e instanceof RegExp?l.toString()===e.toString():l!==l&&e!==e)},Or=(l,e,t=oe)=>{let r=l.length;if(r===e.length)for(;r-- >0&&t(l[r],e[r]););return r<0},Br=(l,e,t=oe)=>l.size===e.size&&t([...l.keys()].sort(),[...e.keys()].sort()),Ir=(l,e,t=oe)=>l.size===e.size&&t([...l].sort(),[...e].sort()),Ar=(l,e,t=oe)=>{if(Object.keys(l).length!==Object.keys(e).length)return!1;for(let r in l)if(!e.hasOwnProperty(r)||!t(l[r],e[r]))return!1;return!0};var Ot=class{value;constructor(e){this.value=e}deref(){return this.value}};var Kt=l=>l instanceof Ot;var Ke=class l{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Jt("next",this._head)}reverseIterator(){return Jt("prev",this.tail)}clear(){this.release()}compare(e,t=Te){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,n=0;for(;r-- >0&&n===0;)n=t(s.value,i.value),s=s.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof l||$t(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!oe(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||Te;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!Kt(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&Tt(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*Jt(l,e){for(;e;)yield e.value,e=e[l]}var Je=class l extends Ke{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new l(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new l}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(Ye(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(Ye(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new l,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==s&&n.next?i(n.next):void 0}});return r?i(r):void 0}shuffle(e,t=Yt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&zt("invalid indices: ${from} / ${to}");let i=new l,n=this.nthCell(r);for(;n&&++r<=s;)i.push(n.value),n=n.next;return i}sort(e=Te){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,n=0;for(let a=0;a<t&&(n++,i=i.next,!!i);a++);let o=t;for(;n>0||o>0&&i;){let a;n===0?(a=i,i=i.next,o--):!i||o===0||e(r.value,i.value)<=0?(a=r,r=r.next,n--):(a=i,i=i.next,o--),this._tail?this._tail.next=a:this._head=a,a.prev=this._tail,this._tail=a}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),Ye(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new l;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let n of r)this.insertBefore(s,n);else for(let n of r)this.push(n);return i}};var ae=class l{map;items;opts;_size;constructor(e,t){let r={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=r.map(),this.items=new Je,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new l(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e),i=Math.max(0,r-(s?s.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(s,e,t,r):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let r=this.map.get(e);return r?this.resetEntry(r):this.set(e,await t())}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let{release:e,maxsize:t,maxlen:r}=this.opts;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e?.(s.k,s.v),this._size-=s.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,r,s){e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var Ze=class l extends ae{constructor(e,t){super(e,{ttl:60*60*1e3,autoExtend:!1,...t})}empty(){return new l(null,this.opts)}has(e){return this.get(e)!==void 0}get(e,t){let r=this.map.get(e);if(r){if(r.value.t>=Date.now())return this.resetEntry(r);this.removeEntry(r)}return t}set(e,t,r=this.opts.ttl){let s=this.opts.ksize(e)+this.opts.vsize(t),i=this.map.get(e),n=Math.max(0,s-(i?i.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(i,e,t,s,r):this._size-=n,t}async getSet(e,t,r=this.opts.ttl){let s=this.get(e);return s!==void 0?s:this.set(e,await t(),r)}prune(){let e=Date.now(),t=this.items.head,r=0;for(;t;)t.value.t<e&&(this.removeEntry(t),r++),t=t.next;return r}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,r=Date.now(),s=this.items.head;for(;s&&(this._size>t||this.length>=e);)s.value.t<r&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(e,t,r,s,i=this.opts.ttl){let n=Date.now()+i;e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,e.value.t=n,this.items.asTail(e)):(this.items.push({k:t,v:r,s,t:n,ttl:i}),this.map.set(t,this.items.tail))}resetEntry(e){return this.opts.autoExtend&&(e.value.t=Date.now()+e.value.ttl),super.resetEntry(e)}};var Qe=(l,e=new Map)=>t=>{let r;return e.has(t)?e.get(t):(e.set(t,r=l(t)),r)};var k=(i=>(i.Aave="Aave",i.LBP="Lbp",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="Xyk",i))(k||{}),re=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(re||{});var Oe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:S,assetOutED:S}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=[];return t.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=[];return s.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:i}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return _(D,e.decimalsOut)}spotPriceOutGivenIn(e){return _(D,e.decimalsIn)}calculateTradeFee(e,t){return S}};var Zt=require("@polkadot/util-crypto"),Qt=require("@polkadot/util"),er=require("viem");function Bt(l,e){let t=[];return JSON.stringify(l,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function _r(l,e,t){let r;return JSON.stringify(l,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Nr=(l,e)=>typeof e=="bigint"?e.toString():e;var It=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var Be=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.client.readContract({abi:It,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:It,address:e,functionName:"decimals"}),this.client.getBlock()]),[n,o,a,u]=r,c=i.number-(i.timestamp-u)/BigInt(t),m=Number(c);return{price:o,decimals:s,updatedAt:m<0?0:m}}};var U=class extends q{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Ze(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=Qe(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new Be(t)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let r=[];try{let i=this.subscribePoolChange(t);r.push(i)}catch{}if(t.type==="Aave")return r;let s=this.subscribeTokensPoolBalance(t);if(r.push(s),this.hasSystemAsset(t)){let i=this.subscribeSystemPoolBalance(t);r.push(i)}if(this.hasErc20Asset(t)){let i=this.subscribeErc20PoolBalance(t);r.push(i)}return this.subscribeLog(t),r}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,i])=>{let n=e.tokens.findIndex(o=>o.id==s);n>=0&&t(e,s)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(i=>i.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};var Rr=["Supply","Withdraw","Repay","Borrow"],Ie=class extends U{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:i})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let r=e+"/"+t;return(0,Zt.encodeAddress)((0,Qt.stringToU8a)(r.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,r]=e.tokens,s=this.getReserveH160Id(t);return this.api.query.system.events(i=>{i.forEach(n=>{let{event:o}=n,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:u,assetOut:c}=o.data.toHuman(),m=u.replace(/,/g,""),h=c.replace(/,/g,"");(m===r.id||h===r.id)&&(this.log(`Sync AAVE [router:Executed] :: ${m}:${h}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:u}=o.data.toHuman();try{let{eventName:c,args:m}=(0,er.decodeEventLog)({abi:We,topics:u.topics,data:u.data});Rr.includes(c)&&m.reserve.toLowerCase()===s.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(n=>{let o=n.id===t.id?s.toString():i.toString();return{...n,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?Bt(e.location,"accountKey20").accountKey20.key:z.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};var X=require("@galacticcouncil/math-lbp"),W=class{static getSpotPrice(e,t,r,s,i){return(0,X.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,X.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,X.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,X.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,X.calculate_pool_trade_fee)(e,t,r)}};var P=class{static toPct(e){return e[0]/e[1]*100}static toDecimals(e){return e[0]/e[1]}static fromPermill(e){return[e/1e3,1e3]}};var Ae=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,i,n,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=n,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let o=this.calculateTradeFee(t,r),a=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),u=t.plus(o),c=this.calculateInGivenOut(e,u),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:i}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,r),u=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:u,errors:i}}}calculateInGivenOut(e,t){let r=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=W.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),_(D,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=W.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),_(D,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=W.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var _e=class extends U{MAX_FINAL_WEIGHT=_(p(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,n])=>this.isActivePool(n.unwrap(),r)).map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),u=await this.getPoolDelta(a,o,r.toString());return this.poolsData.set(i.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...u,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let n=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,n)}else{let n=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(n,1)}})}async getPoolDelta(e,t,r){let{start:s,end:i,assets:n,initialWeight:o,finalWeight:a,repayTarget:u,feeCollector:c}=t,m=W.calculateLinearWeights(s.toString(),i.toString(),o.toString(),a.toString(),r),[h,d]=n,g=h.toString(),f=p(m),y=d.toString(),x=this.MAX_FINAL_WEIGHT.minus(p(f)),[b,A,B]=await Promise.all([this.isRepayFeeApplied(g,u.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,y)]);return{repayFeeApply:b,tokens:[{id:g,weight:f,balance:A.toString()},{id:y,weight:x,balance:B.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=p(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var O=require("@galacticcouncil/math-omnipool");var N=class{static calculateSpotPrice(e,t,r,s){return(0,O.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,O.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,n,o,a,u){return(0,O.calculate_in_given_out)(e,t,r,s,i,n,o,a,u)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,O.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,n,o,a,u){return(0,O.calculate_out_given_in)(e,t,r,s,i,n,o,a,u)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,O.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculateShares(e,t,r,s){return(0,O.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,n,o,a){return(0,O.calculate_liquidity_out)(e,t,r,s,i,n,o,a)}static calculateLiquidityLRNAOut(e,t,r,s,i,n,o,a){return(0,O.calculate_liquidity_lrna_out)(e,t,r,s,i,n,o,a)}static calculateCapDifference(e,t,r,s){let i=(0,v.BigNumber)(t),n=(0,v.BigNumber)(e),o=(0,v.BigNumber)(s),u=(0,v.BigNumber)(r).shiftedBy(-18);if(i.div(o).lt(u)){let m=u.times(o).minus(i).times(n),h=i.times((0,v.BigNumber)(1).minus(u));return m.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return(0,O.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,O.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,O.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,O.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,O.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,r,s,i,n,o,a,u,c,m){return(0,O.recalculate_asset_fee)(e,t,r,s,i,n,o,a,u,c,m)}static recalculateProtocolFee(e,t,r,s,i,n,o,a,u,c,m){return(0,O.recalculate_protocol_fee)(e,t,r,s,i,n,o,a,u,c,m)}static verifyAssetCap(e,t,r,s){return(0,O.verify_asset_cap)(e,t,r,s)}};var Ne=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,i,n){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.hubAssetId=n}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),o=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(2),a=[],u=N.isSellAllowed(e.tradeableIn),c=N.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&a.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(h)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),o=s.minus(i).div(s).multipliedBy(100).decimalPlaces(2),a=[],u=N.isSellAllowed(e.tradeableIn),c=N.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&a.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(h)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=N.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toDecimals(r.assetFee).toString():S.toString(),r?P.toDecimals(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateLrnaInGivenOut(e,t,r){let s=N.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toDecimals(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=N.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toDecimals(r.assetFee).toString():S.toString(),r?P.toDecimals(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenLrnaIn(e,t,r){let s=N.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toDecimals(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=N.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=N.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=N.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=N.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var tr=require("@polkadot/util-crypto"),rr=require("@polkadot/util");var Re=class extends U{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=r.map(async([{args:[a]},u])=>{let{hubReserve:c,shares:m,tradable:h,cap:d,protocolShares:g}=u.unwrap(),f=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:h.bits.toNumber(),balance:f.toString(),cap:p(d.toString()),protocolShares:p(g.toString())}}),o=await Promise.all(n);return o.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=e.assetOut,s=e.assetIn,i="omnipool",n="Short",o=B=>B===M?[M,Pe]:[Pe,B],[a,u,c,m]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(r),this.api.query.emaOracle.oracles(i,o(r),n),this.api.query.emaOracle.oracles(i,o(s),n)]),[h,d,g]=this.getAssetFee(e,a.toNumber(),u,c),[f,y,x]=s===Pe?[0,0,0]:this.getProtocolFee(e,a.toNumber(),u,m),b=h+f,A=g+x;return{assetFee:P.fromPermill(d),protocolFee:P.fromPermill(y),min:P.fromPermill(b),max:P.fromPermill(A)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,i)=>{let n=e.tokens[i];if(s.isNone)return n;let o=s.unwrap();return this.updateTokenState(n,o)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:n,protocolShares:o}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(n.toString()),protocolShares:p(o.toString()),tradeable:i.bits.toNumber()}}getAssetFee(e,t,r,s){let{assetOut:i,balanceOut:n}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,m=P.fromPermill(o.toNumber()),h=P.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=s.unwrap(),{assetFee:g,timestamp:f}=r.unwrap(),y=Math.max(1,t-f.toNumber()),x=d.volume.bIn.toString(),b=d.volume.bOut.toString(),A=d.liquidity.b.toString();i===M&&(x=d.volume.aIn.toString(),b=d.volume.aOut.toString(),A=d.liquidity.a.toString());let B=P.fromPermill(g.toNumber()),w=N.recalculateAssetFee(x,b,A,"9",n.toString(),P.toDecimals(B).toString(),y.toString(),P.toDecimals(m).toString(),P.toDecimals(h).toString(),u.toString(),c.toString());return[o.toNumber(),Number(w)*1e6,a.toNumber()]}getProtocolFee(e,t,r,s){let{assetIn:i,balanceIn:n}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,m=P.fromPermill(o.toNumber()),h=P.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=s.unwrap(),{protocolFee:g,timestamp:f}=r.unwrap(),y=Math.max(1,t-f.toNumber()),x=d.volume.bIn.toString(),b=d.volume.bOut.toString(),A=d.liquidity.b.toString();i===M&&(x=d.volume.aIn.toString(),b=d.volume.aOut.toString(),A=d.liquidity.a.toString());let B=P.fromPermill(g.toNumber()),w=N.recalculateProtocolFee(x,b,A,"9",n.toString(),P.toDecimals(B).toString(),y.toString(),P.toDecimals(m).toString(),P.toDecimals(h).toString(),u.toString(),c.toString());return[o.toNumber(),Number(w)*1e6,a.toNumber()]}getPoolId(){return(0,tr.encodeAddress)((0,rr.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var R=require("@galacticcouncil/math-xyk"),V=class{static getSpotPrice(e,t,r){return(0,R.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,R.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,R.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,R.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,R.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,R.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,R.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,R.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,R.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,R.calculate_liquidity_out_asset_b)(e,t,r,s)}};var Fe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:a,assetOutED:u}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),n=P.toPct(r.exchangeFee),o=s.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:s,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),n=P.toPct(r.exchangeFee),o=s.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:o,feePct:n,errors:a}}calculateInGivenOut(e,t){let r=V.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=V.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=V.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=_(D,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=V.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=_(D,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=V.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var Ee=class extends U{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[n,o]=s.unwrap(),[a,u]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,o.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:a.toString()},{id:o.toString(),balance:u.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var F=require("@galacticcouncil/math-stableswap"),C=class{static getPoolAddress(e){return(0,F.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,i){return(0,F.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,n,o){return(0,F.calculate_in_given_out)(e,t,r,s,i,n,o)}static calculateAddOneAsset(e,t,r,s,i,n,o){return(0,F.calculate_add_one_asset)(e,t,r,s,i,n,o)}static calculateSharesForAmount(e,t,r,s,i,n,o){return(0,F.calculate_shares_for_amount)(e,t,r,s,i,n,o)}static calculateOutGivenIn(e,t,r,s,i,n,o){return(0,F.calculate_out_given_in)(e,t,r,s,i,n,o)}static calculateLiquidityOutOneAsset(e,t,r,s,i,n,o){return(0,F.calculate_liquidity_out_one_asset)(e,t,r,s,i,n,o)}static calculateShares(e,t,r,s,i,n){return(0,F.calculate_shares)(e,t,r,s,i,n)}static calculateSpotPriceWithFee(e,t,r,s,i,n,o,a){return(0,F.calculate_spot_price_with_fee)(e,t,r,s,i,n,o,a)}static recalculatePegs(e,t,r,s,i){let n=(0,F.recalculate_peg)(e,t,r,s,i);return JSON.parse(n)}};var De=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,r,s,i,n,o,a,u,c,m){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.amplification=n,this.id=o,this.fee=a,this.totalIssuance=u,this.pegs=c,this.pegsFee=m}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=P.toPct(r.fee),o=[],a=N.isSellAllowed(e.tradeableIn),u=N.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),n=P.toPct(r.fee),o=[],a=N.isSellAllowed(e.tradeableIn),u=N.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:n,errors:o}}calculateIn(e,t,r){let s=C.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateAddOneAsset(e,t,r){let s=C.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?P.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateSharesForAmount(e,t,r){let s=C.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?P.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=C.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let s=_(D,e.decimalsIn-e.decimalsOut);return p(t).div(s)}let r=_(D,18-e.decimalsIn);return p(t).div(r)}calculateOut(e,t,r){let s=C.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateWithdrawOneAsset(e,t,r){let s=C.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?P.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateShares(e,t,r){let s=C.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?P.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=C.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let s=_(D,e.decimalsOut-e.decimalsIn);return p(t).div(s)}let r=_(D,18-e.decimalsOut);return p(t).div(r)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};var et=require("@polkadot/util-crypto");var sr=340282366920938463463374607431768211455n,ke=class extends U{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),u=this.getPoolAddress(a),[c,m,h]=await Promise.all([this.getPoolDelta(a,o,r.toString()),this.getPoolTokens(u,a,o),this.getPoolPegs(a,o,r.toString())]);return this.stablePools.set(u,o),{address:u,id:a,type:"Stableswap",fee:P.fromPermill(o.fee.toNumber()),tokens:m,...c,...h,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toString(),s=this.stablePools.get(e.address);if(s){let[i,n]=await Promise.all([this.getPoolDelta(e.id,s,r),this.getPoolPegs(e.id,s,r)]);Object.assign(e,i,n)}})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:n,finalBlock:o}=t,a=C.calculateAmplification(s.toString(),i.toString(),n.toString(),o.toString(),r),u=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:u.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async o=>{let[a,u]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:a.bits.toNumber(),balance:u.toString()}}),n=await Promise.all(i);return n.push({id:t,tradeable:15,balance:sr.toString()}),n}getPoolDefaultPegs(e){let t=e.fee,r=C.defaultPegs(e.assets.length);return{pegsFee:P.fromPermill(t.toNumber()),pegs:r}}async getPoolPegs(e,t,r){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getPoolDefaultPegs(t);let i=s.unwrap(),n=await this.getLatestPegs(t,i,r),o=this.getRecentPegs(i),a=i.maxPegUpdate.toHuman(),u=t.fee.toHuman(),[c,m]=C.recalculatePegs(JSON.stringify(o),JSON.stringify(n),r,a.replace(/%/g,""),u.replace(/%/g,"")),h=Number(c)*1e4;return{pegsFee:P.fromPermill(h),pegs:m}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(i=>i.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,i=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),n=s.map(async(o,a)=>{if(o.isOracle){let[u,c,m]=o.asOracle,h=[m.toString(),i[a]].map(b=>Number(b)).sort((b,A)=>b-A),d=await this.api.query.emaOracle.oracles(u,h,c),[{price:g,updatedAt:f}]=d.unwrap(),y=g.n.toString(),x=g.d.toString();return m.toString()===h[0].toString()?[[y,x],f.toString()]:[[x,y],f.toString()]}else if(o.isMmOracle){let u=o.asMmOracle,{price:c,decimals:m,updatedAt:h}=await this.mmOracle.getData(u.toString()),d=10**m;return[[c.toString(),d.toString()],h.toString()]}else return[o.asValue.map(u=>u.toString()),r]});return Promise.all(n)}getPoolAddress(e){let t=Number(e),r=C.getPoolAddress(t);return(0,et.encodeAddress)((0,et.blake2AsHex)(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var le=class extends L{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=Qe(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new Z(this.api),this.aaveClient=new Ie(this.api,t),this.xykClient=new Ee(this.api,t),this.omniClient=new Re(this.api,t),this.lbpClient=new _e(this.api,t),this.stableClient=new ke(this.api,t),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(s=>s.isSupported()).map(s=>s.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(r=>e.some(s=>s===r.getPoolType())).map(r=>r.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new ve(t.type)}}};var ue=class extends le{feeCache;disconnectSubscribeNewHeads=null;constructor(e,t){super(e,t),this.feeCache=new ae(null),this.api.rpc.chain.subscribeNewHeads(async r=>{this.feeCache.release()}).then(r=>{this.disconnectSubscribeNewHeads=r})}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let i=await super.getPoolFees(e,t);return this.feeCache.set(r,i),i}}async destroy(){this.log(`Destroying pool cache!
2
+ Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var ce=class{static get(e){switch(e.type){case"Aave":return Oe.fromPool(e);case"Xyk":return Fe.fromPool(e);case"Omnipool":return Ne.fromPool(e);case"Lbp":return Ae.fromPool(e);case"Stableswap":return De.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var tt=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 Fr=5,Ce=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new tt,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let o=i.dequeue();if(o==null||o.length>Fr)return s;let a=o[o.length-1];(r===null||a[0]===r)&&s.push(o),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let m=[...o];m.push(c),i.enqueue(m)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,n]of t){let o=parseInt(i),a=parseInt(n);r.get(o)?.push([a,s])}return r}};function At(l){let e={};for(let t of l){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let n=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(n)}}}return e}var Me=class{getProposals(e,t,r){let s=At(r),i=Object.keys(s),n=i.map(c=>s[c]).flat(),o=new Ce,a=o.buildAndPopulateGraph(i,n),u=o.findPaths(a,parseInt(e),t?parseInt(t):null);return this.parsePaths(u)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let n=r[i],o=r[i+1];if(o==null)break;s.push(this.toEdge(n,o))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var me=class{routeSuggester;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new Me,this.routerOptions=Object.freeze({includeOnly:t.includeOnly??[]})}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),n=this.getPaths(e,null,s,t).map(o=>o[o.length-1].assetOut);return this.toAssets([...new Set(n)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(o=>this.validPath(o,r)).map(o=>this.toHops(o,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(r);return{assets:s,poolsMap:i}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,ce.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,i])=>{let n=t.get(r);return{poolAddress:r,poolId:n?.id,pool:n?.type,assetIn:s,assetOut:i}})}toAssets(e,t){return e.map(r=>t.get(r))}};var Er=p("100");function Dr(l,e){return l.minus(e).abs().div(l.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function pe(l,e){return l.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function _t(l,e){return D.minus(e.div(l)).multipliedBy(100).decimalPlaces(2)}function Nt(l,e){return e.div(l).minus(D).multipliedBy(100).decimalPlaces(2)}function Q(l,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),l.div(Er).multipliedBy(e).decimalPlaces(0,1)}var rt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(rt||{}),st=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(st||{}),Rt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(Rt||{});var de=class extends me{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,n=s[s.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[r,s]}}getPoolFeeRange(e){let t=e.min?P.toPct(e.min):void 0,r=e.max?P.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new te(e,t);let a;if(s)a=await this.toSellSwaps(r,s,n);else{let w=o.map(async E=>await this.toSellSwaps(r,E,n)),I=await Promise.all(w);a=this.findBestSellRoute(I)}let u=a[0],c=a[a.length-1],m=this.isDirectTrade(a),h=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,I)=>w.multipliedBy(I)),d=_(h,c.assetOutDecimals),g=m?c.calculatedOut:this.calculateDelta0Y(u.amountIn,a,n),f=c.amountOut,y=m?c.tradeFeePct:_t(g,f).toNumber(),x=g.minus(f),b=this.getRouteFeeRange(a),A=u.amountIn.shiftedBy(-1*u.assetInDecimals).multipliedBy(d),B=pe(g,A);return{type:"Sell",amountIn:u.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:x,tradeFeePct:y,tradeFeeRange:b,priceImpactPct:B.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:T(u.amountIn,u.assetInDecimals),amountOut:T(c.amountOut,c.assetOutDecimals),spotPrice:T(d,c.assetOutDecimals),tradeFee:T(x,c.assetOutDecimals),tradeFeePct:y,tradeFeeRange:b,priceImpactPct:B.toNumber(),swaps:a.map(w=>w.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i>0?u=s[i-1]:u=e;let c=o.calculateOutGivenIn(a,u);s.push(c)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i>0?u=s[i-1].amountOut:u=_(p(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:m,calculatedOut:h,feePct:d,errors:g}=o.validateAndSell(a,u,c),f=this.getPoolFeeRange(c),y=o.spotPriceOutGivenIn(a),x=u.shiftedBy(-1*a.decimalsIn).multipliedBy(y),b=pe(h,x);s.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,amountOut:m,calculatedOut:h,spotPrice:y,tradeFeePct:d,tradeFeeRange:f,priceImpactPct:b.toNumber(),errors:g,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:T(u,a.decimalsIn),amountOut:T(m,a.decimalsOut),calculatedOut:T(h,a.decimalsOut),spotPrice:T(y,a.decimalsOut),tradeFeePct:d,tradeFeeRange:f,priceImpactPct:b.toNumber(),errors:g}}})}return s}async getMostLiquidRoute(e,t){let r=await super.getPools(),{poolsMap:s}=await super.validateTokenPair(e,t,r),i=super.getPaths(e,t,s,r);if(i.length===0)throw new te(e,t);let u=r.filter(d=>d.tokens.some(g=>g.id===e&&g.id!==d.id)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(g=>g.id===e)).map(d=>d.map(g=>p(g.balance).shiftedBy(-1*g.decimals)).reduce((g,f)=>g.plus(f))).sort((d,g)=>g.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=i.map(async d=>await this.toSellSwaps(u,d,s)),m=await Promise.all(c);return this.findBestSellRoute(m).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r);if(super.getPaths(e,t,s,r).length===0)return Promise.resolve(void 0);let n=await this.getMostLiquidRoute(e,t),o=await this.toSellSwaps("1",n,s),a=o.map(m=>m.spotPrice.shiftedBy(-1*m.assetOutDecimals)).reduce((m,h)=>m.multipliedBy(h)),u=o[o.length-1].assetOutDecimals;return{amount:_(a,u),decimals:u}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,n=s[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new te(e,t);let a;if(s)a=await this.toBuySwaps(r,s,n);else{let w=o.map(async E=>await this.toBuySwaps(r,E,n)),I=await Promise.all(w);a=this.findBestBuyRoute(I)}let u=a[a.length-1],c=a[0],m=this.isDirectTrade(a),h=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetInDecimals)).reduce((w,I)=>w.multipliedBy(I)),d=_(h,c.assetInDecimals),g=m?c.calculatedIn:this.calculateDelta0X(u.amountOut,a,n),f=c.amountIn,y=m?c.tradeFeePct:Nt(g,f).toNumber(),x=f.minus(g),b=this.getRouteFeeRange(a),A=u.amountOut.shiftedBy(-1*u.assetOutDecimals).multipliedBy(d),B;return g.isZero()?B=-100:B=pe(A,g).toNumber(),{type:"Buy",amountOut:u.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:x,tradeFeePct:y,tradeFeeRange:b,priceImpactPct:B,swaps:a,toHuman(){return{type:"Buy",amountOut:T(u.amountOut,u.assetOutDecimals),amountIn:T(c.amountIn,c.assetInDecimals),spotPrice:T(d,c.assetInDecimals),tradeFee:T(x,c.assetInDecimals),tradeFeePct:y,tradeFeeRange:b,priceImpactPct:B,swaps:a.map(w=>w.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=e:u=s[0];let c=o.calculateInGivenOut(a,u);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=_(p(e),a.decimalsOut).decimalPlaces(0,1):u=s[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:m,calculatedIn:h,feePct:d,errors:g}=o.validateAndBuy(a,u,c),f=this.getPoolFeeRange(c),y=o.spotPriceInGivenOut(a),x=u.shiftedBy(-1*a.decimalsOut).multipliedBy(y),b;h.isZero()?b=-100:b=pe(x,h).toNumber(),s.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:m,amountOut:u,calculatedIn:h,spotPrice:y,tradeFeePct:d,tradeFeeRange:f,priceImpactPct:b,errors:g,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:T(m,a.decimalsIn),amountOut:T(u,a.decimalsOut),calculatedIn:T(h,a.decimalsIn),spotPrice:T(y,a.decimalsIn),tradeFeePct:d,tradeFeeRange:f,priceImpactPct:b,errors:g}}})}return s}};var ir=6e3,nr=p(1e15),Le=6,Ft=-5,Et=6*60*60*1e3;var or=6;var G=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:i})=>s==="Stableswap"?{pool:{Stableswap:i},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var ge=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??ir,minBudgetInNative:t.minBudgetInNative??nr})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[n,o]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:u,priceImpactPct:c}=o,m=u[0],h=u[u.length-1],{assetInDecimals:d}=m,{assetOutDecimals:g}=h,f=Math.abs(c),y=this.getMinimumTradeCount(a,n),x=this.getOptimalTradeCount(f),b=i?Math.round(s/i):x,A=Math.ceil(s/y),B=Math.round(s/x),w=Math.round(s/b),I=a.dividedBy(b).decimalPlaces(0,1),E=await this.router.getBestSell(e,t,T(I,d)),H=a.isLessThan(n),qe=[];H&&qe.push("OrderTooSmall");let Ue=E.amountOut.multipliedBy(b),ot=this.toBlockPeriod(w),at=E.tradeFee.multipliedBy(b),lt=G.build(u),Ge={assetIn:e,assetOut:t,errors:qe,frequencyMin:A,frequencyOpt:B,frequency:w,tradeCount:b,tradeFee:at,tradeImpactPct:E.priceImpactPct,tradePeriod:ot,tradeRoute:lt,type:"Dca"};return{...Ge,amountIn:a,amountOut:Ue,tradeAmountIn:E.amountIn,tradeAmountOut:E.amountOut,toHuman(){return{...Ge,amountIn:T(a,d),amountOut:T(Ue,g),tradeAmountIn:T(E.amountIn,d),tradeAmountOut:T(E.amountOut,g)}}}}async getMinimumOrderBudget(e){if(M===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(M,e);if(t)return this.minOrderBudget.times(t.amount).div(p(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:o,priceImpactPct:a}=i,u=o[0],c=o[o.length-1],{assetInDecimals:m}=u,{assetOutDecimals:h}=c,d=Math.abs(a),g=this.getTwapTradeCount(d),f=n.dividedBy(g).decimalPlaces(0,1),y=await this.router.getBestSell(u.assetIn,c.assetOut,T(f,m)),x=g===1,b=n.isLessThan(s),A=y.priceImpactPct<Ft,B=[];b||x?B.push("OrderTooSmall"):A&&B.push("OrderImpactTooBig");let w=y.amountOut.multipliedBy(g),I=y.tradeFee.multipliedBy(g),E=G.build(o),H={assetIn:e,assetOut:t,errors:B,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:Le,tradeRoute:E,type:"TwapSell"};return{...H,amountIn:n,amountOut:w,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:I,toHuman(){return{...H,amountIn:T(n,m),amountOut:T(w,h),tradeAmountIn:T(y.amountIn,m),tradeAmountOut:T(y.amountOut,h),tradeFee:T(I,h)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:n,swaps:o,priceImpactPct:a}=i,u=o[0],c=o[o.length-1],{assetInDecimals:m}=u,{assetOutDecimals:h}=c,d=Math.abs(a),g=this.getTwapTradeCount(d),f=n.dividedBy(g).decimalPlaces(0,1),y=await this.router.getBestBuy(u.assetIn,c.assetOut,T(f,h)),x=y.amountIn.multipliedBy(g),b=g===1,A=x.isLessThan(s),B=y.priceImpactPct<Ft,w=[];A||b?w.push("OrderTooSmall"):B&&w.push("OrderImpactTooBig");let I=y.tradeFee.multipliedBy(g),E=G.build(o),H={assetIn:e,assetOut:t,errors:w,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:Le,tradeRoute:E,type:"TwapBuy"};return{...H,amountIn:x,amountOut:n,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:I,toHuman(){return{...H,amountIn:T(x,m),amountOut:T(n,h),tradeAmountIn:T(y.amountIn,m),tradeAmountOut:T(y.amountOut,h),tradeFee:T(I,m)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>Et){let s=Et/(this.blockTime*Le);return Math.round(s)}return t}getTwapExecutionTime(e){return e*Le*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,or)}};var he=class extends L{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new q(e),this.aaveUtils=new J(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),fe)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var it=class extends he{_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:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:i,assetOut:n}=s,a=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),u=!0;return s.isWithdraw()&&(u=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,n)).amount.isGreaterThanOrEqualTo(a)),u&&e.isGreaterThanOrEqualTo(a)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=Q(e,this.slippagePct),o=s.assetIn,a=i.assetOut,u=e.plus(n),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(a,o,t.toFixed(),u.toFixed()):c=this.api.tx.router.buy(o,a,t.toFixed(),u.toFixed(),G.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=Q(t,this.slippagePct),o=s.assetIn,a=i.assetOut,u=t.minus(n),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(o,a,e.toFixed(),u.toFixed()):c=this.api.tx.router.sell(o,a,e.toFixed(),u.toFixed(),G.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let h=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSellAll",h,fe)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=Q(e,this.slippagePct),n=r.assetIn,o=s.assetOut,a=e.minus(i),u=this.api.tx.router.sellAll(n,o,a.toFixed(),G.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let m=this.dispatchWithExtraGas(u);return this.wrapTx("RouterSellAll",m,fe)}return this.wrapTx("RouterSellAll",u)}};var nt=class extends he{_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:r,tradeAmountIn:s,tradePeriod:i,tradeRoute:n}=this.order,o=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:n}}},null);return this.wrapTx("DcaSchedule",o)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:o}=this.order,a=Q(i,this.slippagePct),u=i.minus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:u.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:o}=this.order,a=Q(s,this.slippagePct),u=s.plus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:i.toFixed(),maxAmountIn:u.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var ye=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new it(this.api,this.evm).setTrade(e)}order(e){return new nt(this.api,this.evm).setOrder(e)}};function kr(l){let e=new ne(l),t=new we(l),r=new ue(l,t),s=new J(t),i=new de(r),n=new ge(i,{blockTime:e.blockTime,minBudgetInNative:e.minOrderBudget});return{api:{aave:s,router:i,scheduler:n},client:{asset:new Z(l),balance:new q(l)},ctx:{pool:r},evm:t,tx:new ye(l,t),destroy:()=>{r.destroy()}}}0&&(module.exports={AMOUNT_MAX,AaveClient,AavePool,AavePoolClient,AaveUtils,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,ChainParams,DECIMAL_PLACES,DENOMINATOR,ERC20,EvmClient,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,ONE,OmniMath,OmniPool,OmniPoolClient,PolkadotApiClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StableSwapClient,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeOrderError,TradeOrderType,TradeRouteBuilder,TradeRouter,TradeScheduler,TradeType,TxBuilderFactory,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,createChain,createSdkContext,findNestedKey,findNestedObj,getFraction,isEvmAccount,isEvmAddress,isSs58Address,scale,toBn,toDecimals});
package/build/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var ye=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var qe=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Ze="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ge="0x112b087b60C1a166130d59266363C45F8aa99db0",We="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Z=1000000n;var jr=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Q=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:qe,address:Ge,args:[We],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:qe,address:Ge,args:[We,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:ye,address:Ze,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as Se,encodeAddress as et}from"@polkadot/util-crypto";import{hexToU8a as Bt,isHex as It,u8aToHex as At}from"@polkadot/util";import{Buffer as H}from"buffer";var rs=2090,He=1e3,fe="1",ss=2034,W=63,ee=18,D="0",Qe=12,te=15;var Xe="ETH\0";function vt(p){if(!p)return!1;try{let e=Se(p,!0),t=H.from(Xe);return H.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Nt(p){return!!/^0x[a-fA-F0-9]{40}$/.test(p)}function Ft(p){try{let e=It(p)?Bt(p):Se(p);return et(e),!0}catch{return!1}}var z=class p{static toAccount=e=>{let t=H.from(e.slice(2),"hex"),r=H.from(Xe);return et(new Uint8Array(H.concat([r,t,H.alloc(8)])),63)};static fromAccount=e=>{let t=Se(e),r=H.from(Xe),s=t.slice(r.length,-8);return"0x"+H.from(s).toString("hex")};static fromSS58=e=>{let r=Se(e).slice(0,20);return At(r)};static fromAny=e=>{if(Nt(e))return e;if(vt(e))return p.fromAccount(e);if(Ft(e))return p.fromSS58(e);throw new Error("Unknown address type")}};var G=class{static fromAssetId(e){let t=Number(e),r=Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.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"),r=Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as w}from"bignumber.js";var Rt=12;w.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Rt});var S=m(0),R=m(1),ps=m("Infinity");function v(p,e){let t=new w(e.toString()),r=new w(10).pow(t);return p.times(r)}function m(p){return new w(p.toString())}function ds(p,e){let t=m(p);return v(t,e)}function x(p,e){return p.shiftedBy(-1*e).toString()}var Te=m("1e27"),Et=m("1.01"),_t=m("31536000"),Y=class{client;constructor(e){this.client=new Q(e)}async getSummary(e){let t=z.fromAny(e),[r,s,n,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[i]=r,[o,l]=s,[u,c,h,d,g,b]=n,P=m(b).dividedBy(1e18).decimalPlaces(6,w.ROUND_DOWN),T=m(u),f=m(c),A=[];for(let B of o){let O=B.underlyingAsset.toLowerCase(),I=i.find(({underlyingAsset:xt})=>xt.toLowerCase()===O);if(!I)throw new Error("Missing pool reserve for "+O);let F=m(B.scaledATokenBalance),U=m(I.liquidityIndex),he=m(I.liquidityRate),Pe=m(I.availableLiquidity),Me=m(I.priceInMarketReferenceCurrency),Le=a+6,Ue=this.calculateLinearInterest(he,I.lastUpdateTimestamp,Le),be=U.multipliedBy(Ue).dividedBy(Te).decimalPlaces(0,w.ROUND_DOWN),St=F.multipliedBy(be).dividedBy(Te).decimalPlaces(0,w.ROUND_DOWN),Tt=m(l!==0&&l===I.eModeCategoryId?I.eModeLiquidationThreshold:I.reserveLiquidationThreshold).div(1e4),Ot=I.usageAsCollateralEnabled&&B.usageAsCollateralEnabledOnUser&&m(B.scaledATokenBalance).gt(0),wt=G.toAssetId(O);A.push({aTokenBalance:St,availableLiquidity:Pe,decimals:Number(I.decimals),isCollateral:Ot,priceInRef:Me,reserveId:wt,reserveAsset:O,reserveLiquidationThreshold:Tt})}return{healthFactor:P.toNumber(),totalCollateral:T,totalDebt:f,reserves:A}}async hasBorrowPositions(e){let t=z.fromAny(e),r=await this.client.getUserAccountData(t),[s,n]=r;return n>0n}async getHealthFactor(e){let t=z.fromAny(e),r=await this.client.getUserAccountData(t),[s,n,a,i,o,l]=r;return m(l).dividedBy(1e18).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:n,reserves:a}=await this.getSummary(e),i=G.fromAssetId(t),o=a.find(T=>T.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:u,priceInRef:c,reserveLiquidationThreshold:h}=o,d=v(m(r),l).decimalPlaces(0,1),g=u?d.multipliedBy(c).dividedBy(m(10).pow(l)).decimalPlaces(0,w.ROUND_DOWN):S,b=s.minus(g);return b.lte(0)?0:b.multipliedBy(h).dividedBy(n).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:n,reserves:a}=await this.getSummary(e),i=G.fromAssetId(t),o=a.find(P=>P.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:c}=o,d=v(m(r),l).decimalPlaces(0,1).multipliedBy(u).dividedBy(m(10).pow(l)).decimalPlaces(0,w.ROUND_DOWN),g=s.plus(d);return g.lte(0)?0:g.multipliedBy(c).dividedBy(n).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:n}=await this.getSummary(e),a=G.fromAssetId(t),i=s.find(o=>o.reserveAsset===a);if(!i)throw new Error("Missing reserve data for "+a);return this.calculateWithdrawMax(i,r,n)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),n={};for(let a of r){let i=this.calculateWithdrawMax(a,t,s);a.reserveId&&(n[a.reserveId]=i)}return n}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:n,decimals:a,priceInRef:i,reserveLiquidationThreshold:o,isCollateral:l}=e,u=s;if(l&&t.gt(0)){let h=m(r).minus(Et);if(h.gt(0)){let g=h.multipliedBy(t).dividedBy(o).decimalPlaces(0,w.ROUND_DOWN).dividedBy(i).multipliedBy(m(10).pow(a)).decimalPlaces(0,w.ROUND_DOWN);u=w.minimum(s,g)}else u=S}return{amount:w.minimum(u,n),decimals:a}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Te:e.multipliedBy(s).dividedBy(_t).plus(Te).decimalPlaces(0,w.ROUND_DOWN)}};function tt(p){switch(p){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var k=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");tt(r)&&console.log(e,...t)}};var $=class extends k{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:n}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:n.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==D){let c=this.api.consts.balances.existentialDeposit;return{id:D,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:c.toString()}}let{name:n,assetType:a,isSufficient:i,existentialDeposit:o}=t,{symbol:l,decimals:u}=r.get(e)??{};return{id:e,name:n.toHuman(),symbol:l,decimals:u,icon:l,type:a.toHuman(),isSufficient:i?i.toHuman():!0,location:s?.toJSON(),existentialDeposit:o.toString()}}getBond(e,t,r,s){let[n,a]=s,{assetType:i,isSufficient:o,existentialDeposit:l}=t,{symbol:u,decimals:c}=this.getToken(n.toString(),t,r),h=a.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",d.format(h)].join(" ");return{id:e,name:g,symbol:u+"b",decimals:c,icon:u,type:i.toString(),isSufficient:o.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:n.toString(),maturity:h}}getShares(e,t,r,s){let{assets:n}=s,{name:a,symbol:i,assetType:o,isSufficient:l,existentialDeposit:u}=t,h=n.map(b=>b.toString()).map(b=>{let{symbol:P}=this.getToken(b,t,r);return[b,P]}),d=Object.fromEntries(h),g=Object.values(d);return{id:e,name:g.join(", "),symbol:i?.isSome?i.toHuman():a.toHuman(),decimals:18,icon:g.join("/"),type:o.toString(),isSufficient:l.toHuman(),existentialDeposit:u.toString(),meta:d}}getExternal(e,t,r,s){let n=this.getToken(e,t,new Map,s),a=r?.find(i=>i.internalId===n.id);return a?{...n,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:n}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:n,symbol:a}=s.unwrap();return[r.toString(),{decimals:Number(n.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,n,a,i]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),o=this.getSupportedAssets(r),l=this.normalizeMetadata(o,i),u=o.map(([{args:[c]},h])=>{let d=h.unwrap(),g=s.get(c.toString()),{assetType:b}=d;switch(b.toString()){case"Bond":let P=a.get(c.toString());return this.getBond(c.toString(),d,l,P);case"StableSwap":let T=n.get(c.toString());return this.getShares(c.toString(),d,l,T);case"External":return this.getExternal(c.toString(),d,t,g);default:return this.getToken(c.toString(),d,l,g)}});return e?u:u.filter(c=>this.isValidAsset(c))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var M=class extends k{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===D?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:n}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:n})}async getErc20Balance(e,t){let{free:r,reserved:s,frozen:n}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:r,feeFrozen:0n,frozen:n})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(D,this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),n=r?r.map(a=>[e,a]):s.map(({args:[a,i]})=>[a.toString(),i.toString()]);return this.api.query.tokens.accounts.multi(n,a=>{let i=[];a.forEach((o,l)=>{let u=this.calculateFreeBalance(o),c=n[l][1];i.push([c,u])}),t(i)})}async subscribeErc20Balance(e,t,r){let n=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([o,l])=>{let{assetType:u}=l.unwrap();return u.toString()==="Erc20"}).map(([{args:[o]}])=>o.toString()))(),a=async()=>{let i=await Promise.all(n.map(async o=>[o,await this.getErc20Balance(e,o)]));t(i)};return this.api.rpc.chain.subscribeNewHeads(async()=>{a()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:n}=e,a=new w(t),i=new w(r||n),o=new w(s||0n),l=i.gt(o)?i:o;return a.minus(l)}};var re=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),m(this._minOrderBudget)}};import{fixed_from_rational as rt}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as Dt}from"@polkadot/types";import{u8aConcat as st}from"@polkadot/util";import{isAddress as nt}from"@polkadot/util-crypto";var Ye=class extends k{balanceClient;constructor(e){super(e),this.balanceClient=new M(e)}secondsInYear=new w(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,n])=>{let[,a]=s.args,i=n.unwrap().toString(),o=a.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(o)).unwrap(),u=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,o,i)).unwrap(),c=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(o),!1).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:u,priceAdjustment:c,potBalance:b.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,n])=>{let[,a]=s.args,i=n.unwrap().toString(),o=a.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(o)).unwrap(),u=(await this.api.query.xykWarehouseLM.yieldFarm(e,o,i)).unwrap(),c=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(o),!0).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:u,priceAdjustment:c,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new w(1).shiftedBy(18).toString();let n=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(n.isNone)return;let[a]=n.unwrap(),i=a.price.n.toString(),o=a.price.d.toString(),l;return Number(t)<Number(r)?l=rt(i,o):l=rt(o,i),l}getGlobalRewardPerPeriod(e,t,r,s){let a=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return a.gte(r)?r:a}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return st(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",n=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Dt(e,this.padEndU8a(st(s,n,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!nt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&nt(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:i,globalFarm:o,priceAdjustment:l,potBalance:u})=>{let c=new w(o.totalSharesZ.toString()),h=o.plannedYieldingPeriods.toString(),d=new w(o.yieldPerPeriod.toString()),g=new w(o.maxRewardPerPeriod.toString()),b=o.blocksPerPeriod.toString(),P=new w(i.multiplier.toString()).shiftedBy(-18),T=this.secondsInYear.div(new w(r).times(b)),f;if(c.isZero())f=d.times(P).times(T);else{let F=this.getGlobalRewardPerPeriod(c,d,g,l);f=this.getPoolYieldPerPeriod(F,P,c,l).times(T)}let A=new w(o.pendingRewards.toString()).plus(o.accumulatedPaidRewards.toString()),B=g.times(h),O=u?A.plus(u):B;return A.div(O).gte(.999)?S:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((i,o)=>i.plus(o),S).toString():void 0}};var Oe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},it=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},K=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},at=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},ot=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},lt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},ut=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{defineChain as kt}from"viem";var Ct=["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"],ct=p=>{let e=p.__internal__endpoints,t=e.some(s=>Ct.includes(s)),r=e.map(s=>s.replace("wss://","https://").replace("ws://","http://"));return kt({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:t?"https://explorer.evm.hydration.cloud":"https://explorer.nice.hydration.cloud"}},testnet:!t})};import{createPublicClient as pt,createWalletClient as Mt,custom as Lt,http as Ut}from"viem";function mt(p){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return p.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var we=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=ct(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return pt({chain:this.chain,transport:Ut()})}getWsProvider(){return pt({chain:this.chain,transport:mt(this.wsProvider)})}getSigner(e){return Mt({account:e,chain:this.chain,transport:Lt(window.ethereum)})}};import{LRUCache as Wr}from"@thi.ng/cache";import{memoize1 as Gr}from"@thi.ng/memoize";var E=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n))(E||{}),J=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n))(J||{});var xe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,n){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(o=>[o.id,o])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let a=m(s.balance),i=m(n.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:a,balanceOut:i,assetInED:S,assetOutED:S}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=[];return t.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:n}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=[];return s.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:n}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return v(R,e.decimalsOut)}spotPriceOutGivenIn(e){return v(R,e.decimalsIn)}calculateTradeFee(e,t){return S}};import{encodeAddress as Wt}from"@polkadot/util-crypto";import{stringToU8a as Ht}from"@polkadot/util";import{decodeEventLog as Xt}from"viem";function dt(p,e){let t=[];return JSON.stringify(p,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Nn(p,e,t){let r;return JSON.stringify(p,(s,n)=>(n&&n[e]===t&&(r=n),n)),r}var Fn=(p,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as qt}from"@thi.ng/memoize";import{TLRUCache as Gt}from"@thi.ng/cache";var $e=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var se=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,n]=await Promise.all([this.client.readContract({abi:$e,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:$e,address:e,functionName:"decimals"}),this.client.getBlock()]),[a,i,o,l]=r,u=n.number-(n.timestamp-l)/BigInt(t),c=Number(u);return{price:i,decimals:s,updatedAt:c<0?0:c}}};var C=class extends M{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Gt(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=qt(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new se(t)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let r=[];try{let n=this.subscribePoolChange(t);r.push(n)}catch{}if(t.type==="Aave")return r;let s=this.subscribeTokensPoolBalance(t);if(r.push(s),this.hasSystemAsset(t)){let n=this.subscribeSystemPoolBalance(t);r.push(n)}if(this.hasErc20Asset(t)){let n=this.subscribeErc20PoolBalance(t);r.push(n)}return this.subscribeLog(t),r}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,n])=>{let a=e.tokens.findIndex(i=>i.id==s);a>=0&&t(e,s)&&(e.tokens[a].balance=n.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(n=>n.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};var Yt=["Supply","Withdraw","Repay","Borrow"],Be=class extends C{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:n})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:n.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let r=e+"/"+t;return Wt(Ht(r.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,r]=e.tokens,s=this.getReserveH160Id(t);return this.api.query.system.events(n=>{n.forEach(a=>{let{event:i}=a,o=`${i.section}:${i.method}`;if(o==="router:Executed"){let{assetIn:l,assetOut:u}=i.data.toHuman(),c=l.replace(/,/g,""),h=u.replace(/,/g,"");(c===r.id||h===r.id)&&(this.log(`Sync AAVE [router:Executed] :: ${c}:${h}`),this.updatePoolState(e))}if(o==="evm:Log"){let{log:l}=i.data.toHuman();try{let{eventName:u,args:c}=Xt({abi:ye,topics:l.topics,data:l.data});Yt.includes(u)&&c.reserve.toLowerCase()===s.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${u} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:n}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(a=>{let i=a.id===t.id?s.toString():n.toString();return{...a,balance:i}})}getReserveH160Id(e){return e.type==="Erc20"?dt(e.location,"accountKey20").accountKey20.key:G.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as $t,calculate_out_given_in as Vt,calculate_linear_weights as zt,calculate_pool_trade_fee as Kt,get_spot_price as Jt}from"@galacticcouncil/math-lbp";var q=class{static getSpotPrice(e,t,r,s,n){return Jt(e,t,r,s,n)}static calculateInGivenOut(e,t,r,s,n){return $t(e,t,r,s,n)}static calculateOutGivenIn(e,t,r,s,n){return Vt(e,t,r,s,n)}static calculateLinearWeights(e,t,r,s,n){return zt(e,t,r,s,n)}static calculatePoolTradeFee(e,t,r){return Kt(e,t,r)}};var y=class{static toPct(e){return e[0]/e[1]*100}static toDecimals(e){return e[0]/e[1]}static fromPermill(e){return[e/1e3,1e3]}};var Ie=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,n,a,i){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n,this.fee=a,this.repayFeeApply=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(o=>[o.id,o])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let a=m(s.balance),i=m(n.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:i,decimalsIn:s.decimals,decimalsOut:n.decimals,weightIn:s.weight,weightOut:n.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&n.push("MaxOutRatioExceeded"),s===e.assetOut){let i=this.calculateTradeFee(t,r),o=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(i),u=this.calculateInGivenOut(e,l),c=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(c)&&n.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:t,feePct:o,errors:n}}else{let i=this.calculateInGivenOut(e,t),o=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(o)&&n.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:i,amountOut:t,feePct:0,errors:n}}}validateAndSell(e,t,r){let s=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&n.push("MaxInRatioExceeded"),s===e.assetIn){let i=this.calculateOutGivenIn(e,t),o=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(o)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:i,feePct:0,errors:n}}else{let i=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(i,r),l=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),u=i.minus(o),c=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(c)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:u,feePct:l,errors:n}}}calculateInGivenOut(e,t){let r=q.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=q.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=q.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),v(R,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=q.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),v(R,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let r=q.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(r)}};var Ae=class extends C{MAX_FINAL_WEIGHT=v(m(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([n,a])=>this.isActivePool(a.unwrap(),r)).map(async([{args:[n]},a])=>{let i=a.unwrap(),o=n.toString(),l=await this.getPoolDelta(o,i,r.toString());return this.poolsData.set(n.toString(),i),{address:o,type:"Lbp",fee:i.fee.toJSON(),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let a=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(i=>i.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,r){let{start:s,end:n,assets:a,initialWeight:i,finalWeight:o,repayTarget:l,feeCollector:u}=t,c=q.calculateLinearWeights(s.toString(),n.toString(),i.toString(),o.toString(),r),[h,d]=a,g=h.toString(),b=m(c),P=d.toString(),T=this.MAX_FINAL_WEIGHT.minus(m(b)),[f,A,B]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),u.toString()),this.getBalance(e,g),this.getBalance(e,P)]);return{repayFeeApply:f,tokens:[{id:g,weight:b,balance:A.toString()},{id:P,weight:T,balance:B.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=m(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as jt,calculate_lrna_in_given_out as Zt,calculate_out_given_in as Qt,calculate_out_given_lrna_in as er,calculate_pool_trade_fee as tr,calculate_spot_price as rr,calculate_lrna_spot_price as sr,calculate_shares as nr,calculate_liquidity_out as ir,calculate_liquidity_lrna_out as ar,calculate_liquidity_hub_in as or,is_sell_allowed as lr,is_buy_allowed as ur,is_add_liquidity_allowed as cr,is_remove_liquidity_allowed as mr,recalculate_asset_fee as pr,recalculate_protocol_fee as dr,verify_asset_cap as gr}from"@galacticcouncil/math-omnipool";var N=class{static calculateSpotPrice(e,t,r,s){return rr(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return sr(e,t)}static calculateInGivenOut(e,t,r,s,n,a,i,o,l){return jt(e,t,r,s,n,a,i,o,l)}static calculateLrnaInGivenOut(e,t,r,s,n){return Zt(e,t,r,s,n)}static calculateOutGivenIn(e,t,r,s,n,a,i,o,l){return Qt(e,t,r,s,n,a,i,o,l)}static calculateOutGivenLrnaIn(e,t,r,s,n){return er(e,t,r,s,n)}static calculatePoolTradeFee(e,t,r){return tr(e,t,r)}static calculateShares(e,t,r,s){return nr(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,n,a,i,o){return ir(e,t,r,s,n,a,i,o)}static calculateLiquidityLRNAOut(e,t,r,s,n,a,i,o){return ar(e,t,r,s,n,a,i,o)}static calculateCapDifference(e,t,r,s){let n=w(t),a=w(e),i=w(s),l=w(r).shiftedBy(-18);if(n.div(i).lt(l)){let c=l.times(i).minus(n).times(a),h=n.times(w(1).minus(l));return c.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return or(e,t,r,s)}static isSellAllowed(e){return lr(e)}static isBuyAllowed(e){return ur(e)}static isAddLiquidityAllowed(e){return cr(e)}static isRemoveLiquidityAllowed(e){return mr(e)}static recalculateAssetFee(e,t,r,s,n,a,i,o,l,u,c){return pr(e,t,r,s,n,a,i,o,l,u,c)}static recalculateProtocolFee(e,t,r,s,n,a,i,o,l,u,c){return dr(e,t,r,s,n,a,i,o,l,u,c)}static verifyAssetCap(e,t,r,s){return gr(e,t,r,s)}};var ve=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,n,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let a=m(s.balance),i=m(n.balance),o=m(s.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:n.hubReserves,sharesIn:s.shares,sharesOut:n.shares,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:a,balanceOut:i,tradeableIn:s.tradeable,tradeableOut:n.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,r),a=n.minus(s),i=s===S?S:a.div(s).multipliedBy(100).decimalPlaces(2),o=[],l=N.isSellAllowed(e.tradeableIn),u=N.isBuyAllowed(e.tradeableOut);(!l||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let c=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(c)&&o.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(h)&&o.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:t,feePct:i.toNumber(),errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,r),i=s.minus(n).div(s).multipliedBy(100).decimalPlaces(2),o=[],l=N.isSellAllowed(e.tradeableIn),u=N.isBuyAllowed(e.tradeableOut);(!l||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let c=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(c)&&o.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(h)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:i.toNumber(),errors:o}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=N.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString(),r?y.toDecimals(r.protocolFee).toString():S.toString()),n=m(s);return n.isNegative()?S:n}calculateLrnaInGivenOut(e,t,r){let s=N.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString()),n=m(s);return n.isNegative()?S:n}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=N.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString(),r?y.toDecimals(r.protocolFee).toString():S.toString()),n=m(s);return n.isNegative()?S:n}calculateOutGivenLrnaIn(e,t,r){let s=N.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString()),n=m(s);return n.isNegative()?S:n}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=N.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=N.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=N.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=N.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as hr}from"@polkadot/util-crypto";import{stringToU8a as Pr}from"@polkadot/util";var Ne=class extends C{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,n]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=r.map(async([{args:[o]},l])=>{let{hubReserve:u,shares:c,tradable:h,cap:d,protocolShares:g}=l.unwrap(),b=await this.getBalance(t,o.toString());return{id:o.toString(),hubReserves:m(u.toString()),shares:m(c.toString()),tradeable:h.bits.toNumber(),balance:b.toString(),cap:m(d.toString()),protocolShares:m(g.toString())}}),i=await Promise.all(a);return i.push({id:e,tradeable:s.bits.toNumber(),balance:n.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:i,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=e.assetOut,s=e.assetIn,n="omnipool",a="Short",i=B=>B===D?[D,fe]:[fe,B],[o,l,u,c]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(r),this.api.query.emaOracle.oracles(n,i(r),a),this.api.query.emaOracle.oracles(n,i(s),a)]),[h,d,g]=this.getAssetFee(e,o.toNumber(),l,u),[b,P,T]=s===fe?[0,0,0]:this.getProtocolFee(e,o.toNumber(),l,c),f=h+b,A=g+T;return{assetFee:y.fromPermill(d),protocolFee:y.fromPermill(P),min:y.fromPermill(f),max:y.fromPermill(A)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,n)=>{let a=e.tokens[n];if(s.isNone)return a;let i=s.unwrap();return this.updateTokenState(a,i)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:n,cap:a,protocolShares:i}=t;return{...e,hubReserves:m(r.toString()),shares:m(s.toString()),cap:m(a.toString()),protocolShares:m(i.toString()),tradeable:n.bits.toNumber()}}getAssetFee(e,t,r,s){let{assetOut:n,balanceOut:a}=e,{minFee:i,maxFee:o,decay:l,amplification:u}=this.api.consts.dynamicFees.assetFeeParameters,c=y.fromPermill(i.toNumber()),h=y.fromPermill(o.toNumber());if(r.isNone||s.isNone)return[i.toNumber(),i.toNumber(),o.toNumber()];let[d]=s.unwrap(),{assetFee:g,timestamp:b}=r.unwrap(),P=Math.max(1,t-b.toNumber()),T=d.volume.bIn.toString(),f=d.volume.bOut.toString(),A=d.liquidity.b.toString();n===D&&(T=d.volume.aIn.toString(),f=d.volume.aOut.toString(),A=d.liquidity.a.toString());let B=y.fromPermill(g.toNumber()),O=N.recalculateAssetFee(T,f,A,"9",a.toString(),y.toDecimals(B).toString(),P.toString(),y.toDecimals(c).toString(),y.toDecimals(h).toString(),l.toString(),u.toString());return[i.toNumber(),Number(O)*1e6,o.toNumber()]}getProtocolFee(e,t,r,s){let{assetIn:n,balanceIn:a}=e,{minFee:i,maxFee:o,decay:l,amplification:u}=this.api.consts.dynamicFees.protocolFeeParameters,c=y.fromPermill(i.toNumber()),h=y.fromPermill(o.toNumber());if(r.isNone||s.isNone)return[i.toNumber(),i.toNumber(),o.toNumber()];let[d]=s.unwrap(),{protocolFee:g,timestamp:b}=r.unwrap(),P=Math.max(1,t-b.toNumber()),T=d.volume.bIn.toString(),f=d.volume.bOut.toString(),A=d.liquidity.b.toString();n===D&&(T=d.volume.aIn.toString(),f=d.volume.aOut.toString(),A=d.liquidity.a.toString());let B=y.fromPermill(g.toNumber()),O=N.recalculateProtocolFee(T,f,A,"9",a.toString(),y.toDecimals(B).toString(),P.toString(),y.toDecimals(c).toString(),y.toDecimals(h).toString(),l.toString(),u.toString());return[i.toNumber(),Number(O)*1e6,o.toNumber()]}getPoolId(){return hr(Pr("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as br,calculate_out_given_in as yr,calculate_pool_trade_fee as fr,get_spot_price as Sr,calculate_liquidity_in as Tr,calculate_shares as Or,calculate_spot_price as wr,calculate_spot_price_with_fee as xr,calculate_liquidity_out_asset_a as Br,calculate_liquidity_out_asset_b as Ir}from"@galacticcouncil/math-xyk";var X=class{static getSpotPrice(e,t,r){return Sr(e,t,r)}static calculateInGivenOut(e,t,r){return br(e,t,r)}static calculateOutGivenIn(e,t,r){return yr(e,t,r)}static calculatePoolTradeFee(e,t,r){return fr(e,t,r)}static calculateLiquidityIn(e,t,r){return Tr(e,t,r)}static calculateSpotPrice(e,t){return wr(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return xr(e,t,r,s)}static calculateShares(e,t,r){return Or(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return Br(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Ir(e,t,r,s)}};var Fe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,n){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let a=m(s.balance),i=m(n.balance),o=m(s.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:a,balanceOut:i,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=this.calculateTradeFee(s,r),a=y.toPct(r.exchangeFee),i=s.plus(n),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&o.push("MaxOutRatioExceeded");let u=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(u)&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a,errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(s,r),a=y.toPct(r.exchangeFee),i=s.minus(n),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&o.push("MaxInRatioExceeded");let u=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(u)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a,errors:o}}calculateInGivenOut(e,t){let r=X.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=X.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=X.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=v(R,18-e.decimalsOut);return m(t).div(r)}spotPriceOutGivenIn(e){let t=X.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=v(R,18-e.decimalsIn);return m(t).div(r)}calculateTradeFee(e,t){let r=X.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(r)}};var Re=class extends C{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let n=r.toString(),[a,i]=s.unwrap(),[o,l]=await Promise.all([this.getBalance(n,a.toString()),this.getBalance(n,i.toString())]);return{address:n,type:"Xyk",tokens:[{id:a.toString(),balance:o.toString()},{id:i.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as Ar,calculate_out_given_in as vr,calculate_amplification as Nr,calculate_add_one_asset as Fr,calculate_liquidity_out_one_asset as Rr,calculate_pool_trade_fee as Er,calculate_shares as _r,calculate_shares_for_amount as Dr,calculate_spot_price_with_fee as kr,pool_account_name as Cr,recalculate_peg as Mr}from"@galacticcouncil/math-stableswap";var _=class{static getPoolAddress(e){return Cr(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,n){return Nr(e,t,r,s,n)}static calculateInGivenOut(e,t,r,s,n,a,i){return Ar(e,t,r,s,n,a,i)}static calculateAddOneAsset(e,t,r,s,n,a,i){return Fr(e,t,r,s,n,a,i)}static calculateSharesForAmount(e,t,r,s,n,a,i){return Dr(e,t,r,s,n,a,i)}static calculateOutGivenIn(e,t,r,s,n,a,i){return vr(e,t,r,s,n,a,i)}static calculateLiquidityOutOneAsset(e,t,r,s,n,a,i){return Rr(e,t,r,s,n,a,i)}static calculateShares(e,t,r,s,n,a){return _r(e,t,r,s,n,a)}static calculateSpotPriceWithFee(e,t,r,s,n,a,i,o){return kr(e,t,r,s,n,a,i,o)}static calculatePoolTradeFee(e,t,r){return Er(e,t,r)}static recalculatePegs(e,t,r,s,n){let a=Mr(e,t,r,s,n);return JSON.parse(a)}};var Ee=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,r,s,n,a,i,o,l,u,c){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n,this.amplification=a,this.id=i,this.fee=o,this.totalIssuance=l,this.pegs=u,this.pegsFee=c}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let a=m(s.balance),i=m(n.balance),o=m(s.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:i,decimalsIn:s.decimals,decimalsOut:n.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:n.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,r),a=y.toPct(r.fee),i=[],o=N.isSellAllowed(e.tradeableIn),l=N.isBuyAllowed(e.tradeableOut);return(!o||!l)&&i.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&i.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:s,amountOut:t,feePct:a,errors:i}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,r),a=y.toPct(r.fee),i=[],o=N.isSellAllowed(e.tradeableIn),l=N.isBuyAllowed(e.tradeableOut);return(!o||!l)&&i.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&i.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:a,errors:i}}calculateIn(e,t,r){let s=_.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),n=m(s);return n.isNegative()?S:n}calculateAddOneAsset(e,t,r){let s=_.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),n=m(s);return n.isNegative()?S:n}calculateSharesForAmount(e,t,r){let s=_.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),n=m(s);return n.isNegative()?S:n}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let s=v(R,e.decimalsIn-e.decimalsOut);return m(t).div(s)}let r=v(R,18-e.decimalsIn);return m(t).div(r)}calculateOut(e,t,r){let s=_.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),n=m(s);return n.isNegative()?S:n}calculateWithdrawOneAsset(e,t,r){let s=_.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),n=m(s);return n.isNegative()?S:n}calculateShares(e,t,r){let s=_.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),n=m(s);return n.isNegative()?S:n}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let s=v(R,e.decimalsOut-e.decimalsIn);return m(t).div(s)}let r=v(R,18-e.decimalsOut);return m(t).div(r)}calculateTradeFee(e,t){let r=_.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return m(r)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{blake2AsHex as Lr,encodeAddress as Ur}from"@polkadot/util-crypto";var qr=340282366920938463463374607431768211455n,_e=class extends C{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[n]},a])=>{let i=a.unwrap(),o=n.toString(),l=this.getPoolAddress(o),[u,c,h]=await Promise.all([this.getPoolDelta(o,i,r.toString()),this.getPoolTokens(l,o,i),this.getPoolPegs(o,i,r.toString())]);return this.stablePools.set(l,i),{address:l,id:o,type:"Stableswap",fee:y.fromPermill(i.fee.toNumber()),tokens:c,...u,...h,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toString(),s=this.stablePools.get(e.address);if(s){let[n,a]=await Promise.all([this.getPoolDelta(e.id,s,r),this.getPoolPegs(e.id,s,r)]);Object.assign(e,n,a)}})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:n,initialBlock:a,finalBlock:i}=t,o=_.calculateAmplification(s.toString(),n.toString(),a.toString(),i.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:o,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,n=s.map(async i=>{let[o,l]=await Promise.all([this.api.query.stableswap.assetTradability(t,i.toString()),this.getBalance(e,i.toString())]);return{id:i.toString(),tradeable:o.bits.toNumber(),balance:l.toString()}}),a=await Promise.all(n);return a.push({id:t,tradeable:15,balance:qr.toString()}),a}getPoolDefaultPegs(e){let t=e.fee,r=_.defaultPegs(e.assets.length);return{pegsFee:y.fromPermill(t.toNumber()),pegs:r}}async getPoolPegs(e,t,r){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getPoolDefaultPegs(t);let n=s.unwrap(),a=await this.getLatestPegs(t,n,r),i=this.getRecentPegs(n),o=n.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[u,c]=_.recalculatePegs(JSON.stringify(i),JSON.stringify(a),r,o.replace(/%/g,""),l.replace(/%/g,"")),h=Number(u)*1e4;return{pegsFee:y.fromPermill(h),pegs:c}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(n=>n.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,n=Array.from(e.assets.entries()).map(([i,o])=>o.toString()),a=s.map(async(i,o)=>{if(i.isOracle){let[l,u,c]=i.asOracle,h=[c.toString(),n[o]].map(f=>Number(f)).sort((f,A)=>f-A),d=await this.api.query.emaOracle.oracles(l,h,u),[{price:g,updatedAt:b}]=d.unwrap(),P=g.n.toString(),T=g.d.toString();return c.toString()===h[0].toString()?[[P,T],b.toString()]:[[T,P],b.toString()]}else if(i.isMmOracle){let l=i.asMmOracle,{price:u,decimals:c,updatedAt:h}=await this.mmOracle.getData(l.toString()),d=10**c;return[[u.toString(),d.toString()],h.toString()]}else return[i.asValue.map(l=>l.toString()),r]});return Promise.all(a)}getPoolAddress(e){let t=Number(e),r=_.getPoolAddress(t);return Ur(Lr(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var ne=class extends k{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=Gr(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new $(this.api),this.aaveClient=new Be(this.api,t),this.xykClient=new Re(this.api,t),this.omniClient=new Ne(this.api,t),this.lbpClient=new Ae(this.api,t),this.stableClient=new _e(this.api,t),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(s=>s.isSupported()).map(s=>s.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(r=>e.some(s=>s===r.getPoolType())).map(r=>r.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new Oe(t.type)}}};var ie=class extends ne{feeCache;disconnectSubscribeNewHeads=null;constructor(e,t){super(e,t),this.feeCache=new Wr(null),this.api.rpc.chain.subscribeNewHeads(async r=>{this.feeCache.release()}).then(r=>{this.disconnectSubscribeNewHeads=r})}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let n=await super.getPoolFees(e,t);return this.feeCache.set(r,n),n}}async destroy(){this.log(`Destroying pool cache!
2
- Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var ae=class{static get(e){switch(e.type){case"Aave":return xe.fromPool(e);case"Xyk":return Fe.fromPool(e);case"Omnipool":return ve.fromPool(e);case"Lbp":return Ie.fromPool(e);case"Stableswap":return Ee.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var De=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 Hr=5,oe=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],n=new De,a=[];for(a.push([t,""]),n.enqueue(a);n.size()>0;){let i=n.dequeue();if(i==null||i.length>Hr)return s;let o=i[i.length-1];(r===null||o[0]===r)&&s.push(i),e.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,i)){let c=[...i];c.push(u),n.enqueue(c)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,n,a]of t){let i=parseInt(n),o=parseInt(a);r.get(i)?.push([o,s])}return r}};function Ve(p){let e={};for(let t of p){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let n=0;n<r;n++){if(s==n)continue;let a=[t.address,t.tokens[s].id,t.tokens[n].id];e[t.tokens[s].id].push(a)}}}return e}var le=class{getProposals(e,t,r){let s=Ve(r),n=Object.keys(s),a=n.map(u=>s[u]).flat(),i=new oe,o=i.buildAndPopulateGraph(n,a),l=i.findPaths(o,parseInt(e),t?parseInt(t):null);return this.parsePaths(l)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let n=0;n<r.length;n++){let a=r[n],i=r[n+1];if(i==null)break;s.push(this.toEdge(a,i))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ue=class{routeSuggester;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new le,this.routerOptions=Object.freeze({includeOnly:t.includeOnly??[]})}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),a=this.getPaths(e,null,s,t).map(i=>i[i.length-1].assetOut);return this.toAssets([...new Set(a)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(i=>this.validPath(i,r)).map(i=>this.toHops(i,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let n=this.getPoolMap(r);return{assets:s,poolsMap:n}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,ae.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,n])=>{let a=t.get(r);return{poolAddress:r,poolId:a?.id,pool:a?.type,assetIn:s,assetOut:n}})}toAssets(e,t){return e.map(r=>t.get(r))}};var Xr=m("100");function Jl(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ce(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function gt(p,e){return R.minus(e.div(p)).multipliedBy(100).decimalPlaces(2)}function ht(p,e){return e.div(p).minus(R).multipliedBy(100).decimalPlaces(2)}function V(p,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),p.div(Xr).multipliedBy(e).decimalPlaces(0,1)}var ze=(t=>(t.Buy="Buy",t.Sell="Sell",t))(ze||{}),Ke=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(Ke||{}),Pt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(Pt||{});var me=class extends ue{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let n=r[r.length-1].amountOut,a=s[s.length-1].amountOut;return n.isGreaterThan(a)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,a)=>n+a),s=e.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,a)=>n+a);return[r,s]}}getPoolFeeRange(e){let t=e.min?y.toPct(e.min):void 0,r=e.max?y.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,n),i=super.getPaths(e,t,a,n);if(i.length===0)throw new K(e,t);let o;if(s)o=await this.toSellSwaps(r,s,a);else{let O=i.map(async F=>await this.toSellSwaps(r,F,a)),I=await Promise.all(O);o=this.findBestSellRoute(I)}let l=o[0],u=o[o.length-1],c=this.isDirectTrade(o),h=o.map(O=>O.spotPrice.shiftedBy(-1*O.assetOutDecimals)).reduce((O,I)=>O.multipliedBy(I)),d=v(h,u.assetOutDecimals),g=c?u.calculatedOut:this.calculateDelta0Y(l.amountIn,o,a),b=u.amountOut,P=c?u.tradeFeePct:gt(g,b).toNumber(),T=g.minus(b),f=this.getRouteFeeRange(o),A=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(d),B=ce(g,A);return{type:"Sell",amountIn:l.amountIn,amountOut:u.amountOut,spotPrice:d,tradeFee:T,tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B.toNumber(),swaps:o,toHuman(){return{type:"Sell",amountIn:x(l.amountIn,l.assetInDecimals),amountOut:x(u.amountOut,u.assetOutDecimals),spotPrice:x(d,u.assetOutDecimals),tradeFee:x(T,u.assetOutDecimals),tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B.toNumber(),swaps:o.map(O=>O.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let n=0;n<t.length;n++){let a=t[n],i=r.get(a.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(a.assetIn,a.assetOut),l;n>0?l=s[n-1]:l=e;let u=i.calculateOutGivenIn(o,l);s.push(u)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let n=0;n<t.length;n++){let a=t[n],i=r.get(a.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(a.assetIn,a.assetOut),l;n>0?l=s[n-1].amountOut:l=v(m(e),o.decimalsIn).decimalPlaces(0,1);let u=await this.poolService.getPoolFees(o,i),{amountOut:c,calculatedOut:h,feePct:d,errors:g}=i.validateAndSell(o,l,u),b=this.getPoolFeeRange(u),P=i.spotPriceOutGivenIn(o),T=l.shiftedBy(-1*o.decimalsIn).multipliedBy(P),f=ce(h,T);s.push({...a,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:c,calculatedOut:h,spotPrice:P,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===a.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===a.assetIn},toHuman(){return{...a,amountIn:x(l,o.decimalsIn),amountOut:x(c,o.decimalsOut),calculatedOut:x(h,o.decimalsOut),spotPrice:x(P,o.decimalsOut),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:g}}})}return s}async getMostLiquidRoute(e,t){let r=await super.getPools(),{poolsMap:s}=await super.validateTokenPair(e,t,r),n=super.getPaths(e,t,s,r);if(n.length===0)throw new K(e,t);let l=r.filter(d=>d.tokens.some(g=>g.id===e&&g.id!==d.id)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(g=>g.id===e)).map(d=>d.map(g=>m(g.balance).shiftedBy(-1*g.decimals)).reduce((g,b)=>g.plus(b))).sort((d,g)=>g.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),u=n.map(async d=>await this.toSellSwaps(l,d,s)),c=await Promise.all(u);return this.findBestSellRoute(c).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r);if(super.getPaths(e,t,s,r).length===0)return Promise.resolve(void 0);let a=await this.getMostLiquidRoute(e,t),i=await this.toSellSwaps("1",a,s),o=i.map(c=>c.spotPrice.shiftedBy(-1*c.assetOutDecimals)).reduce((c,h)=>c.multipliedBy(h)),l=i[i.length-1].assetOutDecimals;return{amount:v(o,l),decimals:l}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let n=r[0].amountIn,a=s[0].amountIn;return n.isGreaterThan(a)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,n),i=super.getPaths(e,t,a,n);if(i.length===0)throw new K(e,t);let o;if(s)o=await this.toBuySwaps(r,s,a);else{let O=i.map(async F=>await this.toBuySwaps(r,F,a)),I=await Promise.all(O);o=this.findBestBuyRoute(I)}let l=o[o.length-1],u=o[0],c=this.isDirectTrade(o),h=o.map(O=>O.spotPrice.shiftedBy(-1*O.assetInDecimals)).reduce((O,I)=>O.multipliedBy(I)),d=v(h,u.assetInDecimals),g=c?u.calculatedIn:this.calculateDelta0X(l.amountOut,o,a),b=u.amountIn,P=c?u.tradeFeePct:ht(g,b).toNumber(),T=b.minus(g),f=this.getRouteFeeRange(o),A=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(d),B;return g.isZero()?B=-100:B=ce(A,g).toNumber(),{type:"Buy",amountOut:l.amountOut,amountIn:u.amountIn,spotPrice:d,tradeFee:T,tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B,swaps:o,toHuman(){return{type:"Buy",amountOut:x(l.amountOut,l.assetOutDecimals),amountIn:x(u.amountIn,u.assetInDecimals),spotPrice:x(d,u.assetInDecimals),tradeFee:x(T,u.assetInDecimals),tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B,swaps:o.map(O=>O.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let n=t.length-1;n>=0;n--){let a=t[n],i=r.get(a.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(a.assetIn,a.assetOut),l;n==t.length-1?l=e:l=s[0];let u=i.calculateInGivenOut(o,l);s.unshift(u)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let n=t.length-1;n>=0;n--){let a=t[n],i=r.get(a.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(a.assetIn,a.assetOut),l;n==t.length-1?l=v(m(e),o.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let u=await this.poolService.getPoolFees(o,i),{amountIn:c,calculatedIn:h,feePct:d,errors:g}=i.validateAndBuy(o,l,u),b=this.getPoolFeeRange(u),P=i.spotPriceInGivenOut(o),T=l.shiftedBy(-1*o.decimalsOut).multipliedBy(P),f;h.isZero()?f=-100:f=ce(T,h).toNumber(),s.unshift({...a,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:c,amountOut:l,calculatedIn:h,spotPrice:P,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f,errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===a.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===a.assetIn},toHuman(){return{...a,amountIn:x(c,o.decimalsIn),amountOut:x(l,o.decimalsOut),calculatedIn:x(h,o.decimalsIn),spotPrice:x(P,o.decimalsIn),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f,errors:g}}})}return s}};var bt=6e3,yt=m(1e15),pe=6,Je=-5,je=6*60*60*1e3;var ft=6;var L=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:n})=>s==="Stableswap"?{pool:{Stableswap:n},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var de=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??bt,minBudgetInNative:t.minBudgetInNative??yt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,n){let[a,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:l,priceImpactPct:u}=i,c=l[0],h=l[l.length-1],{assetInDecimals:d}=c,{assetOutDecimals:g}=h,b=Math.abs(u),P=this.getMinimumTradeCount(o,a),T=this.getOptimalTradeCount(b),f=n?Math.round(s/n):T,A=Math.ceil(s/P),B=Math.round(s/T),O=Math.round(s/f),I=o.dividedBy(f).decimalPlaces(0,1),F=await this.router.getBestSell(e,t,x(I,d)),U=o.isLessThan(a),he=[];U&&he.push("OrderTooSmall");let Pe=F.amountOut.multipliedBy(f),Me=this.toBlockPeriod(O),Le=F.tradeFee.multipliedBy(f),Ue=L.build(l),be={assetIn:e,assetOut:t,errors:he,frequencyMin:A,frequencyOpt:B,frequency:O,tradeCount:f,tradeFee:Le,tradeImpactPct:F.priceImpactPct,tradePeriod:Me,tradeRoute:Ue,type:"Dca"};return{...be,amountIn:o,amountOut:Pe,tradeAmountIn:F.amountIn,tradeAmountOut:F.amountOut,toHuman(){return{...be,amountIn:x(o,d),amountOut:x(Pe,g),tradeAmountIn:x(F.amountIn,d),tradeAmountOut:x(F.amountOut,g)}}}}async getMinimumOrderBudget(e){if(D===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(D,e);if(t)return this.minOrderBudget.times(t.amount).div(m(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:i,priceImpactPct:o}=n,l=i[0],u=i[i.length-1],{assetInDecimals:c}=l,{assetOutDecimals:h}=u,d=Math.abs(o),g=this.getTwapTradeCount(d),b=a.dividedBy(g).decimalPlaces(0,1),P=await this.router.getBestSell(l.assetIn,u.assetOut,x(b,c)),T=g===1,f=a.isLessThan(s),A=P.priceImpactPct<Je,B=[];f||T?B.push("OrderTooSmall"):A&&B.push("OrderImpactTooBig");let O=P.amountOut.multipliedBy(g),I=P.tradeFee.multipliedBy(g),F=L.build(i),U={assetIn:e,assetOut:t,errors:B,tradeCount:g,tradeImpactPct:P.priceImpactPct,tradePeriod:pe,tradeRoute:F,type:"TwapSell"};return{...U,amountIn:a,amountOut:O,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:I,toHuman(){return{...U,amountIn:x(a,c),amountOut:x(O,h),tradeAmountIn:x(P.amountIn,c),tradeAmountOut:x(P.amountOut,h),tradeFee:x(I,h)}}}}async getTwapBuyOrder(e,t,r){let[s,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:a,swaps:i,priceImpactPct:o}=n,l=i[0],u=i[i.length-1],{assetInDecimals:c}=l,{assetOutDecimals:h}=u,d=Math.abs(o),g=this.getTwapTradeCount(d),b=a.dividedBy(g).decimalPlaces(0,1),P=await this.router.getBestBuy(l.assetIn,u.assetOut,x(b,h)),T=P.amountIn.multipliedBy(g),f=g===1,A=T.isLessThan(s),B=P.priceImpactPct<Je,O=[];A||f?O.push("OrderTooSmall"):B&&O.push("OrderImpactTooBig");let I=P.tradeFee.multipliedBy(g),F=L.build(i),U={assetIn:e,assetOut:t,errors:O,tradeCount:g,tradeImpactPct:P.priceImpactPct,tradePeriod:pe,tradeRoute:F,type:"TwapBuy"};return{...U,amountIn:T,amountOut:a,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:I,toHuman(){return{...U,amountIn:x(T,c),amountOut:x(a,h),tradeAmountIn:x(P.amountIn,c),tradeAmountOut:x(P.amountOut,h),tradeFee:x(I,c)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>je){let s=je/(this.blockTime*pe);return Math.round(s)}return t}getTwapExecutionTime(e){return e*pe*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,ft)}};var j=class extends k{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new M(e),this.aaveUtils=new Y(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),Z)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var ke=class extends j{_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:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:n,assetOut:a}=s,o=(await this.balanceClient.getBalance(this.beneficiary,n)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,a)).amount.isGreaterThanOrEqualTo(o)),l&&e.isGreaterThanOrEqualTo(o)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],n=r[r.length-1],a=V(e,this.slippagePct),i=s.assetIn,o=n.assetOut,l=e.plus(a),u;return this.isDirectOmnipoolTrade(r)?u=this.api.tx.omnipool.buy(o,i,t.toFixed(),l.toFixed()):u=this.api.tx.router.buy(i,o,t.toFixed(),l.toFixed(),L.build(r)),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],n=r[r.length-1],a=V(t,this.slippagePct),i=s.assetIn,o=n.assetOut,l=t.minus(a),u;if(this.isDirectOmnipoolTrade(r)?u=this.api.tx.omnipool.sell(i,o,e.toFixed(),l.toFixed()):u=this.api.tx.router.sell(i,o,e.toFixed(),l.toFixed(),L.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let h=this.dispatchWithExtraGas(u);return this.wrapTx("RouterSellAll",h,Z)}return this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],n=V(e,this.slippagePct),a=r.assetIn,i=s.assetOut,o=e.minus(n),l=this.api.tx.router.sellAll(a,i,o.toFixed(),L.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let c=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",c,Z)}return this.wrapTx("RouterSellAll",l)}};var Ce=class extends j{_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:r,tradeAmountIn:s,tradePeriod:n,tradeRoute:a}=this.order,i=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:a}}},null);return this.wrapTx("DcaSchedule",i)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:a,tradeRoute:i}=this.order,o=V(n,this.slippagePct),l=n.minus(o),u=this.api.tx.dca.schedule({owner:this.beneficiary,period:a,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:i}}},null);return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:a,tradeRoute:i}=this.order,o=V(s,this.slippagePct),l=s.plus(o),u=this.api.tx.dca.schedule({owner:this.beneficiary,period:a,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:n.toFixed(),maxAmountIn:l.toFixed(),route:i}}},null);return this.wrapTx("DcaSchedule.twapBuy",u)}};var ge=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new ke(this.api,this.evm).setTrade(e)}order(e){return new Ce(this.api,this.evm).setOrder(e)}};function uc(p){let e=new re(p),t=new we(p),r=new ie(p,t),s=new Y(t),n=new me(r),a=new de(n,{blockTime:e.blockTime,minBudgetInNative:e.minOrderBudget});return{api:{aave:s,router:n,scheduler:a},client:{asset:new $(p),balance:new M(p)},ctx:{pool:r},evm:t,tx:new ge(p,t),destroy:()=>{r.destroy()}}}export{qr as AMOUNT_MAX,Q as AaveClient,xe as AavePool,Be as AavePoolClient,Y as AaveUtils,$ as AssetClient,at as AssetNotFound,rs as BASILISK_PARACHAIN_ID,M as BalanceClient,w as BigNumber,ie as CachingPoolService,re as ChainParams,Rt as DECIMAL_PLACES,He as DENOMINATOR,G as ERC20,we as EvmClient,Ye as FarmClient,z as H160,fe as HUB_ASSET_ID,ss as HYDRADX_PARACHAIN_ID,W as HYDRADX_SS58_PREFIX,ps as INFINITY,q as LbpMath,Ie as LbpPool,Ae as LbpPoolClient,R as ONE,N as OmniMath,ve as OmniPool,Ne as OmniPoolClient,k as PolkadotApiClient,it as PoolConfigNotFound,J as PoolError,ae as PoolFactory,Oe as PoolNotFound,ne as PoolService,E as PoolType,ut as ProviderConfigNotFound,ee as RUNTIME_DECIMALS,K as RouteNotFound,ue as Router,Qe as SYSTEM_ASSET_DECIMALS,D as SYSTEM_ASSET_ID,_ as StableMath,Ee as StableSwap,_e as StableSwapClient,ot as StorageConfigNotFound,lt as SubscriptionNotSupported,te as TRADEABLE_DEFAULT,Pt as TradeOrderError,Ke as TradeOrderType,L as TradeRouteBuilder,me as TradeRouter,de as TradeScheduler,ze as TradeType,ge as TxBuilderFactory,X as XykMath,Fe as XykPool,Re as XykPoolClient,S as ZERO,Fn as bnFormatter,m as bnum,ht as calculateBuyFee,Jl as calculateDiffToAvg,ce as calculateDiffToRef,gt as calculateSellFee,ct as createChain,uc as createSdkContext,dt as findNestedKey,Nn as findNestedObj,V as getFraction,vt as isEvmAccount,Nt as isEvmAddress,Ft as isSs58Address,v as scale,ds as toBn,x as toDecimals};
1
+ var ye=[{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 Ge=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Qe="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",We="0x112b087b60C1a166130d59266363C45F8aa99db0",He="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Z=1000000n;var Jr=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Q=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:Ge,address:We,args:[He],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:Ge,address:We,args:[He,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:ye,address:Qe,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as Se,encodeAddress as tt}from"@polkadot/util-crypto";import{hexToU8a as It,isHex as At,u8aToHex as vt}from"@polkadot/util";import{Buffer as H}from"buffer";var ts=2090,Xe=1e3,fe="1",rs=2034,W=63,ee=18,D="0",et=12,te=15;var Ye="ETH\0";function Nt(m){if(!m)return!1;try{let e=Se(m,!0),t=H.from(Ye);return H.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Ft(m){return!!/^0x[a-fA-F0-9]{40}$/.test(m)}function Rt(m){try{let e=At(m)?It(m):Se(m);return tt(e),!0}catch{return!1}}var z=class m{static toAccount=e=>{let t=H.from(e.slice(2),"hex"),r=H.from(Ye);return tt(new Uint8Array(H.concat([r,t,H.alloc(8)])),63)};static fromAccount=e=>{let t=Se(e),r=H.from(Ye),s=t.slice(r.length,-8);return"0x"+H.from(s).toString("hex")};static fromSS58=e=>{let r=Se(e).slice(0,20);return vt(r)};static fromAny=e=>{if(Ft(e))return e;if(Nt(e))return m.fromAccount(e);if(Rt(e))return m.fromSS58(e);throw new Error("Unknown address type")}};import{Buffer as Te}from"buffer";var G=class{static fromAssetId(e){let t=Number(e),r=Te.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Te.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Te.from("0000000000000000000000000000000100000000","hex"),r=Te.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as w}from"bignumber.js";var Et=12;w.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Et});var S=p(0),R=p(1),ps=p("Infinity");function v(m,e){let t=new w(e.toString()),r=new w(10).pow(t);return m.times(r)}function p(m){return new w(m.toString())}function ds(m,e){let t=p(m);return v(t,e)}function x(m,e){return m.shiftedBy(-1*e).toString()}var Oe=p("1e27"),_t=p("1.01"),Dt=p("31536000"),Y=class{client;constructor(e){this.client=new Q(e)}async getSummary(e){let t=z.fromAny(e),[r,s,n,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[i]=r,[o,l]=s,[u,c,h,d,g,b]=n,P=p(b).dividedBy(1e18).decimalPlaces(6,w.ROUND_DOWN),T=p(u),f=p(c),A=[];for(let B of o){let O=B.underlyingAsset.toLowerCase(),I=i.find(({underlyingAsset:Bt})=>Bt.toLowerCase()===O);if(!I)throw new Error("Missing pool reserve for "+O);let F=p(B.scaledATokenBalance),U=p(I.liquidityIndex),he=p(I.liquidityRate),Pe=p(I.availableLiquidity),Le=p(I.priceInMarketReferenceCurrency),Ue=a+6,qe=this.calculateLinearInterest(he,I.lastUpdateTimestamp,Ue),be=U.multipliedBy(qe).dividedBy(Oe).decimalPlaces(0,w.ROUND_DOWN),Tt=F.multipliedBy(be).dividedBy(Oe).decimalPlaces(0,w.ROUND_DOWN),Ot=p(l!==0&&l===I.eModeCategoryId?I.eModeLiquidationThreshold:I.reserveLiquidationThreshold).div(1e4),wt=I.usageAsCollateralEnabled&&B.usageAsCollateralEnabledOnUser&&p(B.scaledATokenBalance).gt(0),xt=G.toAssetId(O);A.push({aTokenBalance:Tt,availableLiquidity:Pe,decimals:Number(I.decimals),isCollateral:wt,priceInRef:Le,reserveId:xt,reserveAsset:O,reserveLiquidationThreshold:Ot})}return{healthFactor:P.toNumber(),totalCollateral:T,totalDebt:f,reserves:A}}async hasBorrowPositions(e){let t=z.fromAny(e),r=await this.client.getUserAccountData(t),[s,n]=r;return n>0n}async getHealthFactor(e){let t=z.fromAny(e),r=await this.client.getUserAccountData(t),[s,n,a,i,o,l]=r;return p(l).dividedBy(1e18).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:n,reserves:a}=await this.getSummary(e),i=G.fromAssetId(t),o=a.find(T=>T.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:u,priceInRef:c,reserveLiquidationThreshold:h}=o,d=v(p(r),l).decimalPlaces(0,1),g=u?d.multipliedBy(c).dividedBy(p(10).pow(l)).decimalPlaces(0,w.ROUND_DOWN):S,b=s.minus(g);return b.lte(0)?0:b.multipliedBy(h).dividedBy(n).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:n,reserves:a}=await this.getSummary(e),i=G.fromAssetId(t),o=a.find(P=>P.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:c}=o,d=v(p(r),l).decimalPlaces(0,1).multipliedBy(u).dividedBy(p(10).pow(l)).decimalPlaces(0,w.ROUND_DOWN),g=s.plus(d);return g.lte(0)?0:g.multipliedBy(c).dividedBy(n).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:n}=await this.getSummary(e),a=G.fromAssetId(t),i=s.find(o=>o.reserveAsset===a);if(!i)throw new Error("Missing reserve data for "+a);return this.calculateWithdrawMax(i,r,n)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),n={};for(let a of r){let i=this.calculateWithdrawMax(a,t,s);a.reserveId&&(n[a.reserveId]=i)}return n}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:n,decimals:a,priceInRef:i,reserveLiquidationThreshold:o,isCollateral:l}=e,u=s;if(l&&t.gt(0)){let h=p(r).minus(_t);if(h.gt(0)){let g=h.multipliedBy(t).dividedBy(o).decimalPlaces(0,w.ROUND_DOWN).dividedBy(i).multipliedBy(p(10).pow(a)).decimalPlaces(0,w.ROUND_DOWN);u=w.minimum(s,g)}else u=S}return{amount:w.minimum(u,n),decimals:a}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Oe:e.multipliedBy(s).dividedBy(Dt).plus(Oe).decimalPlaces(0,w.ROUND_DOWN)}};function rt(m){switch(m){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var k=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");rt(r)&&console.log(e,...t)}};var $=class extends k{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:n}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:n.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==D){let c=this.api.consts.balances.existentialDeposit;return{id:D,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:c.toString()}}let{name:n,assetType:a,isSufficient:i,existentialDeposit:o}=t,{symbol:l,decimals:u}=r.get(e)??{};return{id:e,name:n.toHuman(),symbol:l,decimals:u,icon:l,type:a.toHuman(),isSufficient:i?i.toHuman():!0,location:s?.toJSON(),existentialDeposit:o.toString()}}getBond(e,t,r,s){let[n,a]=s,{assetType:i,isSufficient:o,existentialDeposit:l}=t,{symbol:u,decimals:c}=this.getToken(n.toString(),t,r),h=a.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",d.format(h)].join(" ");return{id:e,name:g,symbol:u+"b",decimals:c,icon:u,type:i.toString(),isSufficient:o.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:n.toString(),maturity:h}}getShares(e,t,r,s){let{assets:n}=s,{name:a,symbol:i,assetType:o,isSufficient:l,existentialDeposit:u}=t,h=n.map(b=>b.toString()).map(b=>{let{symbol:P}=this.getToken(b,t,r);return[b,P]}),d=Object.fromEntries(h),g=Object.values(d);return{id:e,name:g.join(", "),symbol:i?.isSome?i.toHuman():a.toHuman(),decimals:18,icon:g.join("/"),type:o.toString(),isSufficient:l.toHuman(),existentialDeposit:u.toString(),meta:d}}getExternal(e,t,r,s){let n=this.getToken(e,t,new Map,s),a=r?.find(i=>i.internalId===n.id);return a?{...n,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:n}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:n,symbol:a}=s.unwrap();return[r.toString(),{decimals:Number(n.toString()),symbol:a.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,n,a,i]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),o=this.getSupportedAssets(r),l=this.normalizeMetadata(o,i),u=o.map(([{args:[c]},h])=>{let d=h.unwrap(),g=s.get(c.toString()),{assetType:b}=d;switch(b.toString()){case"Bond":let P=a.get(c.toString());return this.getBond(c.toString(),d,l,P);case"StableSwap":let T=n.get(c.toString());return this.getShares(c.toString(),d,l,T);case"External":return this.getExternal(c.toString(),d,t,g);default:return this.getToken(c.toString(),d,l,g)}});return e?u:u.filter(c=>this.isValidAsset(c))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var M=class extends k{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===D?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:n}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:n})}async getErc20Balance(e,t){let{free:r,reserved:s,frozen:n}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:r,feeFrozen:0n,frozen:n})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(D,this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),n=r?r.map(a=>[e,a]):s.map(({args:[a,i]})=>[a.toString(),i.toString()]);return this.api.query.tokens.accounts.multi(n,a=>{let i=[];a.forEach((o,l)=>{let u=this.calculateFreeBalance(o),c=n[l][1];i.push([c,u])}),t(i)})}async subscribeErc20Balance(e,t,r){let n=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([o,l])=>{let{assetType:u}=l.unwrap();return u.toString()==="Erc20"}).map(([{args:[o]}])=>o.toString()))(),a=async()=>{let i=await Promise.all(n.map(async o=>[o,await this.getErc20Balance(e,o)]));t(i)};return this.api.rpc.chain.subscribeNewHeads(async()=>{a()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:n}=e,a=new w(t),i=new w(r||n),o=new w(s||0n),l=i.gt(o)?i:o;return a.minus(l)}};var re=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),p(this._minOrderBudget)}};import{fixed_from_rational as st}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as kt}from"@polkadot/types";import{u8aConcat as nt}from"@polkadot/util";import{isAddress as it}from"@polkadot/util-crypto";var $e=class extends k{balanceClient;constructor(e){super(e),this.balanceClient=new M(e)}secondsInYear=new w(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,n])=>{let[,a]=s.args,i=n.unwrap().toString(),o=a.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(o)).unwrap(),u=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,o,i)).unwrap(),c=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(o),!1).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:u,priceAdjustment:c,potBalance:b.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,n])=>{let[,a]=s.args,i=n.unwrap().toString(),o=a.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(o)).unwrap(),u=(await this.api.query.xykWarehouseLM.yieldFarm(e,o,i)).unwrap(),c=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(o),!0).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:u,priceAdjustment:c,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new w(1).shiftedBy(18).toString();let n=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(n.isNone)return;let[a]=n.unwrap(),i=a.price.n.toString(),o=a.price.d.toString(),l;return Number(t)<Number(r)?l=st(i,o):l=st(o,i),l}getGlobalRewardPerPeriod(e,t,r,s){let a=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return a.gte(r)?r:a}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return nt(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",n=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new kt(e,this.padEndU8a(nt(s,n,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!it(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&it(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:i,globalFarm:o,priceAdjustment:l,potBalance:u})=>{let c=new w(o.totalSharesZ.toString()),h=o.plannedYieldingPeriods.toString(),d=new w(o.yieldPerPeriod.toString()),g=new w(o.maxRewardPerPeriod.toString()),b=o.blocksPerPeriod.toString(),P=new w(i.multiplier.toString()).shiftedBy(-18),T=this.secondsInYear.div(new w(r).times(b)),f;if(c.isZero())f=d.times(P).times(T);else{let F=this.getGlobalRewardPerPeriod(c,d,g,l);f=this.getPoolYieldPerPeriod(F,P,c,l).times(T)}let A=new w(o.pendingRewards.toString()).plus(o.accumulatedPaidRewards.toString()),B=g.times(h),O=u?A.plus(u):B;return A.div(O).gte(.999)?S:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((i,o)=>i.plus(o),S).toString():void 0}};var we=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},at=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},K=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},ot=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},lt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},ut=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},ct=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{defineChain as Ct}from"viem";var 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"],mt=m=>{let e=m.__internal__endpoints,t=e.some(s=>Mt.includes(s)),r=e.map(s=>s.replace("wss://","https://").replace("ws://","http://"));return Ct({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:t?"https://explorer.evm.hydration.cloud":"https://explorer.nice.hydration.cloud"}},testnet:!t})};import{createPublicClient as dt,createWalletClient as Lt,custom as Ut,http as qt}from"viem";function pt(m){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return m.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var xe=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=mt(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return dt({chain:this.chain,transport:qt()})}getWsProvider(){return dt({chain:this.chain,transport:pt(this.wsProvider)})}getSigner(e){return Lt({account:e,chain:this.chain,transport:Ut(window.ethereum)})}};import{LRUCache as Gr}from"@thi.ng/cache";import{memoize1 as qr}from"@thi.ng/memoize";var E=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n))(E||{}),J=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n))(J||{});var Be=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,n){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(o=>[o.id,o])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let a=p(s.balance),i=p(n.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:a,balanceOut:i,assetInED:S,assetOutED:S}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=[];return t.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:n}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=[];return s.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:n}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return v(R,e.decimalsOut)}spotPriceOutGivenIn(e){return v(R,e.decimalsIn)}calculateTradeFee(e,t){return S}};import{encodeAddress as Ht}from"@polkadot/util-crypto";import{stringToU8a as Xt}from"@polkadot/util";import{decodeEventLog as Yt}from"viem";function gt(m,e){let t=[];return JSON.stringify(m,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Nn(m,e,t){let r;return JSON.stringify(m,(s,n)=>(n&&n[e]===t&&(r=n),n)),r}var Fn=(m,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as Gt}from"@thi.ng/memoize";import{TLRUCache as Wt}from"@thi.ng/cache";var Ve=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var se=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,n]=await Promise.all([this.client.readContract({abi:Ve,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:Ve,address:e,functionName:"decimals"}),this.client.getBlock()]),[a,i,o,l]=r,u=n.number-(n.timestamp-l)/BigInt(t),c=Number(u);return{price:i,decimals:s,updatedAt:c<0?0:c}}};var C=class extends M{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Wt(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=Gt(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new se(t)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let r=[];try{let n=this.subscribePoolChange(t);r.push(n)}catch{}if(t.type==="Aave")return r;let s=this.subscribeTokensPoolBalance(t);if(r.push(s),this.hasSystemAsset(t)){let n=this.subscribeSystemPoolBalance(t);r.push(n)}if(this.hasErc20Asset(t)){let n=this.subscribeErc20PoolBalance(t);r.push(n)}return this.subscribeLog(t),r}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,n])=>{let a=e.tokens.findIndex(i=>i.id==s);a>=0&&t(e,s)&&(e.tokens[a].balance=n.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(n=>n.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};var $t=["Supply","Withdraw","Repay","Borrow"],Ie=class extends C{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:n})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:n.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let r=e+"/"+t;return Ht(Xt(r.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,r]=e.tokens,s=this.getReserveH160Id(t);return this.api.query.system.events(n=>{n.forEach(a=>{let{event:i}=a,o=`${i.section}:${i.method}`;if(o==="router:Executed"){let{assetIn:l,assetOut:u}=i.data.toHuman(),c=l.replace(/,/g,""),h=u.replace(/,/g,"");(c===r.id||h===r.id)&&(this.log(`Sync AAVE [router:Executed] :: ${c}:${h}`),this.updatePoolState(e))}if(o==="evm:Log"){let{log:l}=i.data.toHuman();try{let{eventName:u,args:c}=Yt({abi:ye,topics:l.topics,data:l.data});$t.includes(u)&&c.reserve.toLowerCase()===s.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${u} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:n}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(a=>{let i=a.id===t.id?s.toString():n.toString();return{...a,balance:i}})}getReserveH160Id(e){return e.type==="Erc20"?gt(e.location,"accountKey20").accountKey20.key:G.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as Vt,calculate_out_given_in as zt,calculate_linear_weights as Kt,calculate_pool_trade_fee as Jt,get_spot_price as jt}from"@galacticcouncil/math-lbp";var q=class{static getSpotPrice(e,t,r,s,n){return jt(e,t,r,s,n)}static calculateInGivenOut(e,t,r,s,n){return Vt(e,t,r,s,n)}static calculateOutGivenIn(e,t,r,s,n){return zt(e,t,r,s,n)}static calculateLinearWeights(e,t,r,s,n){return Kt(e,t,r,s,n)}static calculatePoolTradeFee(e,t,r){return Jt(e,t,r)}};var y=class{static toPct(e){return e[0]/e[1]*100}static toDecimals(e){return e[0]/e[1]}static fromPermill(e){return[e/1e3,1e3]}};var Ae=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,n,a,i){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n,this.fee=a,this.repayFeeApply=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(o=>[o.id,o])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let a=p(s.balance),i=p(n.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:i,decimalsIn:s.decimals,decimalsOut:n.decimals,weightIn:s.weight,weightOut:n.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&n.push("MaxOutRatioExceeded"),s===e.assetOut){let i=this.calculateTradeFee(t,r),o=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(i),u=this.calculateInGivenOut(e,l),c=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(c)&&n.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:t,feePct:o,errors:n}}else{let i=this.calculateInGivenOut(e,t),o=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(o)&&n.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:i,amountOut:t,feePct:0,errors:n}}}validateAndSell(e,t,r){let s=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&n.push("MaxInRatioExceeded"),s===e.assetIn){let i=this.calculateOutGivenIn(e,t),o=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(o)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:i,feePct:0,errors:n}}else{let i=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(i,r),l=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),u=i.minus(o),c=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(c)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:u,feePct:l,errors:n}}}calculateInGivenOut(e,t){let r=q.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=q.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=q.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),v(R,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=q.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),v(R,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=q.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var ve=class extends C{MAX_FINAL_WEIGHT=v(p(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([n,a])=>this.isActivePool(a.unwrap(),r)).map(async([{args:[n]},a])=>{let i=a.unwrap(),o=n.toString(),l=await this.getPoolDelta(o,i,r.toString());return this.poolsData.set(n.toString(),i),{address:o,type:"Lbp",fee:i.fee.toJSON(),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let a=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,a)}else{let a=this.pools.findIndex(i=>i.address==e.address);this.pools.splice(a,1)}})}async getPoolDelta(e,t,r){let{start:s,end:n,assets:a,initialWeight:i,finalWeight:o,repayTarget:l,feeCollector:u}=t,c=q.calculateLinearWeights(s.toString(),n.toString(),i.toString(),o.toString(),r),[h,d]=a,g=h.toString(),b=p(c),P=d.toString(),T=this.MAX_FINAL_WEIGHT.minus(p(b)),[f,A,B]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),u.toString()),this.getBalance(e,g),this.getBalance(e,P)]);return{repayFeeApply:f,tokens:[{id:g,weight:b,balance:A.toString()},{id:P,weight:T,balance:B.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=p(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as Zt,calculate_lrna_in_given_out as Qt,calculate_out_given_in as er,calculate_out_given_lrna_in as tr,calculate_spot_price as rr,calculate_lrna_spot_price as sr,calculate_shares as nr,calculate_liquidity_out as ir,calculate_liquidity_lrna_out as ar,calculate_liquidity_hub_in as or,is_sell_allowed as lr,is_buy_allowed as ur,is_add_liquidity_allowed as cr,is_remove_liquidity_allowed as mr,recalculate_asset_fee as pr,recalculate_protocol_fee as dr,verify_asset_cap as gr}from"@galacticcouncil/math-omnipool";var N=class{static calculateSpotPrice(e,t,r,s){return rr(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return sr(e,t)}static calculateInGivenOut(e,t,r,s,n,a,i,o,l){return Zt(e,t,r,s,n,a,i,o,l)}static calculateLrnaInGivenOut(e,t,r,s,n){return Qt(e,t,r,s,n)}static calculateOutGivenIn(e,t,r,s,n,a,i,o,l){return er(e,t,r,s,n,a,i,o,l)}static calculateOutGivenLrnaIn(e,t,r,s,n){return tr(e,t,r,s,n)}static calculateShares(e,t,r,s){return nr(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,n,a,i,o){return ir(e,t,r,s,n,a,i,o)}static calculateLiquidityLRNAOut(e,t,r,s,n,a,i,o){return ar(e,t,r,s,n,a,i,o)}static calculateCapDifference(e,t,r,s){let n=w(t),a=w(e),i=w(s),l=w(r).shiftedBy(-18);if(n.div(i).lt(l)){let c=l.times(i).minus(n).times(a),h=n.times(w(1).minus(l));return c.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return or(e,t,r,s)}static isSellAllowed(e){return lr(e)}static isBuyAllowed(e){return ur(e)}static isAddLiquidityAllowed(e){return cr(e)}static isRemoveLiquidityAllowed(e){return mr(e)}static recalculateAssetFee(e,t,r,s,n,a,i,o,l,u,c){return pr(e,t,r,s,n,a,i,o,l,u,c)}static recalculateProtocolFee(e,t,r,s,n,a,i,o,l,u,c){return dr(e,t,r,s,n,a,i,o,l,u,c)}static verifyAssetCap(e,t,r,s){return gr(e,t,r,s)}};var Ne=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,n,a){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n,this.hubAssetId=a}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let a=p(s.balance),i=p(n.balance),o=p(s.existentialDeposit),l=p(n.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:n.hubReserves,sharesIn:s.shares,sharesOut:n.shares,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:a,balanceOut:i,tradeableIn:s.tradeable,tradeableOut:n.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,r),a=n.minus(s),i=s===S?S:a.div(s).multipliedBy(100).decimalPlaces(2),o=[],l=N.isSellAllowed(e.tradeableIn),u=N.isBuyAllowed(e.tradeableOut);(!l||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let c=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(c)&&o.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(h)&&o.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:t,feePct:i.toNumber(),errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,r),i=s.minus(n).div(s).multipliedBy(100).decimalPlaces(2),o=[],l=N.isSellAllowed(e.tradeableIn),u=N.isBuyAllowed(e.tradeableOut);(!l||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let c=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(c)&&o.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(h)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:i.toNumber(),errors:o}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=N.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString(),r?y.toDecimals(r.protocolFee).toString():S.toString()),n=p(s);return n.isNegative()?S:n}calculateLrnaInGivenOut(e,t,r){let s=N.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString()),n=p(s);return n.isNegative()?S:n}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=N.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString(),r?y.toDecimals(r.protocolFee).toString():S.toString()),n=p(s);return n.isNegative()?S:n}calculateOutGivenLrnaIn(e,t,r){let s=N.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString()),n=p(s);return n.isNegative()?S:n}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=N.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=N.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=N.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=N.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as hr}from"@polkadot/util-crypto";import{stringToU8a as Pr}from"@polkadot/util";var Fe=class extends C{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,n]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),a=r.map(async([{args:[o]},l])=>{let{hubReserve:u,shares:c,tradable:h,cap:d,protocolShares:g}=l.unwrap(),b=await this.getBalance(t,o.toString());return{id:o.toString(),hubReserves:p(u.toString()),shares:p(c.toString()),tradeable:h.bits.toNumber(),balance:b.toString(),cap:p(d.toString()),protocolShares:p(g.toString())}}),i=await Promise.all(a);return i.push({id:e,tradeable:s.bits.toNumber(),balance:n.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:i,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=e.assetOut,s=e.assetIn,n="omnipool",a="Short",i=B=>B===D?[D,fe]:[fe,B],[o,l,u,c]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(r),this.api.query.emaOracle.oracles(n,i(r),a),this.api.query.emaOracle.oracles(n,i(s),a)]),[h,d,g]=this.getAssetFee(e,o.toNumber(),l,u),[b,P,T]=s===fe?[0,0,0]:this.getProtocolFee(e,o.toNumber(),l,c),f=h+b,A=g+T;return{assetFee:y.fromPermill(d),protocolFee:y.fromPermill(P),min:y.fromPermill(f),max:y.fromPermill(A)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,n)=>{let a=e.tokens[n];if(s.isNone)return a;let i=s.unwrap();return this.updateTokenState(a,i)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:n,cap:a,protocolShares:i}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(a.toString()),protocolShares:p(i.toString()),tradeable:n.bits.toNumber()}}getAssetFee(e,t,r,s){let{assetOut:n,balanceOut:a}=e,{minFee:i,maxFee:o,decay:l,amplification:u}=this.api.consts.dynamicFees.assetFeeParameters,c=y.fromPermill(i.toNumber()),h=y.fromPermill(o.toNumber());if(r.isNone||s.isNone)return[i.toNumber(),i.toNumber(),o.toNumber()];let[d]=s.unwrap(),{assetFee:g,timestamp:b}=r.unwrap(),P=Math.max(1,t-b.toNumber()),T=d.volume.bIn.toString(),f=d.volume.bOut.toString(),A=d.liquidity.b.toString();n===D&&(T=d.volume.aIn.toString(),f=d.volume.aOut.toString(),A=d.liquidity.a.toString());let B=y.fromPermill(g.toNumber()),O=N.recalculateAssetFee(T,f,A,"9",a.toString(),y.toDecimals(B).toString(),P.toString(),y.toDecimals(c).toString(),y.toDecimals(h).toString(),l.toString(),u.toString());return[i.toNumber(),Number(O)*1e6,o.toNumber()]}getProtocolFee(e,t,r,s){let{assetIn:n,balanceIn:a}=e,{minFee:i,maxFee:o,decay:l,amplification:u}=this.api.consts.dynamicFees.protocolFeeParameters,c=y.fromPermill(i.toNumber()),h=y.fromPermill(o.toNumber());if(r.isNone||s.isNone)return[i.toNumber(),i.toNumber(),o.toNumber()];let[d]=s.unwrap(),{protocolFee:g,timestamp:b}=r.unwrap(),P=Math.max(1,t-b.toNumber()),T=d.volume.bIn.toString(),f=d.volume.bOut.toString(),A=d.liquidity.b.toString();n===D&&(T=d.volume.aIn.toString(),f=d.volume.aOut.toString(),A=d.liquidity.a.toString());let B=y.fromPermill(g.toNumber()),O=N.recalculateProtocolFee(T,f,A,"9",a.toString(),y.toDecimals(B).toString(),P.toString(),y.toDecimals(c).toString(),y.toDecimals(h).toString(),l.toString(),u.toString());return[i.toNumber(),Number(O)*1e6,o.toNumber()]}getPoolId(){return hr(Pr("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as br,calculate_out_given_in as yr,calculate_pool_trade_fee as fr,get_spot_price as Sr,calculate_liquidity_in as Tr,calculate_shares as Or,calculate_spot_price as wr,calculate_spot_price_with_fee as xr,calculate_liquidity_out_asset_a as Br,calculate_liquidity_out_asset_b as Ir}from"@galacticcouncil/math-xyk";var X=class{static getSpotPrice(e,t,r){return Sr(e,t,r)}static calculateInGivenOut(e,t,r){return br(e,t,r)}static calculateOutGivenIn(e,t,r){return yr(e,t,r)}static calculatePoolTradeFee(e,t,r){return fr(e,t,r)}static calculateLiquidityIn(e,t,r){return Tr(e,t,r)}static calculateSpotPrice(e,t){return wr(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return xr(e,t,r,s)}static calculateShares(e,t,r){return Or(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return Br(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Ir(e,t,r,s)}};var Re=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,n){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let a=p(s.balance),i=p(n.balance),o=p(s.existentialDeposit),l=p(n.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:a,balanceOut:i,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=this.calculateTradeFee(s,r),a=y.toPct(r.exchangeFee),i=s.plus(n),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&o.push("MaxOutRatioExceeded");let u=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(u)&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a,errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(s,r),a=y.toPct(r.exchangeFee),i=s.minus(n),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&o.push("MaxInRatioExceeded");let u=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(u)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a,errors:o}}calculateInGivenOut(e,t){let r=X.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=X.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=X.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=v(R,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=X.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=v(R,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=X.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var Ee=class extends C{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let n=r.toString(),[a,i]=s.unwrap(),[o,l]=await Promise.all([this.getBalance(n,a.toString()),this.getBalance(n,i.toString())]);return{address:n,type:"Xyk",tokens:[{id:a.toString(),balance:o.toString()},{id:i.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as Ar,calculate_out_given_in as vr,calculate_amplification as Nr,calculate_add_one_asset as Fr,calculate_liquidity_out_one_asset as Rr,calculate_shares as Er,calculate_shares_for_amount as _r,calculate_spot_price_with_fee as Dr,pool_account_name as kr,recalculate_peg as Cr}from"@galacticcouncil/math-stableswap";var _=class{static getPoolAddress(e){return kr(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,n){return Nr(e,t,r,s,n)}static calculateInGivenOut(e,t,r,s,n,a,i){return Ar(e,t,r,s,n,a,i)}static calculateAddOneAsset(e,t,r,s,n,a,i){return Fr(e,t,r,s,n,a,i)}static calculateSharesForAmount(e,t,r,s,n,a,i){return _r(e,t,r,s,n,a,i)}static calculateOutGivenIn(e,t,r,s,n,a,i){return vr(e,t,r,s,n,a,i)}static calculateLiquidityOutOneAsset(e,t,r,s,n,a,i){return Rr(e,t,r,s,n,a,i)}static calculateShares(e,t,r,s,n,a){return Er(e,t,r,s,n,a)}static calculateSpotPriceWithFee(e,t,r,s,n,a,i,o){return Dr(e,t,r,s,n,a,i,o)}static recalculatePegs(e,t,r,s,n){let a=Cr(e,t,r,s,n);return JSON.parse(a)}};var _e=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,r,s,n,a,i,o,l,u,c){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n,this.amplification=a,this.id=i,this.fee=o,this.totalIssuance=l,this.pegs=u,this.pegsFee=c}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let a=p(s.balance),i=p(n.balance),o=p(s.existentialDeposit),l=p(n.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:i,decimalsIn:s.decimals,decimalsOut:n.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:n.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,r),a=y.toPct(r.fee),i=[],o=N.isSellAllowed(e.tradeableIn),l=N.isBuyAllowed(e.tradeableOut);return(!o||!l)&&i.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&i.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:s,amountOut:t,feePct:a,errors:i}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,r),a=y.toPct(r.fee),i=[],o=N.isSellAllowed(e.tradeableIn),l=N.isBuyAllowed(e.tradeableOut);return(!o||!l)&&i.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&i.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:a,errors:i}}calculateIn(e,t,r){let s=_.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateAddOneAsset(e,t,r){let s=_.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateSharesForAmount(e,t,r){let s=_.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let s=v(R,e.decimalsIn-e.decimalsOut);return p(t).div(s)}let r=v(R,18-e.decimalsIn);return p(t).div(r)}calculateOut(e,t,r){let s=_.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateWithdrawOneAsset(e,t,r){let s=_.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateShares(e,t,r){let s=_.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let s=v(R,e.decimalsOut-e.decimalsIn);return p(t).div(s)}let r=v(R,18-e.decimalsOut);return p(t).div(r)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{blake2AsHex as Mr,encodeAddress as Lr}from"@polkadot/util-crypto";var Ur=340282366920938463463374607431768211455n,De=class extends C{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[n]},a])=>{let i=a.unwrap(),o=n.toString(),l=this.getPoolAddress(o),[u,c,h]=await Promise.all([this.getPoolDelta(o,i,r.toString()),this.getPoolTokens(l,o,i),this.getPoolPegs(o,i,r.toString())]);return this.stablePools.set(l,i),{address:l,id:o,type:"Stableswap",fee:y.fromPermill(i.fee.toNumber()),tokens:c,...u,...h,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toString(),s=this.stablePools.get(e.address);if(s){let[n,a]=await Promise.all([this.getPoolDelta(e.id,s,r),this.getPoolPegs(e.id,s,r)]);Object.assign(e,n,a)}})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:n,initialBlock:a,finalBlock:i}=t,o=_.calculateAmplification(s.toString(),n.toString(),a.toString(),i.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:o,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,n=s.map(async i=>{let[o,l]=await Promise.all([this.api.query.stableswap.assetTradability(t,i.toString()),this.getBalance(e,i.toString())]);return{id:i.toString(),tradeable:o.bits.toNumber(),balance:l.toString()}}),a=await Promise.all(n);return a.push({id:t,tradeable:15,balance:Ur.toString()}),a}getPoolDefaultPegs(e){let t=e.fee,r=_.defaultPegs(e.assets.length);return{pegsFee:y.fromPermill(t.toNumber()),pegs:r}}async getPoolPegs(e,t,r){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getPoolDefaultPegs(t);let n=s.unwrap(),a=await this.getLatestPegs(t,n,r),i=this.getRecentPegs(n),o=n.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[u,c]=_.recalculatePegs(JSON.stringify(i),JSON.stringify(a),r,o.replace(/%/g,""),l.replace(/%/g,"")),h=Number(u)*1e4;return{pegsFee:y.fromPermill(h),pegs:c}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(n=>n.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,n=Array.from(e.assets.entries()).map(([i,o])=>o.toString()),a=s.map(async(i,o)=>{if(i.isOracle){let[l,u,c]=i.asOracle,h=[c.toString(),n[o]].map(f=>Number(f)).sort((f,A)=>f-A),d=await this.api.query.emaOracle.oracles(l,h,u),[{price:g,updatedAt:b}]=d.unwrap(),P=g.n.toString(),T=g.d.toString();return c.toString()===h[0].toString()?[[P,T],b.toString()]:[[T,P],b.toString()]}else if(i.isMmOracle){let l=i.asMmOracle,{price:u,decimals:c,updatedAt:h}=await this.mmOracle.getData(l.toString()),d=10**c;return[[u.toString(),d.toString()],h.toString()]}else return[i.asValue.map(l=>l.toString()),r]});return Promise.all(a)}getPoolAddress(e){let t=Number(e),r=_.getPoolAddress(t);return Lr(Mr(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var ne=class extends k{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=qr(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new $(this.api),this.aaveClient=new Ie(this.api,t),this.xykClient=new Ee(this.api,t),this.omniClient=new Fe(this.api,t),this.lbpClient=new ve(this.api,t),this.stableClient=new De(this.api,t),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(s=>s.isSupported()).map(s=>s.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(r=>e.some(s=>s===r.getPoolType())).map(r=>r.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new we(t.type)}}};var ie=class extends ne{feeCache;disconnectSubscribeNewHeads=null;constructor(e,t){super(e,t),this.feeCache=new Gr(null),this.api.rpc.chain.subscribeNewHeads(async r=>{this.feeCache.release()}).then(r=>{this.disconnectSubscribeNewHeads=r})}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let n=await super.getPoolFees(e,t);return this.feeCache.set(r,n),n}}async destroy(){this.log(`Destroying pool cache!
2
+ Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var ae=class{static get(e){switch(e.type){case"Aave":return Be.fromPool(e);case"Xyk":return Re.fromPool(e);case"Omnipool":return Ne.fromPool(e);case"Lbp":return Ae.fromPool(e);case"Stableswap":return _e.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};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 Wr=5,oe=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],n=new ke,a=[];for(a.push([t,""]),n.enqueue(a);n.size()>0;){let i=n.dequeue();if(i==null||i.length>Wr)return s;let o=i[i.length-1];(r===null||o[0]===r)&&s.push(i),e.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,i)){let c=[...i];c.push(u),n.enqueue(c)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,n,a]of t){let i=parseInt(n),o=parseInt(a);r.get(i)?.push([o,s])}return r}};function ze(m){let e={};for(let t of m){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let n=0;n<r;n++){if(s==n)continue;let a=[t.address,t.tokens[s].id,t.tokens[n].id];e[t.tokens[s].id].push(a)}}}return e}var le=class{getProposals(e,t,r){let s=ze(r),n=Object.keys(s),a=n.map(u=>s[u]).flat(),i=new oe,o=i.buildAndPopulateGraph(n,a),l=i.findPaths(o,parseInt(e),t?parseInt(t):null);return this.parsePaths(l)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let n=0;n<r.length;n++){let a=r[n],i=r[n+1];if(i==null)break;s.push(this.toEdge(a,i))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ue=class{routeSuggester;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new le,this.routerOptions=Object.freeze({includeOnly:t.includeOnly??[]})}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),a=this.getPaths(e,null,s,t).map(i=>i[i.length-1].assetOut);return this.toAssets([...new Set(a)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(i=>this.validPath(i,r)).map(i=>this.toHops(i,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let n=this.getPoolMap(r);return{assets:s,poolsMap:n}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,ae.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,n])=>{let a=t.get(r);return{poolAddress:r,poolId:a?.id,pool:a?.type,assetIn:s,assetOut:n}})}toAssets(e,t){return e.map(r=>t.get(r))}};var Hr=p("100");function Jl(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ce(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function ht(m,e){return R.minus(e.div(m)).multipliedBy(100).decimalPlaces(2)}function Pt(m,e){return e.div(m).minus(R).multipliedBy(100).decimalPlaces(2)}function V(m,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),m.div(Hr).multipliedBy(e).decimalPlaces(0,1)}var Ke=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Ke||{}),Je=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(Je||{}),bt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(bt||{});var me=class extends ue{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let n=r[r.length-1].amountOut,a=s[s.length-1].amountOut;return n.isGreaterThan(a)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,a)=>n+a),s=e.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,a)=>n+a);return[r,s]}}getPoolFeeRange(e){let t=e.min?y.toPct(e.min):void 0,r=e.max?y.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,n),i=super.getPaths(e,t,a,n);if(i.length===0)throw new K(e,t);let o;if(s)o=await this.toSellSwaps(r,s,a);else{let O=i.map(async F=>await this.toSellSwaps(r,F,a)),I=await Promise.all(O);o=this.findBestSellRoute(I)}let l=o[0],u=o[o.length-1],c=this.isDirectTrade(o),h=o.map(O=>O.spotPrice.shiftedBy(-1*O.assetOutDecimals)).reduce((O,I)=>O.multipliedBy(I)),d=v(h,u.assetOutDecimals),g=c?u.calculatedOut:this.calculateDelta0Y(l.amountIn,o,a),b=u.amountOut,P=c?u.tradeFeePct:ht(g,b).toNumber(),T=g.minus(b),f=this.getRouteFeeRange(o),A=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(d),B=ce(g,A);return{type:"Sell",amountIn:l.amountIn,amountOut:u.amountOut,spotPrice:d,tradeFee:T,tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B.toNumber(),swaps:o,toHuman(){return{type:"Sell",amountIn:x(l.amountIn,l.assetInDecimals),amountOut:x(u.amountOut,u.assetOutDecimals),spotPrice:x(d,u.assetOutDecimals),tradeFee:x(T,u.assetOutDecimals),tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B.toNumber(),swaps:o.map(O=>O.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let n=0;n<t.length;n++){let a=t[n],i=r.get(a.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(a.assetIn,a.assetOut),l;n>0?l=s[n-1]:l=e;let u=i.calculateOutGivenIn(o,l);s.push(u)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let n=0;n<t.length;n++){let a=t[n],i=r.get(a.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(a.assetIn,a.assetOut),l;n>0?l=s[n-1].amountOut:l=v(p(e),o.decimalsIn).decimalPlaces(0,1);let u=await this.poolService.getPoolFees(o,i),{amountOut:c,calculatedOut:h,feePct:d,errors:g}=i.validateAndSell(o,l,u),b=this.getPoolFeeRange(u),P=i.spotPriceOutGivenIn(o),T=l.shiftedBy(-1*o.decimalsIn).multipliedBy(P),f=ce(h,T);s.push({...a,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:c,calculatedOut:h,spotPrice:P,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===a.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===a.assetIn},toHuman(){return{...a,amountIn:x(l,o.decimalsIn),amountOut:x(c,o.decimalsOut),calculatedOut:x(h,o.decimalsOut),spotPrice:x(P,o.decimalsOut),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:g}}})}return s}async getMostLiquidRoute(e,t){let r=await super.getPools(),{poolsMap:s}=await super.validateTokenPair(e,t,r),n=super.getPaths(e,t,s,r);if(n.length===0)throw new K(e,t);let l=r.filter(d=>d.tokens.some(g=>g.id===e&&g.id!==d.id)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(g=>g.id===e)).map(d=>d.map(g=>p(g.balance).shiftedBy(-1*g.decimals)).reduce((g,b)=>g.plus(b))).sort((d,g)=>g.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),u=n.map(async d=>await this.toSellSwaps(l,d,s)),c=await Promise.all(u);return this.findBestSellRoute(c).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r);if(super.getPaths(e,t,s,r).length===0)return Promise.resolve(void 0);let a=await this.getMostLiquidRoute(e,t),i=await this.toSellSwaps("1",a,s),o=i.map(c=>c.spotPrice.shiftedBy(-1*c.assetOutDecimals)).reduce((c,h)=>c.multipliedBy(h)),l=i[i.length-1].assetOutDecimals;return{amount:v(o,l),decimals:l}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let n=r[0].amountIn,a=s[0].amountIn;return n.isGreaterThan(a)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:a}=await super.validateTokenPair(e,t,n),i=super.getPaths(e,t,a,n);if(i.length===0)throw new K(e,t);let o;if(s)o=await this.toBuySwaps(r,s,a);else{let O=i.map(async F=>await this.toBuySwaps(r,F,a)),I=await Promise.all(O);o=this.findBestBuyRoute(I)}let l=o[o.length-1],u=o[0],c=this.isDirectTrade(o),h=o.map(O=>O.spotPrice.shiftedBy(-1*O.assetInDecimals)).reduce((O,I)=>O.multipliedBy(I)),d=v(h,u.assetInDecimals),g=c?u.calculatedIn:this.calculateDelta0X(l.amountOut,o,a),b=u.amountIn,P=c?u.tradeFeePct:Pt(g,b).toNumber(),T=b.minus(g),f=this.getRouteFeeRange(o),A=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(d),B;return g.isZero()?B=-100:B=ce(A,g).toNumber(),{type:"Buy",amountOut:l.amountOut,amountIn:u.amountIn,spotPrice:d,tradeFee:T,tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B,swaps:o,toHuman(){return{type:"Buy",amountOut:x(l.amountOut,l.assetOutDecimals),amountIn:x(u.amountIn,u.assetInDecimals),spotPrice:x(d,u.assetInDecimals),tradeFee:x(T,u.assetInDecimals),tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B,swaps:o.map(O=>O.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let n=t.length-1;n>=0;n--){let a=t[n],i=r.get(a.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(a.assetIn,a.assetOut),l;n==t.length-1?l=e:l=s[0];let u=i.calculateInGivenOut(o,l);s.unshift(u)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let n=t.length-1;n>=0;n--){let a=t[n],i=r.get(a.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(a.assetIn,a.assetOut),l;n==t.length-1?l=v(p(e),o.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let u=await this.poolService.getPoolFees(o,i),{amountIn:c,calculatedIn:h,feePct:d,errors:g}=i.validateAndBuy(o,l,u),b=this.getPoolFeeRange(u),P=i.spotPriceInGivenOut(o),T=l.shiftedBy(-1*o.decimalsOut).multipliedBy(P),f;h.isZero()?f=-100:f=ce(T,h).toNumber(),s.unshift({...a,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:c,amountOut:l,calculatedIn:h,spotPrice:P,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f,errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===a.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===a.assetIn},toHuman(){return{...a,amountIn:x(c,o.decimalsIn),amountOut:x(l,o.decimalsOut),calculatedIn:x(h,o.decimalsIn),spotPrice:x(P,o.decimalsIn),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f,errors:g}}})}return s}};var yt=6e3,ft=p(1e15),pe=6,je=-5,Ze=6*60*60*1e3;var St=6;var L=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:n})=>s==="Stableswap"?{pool:{Stableswap:n},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var de=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??yt,minBudgetInNative:t.minBudgetInNative??ft})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,n){let[a,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:l,priceImpactPct:u}=i,c=l[0],h=l[l.length-1],{assetInDecimals:d}=c,{assetOutDecimals:g}=h,b=Math.abs(u),P=this.getMinimumTradeCount(o,a),T=this.getOptimalTradeCount(b),f=n?Math.round(s/n):T,A=Math.ceil(s/P),B=Math.round(s/T),O=Math.round(s/f),I=o.dividedBy(f).decimalPlaces(0,1),F=await this.router.getBestSell(e,t,x(I,d)),U=o.isLessThan(a),he=[];U&&he.push("OrderTooSmall");let Pe=F.amountOut.multipliedBy(f),Le=this.toBlockPeriod(O),Ue=F.tradeFee.multipliedBy(f),qe=L.build(l),be={assetIn:e,assetOut:t,errors:he,frequencyMin:A,frequencyOpt:B,frequency:O,tradeCount:f,tradeFee:Ue,tradeImpactPct:F.priceImpactPct,tradePeriod:Le,tradeRoute:qe,type:"Dca"};return{...be,amountIn:o,amountOut:Pe,tradeAmountIn:F.amountIn,tradeAmountOut:F.amountOut,toHuman(){return{...be,amountIn:x(o,d),amountOut:x(Pe,g),tradeAmountIn:x(F.amountIn,d),tradeAmountOut:x(F.amountOut,g)}}}}async getMinimumOrderBudget(e){if(D===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(D,e);if(t)return this.minOrderBudget.times(t.amount).div(p(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:i,priceImpactPct:o}=n,l=i[0],u=i[i.length-1],{assetInDecimals:c}=l,{assetOutDecimals:h}=u,d=Math.abs(o),g=this.getTwapTradeCount(d),b=a.dividedBy(g).decimalPlaces(0,1),P=await this.router.getBestSell(l.assetIn,u.assetOut,x(b,c)),T=g===1,f=a.isLessThan(s),A=P.priceImpactPct<je,B=[];f||T?B.push("OrderTooSmall"):A&&B.push("OrderImpactTooBig");let O=P.amountOut.multipliedBy(g),I=P.tradeFee.multipliedBy(g),F=L.build(i),U={assetIn:e,assetOut:t,errors:B,tradeCount:g,tradeImpactPct:P.priceImpactPct,tradePeriod:pe,tradeRoute:F,type:"TwapSell"};return{...U,amountIn:a,amountOut:O,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:I,toHuman(){return{...U,amountIn:x(a,c),amountOut:x(O,h),tradeAmountIn:x(P.amountIn,c),tradeAmountOut:x(P.amountOut,h),tradeFee:x(I,h)}}}}async getTwapBuyOrder(e,t,r){let[s,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:a,swaps:i,priceImpactPct:o}=n,l=i[0],u=i[i.length-1],{assetInDecimals:c}=l,{assetOutDecimals:h}=u,d=Math.abs(o),g=this.getTwapTradeCount(d),b=a.dividedBy(g).decimalPlaces(0,1),P=await this.router.getBestBuy(l.assetIn,u.assetOut,x(b,h)),T=P.amountIn.multipliedBy(g),f=g===1,A=T.isLessThan(s),B=P.priceImpactPct<je,O=[];A||f?O.push("OrderTooSmall"):B&&O.push("OrderImpactTooBig");let I=P.tradeFee.multipliedBy(g),F=L.build(i),U={assetIn:e,assetOut:t,errors:O,tradeCount:g,tradeImpactPct:P.priceImpactPct,tradePeriod:pe,tradeRoute:F,type:"TwapBuy"};return{...U,amountIn:T,amountOut:a,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:I,toHuman(){return{...U,amountIn:x(T,c),amountOut:x(a,h),tradeAmountIn:x(P.amountIn,c),tradeAmountOut:x(P.amountOut,h),tradeFee:x(I,c)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>Ze){let s=Ze/(this.blockTime*pe);return Math.round(s)}return t}getTwapExecutionTime(e){return e*pe*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,St)}};var j=class extends k{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new M(e),this.aaveUtils=new Y(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),Z)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Ce=class extends j{_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:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:n,assetOut:a}=s,o=(await this.balanceClient.getBalance(this.beneficiary,n)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,a)).amount.isGreaterThanOrEqualTo(o)),l&&e.isGreaterThanOrEqualTo(o)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],n=r[r.length-1],a=V(e,this.slippagePct),i=s.assetIn,o=n.assetOut,l=e.plus(a),u;return this.isDirectOmnipoolTrade(r)?u=this.api.tx.omnipool.buy(o,i,t.toFixed(),l.toFixed()):u=this.api.tx.router.buy(i,o,t.toFixed(),l.toFixed(),L.build(r)),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],n=r[r.length-1],a=V(t,this.slippagePct),i=s.assetIn,o=n.assetOut,l=t.minus(a),u;if(this.isDirectOmnipoolTrade(r)?u=this.api.tx.omnipool.sell(i,o,e.toFixed(),l.toFixed()):u=this.api.tx.router.sell(i,o,e.toFixed(),l.toFixed(),L.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let h=this.dispatchWithExtraGas(u);return this.wrapTx("RouterSellAll",h,Z)}return this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],n=V(e,this.slippagePct),a=r.assetIn,i=s.assetOut,o=e.minus(n),l=this.api.tx.router.sellAll(a,i,o.toFixed(),L.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let c=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",c,Z)}return this.wrapTx("RouterSellAll",l)}};var Me=class extends j{_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:r,tradeAmountIn:s,tradePeriod:n,tradeRoute:a}=this.order,i=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:a}}},null);return this.wrapTx("DcaSchedule",i)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:a,tradeRoute:i}=this.order,o=V(n,this.slippagePct),l=n.minus(o),u=this.api.tx.dca.schedule({owner:this.beneficiary,period:a,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:i}}},null);return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:a,tradeRoute:i}=this.order,o=V(s,this.slippagePct),l=s.plus(o),u=this.api.tx.dca.schedule({owner:this.beneficiary,period:a,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:n.toFixed(),maxAmountIn:l.toFixed(),route:i}}},null);return this.wrapTx("DcaSchedule.twapBuy",u)}};var ge=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new Ce(this.api,this.evm).setTrade(e)}order(e){return new Me(this.api,this.evm).setOrder(e)}};function uc(m){let e=new re(m),t=new xe(m),r=new ie(m,t),s=new Y(t),n=new me(r),a=new de(n,{blockTime:e.blockTime,minBudgetInNative:e.minOrderBudget});return{api:{aave:s,router:n,scheduler:a},client:{asset:new $(m),balance:new M(m)},ctx:{pool:r},evm:t,tx:new ge(m,t),destroy:()=>{r.destroy()}}}export{Ur as AMOUNT_MAX,Q as AaveClient,Be as AavePool,Ie as AavePoolClient,Y as AaveUtils,$ as AssetClient,ot as AssetNotFound,ts as BASILISK_PARACHAIN_ID,M as BalanceClient,w as BigNumber,ie as CachingPoolService,re as ChainParams,Et as DECIMAL_PLACES,Xe as DENOMINATOR,G as ERC20,xe as EvmClient,$e as FarmClient,z as H160,fe as HUB_ASSET_ID,rs as HYDRADX_PARACHAIN_ID,W as HYDRADX_SS58_PREFIX,ps as INFINITY,q as LbpMath,Ae as LbpPool,ve as LbpPoolClient,R as ONE,N as OmniMath,Ne as OmniPool,Fe as OmniPoolClient,k as PolkadotApiClient,at as PoolConfigNotFound,J as PoolError,ae as PoolFactory,we as PoolNotFound,ne as PoolService,E as PoolType,ct as ProviderConfigNotFound,ee as RUNTIME_DECIMALS,K as RouteNotFound,ue as Router,et as SYSTEM_ASSET_DECIMALS,D as SYSTEM_ASSET_ID,_ as StableMath,_e as StableSwap,De as StableSwapClient,lt as StorageConfigNotFound,ut as SubscriptionNotSupported,te as TRADEABLE_DEFAULT,bt as TradeOrderError,Je as TradeOrderType,L as TradeRouteBuilder,me as TradeRouter,de as TradeScheduler,Ke as TradeType,ge as TxBuilderFactory,X as XykMath,Re as XykPool,Ee as XykPoolClient,S as ZERO,Fn as bnFormatter,p as bnum,Pt as calculateBuyFee,Jl as calculateDiffToAvg,ce as calculateDiffToRef,ht as calculateSellFee,mt as createChain,uc as createSdkContext,gt as findNestedKey,Nn as findNestedObj,V as getFraction,Nt as isEvmAccount,Ft as isEvmAddress,Rt as isSs58Address,v as scale,ds as toBn,x as toDecimals};
@@ -5,7 +5,6 @@ export declare class OmniMath {
5
5
  static calculateLrnaInGivenOut(assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string): string;
6
6
  static calculateOutGivenIn(assetInBalance: string, assetInHubReserve: string, assetInShares: string, assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountIn: string, assetFee: string, protocolFee: string): string;
7
7
  static calculateOutGivenLrnaIn(assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string): string;
8
- static calculatePoolTradeFee(amount: string, feeNumerator: number, feeDenominator: number): string;
9
8
  static calculateShares(assetReserve: string, assetHubReserve: string, assetShares: string, amountIn: string): string;
10
9
  static calculateLiquidityOut(assetReserve: string, assetHubReserve: string, assetShares: string, positionAmount: string, positionShares: string, positionPrice: string, sharesToRemove: string, withdrawalFee: string): string;
11
10
  static calculateLiquidityLRNAOut(assetReserve: string, assetHubReserve: string, assetShares: string, positionAmount: string, positionShares: string, positionPrice: string, sharesToRemove: string, withdrawalFee: string): string;
@@ -9,6 +9,5 @@ export declare class StableMath {
9
9
  static calculateLiquidityOutOneAsset(reserves: string, shares: string, assetOut: number, amplification: string, shareIssuance: string, withdrawFee: string, pegs: string): string;
10
10
  static calculateShares(reserves: string, assets: string, amplification: string, shareIssuance: string, fee: string, pegs: string): string;
11
11
  static calculateSpotPriceWithFee(poolId: string, reserves: string, amplification: string, assetIn: string, assetOut: string, shareIssuance: string, fee: string, pegs: string): string;
12
- static calculatePoolTradeFee(amount: string, feeNumerator: number, feeDenominator: number): string;
13
12
  static recalculatePegs(currentPegs: string, targetPegs: string, currentBlock: string, maxPegUpdate: string, poolFee: string): [string, string[][]];
14
13
  }
@@ -44,7 +44,6 @@ export declare class StableSwap implements Pool {
44
44
  private calculateShares;
45
45
  calculateOutGivenIn(poolPair: PoolPair, amountIn: BigNumber, fees?: StableSwapFees): BigNumber;
46
46
  spotPriceOutGivenIn(poolPair: PoolPair): BigNumber;
47
- calculateTradeFee(amount: BigNumber, fees: StableSwapFees): BigNumber;
48
47
  private getPegs;
49
48
  private getReserves;
50
49
  private getAssets;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk",
3
- "version": "9.3.0",
3
+ "version": "9.4.0",
4
4
  "description": "Galactic off-chain routing & optimization of orders across pools for best price execution",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {
@@ -32,11 +32,11 @@
32
32
  "test": "NODE_NO_WARNINGS=1 jest"
33
33
  },
34
34
  "dependencies": {
35
- "@galacticcouncil/math-lbp": "^1.1.0",
36
- "@galacticcouncil/math-liquidity-mining": "^1.1.0",
37
- "@galacticcouncil/math-omnipool": "^1.2.0",
38
- "@galacticcouncil/math-stableswap": "^2.1.0",
39
- "@galacticcouncil/math-xyk": "^1.1.0",
35
+ "@galacticcouncil/math-lbp": "^1.2.0",
36
+ "@galacticcouncil/math-liquidity-mining": "^1.2.0",
37
+ "@galacticcouncil/math-omnipool": "^1.3.0",
38
+ "@galacticcouncil/math-stableswap": "^2.2.0",
39
+ "@galacticcouncil/math-xyk": "^1.2.0",
40
40
  "@thi.ng/cache": "^2.1.35",
41
41
  "@thi.ng/memoize": "^4.0.2",
42
42
  "bignumber.js": "^9.1.0",