@galacticcouncil/sdk 10.1.0 → 10.2.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 xt=Object.defineProperty;var Ar=Object.getOwnPropertyDescriptor;var Fr=Object.getOwnPropertyNames;var Er=Object.prototype.hasOwnProperty;var Rr=(u,e)=>{for(var t in e)xt(u,t,{get:e[t],enumerable:!0})},Nr=(u,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fr(e))!Er.call(u,s)&&s!==t&&xt(u,s,{get:()=>e[s],enumerable:!(r=Ar(e,s))||r.enumerable});return u};var _r=u=>Nr(xt({},"__esModule",{value:!0}),u);var ss={};Rr(ss,{AaveClient:()=>le,AavePool:()=>Ne,AavePoolClient:()=>ke,AaveUtils:()=>ee,AssetClient:()=>te,AssetNotFound:()=>Rt,BASILISK_PARACHAIN_ID:()=>ys,BalanceClient:()=>U,BalanceClientV2:()=>ue,BigNumber:()=>B.BigNumber,CachingPoolService:()=>ye,ChainParams:()=>me,DECIMAL_PLACES:()=>er,DEFAULT_BLOCK_TIME:()=>Xt,DEFAULT_MIN_BUDGET:()=>Yt,ERC20:()=>V,EvmClient:()=>Re,EvmRpcAdapter:()=>Ee,FarmClient:()=>et,H160:()=>Y,HUB_ASSET_ID:()=>Je,HYDRADX_PARACHAIN_ID:()=>fs,HYDRADX_SS58_PREFIX:()=>z,INFINITY:()=>Cr,LbpMath:()=>X,LbpPool:()=>De,LbpPoolClient:()=>Me,MmOracleClient:()=>pe,ONE:()=>R,ORDER_MIN_BLOCK_PERIOD:()=>Vt,OmniMath:()=>E,OmniPool:()=>Le,OmniPoolClient:()=>He,PERBILL_DENOMINATOR:()=>$t,PERMILL_DENOMINATOR:()=>ne,PolkadotApiClient:()=>H,PoolConfigNotFound:()=>Et,PoolError:()=>se,PoolFactory:()=>fe,PoolNotFound:()=>Ae,PoolService:()=>he,PoolType:()=>_,ProviderConfigNotFound:()=>Ct,RUNTIME_DECIMALS:()=>Te,RouteNotFound:()=>Fe,Router:()=>be,SYSTEM_ASSET_DECIMALS:()=>jt,SYSTEM_ASSET_ID:()=>N,StableMath:()=>M,StableSwap:()=>ae,StableSwapClient:()=>Ue,StorageConfigNotFound:()=>Nt,SubscriptionNotSupported:()=>_t,TRADEABLE_DEFAULT:()=>Oe,TWAP_BLOCK_PERIOD:()=>ve,TWAP_MAX_DURATION:()=>yt,TWAP_MAX_PRICE_IMPACT:()=>ht,TWAP_TX_MULTIPLIER:()=>es,TradeOrderError:()=>zt,TradeOrderType:()=>gt,TradeRouteBuilder:()=>W,TradeRouter:()=>Se,TradeScheduler:()=>xe,TradeType:()=>dt,TxBuilderFactory:()=>we,XykMath:()=>J,XykPool:()=>Ge,XykPoolClient:()=>qe,ZERO:()=>v,bnFormatter:()=>Vr,bnum:()=>p,calculateBuyFee:()=>Wt,calculateDiffToAvg:()=>Zr,calculateDiffToRef:()=>Pe,calculateSellFee:()=>Ut,createChain:()=>kt,createSdkContext:()=>rs,findNestedKey:()=>Ce,findNestedObj:()=>Yr,getFraction:()=>ie,hashPools:()=>jr,isEvmAccount:()=>Qt,isEvmAddress:()=>Jt,isSs58Address:()=>Zt,scale:()=>F,toBn:()=>kr,toDecimals:()=>O});module.exports=_r(ss);var Qe=[{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 Bt=[{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 Kt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",wt="0x112b087b60C1a166130d59266363C45F8aa99db0",Tt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",oe=1000000n;var ms=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var le=class{rpcAdapter;constructor(e){this.rpcAdapter=e.getRPCAdapter()}async getBlockTimestamp(){let e=await this.rpcAdapter.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.rpcAdapter.readContract({abi:Bt,address:wt,functionName:"getReservesData",args:[Tt]})}async getUserReservesData(e){return await this.rpcAdapter.readContract({abi:Bt,address:wt,functionName:"getUserReservesData",args:[Tt,e]})}async getUserAccountData(e){return await this.rpcAdapter.readContract({abi:Qe,address:Kt,functionName:"getUserAccountData",args:[e]})}};var Z=require("@polkadot/util-crypto"),ce=require("@polkadot/util"),j=require("buffer");var ys=2090,ne=1e6,$t=1e9,Je="1",fs=2034,z=63,Te=18,N="0",jt=12,Oe=15;var Ot="ETH\0";function Qt(u){if(!u)return!1;try{let e=(0,Z.decodeAddress)(u,!0),t=j.Buffer.from(Ot);return j.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Jt(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Zt(u){try{let e=(0,ce.isHex)(u)?(0,ce.hexToU8a)(u):(0,Z.decodeAddress)(u);return(0,Z.encodeAddress)(e),!0}catch{return!1}}var Y=class u{static toAccount=e=>{let t=j.Buffer.from(e.slice(2),"hex"),r=j.Buffer.from(Ot);return(0,Z.encodeAddress)(new Uint8Array(j.Buffer.concat([r,t,j.Buffer.alloc(8)])),63)};static fromAccount=e=>{let t=(0,Z.decodeAddress)(e),r=j.Buffer.from(Ot),s=t.slice(r.length,-8);return"0x"+j.Buffer.from(s).toString("hex")};static fromSS58=e=>{let r=(0,Z.decodeAddress)(e).slice(0,20);return(0,ce.u8aToHex)(r)};static fromAny=e=>{if(Jt(e))return e;if(Qt(e))return u.fromAccount(e);if(Zt(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var Ie=require("buffer"),V=class{static fromAssetId(e){let t=Number(e),r=Ie.Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Ie.Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Ie.Buffer.from("0000000000000000000000000000000100000000","hex"),r=Ie.Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};var B=require("bignumber.js"),er=12;B.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:er});var v=p(0),R=p(1),Cr=p("Infinity");function F(u,e){let t=new B.BigNumber(e.toString()),r=new B.BigNumber(10).pow(t);return u.times(r).decimalPlaces(4)}function p(u){return new B.BigNumber(u.toString())}function kr(u,e){let t=p(u);return F(t,e)}function O(u,e){return u.shiftedBy(-1*e).toString()}var Ze=p("1e27"),Dr=p("1.01"),Mr=p("31536000"),ee=class{client;constructor(e){this.client=new le(e)}async getSummary(e){let t=Y.fromAny(e),[r,s,i,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[o]=r,[n,l]=s,[c,m,d,h,g,f]=i,y=p(f).dividedBy(1e18).decimalPlaces(6,B.BigNumber.ROUND_DOWN),S=p(c),P=p(m),x=[];for(let A of n){let w=A.underlyingAsset.toLowerCase(),T=o.find(({underlyingAsset:Ir})=>Ir.toLowerCase()===w);if(!T)throw new Error("Missing pool reserve for "+w);let D=p(A.scaledATokenBalance),q=p(T.liquidityIndex),Ke=p(T.liquidityRate),$e=p(T.availableLiquidity),Pt=p(T.priceInMarketReferenceCurrency),St=a+6,vt=this.calculateLinearInterest(Ke,T.lastUpdateTimestamp,St),je=q.multipliedBy(vt).dividedBy(Ze).decimalPlaces(0,B.BigNumber.ROUND_DOWN),Br=D.multipliedBy(je).dividedBy(Ze).decimalPlaces(0,B.BigNumber.ROUND_DOWN),wr=p(l!==0&&l===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold).div(1e4),Tr=T.usageAsCollateralEnabled&&A.usageAsCollateralEnabledOnUser&&p(A.scaledATokenBalance).gt(0),Or=V.toAssetId(w);x.push({aTokenBalance:Br,availableLiquidity:$e,decimals:Number(T.decimals),isCollateral:Tr,priceInRef:Pt,reserveId:Or,reserveAsset:w,reserveLiquidationThreshold:wr})}return{healthFactor:y.toNumber(),totalCollateral:S,totalDebt:P,reserves:x}}async hasBorrowPositions(e){let t=Y.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=Y.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,a,o,n,l]=r;return p(l).dividedBy(1e18).decimalPlaces(6,B.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:a}=await this.getSummary(e),o=V.fromAssetId(t),n=a.find(S=>S.reserveAsset===o);if(!n)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:c,priceInRef:m,reserveLiquidationThreshold:d}=n,h=F(p(r),l).decimalPlaces(0,1),g=c?h.multipliedBy(m).dividedBy(p(10).pow(l)).decimalPlaces(0,B.BigNumber.ROUND_DOWN):v,f=s.minus(g);return f.lte(0)?0:f.multipliedBy(d).dividedBy(i).decimalPlaces(6,B.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:a}=await this.getSummary(e),o=V.fromAssetId(t),n=a.find(y=>y.reserveAsset===o);if(!n)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:m}=n,h=F(p(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(p(10).pow(l)).decimalPlaces(0,B.BigNumber.ROUND_DOWN),g=s.plus(h);return g.lte(0)?0:g.multipliedBy(m).dividedBy(i).decimalPlaces(6,B.BigNumber.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),a=V.fromAssetId(t),o=s.find(n=>n.reserveAsset===a);if(!o)throw new Error("Missing reserve data for "+a);return this.calculateWithdrawMax(o,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let a of r){let o=this.calculateWithdrawMax(a,t,s);a.reserveId&&(i[a.reserveId]=o)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:a,priceInRef:o,reserveLiquidationThreshold:n,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let d=p(r).minus(Dr);if(d.gt(0)){let g=d.multipliedBy(t).dividedBy(n).decimalPlaces(0,B.BigNumber.ROUND_DOWN).dividedBy(o).multipliedBy(p(10).pow(a)).decimalPlaces(0,B.BigNumber.ROUND_DOWN);c=B.BigNumber.minimum(s,g)}else c=v}return{amount:B.BigNumber.minimum(c,i),decimals:a}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Ze:e.multipliedBy(s).dividedBy(Mr).plus(Ze).decimalPlaces(0,B.BigNumber.ROUND_DOWN)}};function tr(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var ks=require("@galacticcouncil/api-augment/hydradx"),Ds=require("@galacticcouncil/api-augment/basilisk"),H=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");tr(r)&&console.log(e,...t)}};var te=class extends H{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=="0"){let m=this.api.consts.balances.existentialDeposit;return{id:"0",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:a,isSufficient:o,existentialDeposit:n}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:a.toHuman(),isSufficient:o?o.toHuman():!0,location:s?.toJSON(),existentialDeposit:n.toString()}}getBond(e,t,r,s){let[i,a]=s,{assetType:o,isSufficient:n,existentialDeposit:l}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,r),d=a.toNumber(),h=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",h.format(d)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:m,icon:c,type:o.toString(),isSufficient:n.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:d}}getShares(e,t,r,s){let{assets:i}=s,{name:a,symbol:o,assetType:n,isSufficient:l,existentialDeposit:c}=t,d=i.map(f=>f.toString()).map(f=>{let{symbol:y}=this.getToken(f,t,r);return[f,y]}),h=Object.fromEntries(d),g=Object.values(h);return{id:e,name:g.join(", "),symbol:o?.isSome?o.toHuman():a.toHuman(),decimals:18,icon:g.join("/"),type:n.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:h}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),a=r?.find(o=>o.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:a}=s.unwrap();return[r.toString(),{decimals:Number(i.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,i,a,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),n=this.getSupportedAssets(r),l=this.normalizeMetadata(n,o),c=n.map(([{args:[m]},d])=>{let h=d.unwrap(),g=s.get(m.toString()),{assetType:f}=h;switch(f.toString()){case"Bond":let y=a.get(m.toString());return this.getBond(m.toString(),h,l,y);case"StableSwap":let S=i.get(m.toString());return this.getShares(m.toString(),h,l,S);case"External":return this.getExternal(m.toString(),h,t,g);default:return this.getToken(m.toString(),h,l,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 U=class extends H{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==="0"?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 r=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateFreeBalance(r)))}async subscribeSystemBalances(e,t){return this.api.query.system.account.multi(e,r=>{let s=[];r.forEach((i,a)=>{let o=this.calculateFreeBalance(i.data),n=e[a];s.push([n,o])}),t(s)})}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(a=>[e,a]):s.map(({args:[a,o]})=>[a.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,a=>{let o=[];a.forEach((n,l)=>{let c=this.calculateFreeBalance(n),m=i[l][1];o.push([m,c])}),t(o)})}async subscribeTokenBalances(e,t){return this.api.query.tokens.accounts.multi(e,r=>{let s=[];r.forEach((i,a)=>{let o=this.calculateFreeBalance(i),n=e[a];s.push([n,o])}),t(s)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([n,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[n]}])=>n.toString()))(),a=async()=>{let o=await Promise.all(i.map(async n=>[n,await this.getErc20Balance(e,n)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{a()})}async subscribeErc20Balances(e,t){let r=async()=>{let s=await Promise.all(e.map(async i=>{let[a,o]=i;return[i,await this.getErc20Balance(a,o)]}));t(s)};return this.api.rpc.chain.subscribeNewHeads(async()=>{r()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let t=e.free.toString(),r=e.frozen.toString();return(0,B.BigNumber)(t).lt(r)?(0,B.BigNumber)(0):(0,B.BigNumber)(t).minus(r)}};var ue=class extends H{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==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(a=>[e,a]):s.map(({args:[a,o]})=>[a.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,a=>{let o=[];a.forEach((n,l)=>{let c=i[l][1],m=this.calculateBalance(n);o.push([c,m])}),t(o)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([n,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[n]}])=>n.toString()))(),a=async()=>{let o=await Promise.all(i.map(async n=>[n,await this.getErc20Balance(e,n)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{a()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=(0,B.BigNumber)(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),i=t.gte(r)?t.minus(r).toString():"0",a=t.plus(s).toString();return{free:t.toString(),total:a,transferable:i,reserved:s,frozen:r}}};var me=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 It=require("@galacticcouncil/math-liquidity-mining"),rr=require("@polkadot/types"),At=require("@polkadot/util"),Ft=require("@polkadot/util-crypto");var et=class extends H{balanceClient;constructor(e){super(e),this.balanceClient=new U(e)}secondsInYear=new B.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[,a]=s.args,o=i.unwrap().toString(),n=a.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(n)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,n,o)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(n),!1).toString(),g=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(h,g);return{assetId:e,globalFarm:l,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[,a]=s.args,o=i.unwrap().toString(),n=a.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(n)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,n,o)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(n),!0).toString(),g=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(h,g);return{assetId:e,globalFarm:l,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 B.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),o=a.price.n.toString(),n=a.price.d.toString(),l;return Number(t)<Number(r)?l=(0,It.fixed_from_rational)(o,n):l=(0,It.fixed_from_rational)(n,o),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(0,At.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new rr.GenericAccountId32(e,this.padEndU8a((0,At.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:n,priceAdjustment:l,potBalance:c})=>{let m=new B.BigNumber(n.totalSharesZ.toString()),d=n.plannedYieldingPeriods.toString(),h=new B.BigNumber(n.yieldPerPeriod.toString()),g=new B.BigNumber(n.maxRewardPerPeriod.toString()),f=n.blocksPerPeriod.toString(),y=new B.BigNumber(o.multiplier.toString()).shiftedBy(-18),S=this.secondsInYear.div(new B.BigNumber(r).times(f)),P;if(m.isZero())P=h.times(y).times(S);else{let D=this.getGlobalRewardPerPeriod(m,h,g,l);P=this.getPoolYieldPerPeriod(D,y,m,l).times(S)}let x=new B.BigNumber(n.pendingRewards.toString()).plus(n.accumulatedPaidRewards.toString()),A=g.times(d),w=c?x.plus(c):A;return x.div(w).gte(.999)?v:P.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,n)=>o.plus(n),v).toString():void 0}};var Ae=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Et=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Fe=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Rt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},_t=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"}};var tt=require("viem"),Lr=1e7,Ee=class{api;constructor(e){this.api=e}async getBlock(){let e=await this.api.query.ethereum.currentBlock(),{header:t}=e.unwrap(),r=t.timestamp.toBigInt()/1000n,s=t.number.toBigInt();return{timestamp:r,number:s}}readContract=(async e=>{let{abi:t,address:r,functionName:s,args:i}=e,a=(0,tt.encodeFunctionData)({abi:t,functionName:s,args:i}),o=await this.api.call.ethereumRuntimeRPCApi.call("",r,a,0,Lr,null,null,null,!1,[]);if(o.isErr)throw console.error(s,o.asErr.toHuman()),new Error("Contract read failure");let{value:n,exitReason:l,usedGas:c}=o.asOk;if(l.isSucceed)return(0,tt.decodeFunctionResult)({abi:t,functionName:s,data:n.toHex()});throw console.log(s,l.toString(),c.toHuman()),new Error("Contract read error")})};var sr=require("viem"),Hr=["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"],kt=u=>{let t=[u.endpoint,...Hr],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return(0,sr.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1})};var Q=require("viem");function ir(u){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return u.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var Re=class{api;chain;constructor(e){this.api=e,this.chain=kt(this.provider)}get provider(){let{provider:e}=this.api._options;return e}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,Q.createPublicClient)({chain:this.chain,transport:(0,Q.http)()})}getWsProvider(){return(0,Q.createPublicClient)({chain:this.chain,transport:ir(this.provider)})}getSigner(e){return(0,Q.createWalletClient)({account:e,chain:this.chain,transport:(0,Q.custom)(window.ethereum)})}getRPCAdapter(){return new Ee(this.api)}};var Dt=[{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 pe=class{rpcAdapter;constructor(e){this.rpcAdapter=e.getRPCAdapter()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.rpcAdapter.readContract({abi:Dt,address:e,functionName:"latestRoundData"}),this.rpcAdapter.readContract({abi:Dt,address:e,functionName:"decimals"}),this.rpcAdapter.getBlock()]),[a,o,n,l]=r,c=i.number-(i.timestamp-l)/BigInt(t),m=Number(c);return{price:o,decimals:s,updatedAt:m<0?0:m}}};var re=(u,e=new Map)=>t=>{let r;return e.has(t)?e.get(t):(e.set(t,r=u(t)),r)};var _=(a=>(a.Aave="Aave",a.LBP="Lbp",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="Xyk",a.HSM="Hsm",a))(_||{}),se=(c=>(c.UnknownError="UnknownError",c.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",c.InsufficientTradingAmount="InsufficientTradingAmount",c.InsufficientCollateral="InsufficientCollateral",c.MaxHoldingExceeded="MaxHoldingExceeded",c.MaxInRatioExceeded="MaxInRatioExceeded",c.MaxOutRatioExceeded="MaxOutRatioExceeded",c.TradeNotAllowed="TradeNotAllowed",c.MaxBuyBackExceeded="MaxBuyBackExceeded",c.MaxBuyPriceExceeded="MaxBuyPriceExceeded",c))(se||{});var Ne=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e)}constructor(e){this.type="Aave",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(n=>[n.id,n])),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 a=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:o,assetInED:v,assetOutED:v}}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=[];return t.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=[];return r.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return F(R,e.decimalsOut)}spotPriceOutGivenIn(e){return F(R,e.decimalsIn)}calculateTradeFee(e,t){return v}};var dr=require("@polkadot/util-crypto"),gr=require("@polkadot/util"),hr=require("viem");var _e=(u,e)=>u===e?0:u==null?e==null?0:-1:e==null?u==null?0:1:typeof u.compare=="function"?u.compare(e):typeof e.compare=="function"?-e.compare(u):u<e?-1:u>e?1:0;var rt=(u,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(u(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var Gr=rt(()=>"illegal argument(s)"),nr=u=>{throw new Gr(u)};var qr=rt(()=>"index out of bounds"),Mt=u=>{throw new qr(u)},st=(u,e,t)=>(u<e||u>=t)&&Mt(u);var ar=23283064365386963e-26,it=class{float(e=1){return this.int()*ar*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*ar-.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 nt=class extends it{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 or=new nt(Math.random);var lr=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var cr=Object.getPrototypeOf({}),at="function",ur="string",de=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===at)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===at)return e.equiv(u)}else return u==e;return typeof u===ur||typeof e===ur?!1:(t=Object.getPrototypeOf(u),(t==null||t===cr)&&(t=Object.getPrototypeOf(e),t==null||t===cr)?Xr(u,e):typeof u!==at&&u.length!==void 0&&typeof e!==at&&e.length!==void 0?Ur(u,e):u instanceof Set&&e instanceof Set?Wr(u,e):u instanceof Map&&e instanceof Map?zr(u,e):u instanceof Date&&e instanceof Date?u.getTime()===e.getTime():u instanceof RegExp&&e instanceof RegExp?u.toString()===e.toString():u!==u&&e!==e)},Ur=(u,e,t=de)=>{let r=u.length;if(r===e.length)for(;r-- >0&&t(u[r],e[r]););return r<0},Wr=(u,e,t=de)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),zr=(u,e,t=de)=>u.size===e.size&&t([...u].sort(),[...e].sort()),Xr=(u,e,t=de)=>{if(Object.keys(u).length!==Object.keys(e).length)return!1;for(let r in u)if(!e.hasOwnProperty(r)||!t(u[r],e[r]))return!1;return!0};var Lt=class{value;constructor(e){this.value=e}deref(){return this.value}};var mr=u=>u instanceof Lt;var ot=class u{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return pr("next",this._head)}reverseIterator(){return pr("prev",this.tail)}clear(){this.release()}compare(e,t=_e){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,a=0;for(;r-- >0&&a===0;)a=t(s.value,i.value),s=s.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof u||lr(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(!de(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?.value}insertSorted(e,t){t=t||_e;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?.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!mr(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&&Mt(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*pr(u,e){for(;e;)yield e.value,e=e[u]}var lt=class u extends ot{_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 u(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 u}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):(st(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):(st(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new u,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=a=>({first(){return a.value},next(){return a!==s&&a.next?i(a.next):void 0}});return r?i(r):void 0}shuffle(e,t=or){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)&&nr("invalid indices: ${from} / ${to}");let i=new u,a=this.nthCell(r);for(;a&&++r<=s;)i.push(a.value),a=a.next;return i}sort(e=_e){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,a=0;for(let n=0;n<t&&(a++,i=i.next,!!i);n++);let o=t;for(;a>0||o>0&&i;){let n;a===0?(n=i,i=i.next,o--):!i||o===0||e(r.value,i.value)<=0?(n=r,r=r.next,a--):(n=i,i=i.next,o--),this._tail?this._tail.next=n:this._head=n,n.prev=this._tail,this._tail=n}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),st(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new u;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 a of r)this.insertBefore(s,a);else for(let a of r)this.push(a);return i}};var ct=class u{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 lt,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 u(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 ge=class u extends ct{constructor(e,t){super(e,{ttl:3600*1e3,autoExtend:!1,...t})}empty(){return new u(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),a=Math.max(0,s-(i?i.value.s:0));return this._size+=a,this.ensureSize()?this.doSetEntry(i,e,t,s,r):this._size-=a,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 a=Date.now()+i;e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,e.value.t=a,this.items.asTail(e)):(this.items.push({k:t,v:r,s,t:a,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 G=class extends U{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;onNewBlockHandler;onEventsHandler;memPoolsCache=new ge(null,{maxlen:1,ttl:3600*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=re(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new pe(t),this.onNewBlockHandler=this.onNewBlock.bind(this),this.onEventsHandler=this.onEvents.bind(this)}onNewBlock(e){}onEvents(e){}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 this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools();let e=this.subscribeBalances(),t=this.subscribeUpdates();this.subs.push(e),this.subs.push(t);let r=this.getPoolType();return this.log(r,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(r,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}async subscribeBalances(){let e=[],t=[],r=[],s=[];for(let o of this.augmentedPools){let{address:n,tokens:l}=o;l.filter(c=>c.id==="0").forEach(()=>{e.push(n)}),l.filter(c=>["Token","StableSwap"].includes(c.type)&&c.id!=="0"&&c.id!==o.id).forEach(c=>{t.push([n,c.id])}),l.filter(c=>c.type==="Erc20").forEach(c=>{r.push([n,c.id])})}let i=o=>{o.forEach(([n,l])=>{let c=this.pools.find(m=>m.address===n);if(c){let m=c.tokens.findIndex(d=>d.id==="0");c.tokens[m].balance=l.toString()}})},a=o=>{o.forEach(([n,l])=>{let[c,m]=n,d=this.pools.find(h=>h.address===c);if(d){let h=d.tokens.findIndex(g=>g.id===m);d.tokens[h].balance=l.toString()}})};if(e.length>0){let o=await this.subscribeSystemBalances(e,i);s.push(o)}if(t.length>0){let o=await this.subscribeTokenBalances(t,a);s.push(o)}if(r.length>0){let o=await this.subscribeErc20Balances(r,a);s.push(o)}return()=>{for(let o of s)try{o()}catch(n){console.warn("Balance unsub failed",n)}}}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t()).catch(t=>console.warn("Unsub failed",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}};function Ce(u,e){let t=[];return JSON.stringify(u,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Yr(u,e,t){let r;return JSON.stringify(u,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Vr=(u,e)=>typeof e=="bigint"?e.toString():e;var Kr=["Supply","Withdraw","Repay","Borrow"],ke=class extends G{getPoolType(){return"Aave"}getPoolId(e,t){let r="aave:"+e+"/"+t;return(0,dr.encodeAddress)((0,gr.stringToU8a)(r.padEnd(32,"\0")),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}getReserveH160Id(e){return e.type==="Erc20"?Ce(e.location,"accountKey20").accountKey20.key:V.fromAssetId(e.id)}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,r){return{}}onEvents(e){e.forEach(t=>{let{event:r}=t,s=`${r.section}:${r.method}`;if(s==="router:Executed"){let[i,a]=r.data.toJSON();this.pools.filter(o=>o.tokens.some(n=>n.id===i.toString()||n.id===a.toString())).forEach(o=>{this.log(`Sync AAVE via [router:Executed] :: ${i}:${a}`),this.updatePoolState(o)})}if(s==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:a,args:o}=(0,hr.decodeEventLog)({abi:Qe,topics:i.topics,data:i.data});if(Kr.includes(a)){let n=o.reserve.toLowerCase();this.pools.filter(l=>{let[c]=l.tokens;return this.getReserveH160Id(c).toLowerCase()===n}).forEach(l=>{this.log(`Sync AAVE via [evm:Log] :: ${a} ${n}`),this.updatePoolState(l)})}}catch{}}})}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return()=>{}}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(a=>{let o=a.id===t.id?s.toString():i.toString();return{...a,balance:o}})}};var K=require("@galacticcouncil/math-lbp"),X=class{static getSpotPrice(e,t,r,s,i){return(0,K.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,K.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,K.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,K.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,K.calculate_pool_trade_fee)(e,t,r)}};var b=class u{static toPct(e){let[t,r]=e;return u.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return u.safeDivide(t,r)}static fromPermill(e){return[e,1e6]}static fromPerbill(e){return[e,1e9]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,r=12){let s=10**r;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};var De=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new u(e)}constructor(e){this.type="Lbp",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.fee=e.fee,this.repayFeeApply=e.repayFeeApply}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(n=>[n.id,n])),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 a=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,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 a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let o=this.calculateTradeFee(t,r),n=b.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(o),c=this.calculateInGivenOut(e,l),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:n,errors:i}}else{let o=this.calculateInGivenOut(e,t),n=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(n)&&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 a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let o=this.calculateOutGivenIn(e,t),n=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(o,r),l=b.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=o.minus(n),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=X.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?v:s}calculateOutGivenIn(e,t){let r=X.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?v:s}spotPriceInGivenOut(e){let t=X.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),F(R,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=X.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),F(R,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=X.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var Me=class extends G{MAX_FINAL_WEIGHT=F(p(100),6);poolsData=new Map([]);getPoolType(){return"Lbp"}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toNumber(),t=this.api.consts.lbp.maxOutRatio.toNumber(),r=this.api.consts.lbp.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getPoolDelta(e,t,r){let{start:s,end:i,assets:a,initialWeight:o,finalWeight:n,repayTarget:l,feeCollector:c}=t,m=X.calculateLinearWeights(s.toString(),i.toString(),o.toString(),n.toString(),r),[d,h]=a,g=d.toString(),f=p(m),y=h.toString(),S=this.MAX_FINAL_WEIGHT.minus(p(f)),[P,x,A]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,y)]);return{repayFeeApply:P,tokens:[{id:g,weight:f,balance:x.toString()},{id:y,weight:S,balance:A.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>=r&&t<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}}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,a])=>this.isActivePool(a.unwrap(),r.toNumber())).map(async([{args:[i]},a])=>{let o=a.unwrap(),n=i.toString(),l=await this.getPoolDelta(n,o,r.toString());this.poolsData.set(i.toString(),o);let[c,m]=o.fee;return{address:n,type:"Lbp",fee:b.fromRate(c.toNumber(),m.toNumber()),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t,r){let s=this.pools.find(i=>i.address===r);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getRepayFee(){let[e,t]=this.api.consts.lbp.repayFee;return b.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return this.api.query.parachainSystem.validationData(async e=>{let{relayParentNumber:t}=e.unwrap();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s)if(this.isActivePool(s,t.toNumber())){let a=await this.getPoolDelta(r.address,s,t.toString());Object.assign(r,a)}else{let a=this.pools.findIndex(o=>o.address==r.address);this.pools.splice(a,1)}})})}};var I=require("@galacticcouncil/math-omnipool");var E=class{static calculateSpotPrice(e,t,r,s){return(0,I.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,I.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,a,o,n,l){return(0,I.calculate_in_given_out)(e,t,r,s,i,a,o,n,l)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,I.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,a,o,n,l){return(0,I.calculate_out_given_in)(e,t,r,s,i,a,o,n,l)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,I.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculateShares(e,t,r,s){return(0,I.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,a,o,n){return(0,I.calculate_liquidity_out)(e,t,r,s,i,a,o,n)}static calculateLiquidityLRNAOut(e,t,r,s,i,a,o,n){return(0,I.calculate_liquidity_lrna_out)(e,t,r,s,i,a,o,n)}static calculateCapDifference(e,t,r,s){let i=(0,B.BigNumber)(t),a=(0,B.BigNumber)(e),o=(0,B.BigNumber)(s),l=(0,B.BigNumber)(r).shiftedBy(-18);if(i.div(o).lt(l)){let m=l.times(o).minus(i).times(a),d=i.times((0,B.BigNumber)(1).minus(l));return m.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return(0,I.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,I.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,I.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,I.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,I.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,r,s,i,a,o,n,l,c,m){return(0,I.recalculate_asset_fee)(e,t,r,s,i,a,o,n,l,c,m)}static recalculateProtocolFee(e,t,r,s,i,a,o,n,l,c,m){return(0,I.recalculate_protocol_fee)(e,t,r,s,i,a,o,n,l,c,m)}static verifyAssetCap(e,t,r,s){return(0,I.verify_asset_cap)(e,t,r,s)}};var Le=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new u(e)}constructor(e){this.type="Omnipool",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.hubAssetId=e.hubAssetId}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 a=p(s.balance),o=p(i.balance),n=p(s.existentialDeposit),l=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:a,balanceOut:o,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:n,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),o=s===v?v:a.div(s).multipliedBy(100).decimalPlaces(4),n=[],l=E.isSellAllowed(e.tradeableIn),c=E.isBuyAllowed(e.tradeableOut);(!l||!c)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&n.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&n.push("MaxOutRatioExceeded");let d=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(d)&&n.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:n}}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(4),n=[],l=E.isSellAllowed(e.tradeableIn),c=E.isBuyAllowed(e.tradeableOut);(!l||!c)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&n.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&n.push("MaxInRatioExceeded");let d=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(d)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:n}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=E.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?b.toRaw(r.assetFee).toString():v.toString(),r?b.toRaw(r.protocolFee).toString():v.toString()),i=p(s);return i.isNegative()?v:i}calculateLrnaInGivenOut(e,t,r){let s=E.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?b.toRaw(r.assetFee).toString():v.toString()),i=p(s);return i.isNegative()?v:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=E.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?b.toRaw(r.assetFee).toString():v.toString(),r?b.toRaw(r.protocolFee).toString():v.toString()),i=p(s);return i.isNegative()?v:i}calculateOutGivenLrnaIn(e,t,r){let s=E.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?b.toRaw(r.assetFee).toString():v.toString()),i=p(s);return i.isNegative()?v:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=E.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=E.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=E.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=E.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var br=require("@polkadot/util-crypto"),Pr=require("@polkadot/util");var yr="omnipool",fr="Short",He=class extends G{dynamicFees=new Map;dynamicFeesConfiguration=new Map;oracles=new Map;memQueryCache=new ge(null,{ttl:6*1e3});memOracleQuery=re(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(yr,t,fr)},this.memQueryCache);memFeesQuery=re(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);memFeesConfigurationQuery=re(e=>this.api.query.dynamicFees.assetFeeConfiguration(e),this.memQueryCache);getPoolType(){return"Omnipool"}getPoolId(){return(0,br.encodeAddress)((0,Pr.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getOracleKey(e){return e==="0"?["0","1"]:["1",e]}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toNumber(),t=this.api.consts.omnipool.maxOutRatio.toNumber(),r=this.api.consts.omnipool.minimumTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getDynamicFees(e){return this.dynamicFees.has(e)?this.dynamicFees.get(e):this.memFeesQuery(e)}async getDynamicFeesConfiguration(e){return this.dynamicFeesConfiguration.has(e)?this.dynamicFeesConfiguration.get(e):this.memFeesConfigurationQuery(e)}async getOraclePrice(e){let r=this.getOracleKey(e).join(":");return this.oracles.has(r)?this.oracles.get(r):this.memOracleQuery(r)}isSupported(){return this.api.query.omnipool!==void 0}isAssetConfigSupported(){return this.api.query.dynamicFees.assetFeeConfiguration!==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)]),a=r.map(async([{args:[n]},l])=>{let{hubReserve:c,shares:m,tradable:d,cap:h,protocolShares:g}=l.unwrap(),f=await this.getBalance(t,n.toString());return{id:n.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:d.bits.toNumber(),balance:f.toString(),cap:p(h.toString()),protocolShares:p(g.toString())}}),o=await Promise.all(a);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,r){let s=t.assetOut,i=t.assetIn,a;if(this.isAssetConfigSupported()&&(a=await this.getDynamicFeesConfiguration(s).then(P=>P.unwrapOr(null))),a?.isFixed){let P=a.asFixed.assetFee.toNumber(),x=a.asFixed.protocolFee.toNumber();return{assetFee:b.fromPermill(P),protocolFee:b.fromPermill(x)}}let[o,n,l]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[c,m,d]=this.getAssetFee(t,e,o,n,a?.isDynamic?a.asDynamic.assetFeeParams:void 0),[h,g,f]=i==="1"?[0,0,0]:this.getProtocolFee(t,e,o,l,a?.isDynamic?a.asDynamic.protocolFeeParams:void 0),y=c+h,S=d+f;return{assetFee:b.fromPermill(m),protocolFee:b.fromPermill(g),min:b.fromPermill(y),max:b.fromPermill(S)}}getAssetFee(e,t,r,s,i){let{assetOut:a,balanceOut:o}=e,{minFee:n,maxFee:l,decay:c,amplification:m}=i||this.api.consts.dynamicFees.assetFeeParameters,d=b.fromPermill(n.toNumber()),h=b.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[n.toNumber(),n.toNumber(),l.toNumber()];let[g]=s.unwrap(),{assetFee:f,timestamp:y}=r.unwrap(),S=Math.max(1,t-y.toNumber()),P=g.volume.bIn.toString(),x=g.volume.bOut.toString(),A=g.liquidity.b.toString();a==="0"&&(P=g.volume.aIn.toString(),x=g.volume.aOut.toString(),A=g.liquidity.a.toString());let w=b.fromPermill(f.toNumber()),T=E.recalculateAssetFee(P,x,A,"9",o.toString(),b.toRaw(w).toString(),S.toString(),b.toRaw(d).toString(),b.toRaw(h).toString(),c.toString(),m.toString());return[n.toNumber(),Number(T)*1e6,l.toNumber()]}getProtocolFee(e,t,r,s,i){let{assetIn:a,balanceIn:o}=e,{minFee:n,maxFee:l,decay:c,amplification:m}=i||this.api.consts.dynamicFees.protocolFeeParameters,d=b.fromPermill(n.toNumber()),h=b.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[n.toNumber(),n.toNumber(),l.toNumber()];let[g]=s.unwrap(),{protocolFee:f,timestamp:y}=r.unwrap(),S=Math.max(1,t-y.toNumber()),P=g.volume.bIn.toString(),x=g.volume.bOut.toString(),A=g.liquidity.b.toString();a==="0"&&(P=g.volume.aIn.toString(),x=g.volume.aOut.toString(),A=g.liquidity.a.toString());let w=b.fromPermill(f.toNumber()),T=E.recalculateProtocolFee(P,x,A,"9",o.toString(),b.toRaw(w).toString(),S.toString(),b.toRaw(d).toString(),b.toRaw(h).toString(),c.toString(),m.toString());return[n.toNumber(),Number(T)*1e6,l.toNumber()]}async subscribeUpdates(){let[e]=this.pools,t=e.tokens.map(n=>n.id),r=[],s=await this.api.query.omnipool.assets.multi(t,n=>{e.tokens=n.map((l,c)=>{let m=e.tokens[c];if(l.isNone)return m;let d=l.unwrap();return this.updateTokenState(m,d)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,n=>{n.forEach((l,c)=>{let m=t[c];this.dynamicFees.set(m,l)})});if(r.push(i),this.isAssetConfigSupported()){let n=await this.api.query.dynamicFees.assetFeeConfiguration.multi(t,l=>{l.forEach((c,m)=>{let d=t[m];this.dynamicFeesConfiguration.set(d,c)})});r.push(n)}let a=t.map(n=>{let l=this.getOracleKey(n);return[yr,l,fr]}),o=await this.api.query.emaOracle.oracles.multi(a,n=>{n.forEach(async(l,c)=>{let m=a[c],[d,h,g]=m;this.oracles.set(h.join(":"),l)})});return r.push(o),()=>{for(let n of r)try{n()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:a,protocolShares:o}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(a.toString()),protocolShares:p(o.toString()),tradeable:i.bits.toNumber()}}};var C=require("@galacticcouncil/math-xyk"),J=class{static getSpotPrice(e,t,r){return(0,C.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,C.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,C.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,C.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,C.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,C.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,C.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,C.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,C.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,C.calculate_liquidity_out_asset_b)(e,t,r,s)}};var Ge=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e)}constructor(e){this.type="Xyk",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}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 a=p(s.balance),o=p(i.balance),n=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:o,assetInED:n,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),a=b.toPct(r.exchangeFee),o=s.plus(i),n=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&n.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&n.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&n.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:s,amountOut:t,feePct:a,errors:n}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),a=b.toPct(r.exchangeFee),o=s.minus(i),n=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&n.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&n.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:o,feePct:a,errors:n}}calculateInGivenOut(e,t){let r=J.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?v:s}calculateOutGivenIn(e,t){let r=J.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?v:s}spotPriceInGivenOut(e){let t=J.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=F(R,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=J.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=F(R,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=J.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var qe=class extends G{getPoolType(){return"Xyk"}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toNumber(),t=this.api.consts.xyk.maxOutRatio.toNumber(),r=this.api.consts.xyk.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}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(),[a,o]=s.unwrap(),[n,l]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,o.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:n.toString()},{id:o.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t,r){return{exchangeFee:this.getExchangeFee()}}getExchangeFee(){let[e,t]=this.api.consts.xyk.getExchangeFee;return b.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return()=>{}}};var k=require("@galacticcouncil/math-stableswap"),M=class{static getPoolAddress(e){return(0,k.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,k.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,a,o){return(0,k.calculate_in_given_out)(e,t,r,s,i,a,o)}static calculateAddOneAsset(e,t,r,s,i,a,o){return(0,k.calculate_add_one_asset)(e,t,r,s,i,a,o)}static calculateSharesForAmount(e,t,r,s,i,a,o){return(0,k.calculate_shares_for_amount)(e,t,r,s,i,a,o)}static calculateOutGivenIn(e,t,r,s,i,a,o){return(0,k.calculate_out_given_in)(e,t,r,s,i,a,o)}static calculateLiquidityOutOneAsset(e,t,r,s,i,a,o){return(0,k.calculate_liquidity_out_one_asset)(e,t,r,s,i,a,o)}static calculateShares(e,t,r,s,i,a){return(0,k.calculate_shares)(e,t,r,s,i,a)}static calculateSpotPriceWithFee(e,t,r,s,i,a,o,n){return(0,k.calculate_spot_price_with_fee)(e,t,r,s,i,a,o,n)}static recalculatePegs(e,t,r,s,i){let a=(0,k.recalculate_peg)(e,t,r,s,i);return JSON.parse(a)}};var ae=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new u(e)}constructor(e){this.type="Stableswap",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.amplification=e.amplification,this.id=e.id,this.fee=e.fee,this.totalIssuance=e.totalIssuance,this.pegs=e.pegs,this.pegsFee=e.pegsFee}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 a=p(s.balance),o=p(i.balance),n=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:n,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),o=s===v?v:a.div(s).multipliedBy(100).decimalPlaces(4),n=[],l=E.isSellAllowed(e.tradeableIn),c=E.isBuyAllowed(e.tradeableOut);return(!l||!c)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&n.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:n}}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(4),n=[],l=E.isSellAllowed(e.tradeableIn),c=E.isBuyAllowed(e.tradeableOut);return(!l||!c)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&n.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:n}}calculateIn(e,t,r){let s=M.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?b.toRaw(r.fee).toString():v.toString(),this.getPegs()),i=p(s);return i.isNegative()?v:i}calculateAddOneAsset(e,t,r){let s=M.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?b.toRaw(r.fee).toString():v.toString(),this.getPegs()),i=p(s);return i.isNegative()?v:i}calculateSharesForAmount(e,t,r){let s=M.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?b.toRaw(r.fee).toString():v.toString(),this.getPegs()),i=p(s);return i.isNegative()?v: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=M.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=F(R,e.decimalsIn-e.decimalsOut);return p(t).div(s).decimalPlaces(0,1)}let r=F(R,18-e.decimalsIn);return p(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=M.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?b.toRaw(r.fee).toString():v.toString(),this.getPegs()),i=p(s);return i.isNegative()?v:i}calculateWithdrawOneAsset(e,t,r){let s=M.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?b.toRaw(r.fee).toString():v.toString(),this.getPegs()),i=p(s);return i.isNegative()?v:i}calculateShares(e,t,r){let s=M.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?b.toRaw(r.fee).toString():v.toString(),this.getPegs()),i=p(s);return i.isNegative()?v: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=M.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=F(R,e.decimalsOut-e.decimalsIn);return p(t).div(s).decimalPlaces(0,1)}let r=F(R,18-e.decimalsOut);return p(t).div(r).decimalPlaces(0,1)}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 ut=require("@polkadot/util-crypto");var Ue=class extends G{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=Number(e),r=M.getPoolAddress(t);return(0,ut.encodeAddress)((0,ut.blake2AsHex)(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toNumber()}}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:a,finalBlock:o}=t,n=M.calculateAmplification(s.toString(),i.toString(),a.toString(),o.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:n,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async a=>{let[o,n]=await Promise.all([this.api.query.stableswap.assetTradability(t,a.toString()),this.getBalance(e,a.toString())]);return{id:a.toString(),tradeable:o.bits.toNumber(),balance:n.toString()}});return Promise.all(i)}isSupported(){return this.api.query.stableswap!==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:[a]},o])=>{try{let n=o.unwrap(),l=a.toString(),c=this.getPoolAddress(l),[m,d,h]=await Promise.all([this.getPoolDelta(l,n,r.toString()),this.getPoolTokens(c,l,n),this.getPoolPegs(l,n,r.toString())]);return d.push({id:l,tradeable:15,balance:m.totalIssuance}),this.poolsData.set(c,n),{address:c,id:l,type:"Stableswap",fee:b.fromPermill(n.fee.toNumber()),tokens:d,...m,...h,...this.getPoolLimits()}}catch(n){return console.warn(`Skipping pool ${a.toString()}
2
- `,String(n)),null}});return(await Promise.all(s)).filter(a=>a!==null)}async getPoolFees(e,t,r){return{fee:this.pools.find(i=>i.address===r).pegsFee}}async getPoolPegs(e,t,r){let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getDefaultPegs(t);let i=s.unwrap(),a=await this.getLatestPegs(t,i,r),o=this.getRecentPegs(i),n=b.fromPermill(t.fee.toNumber()),l=b.fromPerbill(i.maxPegUpdate.toNumber()),[c,m]=M.recalculatePegs(JSON.stringify(o),JSON.stringify(a),r,b.toRaw(l).toString(),b.toRaw(n).toString()),d=Number(c)*1e6;return{pegsFee:b.fromPermill(d),pegs:m}}getDefaultPegs(e){let t=e.fee,r=M.defaultPegs(e.assets.length);return{pegsFee:b.fromPermill(t.toNumber()),pegs:r}}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,n])=>n.toString()),a=s.map(async(o,n)=>{if(o.isOracle){let[l,c,m]=o.asOracle,d=[m.toString(),i[n]].map(P=>Number(P)).sort((P,x)=>P-x),h=await this.api.query.emaOracle.oracles(l,d,c),[{price:g,updatedAt:f}]=h.unwrap(),y=g.n.toString(),S=g.d.toString();return m.toString()===d[0].toString()?[[y,S],f.toString()]:[[S,y],f.toString()]}else if(o.isMmOracle){let l=o.asMmOracle,{price:c,decimals:m,updatedAt:d}=await this.mmOracle.getData(l.toString()),h=10**m;return[[c.toString(),h.toString()],d.toString()]}else{if(o.isValue)return[o.asValue.map(l=>l.toString()),r];throw Error(o.type+" is not supported")}});return Promise.all(a)}async subscribeUpdates(){return this.api.query.system.number(async e=>{let t=e.toString();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s){let[i,a]=await Promise.all([this.getPoolDelta(r.id,s,t),this.getPoolPegs(r.id,s,t)]),o=r.tokens.map(n=>n.id===r.id?{...n,balance:i.totalIssuance}:n);Object.assign(r,{tokens:o},i,a)}})})}};var L=require("@galacticcouncil/math-hsm"),$=class{static calculateCollateralInGivenHollarOut(e,t,r){return(0,L.calculate_collateral_in_given_hollar_out)(e,t,r)}static calculateCollateralOutGivenHollarIn(e,t,r){return(0,L.calculate_collateral_out_given_hollar_in)(e,t,r)}static calculateHollarOutGivenCollateralIn(e,t,r){return(0,L.calculate_hollar_out_given_collateral_in)(e,t,r)}static calculateHollarInGivenCollateralOut(e,t,r){return(0,L.calculate_hollar_in_given_collateral_out)(e,t,r)}static calculateImbalance(e,t,r){return(0,L.calculate_imbalance)(e,t,r)}static calculateBuybackLimit(e,t){return(0,L.calculate_buyback_limit)(e,t)}static calculateBuybackPriceWithFee(e,t,r){return(0,L.calculate_buyback_price_with_fee)(e,t,r)}static calculateMaxPrice(e,t){return(0,L.calculate_max_price)(e,t)}};var mt=class u extends ae{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new u(e)}constructor(e){super(e),this.type="Hsm",this.hsmAddress=e.hsmAddress,this.hsmMintCapacity=e.hsmMintCapacity,this.hollarId=e.hollarId,this.hollarH160=e.hollarH160,this.collateralId=e.collateralId,this.collateralBalance=e.collateralBalance,this.maxBuyPriceCoefficient=e.maxBuyPriceCoefficient,this.maxInHolding=e.maxInHolding,this.purchaseFee=e.purchaseFee,this.buyBackFee=e.buyBackFee,this.buyBackRate=e.buyBackRate}validatePair(e,t){return!0}parsePair(e,t){return super.parsePair(e,t)}validateTradeHollarIn(e,t,r,s){let i=this.calculateBuybackLimit(e);t.gt(i)&&s.push("MaxBuyBackExceeded");let a=this.calculateBuyPrice(e,t,r),o=this.calculateMaxPrice(e);return a.gt(o)&&s.push("MaxBuyPriceExceeded"),r.gt(this.collateralBalance)&&s.push("InsufficientCollateral"),s}validateTradeHollarOut(e,t,r){return this.collateralBalance.plus(e).gt(this.maxInHolding)&&r.push("MaxHoldingExceeded"),t.gt(this.hsmMintCapacity)&&r.push("FacilitatorCapacityExceeded"),r}validateTradeConstraints(e,t,r){let s=[];return e.assetIn===this.hollarId?this.validateTradeHollarIn(e,t,r,s):this.validateTradeHollarOut(t,r,s)}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=this.validateTradeConstraints(e,r,t);return{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=this.validateTradeConstraints(e,t,r);return{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(e,t){let r=super.calculateInGivenOut(e,t,{fee:this.fee}),s=$.calculateHollarInGivenCollateralOut(t.toFixed(0),r.toFixed(0),b.toRaw(this.buyBackFee).toString());return p(s)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),r=$.calculateCollateralInGivenHollarOut(e.toFixed(0),JSON.stringify(t),b.toRaw(this.purchaseFee).toString());return p(r)}calculateInGivenOut(e,t){return e.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(t):this.calculateHollarInGivenCollateralOut(e,t)}calculateCollateralOutGivenHollarIn(e,t){let r=super.calculateOutGivenIn(e,t,{fee:this.fee}),s=$.calculateCollateralOutGivenHollarIn(t.toFixed(0),r.toFixed(0),b.toRaw(this.buyBackFee).toString());return p(s)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),r=$.calculateHollarOutGivenCollateralIn(e.toFixed(0),JSON.stringify(t),b.toRaw(this.purchaseFee).toString());return p(r)}calculateOutGivenIn(e,t){return e.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(e,t):this.calculateHollarOutGivenCollateralIn(t)}calculateImbalance(e){let t=this.getCollateralPeg(),r=$.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return p(r)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),r=$.calculateBuybackLimit(t.toString(),b.toRaw(this.buyBackRate).toString());return p(r)}calculateBuyPrice(e,t,r){let s=t.dividedBy(p(10).pow(e.decimalsIn));return r.dividedBy(p(10).pow(e.decimalsOut)).dividedBy(s)}calculateMaxPrice(e){let t=this.getCollateralPeg(),r=$.calculateMaxPrice(JSON.stringify(t),this.maxBuyPriceCoefficient.toFixed(0)),[s,i]=JSON.parse(r);return p(s).div(p(i)).shiftedBy(-1*e.decimalsOut)}spotPriceInGivenOut(e){let t=F(R,e.decimalsOut);return this.calculateInGivenOut(e,t)}spotPriceOutGivenIn(e){let t=F(R,e.decimalsIn);return this.calculateOutGivenIn(e,t)}getCollateralPeg(){let e=this.tokens.findIndex(s=>s.id!==this.hollarId),t=this.pegs[e],r=this.tokens[e].decimals;return this.isDefaultPeg(t)?[F(R,18).toString(),F(R,r).toString()]:t}isDefaultPeg(e){let[t,r]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&r==="1"}};var Ht=require("@polkadot/util"),Gt=require("@polkadot/util-crypto"),Sr=require("viem");var We=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var ze=class{rpcAdapter;constructor(e){this.rpcAdapter=e.getRPCAdapter()}async getFacilitatorCapacity(e,t){let[r,s]=await this.rpcAdapter.readContract({abi:We,address:e,functionName:"getFacilitatorBucket",args:[t]});return r-s}};var $r=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],pt=class extends G{stableClient;ghoTokenClient;constructor(e,t,r){super(e,t),this.stableClient=r,this.ghoTokenClient=new ze(t)}getPoolType(){return"Hsm"}getPoolId(e){let t="hsm:"+e;return(0,Gt.encodeAddress)((0,Ht.stringToU8a)(t.padEnd(32,"\0")),63)}getFacilitatorAddress(){return(0,Gt.encodeAddress)((0,Ht.stringToU8a)("modlpy/hsmod".padEnd(32,"\0")),63)}getHollarAddress(e){return Ce(e,"accountKey20").accountKey20.key}isSupported(){return this.api.query.hsm!==void 0}async loadPools(){let e=this.api.consts.hsm.hollarId.toString(),[t,r,s]=await Promise.all([this.api.query.assetRegistry.assetLocations(e),this.api.query.hsm.collaterals.entries(),this.stableClient.getPoolsMem()]);if(r.length===0)return[];let i=this.getFacilitatorAddress(),a=Y.fromAny(i),o=this.getHollarAddress(t.unwrap()),n=await this.ghoTokenClient.getFacilitatorCapacity(o,a),l=r.map(async([{args:[m]},d])=>{let h=d.unwrap(),g=m.toString(),{poolId:f,maxBuyPriceCoefficient:y,maxInHolding:S,purchaseFee:P,buyBackFee:x,buybackRate:A}=h,w=s.find(T=>T.id===f.toString());if(w){let T=this.getPoolId(f.toString()),D=await this.getBalance(i,g);return{...w,address:T,type:"Hsm",tokens:w.tokens.filter(q=>q.id!==f.toString()),hsmAddress:i,hsmMintCapacity:p(n),hollarId:e,hollarH160:o,collateralId:g,collateralBalance:D,maxBuyPriceCoefficient:p(y.toString()),maxInHolding:p(S.unwrap().toString()),purchaseFee:b.fromPermill(P.toNumber()),buyBackFee:b.fromPermill(x.toNumber()),buyBackRate:b.fromPerbill(A.toNumber())}}});return(await Promise.all(l)).filter(m=>m!==null)}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(async t=>{let{event:r}=t;if(`${r.section}:${r.method}`==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:a,args:o}=(0,Sr.decodeEventLog)({abi:We,topics:i.topics,data:i.data}),[n]=this.pools,{hsmAddress:l,hollarH160:c}=n,m=Y.fromAny(l),d=m.toLowerCase()===o.facilitatorAddress.toLowerCase();if($r.includes(a)&&d){let h=await this.ghoTokenClient.getFacilitatorCapacity(c,m);this.log(`Sync HSM facilitator via [evm:Log] :: ${a} ${h}`),this.pools.forEach(g=>{Object.assign(g,{hsmMintCapacity:h})})}}catch{}}})}async subscribeBalances(){let e=[],t=[],r=[];for(let i of this.pools){let{tokens:a,hsmAddress:o,collateralId:n}=i;a.find(c=>c.id===n).type==="Erc20"?t.push([o,n]):e.push([o,n])}let s=i=>{i.forEach(([a,o])=>{let[n,l]=a,c=this.pools.find(m=>m.tokens.some(d=>d.id===l));c&&Object.assign(c,{collateralBalance:o})})};if(e.length>0){let i=await this.subscribeTokenBalances(e,s);r.push(i)}if(t.length>0){let i=await this.subscribeErc20Balances(t,s);r.push(i)}return()=>{for(let i of r)try{i()}catch(a){console.warn("Balance unsub failed",a)}}}async subscribeUpdates(){return()=>{}}};var he=class extends H{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;hsmClient;clients=[];onChainAssets=[];block=0;blockHandlers=[];eventHandlers=[];disconnectSubscribeNewHeads=null;disconnectSubscribeEvents=null;memRegistry=re(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new te(this.api),this.aaveClient=new ke(this.api,t),this.xykClient=new qe(this.api,t),this.omniClient=new He(this.api,t),this.lbpClient=new Me(this.api,t),this.stableClient=new Ue(this.api,t),this.hsmClient=new pt(this.api,t,this.stableClient),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient,this.hsmClient],this.blockHandlers=this.clients.map(r=>r.onNewBlockHandler),this.eventHandlers=this.clients.map(r=>r.onEventsHandler),this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r}),this.api.query.system.events(r=>{this.onEvents(r)}).then(r=>{this.disconnectSubscribeEvents=r})}onNewBlock(e){this.block=e;for(let t of this.blockHandlers)try{t(e)}catch(r){this.log("onNewBlock handler error",r)}}onEvents(e){for(let t of this.eventHandlers)try{t(e)}catch(r){this.log("onEvents handler error",r)}}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={}){this.isRegistrySynced||await this.memRegistry(1);let{includeOnly:t=[],exclude:r=[]}=e;return t.length>0?this.getFilteredPools(s=>t.includes(s.getPoolType())):r.length>0?this.getFilteredPools(s=>!r.includes(s.getPoolType())):this.getFilteredPools(s=>s.isSupported())}async getFilteredPools(e){let t=this.clients.filter(e);return(await Promise.all(t.map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe(),this.hsmClient.unsubscribe(),this.disconnectSubscribeNewHeads?.(),this.disconnectSubscribeEvents?.()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(this.block,e,t.address);case"Xyk":return this.xykClient.getPoolFees(this.block,e,t.address);case"Omnipool":return this.omniClient.getPoolFees(this.block,e,t.address);case"Lbp":return this.lbpClient.getPoolFees(this.block,e,t.address);case"Stableswap":return this.stableClient.getPoolFees(this.block,e,t.address);case"Hsm":return this.hsmClient.getPoolFees(this.block,e,t.address);default:throw new Ae(t.type)}}};var ye=class extends he{feeCache=new Map;constructor(e,t){super(e,t)}onNewBlock(e){super.onNewBlock(e),this.feeCache.clear()}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);let s=super.getPoolFees(e,t);return this.feeCache.set(r,s),s}async destroy(){this.feeCache.clear(),super.destroy()}};var fe=class{static get(e){switch(e.type){case"Aave":return Ne.fromPool(e);case"Xyk":return Ge.fromPool(e);case"Omnipool":return Le.fromPool(e);case"Lbp":return De.fromPool(e);case"Stableswap":return ae.fromPool(e);case"Hsm":return mt.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var vr=require("@noble/hashes/sha2"),xr=require("@noble/hashes/utils");function jr(u){let e=u.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=(0,vr.sha256)(t);return(0,xr.bytesToHex)(r)}var Xe=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 Qr=10,Ye=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 Xe,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let o=i.dequeue();if(!o||o.length>Qr)continue;let n=o[o.length-1];(r===null||n[0]===r)&&s.push(o),e.get(n[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let m=[...o];m.push(c),i.enqueue(m)}})}return s}findShortestPaths(e,t,r){let s=[],i=new Xe,a=[];a.push([t,""]),i.enqueue(a);let o=1/0;for(;i.size()>0;){let n=i.dequeue();if(!n)continue;let l=n[n.length-1];if(l[0]===r){n.length<o?(o=n.length,s.length=0,s.push(n)):n.length===o&&s.push(n);continue}let c=e.get(l[0]);for(let m of c??[])this.isNotVisited(m,n)&&i.enqueue([...n,m])}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,a]of t){let o=parseInt(i),n=parseInt(a);r.get(o)?.push([n,s])}return r}};function qt(u){let e={};for(let t of u){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 a=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(a)}}}return e}var Ve=class{getProposals(e,t,r){let s=r.filter(P=>P.type==="Xyk"),i=r.filter(P=>P.type!=="Xyk"),a=parseInt(e),o=parseInt(t),n=new Set(i.map(P=>P.tokens).flat().map(P=>P.id)),l=n.has(e),c=n.has(t),m=new Ye,d=P=>{let x=qt(P),A=Object.keys(x),w=A.flatMap(T=>x[T]);return m.buildAndPopulateGraph(A,w)};if(!l&&!c){let P=s.filter(w=>w.tokens.find(T=>T.id===e)||w.tokens.find(T=>T.id===t)),x=d(P),A=m.findPaths(x,a,o);return this.parsePaths(A)}if(l&&c){let P=d(i),x=m.findPaths(P,a,o);return this.parsePaths(x)}let h=l?t:e,g=s.filter(P=>P.tokens.some(x=>x.id===h));if(g.length===0)return[];let f=[...i,...g],y=d(f),S=m.findPaths(y,a,o);return this.parsePaths(S)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let a=r[i],o=r[i+1];if(o==null)break;s.push(this.toEdge(a,o))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var be=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new Ve,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}buildRouteKey(e,t,r){return`${e}->${t}::${r.length}`}async getPools(){return this.poolService.getPools(this.routerOptions)}async getAllAssets(){let e=await this.getPools(),t=this.getAssets(e);return[...new Map(t).values()]}async getRouteableAssets(e){let t=await this.getAllAssets();return(await Promise.all(t.map(s=>s.id).filter(s=>s!==e).map(s=>this.getRoutes(s,e)))).filter(s=>s.length>0).map(([s])=>s[0].assetIn).sort()}async getRoutes(e,t){let r=await this.getPools();return this.validateInput(e,t,r),this.getPaths(e,t,r)}validateInput(e,t,r){if(r.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(r);if(s.get(e)===null)throw new Error(e+" is not supported asset");if(s.get(t)===null)throw new Error(t+" is not supported asset");return this.toPoolsMap(r)}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){let s=this.toPoolsMap(r);return this.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}getProposals(e,t,r){let s=this.buildRouteKey(e,t,r);if(this.routeProposals.has(s))return this.routeProposals.get(s);let i=this.routeSuggester.getProposals(e,t,r);return this.routeProposals.set(s,i),i}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}toPoolsMap(e){return new Map(e.map(t=>[t.address,fe.get(t)]))}toHops(e,t){return e.map(([r,s,i])=>{let a=t.get(r);return{poolAddress:r,poolId:a?.id,pool:a?.type,assetIn:s,assetOut:i}})}};var Jr=p("100");function Zr(u,e){return u.minus(e).abs().div(u.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Pe(u,e){return u.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ut(u,e){return R.minus(e.div(u)).multipliedBy(100).decimalPlaces(4)}function Wt(u,e){return e.div(u).minus(R).multipliedBy(100).decimalPlaces(4)}function ie(u,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),u.div(Jr).multipliedBy(e).decimalPlaces(0,1)}var dt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(dt||{}),gt=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(gt||{}),zt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(zt||{});var Se=class extends be{mlr;poolsSnapshot;constructor(e,t={}){super(e,t),this.mlr=new Map}buildCtxSync(e,t){let r=this.poolsSnapshot,s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(!i.length)throw new Fe(e,t);return{paths:i,pools:r,poolsMap:s}}async withCtx(e,t,r){this.poolsSnapshot||(this.poolsSnapshot=await super.getPools());let s=this.buildCtxSync(e,t);return r(s)}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,a=s[s.length-1].amountOut;return i.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(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[r,s]}}getPoolFeeRange(e){let t=e.min?b.toPct(e.min):void 0,r=e.max?b.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){return this.withCtx(e,t,async({paths:i,poolsMap:a})=>{let o;if(s)o=await this.toSellSwaps(r,s,a);else{let n=i.map(c=>this.toSellSwaps(r,c,a)),l=await Promise.all(n);o=this.findBestSellRoute(l)}return this.buildSell(a,o)})}async getSellTrades(e,t,r){return this.withCtx(e,t,async({paths:s,poolsMap:i})=>{let a=s.map(n=>this.toSellSwaps(r,n,i));return(await Promise.all(a)).filter(n=>n.every(l=>l.errors.length==0)).map(n=>this.buildSell(i,n)).sort((n,l)=>n.amountOut.isGreaterThan(l.amountOut)?-1:1)})}buildSell(e,t){let r=t[0],s=t[t.length-1],i=this.isDirectTrade(t),a=t.map(f=>f.spotPrice.shiftedBy(-1*f.assetOutDecimals)).reduce((f,y)=>f.multipliedBy(y)),o=F(a,s.assetOutDecimals),n=i?s.calculatedOut:this.calculateDelta0Y(r.amountIn,t,e),l=s.amountOut,c=i?s.tradeFeePct:Ut(n,l).toNumber(),m=n.minus(l),d=this.getRouteFeeRange(t),h=r.amountIn.shiftedBy(-1*r.assetInDecimals).multipliedBy(o),g=Pe(n,h);return{type:"Sell",amountIn:r.amountIn,amountOut:s.amountOut,spotPrice:o,tradeFee:m,tradeFeePct:c,tradeFeeRange:d,priceImpactPct:g.toNumber(),swaps:t,toHuman(){return{type:"Sell",amountIn:O(r.amountIn,r.assetInDecimals),amountOut:O(s.amountOut,s.assetOutDecimals),spotPrice:O(o,s.assetOutDecimals),tradeFee:O(m,s.assetOutDecimals),tradeFeePct:c,tradeFeeRange:d,priceImpactPct:g.toNumber(),swaps:t.map(f=>f.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],o=r.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let n=o.parsePair(a.assetIn,a.assetOut),l;i>0?l=s[i-1]:l=e;let c=o.calculateOutGivenIn(n,l);s.push(c)}return s[s.length-1]}async calculateMostLiquidRoute(e,t,r){let{paths:s,pools:i,poolsMap:a}=r,c=i.filter(y=>y.tokens.some(S=>S.id===e)).map(y=>y.type==="Aave"?y.tokens:y.tokens.filter(S=>S.id===e)).map(y=>y.map(S=>p(S.balance).shiftedBy(-1*S.decimals)).reduce((S,P)=>S.plus(P))).sort((y,S)=>S.isLessThan(y)?-1:1)[0].div(100).multipliedBy(.1),m=s.map(async y=>await this.toSellSwaps(c,y,a)),d=await Promise.all(m),g=this.findBestSellRoute(d).map(y=>({poolAddress:y.poolAddress,poolId:y?.poolId,pool:y.pool,assetIn:y.assetIn,assetOut:y.assetOut})),f=this.buildRouteKey(e,t,i);return this.mlr.set(f,g),g}async toSellSwaps(e,t,r){let s=[],i=[];for(let n=0;n<t.length;n++){let l=t[n],c=r.get(l.poolAddress);if(!c)throw new Error("Pool does not exit");let m=c.parsePair(l.assetIn,l.assetOut);s[n]=c,i[n]=m}let a=await Promise.all(i.map((n,l)=>this.poolService.getPoolFees(n,s[l]))),o=[];for(let n=0;n<t.length;n++){let l=t[n],c=s[n],m=a[n],d=i[n],h;n>0?h=o[n-1].amountOut:h=F(p(e),d.decimalsIn).decimalPlaces(0,1);let{amountOut:g,calculatedOut:f,feePct:y,errors:S}=c.validateAndSell(d,h,m),P=this.getPoolFeeRange(m),x=c.spotPriceOutGivenIn(d),A=h.shiftedBy(-1*d.decimalsIn).multipliedBy(x),w=Pe(f,A),T=c.type==="Aave";o.push({...l,assetInDecimals:d.decimalsIn,assetOutDecimals:d.decimalsOut,amountIn:h,amountOut:g,calculatedOut:f,spotPrice:x,tradeFeePct:y,tradeFeeRange:P,priceImpactPct:w.toNumber(),errors:S,isSupply:()=>T&&c.tokens[0].id===l.assetIn,isWithdraw:()=>T&&c.tokens[1].id===l.assetIn,toHuman(){return{...l,amountIn:O(h,d.decimalsIn),amountOut:O(g,d.decimalsOut),calculatedOut:O(f,d.decimalsOut),spotPrice:O(x,d.decimalsOut),tradeFeePct:y,priceImpactPct:w.toNumber(),errors:S}}})}return o}async getMostLiquidRoute(e,t){return this.withCtx(e,t,async r=>{let s=this.buildRouteKey(e,t,r.pools),i=this.mlr.get(s);return i||this.calculateMostLiquidRoute(e,t,r)})}async getBestSpotPrice(e,t){return this.withCtx(e,t,async r=>{let{pools:s,poolsMap:i}=r,a=this.buildRouteKey(e,t,s),o=this.mlr.get(a);o||(o=await this.calculateMostLiquidRoute(e,t,r));let n=await this.toSellSwaps("1",o,i),l=n.map(d=>d.spotPrice.shiftedBy(-1*d.assetOutDecimals)).reduce((d,h)=>d.multipliedBy(h)),c=n[n.length-1].assetOutDecimals;return{amount:F(l,c),decimals:c}}).catch(()=>{})}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,a=s[0].amountIn;return i.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){return this.withCtx(e,t,async({paths:i,poolsMap:a})=>{let o;if(s)o=await this.toBuySwaps(r,s,a);else{let n=i.map(c=>this.toBuySwaps(r,c,a)),l=await Promise.all(n);o=this.findBestBuyRoute(l)}return this.buildBuy(a,o)})}async getBuyTrades(e,t,r){return this.withCtx(e,t,async({paths:s,poolsMap:i})=>{let a=s.map(n=>this.toBuySwaps(r,n,i));return(await Promise.all(a)).filter(n=>n.every(l=>l.errors.length==0)).map(n=>this.buildBuy(i,n)).sort((n,l)=>n.amountIn.isGreaterThan(l.amountIn)?1:-1)})}buildBuy(e,t){let r=t[t.length-1],s=t[0],i=this.isDirectTrade(t),a=t.map(f=>f.spotPrice.shiftedBy(-1*f.assetInDecimals)).reduce((f,y)=>f.multipliedBy(y)),o=F(a,s.assetInDecimals),n=i?s.calculatedIn:this.calculateDelta0X(r.amountOut,t,e),l=s.amountIn,c=i?s.tradeFeePct:Wt(n,l).toNumber(),m=l.minus(n),d=this.getRouteFeeRange(t),h=r.amountOut.shiftedBy(-1*r.assetOutDecimals).multipliedBy(o),g;return n.isZero()?g=-100:g=Pe(h,n).toNumber(),{type:"Buy",amountOut:r.amountOut,amountIn:s.amountIn,spotPrice:o,tradeFee:m,tradeFeePct:c,tradeFeeRange:d,priceImpactPct:g,swaps:t,toHuman(){return{type:"Buy",amountOut:O(r.amountOut,r.assetOutDecimals),amountIn:O(s.amountIn,s.assetInDecimals),spotPrice:O(o,s.assetInDecimals),tradeFee:O(m,s.assetInDecimals),tradeFeePct:c,tradeFeeRange:d,priceImpactPct:g,swaps:t.map(f=>f.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],o=r.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let n=o.parsePair(a.assetIn,a.assetOut),l;i==t.length-1?l=e:l=s[0];let c=o.calculateInGivenOut(n,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[],i=[];for(let n=0;n<t.length;n++){let l=t[n],c=r.get(l.poolAddress);if(!c)throw new Error("Pool does not exit");let m=c.parsePair(l.assetIn,l.assetOut);s[n]=c,i[n]=m}let a=await Promise.all(i.map((n,l)=>this.poolService.getPoolFees(n,s[l]))),o=[];for(let n=t.length-1;n>=0;n--){let l=t[n],c=s[n],m=a[n],d=i[n],h;n==t.length-1?h=F(p(e),d.decimalsOut).decimalPlaces(0,1):h=o[0].amountIn;let{amountIn:g,calculatedIn:f,feePct:y,errors:S}=c.validateAndBuy(d,h,m),P=this.getPoolFeeRange(m),x=c.spotPriceInGivenOut(d),A=h.shiftedBy(-1*d.decimalsOut).multipliedBy(x),w;f.isZero()?w=-100:w=Pe(A,f).toNumber(),o.unshift({...l,assetInDecimals:d.decimalsIn,assetOutDecimals:d.decimalsOut,amountIn:g,amountOut:h,calculatedIn:f,spotPrice:x,tradeFeePct:y,tradeFeeRange:P,priceImpactPct:w,errors:S,isSupply(){return c.type==="Aave"&&c.tokens[0].id===l.assetIn},isWithdraw(){return c.type==="Aave"&&c.tokens[1].id===l.assetIn},toHuman(){return{...l,amountIn:O(g,d.decimalsIn),amountOut:O(h,d.decimalsOut),calculatedIn:O(f,d.decimalsIn),spotPrice:O(x,d.decimalsIn),tradeFeePct:y,tradeFeeRange:P,priceImpactPct:w,errors:S}}})}return o}};var Xt=6e3,Yt=p(1e15),ve=6,ht=-5,yt=360*60*1e3,es=3,Vt=6;var W=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 xe=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??Xt,minBudgetInNative:t.minBudgetInNative??Yt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[a,o]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:l,priceImpactPct:c}=o,m=l[0],d=l[l.length-1],{assetInDecimals:h}=m,{assetOutDecimals:g}=d,f=Math.abs(c),y=this.getMinimumTradeCount(n,a),S=this.getOptimalTradeCount(f),P=i?Math.round(s/i):S,x=Math.ceil(s/y),A=Math.round(s/S),w=Math.round(s/P),T=n.dividedBy(P).decimalPlaces(0,1),D=await this.router.getBestSell(e,t,O(T,h)),q=n.isLessThan(a),Ke=[];q&&Ke.push("OrderTooSmall");let $e=D.amountOut.multipliedBy(P),Pt=this.toBlockPeriod(w),St=D.tradeFee.multipliedBy(P),vt=W.build(l),je={assetIn:e,assetOut:t,errors:Ke,frequencyMin:x,frequencyOpt:A,frequency:w,tradeCount:P,tradeFee:St,tradeImpactPct:D.priceImpactPct,tradePeriod:Pt,tradeRoute:vt,type:"Dca"};return{...je,amountIn:n,amountOut:$e,tradeAmountIn:D.amountIn,tradeAmountOut:D.amountOut,toHuman(){return{...je,amountIn:O(n,h),amountOut:O($e,g),tradeAmountIn:O(D.amountIn,h),tradeAmountOut:O(D.amountOut,g)}}}}async getMinimumOrderBudget(e){if("0"===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice("0",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:a,swaps:o,priceImpactPct:n}=i,l=o[0],c=o[o.length-1],{assetInDecimals:m}=l,{assetOutDecimals:d}=c,h=Math.abs(n),g=this.getTwapTradeCount(h),f=a.dividedBy(g).decimalPlaces(0,1),y=await this.router.getBestSell(l.assetIn,c.assetOut,O(f,m)),S=g===1,P=a.isLessThan(s),x=y.priceImpactPct<ht,A=[];P||S?A.push("OrderTooSmall"):x&&A.push("OrderImpactTooBig");let w=y.amountOut.multipliedBy(g),T=y.tradeFee.multipliedBy(g),D=W.build(o),q={assetIn:e,assetOut:t,errors:A,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:ve,tradeRoute:D,type:"TwapSell"};return{...q,amountIn:a,amountOut:w,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:T,toHuman(){return{...q,amountIn:O(a,m),amountOut:O(w,d),tradeAmountIn:O(y.amountIn,m),tradeAmountOut:O(y.amountOut,d),tradeFee:O(T,d)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:a,swaps:o,priceImpactPct:n}=i,l=o[0],c=o[o.length-1],{assetInDecimals:m}=l,{assetOutDecimals:d}=c,h=Math.abs(n),g=this.getTwapTradeCount(h),f=a.dividedBy(g).decimalPlaces(0,1),y=await this.router.getBestBuy(l.assetIn,c.assetOut,O(f,d)),S=y.amountIn.multipliedBy(g),P=g===1,x=S.isLessThan(s),A=y.priceImpactPct<ht,w=[];x||P?w.push("OrderTooSmall"):A&&w.push("OrderImpactTooBig");let T=y.tradeFee.multipliedBy(g),D=W.build(o),q={assetIn:e,assetOut:t,errors:w,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:ve,tradeRoute:D,type:"TwapBuy"};return{...q,amountIn:S,amountOut:a,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:T,toHuman(){return{...q,amountIn:O(S,m),amountOut:O(a,d),tradeAmountIn:O(y.amountIn,m),tradeAmountOut:O(y.amountOut,d),tradeFee:O(T,m)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>yt){let s=yt/(this.blockTime*ve);return Math.round(s)}return t}getTwapExecutionTime(e){return e*ve*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,Vt)}};var Be=class extends H{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new U(e),this.aaveUtils=new ee(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(),oe)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var ft=class extends Be{_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:a}=s,n=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,a)).amount.isGreaterThanOrEqualTo(n)),l&&e.isGreaterThanOrEqualTo(n)?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],a=ie(e,this.slippagePct),o=s.assetIn,n=i.assetOut,l=e.plus(a),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(n,o,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(o,n,t.toFixed(),l.toFixed(),W.build(r)),await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let d=this.dispatchWithExtraGas(c);return this.wrapTx("RouterBuy",d,oe)}return this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],a=ie(t,this.slippagePct),o=s.assetIn,n=i.assetOut,l=t.minus(a),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(o,n,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(o,n,e.toFixed(),l.toFixed(),W.build(r)),await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let d=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSell",d,oe)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=ie(e,this.slippagePct),a=r.assetIn,o=s.assetOut,n=e.minus(i),l=this.api.tx.router.sellAll(a,o,n.toFixed(),W.build(t));if(await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let m=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",m,oe)}return this.wrapTx("RouterSellAll",l)}};var bt=class extends Be{_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:a}=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:a}}},null);return this.wrapTx("DcaSchedule",o)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:a,tradeRoute:o}=this.order,n=ie(i,this.slippagePct),l=i.minus(n),c=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:o}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:a,tradeRoute:o}=this.order,n=ie(s,this.slippagePct),l=s.plus(n),c=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:i.toFixed(),maxAmountIn:l.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var we=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new ft(this.api,this.evm).setTrade(e)}order(e){return new bt(this.api,this.evm).setOrder(e)}};var ts={router:{}};function rs(u,e=ts){let t=new me(u),r=new Re(u),s=new ye(u,r),i=new ee(r),a=new Se(s,e.router),o=new xe(a,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:i,router:a,scheduler:o},client:{asset:new te(u),balance:new U(u),balanceV2:new ue(u)},ctx:{pool:s},evm:r,tx:new we(u,r),destroy:()=>{s.destroy()}}}0&&(module.exports={AaveClient,AavePool,AavePoolClient,AaveUtils,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BalanceClientV2,BigNumber,CachingPoolService,ChainParams,DECIMAL_PLACES,DEFAULT_BLOCK_TIME,DEFAULT_MIN_BUDGET,ERC20,EvmClient,EvmRpcAdapter,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,MmOracleClient,ONE,ORDER_MIN_BLOCK_PERIOD,OmniMath,OmniPool,OmniPoolClient,PERBILL_DENOMINATOR,PERMILL_DENOMINATOR,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,TWAP_BLOCK_PERIOD,TWAP_MAX_DURATION,TWAP_MAX_PRICE_IMPACT,TWAP_TX_MULTIPLIER,TradeOrderError,TradeOrderType,TradeRouteBuilder,TradeRouter,TradeScheduler,TradeType,TxBuilderFactory,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,createChain,createSdkContext,findNestedKey,findNestedObj,getFraction,hashPools,isEvmAccount,isEvmAddress,isSs58Address,scale,toBn,toDecimals});
1
+ "use strict";var xt=Object.defineProperty;var Fr=Object.getOwnPropertyDescriptor;var Rr=Object.getOwnPropertyNames;var Er=Object.prototype.hasOwnProperty;var Nr=(u,e)=>{for(var t in e)xt(u,t,{get:e[t],enumerable:!0})},_r=(u,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Rr(e))!Er.call(u,s)&&s!==t&&xt(u,s,{get:()=>e[s],enumerable:!(r=Fr(e,s))||r.enumerable});return u};var Cr=u=>_r(xt({},"__esModule",{value:!0}),u);var ns={};Nr(ns,{AaveClient:()=>le,AavePool:()=>Ne,AavePoolClient:()=>ke,AaveUtils:()=>ee,AssetClient:()=>te,AssetNotFound:()=>Et,BASILISK_PARACHAIN_ID:()=>bs,BalanceClient:()=>W,BalanceClientV2:()=>ue,BigNumber:()=>S.BigNumber,CachingPoolService:()=>ye,ChainParams:()=>me,DECIMAL_PLACES:()=>er,DEFAULT_BLOCK_TIME:()=>Xt,DEFAULT_MIN_BUDGET:()=>Vt,ERC20:()=>G,EvmClient:()=>Ee,EvmRpcAdapter:()=>Re,FarmClient:()=>et,H160:()=>Y,HUB_ASSET_ID:()=>Je,HYDRADX_PARACHAIN_ID:()=>Ps,HYDRADX_SS58_PREFIX:()=>X,INFINITY:()=>kr,LbpMath:()=>V,LbpPool:()=>De,LbpPoolClient:()=>Me,MmOracleClient:()=>pe,ONE:()=>E,ORDER_MIN_BLOCK_PERIOD:()=>Yt,OmniMath:()=>R,OmniPool:()=>Le,OmniPoolClient:()=>He,PERBILL_DENOMINATOR:()=>$t,PERMILL_DENOMINATOR:()=>ne,PolkadotApiClient:()=>H,PoolConfigNotFound:()=>Rt,PoolError:()=>se,PoolFactory:()=>fe,PoolNotFound:()=>Ae,PoolService:()=>he,PoolType:()=>_,ProviderConfigNotFound:()=>Ct,RUNTIME_DECIMALS:()=>Te,RouteNotFound:()=>Fe,Router:()=>be,SYSTEM_ASSET_DECIMALS:()=>jt,SYSTEM_ASSET_ID:()=>N,StableMath:()=>M,StableSwap:()=>ae,StableSwapClient:()=>Ge,StorageConfigNotFound:()=>Nt,SubscriptionNotSupported:()=>_t,TRADEABLE_DEFAULT:()=>Oe,TWAP_BLOCK_PERIOD:()=>Se,TWAP_MAX_DURATION:()=>yt,TWAP_MAX_PRICE_IMPACT:()=>ht,TWAP_TX_MULTIPLIER:()=>rs,TradeOrderError:()=>zt,TradeOrderType:()=>gt,TradeRouteBuilder:()=>z,TradeRouter:()=>ve,TradeScheduler:()=>xe,TradeType:()=>dt,TxBuilderFactory:()=>we,XykMath:()=>J,XykPool:()=>qe,XykPoolClient:()=>Ue,ZERO:()=>x,bnFormatter:()=>$r,bnum:()=>p,calculateBuyFee:()=>Wt,calculateDiffToAvg:()=>ts,calculateDiffToRef:()=>Pe,calculateSellFee:()=>Gt,createChain:()=>kt,createSdkContext:()=>is,findNestedKey:()=>Ce,findNestedObj:()=>Kr,getFraction:()=>ie,hashPools:()=>Jr,isEvmAccount:()=>Qt,isEvmAddress:()=>Jt,isSs58Address:()=>Zt,scale:()=>A,toBn:()=>Dr,toDecimals:()=>O});module.exports=Cr(ns);var Qe=[{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 Bt=[{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 Kt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",wt="0x112b087b60C1a166130d59266363C45F8aa99db0",Tt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",oe=1000000n;var ds=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var le=class{rpcAdapter;constructor(e){this.rpcAdapter=e.getRPCAdapter()}async getBlockTimestamp(){let e=await this.rpcAdapter.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.rpcAdapter.readContract({abi:Bt,address:wt,functionName:"getReservesData",args:[Tt]})}async getUserReservesData(e){return await this.rpcAdapter.readContract({abi:Bt,address:wt,functionName:"getUserReservesData",args:[Tt,e]})}async getUserAccountData(e){return await this.rpcAdapter.readContract({abi:Qe,address:Kt,functionName:"getUserAccountData",args:[e]})}};var Z=require("@polkadot/util-crypto"),ce=require("@polkadot/util"),j=require("buffer");var bs=2090,ne=1e6,$t=1e9,Je="1",Ps=2034,X=63,Te=18,N="0",jt=12,Oe=15;var Ot="ETH\0";function Qt(u){if(!u)return!1;try{let e=(0,Z.decodeAddress)(u,!0),t=j.Buffer.from(Ot);return j.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Jt(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Zt(u){try{let e=(0,ce.isHex)(u)?(0,ce.hexToU8a)(u):(0,Z.decodeAddress)(u);return(0,Z.encodeAddress)(e),!0}catch{return!1}}var Y=class u{static toAccount=e=>{let t=j.Buffer.from(e.slice(2),"hex"),r=j.Buffer.from(Ot);return(0,Z.encodeAddress)(new Uint8Array(j.Buffer.concat([r,t,j.Buffer.alloc(8)])),63)};static fromAccount=e=>{let t=(0,Z.decodeAddress)(e),r=j.Buffer.from(Ot),s=t.slice(r.length,-8);return"0x"+j.Buffer.from(s).toString("hex")};static fromSS58=e=>{let r=(0,Z.decodeAddress)(e).slice(0,20);return(0,ce.u8aToHex)(r)};static fromAny=e=>{if(Jt(e))return e;if(Qt(e))return u.fromAccount(e);if(Zt(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var Ie=require("buffer"),G=class{static fromAssetId(e){let t=Number(e),r=Ie.Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Ie.Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Ie.Buffer.from("0000000000000000000000000000000100000000","hex"),r=Ie.Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};var S=require("bignumber.js"),er=12;S.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:er});var x=p(0),E=p(1),kr=p("Infinity");function A(u,e){let t=new S.BigNumber(e.toString()),r=new S.BigNumber(10).pow(t);return u.times(r).decimalPlaces(4)}function p(u){return new S.BigNumber(u.toString())}function Dr(u,e){let t=p(u);return A(t,e)}function O(u,e){return u.shiftedBy(-1*e).toString()}var Ze=p("1e27"),Mr=p("1.01"),Lr=p("31536000"),tr=4,Hr=-1,ee=class{client;constructor(e){this.client=new le(e)}async getSummary(e){let t=Y.fromAny(e),[r,s,i,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[o]=r,[n,l]=s,[c,m,d,h,g,f]=i,y=p(f).dividedBy(1e18).decimalPlaces(6,S.BigNumber.ROUND_DOWN),v=p(c),P=p(m),B=[];for(let I of n){let T=I.underlyingAsset.toLowerCase(),w=o.find(({underlyingAsset:Ar})=>Ar.toLowerCase()===T);if(!w)throw new Error("Missing pool reserve for "+T);let D=p(I.scaledATokenBalance),U=p(w.liquidityIndex),Ke=p(w.liquidityRate),$e=p(w.availableLiquidity),Pt=p(w.priceInMarketReferenceCurrency),vt=a+6,St=this.calculateLinearInterest(Ke,w.lastUpdateTimestamp,vt),je=U.multipliedBy(St).dividedBy(Ze).decimalPlaces(0,S.BigNumber.ROUND_DOWN),wr=D.multipliedBy(je).dividedBy(Ze).decimalPlaces(0,S.BigNumber.ROUND_DOWN),Tr=p(l!==0&&l===w.eModeCategoryId?w.eModeLiquidationThreshold:w.reserveLiquidationThreshold).div(1e4),Or=w.usageAsCollateralEnabled&&I.usageAsCollateralEnabledOnUser&&p(I.scaledATokenBalance).gt(0),Ir=G.toAssetId(T);B.push({aTokenBalance:wr,availableLiquidity:$e,decimals:Number(w.decimals),isCollateral:Or,priceInRef:Pt,reserveId:Ir,reserveAsset:T,reserveLiquidationThreshold:Tr})}return{healthFactor:y.toNumber(),currentLiquidationThreshold:p(h).dividedBy(10**tr).toNumber(),totalCollateral:v,totalDebt:P,reserves:B}}async hasBorrowPositions(e){let t=Y.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=Y.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,a,o,n,l]=r;return this.calculateHealthFactorFromBalances(p(i),p(s),p(o))}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:a,currentLiquidationThreshold:o}=await this.getSummary(e),n=G.fromAssetId(t),l=a.find(B=>B.reserveAsset===n);if(!l)throw new Error("Missing reserve ctx for "+n);let{decimals:c,isCollateral:m,priceInRef:d,reserveLiquidationThreshold:h}=l,g=A(p(r),c).decimalPlaces(0,S.BigNumber.ROUND_DOWN),f=m?g.multipliedBy(d).dividedBy(p(10).pow(c)).decimalPlaces(0,S.BigNumber.ROUND_DOWN):x,y=s.minus(f);if(y.lte(0))return 0;let v=s.multipliedBy(p(o)).minus(f.multipliedBy(h)).dividedBy(y);return y.multipliedBy(v).dividedBy(i).decimalPlaces(6,S.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:a,currentLiquidationThreshold:o}=await this.getSummary(e),n=G.fromAssetId(t),l=a.find(P=>P.reserveAsset===n);if(!l)throw new Error("Missing reserve ctx for "+n);let{decimals:c,priceInRef:m,reserveLiquidationThreshold:d}=l,g=A(p(r),c).decimalPlaces(0,S.BigNumber.ROUND_DOWN).multipliedBy(m).dividedBy(p(10).pow(c)).decimalPlaces(0,S.BigNumber.ROUND_DOWN),f=s.plus(g);if(f.lte(0))return 0;let y=s.multipliedBy(p(o)).plus(g.multipliedBy(d)).dividedBy(f);return f.multipliedBy(y).dividedBy(i).decimalPlaces(6,S.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSwap(e,t,r,s,i){let{totalDebt:a,reserves:o,healthFactor:n}=await this.getSummary(e),l=G.fromAssetId(r),c=G.fromAssetId(i),m=o.find(w=>w.reserveAsset===l),d=o.find(w=>w.reserveAsset===c);if(!m)throw new Error(`Missing reserve ctx for ${l}`);if(!d)throw new Error(`Missing reserve ctx for ${c}`);let h=A(p(t),m.decimals).decimalPlaces(0,S.BigNumber.ROUND_DOWN),g=A(p(s),d.decimals).decimalPlaces(0,S.BigNumber.ROUND_DOWN),f=h.multipliedBy(m.priceInRef).dividedBy(p(10).pow(m.decimals)).decimalPlaces(0,S.BigNumber.ROUND_DOWN),y=g.multipliedBy(d.priceInRef).dividedBy(p(10).pow(d.decimals)).decimalPlaces(0,S.BigNumber.ROUND_DOWN),v=m.isCollateral?f.multipliedBy(m.reserveLiquidationThreshold):x,I=y.multipliedBy(d.reserveLiquidationThreshold).minus(v).dividedBy(a);return p(n).plus(I).decimalPlaces(6,S.BigNumber.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),a=G.fromAssetId(t),o=s.find(n=>n.reserveAsset===a);if(!o)throw new Error("Missing reserve data for "+a);return this.calculateWithdrawMax(o,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let a of r){let o=this.calculateWithdrawMax(a,t,s);a.reserveId&&(i[a.reserveId]=o)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:a,priceInRef:o,reserveLiquidationThreshold:n,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let d=p(r).minus(Mr);if(d.gt(0)){let g=d.multipliedBy(t).dividedBy(n).decimalPlaces(0,S.BigNumber.ROUND_DOWN).dividedBy(o).multipliedBy(p(10).pow(a)).decimalPlaces(0,S.BigNumber.ROUND_DOWN);c=S.BigNumber.minimum(s,g)}else c=x}return{amount:S.BigNumber.minimum(c,i),decimals:a}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Ze:e.multipliedBy(s).dividedBy(Lr).plus(Ze).decimalPlaces(0,S.BigNumber.ROUND_DOWN)}calculateHealthFactorFromBalances(e,t,r){return e.lte(0)?Hr:t.multipliedBy(r).dividedBy(e).dividedBy(p(10).pow(tr)).decimalPlaces(6,S.BigNumber.ROUND_DOWN).toNumber()}};function rr(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var Ms=require("@galacticcouncil/api-augment/hydradx"),Ls=require("@galacticcouncil/api-augment/basilisk"),H=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");rr(r)&&console.log(e,...t)}};var te=class extends H{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=="0"){let m=this.api.consts.balances.existentialDeposit;return{id:"0",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:a,isSufficient:o,existentialDeposit:n}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:a.toHuman(),isSufficient:o?o.toHuman():!0,location:s?.toJSON(),existentialDeposit:n.toString()}}getBond(e,t,r,s){let[i,a]=s,{assetType:o,isSufficient:n,existentialDeposit:l}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,r),d=a.toNumber(),h=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",h.format(d)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:m,icon:c,type:o.toString(),isSufficient:n.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:d}}getShares(e,t,r,s){let{assets:i}=s,{name:a,symbol:o,assetType:n,isSufficient:l,existentialDeposit:c}=t,d=i.map(f=>f.toString()).map(f=>{let{symbol:y}=this.getToken(f,t,r);return[f,y]}),h=Object.fromEntries(d),g=Object.values(h);return{id:e,name:g.join(", "),symbol:o?.isSome?o.toHuman():a.toHuman(),decimals:18,icon:g.join("/"),type:n.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:h}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),a=r?.find(o=>o.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:a}=s.unwrap();return[r.toString(),{decimals:Number(i.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,i,a,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),n=this.getSupportedAssets(r),l=this.normalizeMetadata(n,o),c=n.map(([{args:[m]},d])=>{let h=d.unwrap(),g=s.get(m.toString()),{assetType:f}=h;switch(f.toString()){case"Bond":let y=a.get(m.toString());return this.getBond(m.toString(),h,l,y);case"StableSwap":let v=i.get(m.toString());return this.getShares(m.toString(),h,l,v);case"External":return this.getExternal(m.toString(),h,t,g);default:return this.getToken(m.toString(),h,l,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 W=class extends H{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==="0"?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 r=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateFreeBalance(r)))}async subscribeSystemBalances(e,t){return this.api.query.system.account.multi(e,r=>{let s=[];r.forEach((i,a)=>{let o=this.calculateFreeBalance(i.data),n=e[a];s.push([n,o])}),t(s)})}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(a=>[e,a]):s.map(({args:[a,o]})=>[a.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,a=>{let o=[];a.forEach((n,l)=>{let c=this.calculateFreeBalance(n),m=i[l][1];o.push([m,c])}),t(o)})}async subscribeTokenBalances(e,t){return this.api.query.tokens.accounts.multi(e,r=>{let s=[];r.forEach((i,a)=>{let o=this.calculateFreeBalance(i),n=e[a];s.push([n,o])}),t(s)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([n,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[n]}])=>n.toString()))(),a=async()=>{let o=await Promise.all(i.map(async n=>[n,await this.getErc20Balance(e,n)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{a()})}async subscribeErc20Balances(e,t){let r=async()=>{let s=await Promise.all(e.map(async i=>{let[a,o]=i;return[i,await this.getErc20Balance(a,o)]}));t(s)};return this.api.rpc.chain.subscribeNewHeads(async()=>{r()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let t=e.free.toString(),r=e.frozen.toString();return(0,S.BigNumber)(t).lt(r)?(0,S.BigNumber)(0):(0,S.BigNumber)(t).minus(r)}};var ue=class extends H{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==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(a=>[e,a]):s.map(({args:[a,o]})=>[a.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,a=>{let o=[];a.forEach((n,l)=>{let c=i[l][1],m=this.calculateBalance(n);o.push([c,m])}),t(o)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([n,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[n]}])=>n.toString()))(),a=async()=>{let o=await Promise.all(i.map(async n=>[n,await this.getErc20Balance(e,n)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{a()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=(0,S.BigNumber)(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),i=t.gte(r)?t.minus(r).toString():"0",a=t.plus(s).toString();return{free:t.toString(),total:a,transferable:i,reserved:s,frozen:r}}};var me=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 It=require("@galacticcouncil/math-liquidity-mining"),sr=require("@polkadot/types"),At=require("@polkadot/util"),Ft=require("@polkadot/util-crypto");var et=class extends H{balanceClient;constructor(e){super(e),this.balanceClient=new W(e)}secondsInYear=new S.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[,a]=s.args,o=i.unwrap().toString(),n=a.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(n)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,n,o)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(n),!1).toString(),g=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(h,g);return{assetId:e,globalFarm:l,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[,a]=s.args,o=i.unwrap().toString(),n=a.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(n)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,n,o)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(n),!0).toString(),g=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(h,g);return{assetId:e,globalFarm:l,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 S.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),o=a.price.n.toString(),n=a.price.d.toString(),l;return Number(t)<Number(r)?l=(0,It.fixed_from_rational)(o,n):l=(0,It.fixed_from_rational)(n,o),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(0,At.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new sr.GenericAccountId32(e,this.padEndU8a((0,At.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:n,priceAdjustment:l,potBalance:c})=>{let m=new S.BigNumber(n.totalSharesZ.toString()),d=n.plannedYieldingPeriods.toString(),h=new S.BigNumber(n.yieldPerPeriod.toString()),g=new S.BigNumber(n.maxRewardPerPeriod.toString()),f=n.blocksPerPeriod.toString(),y=new S.BigNumber(o.multiplier.toString()).shiftedBy(-18),v=this.secondsInYear.div(new S.BigNumber(r).times(f)),P;if(m.isZero())P=h.times(y).times(v);else{let D=this.getGlobalRewardPerPeriod(m,h,g,l);P=this.getPoolYieldPerPeriod(D,y,m,l).times(v)}let B=new S.BigNumber(n.pendingRewards.toString()).plus(n.accumulatedPaidRewards.toString()),I=g.times(d),T=c?B.plus(c):I;return B.div(T).gte(.999)?x:P.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,n)=>o.plus(n),x).toString():void 0}};var Ae=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Rt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Fe=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},_t=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"}};var tt=require("viem"),qr=1e7,Re=class{api;constructor(e){this.api=e}async getBlock(){let e=await this.api.query.ethereum.currentBlock(),{header:t}=e.unwrap(),r=t.timestamp.toBigInt()/1000n,s=t.number.toBigInt();return{timestamp:r,number:s}}readContract=(async e=>{let{abi:t,address:r,functionName:s,args:i}=e,a=(0,tt.encodeFunctionData)({abi:t,functionName:s,args:i}),o=await this.api.call.ethereumRuntimeRPCApi.call("",r,a,0,qr,null,null,null,!1,[]);if(o.isErr)throw console.error(s,o.asErr.toHuman()),new Error("Contract read failure");let{value:n,exitReason:l,usedGas:c}=o.asOk;if(l.isSucceed)return(0,tt.decodeFunctionResult)({abi:t,functionName:s,data:n.toHex()});throw console.log(s,l.toString(),c.toHuman()),new Error("Contract read error")})};var ir=require("viem"),Ur=["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"],kt=u=>{let t=[u.endpoint,...Ur],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return(0,ir.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1})};var Q=require("viem");function nr(u){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return u.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var Ee=class{api;chain;constructor(e){this.api=e,this.chain=kt(this.provider)}get provider(){let{provider:e}=this.api._options;return e}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,Q.createPublicClient)({chain:this.chain,transport:(0,Q.http)()})}getWsProvider(){return(0,Q.createPublicClient)({chain:this.chain,transport:nr(this.provider)})}getSigner(e){return(0,Q.createWalletClient)({account:e,chain:this.chain,transport:(0,Q.custom)(window.ethereum)})}getRPCAdapter(){return new Re(this.api)}};var Dt=[{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 pe=class{rpcAdapter;constructor(e){this.rpcAdapter=e.getRPCAdapter()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.rpcAdapter.readContract({abi:Dt,address:e,functionName:"latestRoundData"}),this.rpcAdapter.readContract({abi:Dt,address:e,functionName:"decimals"}),this.rpcAdapter.getBlock()]),[a,o,n,l]=r,c=i.number-(i.timestamp-l)/BigInt(t),m=Number(c);return{price:o,decimals:s,updatedAt:m<0?0:m}}};var re=(u,e=new Map)=>t=>{let r;return e.has(t)?e.get(t):(e.set(t,r=u(t)),r)};var _=(a=>(a.Aave="Aave",a.LBP="Lbp",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="Xyk",a.HSM="Hsm",a))(_||{}),se=(c=>(c.UnknownError="UnknownError",c.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",c.InsufficientTradingAmount="InsufficientTradingAmount",c.InsufficientCollateral="InsufficientCollateral",c.MaxHoldingExceeded="MaxHoldingExceeded",c.MaxInRatioExceeded="MaxInRatioExceeded",c.MaxOutRatioExceeded="MaxOutRatioExceeded",c.TradeNotAllowed="TradeNotAllowed",c.MaxBuyBackExceeded="MaxBuyBackExceeded",c.MaxBuyPriceExceeded="MaxBuyPriceExceeded",c))(se||{});var Ne=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e)}constructor(e){this.type="Aave",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(n=>[n.id,n])),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 a=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:o,assetInED:x,assetOutED:x}}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=[];return t.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=[];return r.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return A(E,e.decimalsOut)}spotPriceOutGivenIn(e){return A(E,e.decimalsIn)}calculateTradeFee(e,t){return x}};var gr=require("@polkadot/util-crypto"),hr=require("@polkadot/util"),yr=require("viem");var _e=(u,e)=>u===e?0:u==null?e==null?0:-1:e==null?u==null?0:1:typeof u.compare=="function"?u.compare(e):typeof e.compare=="function"?-e.compare(u):u<e?-1:u>e?1:0;var rt=(u,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(u(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var Gr=rt(()=>"illegal argument(s)"),ar=u=>{throw new Gr(u)};var Wr=rt(()=>"index out of bounds"),Mt=u=>{throw new Wr(u)},st=(u,e,t)=>(u<e||u>=t)&&Mt(u);var or=23283064365386963e-26,it=class{float(e=1){return this.int()*or*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*or-.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 nt=class extends it{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 lr=new nt(Math.random);var cr=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var ur=Object.getPrototypeOf({}),at="function",mr="string",de=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===at)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===at)return e.equiv(u)}else return u==e;return typeof u===mr||typeof e===mr?!1:(t=Object.getPrototypeOf(u),(t==null||t===ur)&&(t=Object.getPrototypeOf(e),t==null||t===ur)?Yr(u,e):typeof u!==at&&u.length!==void 0&&typeof e!==at&&e.length!==void 0?zr(u,e):u instanceof Set&&e instanceof Set?Xr(u,e):u instanceof Map&&e instanceof Map?Vr(u,e):u instanceof Date&&e instanceof Date?u.getTime()===e.getTime():u instanceof RegExp&&e instanceof RegExp?u.toString()===e.toString():u!==u&&e!==e)},zr=(u,e,t=de)=>{let r=u.length;if(r===e.length)for(;r-- >0&&t(u[r],e[r]););return r<0},Xr=(u,e,t=de)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),Vr=(u,e,t=de)=>u.size===e.size&&t([...u].sort(),[...e].sort()),Yr=(u,e,t=de)=>{if(Object.keys(u).length!==Object.keys(e).length)return!1;for(let r in u)if(!e.hasOwnProperty(r)||!t(u[r],e[r]))return!1;return!0};var Lt=class{value;constructor(e){this.value=e}deref(){return this.value}};var pr=u=>u instanceof Lt;var ot=class u{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return dr("next",this._head)}reverseIterator(){return dr("prev",this.tail)}clear(){this.release()}compare(e,t=_e){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,a=0;for(;r-- >0&&a===0;)a=t(s.value,i.value),s=s.next,i=i.next;return a}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof u||cr(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(!de(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?.value}insertSorted(e,t){t=t||_e;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?.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!pr(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&&Mt(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*dr(u,e){for(;e;)yield e.value,e=e[u]}var lt=class u extends ot{_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 u(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 u}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):(st(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):(st(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new u,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=a=>({first(){return a.value},next(){return a!==s&&a.next?i(a.next):void 0}});return r?i(r):void 0}shuffle(e,t=lr){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)&&ar("invalid indices: ${from} / ${to}");let i=new u,a=this.nthCell(r);for(;a&&++r<=s;)i.push(a.value),a=a.next;return i}sort(e=_e){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,a=0;for(let n=0;n<t&&(a++,i=i.next,!!i);n++);let o=t;for(;a>0||o>0&&i;){let n;a===0?(n=i,i=i.next,o--):!i||o===0||e(r.value,i.value)<=0?(n=r,r=r.next,a--):(n=i,i=i.next,o--),this._tail?this._tail.next=n:this._head=n,n.prev=this._tail,this._tail=n}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),st(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new u;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 a of r)this.insertBefore(s,a);else for(let a of r)this.push(a);return i}};var ct=class u{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 lt,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 u(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 ge=class u extends ct{constructor(e,t){super(e,{ttl:3600*1e3,autoExtend:!1,...t})}empty(){return new u(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),a=Math.max(0,s-(i?i.value.s:0));return this._size+=a,this.ensureSize()?this.doSetEntry(i,e,t,s,r):this._size-=a,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 a=Date.now()+i;e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,e.value.t=a,this.items.asTail(e)):(this.items.push({k:t,v:r,s,t:a,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 q=class extends W{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;onNewBlockHandler;onEventsHandler;memPoolsCache=new ge(null,{maxlen:1,ttl:3600*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=re(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new pe(t),this.onNewBlockHandler=this.onNewBlock.bind(this),this.onEventsHandler=this.onEvents.bind(this)}onNewBlock(e){}onEvents(e){}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 this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools();let e=this.subscribeBalances(),t=this.subscribeUpdates();this.subs.push(e),this.subs.push(t);let r=this.getPoolType();return this.log(r,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(r,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}async subscribeBalances(){let e=[],t=[],r=[],s=[];for(let o of this.augmentedPools){let{address:n,tokens:l}=o;l.filter(c=>c.id==="0").forEach(()=>{e.push(n)}),l.filter(c=>["Token","StableSwap"].includes(c.type)&&c.id!=="0"&&c.id!==o.id).forEach(c=>{t.push([n,c.id])}),l.filter(c=>c.type==="Erc20").forEach(c=>{r.push([n,c.id])})}let i=o=>{o.forEach(([n,l])=>{let c=this.pools.find(m=>m.address===n);if(c){let m=c.tokens.findIndex(d=>d.id==="0");c.tokens[m].balance=l.toString()}})},a=o=>{o.forEach(([n,l])=>{let[c,m]=n,d=this.pools.find(h=>h.address===c);if(d){let h=d.tokens.findIndex(g=>g.id===m);d.tokens[h].balance=l.toString()}})};if(e.length>0){let o=await this.subscribeSystemBalances(e,i);s.push(o)}if(t.length>0){let o=await this.subscribeTokenBalances(t,a);s.push(o)}if(r.length>0){let o=await this.subscribeErc20Balances(r,a);s.push(o)}return()=>{for(let o of s)try{o()}catch(n){console.warn("Balance unsub failed",n)}}}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t()).catch(t=>console.warn("Unsub failed",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}};function Ce(u,e){let t=[];return JSON.stringify(u,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Kr(u,e,t){let r;return JSON.stringify(u,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var $r=(u,e)=>typeof e=="bigint"?e.toString():e;var jr=["Supply","Withdraw","Repay","Borrow"],ke=class extends q{getPoolType(){return"Aave"}getPoolId(e,t){let r="aave:"+e+"/"+t;return(0,gr.encodeAddress)((0,hr.stringToU8a)(r.padEnd(32,"\0")),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}getReserveH160Id(e){return e.type==="Erc20"?Ce(e.location,"accountKey20").accountKey20.key:G.fromAssetId(e.id)}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,r){return{}}onEvents(e){e.forEach(t=>{let{event:r}=t,s=`${r.section}:${r.method}`;if(s==="router:Executed"){let[i,a]=r.data.toJSON();this.pools.filter(o=>o.tokens.some(n=>n.id===i.toString()||n.id===a.toString())).forEach(o=>{this.log(`Sync AAVE via [router:Executed] :: ${i}:${a}`),this.updatePoolState(o)})}if(s==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:a,args:o}=(0,yr.decodeEventLog)({abi:Qe,topics:i.topics,data:i.data});if(jr.includes(a)){let n=o.reserve.toLowerCase();this.pools.filter(l=>{let[c]=l.tokens;return this.getReserveH160Id(c).toLowerCase()===n}).forEach(l=>{this.log(`Sync AAVE via [evm:Log] :: ${a} ${n}`),this.updatePoolState(l)})}}catch{}}})}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return()=>{}}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(a=>{let o=a.id===t.id?s.toString():i.toString();return{...a,balance:o}})}};var K=require("@galacticcouncil/math-lbp"),V=class{static getSpotPrice(e,t,r,s,i){return(0,K.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,K.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,K.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,K.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,K.calculate_pool_trade_fee)(e,t,r)}};var b=class u{static toPct(e){let[t,r]=e;return u.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return u.safeDivide(t,r)}static fromPermill(e){return[e,1e6]}static fromPerbill(e){return[e,1e9]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,r=12){let s=10**r;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};var De=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new u(e)}constructor(e){this.type="Lbp",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.fee=e.fee,this.repayFeeApply=e.repayFeeApply}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(n=>[n.id,n])),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 a=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,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 a=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let o=this.calculateTradeFee(t,r),n=b.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(o),c=this.calculateInGivenOut(e,l),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:n,errors:i}}else{let o=this.calculateInGivenOut(e,t),n=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(n)&&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 a=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let o=this.calculateOutGivenIn(e,t),n=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(o,r),l=b.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=o.minus(n),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=V.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?x:s}calculateOutGivenIn(e,t){let r=V.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?x:s}spotPriceInGivenOut(e){let t=V.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),A(E,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=V.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),A(E,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=V.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var Me=class extends q{MAX_FINAL_WEIGHT=A(p(100),6);poolsData=new Map([]);getPoolType(){return"Lbp"}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toNumber(),t=this.api.consts.lbp.maxOutRatio.toNumber(),r=this.api.consts.lbp.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getPoolDelta(e,t,r){let{start:s,end:i,assets:a,initialWeight:o,finalWeight:n,repayTarget:l,feeCollector:c}=t,m=V.calculateLinearWeights(s.toString(),i.toString(),o.toString(),n.toString(),r),[d,h]=a,g=d.toString(),f=p(m),y=h.toString(),v=this.MAX_FINAL_WEIGHT.minus(p(f)),[P,B,I]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,y)]);return{repayFeeApply:P,tokens:[{id:g,weight:f,balance:B.toString()},{id:y,weight:v,balance:I.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>=r&&t<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}}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,a])=>this.isActivePool(a.unwrap(),r.toNumber())).map(async([{args:[i]},a])=>{let o=a.unwrap(),n=i.toString(),l=await this.getPoolDelta(n,o,r.toString());this.poolsData.set(i.toString(),o);let[c,m]=o.fee;return{address:n,type:"Lbp",fee:b.fromRate(c.toNumber(),m.toNumber()),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t,r){let s=this.pools.find(i=>i.address===r);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getRepayFee(){let[e,t]=this.api.consts.lbp.repayFee;return b.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return this.api.query.parachainSystem.validationData(async e=>{let{relayParentNumber:t}=e.unwrap();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s)if(this.isActivePool(s,t.toNumber())){let a=await this.getPoolDelta(r.address,s,t.toString());Object.assign(r,a)}else{let a=this.pools.findIndex(o=>o.address==r.address);this.pools.splice(a,1)}})})}};var F=require("@galacticcouncil/math-omnipool");var R=class{static calculateSpotPrice(e,t,r,s){return(0,F.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,F.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,a,o,n,l){return(0,F.calculate_in_given_out)(e,t,r,s,i,a,o,n,l)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,F.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,a,o,n,l){return(0,F.calculate_out_given_in)(e,t,r,s,i,a,o,n,l)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,F.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculateShares(e,t,r,s){return(0,F.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,a,o,n){return(0,F.calculate_liquidity_out)(e,t,r,s,i,a,o,n)}static calculateLiquidityLRNAOut(e,t,r,s,i,a,o,n){return(0,F.calculate_liquidity_lrna_out)(e,t,r,s,i,a,o,n)}static calculateCapDifference(e,t,r,s){let i=(0,S.BigNumber)(t),a=(0,S.BigNumber)(e),o=(0,S.BigNumber)(s),l=(0,S.BigNumber)(r).shiftedBy(-18);if(i.div(o).lt(l)){let m=l.times(o).minus(i).times(a),d=i.times((0,S.BigNumber)(1).minus(l));return m.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return(0,F.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,F.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,F.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,F.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,F.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,r,s,i,a,o,n,l,c,m){return(0,F.recalculate_asset_fee)(e,t,r,s,i,a,o,n,l,c,m)}static recalculateProtocolFee(e,t,r,s,i,a,o,n,l,c,m){return(0,F.recalculate_protocol_fee)(e,t,r,s,i,a,o,n,l,c,m)}static verifyAssetCap(e,t,r,s){return(0,F.verify_asset_cap)(e,t,r,s)}};var Le=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new u(e)}constructor(e){this.type="Omnipool",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.hubAssetId=e.hubAssetId}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 a=p(s.balance),o=p(i.balance),n=p(s.existentialDeposit),l=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:a,balanceOut:o,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:n,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),o=s===x?x:a.div(s).multipliedBy(100).decimalPlaces(4),n=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);(!l||!c)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&n.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&n.push("MaxOutRatioExceeded");let d=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(d)&&n.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:n}}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(4),n=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);(!l||!c)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&n.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&n.push("MaxInRatioExceeded");let d=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(d)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:n}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=R.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?b.toRaw(r.assetFee).toString():x.toString(),r?b.toRaw(r.protocolFee).toString():x.toString()),i=p(s);return i.isNegative()?x:i}calculateLrnaInGivenOut(e,t,r){let s=R.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?b.toRaw(r.assetFee).toString():x.toString()),i=p(s);return i.isNegative()?x:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=R.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?b.toRaw(r.assetFee).toString():x.toString(),r?b.toRaw(r.protocolFee).toString():x.toString()),i=p(s);return i.isNegative()?x:i}calculateOutGivenLrnaIn(e,t,r){let s=R.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?b.toRaw(r.assetFee).toString():x.toString()),i=p(s);return i.isNegative()?x:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=R.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=R.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=R.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=R.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var Pr=require("@polkadot/util-crypto"),vr=require("@polkadot/util");var fr="omnipool",br="Short",He=class extends q{dynamicFees=new Map;dynamicFeesConfiguration=new Map;oracles=new Map;memQueryCache=new ge(null,{ttl:6*1e3});memOracleQuery=re(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(fr,t,br)},this.memQueryCache);memFeesQuery=re(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);memFeesConfigurationQuery=re(e=>this.api.query.dynamicFees.assetFeeConfiguration(e),this.memQueryCache);getPoolType(){return"Omnipool"}getPoolId(){return(0,Pr.encodeAddress)((0,vr.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getOracleKey(e){return e==="0"?["0","1"]:["1",e]}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toNumber(),t=this.api.consts.omnipool.maxOutRatio.toNumber(),r=this.api.consts.omnipool.minimumTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getDynamicFees(e){return this.dynamicFees.has(e)?this.dynamicFees.get(e):this.memFeesQuery(e)}async getDynamicFeesConfiguration(e){return this.dynamicFeesConfiguration.has(e)?this.dynamicFeesConfiguration.get(e):this.memFeesConfigurationQuery(e)}async getOraclePrice(e){let r=this.getOracleKey(e).join(":");return this.oracles.has(r)?this.oracles.get(r):this.memOracleQuery(r)}isSupported(){return this.api.query.omnipool!==void 0}isAssetConfigSupported(){return this.api.query.dynamicFees.assetFeeConfiguration!==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)]),a=r.map(async([{args:[n]},l])=>{let{hubReserve:c,shares:m,tradable:d,cap:h,protocolShares:g}=l.unwrap(),f=await this.getBalance(t,n.toString());return{id:n.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:d.bits.toNumber(),balance:f.toString(),cap:p(h.toString()),protocolShares:p(g.toString())}}),o=await Promise.all(a);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,r){let s=t.assetOut,i=t.assetIn,a;if(this.isAssetConfigSupported()&&(a=await this.getDynamicFeesConfiguration(s).then(P=>P.unwrapOr(null))),a?.isFixed){let P=a.asFixed.assetFee.toNumber(),B=a.asFixed.protocolFee.toNumber();return{assetFee:b.fromPermill(P),protocolFee:b.fromPermill(B)}}let[o,n,l]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[c,m,d]=this.getAssetFee(t,e,o,n,a?.isDynamic?a.asDynamic.assetFeeParams:void 0),[h,g,f]=i==="1"?[0,0,0]:this.getProtocolFee(t,e,o,l,a?.isDynamic?a.asDynamic.protocolFeeParams:void 0),y=c+h,v=d+f;return{assetFee:b.fromPermill(m),protocolFee:b.fromPermill(g),min:b.fromPermill(y),max:b.fromPermill(v)}}getAssetFee(e,t,r,s,i){let{assetOut:a,balanceOut:o}=e,{minFee:n,maxFee:l,decay:c,amplification:m}=i||this.api.consts.dynamicFees.assetFeeParameters,d=b.fromPermill(n.toNumber()),h=b.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[n.toNumber(),n.toNumber(),l.toNumber()];let[g]=s.unwrap(),{assetFee:f,timestamp:y}=r.unwrap(),v=Math.max(1,t-y.toNumber()),P=g.volume.bIn.toString(),B=g.volume.bOut.toString(),I=g.liquidity.b.toString();a==="0"&&(P=g.volume.aIn.toString(),B=g.volume.aOut.toString(),I=g.liquidity.a.toString());let T=b.fromPermill(f.toNumber()),w=R.recalculateAssetFee(P,B,I,"9",o.toString(),b.toRaw(T).toString(),v.toString(),b.toRaw(d).toString(),b.toRaw(h).toString(),c.toString(),m.toString());return[n.toNumber(),Number(w)*1e6,l.toNumber()]}getProtocolFee(e,t,r,s,i){let{assetIn:a,balanceIn:o}=e,{minFee:n,maxFee:l,decay:c,amplification:m}=i||this.api.consts.dynamicFees.protocolFeeParameters,d=b.fromPermill(n.toNumber()),h=b.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[n.toNumber(),n.toNumber(),l.toNumber()];let[g]=s.unwrap(),{protocolFee:f,timestamp:y}=r.unwrap(),v=Math.max(1,t-y.toNumber()),P=g.volume.bIn.toString(),B=g.volume.bOut.toString(),I=g.liquidity.b.toString();a==="0"&&(P=g.volume.aIn.toString(),B=g.volume.aOut.toString(),I=g.liquidity.a.toString());let T=b.fromPermill(f.toNumber()),w=R.recalculateProtocolFee(P,B,I,"9",o.toString(),b.toRaw(T).toString(),v.toString(),b.toRaw(d).toString(),b.toRaw(h).toString(),c.toString(),m.toString());return[n.toNumber(),Number(w)*1e6,l.toNumber()]}async subscribeUpdates(){let[e]=this.pools,t=e.tokens.map(n=>n.id),r=[],s=await this.api.query.omnipool.assets.multi(t,n=>{e.tokens=n.map((l,c)=>{let m=e.tokens[c];if(l.isNone)return m;let d=l.unwrap();return this.updateTokenState(m,d)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,n=>{n.forEach((l,c)=>{let m=t[c];this.dynamicFees.set(m,l)})});if(r.push(i),this.isAssetConfigSupported()){let n=await this.api.query.dynamicFees.assetFeeConfiguration.multi(t,l=>{l.forEach((c,m)=>{let d=t[m];this.dynamicFeesConfiguration.set(d,c)})});r.push(n)}let a=t.map(n=>{let l=this.getOracleKey(n);return[fr,l,br]}),o=await this.api.query.emaOracle.oracles.multi(a,n=>{n.forEach(async(l,c)=>{let m=a[c],[d,h,g]=m;this.oracles.set(h.join(":"),l)})});return r.push(o),()=>{for(let n of r)try{n()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:a,protocolShares:o}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(a.toString()),protocolShares:p(o.toString()),tradeable:i.bits.toNumber()}}};var C=require("@galacticcouncil/math-xyk"),J=class{static getSpotPrice(e,t,r){return(0,C.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,C.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,C.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,C.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,C.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,C.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,C.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,C.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,C.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,C.calculate_liquidity_out_asset_b)(e,t,r,s)}};var qe=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e)}constructor(e){this.type="Xyk",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}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 a=p(s.balance),o=p(i.balance),n=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:o,assetInED:n,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),a=b.toPct(r.exchangeFee),o=s.plus(i),n=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&n.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&n.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&n.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:s,amountOut:t,feePct:a,errors:n}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),a=b.toPct(r.exchangeFee),o=s.minus(i),n=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&n.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&n.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:o,feePct:a,errors:n}}calculateInGivenOut(e,t){let r=J.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?x:s}calculateOutGivenIn(e,t){let r=J.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?x:s}spotPriceInGivenOut(e){let t=J.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=A(E,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=J.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=A(E,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=J.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var Ue=class extends q{getPoolType(){return"Xyk"}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toNumber(),t=this.api.consts.xyk.maxOutRatio.toNumber(),r=this.api.consts.xyk.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}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(),[a,o]=s.unwrap(),[n,l]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,o.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:n.toString()},{id:o.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t,r){return{exchangeFee:this.getExchangeFee()}}getExchangeFee(){let[e,t]=this.api.consts.xyk.getExchangeFee;return b.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return()=>{}}};var k=require("@galacticcouncil/math-stableswap"),M=class{static getPoolAddress(e){return(0,k.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,k.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,a,o){return(0,k.calculate_in_given_out)(e,t,r,s,i,a,o)}static calculateAddOneAsset(e,t,r,s,i,a,o){return(0,k.calculate_add_one_asset)(e,t,r,s,i,a,o)}static calculateSharesForAmount(e,t,r,s,i,a,o){return(0,k.calculate_shares_for_amount)(e,t,r,s,i,a,o)}static calculateOutGivenIn(e,t,r,s,i,a,o){return(0,k.calculate_out_given_in)(e,t,r,s,i,a,o)}static calculateLiquidityOutOneAsset(e,t,r,s,i,a,o){return(0,k.calculate_liquidity_out_one_asset)(e,t,r,s,i,a,o)}static calculateShares(e,t,r,s,i,a){return(0,k.calculate_shares)(e,t,r,s,i,a)}static calculateSpotPriceWithFee(e,t,r,s,i,a,o,n){return(0,k.calculate_spot_price_with_fee)(e,t,r,s,i,a,o,n)}static recalculatePegs(e,t,r,s,i){let a=(0,k.recalculate_peg)(e,t,r,s,i);return JSON.parse(a)}};var ae=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new u(e)}constructor(e){this.type="Stableswap",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.amplification=e.amplification,this.id=e.id,this.fee=e.fee,this.totalIssuance=e.totalIssuance,this.pegs=e.pegs,this.pegsFee=e.pegsFee}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 a=p(s.balance),o=p(i.balance),n=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:n,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),o=s===x?x:a.div(s).multipliedBy(100).decimalPlaces(4),n=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);return(!l||!c)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&n.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:n}}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(4),n=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);return(!l||!c)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&n.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:n}}calculateIn(e,t,r){let s=M.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?b.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=p(s);return i.isNegative()?x:i}calculateAddOneAsset(e,t,r){let s=M.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?b.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=p(s);return i.isNegative()?x:i}calculateSharesForAmount(e,t,r){let s=M.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?b.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=p(s);return i.isNegative()?x: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=M.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=A(E,e.decimalsIn-e.decimalsOut);return p(t).div(s).decimalPlaces(0,1)}let r=A(E,18-e.decimalsIn);return p(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=M.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?b.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=p(s);return i.isNegative()?x:i}calculateWithdrawOneAsset(e,t,r){let s=M.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?b.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=p(s);return i.isNegative()?x:i}calculateShares(e,t,r){let s=M.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?b.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=p(s);return i.isNegative()?x: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=M.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=A(E,e.decimalsOut-e.decimalsIn);return p(t).div(s).decimalPlaces(0,1)}let r=A(E,18-e.decimalsOut);return p(t).div(r).decimalPlaces(0,1)}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 ut=require("@polkadot/util-crypto");var Ge=class extends q{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=Number(e),r=M.getPoolAddress(t);return(0,ut.encodeAddress)((0,ut.blake2AsHex)(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toNumber()}}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:a,finalBlock:o}=t,n=M.calculateAmplification(s.toString(),i.toString(),a.toString(),o.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:n,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async a=>{let[o,n]=await Promise.all([this.api.query.stableswap.assetTradability(t,a.toString()),this.getBalance(e,a.toString())]);return{id:a.toString(),tradeable:o.bits.toNumber(),balance:n.toString()}});return Promise.all(i)}isSupported(){return this.api.query.stableswap!==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:[a]},o])=>{try{let n=o.unwrap(),l=a.toString(),c=this.getPoolAddress(l),[m,d,h]=await Promise.all([this.getPoolDelta(l,n,r.toString()),this.getPoolTokens(c,l,n),this.getPoolPegs(l,n,r.toString())]);return d.push({id:l,tradeable:15,balance:m.totalIssuance}),this.poolsData.set(c,n),{address:c,id:l,type:"Stableswap",fee:b.fromPermill(n.fee.toNumber()),tokens:d,...m,...h,...this.getPoolLimits()}}catch(n){return console.warn(`Skipping pool ${a.toString()}
2
+ `,String(n)),null}});return(await Promise.all(s)).filter(a=>a!==null)}async getPoolFees(e,t,r){return{fee:this.pools.find(i=>i.address===r).pegsFee}}async getPoolPegs(e,t,r){let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getDefaultPegs(t);let i=s.unwrap(),a=await this.getLatestPegs(t,i,r),o=this.getRecentPegs(i),n=b.fromPermill(t.fee.toNumber()),l=b.fromPerbill(i.maxPegUpdate.toNumber()),[c,m]=M.recalculatePegs(JSON.stringify(o),JSON.stringify(a),r,b.toRaw(l).toString(),b.toRaw(n).toString()),d=Number(c)*1e6;return{pegsFee:b.fromPermill(d),pegs:m}}getDefaultPegs(e){let t=e.fee,r=M.defaultPegs(e.assets.length);return{pegsFee:b.fromPermill(t.toNumber()),pegs:r}}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,n])=>n.toString()),a=s.map(async(o,n)=>{if(o.isOracle){let[l,c,m]=o.asOracle,d=[m.toString(),i[n]].map(P=>Number(P)).sort((P,B)=>P-B),h=await this.api.query.emaOracle.oracles(l,d,c),[{price:g,updatedAt:f}]=h.unwrap(),y=g.n.toString(),v=g.d.toString();return m.toString()===d[0].toString()?[[y,v],f.toString()]:[[v,y],f.toString()]}else if(o.isMmOracle){let l=o.asMmOracle,{price:c,decimals:m,updatedAt:d}=await this.mmOracle.getData(l.toString()),h=10**m;return[[c.toString(),h.toString()],d.toString()]}else{if(o.isValue)return[o.asValue.map(l=>l.toString()),r];throw Error(o.type+" is not supported")}});return Promise.all(a)}async subscribeUpdates(){return this.api.query.system.number(async e=>{let t=e.toString();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s){let[i,a]=await Promise.all([this.getPoolDelta(r.id,s,t),this.getPoolPegs(r.id,s,t)]),o=r.tokens.map(n=>n.id===r.id?{...n,balance:i.totalIssuance}:n);Object.assign(r,{tokens:o},i,a)}})})}};var L=require("@galacticcouncil/math-hsm"),$=class{static calculateCollateralInGivenHollarOut(e,t,r){return(0,L.calculate_collateral_in_given_hollar_out)(e,t,r)}static calculateCollateralOutGivenHollarIn(e,t,r){return(0,L.calculate_collateral_out_given_hollar_in)(e,t,r)}static calculateHollarOutGivenCollateralIn(e,t,r){return(0,L.calculate_hollar_out_given_collateral_in)(e,t,r)}static calculateHollarInGivenCollateralOut(e,t,r){return(0,L.calculate_hollar_in_given_collateral_out)(e,t,r)}static calculateImbalance(e,t,r){return(0,L.calculate_imbalance)(e,t,r)}static calculateBuybackLimit(e,t){return(0,L.calculate_buyback_limit)(e,t)}static calculateBuybackPriceWithFee(e,t,r){return(0,L.calculate_buyback_price_with_fee)(e,t,r)}static calculateMaxPrice(e,t){return(0,L.calculate_max_price)(e,t)}};var mt=class u extends ae{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new u(e)}constructor(e){super(e),this.type="Hsm",this.hsmAddress=e.hsmAddress,this.hsmMintCapacity=e.hsmMintCapacity,this.hollarId=e.hollarId,this.hollarH160=e.hollarH160,this.collateralId=e.collateralId,this.collateralBalance=e.collateralBalance,this.maxBuyPriceCoefficient=e.maxBuyPriceCoefficient,this.maxInHolding=e.maxInHolding,this.purchaseFee=e.purchaseFee,this.buyBackFee=e.buyBackFee,this.buyBackRate=e.buyBackRate}validatePair(e,t){return!0}parsePair(e,t){return super.parsePair(e,t)}validateTradeHollarIn(e,t,r,s){let i=this.calculateBuybackLimit(e);t.gt(i)&&s.push("MaxBuyBackExceeded");let a=this.calculateBuyPrice(e,t,r),o=this.calculateMaxPrice(e);return a.gt(o)&&s.push("MaxBuyPriceExceeded"),r.gt(this.collateralBalance)&&s.push("InsufficientCollateral"),s}validateTradeHollarOut(e,t,r){return this.collateralBalance.plus(e).gt(this.maxInHolding)&&r.push("MaxHoldingExceeded"),t.gt(this.hsmMintCapacity)&&r.push("FacilitatorCapacityExceeded"),r}validateTradeConstraints(e,t,r){let s=[];return e.assetIn===this.hollarId?this.validateTradeHollarIn(e,t,r,s):this.validateTradeHollarOut(t,r,s)}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=this.validateTradeConstraints(e,r,t);return{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=this.validateTradeConstraints(e,t,r);return{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(e,t){let r=super.calculateInGivenOut(e,t,{fee:this.fee}),s=$.calculateHollarInGivenCollateralOut(t.toFixed(0),r.toFixed(0),b.toRaw(this.buyBackFee).toString());return p(s)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),r=$.calculateCollateralInGivenHollarOut(e.toFixed(0),JSON.stringify(t),b.toRaw(this.purchaseFee).toString());return p(r)}calculateInGivenOut(e,t){return e.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(t):this.calculateHollarInGivenCollateralOut(e,t)}calculateCollateralOutGivenHollarIn(e,t){let r=super.calculateOutGivenIn(e,t,{fee:this.fee}),s=$.calculateCollateralOutGivenHollarIn(t.toFixed(0),r.toFixed(0),b.toRaw(this.buyBackFee).toString());return p(s)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),r=$.calculateHollarOutGivenCollateralIn(e.toFixed(0),JSON.stringify(t),b.toRaw(this.purchaseFee).toString());return p(r)}calculateOutGivenIn(e,t){return e.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(e,t):this.calculateHollarOutGivenCollateralIn(t)}calculateImbalance(e){let t=this.getCollateralPeg(),r=$.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return p(r)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),r=$.calculateBuybackLimit(t.toString(),b.toRaw(this.buyBackRate).toString());return p(r)}calculateBuyPrice(e,t,r){let s=t.dividedBy(p(10).pow(e.decimalsIn));return r.dividedBy(p(10).pow(e.decimalsOut)).dividedBy(s)}calculateMaxPrice(e){let t=this.getCollateralPeg(),r=$.calculateMaxPrice(JSON.stringify(t),this.maxBuyPriceCoefficient.toFixed(0)),[s,i]=JSON.parse(r);return p(s).div(p(i)).shiftedBy(-1*e.decimalsOut)}spotPriceInGivenOut(e){let t=A(E,e.decimalsOut);return this.calculateInGivenOut(e,t)}spotPriceOutGivenIn(e){let t=A(E,e.decimalsIn);return this.calculateOutGivenIn(e,t)}getCollateralPeg(){let e=this.tokens.findIndex(s=>s.id!==this.hollarId),t=this.pegs[e],r=this.tokens[e].decimals;return this.isDefaultPeg(t)?[A(E,18).toString(),A(E,r).toString()]:t}isDefaultPeg(e){let[t,r]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&r==="1"}};var Ht=require("@polkadot/util"),qt=require("@polkadot/util-crypto"),Sr=require("viem");var We=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var ze=class{rpcAdapter;constructor(e){this.rpcAdapter=e.getRPCAdapter()}async getFacilitatorCapacity(e,t){let[r,s]=await this.rpcAdapter.readContract({abi:We,address:e,functionName:"getFacilitatorBucket",args:[t]});return r-s}};var Qr=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],pt=class extends q{stableClient;ghoTokenClient;constructor(e,t,r){super(e,t),this.stableClient=r,this.ghoTokenClient=new ze(t)}getPoolType(){return"Hsm"}getPoolId(e){let t="hsm:"+e;return(0,qt.encodeAddress)((0,Ht.stringToU8a)(t.padEnd(32,"\0")),63)}getFacilitatorAddress(){return(0,qt.encodeAddress)((0,Ht.stringToU8a)("modlpy/hsmod".padEnd(32,"\0")),63)}getHollarAddress(e){return Ce(e,"accountKey20").accountKey20.key}isSupported(){return this.api.query.hsm!==void 0}async loadPools(){let e=this.api.consts.hsm.hollarId.toString(),[t,r,s]=await Promise.all([this.api.query.assetRegistry.assetLocations(e),this.api.query.hsm.collaterals.entries(),this.stableClient.getPoolsMem()]);if(r.length===0)return[];let i=this.getFacilitatorAddress(),a=Y.fromAny(i),o=this.getHollarAddress(t.unwrap()),n=await this.ghoTokenClient.getFacilitatorCapacity(o,a),l=r.map(async([{args:[m]},d])=>{let h=d.unwrap(),g=m.toString(),{poolId:f,maxBuyPriceCoefficient:y,maxInHolding:v,purchaseFee:P,buyBackFee:B,buybackRate:I}=h,T=s.find(w=>w.id===f.toString());if(T){let w=this.getPoolId(f.toString()),D=await this.getBalance(i,g);return{...T,address:w,type:"Hsm",tokens:T.tokens.filter(U=>U.id!==f.toString()),hsmAddress:i,hsmMintCapacity:p(n),hollarId:e,hollarH160:o,collateralId:g,collateralBalance:D,maxBuyPriceCoefficient:p(y.toString()),maxInHolding:p(v.unwrap().toString()),purchaseFee:b.fromPermill(P.toNumber()),buyBackFee:b.fromPermill(B.toNumber()),buyBackRate:b.fromPerbill(I.toNumber())}}});return(await Promise.all(l)).filter(m=>m!==null)}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(async t=>{let{event:r}=t;if(`${r.section}:${r.method}`==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:a,args:o}=(0,Sr.decodeEventLog)({abi:We,topics:i.topics,data:i.data}),[n]=this.pools,{hsmAddress:l,hollarH160:c}=n,m=Y.fromAny(l),d=m.toLowerCase()===o.facilitatorAddress.toLowerCase();if(Qr.includes(a)&&d){let h=await this.ghoTokenClient.getFacilitatorCapacity(c,m);this.log(`Sync HSM facilitator via [evm:Log] :: ${a} ${h}`),this.pools.forEach(g=>{Object.assign(g,{hsmMintCapacity:h})})}}catch{}}})}async subscribeBalances(){let e=[],t=[],r=[];for(let i of this.pools){let{tokens:a,hsmAddress:o,collateralId:n}=i;a.find(c=>c.id===n).type==="Erc20"?t.push([o,n]):e.push([o,n])}let s=i=>{i.forEach(([a,o])=>{let[n,l]=a,c=this.pools.find(m=>m.tokens.some(d=>d.id===l));c&&Object.assign(c,{collateralBalance:o})})};if(e.length>0){let i=await this.subscribeTokenBalances(e,s);r.push(i)}if(t.length>0){let i=await this.subscribeErc20Balances(t,s);r.push(i)}return()=>{for(let i of r)try{i()}catch(a){console.warn("Balance unsub failed",a)}}}async subscribeUpdates(){return()=>{}}};var he=class extends H{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;hsmClient;clients=[];onChainAssets=[];block=0;blockHandlers=[];eventHandlers=[];disconnectSubscribeNewHeads=null;disconnectSubscribeEvents=null;memRegistry=re(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new te(this.api),this.aaveClient=new ke(this.api,t),this.xykClient=new Ue(this.api,t),this.omniClient=new He(this.api,t),this.lbpClient=new Me(this.api,t),this.stableClient=new Ge(this.api,t),this.hsmClient=new pt(this.api,t,this.stableClient),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient,this.hsmClient],this.blockHandlers=this.clients.map(r=>r.onNewBlockHandler),this.eventHandlers=this.clients.map(r=>r.onEventsHandler),this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r}),this.api.query.system.events(r=>{this.onEvents(r)}).then(r=>{this.disconnectSubscribeEvents=r})}onNewBlock(e){this.block=e;for(let t of this.blockHandlers)try{t(e)}catch(r){this.log("onNewBlock handler error",r)}}onEvents(e){for(let t of this.eventHandlers)try{t(e)}catch(r){this.log("onEvents handler error",r)}}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={}){this.isRegistrySynced||await this.memRegistry(1);let{includeOnly:t=[],exclude:r=[]}=e;return t.length>0?this.getFilteredPools(s=>t.includes(s.getPoolType())):r.length>0?this.getFilteredPools(s=>!r.includes(s.getPoolType())):this.getFilteredPools(s=>s.isSupported())}async getFilteredPools(e){let t=this.clients.filter(e);return(await Promise.all(t.map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe(),this.hsmClient.unsubscribe(),this.disconnectSubscribeNewHeads?.(),this.disconnectSubscribeEvents?.()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(this.block,e,t.address);case"Xyk":return this.xykClient.getPoolFees(this.block,e,t.address);case"Omnipool":return this.omniClient.getPoolFees(this.block,e,t.address);case"Lbp":return this.lbpClient.getPoolFees(this.block,e,t.address);case"Stableswap":return this.stableClient.getPoolFees(this.block,e,t.address);case"Hsm":return this.hsmClient.getPoolFees(this.block,e,t.address);default:throw new Ae(t.type)}}};var ye=class extends he{feeCache=new Map;constructor(e,t){super(e,t)}onNewBlock(e){super.onNewBlock(e),this.feeCache.clear()}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);let s=super.getPoolFees(e,t);return this.feeCache.set(r,s),s}async destroy(){this.feeCache.clear(),super.destroy()}};var fe=class{static get(e){switch(e.type){case"Aave":return Ne.fromPool(e);case"Xyk":return qe.fromPool(e);case"Omnipool":return Le.fromPool(e);case"Lbp":return De.fromPool(e);case"Stableswap":return ae.fromPool(e);case"Hsm":return mt.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var xr=require("@noble/hashes/sha2"),Br=require("@noble/hashes/utils");function Jr(u){let e=u.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=(0,xr.sha256)(t);return(0,Br.bytesToHex)(r)}var Xe=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 Zr=10,Ve=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 Xe,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let o=i.dequeue();if(!o||o.length>Zr)continue;let n=o[o.length-1];(r===null||n[0]===r)&&s.push(o),e.get(n[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let m=[...o];m.push(c),i.enqueue(m)}})}return s}findShortestPaths(e,t,r){let s=[],i=new Xe,a=[];a.push([t,""]),i.enqueue(a);let o=1/0;for(;i.size()>0;){let n=i.dequeue();if(!n)continue;let l=n[n.length-1];if(l[0]===r){n.length<o?(o=n.length,s.length=0,s.push(n)):n.length===o&&s.push(n);continue}let c=e.get(l[0]);for(let m of c??[])this.isNotVisited(m,n)&&i.enqueue([...n,m])}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,a]of t){let o=parseInt(i),n=parseInt(a);r.get(o)?.push([n,s])}return r}};function Ut(u){let e={};for(let t of u){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 a=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(a)}}}return e}var Ye=class{getProposals(e,t,r){let s=r.filter(P=>P.type==="Xyk"),i=r.filter(P=>P.type!=="Xyk"),a=parseInt(e),o=parseInt(t),n=new Set(i.map(P=>P.tokens).flat().map(P=>P.id)),l=n.has(e),c=n.has(t),m=new Ve,d=P=>{let B=Ut(P),I=Object.keys(B),T=I.flatMap(w=>B[w]);return m.buildAndPopulateGraph(I,T)};if(!l&&!c){let P=s.filter(T=>T.tokens.find(w=>w.id===e)||T.tokens.find(w=>w.id===t)),B=d(P),I=m.findPaths(B,a,o);return this.parsePaths(I)}if(l&&c){let P=d(i),B=m.findPaths(P,a,o);return this.parsePaths(B)}let h=l?t:e,g=s.filter(P=>P.tokens.some(B=>B.id===h));if(g.length===0)return[];let f=[...i,...g],y=d(f),v=m.findPaths(y,a,o);return this.parsePaths(v)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let a=r[i],o=r[i+1];if(o==null)break;s.push(this.toEdge(a,o))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var be=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new Ye,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}buildRouteKey(e,t,r){return`${e}->${t}::${r.length}`}async getPools(){return this.poolService.getPools(this.routerOptions)}async getAllAssets(){let e=await this.getPools(),t=this.getAssets(e);return[...new Map(t).values()]}async getRouteableAssets(e){let t=await this.getAllAssets();return(await Promise.all(t.map(s=>s.id).filter(s=>s!==e).map(s=>this.getRoutes(s,e)))).filter(s=>s.length>0).map(([s])=>s[0].assetIn).sort()}async getRoutes(e,t){let r=await this.getPools();return this.validateInput(e,t,r),this.getPaths(e,t,r)}validateInput(e,t,r){if(r.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(r);if(s.get(e)===null)throw new Error(e+" is not supported asset");if(s.get(t)===null)throw new Error(t+" is not supported asset");return this.toPoolsMap(r)}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){let s=this.toPoolsMap(r);return this.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}getProposals(e,t,r){let s=this.buildRouteKey(e,t,r);if(this.routeProposals.has(s))return this.routeProposals.get(s);let i=this.routeSuggester.getProposals(e,t,r);return this.routeProposals.set(s,i),i}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}toPoolsMap(e){return new Map(e.map(t=>[t.address,fe.get(t)]))}toHops(e,t){return e.map(([r,s,i])=>{let a=t.get(r);return{poolAddress:r,poolId:a?.id,pool:a?.type,assetIn:s,assetOut:i}})}};var es=p("100");function ts(u,e){return u.minus(e).abs().div(u.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function Pe(u,e){return u.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Gt(u,e){return E.minus(e.div(u)).multipliedBy(100).decimalPlaces(4)}function Wt(u,e){return e.div(u).minus(E).multipliedBy(100).decimalPlaces(4)}function ie(u,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),u.div(es).multipliedBy(e).decimalPlaces(0,1)}var dt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(dt||{}),gt=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(gt||{}),zt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(zt||{});var ve=class extends be{mlr;poolsSnapshot;constructor(e,t={}){super(e,t),this.mlr=new Map}buildCtxSync(e,t){let r=this.poolsSnapshot,s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(!i.length)throw new Fe(e,t);return{paths:i,pools:r,poolsMap:s}}async withCtx(e,t,r){this.poolsSnapshot||(this.poolsSnapshot=await super.getPools());let s=this.buildCtxSync(e,t);return r(s)}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,a=s[s.length-1].amountOut;return i.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(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[r,s]}}getPoolFeeRange(e){let t=e.min?b.toPct(e.min):void 0,r=e.max?b.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){return this.withCtx(e,t,async({paths:i,poolsMap:a})=>{let o;if(s)o=await this.toSellSwaps(r,s,a);else{let n=i.map(c=>this.toSellSwaps(r,c,a)),l=await Promise.all(n);o=this.findBestSellRoute(l)}return this.buildSell(a,o)})}async getSellTrades(e,t,r){return this.withCtx(e,t,async({paths:s,poolsMap:i})=>{let a=s.map(n=>this.toSellSwaps(r,n,i));return(await Promise.all(a)).filter(n=>n.every(l=>l.errors.length==0)).map(n=>this.buildSell(i,n)).sort((n,l)=>n.amountOut.isGreaterThan(l.amountOut)?-1:1)})}buildSell(e,t){let r=t[0],s=t[t.length-1],i=this.isDirectTrade(t),a=t.map(f=>f.spotPrice.shiftedBy(-1*f.assetOutDecimals)).reduce((f,y)=>f.multipliedBy(y)),o=A(a,s.assetOutDecimals),n=i?s.calculatedOut:this.calculateDelta0Y(r.amountIn,t,e),l=s.amountOut,c=i?s.tradeFeePct:Gt(n,l).toNumber(),m=n.minus(l),d=this.getRouteFeeRange(t),h=r.amountIn.shiftedBy(-1*r.assetInDecimals).multipliedBy(o),g=Pe(n,h);return{type:"Sell",amountIn:r.amountIn,amountOut:s.amountOut,spotPrice:o,tradeFee:m,tradeFeePct:c,tradeFeeRange:d,priceImpactPct:g.toNumber(),swaps:t,toHuman(){return{type:"Sell",amountIn:O(r.amountIn,r.assetInDecimals),amountOut:O(s.amountOut,s.assetOutDecimals),spotPrice:O(o,s.assetOutDecimals),tradeFee:O(m,s.assetOutDecimals),tradeFeePct:c,tradeFeeRange:d,priceImpactPct:g.toNumber(),swaps:t.map(f=>f.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],o=r.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let n=o.parsePair(a.assetIn,a.assetOut),l;i>0?l=s[i-1]:l=e;let c=o.calculateOutGivenIn(n,l);s.push(c)}return s[s.length-1]}async calculateMostLiquidRoute(e,t,r){let{paths:s,pools:i,poolsMap:a}=r,c=i.filter(y=>y.tokens.some(v=>v.id===e)).map(y=>y.type==="Aave"?y.tokens:y.tokens.filter(v=>v.id===e)).map(y=>y.map(v=>p(v.balance).shiftedBy(-1*v.decimals)).reduce((v,P)=>v.plus(P))).sort((y,v)=>v.isLessThan(y)?-1:1)[0].div(100).multipliedBy(.1),m=s.map(async y=>await this.toSellSwaps(c,y,a)),d=await Promise.all(m),g=this.findBestSellRoute(d).map(y=>({poolAddress:y.poolAddress,poolId:y?.poolId,pool:y.pool,assetIn:y.assetIn,assetOut:y.assetOut})),f=this.buildRouteKey(e,t,i);return this.mlr.set(f,g),g}async toSellSwaps(e,t,r){let s=[],i=[];for(let n=0;n<t.length;n++){let l=t[n],c=r.get(l.poolAddress);if(!c)throw new Error("Pool does not exit");let m=c.parsePair(l.assetIn,l.assetOut);s[n]=c,i[n]=m}let a=await Promise.all(i.map((n,l)=>this.poolService.getPoolFees(n,s[l]))),o=[];for(let n=0;n<t.length;n++){let l=t[n],c=s[n],m=a[n],d=i[n],h;n>0?h=o[n-1].amountOut:h=A(p(e),d.decimalsIn).decimalPlaces(0,1);let{amountOut:g,calculatedOut:f,feePct:y,errors:v}=c.validateAndSell(d,h,m),P=this.getPoolFeeRange(m),B=c.spotPriceOutGivenIn(d),I=h.shiftedBy(-1*d.decimalsIn).multipliedBy(B),T=Pe(f,I),w=c.type==="Aave";o.push({...l,assetInDecimals:d.decimalsIn,assetOutDecimals:d.decimalsOut,amountIn:h,amountOut:g,calculatedOut:f,spotPrice:B,tradeFeePct:y,tradeFeeRange:P,priceImpactPct:T.toNumber(),errors:v,isSupply:()=>w&&c.tokens[0].id===l.assetIn,isWithdraw:()=>w&&c.tokens[1].id===l.assetIn,toHuman(){return{...l,amountIn:O(h,d.decimalsIn),amountOut:O(g,d.decimalsOut),calculatedOut:O(f,d.decimalsOut),spotPrice:O(B,d.decimalsOut),tradeFeePct:y,priceImpactPct:T.toNumber(),errors:v}}})}return o}async getMostLiquidRoute(e,t){return this.withCtx(e,t,async r=>{let s=this.buildRouteKey(e,t,r.pools),i=this.mlr.get(s);return i||this.calculateMostLiquidRoute(e,t,r)})}async getBestSpotPrice(e,t){return this.withCtx(e,t,async r=>{let{pools:s,poolsMap:i}=r,a=this.buildRouteKey(e,t,s),o=this.mlr.get(a);o||(o=await this.calculateMostLiquidRoute(e,t,r));let n=await this.toSellSwaps("1",o,i),l=n.map(d=>d.spotPrice.shiftedBy(-1*d.assetOutDecimals)).reduce((d,h)=>d.multipliedBy(h)),c=n[n.length-1].assetOutDecimals;return{amount:A(l,c),decimals:c}}).catch(()=>{})}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,a=s[0].amountIn;return i.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){return this.withCtx(e,t,async({paths:i,poolsMap:a})=>{let o;if(s)o=await this.toBuySwaps(r,s,a);else{let n=i.map(c=>this.toBuySwaps(r,c,a)),l=await Promise.all(n);o=this.findBestBuyRoute(l)}return this.buildBuy(a,o)})}async getBuyTrades(e,t,r){return this.withCtx(e,t,async({paths:s,poolsMap:i})=>{let a=s.map(n=>this.toBuySwaps(r,n,i));return(await Promise.all(a)).filter(n=>n.every(l=>l.errors.length==0)).map(n=>this.buildBuy(i,n)).sort((n,l)=>n.amountIn.isGreaterThan(l.amountIn)?1:-1)})}buildBuy(e,t){let r=t[t.length-1],s=t[0],i=this.isDirectTrade(t),a=t.map(f=>f.spotPrice.shiftedBy(-1*f.assetInDecimals)).reduce((f,y)=>f.multipliedBy(y)),o=A(a,s.assetInDecimals),n=i?s.calculatedIn:this.calculateDelta0X(r.amountOut,t,e),l=s.amountIn,c=i?s.tradeFeePct:Wt(n,l).toNumber(),m=l.minus(n),d=this.getRouteFeeRange(t),h=r.amountOut.shiftedBy(-1*r.assetOutDecimals).multipliedBy(o),g;return n.isZero()?g=-100:g=Pe(h,n).toNumber(),{type:"Buy",amountOut:r.amountOut,amountIn:s.amountIn,spotPrice:o,tradeFee:m,tradeFeePct:c,tradeFeeRange:d,priceImpactPct:g,swaps:t,toHuman(){return{type:"Buy",amountOut:O(r.amountOut,r.assetOutDecimals),amountIn:O(s.amountIn,s.assetInDecimals),spotPrice:O(o,s.assetInDecimals),tradeFee:O(m,s.assetInDecimals),tradeFeePct:c,tradeFeeRange:d,priceImpactPct:g,swaps:t.map(f=>f.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],o=r.get(a.poolAddress);if(o==null)throw new Error("Pool does not exit");let n=o.parsePair(a.assetIn,a.assetOut),l;i==t.length-1?l=e:l=s[0];let c=o.calculateInGivenOut(n,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[],i=[];for(let n=0;n<t.length;n++){let l=t[n],c=r.get(l.poolAddress);if(!c)throw new Error("Pool does not exit");let m=c.parsePair(l.assetIn,l.assetOut);s[n]=c,i[n]=m}let a=await Promise.all(i.map((n,l)=>this.poolService.getPoolFees(n,s[l]))),o=[];for(let n=t.length-1;n>=0;n--){let l=t[n],c=s[n],m=a[n],d=i[n],h;n==t.length-1?h=A(p(e),d.decimalsOut).decimalPlaces(0,1):h=o[0].amountIn;let{amountIn:g,calculatedIn:f,feePct:y,errors:v}=c.validateAndBuy(d,h,m),P=this.getPoolFeeRange(m),B=c.spotPriceInGivenOut(d),I=h.shiftedBy(-1*d.decimalsOut).multipliedBy(B),T;f.isZero()?T=-100:T=Pe(I,f).toNumber(),o.unshift({...l,assetInDecimals:d.decimalsIn,assetOutDecimals:d.decimalsOut,amountIn:g,amountOut:h,calculatedIn:f,spotPrice:B,tradeFeePct:y,tradeFeeRange:P,priceImpactPct:T,errors:v,isSupply(){return c.type==="Aave"&&c.tokens[0].id===l.assetIn},isWithdraw(){return c.type==="Aave"&&c.tokens[1].id===l.assetIn},toHuman(){return{...l,amountIn:O(g,d.decimalsIn),amountOut:O(h,d.decimalsOut),calculatedIn:O(f,d.decimalsIn),spotPrice:O(B,d.decimalsIn),tradeFeePct:y,tradeFeeRange:P,priceImpactPct:T,errors:v}}})}return o}};var Xt=6e3,Vt=p(1e15),Se=6,ht=-5,yt=360*60*1e3,rs=3,Yt=6;var z=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 xe=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??Xt,minBudgetInNative:t.minBudgetInNative??Vt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[a,o]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:l,priceImpactPct:c}=o,m=l[0],d=l[l.length-1],{assetInDecimals:h}=m,{assetOutDecimals:g}=d,f=Math.abs(c),y=this.getMinimumTradeCount(n,a),v=this.getOptimalTradeCount(f),P=i?Math.round(s/i):v,B=Math.ceil(s/y),I=Math.round(s/v),T=Math.round(s/P),w=n.dividedBy(P).decimalPlaces(0,1),D=await this.router.getBestSell(e,t,O(w,h)),U=n.isLessThan(a),Ke=[];U&&Ke.push("OrderTooSmall");let $e=D.amountOut.multipliedBy(P),Pt=this.toBlockPeriod(T),vt=D.tradeFee.multipliedBy(P),St=z.build(l),je={assetIn:e,assetOut:t,errors:Ke,frequencyMin:B,frequencyOpt:I,frequency:T,tradeCount:P,tradeFee:vt,tradeImpactPct:D.priceImpactPct,tradePeriod:Pt,tradeRoute:St,type:"Dca"};return{...je,amountIn:n,amountOut:$e,tradeAmountIn:D.amountIn,tradeAmountOut:D.amountOut,toHuman(){return{...je,amountIn:O(n,h),amountOut:O($e,g),tradeAmountIn:O(D.amountIn,h),tradeAmountOut:O(D.amountOut,g)}}}}async getMinimumOrderBudget(e){if("0"===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice("0",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:a,swaps:o,priceImpactPct:n}=i,l=o[0],c=o[o.length-1],{assetInDecimals:m}=l,{assetOutDecimals:d}=c,h=Math.abs(n),g=this.getTwapTradeCount(h),f=a.dividedBy(g).decimalPlaces(0,1),y=await this.router.getBestSell(l.assetIn,c.assetOut,O(f,m)),v=g===1,P=a.isLessThan(s),B=y.priceImpactPct<ht,I=[];P||v?I.push("OrderTooSmall"):B&&I.push("OrderImpactTooBig");let T=y.amountOut.multipliedBy(g),w=y.tradeFee.multipliedBy(g),D=z.build(o),U={assetIn:e,assetOut:t,errors:I,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:Se,tradeRoute:D,type:"TwapSell"};return{...U,amountIn:a,amountOut:T,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:w,toHuman(){return{...U,amountIn:O(a,m),amountOut:O(T,d),tradeAmountIn:O(y.amountIn,m),tradeAmountOut:O(y.amountOut,d),tradeFee:O(w,d)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:a,swaps:o,priceImpactPct:n}=i,l=o[0],c=o[o.length-1],{assetInDecimals:m}=l,{assetOutDecimals:d}=c,h=Math.abs(n),g=this.getTwapTradeCount(h),f=a.dividedBy(g).decimalPlaces(0,1),y=await this.router.getBestBuy(l.assetIn,c.assetOut,O(f,d)),v=y.amountIn.multipliedBy(g),P=g===1,B=v.isLessThan(s),I=y.priceImpactPct<ht,T=[];B||P?T.push("OrderTooSmall"):I&&T.push("OrderImpactTooBig");let w=y.tradeFee.multipliedBy(g),D=z.build(o),U={assetIn:e,assetOut:t,errors:T,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:Se,tradeRoute:D,type:"TwapBuy"};return{...U,amountIn:v,amountOut:a,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:w,toHuman(){return{...U,amountIn:O(v,m),amountOut:O(a,d),tradeAmountIn:O(y.amountIn,m),tradeAmountOut:O(y.amountOut,d),tradeFee:O(w,m)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>yt){let s=yt/(this.blockTime*Se);return Math.round(s)}return t}getTwapExecutionTime(e){return e*Se*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,Yt)}};var Be=class extends H{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new W(e),this.aaveUtils=new ee(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(),oe)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var ft=class extends Be{_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:a}=s,n=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,a)).amount.isGreaterThanOrEqualTo(n)),l&&e.isGreaterThanOrEqualTo(n)?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],a=ie(e,this.slippagePct),o=s.assetIn,n=i.assetOut,l=e.plus(a),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(n,o,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(o,n,t.toFixed(),l.toFixed(),z.build(r)),await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let d=this.dispatchWithExtraGas(c);return this.wrapTx("RouterBuy",d,oe)}return this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],a=ie(t,this.slippagePct),o=s.assetIn,n=i.assetOut,l=t.minus(a),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(o,n,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(o,n,e.toFixed(),l.toFixed(),z.build(r)),await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let d=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSell",d,oe)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=ie(e,this.slippagePct),a=r.assetIn,o=s.assetOut,n=e.minus(i),l=this.api.tx.router.sellAll(a,o,n.toFixed(),z.build(t));if(await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let m=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",m,oe)}return this.wrapTx("RouterSellAll",l)}};var bt=class extends Be{_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:a}=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:a}}},null);return this.wrapTx("DcaSchedule",o)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:a,tradeRoute:o}=this.order,n=ie(i,this.slippagePct),l=i.minus(n),c=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:o}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:a,tradeRoute:o}=this.order,n=ie(s,this.slippagePct),l=s.plus(n),c=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:i.toFixed(),maxAmountIn:l.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var we=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new ft(this.api,this.evm).setTrade(e)}order(e){return new bt(this.api,this.evm).setOrder(e)}};var ss={router:{}};function is(u,e=ss){let t=new me(u),r=new Ee(u),s=new ye(u,r),i=new ee(r),a=new ve(s,e.router),o=new xe(a,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:i,router:a,scheduler:o},client:{asset:new te(u),balance:new W(u),balanceV2:new ue(u)},ctx:{pool:s},evm:r,tx:new we(u,r),destroy:()=>{s.destroy()}}}0&&(module.exports={AaveClient,AavePool,AavePoolClient,AaveUtils,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BalanceClientV2,BigNumber,CachingPoolService,ChainParams,DECIMAL_PLACES,DEFAULT_BLOCK_TIME,DEFAULT_MIN_BUDGET,ERC20,EvmClient,EvmRpcAdapter,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,MmOracleClient,ONE,ORDER_MIN_BLOCK_PERIOD,OmniMath,OmniPool,OmniPoolClient,PERBILL_DENOMINATOR,PERMILL_DENOMINATOR,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,TWAP_BLOCK_PERIOD,TWAP_MAX_DURATION,TWAP_MAX_PRICE_IMPACT,TWAP_TX_MULTIPLIER,TradeOrderError,TradeOrderType,TradeRouteBuilder,TradeRouter,TradeScheduler,TradeType,TxBuilderFactory,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,createChain,createSdkContext,findNestedKey,findNestedObj,getFraction,hashPools,isEvmAccount,isEvmAddress,isSs58Address,scale,toBn,toDecimals});