@galacticcouncil/sdk 9.10.0 → 9.11.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 Pt=Object.defineProperty;var wr=Object.getOwnPropertyDescriptor;var Or=Object.getOwnPropertyNames;var Tr=Object.prototype.hasOwnProperty;var Ir=(u,e)=>{for(var t in e)Pt(u,t,{get:e[t],enumerable:!0})},Ar=(u,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Or(e))!Tr.call(u,s)&&s!==t&&Pt(u,s,{get:()=>e[s],enumerable:!(r=wr(e,s))||r.enumerable});return u};var Rr=u=>Ar(Pt({},"__esModule",{value:!0}),u);var jr={};Ir(jr,{AaveClient:()=>oe,AavePool:()=>Ne,AavePoolClient:()=>ke,AaveUtils:()=>Z,AssetClient:()=>ee,AssetNotFound:()=>Tt,BASILISK_PARACHAIN_ID:()=>us,BalanceClient:()=>G,BalanceClientV2:()=>ue,BigNumber:()=>v.BigNumber,CachingPoolService:()=>ge,ChainParams:()=>ce,DECIMAL_PLACES:()=>Kt,DEFAULT_BLOCK_TIME:()=>Ut,DEFAULT_MIN_BUDGET:()=>Gt,ERC20:()=>Y,EvmClient:()=>_e,FarmClient:()=>je,H160:()=>ie,HUB_ASSET_ID:()=>we,HYDRADX_PARACHAIN_ID:()=>cs,HYDRADX_SS58_PREFIX:()=>X,INFINITY:()=>_r,LbpMath:()=>W,LbpPool:()=>Ce,LbpPoolClient:()=>De,ONE:()=>N,ORDER_MIN_BLOCK_PERIOD:()=>Ht,OmniMath:()=>_,OmniPool:()=>Me,OmniPoolClient:()=>Le,PERBILL_DENOMINATOR:()=>zt,PERMILL_DENOMINATOR:()=>se,PolkadotApiClient:()=>q,PoolConfigNotFound:()=>Ot,PoolError:()=>te,PoolFactory:()=>he,PoolNotFound:()=>Ae,PoolService:()=>de,PoolType:()=>F,ProviderConfigNotFound:()=>Rt,RUNTIME_DECIMALS:()=>Oe,RouteNotFound:()=>Re,Router:()=>ye,SYSTEM_ASSET_DECIMALS:()=>Xt,SYSTEM_ASSET_ID:()=>C,StableMath:()=>D,StableSwap:()=>ae,StableSwapClient:()=>Ge,StorageConfigNotFound:()=>It,SubscriptionNotSupported:()=>At,TRADEABLE_DEFAULT:()=>Te,TWAP_BLOCK_PERIOD:()=>be,TWAP_MAX_DURATION:()=>mt,TWAP_MAX_PRICE_IMPACT:()=>ct,TWAP_TX_MULTIPLIER:()=>$r,TradeOrderError:()=>qt,TradeOrderType:()=>ut,TradeRouteBuilder:()=>H,TradeRouter:()=>fe,TradeScheduler:()=>Se,TradeType:()=>lt,TxBuilderFactory:()=>ve,XykMath:()=>Q,XykPool:()=>qe,XykPoolClient:()=>Ue,ZERO:()=>S,bnFormatter:()=>Hr,bnum:()=>p,calculateBuyFee:()=>Lt,calculateDiffToAvg:()=>Yr,calculateDiffToRef:()=>Pe,calculateSellFee:()=>Mt,createChain:()=>_t,createSdkContext:()=>Kr,findNestedKey:()=>kt,findNestedObj:()=>Gr,getFraction:()=>re,hashPools:()=>Ct,isEvmAccount:()=>Yt,isEvmAddress:()=>$t,isSs58Address:()=>Vt,scale:()=>A,toBn:()=>Nr,toDecimals:()=>O});module.exports=Rr(jr);var Ve=[{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 ft=[{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 Wt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",bt="0x112b087b60C1a166130d59266363C45F8aa99db0",St="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Be=1000000n;var is=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var oe=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:ft,address:bt,args:[St],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:ft,address:bt,args:[St,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:Ve,address:Wt,args:[e],functionName:"getUserAccountData"})}};var J=require("@polkadot/util-crypto"),le=require("@polkadot/util"),K=require("buffer");var us=2090,se=1e6,zt=1e9,we="1",cs=2034,X=63,Oe=18,C="0",Xt=12,Te=15;var xt="ETH\0";function Yt(u){if(!u)return!1;try{let e=(0,J.decodeAddress)(u,!0),t=K.Buffer.from(xt);return K.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function $t(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Vt(u){try{let e=(0,le.isHex)(u)?(0,le.hexToU8a)(u):(0,J.decodeAddress)(u);return(0,J.encodeAddress)(e),!0}catch{return!1}}var ie=class u{static toAccount=e=>{let t=K.Buffer.from(e.slice(2),"hex"),r=K.Buffer.from(xt);return(0,J.encodeAddress)(new Uint8Array(K.Buffer.concat([r,t,K.Buffer.alloc(8)])),63)};static fromAccount=e=>{let t=(0,J.decodeAddress)(e),r=K.Buffer.from(xt),s=t.slice(r.length,-8);return"0x"+K.Buffer.from(s).toString("hex")};static fromSS58=e=>{let r=(0,J.decodeAddress)(e).slice(0,20);return(0,le.u8aToHex)(r)};static fromAny=e=>{if($t(e))return e;if(Yt(e))return u.fromAccount(e);if(Vt(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var Ie=require("buffer"),Y=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 v=require("bignumber.js"),Kt=12;v.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Kt});var S=p(0),N=p(1),_r=p("Infinity");function A(u,e){let t=new v.BigNumber(e.toString()),r=new v.BigNumber(10).pow(t);return u.times(r).decimalPlaces(4)}function p(u){return new v.BigNumber(u.toString())}function Nr(u,e){let t=p(u);return A(t,e)}function O(u,e){return u.shiftedBy(-1*e).toString()}var Ke=p("1e27"),Fr=p("1.01"),Er=p("31536000"),Z=class{client;constructor(e){this.client=new oe(e)}async getSummary(e){let t=ie.fromAny(e),[r,s,i,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[a]=r,[o,l]=s,[c,m,g,d,h,f]=i,P=p(f).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN),B=p(c),b=p(m),w=[];for(let x of o){let I=x.underlyingAsset.toLowerCase(),R=a.find(({underlyingAsset:Br})=>Br.toLowerCase()===I);if(!R)throw new Error("Missing pool reserve for "+I);let L=p(x.scaledATokenBalance),z=p(R.liquidityIndex),Xe=p(R.liquidityRate),Ye=p(R.availableLiquidity),gt=p(R.priceInMarketReferenceCurrency),ht=n+6,yt=this.calculateLinearInterest(Xe,R.lastUpdateTimestamp,ht),$e=z.multipliedBy(yt).dividedBy(Ke).decimalPlaces(0,v.BigNumber.ROUND_DOWN),br=L.multipliedBy($e).dividedBy(Ke).decimalPlaces(0,v.BigNumber.ROUND_DOWN),Sr=p(l!==0&&l===R.eModeCategoryId?R.eModeLiquidationThreshold:R.reserveLiquidationThreshold).div(1e4),xr=R.usageAsCollateralEnabled&&x.usageAsCollateralEnabledOnUser&&p(x.scaledATokenBalance).gt(0),vr=Y.toAssetId(I);w.push({aTokenBalance:br,availableLiquidity:Ye,decimals:Number(R.decimals),isCollateral:xr,priceInRef:gt,reserveId:vr,reserveAsset:I,reserveLiquidationThreshold:Sr})}return{healthFactor:P.toNumber(),totalCollateral:B,totalDebt:b,reserves:w}}async hasBorrowPositions(e){let t=ie.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=ie.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,n,a,o,l]=r;return p(l).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),a=Y.fromAssetId(t),o=n.find(B=>B.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,isCollateral:c,priceInRef:m,reserveLiquidationThreshold:g}=o,d=A(p(r),l).decimalPlaces(0,1),h=c?d.multipliedBy(m).dividedBy(p(10).pow(l)).decimalPlaces(0,v.BigNumber.ROUND_DOWN):S,f=s.minus(h);return f.lte(0)?0:f.multipliedBy(g).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),a=Y.fromAssetId(t),o=n.find(P=>P.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:m}=o,d=A(p(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(p(10).pow(l)).decimalPlaces(0,v.BigNumber.ROUND_DOWN),h=s.plus(d);return h.lte(0)?0:h.multipliedBy(m).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),n=Y.fromAssetId(t),a=s.find(o=>o.reserveAsset===n);if(!a)throw new Error("Missing reserve data for "+n);return this.calculateWithdrawMax(a,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let n of r){let a=this.calculateWithdrawMax(n,t,s);n.reserveId&&(i[n.reserveId]=a)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:n,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let g=p(r).minus(Fr);if(g.gt(0)){let h=g.multipliedBy(t).dividedBy(o).decimalPlaces(0,v.BigNumber.ROUND_DOWN).dividedBy(a).multipliedBy(p(10).pow(n)).decimalPlaces(0,v.BigNumber.ROUND_DOWN);c=v.BigNumber.minimum(s,h)}else c=S}return{amount:v.BigNumber.minimum(c,i),decimals:n}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Ke:e.multipliedBy(s).dividedBy(Er).plus(Ke).decimalPlaces(0,v.BigNumber.ROUND_DOWN)}};function jt(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var As=require("@galacticcouncil/api-augment/hydradx"),Rs=require("@galacticcouncil/api-augment/basilisk"),q=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");jt(r)&&console.log(e,...t)}};var ee=class extends q{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==C){let m=this.api.consts.balances.existentialDeposit;return{id:C,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:a,existentialDeposit:o}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:n.toHuman(),isSufficient:a?a.toHuman():!0,location:s?.toJSON(),existentialDeposit:o.toString()}}getBond(e,t,r,s){let[i,n]=s,{assetType:a,isSufficient:o,existentialDeposit:l}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,r),g=n.toNumber(),d=new Intl.DateTimeFormat("en-GB"),h=[c,"Bond",d.format(g)].join(" ");return{id:e,name:h,symbol:c+"b",decimals:m,icon:c,type:a.toString(),isSufficient:o.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:g}}getShares(e,t,r,s){let{assets:i}=s,{name:n,symbol:a,assetType:o,isSufficient:l,existentialDeposit:c}=t,g=i.map(f=>f.toString()).map(f=>{let{symbol:P}=this.getToken(f,t,r);return[f,P]}),d=Object.fromEntries(g),h=Object.values(d);return{id:e,name:h.join(", "),symbol:a?.isSome?a.toHuman():n.toHuman(),decimals:18,icon:h.join("/"),type:o.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),n=r?.find(a=>a.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:n}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,i,n,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),o=this.getSupportedAssets(r),l=this.normalizeMetadata(o,a),c=o.map(([{args:[m]},g])=>{let d=g.unwrap(),h=s.get(m.toString()),{assetType:f}=d;switch(f.toString()){case"Bond":let P=n.get(m.toString());return this.getBond(m.toString(),d,l,P);case"StableSwap":let B=i.get(m.toString());return this.getShares(m.toString(),d,l,B);case"External":return this.getExternal(m.toString(),d,t,h);default:return this.getToken(m.toString(),d,l,h)}});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 G=class extends q{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===C?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(C,this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,a]})=>[n.toString(),a.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let a=[];n.forEach((o,l)=>{let c=this.calculateFreeBalance(o),m=i[l][1];a.push([m,c])}),t(a)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([o,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[o]}])=>o.toString()))(),n=async()=>{let a=await Promise.all(i.map(async o=>[o,await this.getErc20Balance(e,o)]));t(a)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}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,v.BigNumber)(t).lt(r)?(0,v.BigNumber)(0):(0,v.BigNumber)(t).minus(r)}};var ue=class extends q{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===C?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(C,this.calculateBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,a]})=>[n.toString(),a.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let a=[];n.forEach((o,l)=>{let c=i[l][1],m=this.calculateBalance(o);a.push([c,m])}),t(a)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([o,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[o]}])=>o.toString()))(),n=async()=>{let a=await Promise.all(i.map(async o=>[o,await this.getErc20Balance(e,o)]));t(a)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=(0,v.BigNumber)(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),i=t.gte(r)?t.minus(r).toString():"0",n=t.plus(s).toString();return{free:t.toString(),total:n,transferable:i,reserved:s,frozen:r}}};var ce=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 vt=require("@galacticcouncil/math-liquidity-mining"),Qt=require("@polkadot/types"),Bt=require("@polkadot/util"),wt=require("@polkadot/util-crypto");var je=class extends q{balanceClient;constructor(e){super(e),this.balanceClient=new G(e)}secondsInYear=new v.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,a=i.unwrap().toString(),o=n.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,o,a)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(o),!1).toString(),h=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(d,h);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[,n]=s.args,a=i.unwrap().toString(),o=n.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,o,a)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(o),!0).toString(),h=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(d,h);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 v.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),a=n.price.n.toString(),o=n.price.d.toString(),l;return Number(t)<Number(r)?l=(0,vt.fixed_from_rational)(a,o):l=(0,vt.fixed_from_rational)(o,a),l}getGlobalRewardPerPeriod(e,t,r,s){let n=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return n.gte(r)?r:n}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return(0,Bt.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Qt.GenericAccountId32(e,this.padEndU8a((0,Bt.u8aConcat)(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,wt.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,wt.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:a,globalFarm:o,priceAdjustment:l,potBalance:c})=>{let m=new v.BigNumber(o.totalSharesZ.toString()),g=o.plannedYieldingPeriods.toString(),d=new v.BigNumber(o.yieldPerPeriod.toString()),h=new v.BigNumber(o.maxRewardPerPeriod.toString()),f=o.blocksPerPeriod.toString(),P=new v.BigNumber(a.multiplier.toString()).shiftedBy(-18),B=this.secondsInYear.div(new v.BigNumber(r).times(f)),b;if(m.isZero())b=d.times(P).times(B);else{let L=this.getGlobalRewardPerPeriod(m,d,h,l);b=this.getPoolYieldPerPeriod(L,P,m,l).times(B)}let w=new v.BigNumber(o.pendingRewards.toString()).plus(o.accumulatedPaidRewards.toString()),x=h.times(g),I=c?w.plus(c):x;return w.div(I).gte(.999)?S:b.div(t==="isolatedpool"?2:1).times(100)}).reduce((a,o)=>a.plus(o),S).toString():void 0}};var Ae=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Ot=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Re=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Tt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},It=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},At=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Rt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Jt=require("viem"),kr=["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"],_t=u=>{let t=[u.endpoint,...kr],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return(0,Jt.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://explorer.evm.hydration.cloud"}},testnet:!1})};var j=require("viem");function Zt(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 _e=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=_t(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,j.createPublicClient)({chain:this.chain,transport:(0,j.http)()})}getWsProvider(){return(0,j.createPublicClient)({chain:this.chain,transport:Zt(this.wsProvider)})}getSigner(e){return(0,j.createWalletClient)({account:e,chain:this.chain,transport:(0,j.custom)(window.ethereum)})}};var ne=(u,e=new Map)=>t=>{let r;return e.has(t)?e.get(t):(e.set(t,r=u(t)),r)};var F=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n.HSM="Hsm",n))(F||{}),te=(a=>(a.UnknownError="UnknownError",a.InsufficientTradingAmount="InsufficientTradingAmount",a.MaxInRatioExceeded="MaxInRatioExceeded",a.MaxOutRatioExceeded="MaxOutRatioExceeded",a.TradeNotAllowed="TradeNotAllowed",a.MaxBuyBackExceeded="MaxBuyBackExceeded",a.MaxBuyPriceExceeded="MaxBuyPriceExceeded",a))(te||{});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(o=>[o.id,o])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),a=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:a,assetInED:S,assetOutED:S}}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(N,e.decimalsOut)}spotPriceOutGivenIn(e){return A(N,e.decimalsIn)}calculateTradeFee(e,t){return S}};var lr=require("@polkadot/util-crypto"),ur=require("@polkadot/util"),cr=require("viem");var Fe=(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 Qe=(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 Cr=Qe(()=>"illegal argument(s)"),er=u=>{throw new Cr(u)};var Dr=Qe(()=>"index out of bounds"),Nt=u=>{throw new Dr(u)},Je=(u,e,t)=>(u<e||u>=t)&&Nt(u);var tr=23283064365386963e-26,Ze=class{float(e=1){return this.int()*tr*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*tr-.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 et=class extends Ze{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 rr=new et(Math.random);var sr=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var ir=Object.getPrototypeOf({}),tt="function",nr="string",me=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===tt)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===tt)return e.equiv(u)}else return u==e;return typeof u===nr||typeof e===nr?!1:(t=Object.getPrototypeOf(u),(t==null||t===ir)&&(t=Object.getPrototypeOf(e),t==null||t===ir)?Ur(u,e):typeof u!==tt&&u.length!==void 0&&typeof e!==tt&&e.length!==void 0?Mr(u,e):u instanceof Set&&e instanceof Set?Lr(u,e):u instanceof Map&&e instanceof Map?qr(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)},Mr=(u,e,t=me)=>{let r=u.length;if(r===e.length)for(;r-- >0&&t(u[r],e[r]););return r<0},Lr=(u,e,t=me)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),qr=(u,e,t=me)=>u.size===e.size&&t([...u].sort(),[...e].sort()),Ur=(u,e,t=me)=>{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 Ft=class{value;constructor(e){this.value=e}deref(){return this.value}};var ar=u=>u instanceof Ft;var rt=class u{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return or("next",this._head)}reverseIterator(){return or("prev",this.tail)}clear(){this.release()}compare(e,t=Fe){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,n=0;for(;r-- >0&&n===0;)n=t(s.value,i.value),s=s.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof u||sr(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(!me(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||Fe;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!ar(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&&Nt(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*or(u,e){for(;e;)yield e.value,e=e[u]}var st=class u extends rt{_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):(Je(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):(Je(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=n=>({first(){return n.value},next(){return n!==s&&n.next?i(n.next):void 0}});return r?i(r):void 0}shuffle(e,t=rr){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)&&er("invalid indices: ${from} / ${to}");let i=new u,n=this.nthCell(r);for(;n&&++r<=s;)i.push(n.value),n=n.next;return i}sort(e=Fe){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,n=0;for(let o=0;o<t&&(n++,i=i.next,!!i);o++);let a=t;for(;n>0||a>0&&i;){let o;n===0?(o=i,i=i.next,a--):!i||a===0||e(r.value,i.value)<=0?(o=r,r=r.next,n--):(o=i,i=i.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}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),Je(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 n of r)this.insertBefore(s,n);else for(let n of r)this.push(n);return i}};var it=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 st,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 pe=class u extends it{constructor(e,t){super(e,{ttl:60*60*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),n=Math.max(0,s-(i?i.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(i,e,t,s,r):this._size-=n,t}async getSet(e,t,r=this.opts.ttl){let s=this.get(e);return s!==void 0?s:this.set(e,await t(),r)}prune(){let e=Date.now(),t=this.items.head,r=0;for(;t;)t.value.t<e&&(this.removeEntry(t),r++),t=t.next;return r}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,r=Date.now(),s=this.items.head;for(;s&&(this._size>t||this.length>=e);)s.value.t<r&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(e,t,r,s,i=this.opts.ttl){let n=Date.now()+i;e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,e.value.t=n,this.items.asTail(e)):(this.items.push({k:t,v:r,s,t:n,ttl:i}),this.map.set(t,this.items.tail))}resetEntry(e){return this.opts.autoExtend&&(e.value.t=Date.now()+e.value.ttl),super.resetEntry(e)}};var Et=[{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 Ee=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.client.readContract({abi:Et,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:Et,address:e,functionName:"decimals"}),this.client.getBlock()]),[n,a,o,l]=r,c=i.number-(i.timestamp-l)/BigInt(t),m=Number(c);return{price:a,decimals:s,updatedAt:m<0?0:m}}};var U=class extends G{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new pe(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=ne(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new Ee(t)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools();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=this.augmentedPools.map(async r=>{let s=[],i=await this.subscribeTokensPoolBalance(r);if(s.push(i),this.hasSystemAsset(r)){let n=await this.subscribeSystemPoolBalance(r);s.push(n)}if(this.hasErc20Asset(r)){let n=await this.subscribeErc20PoolBalance(r);s.push(n)}return this.subscribeLog(r),s}),t=await Promise.all(e);return()=>{for(let r of t.flat())try{r()}catch(s){console.warn("Balance unsub failed",s)}}}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t()).catch(t=>console.warn("Unsub failed",t))})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,i])=>{let n=e.tokens.findIndex(a=>a.id==s);n>=0&&t(e,s)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(i=>i.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};function kt(u,e){let t=[];return JSON.stringify(u,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Gr(u,e,t){let r;return JSON.stringify(u,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Hr=(u,e)=>typeof e=="bigint"?e.toString():e;var Wr=["Supply","Withdraw","Repay","Borrow"],ke=class extends U{getPoolType(){return"Aave"}getPoolId(e,t){let r="aave:"+e+"/"+t;return(0,lr.encodeAddress)((0,ur.stringToU8a)(r.padEnd(32,"\0")),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}getReserveH160Id(e){return e.type==="Erc20"?kt(e.location,"accountKey20").accountKey20.key:Y.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{}}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return this.api.query.system.events(e=>{e.forEach(t=>{let{event:r}=t,s=`${r.section}:${r.method}`;if(s==="router:Executed"){let[i,n]=r.data.toJSON();this.pools.filter(a=>a.tokens.some(o=>o.id===i.toString()||o.id===n.toString())).forEach(a=>{this.log(`Sync AAVE via [router:Executed] :: ${i}:${n}`),this.updatePoolState(a)})}if(s==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:n,args:a}=(0,cr.decodeEventLog)({abi:Ve,topics:i.topics,data:i.data});if(Wr.includes(n)){let o=a.reserve.toLowerCase();this.pools.filter(l=>{let[c]=l.tokens;return this.getReserveH160Id(c).toLowerCase()===o}).forEach(l=>{this.log(`Sync AAVE via [evm:Log] :: ${n} ${o}`),this.updatePoolState(l)})}}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(n=>{let a=n.id===t.id?s.toString():i.toString();return{...n,balance:a}})}};var $=require("@galacticcouncil/math-lbp"),W=class{static getSpotPrice(e,t,r,s,i){return(0,$.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,$.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,$.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,$.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,$.calculate_pool_trade_fee)(e,t,r)}};var y=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 Ce=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(o=>[o.id,o])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),a=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:a,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let a=this.calculateTradeFee(t,r),o=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(a),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:o,errors:i}}else{let a=this.calculateInGivenOut(e,t),o=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(o)&&i.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let a=this.calculateOutGivenIn(e,t),o=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(o)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:a,feePct:0,errors:i}}else{let a=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(a,r),l=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=a.minus(o),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=W.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),A(N,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=W.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),A(N,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=W.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var De=class extends U{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:n,initialWeight:a,finalWeight:o,repayTarget:l,feeCollector:c}=t,m=W.calculateLinearWeights(s.toString(),i.toString(),a.toString(),o.toString(),r),[g,d]=n,h=g.toString(),f=p(m),P=d.toString(),B=this.MAX_FINAL_WEIGHT.minus(p(f)),[b,w,x]=await Promise.all([this.isRepayFeeApplied(h,l.toString(),c.toString()),this.getBalance(e,h),this.getBalance(e,P)]);return{repayFeeApply:b,tokens:[{id:h,weight:f,balance:w.toString()},{id:P,weight:B,balance:x.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,n])=>this.isActivePool(n.unwrap(),r.toNumber())).map(async([{args:[i]},n])=>{let a=n.unwrap(),o=i.toString(),l=await this.getPoolDelta(o,a,r.toString());this.poolsData.set(i.toString(),a);let[c,m]=a.fee;return{address:o,type:"Lbp",fee:y.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 y.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 n=await this.getPoolDelta(r.address,s,t.toString());Object.assign(r,n)}else{let n=this.pools.findIndex(a=>a.address==r.address);this.pools.splice(n,1)}})})}};var T=require("@galacticcouncil/math-omnipool");var _=class{static calculateSpotPrice(e,t,r,s){return(0,T.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,T.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,n,a,o,l){return(0,T.calculate_in_given_out)(e,t,r,s,i,n,a,o,l)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,T.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,n,a,o,l){return(0,T.calculate_out_given_in)(e,t,r,s,i,n,a,o,l)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,T.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculateShares(e,t,r,s){return(0,T.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,n,a,o){return(0,T.calculate_liquidity_out)(e,t,r,s,i,n,a,o)}static calculateLiquidityLRNAOut(e,t,r,s,i,n,a,o){return(0,T.calculate_liquidity_lrna_out)(e,t,r,s,i,n,a,o)}static calculateCapDifference(e,t,r,s){let i=(0,v.BigNumber)(t),n=(0,v.BigNumber)(e),a=(0,v.BigNumber)(s),l=(0,v.BigNumber)(r).shiftedBy(-18);if(i.div(a).lt(l)){let m=l.times(a).minus(i).times(n),g=i.times((0,v.BigNumber)(1).minus(l));return m.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return(0,T.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,T.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,T.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,T.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,T.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,r,s,i,n,a,o,l,c,m){return(0,T.recalculate_asset_fee)(e,t,r,s,i,n,a,o,l,c,m)}static recalculateProtocolFee(e,t,r,s,i,n,a,o,l,c,m){return(0,T.recalculate_protocol_fee)(e,t,r,s,i,n,a,o,l,c,m)}static verifyAssetCap(e,t,r,s){return(0,T.verify_asset_cap)(e,t,r,s)}};var Me=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 n=p(s.balance),a=p(i.balance),o=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:n,balanceOut:a,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),a=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(4),o=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&o.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(g)&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a.toNumber(),errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),a=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),o=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&o.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(g)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a.toNumber(),errors:o}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=_.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateLrnaInGivenOut(e,t,r){let s=_.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=_.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenLrnaIn(e,t,r){let s=_.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=_.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=_.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=_.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=_.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var dr=require("@polkadot/util-crypto"),gr=require("@polkadot/util");var mr="omnipool",pr="Short",Le=class extends U{dynamicFees=new Map;oracles=new Map;memQueryCache=new pe(null,{ttl:6*1e3});memOracleQuery=ne(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(mr,t,pr)},this.memQueryCache);memFeesQuery=ne(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);getPoolType(){return"Omnipool"}getPoolId(){return(0,dr.encodeAddress)((0,gr.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getOracleKey(e){return e===C?[C,we]:[we,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 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}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=r.map(async([{args:[o]},l])=>{let{hubReserve:c,shares:m,tradable:g,cap:d,protocolShares:h}=l.unwrap(),f=await this.getBalance(t,o.toString());return{id:o.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:g.bits.toNumber(),balance:f.toString(),cap:p(d.toString()),protocolShares:p(h.toString())}}),a=await Promise.all(n);return a.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:a,...this.getPoolLimits()}]}async getPoolFees(e,t,r){let s=t.assetOut,i=t.assetIn,[n,a,o]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[l,c,m]=this.getAssetFee(t,e,n,a),[g,d,h]=i===we?[0,0,0]:this.getProtocolFee(t,e,n,o),f=l+g,P=m+h;return{assetFee:y.fromPermill(c),protocolFee:y.fromPermill(d),min:y.fromPermill(f),max:y.fromPermill(P)}}getAssetFee(e,t,r,s){let{assetOut:i,balanceOut:n}=e,{minFee:a,maxFee:o,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,m=y.fromPermill(a.toNumber()),g=y.fromPermill(o.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),o.toNumber()];let[d]=s.unwrap(),{assetFee:h,timestamp:f}=r.unwrap(),P=Math.max(1,t-f.toNumber()),B=d.volume.bIn.toString(),b=d.volume.bOut.toString(),w=d.liquidity.b.toString();i===C&&(B=d.volume.aIn.toString(),b=d.volume.aOut.toString(),w=d.liquidity.a.toString());let x=y.fromPermill(h.toNumber()),I=_.recalculateAssetFee(B,b,w,"9",n.toString(),y.toRaw(x).toString(),P.toString(),y.toRaw(m).toString(),y.toRaw(g).toString(),l.toString(),c.toString());return[a.toNumber(),Number(I)*1e6,o.toNumber()]}getProtocolFee(e,t,r,s){let{assetIn:i,balanceIn:n}=e,{minFee:a,maxFee:o,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,m=y.fromPermill(a.toNumber()),g=y.fromPermill(o.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),o.toNumber()];let[d]=s.unwrap(),{protocolFee:h,timestamp:f}=r.unwrap(),P=Math.max(1,t-f.toNumber()),B=d.volume.bIn.toString(),b=d.volume.bOut.toString(),w=d.liquidity.b.toString();i===C&&(B=d.volume.aIn.toString(),b=d.volume.aOut.toString(),w=d.liquidity.a.toString());let x=y.fromPermill(h.toNumber()),I=_.recalculateProtocolFee(B,b,w,"9",n.toString(),y.toRaw(x).toString(),P.toString(),y.toRaw(m).toString(),y.toRaw(g).toString(),l.toString(),c.toString());return[a.toNumber(),Number(I)*1e6,o.toNumber()]}async subscribeUpdates(){let[e]=this.pools,t=e.tokens.map(o=>o.id),r=[],s=await this.api.query.omnipool.assets.multi(t,o=>{e.tokens=o.map((l,c)=>{let m=e.tokens[c];if(l.isNone)return m;let g=l.unwrap();return this.updateTokenState(m,g)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,o=>{o.forEach((l,c)=>{let m=t[c];this.dynamicFees.set(m,l)})});r.push(i);let n=t.map(o=>{let l=this.getOracleKey(o);return[mr,l,pr]}),a=await this.api.query.emaOracle.oracles.multi(n,o=>{o.forEach(async(l,c)=>{let m=n[c],[g,d,h]=m;this.oracles.set(d.join(":"),l)})});return r.push(a),()=>{for(let o of r)try{o()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:n,protocolShares:a}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(n.toString()),protocolShares:p(a.toString()),tradeable:i.bits.toNumber()}}};var E=require("@galacticcouncil/math-xyk"),Q=class{static getSpotPrice(e,t,r){return(0,E.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,E.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,E.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,E.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,E.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,E.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,E.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,E.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,E.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,E.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 n=p(s.balance),a=p(i.balance),o=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:a,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),a=s.plus(i),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&o.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(c)&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),a=s.minus(i),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&o.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(c)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:a,feePct:n,errors:o}}calculateInGivenOut(e,t){let r=Q.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=Q.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=Q.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=A(N,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=Q.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=A(N,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=Q.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var Ue=class extends U{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(),[n,a]=s.unwrap(),[o,l]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,a.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:o.toString()},{id:a.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 y.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return()=>{}}};var k=require("@galacticcouncil/math-stableswap"),D=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,n,a){return(0,k.calculate_in_given_out)(e,t,r,s,i,n,a)}static calculateAddOneAsset(e,t,r,s,i,n,a){return(0,k.calculate_add_one_asset)(e,t,r,s,i,n,a)}static calculateSharesForAmount(e,t,r,s,i,n,a){return(0,k.calculate_shares_for_amount)(e,t,r,s,i,n,a)}static calculateOutGivenIn(e,t,r,s,i,n,a){return(0,k.calculate_out_given_in)(e,t,r,s,i,n,a)}static calculateLiquidityOutOneAsset(e,t,r,s,i,n,a){return(0,k.calculate_liquidity_out_one_asset)(e,t,r,s,i,n,a)}static calculateShares(e,t,r,s,i,n){return(0,k.calculate_shares)(e,t,r,s,i,n)}static calculateSpotPriceWithFee(e,t,r,s,i,n,a,o){return(0,k.calculate_spot_price_with_fee)(e,t,r,s,i,n,a,o)}static recalculatePegs(e,t,r,s,i){let n=(0,k.recalculate_peg)(e,t,r,s,i);return JSON.parse(n)}};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 n=p(s.balance),a=p(i.balance),o=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:a,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),a=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(4),o=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);return(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a.toNumber(),errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),a=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),o=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);return(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a.toNumber(),errors:o}}calculateIn(e,t,r){let s=D.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateAddOneAsset(e,t,r){let s=D.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateSharesForAmount(e,t,r){let s=D.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=D.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(N,e.decimalsIn-e.decimalsOut);return p(t).div(s).decimalPlaces(0,1)}let r=A(N,18-e.decimalsIn);return p(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=D.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateWithdrawOneAsset(e,t,r){let s=D.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateShares(e,t,r){let s=D.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=D.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(N,e.decimalsOut-e.decimalsIn);return p(t).div(s).decimalPlaces(0,1)}let r=A(N,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 nt=require("@polkadot/util-crypto");var Ge=class extends U{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=Number(e),r=D.getPoolAddress(t);return(0,nt.encodeAddress)((0,nt.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:n,finalBlock:a}=t,o=D.calculateAmplification(s.toString(),i.toString(),n.toString(),a.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:o,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async n=>{let[a,o]=await Promise.all([this.api.query.stableswap.assetTradability(t,n.toString()),this.getBalance(e,n.toString())]);return{id:n.toString(),tradeable:a.bits.toNumber(),balance:o.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:[n]},a])=>{try{let o=a.unwrap(),l=n.toString(),c=this.getPoolAddress(l),[m,g,d]=await Promise.all([this.getPoolDelta(l,o,r.toString()),this.getPoolTokens(c,l,o),this.getPoolPegs(l,o,r.toString())]);return g.push({id:l,tradeable:15,balance:m.totalIssuance}),this.poolsData.set(c,o),{address:c,id:l,type:"Stableswap",fee:y.fromPermill(o.fee.toNumber()),tokens:g,...m,...d,...this.getPoolLimits()}}catch(o){return console.warn(`Skipping pool ${n.toString()}
2
- `,String(o)),null}});return(await Promise.all(s)).filter(n=>n!==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(),n=await this.getLatestPegs(t,i,r),a=this.getRecentPegs(i),o=y.fromPermill(i.maxPegUpdate.toNumber()),l=y.fromPermill(t.fee.toNumber()),[c,m]=D.recalculatePegs(JSON.stringify(a),JSON.stringify(n),r,y.toRaw(o).toString(),y.toRaw(l).toString()),g=Number(c)*1e6;return{pegsFee:y.fromPermill(g),pegs:m}}getDefaultPegs(e){let t=e.fee,r=D.defaultPegs(e.assets.length);return{pegsFee:y.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(([a,o])=>o.toString()),n=s.map(async(a,o)=>{if(a.isOracle){let[l,c,m]=a.asOracle,g=[m.toString(),i[o]].map(b=>Number(b)).sort((b,w)=>b-w),d=await this.api.query.emaOracle.oracles(l,g,c),[{price:h,updatedAt:f}]=d.unwrap(),P=h.n.toString(),B=h.d.toString();return m.toString()===g[0].toString()?[[P,B],f.toString()]:[[B,P],f.toString()]}else if(a.isMmOracle){let l=a.asMmOracle,{price:c,decimals:m,updatedAt:g}=await this.mmOracle.getData(l.toString()),d=10**m;return[[c.toString(),d.toString()],g.toString()]}else{if(a.isValue)return[a.asValue.map(l=>l.toString()),r];throw Error(a.type+" is not supported")}});return Promise.all(n)}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,n]=await Promise.all([this.getPoolDelta(r.id,s,t),this.getPoolPegs(r.id,s,t)]),a=r.tokens.map(o=>o.id===r.id?{...o,balance:i.totalIssuance}:o);Object.assign(r,{tokens:a},i,n)}})})}};var M=require("@galacticcouncil/math-hsm"),V=class{static calculateCollateralInGivenHollarOut(e,t,r){return(0,M.calculate_collateral_in_given_hollar_out)(e,t,r)}static calculateCollateralOutGivenHollarIn(e,t,r){return(0,M.calculate_collateral_out_given_hollar_in)(e,t,r)}static calculateHollarOutGivenCollateralIn(e,t,r){return(0,M.calculate_hollar_out_given_collateral_in)(e,t,r)}static calculateHollarInGivenCollateralOut(e,t,r){return(0,M.calculate_hollar_in_given_collateral_out)(e,t,r)}static calculateImbalance(e,t,r){return(0,M.calculate_imbalance)(e,t,r)}static calculateBuybackLimit(e,t){return(0,M.calculate_buyback_limit)(e,t)}static calculateBuybackPriceWithFee(e,t,r){return(0,M.calculate_buyback_price_with_fee)(e,t,r)}static calculateMaxPrice(e,t){return(0,M.calculate_max_price)(e,t)}};var at=class u extends ae{maxBuyPriceCoefficient;maxInHolding;hollarId;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new u(e)}constructor(e){super(e),this.type="Hsm",this.maxBuyPriceCoefficient=e.maxBuyPriceCoefficient,this.maxInHolding=e.maxInHolding,this.hollarId=e.hollarId,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)}validateBuyConstraints(e,t,r){let s=[];if(e.assetIn===this.hollarId){let i=this.calculateBuybackLimit(e);t.gt(i)&&s.push("MaxBuyBackExceeded");let n=this.calculateBuyPrice(e,t,r),a=this.calculateMaxPrice(e);n.gt(a)&&s.push("MaxBuyPriceExceeded")}return s}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=this.validateBuyConstraints(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.validateBuyConstraints(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=V.calculateHollarInGivenCollateralOut(t.toFixed(0),r.toFixed(0),y.toRaw(this.buyBackFee).toString());return p(s)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),r=V.calculateCollateralInGivenHollarOut(e.toFixed(0),JSON.stringify(t),y.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=V.calculateCollateralOutGivenHollarIn(t.toFixed(0),r.toFixed(0),y.toRaw(this.buyBackFee).toString());return p(s)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),r=V.calculateHollarOutGivenCollateralIn(e.toFixed(0),JSON.stringify(t),y.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=V.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return p(r)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),r=V.calculateBuybackLimit(t.toString(),y.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=V.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(N,e.decimalsOut);return this.calculateInGivenOut(e,t)}spotPriceOutGivenIn(e){let t=A(N,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(N,18).toString(),A(N,r).toString()]:t}isDefaultPeg(e){let[t,r]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&r==="1"}};var hr=require("@polkadot/util-crypto"),yr=require("@polkadot/util");var ot=class extends U{stableClient;constructor(e,t,r){super(e,t),this.stableClient=r}getPoolType(){return"Hsm"}getPoolId(e){let t="hsm:"+e;return(0,hr.encodeAddress)((0,yr.stringToU8a)(t.padEnd(32,"\0")),63)}isSupported(){return this.api.query.hsm!==void 0}async loadPools(){let[e,t,r]=await Promise.all([this.api.consts.hsm.hollarId.toString(),this.api.query.hsm.collaterals.entries(),this.stableClient.getPoolsMem()]);return t.map(([{},i])=>{let n=i.unwrap(),{poolId:a,maxBuyPriceCoefficient:o,maxInHolding:l,purchaseFee:c,buyBackFee:m,buybackRate:g}=n,d=r.find(h=>h.id===a.toString());if(d){let h=this.getPoolId(a.toString());return{...d,address:h,type:"Hsm",tokens:d.tokens.filter(f=>f.id!==a.toString()),hollarId:e,maxBuyPriceCoefficient:p(o.toString()),maxInHolding:p(l.unwrap().toString()),purchaseFee:y.fromPermill(c.toNumber()),buyBackFee:y.fromPermill(m.toNumber()),buyBackRate:y.fromPerbill(g.toNumber())}}}).filter(i=>i!==null)}async getPoolFees(e,t,r){return{}}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return()=>{}}};var de=class extends q{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;hsmClient;clients=[];onChainAssets=[];block=0;disconnectSubscribeNewHeads=null;memRegistry=ne(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new ee(this.api),this.aaveClient=new ke(this.api,t),this.xykClient=new Ue(this.api,t),this.omniClient=new Le(this.api,t),this.lbpClient=new De(this.api,t),this.stableClient=new Ge(this.api,t),this.hsmClient=new ot(this.api,t,this.stableClient),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient,this.hsmClient],this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r})}onNewBlock(e){this.block=e}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?.()}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 ge=class extends de{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 he=class{static get(e){switch(e.type){case"Aave":return Ne.fromPool(e);case"Xyk":return qe.fromPool(e);case"Omnipool":return Me.fromPool(e);case"Lbp":return Ce.fromPool(e);case"Stableswap":return ae.fromPool(e);case"Hsm":return at.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Pr=require("@noble/hashes/sha256"),fr=require("@noble/hashes/utils");function Ct(u){let e=u.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=(0,Pr.sha256)(t);return(0,fr.bytesToHex)(r)}var He=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=8,We=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 He,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let a=i.dequeue();if(!a||a.length>zr)continue;let o=a[a.length-1];(r===null||o[0]===r)&&s.push(a),e.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,a)){let m=[...a];m.push(c),i.enqueue(m)}})}return s}findShortestPaths(e,t,r){let s=[],i=new He,n=[];n.push([t,""]),i.enqueue(n);let a=1/0;for(;i.size()>0;){let o=i.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===r){o.length<a?(a=o.length,s.length=0,s.push(o)):o.length===a&&s.push(o);continue}let c=e.get(l[0]);for(let m of c??[])this.isNotVisited(m,o)&&i.enqueue([...o,m])}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,n]of t){let a=parseInt(i),o=parseInt(n);r.get(a)?.push([o,s])}return r}};function Dt(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 n=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(n)}}}return e}var ze=class{getProposals(e,t,r){let s=r.filter(b=>b.type==="Xyk"),i=r.filter(b=>b.type!=="Xyk"),n=parseInt(e),a=parseInt(t),o=new Set(i.map(b=>b.tokens).flat().map(b=>b.id)),l=o.has(e),c=o.has(t),m=new We,g=b=>{let w=Dt(b),x=Object.keys(w),I=x.flatMap(R=>w[R]);return m.buildAndPopulateGraph(x,I)};if(!l&&!c){let b=s.filter(I=>I.tokens.find(R=>R.id===e)||I.tokens.find(R=>R.id===t)),w=g(b),x=m.findPaths(w,n,a);return this.parsePaths(x)}if(l&&c){let b=g(i),w=m.findPaths(b,n,a);return this.parsePaths(w)}let d=l?t:e,h=s.filter(b=>b.tokens.some(w=>w.id===d)),f=[...i,...h],P=g(f),B=m.findPaths(P,n,a);return this.parsePaths(B)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let n=r[i],a=r[i+1];if(a==null)break;s.push(this.toEdge(n,a))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ye=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new ze,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}async getPools(){return await this.poolService.getPools(this.routerOptions)}async getAllAssets(){let e=await this.getPools(),t=this.getAssets(e);return[...new Map(t).values()]}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(a=>this.validPath(a,s)).map(a=>this.toHops(a,s))}getProposals(e,t,r){let s=`${e}->${t}::${Ct(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,he.get(t)]))}toHops(e,t){return e.map(([r,s,i])=>{let n=t.get(r);return{poolAddress:r,poolId:n?.id,pool:n?.type,assetIn:s,assetOut:i}})}};var Xr=p("100");function Yr(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 Mt(u,e){return N.minus(e.div(u)).multipliedBy(100).decimalPlaces(4)}function Lt(u,e){return e.div(u).minus(N).multipliedBy(100).decimalPlaces(4)}function re(u,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),u.div(Xr).multipliedBy(e).decimalPlaces(0,1)}var lt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(lt||{}),ut=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(ut||{}),qt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(qt||{});var fe=class extends ye{async loadRouteContext(e,t){let r=await super.getPools(),s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(i.length===0)throw new Re(e,t);return{paths:i,pools:r,poolsMap:s}}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,n=s[s.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[r,s]}}getPoolFeeRange(e){let t=e.min?y.toPct(e.min):void 0,r=e.max?y.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),a;if(s)a=await this.toSellSwaps(r,s,n);else{let x=i.map(async R=>await this.toSellSwaps(r,R,n)),I=await Promise.all(x);a=this.findBestSellRoute(I)}let o=a[0],l=a[a.length-1],c=this.isDirectTrade(a),m=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,I)=>x.multipliedBy(I)),g=A(m,l.assetOutDecimals),d=c?l.calculatedOut:this.calculateDelta0Y(o.amountIn,a,n),h=l.amountOut,f=c?l.tradeFeePct:Mt(d,h).toNumber(),P=d.minus(h),B=this.getRouteFeeRange(a),b=o.amountIn.shiftedBy(-1*o.assetInDecimals).multipliedBy(g),w=Pe(d,b);return{type:"Sell",amountIn:o.amountIn,amountOut:l.amountOut,spotPrice:g,tradeFee:P,tradeFeePct:f,tradeFeeRange:B,priceImpactPct:w.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:O(o.amountIn,o.assetInDecimals),amountOut:O(l.amountOut,l.assetOutDecimals),spotPrice:O(g,l.assetOutDecimals),tradeFee:O(P,l.assetOutDecimals),tradeFeePct:f,tradeFeeRange:B,priceImpactPct:w.toNumber(),swaps:a.map(x=>x.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1]:l=e;let c=a.calculateOutGivenIn(o,l);s.push(c)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1].amountOut:l=A(p(e),o.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(o,a),{amountOut:m,calculatedOut:g,feePct:d,errors:h}=a.validateAndSell(o,l,c),f=this.getPoolFeeRange(c),P=a.spotPriceOutGivenIn(o),B=l.shiftedBy(-1*o.decimalsIn).multipliedBy(P),b=Pe(g,B);s.push({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:m,calculatedOut:g,spotPrice:P,tradeFeePct:d,tradeFeeRange:f,priceImpactPct:b.toNumber(),errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===n.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:O(l,o.decimalsIn),amountOut:O(m,o.decimalsOut),calculatedOut:O(g,o.decimalsOut),spotPrice:O(P,o.decimalsOut),tradeFeePct:d,tradeFeeRange:f,priceImpactPct:b.toNumber(),errors:h}}})}return s}async getMostLiquidRoute(e,t){let{paths:r,pools:s,poolsMap:i}=await this.loadRouteContext(e,t),l=s.filter(d=>d.tokens.some(h=>h.id===e)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(h=>h.id===e)).map(d=>d.map(h=>p(h.balance).shiftedBy(-1*h.decimals)).reduce((h,f)=>h.plus(f))).sort((d,h)=>h.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=r.map(async d=>await this.toSellSwaps(l,d,i)),m=await Promise.all(c);return this.findBestSellRoute(m).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r;try{r=await this.loadRouteContext(e,t)}catch{return Promise.resolve(void 0)}let{poolsMap:s}=r,i=await this.getMostLiquidRoute(e,t),n=await this.toSellSwaps("1",i,s),a=n.map(c=>c.spotPrice.shiftedBy(-1*c.assetOutDecimals)).reduce((c,m)=>c.multipliedBy(m)),o=n[n.length-1].assetOutDecimals;return{amount:A(a,o),decimals:o}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,n=s[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),a;if(s)a=await this.toBuySwaps(r,s,n);else{let x=i.map(async R=>await this.toBuySwaps(r,R,n)),I=await Promise.all(x);a=this.findBestBuyRoute(I)}let o=a[a.length-1],l=a[0],c=this.isDirectTrade(a),m=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetInDecimals)).reduce((x,I)=>x.multipliedBy(I)),g=A(m,l.assetInDecimals),d=c?l.calculatedIn:this.calculateDelta0X(o.amountOut,a,n),h=l.amountIn,f=c?l.tradeFeePct:Lt(d,h).toNumber(),P=h.minus(d),B=this.getRouteFeeRange(a),b=o.amountOut.shiftedBy(-1*o.assetOutDecimals).multipliedBy(g),w;return d.isZero()?w=-100:w=Pe(b,d).toNumber(),{type:"Buy",amountOut:o.amountOut,amountIn:l.amountIn,spotPrice:g,tradeFee:P,tradeFeePct:f,tradeFeeRange:B,priceImpactPct:w,swaps:a,toHuman(){return{type:"Buy",amountOut:O(o.amountOut,o.assetOutDecimals),amountIn:O(l.amountIn,l.assetInDecimals),spotPrice:O(g,l.assetInDecimals),tradeFee:O(P,l.assetInDecimals),tradeFeePct:f,tradeFeeRange:B,priceImpactPct:w,swaps:a.map(x=>x.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=e:l=s[0];let c=a.calculateInGivenOut(o,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=A(p(e),o.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(o,a),{amountIn:m,calculatedIn:g,feePct:d,errors:h}=a.validateAndBuy(o,l,c),f=this.getPoolFeeRange(c),P=a.spotPriceInGivenOut(o),B=l.shiftedBy(-1*o.decimalsOut).multipliedBy(P),b;g.isZero()?b=-100:b=Pe(B,g).toNumber(),s.unshift({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:m,amountOut:l,calculatedIn:g,spotPrice:P,tradeFeePct:d,tradeFeeRange:f,priceImpactPct:b,errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===n.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:O(m,o.decimalsIn),amountOut:O(l,o.decimalsOut),calculatedIn:O(g,o.decimalsIn),spotPrice:O(P,o.decimalsIn),tradeFeePct:d,tradeFeeRange:f,priceImpactPct:b,errors:h}}})}return s}};var Ut=6e3,Gt=p(1e15),be=6,ct=-5,mt=6*60*60*1e3,$r=3,Ht=6;var H=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 Se=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??Ut,minBudgetInNative:t.minBudgetInNative??Gt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[n,a]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:l,priceImpactPct:c}=a,m=l[0],g=l[l.length-1],{assetInDecimals:d}=m,{assetOutDecimals:h}=g,f=Math.abs(c),P=this.getMinimumTradeCount(o,n),B=this.getOptimalTradeCount(f),b=i?Math.round(s/i):B,w=Math.ceil(s/P),x=Math.round(s/B),I=Math.round(s/b),R=o.dividedBy(b).decimalPlaces(0,1),L=await this.router.getBestSell(e,t,O(R,d)),z=o.isLessThan(n),Xe=[];z&&Xe.push("OrderTooSmall");let Ye=L.amountOut.multipliedBy(b),gt=this.toBlockPeriod(I),ht=L.tradeFee.multipliedBy(b),yt=H.build(l),$e={assetIn:e,assetOut:t,errors:Xe,frequencyMin:w,frequencyOpt:x,frequency:I,tradeCount:b,tradeFee:ht,tradeImpactPct:L.priceImpactPct,tradePeriod:gt,tradeRoute:yt,type:"Dca"};return{...$e,amountIn:o,amountOut:Ye,tradeAmountIn:L.amountIn,tradeAmountOut:L.amountOut,toHuman(){return{...$e,amountIn:O(o,d),amountOut:O(Ye,h),tradeAmountIn:O(L.amountIn,d),tradeAmountOut:O(L.amountOut,h)}}}}async getMinimumOrderBudget(e){if(C===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(C,e);if(t)return this.minOrderBudget.times(t.amount).div(p(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:a,priceImpactPct:o}=i,l=a[0],c=a[a.length-1],{assetInDecimals:m}=l,{assetOutDecimals:g}=c,d=Math.abs(o),h=this.getTwapTradeCount(d),f=n.dividedBy(h).decimalPlaces(0,1),P=await this.router.getBestSell(l.assetIn,c.assetOut,O(f,m)),B=h===1,b=n.isLessThan(s),w=P.priceImpactPct<ct,x=[];b||B?x.push("OrderTooSmall"):w&&x.push("OrderImpactTooBig");let I=P.amountOut.multipliedBy(h),R=P.tradeFee.multipliedBy(h),L=H.build(a),z={assetIn:e,assetOut:t,errors:x,tradeCount:h,tradeImpactPct:P.priceImpactPct,tradePeriod:be,tradeRoute:L,type:"TwapSell"};return{...z,amountIn:n,amountOut:I,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:R,toHuman(){return{...z,amountIn:O(n,m),amountOut:O(I,g),tradeAmountIn:O(P.amountIn,m),tradeAmountOut:O(P.amountOut,g),tradeFee:O(R,g)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:n,swaps:a,priceImpactPct:o}=i,l=a[0],c=a[a.length-1],{assetInDecimals:m}=l,{assetOutDecimals:g}=c,d=Math.abs(o),h=this.getTwapTradeCount(d),f=n.dividedBy(h).decimalPlaces(0,1),P=await this.router.getBestBuy(l.assetIn,c.assetOut,O(f,g)),B=P.amountIn.multipliedBy(h),b=h===1,w=B.isLessThan(s),x=P.priceImpactPct<ct,I=[];w||b?I.push("OrderTooSmall"):x&&I.push("OrderImpactTooBig");let R=P.tradeFee.multipliedBy(h),L=H.build(a),z={assetIn:e,assetOut:t,errors:I,tradeCount:h,tradeImpactPct:P.priceImpactPct,tradePeriod:be,tradeRoute:L,type:"TwapBuy"};return{...z,amountIn:B,amountOut:n,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:R,toHuman(){return{...z,amountIn:O(B,m),amountOut:O(n,g),tradeAmountIn:O(P.amountIn,m),tradeAmountOut:O(P.amountOut,g),tradeFee:O(R,m)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>mt){let s=mt/(this.blockTime*be);return Math.round(s)}return t}getTwapExecutionTime(e){return e*be*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,Ht)}};var xe=class extends q{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new G(e),this.aaveUtils=new Z(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(),Be)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var pt=class extends xe{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:i,assetOut:n}=s,o=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,n)).amount.isGreaterThanOrEqualTo(o)),l&&e.isGreaterThanOrEqualTo(o)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=re(e,this.slippagePct),a=s.assetIn,o=i.assetOut,l=e.plus(n),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(o,a,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(a,o,t.toFixed(),l.toFixed(),H.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=re(t,this.slippagePct),a=s.assetIn,o=i.assetOut,l=t.minus(n),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(a,o,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(a,o,e.toFixed(),l.toFixed(),H.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let g=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSellAll",g,Be)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=re(e,this.slippagePct),n=r.assetIn,a=s.assetOut,o=e.minus(i),l=this.api.tx.router.sellAll(n,a,o.toFixed(),H.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let m=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",m,Be)}return this.wrapTx("RouterSellAll",l)}};var dt=class extends xe{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradePeriod:i,tradeRoute:n}=this.order,a=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:n}}},null);return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:a}=this.order,o=re(i,this.slippagePct),l=i.minus(o),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:a}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:a}=this.order,o=re(s,this.slippagePct),l=s.plus(o),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:i.toFixed(),maxAmountIn:l.toFixed(),route:a}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var ve=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new pt(this.api,this.evm).setTrade(e)}order(e){return new dt(this.api,this.evm).setOrder(e)}};var Vr={router:{}};function Kr(u,e=Vr){let t=new ce(u),r=new _e(u),s=new ge(u,r),i=new Z(r),n=new fe(s,e.router),a=new Se(n,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:i,router:n,scheduler:a},client:{asset:new ee(u),balance:new G(u),balanceV2:new ue(u)},ctx:{pool:s},evm:r,tx:new ve(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,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,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 ft=Object.defineProperty;var wr=Object.getOwnPropertyDescriptor;var Or=Object.getOwnPropertyNames;var Tr=Object.prototype.hasOwnProperty;var Ir=(u,e)=>{for(var t in e)ft(u,t,{get:e[t],enumerable:!0})},Ar=(u,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Or(e))!Tr.call(u,s)&&s!==t&&ft(u,s,{get:()=>e[s],enumerable:!(r=wr(e,s))||r.enumerable});return u};var Fr=u=>Ar(ft({},"__esModule",{value:!0}),u);var jr={};Ir(jr,{AaveClient:()=>oe,AavePool:()=>Ne,AavePoolClient:()=>Ce,AaveUtils:()=>Z,AssetClient:()=>ee,AssetNotFound:()=>Tt,BASILISK_PARACHAIN_ID:()=>us,BalanceClient:()=>G,BalanceClientV2:()=>ue,BigNumber:()=>v.BigNumber,CachingPoolService:()=>ge,ChainParams:()=>ce,DECIMAL_PLACES:()=>Kt,DEFAULT_BLOCK_TIME:()=>Ut,DEFAULT_MIN_BUDGET:()=>Gt,ERC20:()=>Y,EvmClient:()=>Re,FarmClient:()=>je,H160:()=>ne,HUB_ASSET_ID:()=>we,HYDRADX_PARACHAIN_ID:()=>cs,HYDRADX_SS58_PREFIX:()=>X,INFINITY:()=>Rr,LbpMath:()=>W,LbpPool:()=>ke,LbpPoolClient:()=>De,ONE:()=>N,ORDER_MIN_BLOCK_PERIOD:()=>Ht,OmniMath:()=>R,OmniPool:()=>Me,OmniPoolClient:()=>Le,PERBILL_DENOMINATOR:()=>zt,PERMILL_DENOMINATOR:()=>ie,PolkadotApiClient:()=>q,PoolConfigNotFound:()=>Ot,PoolError:()=>re,PoolFactory:()=>he,PoolNotFound:()=>Ae,PoolService:()=>de,PoolType:()=>_,ProviderConfigNotFound:()=>Ft,RUNTIME_DECIMALS:()=>Oe,RouteNotFound:()=>Fe,Router:()=>ye,SYSTEM_ASSET_DECIMALS:()=>Xt,SYSTEM_ASSET_ID:()=>k,StableMath:()=>D,StableSwap:()=>ae,StableSwapClient:()=>Ge,StorageConfigNotFound:()=>It,SubscriptionNotSupported:()=>At,TRADEABLE_DEFAULT:()=>Te,TWAP_BLOCK_PERIOD:()=>be,TWAP_MAX_DURATION:()=>mt,TWAP_MAX_PRICE_IMPACT:()=>ct,TWAP_TX_MULTIPLIER:()=>$r,TradeOrderError:()=>qt,TradeOrderType:()=>ut,TradeRouteBuilder:()=>H,TradeRouter:()=>Pe,TradeScheduler:()=>Se,TradeType:()=>lt,TxBuilderFactory:()=>ve,XykMath:()=>Q,XykPool:()=>qe,XykPoolClient:()=>Ue,ZERO:()=>x,bnFormatter:()=>Hr,bnum:()=>p,calculateBuyFee:()=>Lt,calculateDiffToAvg:()=>Yr,calculateDiffToRef:()=>fe,calculateSellFee:()=>Mt,createChain:()=>Rt,createSdkContext:()=>Kr,findNestedKey:()=>Ct,findNestedObj:()=>Gr,getFraction:()=>se,hashPools:()=>kt,isEvmAccount:()=>Yt,isEvmAddress:()=>$t,isSs58Address:()=>Vt,scale:()=>F,toBn:()=>Nr,toDecimals:()=>O});module.exports=Fr(jr);var Ve=[{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 Pt=[{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 Wt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",bt="0x112b087b60C1a166130d59266363C45F8aa99db0",St="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Be=1000000n;var is=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var oe=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:Pt,address:bt,args:[St],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:Pt,address:bt,args:[St,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:Ve,address:Wt,args:[e],functionName:"getUserAccountData"})}};var J=require("@polkadot/util-crypto"),le=require("@polkadot/util"),K=require("buffer");var us=2090,ie=1e6,zt=1e9,we="1",cs=2034,X=63,Oe=18,k="0",Xt=12,Te=15;var xt="ETH\0";function Yt(u){if(!u)return!1;try{let e=(0,J.decodeAddress)(u,!0),t=K.Buffer.from(xt);return K.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function $t(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Vt(u){try{let e=(0,le.isHex)(u)?(0,le.hexToU8a)(u):(0,J.decodeAddress)(u);return(0,J.encodeAddress)(e),!0}catch{return!1}}var ne=class u{static toAccount=e=>{let t=K.Buffer.from(e.slice(2),"hex"),r=K.Buffer.from(xt);return(0,J.encodeAddress)(new Uint8Array(K.Buffer.concat([r,t,K.Buffer.alloc(8)])),63)};static fromAccount=e=>{let t=(0,J.decodeAddress)(e),r=K.Buffer.from(xt),s=t.slice(r.length,-8);return"0x"+K.Buffer.from(s).toString("hex")};static fromSS58=e=>{let r=(0,J.decodeAddress)(e).slice(0,20);return(0,le.u8aToHex)(r)};static fromAny=e=>{if($t(e))return e;if(Yt(e))return u.fromAccount(e);if(Vt(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var Ie=require("buffer"),Y=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 v=require("bignumber.js"),Kt=12;v.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Kt});var x=p(0),N=p(1),Rr=p("Infinity");function F(u,e){let t=new v.BigNumber(e.toString()),r=new v.BigNumber(10).pow(t);return u.times(r).decimalPlaces(4)}function p(u){return new v.BigNumber(u.toString())}function Nr(u,e){let t=p(u);return F(t,e)}function O(u,e){return u.shiftedBy(-1*e).toString()}var Ke=p("1e27"),_r=p("1.01"),Er=p("31536000"),Z=class{client;constructor(e){this.client=new oe(e)}async getSummary(e){let t=ne.fromAny(e),[r,s,i,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[a]=r,[o,l]=s,[c,m,h,g,d,b]=i,f=p(b).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN),B=p(c),P=p(m),w=[];for(let S of o){let A=S.underlyingAsset.toLowerCase(),T=a.find(({underlyingAsset:Br})=>Br.toLowerCase()===A);if(!T)throw new Error("Missing pool reserve for "+A);let L=p(S.scaledATokenBalance),z=p(T.liquidityIndex),Xe=p(T.liquidityRate),Ye=p(T.availableLiquidity),gt=p(T.priceInMarketReferenceCurrency),ht=n+6,yt=this.calculateLinearInterest(Xe,T.lastUpdateTimestamp,ht),$e=z.multipliedBy(yt).dividedBy(Ke).decimalPlaces(0,v.BigNumber.ROUND_DOWN),br=L.multipliedBy($e).dividedBy(Ke).decimalPlaces(0,v.BigNumber.ROUND_DOWN),Sr=p(l!==0&&l===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold).div(1e4),xr=T.usageAsCollateralEnabled&&S.usageAsCollateralEnabledOnUser&&p(S.scaledATokenBalance).gt(0),vr=Y.toAssetId(A);w.push({aTokenBalance:br,availableLiquidity:Ye,decimals:Number(T.decimals),isCollateral:xr,priceInRef:gt,reserveId:vr,reserveAsset:A,reserveLiquidationThreshold:Sr})}return{healthFactor:f.toNumber(),totalCollateral:B,totalDebt:P,reserves:w}}async hasBorrowPositions(e){let t=ne.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=ne.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,n,a,o,l]=r;return p(l).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),a=Y.fromAssetId(t),o=n.find(B=>B.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,isCollateral:c,priceInRef:m,reserveLiquidationThreshold:h}=o,g=F(p(r),l).decimalPlaces(0,1),d=c?g.multipliedBy(m).dividedBy(p(10).pow(l)).decimalPlaces(0,v.BigNumber.ROUND_DOWN):x,b=s.minus(d);return b.lte(0)?0:b.multipliedBy(h).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),a=Y.fromAssetId(t),o=n.find(f=>f.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:m}=o,g=F(p(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(p(10).pow(l)).decimalPlaces(0,v.BigNumber.ROUND_DOWN),d=s.plus(g);return d.lte(0)?0:d.multipliedBy(m).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),n=Y.fromAssetId(t),a=s.find(o=>o.reserveAsset===n);if(!a)throw new Error("Missing reserve data for "+n);return this.calculateWithdrawMax(a,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let n of r){let a=this.calculateWithdrawMax(n,t,s);n.reserveId&&(i[n.reserveId]=a)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:n,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let h=p(r).minus(_r);if(h.gt(0)){let d=h.multipliedBy(t).dividedBy(o).decimalPlaces(0,v.BigNumber.ROUND_DOWN).dividedBy(a).multipliedBy(p(10).pow(n)).decimalPlaces(0,v.BigNumber.ROUND_DOWN);c=v.BigNumber.minimum(s,d)}else c=x}return{amount:v.BigNumber.minimum(c,i),decimals:n}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Ke:e.multipliedBy(s).dividedBy(Er).plus(Ke).decimalPlaces(0,v.BigNumber.ROUND_DOWN)}};function jt(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var As=require("@galacticcouncil/api-augment/hydradx"),Fs=require("@galacticcouncil/api-augment/basilisk"),q=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");jt(r)&&console.log(e,...t)}};var ee=class extends q{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==k){let m=this.api.consts.balances.existentialDeposit;return{id:k,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:a,existentialDeposit:o}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:n.toHuman(),isSufficient:a?a.toHuman():!0,location:s?.toJSON(),existentialDeposit:o.toString()}}getBond(e,t,r,s){let[i,n]=s,{assetType:a,isSufficient:o,existentialDeposit:l}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,r),h=n.toNumber(),g=new Intl.DateTimeFormat("en-GB"),d=[c,"Bond",g.format(h)].join(" ");return{id:e,name:d,symbol:c+"b",decimals:m,icon:c,type:a.toString(),isSufficient:o.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:h}}getShares(e,t,r,s){let{assets:i}=s,{name:n,symbol:a,assetType:o,isSufficient:l,existentialDeposit:c}=t,h=i.map(b=>b.toString()).map(b=>{let{symbol:f}=this.getToken(b,t,r);return[b,f]}),g=Object.fromEntries(h),d=Object.values(g);return{id:e,name:d.join(", "),symbol:a?.isSome?a.toHuman():n.toHuman(),decimals:18,icon:d.join("/"),type:o.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:g}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),n=r?.find(a=>a.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:n}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,i,n,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),o=this.getSupportedAssets(r),l=this.normalizeMetadata(o,a),c=o.map(([{args:[m]},h])=>{let g=h.unwrap(),d=s.get(m.toString()),{assetType:b}=g;switch(b.toString()){case"Bond":let f=n.get(m.toString());return this.getBond(m.toString(),g,l,f);case"StableSwap":let B=i.get(m.toString());return this.getShares(m.toString(),g,l,B);case"External":return this.getExternal(m.toString(),g,t,d);default:return this.getToken(m.toString(),g,l,d)}});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 G=class extends q{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===k?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(k,this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,a]})=>[n.toString(),a.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let a=[];n.forEach((o,l)=>{let c=this.calculateFreeBalance(o),m=i[l][1];a.push([m,c])}),t(a)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([o,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[o]}])=>o.toString()))(),n=async()=>{let a=await Promise.all(i.map(async o=>[o,await this.getErc20Balance(e,o)]));t(a)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}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,v.BigNumber)(t).lt(r)?(0,v.BigNumber)(0):(0,v.BigNumber)(t).minus(r)}};var ue=class extends q{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===k?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(k,this.calculateBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,a]})=>[n.toString(),a.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let a=[];n.forEach((o,l)=>{let c=i[l][1],m=this.calculateBalance(o);a.push([c,m])}),t(a)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([o,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[o]}])=>o.toString()))(),n=async()=>{let a=await Promise.all(i.map(async o=>[o,await this.getErc20Balance(e,o)]));t(a)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=(0,v.BigNumber)(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),i=t.gte(r)?t.minus(r).toString():"0",n=t.plus(s).toString();return{free:t.toString(),total:n,transferable:i,reserved:s,frozen:r}}};var ce=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 vt=require("@galacticcouncil/math-liquidity-mining"),Qt=require("@polkadot/types"),Bt=require("@polkadot/util"),wt=require("@polkadot/util-crypto");var je=class extends q{balanceClient;constructor(e){super(e),this.balanceClient=new G(e)}secondsInYear=new v.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,a=i.unwrap().toString(),o=n.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,o,a)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),g=this.getAccountResolver(this.api.registry)(Number(o),!1).toString(),d=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(g,d);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:m,potBalance:b.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,a=i.unwrap().toString(),o=n.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,o,a)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),g=this.getAccountResolver(this.api.registry)(Number(o),!0).toString(),d=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(g,d);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:m,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new v.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),a=n.price.n.toString(),o=n.price.d.toString(),l;return Number(t)<Number(r)?l=(0,vt.fixed_from_rational)(a,o):l=(0,vt.fixed_from_rational)(o,a),l}getGlobalRewardPerPeriod(e,t,r,s){let n=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return n.gte(r)?r:n}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return(0,Bt.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Qt.GenericAccountId32(e,this.padEndU8a((0,Bt.u8aConcat)(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,wt.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,wt.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:a,globalFarm:o,priceAdjustment:l,potBalance:c})=>{let m=new v.BigNumber(o.totalSharesZ.toString()),h=o.plannedYieldingPeriods.toString(),g=new v.BigNumber(o.yieldPerPeriod.toString()),d=new v.BigNumber(o.maxRewardPerPeriod.toString()),b=o.blocksPerPeriod.toString(),f=new v.BigNumber(a.multiplier.toString()).shiftedBy(-18),B=this.secondsInYear.div(new v.BigNumber(r).times(b)),P;if(m.isZero())P=g.times(f).times(B);else{let L=this.getGlobalRewardPerPeriod(m,g,d,l);P=this.getPoolYieldPerPeriod(L,f,m,l).times(B)}let w=new v.BigNumber(o.pendingRewards.toString()).plus(o.accumulatedPaidRewards.toString()),S=d.times(h),A=c?w.plus(c):S;return w.div(A).gte(.999)?x:P.div(t==="isolatedpool"?2:1).times(100)}).reduce((a,o)=>a.plus(o),x).toString():void 0}};var Ae=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Ot=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"}},Tt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},It=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},At=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Ft=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Jt=require("viem"),Cr=["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"],Rt=u=>{let t=[u.endpoint,...Cr],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return(0,Jt.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://explorer.evm.hydration.cloud"}},testnet:!1})};var j=require("viem");function Zt(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{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=Rt(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,j.createPublicClient)({chain:this.chain,transport:(0,j.http)()})}getWsProvider(){return(0,j.createPublicClient)({chain:this.chain,transport:Zt(this.wsProvider)})}getSigner(e){return(0,j.createWalletClient)({account:e,chain:this.chain,transport:(0,j.custom)(window.ethereum)})}};var te=(u,e=new Map)=>t=>{let r;return e.has(t)?e.get(t):(e.set(t,r=u(t)),r)};var _=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n.HSM="Hsm",n))(_||{}),re=(a=>(a.UnknownError="UnknownError",a.InsufficientTradingAmount="InsufficientTradingAmount",a.MaxInRatioExceeded="MaxInRatioExceeded",a.MaxOutRatioExceeded="MaxOutRatioExceeded",a.TradeNotAllowed="TradeNotAllowed",a.MaxBuyBackExceeded="MaxBuyBackExceeded",a.MaxBuyPriceExceeded="MaxBuyPriceExceeded",a))(re||{});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(o=>[o.id,o])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),a=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:a,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 F(N,e.decimalsOut)}spotPriceOutGivenIn(e){return F(N,e.decimalsIn)}calculateTradeFee(e,t){return x}};var lr=require("@polkadot/util-crypto"),ur=require("@polkadot/util"),cr=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 Qe=(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 kr=Qe(()=>"illegal argument(s)"),er=u=>{throw new kr(u)};var Dr=Qe(()=>"index out of bounds"),Nt=u=>{throw new Dr(u)},Je=(u,e,t)=>(u<e||u>=t)&&Nt(u);var tr=23283064365386963e-26,Ze=class{float(e=1){return this.int()*tr*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*tr-.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 et=class extends Ze{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 rr=new et(Math.random);var sr=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var ir=Object.getPrototypeOf({}),tt="function",nr="string",me=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===tt)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===tt)return e.equiv(u)}else return u==e;return typeof u===nr||typeof e===nr?!1:(t=Object.getPrototypeOf(u),(t==null||t===ir)&&(t=Object.getPrototypeOf(e),t==null||t===ir)?Ur(u,e):typeof u!==tt&&u.length!==void 0&&typeof e!==tt&&e.length!==void 0?Mr(u,e):u instanceof Set&&e instanceof Set?Lr(u,e):u instanceof Map&&e instanceof Map?qr(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)},Mr=(u,e,t=me)=>{let r=u.length;if(r===e.length)for(;r-- >0&&t(u[r],e[r]););return r<0},Lr=(u,e,t=me)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),qr=(u,e,t=me)=>u.size===e.size&&t([...u].sort(),[...e].sort()),Ur=(u,e,t=me)=>{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 _t=class{value;constructor(e){this.value=e}deref(){return this.value}};var ar=u=>u instanceof _t;var rt=class u{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return or("next",this._head)}reverseIterator(){return or("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,n=0;for(;r-- >0&&n===0;)n=t(s.value,i.value),s=s.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof u||sr(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(!me(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||_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&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!ar(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&&Nt(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*or(u,e){for(;e;)yield e.value,e=e[u]}var st=class u extends rt{_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):(Je(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):(Je(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=n=>({first(){return n.value},next(){return n!==s&&n.next?i(n.next):void 0}});return r?i(r):void 0}shuffle(e,t=rr){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)&&er("invalid indices: ${from} / ${to}");let i=new u,n=this.nthCell(r);for(;n&&++r<=s;)i.push(n.value),n=n.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,n=0;for(let o=0;o<t&&(n++,i=i.next,!!i);o++);let a=t;for(;n>0||a>0&&i;){let o;n===0?(o=i,i=i.next,a--):!i||a===0||e(r.value,i.value)<=0?(o=r,r=r.next,n--):(o=i,i=i.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}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),Je(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 n of r)this.insertBefore(s,n);else for(let n of r)this.push(n);return i}};var it=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 st,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 pe=class u extends it{constructor(e,t){super(e,{ttl:60*60*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),n=Math.max(0,s-(i?i.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(i,e,t,s,r):this._size-=n,t}async getSet(e,t,r=this.opts.ttl){let s=this.get(e);return s!==void 0?s:this.set(e,await t(),r)}prune(){let e=Date.now(),t=this.items.head,r=0;for(;t;)t.value.t<e&&(this.removeEntry(t),r++),t=t.next;return r}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,r=Date.now(),s=this.items.head;for(;s&&(this._size>t||this.length>=e);)s.value.t<r&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(e,t,r,s,i=this.opts.ttl){let n=Date.now()+i;e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,e.value.t=n,this.items.asTail(e)):(this.items.push({k:t,v:r,s,t:n,ttl:i}),this.map.set(t,this.items.tail))}resetEntry(e){return this.opts.autoExtend&&(e.value.t=Date.now()+e.value.ttl),super.resetEntry(e)}};var Et=[{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 Ee=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.client.readContract({abi:Et,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:Et,address:e,functionName:"decimals"}),this.client.getBlock()]),[n,a,o,l]=r,c=i.number-(i.timestamp-l)/BigInt(t),m=Number(c);return{price:a,decimals:s,updatedAt:m<0?0:m}}};var U=class extends G{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new pe(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=te(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new Ee(t)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools();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=this.augmentedPools.map(async r=>{let s=[],i=await this.subscribeTokensPoolBalance(r);if(s.push(i),this.hasSystemAsset(r)){let n=await this.subscribeSystemPoolBalance(r);s.push(n)}if(this.hasErc20Asset(r)){let n=await this.subscribeErc20PoolBalance(r);s.push(n)}return this.subscribeLog(r),s}),t=await Promise.all(e);return()=>{for(let r of t.flat())try{r()}catch(s){console.warn("Balance unsub failed",s)}}}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t()).catch(t=>console.warn("Unsub failed",t))})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,i])=>{let n=e.tokens.findIndex(a=>a.id==s);n>=0&&t(e,s)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(i=>i.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};function Ct(u,e){let t=[];return JSON.stringify(u,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Gr(u,e,t){let r;return JSON.stringify(u,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Hr=(u,e)=>typeof e=="bigint"?e.toString():e;var Wr=["Supply","Withdraw","Repay","Borrow"],Ce=class extends U{getPoolType(){return"Aave"}getPoolId(e,t){let r="aave:"+e+"/"+t;return(0,lr.encodeAddress)((0,ur.stringToU8a)(r.padEnd(32,"\0")),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}getReserveH160Id(e){return e.type==="Erc20"?Ct(e.location,"accountKey20").accountKey20.key:Y.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{}}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return this.api.query.system.events(e=>{e.forEach(t=>{let{event:r}=t,s=`${r.section}:${r.method}`;if(s==="router:Executed"){let[i,n]=r.data.toJSON();this.pools.filter(a=>a.tokens.some(o=>o.id===i.toString()||o.id===n.toString())).forEach(a=>{this.log(`Sync AAVE via [router:Executed] :: ${i}:${n}`),this.updatePoolState(a)})}if(s==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:n,args:a}=(0,cr.decodeEventLog)({abi:Ve,topics:i.topics,data:i.data});if(Wr.includes(n)){let o=a.reserve.toLowerCase();this.pools.filter(l=>{let[c]=l.tokens;return this.getReserveH160Id(c).toLowerCase()===o}).forEach(l=>{this.log(`Sync AAVE via [evm:Log] :: ${n} ${o}`),this.updatePoolState(l)})}}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(n=>{let a=n.id===t.id?s.toString():i.toString();return{...n,balance:a}})}};var $=require("@galacticcouncil/math-lbp"),W=class{static getSpotPrice(e,t,r,s,i){return(0,$.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,$.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,$.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,$.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,$.calculate_pool_trade_fee)(e,t,r)}};var y=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 ke=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(o=>[o.id,o])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),a=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:a,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let a=this.calculateTradeFee(t,r),o=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(a),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:o,errors:i}}else{let a=this.calculateInGivenOut(e,t),o=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(o)&&i.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let a=this.calculateOutGivenIn(e,t),o=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(o)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:a,feePct:0,errors:i}}else{let a=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(a,r),l=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=a.minus(o),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?x:s}calculateOutGivenIn(e,t){let r=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?x:s}spotPriceInGivenOut(e){let t=W.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),F(N,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=W.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),F(N,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=W.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var De=class extends U{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:n,initialWeight:a,finalWeight:o,repayTarget:l,feeCollector:c}=t,m=W.calculateLinearWeights(s.toString(),i.toString(),a.toString(),o.toString(),r),[h,g]=n,d=h.toString(),b=p(m),f=g.toString(),B=this.MAX_FINAL_WEIGHT.minus(p(b)),[P,w,S]=await Promise.all([this.isRepayFeeApplied(d,l.toString(),c.toString()),this.getBalance(e,d),this.getBalance(e,f)]);return{repayFeeApply:P,tokens:[{id:d,weight:b,balance:w.toString()},{id:f,weight:B,balance:S.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,n])=>this.isActivePool(n.unwrap(),r.toNumber())).map(async([{args:[i]},n])=>{let a=n.unwrap(),o=i.toString(),l=await this.getPoolDelta(o,a,r.toString());this.poolsData.set(i.toString(),a);let[c,m]=a.fee;return{address:o,type:"Lbp",fee:y.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 y.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 n=await this.getPoolDelta(r.address,s,t.toString());Object.assign(r,n)}else{let n=this.pools.findIndex(a=>a.address==r.address);this.pools.splice(n,1)}})})}};var I=require("@galacticcouncil/math-omnipool");var R=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,n,a,o,l){return(0,I.calculate_in_given_out)(e,t,r,s,i,n,a,o,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,n,a,o,l){return(0,I.calculate_out_given_in)(e,t,r,s,i,n,a,o,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,n,a,o){return(0,I.calculate_liquidity_out)(e,t,r,s,i,n,a,o)}static calculateLiquidityLRNAOut(e,t,r,s,i,n,a,o){return(0,I.calculate_liquidity_lrna_out)(e,t,r,s,i,n,a,o)}static calculateCapDifference(e,t,r,s){let i=(0,v.BigNumber)(t),n=(0,v.BigNumber)(e),a=(0,v.BigNumber)(s),l=(0,v.BigNumber)(r).shiftedBy(-18);if(i.div(a).lt(l)){let m=l.times(a).minus(i).times(n),h=i.times((0,v.BigNumber)(1).minus(l));return m.div(h).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,n,a,o,l,c,m){return(0,I.recalculate_asset_fee)(e,t,r,s,i,n,a,o,l,c,m)}static recalculateProtocolFee(e,t,r,s,i,n,a,o,l,c,m){return(0,I.recalculate_protocol_fee)(e,t,r,s,i,n,a,o,l,c,m)}static verifyAssetCap(e,t,r,s){return(0,I.verify_asset_cap)(e,t,r,s)}};var Me=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 n=p(s.balance),a=p(i.balance),o=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:n,balanceOut:a,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),a=s===x?x:n.div(s).multipliedBy(100).decimalPlaces(4),o=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&o.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(h)&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a.toNumber(),errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),a=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),o=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&o.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(h)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a.toNumber(),errors:o}}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?y.toRaw(r.assetFee).toString():x.toString(),r?y.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?y.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?y.toRaw(r.assetFee).toString():x.toString(),r?y.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?y.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 dr=require("@polkadot/util-crypto"),gr=require("@polkadot/util");var mr="omnipool",pr="Short",Le=class extends U{dynamicFees=new Map;dynamicFeesConfiguration=new Map;oracles=new Map;memQueryCache=new pe(null,{ttl:6*1e3});memOracleQuery=te(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(mr,t,pr)},this.memQueryCache);memFeesQuery=te(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);memFeesConfigurationQuery=te(e=>this.api.query.dynamicFees.assetFeeConfiguration(e),this.memQueryCache);getPoolType(){return"Omnipool"}getPoolId(){return(0,dr.encodeAddress)((0,gr.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getOracleKey(e){return e===k?[k,we]:[we,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)]),n=r.map(async([{args:[o]},l])=>{let{hubReserve:c,shares:m,tradable:h,cap:g,protocolShares:d}=l.unwrap(),b=await this.getBalance(t,o.toString());return{id:o.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:h.bits.toNumber(),balance:b.toString(),cap:p(g.toString()),protocolShares:p(d.toString())}}),a=await Promise.all(n);return a.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:a,...this.getPoolLimits()}]}async getPoolFees(e,t,r){let s=t.assetOut,i=t.assetIn,n;if(this.isAssetConfigSupported()&&(n=await this.getDynamicFeesConfiguration(s).then(P=>P.unwrapOr(null))),n?.isFixed){let P=n.asFixed.assetFee.toNumber(),w=n.asFixed.protocolFee.toNumber();return{assetFee:y.fromPermill(P),protocolFee:y.fromPermill(w)}}let[a,o,l]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[c,m,h]=this.getAssetFee(t,e,a,o,n?.isDynamic?n.asDynamic.assetFeeParams:void 0),[g,d,b]=i===we?[0,0,0]:this.getProtocolFee(t,e,a,l,n?.isDynamic?n.asDynamic.protocolFeeParams:void 0),f=c+g,B=h+b;return{assetFee:y.fromPermill(m),protocolFee:y.fromPermill(d),min:y.fromPermill(f),max:y.fromPermill(B)}}getAssetFee(e,t,r,s,i){let{assetOut:n,balanceOut:a}=e,{minFee:o,maxFee:l,decay:c,amplification:m}=i||this.api.consts.dynamicFees.assetFeeParameters,h=y.fromPermill(o.toNumber()),g=y.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),l.toNumber()];let[d]=s.unwrap(),{assetFee:b,timestamp:f}=r.unwrap(),B=Math.max(1,t-f.toNumber()),P=d.volume.bIn.toString(),w=d.volume.bOut.toString(),S=d.liquidity.b.toString();n===k&&(P=d.volume.aIn.toString(),w=d.volume.aOut.toString(),S=d.liquidity.a.toString());let A=y.fromPermill(b.toNumber()),T=R.recalculateAssetFee(P,w,S,"9",a.toString(),y.toRaw(A).toString(),B.toString(),y.toRaw(h).toString(),y.toRaw(g).toString(),c.toString(),m.toString());return[o.toNumber(),Number(T)*1e6,l.toNumber()]}getProtocolFee(e,t,r,s,i){let{assetIn:n,balanceIn:a}=e,{minFee:o,maxFee:l,decay:c,amplification:m}=i||this.api.consts.dynamicFees.protocolFeeParameters,h=y.fromPermill(o.toNumber()),g=y.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),l.toNumber()];let[d]=s.unwrap(),{protocolFee:b,timestamp:f}=r.unwrap(),B=Math.max(1,t-f.toNumber()),P=d.volume.bIn.toString(),w=d.volume.bOut.toString(),S=d.liquidity.b.toString();n===k&&(P=d.volume.aIn.toString(),w=d.volume.aOut.toString(),S=d.liquidity.a.toString());let A=y.fromPermill(b.toNumber()),T=R.recalculateProtocolFee(P,w,S,"9",a.toString(),y.toRaw(A).toString(),B.toString(),y.toRaw(h).toString(),y.toRaw(g).toString(),c.toString(),m.toString());return[o.toNumber(),Number(T)*1e6,l.toNumber()]}async subscribeUpdates(){let[e]=this.pools,t=e.tokens.map(o=>o.id),r=[],s=await this.api.query.omnipool.assets.multi(t,o=>{e.tokens=o.map((l,c)=>{let m=e.tokens[c];if(l.isNone)return m;let h=l.unwrap();return this.updateTokenState(m,h)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,o=>{o.forEach((l,c)=>{let m=t[c];this.dynamicFees.set(m,l)})});if(r.push(i),this.isAssetConfigSupported()){let o=await this.api.query.dynamicFees.assetFeeConfiguration.multi(t,l=>{l.forEach((c,m)=>{let h=t[m];this.dynamicFeesConfiguration.set(h,c)})});r.push(o)}let n=t.map(o=>{let l=this.getOracleKey(o);return[mr,l,pr]}),a=await this.api.query.emaOracle.oracles.multi(n,o=>{o.forEach(async(l,c)=>{let m=n[c],[h,g,d]=m;this.oracles.set(g.join(":"),l)})});return r.push(a),()=>{for(let o of r)try{o()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:n,protocolShares:a}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(n.toString()),protocolShares:p(a.toString()),tradeable:i.bits.toNumber()}}};var E=require("@galacticcouncil/math-xyk"),Q=class{static getSpotPrice(e,t,r){return(0,E.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,E.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,E.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,E.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,E.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,E.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,E.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,E.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,E.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,E.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 n=p(s.balance),a=p(i.balance),o=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:a,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),a=s.plus(i),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&o.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(c)&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),a=s.minus(i),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&o.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(c)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:a,feePct:n,errors:o}}calculateInGivenOut(e,t){let r=Q.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?x:s}calculateOutGivenIn(e,t){let r=Q.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?x:s}spotPriceInGivenOut(e){let t=Q.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=F(N,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=Q.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=F(N,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=Q.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var Ue=class extends U{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(),[n,a]=s.unwrap(),[o,l]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,a.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:o.toString()},{id:a.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 y.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return()=>{}}};var C=require("@galacticcouncil/math-stableswap"),D=class{static getPoolAddress(e){return(0,C.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,C.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,n,a){return(0,C.calculate_in_given_out)(e,t,r,s,i,n,a)}static calculateAddOneAsset(e,t,r,s,i,n,a){return(0,C.calculate_add_one_asset)(e,t,r,s,i,n,a)}static calculateSharesForAmount(e,t,r,s,i,n,a){return(0,C.calculate_shares_for_amount)(e,t,r,s,i,n,a)}static calculateOutGivenIn(e,t,r,s,i,n,a){return(0,C.calculate_out_given_in)(e,t,r,s,i,n,a)}static calculateLiquidityOutOneAsset(e,t,r,s,i,n,a){return(0,C.calculate_liquidity_out_one_asset)(e,t,r,s,i,n,a)}static calculateShares(e,t,r,s,i,n){return(0,C.calculate_shares)(e,t,r,s,i,n)}static calculateSpotPriceWithFee(e,t,r,s,i,n,a,o){return(0,C.calculate_spot_price_with_fee)(e,t,r,s,i,n,a,o)}static recalculatePegs(e,t,r,s,i){let n=(0,C.recalculate_peg)(e,t,r,s,i);return JSON.parse(n)}};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 n=p(s.balance),a=p(i.balance),o=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:a,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),a=s===x?x:n.div(s).multipliedBy(100).decimalPlaces(4),o=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);return(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a.toNumber(),errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),a=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),o=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);return(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a.toNumber(),errors:o}}calculateIn(e,t,r){let s=D.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=p(s);return i.isNegative()?x:i}calculateAddOneAsset(e,t,r){let s=D.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=p(s);return i.isNegative()?x:i}calculateSharesForAmount(e,t,r){let s=D.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.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=D.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(N,e.decimalsIn-e.decimalsOut);return p(t).div(s).decimalPlaces(0,1)}let r=F(N,18-e.decimalsIn);return p(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=D.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=p(s);return i.isNegative()?x:i}calculateWithdrawOneAsset(e,t,r){let s=D.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=p(s);return i.isNegative()?x:i}calculateShares(e,t,r){let s=D.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.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=D.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(N,e.decimalsOut-e.decimalsIn);return p(t).div(s).decimalPlaces(0,1)}let r=F(N,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 nt=require("@polkadot/util-crypto");var Ge=class extends U{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=Number(e),r=D.getPoolAddress(t);return(0,nt.encodeAddress)((0,nt.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:n,finalBlock:a}=t,o=D.calculateAmplification(s.toString(),i.toString(),n.toString(),a.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:o,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async n=>{let[a,o]=await Promise.all([this.api.query.stableswap.assetTradability(t,n.toString()),this.getBalance(e,n.toString())]);return{id:n.toString(),tradeable:a.bits.toNumber(),balance:o.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:[n]},a])=>{try{let o=a.unwrap(),l=n.toString(),c=this.getPoolAddress(l),[m,h,g]=await Promise.all([this.getPoolDelta(l,o,r.toString()),this.getPoolTokens(c,l,o),this.getPoolPegs(l,o,r.toString())]);return h.push({id:l,tradeable:15,balance:m.totalIssuance}),this.poolsData.set(c,o),{address:c,id:l,type:"Stableswap",fee:y.fromPermill(o.fee.toNumber()),tokens:h,...m,...g,...this.getPoolLimits()}}catch(o){return console.warn(`Skipping pool ${n.toString()}
2
+ `,String(o)),null}});return(await Promise.all(s)).filter(n=>n!==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(),n=await this.getLatestPegs(t,i,r),a=this.getRecentPegs(i),o=y.fromPermill(i.maxPegUpdate.toNumber()),l=y.fromPermill(t.fee.toNumber()),[c,m]=D.recalculatePegs(JSON.stringify(a),JSON.stringify(n),r,y.toRaw(o).toString(),y.toRaw(l).toString()),h=Number(c)*1e6;return{pegsFee:y.fromPermill(h),pegs:m}}getDefaultPegs(e){let t=e.fee,r=D.defaultPegs(e.assets.length);return{pegsFee:y.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(([a,o])=>o.toString()),n=s.map(async(a,o)=>{if(a.isOracle){let[l,c,m]=a.asOracle,h=[m.toString(),i[o]].map(P=>Number(P)).sort((P,w)=>P-w),g=await this.api.query.emaOracle.oracles(l,h,c),[{price:d,updatedAt:b}]=g.unwrap(),f=d.n.toString(),B=d.d.toString();return m.toString()===h[0].toString()?[[f,B],b.toString()]:[[B,f],b.toString()]}else if(a.isMmOracle){let l=a.asMmOracle,{price:c,decimals:m,updatedAt:h}=await this.mmOracle.getData(l.toString()),g=10**m;return[[c.toString(),g.toString()],h.toString()]}else{if(a.isValue)return[a.asValue.map(l=>l.toString()),r];throw Error(a.type+" is not supported")}});return Promise.all(n)}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,n]=await Promise.all([this.getPoolDelta(r.id,s,t),this.getPoolPegs(r.id,s,t)]),a=r.tokens.map(o=>o.id===r.id?{...o,balance:i.totalIssuance}:o);Object.assign(r,{tokens:a},i,n)}})})}};var M=require("@galacticcouncil/math-hsm"),V=class{static calculateCollateralInGivenHollarOut(e,t,r){return(0,M.calculate_collateral_in_given_hollar_out)(e,t,r)}static calculateCollateralOutGivenHollarIn(e,t,r){return(0,M.calculate_collateral_out_given_hollar_in)(e,t,r)}static calculateHollarOutGivenCollateralIn(e,t,r){return(0,M.calculate_hollar_out_given_collateral_in)(e,t,r)}static calculateHollarInGivenCollateralOut(e,t,r){return(0,M.calculate_hollar_in_given_collateral_out)(e,t,r)}static calculateImbalance(e,t,r){return(0,M.calculate_imbalance)(e,t,r)}static calculateBuybackLimit(e,t){return(0,M.calculate_buyback_limit)(e,t)}static calculateBuybackPriceWithFee(e,t,r){return(0,M.calculate_buyback_price_with_fee)(e,t,r)}static calculateMaxPrice(e,t){return(0,M.calculate_max_price)(e,t)}};var at=class u extends ae{maxBuyPriceCoefficient;maxInHolding;hollarId;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new u(e)}constructor(e){super(e),this.type="Hsm",this.maxBuyPriceCoefficient=e.maxBuyPriceCoefficient,this.maxInHolding=e.maxInHolding,this.hollarId=e.hollarId,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)}validateBuyConstraints(e,t,r){let s=[];if(e.assetIn===this.hollarId){let i=this.calculateBuybackLimit(e);t.gt(i)&&s.push("MaxBuyBackExceeded");let n=this.calculateBuyPrice(e,t,r),a=this.calculateMaxPrice(e);n.gt(a)&&s.push("MaxBuyPriceExceeded")}return s}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=this.validateBuyConstraints(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.validateBuyConstraints(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=V.calculateHollarInGivenCollateralOut(t.toFixed(0),r.toFixed(0),y.toRaw(this.buyBackFee).toString());return p(s)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),r=V.calculateCollateralInGivenHollarOut(e.toFixed(0),JSON.stringify(t),y.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=V.calculateCollateralOutGivenHollarIn(t.toFixed(0),r.toFixed(0),y.toRaw(this.buyBackFee).toString());return p(s)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),r=V.calculateHollarOutGivenCollateralIn(e.toFixed(0),JSON.stringify(t),y.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=V.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return p(r)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),r=V.calculateBuybackLimit(t.toString(),y.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=V.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(N,e.decimalsOut);return this.calculateInGivenOut(e,t)}spotPriceOutGivenIn(e){let t=F(N,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(N,18).toString(),F(N,r).toString()]:t}isDefaultPeg(e){let[t,r]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&r==="1"}};var hr=require("@polkadot/util-crypto"),yr=require("@polkadot/util");var ot=class extends U{stableClient;constructor(e,t,r){super(e,t),this.stableClient=r}getPoolType(){return"Hsm"}getPoolId(e){let t="hsm:"+e;return(0,hr.encodeAddress)((0,yr.stringToU8a)(t.padEnd(32,"\0")),63)}isSupported(){return this.api.query.hsm!==void 0}async loadPools(){let[e,t,r]=await Promise.all([this.api.consts.hsm.hollarId.toString(),this.api.query.hsm.collaterals.entries(),this.stableClient.getPoolsMem()]);return t.map(([{},i])=>{let n=i.unwrap(),{poolId:a,maxBuyPriceCoefficient:o,maxInHolding:l,purchaseFee:c,buyBackFee:m,buybackRate:h}=n,g=r.find(d=>d.id===a.toString());if(g){let d=this.getPoolId(a.toString());return{...g,address:d,type:"Hsm",tokens:g.tokens.filter(b=>b.id!==a.toString()),hollarId:e,maxBuyPriceCoefficient:p(o.toString()),maxInHolding:p(l.unwrap().toString()),purchaseFee:y.fromPermill(c.toNumber()),buyBackFee:y.fromPermill(m.toNumber()),buyBackRate:y.fromPerbill(h.toNumber())}}}).filter(i=>i!==null)}async getPoolFees(e,t,r){return{}}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return()=>{}}};var de=class extends q{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;hsmClient;clients=[];onChainAssets=[];block=0;disconnectSubscribeNewHeads=null;memRegistry=te(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new ee(this.api),this.aaveClient=new Ce(this.api,t),this.xykClient=new Ue(this.api,t),this.omniClient=new Le(this.api,t),this.lbpClient=new De(this.api,t),this.stableClient=new Ge(this.api,t),this.hsmClient=new ot(this.api,t,this.stableClient),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient,this.hsmClient],this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r})}onNewBlock(e){this.block=e}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?.()}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 ge=class extends de{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 he=class{static get(e){switch(e.type){case"Aave":return Ne.fromPool(e);case"Xyk":return qe.fromPool(e);case"Omnipool":return Me.fromPool(e);case"Lbp":return ke.fromPool(e);case"Stableswap":return ae.fromPool(e);case"Hsm":return at.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var fr=require("@noble/hashes/sha256"),Pr=require("@noble/hashes/utils");function kt(u){let e=u.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=(0,fr.sha256)(t);return(0,Pr.bytesToHex)(r)}var He=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=8,We=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 He,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let a=i.dequeue();if(!a||a.length>zr)continue;let o=a[a.length-1];(r===null||o[0]===r)&&s.push(a),e.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,a)){let m=[...a];m.push(c),i.enqueue(m)}})}return s}findShortestPaths(e,t,r){let s=[],i=new He,n=[];n.push([t,""]),i.enqueue(n);let a=1/0;for(;i.size()>0;){let o=i.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===r){o.length<a?(a=o.length,s.length=0,s.push(o)):o.length===a&&s.push(o);continue}let c=e.get(l[0]);for(let m of c??[])this.isNotVisited(m,o)&&i.enqueue([...o,m])}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,n]of t){let a=parseInt(i),o=parseInt(n);r.get(a)?.push([o,s])}return r}};function Dt(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 n=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(n)}}}return e}var ze=class{getProposals(e,t,r){let s=r.filter(P=>P.type==="Xyk"),i=r.filter(P=>P.type!=="Xyk"),n=parseInt(e),a=parseInt(t),o=new Set(i.map(P=>P.tokens).flat().map(P=>P.id)),l=o.has(e),c=o.has(t),m=new We,h=P=>{let w=Dt(P),S=Object.keys(w),A=S.flatMap(T=>w[T]);return m.buildAndPopulateGraph(S,A)};if(!l&&!c){let P=s.filter(A=>A.tokens.find(T=>T.id===e)||A.tokens.find(T=>T.id===t)),w=h(P),S=m.findPaths(w,n,a);return this.parsePaths(S)}if(l&&c){let P=h(i),w=m.findPaths(P,n,a);return this.parsePaths(w)}let g=l?t:e,d=s.filter(P=>P.tokens.some(w=>w.id===g)),b=[...i,...d],f=h(b),B=m.findPaths(f,n,a);return this.parsePaths(B)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let n=r[i],a=r[i+1];if(a==null)break;s.push(this.toEdge(n,a))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ye=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new ze,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}async getPools(){return await this.poolService.getPools(this.routerOptions)}async getAllAssets(){let e=await this.getPools(),t=this.getAssets(e);return[...new Map(t).values()]}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(a=>this.validPath(a,s)).map(a=>this.toHops(a,s))}getProposals(e,t,r){let s=`${e}->${t}::${kt(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,he.get(t)]))}toHops(e,t){return e.map(([r,s,i])=>{let n=t.get(r);return{poolAddress:r,poolId:n?.id,pool:n?.type,assetIn:s,assetOut:i}})}};var Xr=p("100");function Yr(u,e){return u.minus(e).abs().div(u.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function fe(u,e){return u.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Mt(u,e){return N.minus(e.div(u)).multipliedBy(100).decimalPlaces(4)}function Lt(u,e){return e.div(u).minus(N).multipliedBy(100).decimalPlaces(4)}function se(u,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),u.div(Xr).multipliedBy(e).decimalPlaces(0,1)}var lt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(lt||{}),ut=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(ut||{}),qt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(qt||{});var Pe=class extends ye{async loadRouteContext(e,t){let r=await super.getPools(),s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(i.length===0)throw new Fe(e,t);return{paths:i,pools:r,poolsMap:s}}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,n=s[s.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[r,s]}}getPoolFeeRange(e){let t=e.min?y.toPct(e.min):void 0,r=e.max?y.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),a;if(s)a=await this.toSellSwaps(r,s,n);else{let S=i.map(async T=>await this.toSellSwaps(r,T,n)),A=await Promise.all(S);a=this.findBestSellRoute(A)}let o=a[0],l=a[a.length-1],c=this.isDirectTrade(a),m=a.map(S=>S.spotPrice.shiftedBy(-1*S.assetOutDecimals)).reduce((S,A)=>S.multipliedBy(A)),h=F(m,l.assetOutDecimals),g=c?l.calculatedOut:this.calculateDelta0Y(o.amountIn,a,n),d=l.amountOut,b=c?l.tradeFeePct:Mt(g,d).toNumber(),f=g.minus(d),B=this.getRouteFeeRange(a),P=o.amountIn.shiftedBy(-1*o.assetInDecimals).multipliedBy(h),w=fe(g,P);return{type:"Sell",amountIn:o.amountIn,amountOut:l.amountOut,spotPrice:h,tradeFee:f,tradeFeePct:b,tradeFeeRange:B,priceImpactPct:w.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:O(o.amountIn,o.assetInDecimals),amountOut:O(l.amountOut,l.assetOutDecimals),spotPrice:O(h,l.assetOutDecimals),tradeFee:O(f,l.assetOutDecimals),tradeFeePct:b,tradeFeeRange:B,priceImpactPct:w.toNumber(),swaps:a.map(S=>S.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1]:l=e;let c=a.calculateOutGivenIn(o,l);s.push(c)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1].amountOut:l=F(p(e),o.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(o,a),{amountOut:m,calculatedOut:h,feePct:g,errors:d}=a.validateAndSell(o,l,c),b=this.getPoolFeeRange(c),f=a.spotPriceOutGivenIn(o),B=l.shiftedBy(-1*o.decimalsIn).multipliedBy(f),P=fe(h,B);s.push({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:m,calculatedOut:h,spotPrice:f,tradeFeePct:g,tradeFeeRange:b,priceImpactPct:P.toNumber(),errors:d,isSupply(){return a.type==="Aave"&&a.tokens[0].id===n.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:O(l,o.decimalsIn),amountOut:O(m,o.decimalsOut),calculatedOut:O(h,o.decimalsOut),spotPrice:O(f,o.decimalsOut),tradeFeePct:g,tradeFeeRange:b,priceImpactPct:P.toNumber(),errors:d}}})}return s}async getMostLiquidRoute(e,t){let{paths:r,pools:s,poolsMap:i}=await this.loadRouteContext(e,t),l=s.filter(g=>g.tokens.some(d=>d.id===e)).map(g=>g.type==="Aave"?g.tokens:g.tokens.filter(d=>d.id===e)).map(g=>g.map(d=>p(d.balance).shiftedBy(-1*d.decimals)).reduce((d,b)=>d.plus(b))).sort((g,d)=>d.isLessThan(g)?-1:1)[0].div(100).multipliedBy(.1),c=r.map(async g=>await this.toSellSwaps(l,g,i)),m=await Promise.all(c);return this.findBestSellRoute(m).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut}))}async getBestSpotPrice(e,t){let r;try{r=await this.loadRouteContext(e,t)}catch{return Promise.resolve(void 0)}let{poolsMap:s}=r,i=await this.getMostLiquidRoute(e,t),n=await this.toSellSwaps("1",i,s),a=n.map(c=>c.spotPrice.shiftedBy(-1*c.assetOutDecimals)).reduce((c,m)=>c.multipliedBy(m)),o=n[n.length-1].assetOutDecimals;return{amount:F(a,o),decimals:o}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,n=s[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),a;if(s)a=await this.toBuySwaps(r,s,n);else{let S=i.map(async T=>await this.toBuySwaps(r,T,n)),A=await Promise.all(S);a=this.findBestBuyRoute(A)}let o=a[a.length-1],l=a[0],c=this.isDirectTrade(a),m=a.map(S=>S.spotPrice.shiftedBy(-1*S.assetInDecimals)).reduce((S,A)=>S.multipliedBy(A)),h=F(m,l.assetInDecimals),g=c?l.calculatedIn:this.calculateDelta0X(o.amountOut,a,n),d=l.amountIn,b=c?l.tradeFeePct:Lt(g,d).toNumber(),f=d.minus(g),B=this.getRouteFeeRange(a),P=o.amountOut.shiftedBy(-1*o.assetOutDecimals).multipliedBy(h),w;return g.isZero()?w=-100:w=fe(P,g).toNumber(),{type:"Buy",amountOut:o.amountOut,amountIn:l.amountIn,spotPrice:h,tradeFee:f,tradeFeePct:b,tradeFeeRange:B,priceImpactPct:w,swaps:a,toHuman(){return{type:"Buy",amountOut:O(o.amountOut,o.assetOutDecimals),amountIn:O(l.amountIn,l.assetInDecimals),spotPrice:O(h,l.assetInDecimals),tradeFee:O(f,l.assetInDecimals),tradeFeePct:b,tradeFeeRange:B,priceImpactPct:w,swaps:a.map(S=>S.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=e:l=s[0];let c=a.calculateInGivenOut(o,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=F(p(e),o.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(o,a),{amountIn:m,calculatedIn:h,feePct:g,errors:d}=a.validateAndBuy(o,l,c),b=this.getPoolFeeRange(c),f=a.spotPriceInGivenOut(o),B=l.shiftedBy(-1*o.decimalsOut).multipliedBy(f),P;h.isZero()?P=-100:P=fe(B,h).toNumber(),s.unshift({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:m,amountOut:l,calculatedIn:h,spotPrice:f,tradeFeePct:g,tradeFeeRange:b,priceImpactPct:P,errors:d,isSupply(){return a.type==="Aave"&&a.tokens[0].id===n.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:O(m,o.decimalsIn),amountOut:O(l,o.decimalsOut),calculatedIn:O(h,o.decimalsIn),spotPrice:O(f,o.decimalsIn),tradeFeePct:g,tradeFeeRange:b,priceImpactPct:P,errors:d}}})}return s}};var Ut=6e3,Gt=p(1e15),be=6,ct=-5,mt=6*60*60*1e3,$r=3,Ht=6;var H=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 Se=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??Ut,minBudgetInNative:t.minBudgetInNative??Gt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[n,a]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:l,priceImpactPct:c}=a,m=l[0],h=l[l.length-1],{assetInDecimals:g}=m,{assetOutDecimals:d}=h,b=Math.abs(c),f=this.getMinimumTradeCount(o,n),B=this.getOptimalTradeCount(b),P=i?Math.round(s/i):B,w=Math.ceil(s/f),S=Math.round(s/B),A=Math.round(s/P),T=o.dividedBy(P).decimalPlaces(0,1),L=await this.router.getBestSell(e,t,O(T,g)),z=o.isLessThan(n),Xe=[];z&&Xe.push("OrderTooSmall");let Ye=L.amountOut.multipliedBy(P),gt=this.toBlockPeriod(A),ht=L.tradeFee.multipliedBy(P),yt=H.build(l),$e={assetIn:e,assetOut:t,errors:Xe,frequencyMin:w,frequencyOpt:S,frequency:A,tradeCount:P,tradeFee:ht,tradeImpactPct:L.priceImpactPct,tradePeriod:gt,tradeRoute:yt,type:"Dca"};return{...$e,amountIn:o,amountOut:Ye,tradeAmountIn:L.amountIn,tradeAmountOut:L.amountOut,toHuman(){return{...$e,amountIn:O(o,g),amountOut:O(Ye,d),tradeAmountIn:O(L.amountIn,g),tradeAmountOut:O(L.amountOut,d)}}}}async getMinimumOrderBudget(e){if(k===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(k,e);if(t)return this.minOrderBudget.times(t.amount).div(p(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:a,priceImpactPct:o}=i,l=a[0],c=a[a.length-1],{assetInDecimals:m}=l,{assetOutDecimals:h}=c,g=Math.abs(o),d=this.getTwapTradeCount(g),b=n.dividedBy(d).decimalPlaces(0,1),f=await this.router.getBestSell(l.assetIn,c.assetOut,O(b,m)),B=d===1,P=n.isLessThan(s),w=f.priceImpactPct<ct,S=[];P||B?S.push("OrderTooSmall"):w&&S.push("OrderImpactTooBig");let A=f.amountOut.multipliedBy(d),T=f.tradeFee.multipliedBy(d),L=H.build(a),z={assetIn:e,assetOut:t,errors:S,tradeCount:d,tradeImpactPct:f.priceImpactPct,tradePeriod:be,tradeRoute:L,type:"TwapSell"};return{...z,amountIn:n,amountOut:A,tradeAmountIn:f.amountIn,tradeAmountOut:f.amountOut,tradeFee:T,toHuman(){return{...z,amountIn:O(n,m),amountOut:O(A,h),tradeAmountIn:O(f.amountIn,m),tradeAmountOut:O(f.amountOut,h),tradeFee:O(T,h)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:n,swaps:a,priceImpactPct:o}=i,l=a[0],c=a[a.length-1],{assetInDecimals:m}=l,{assetOutDecimals:h}=c,g=Math.abs(o),d=this.getTwapTradeCount(g),b=n.dividedBy(d).decimalPlaces(0,1),f=await this.router.getBestBuy(l.assetIn,c.assetOut,O(b,h)),B=f.amountIn.multipliedBy(d),P=d===1,w=B.isLessThan(s),S=f.priceImpactPct<ct,A=[];w||P?A.push("OrderTooSmall"):S&&A.push("OrderImpactTooBig");let T=f.tradeFee.multipliedBy(d),L=H.build(a),z={assetIn:e,assetOut:t,errors:A,tradeCount:d,tradeImpactPct:f.priceImpactPct,tradePeriod:be,tradeRoute:L,type:"TwapBuy"};return{...z,amountIn:B,amountOut:n,tradeAmountIn:f.amountIn,tradeAmountOut:f.amountOut,tradeFee:T,toHuman(){return{...z,amountIn:O(B,m),amountOut:O(n,h),tradeAmountIn:O(f.amountIn,m),tradeAmountOut:O(f.amountOut,h),tradeFee:O(T,m)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>mt){let s=mt/(this.blockTime*be);return Math.round(s)}return t}getTwapExecutionTime(e){return e*be*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,Ht)}};var xe=class extends q{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new G(e),this.aaveUtils=new Z(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(),Be)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var pt=class extends xe{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:i,assetOut:n}=s,o=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,n)).amount.isGreaterThanOrEqualTo(o)),l&&e.isGreaterThanOrEqualTo(o)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=se(e,this.slippagePct),a=s.assetIn,o=i.assetOut,l=e.plus(n),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(o,a,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(a,o,t.toFixed(),l.toFixed(),H.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=se(t,this.slippagePct),a=s.assetIn,o=i.assetOut,l=t.minus(n),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(a,o,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(a,o,e.toFixed(),l.toFixed(),H.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let h=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSellAll",h,Be)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=se(e,this.slippagePct),n=r.assetIn,a=s.assetOut,o=e.minus(i),l=this.api.tx.router.sellAll(n,a,o.toFixed(),H.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let m=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",m,Be)}return this.wrapTx("RouterSellAll",l)}};var dt=class extends xe{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradePeriod:i,tradeRoute:n}=this.order,a=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:n}}},null);return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:a}=this.order,o=se(i,this.slippagePct),l=i.minus(o),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:a}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:a}=this.order,o=se(s,this.slippagePct),l=s.plus(o),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:i.toFixed(),maxAmountIn:l.toFixed(),route:a}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var ve=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new pt(this.api,this.evm).setTrade(e)}order(e){return new dt(this.api,this.evm).setOrder(e)}};var Vr={router:{}};function Kr(u,e=Vr){let t=new ce(u),r=new Re(u),s=new ge(u,r),i=new Z(r),n=new Pe(s,e.router),a=new Se(n,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:i,router:n,scheduler:a},client:{asset:new ee(u),balance:new G(u),balanceV2:new ue(u)},ctx:{pool:s},evm:r,tx:new ve(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,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,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});
package/build/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var xe=[{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 Ve=[{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 st="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",$e="0x112b087b60C1a166130d59266363C45F8aa99db0",Ke="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ee=1000000n;var Ps=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var te=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:Ve,address:$e,args:[Ke],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:Ve,address:$e,args:[Ke,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:xe,address:st,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as we,encodeAddress as at}from"@polkadot/util-crypto";import{hexToU8a as Ct,isHex as Dt,u8aToHex as Mt}from"@polkadot/util";import{Buffer as X}from"buffer";var xs=2090,V=1e6,it=1e9,Oe="1",Os=2034,U=63,re=18,E="0",nt=12,se=15;var ze="ETH\0";function Lt(p){if(!p)return!1;try{let e=we(p,!0),t=X.from(ze);return X.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Gt(p){return!!/^0x[a-fA-F0-9]{40}$/.test(p)}function Ut(p){try{let e=Dt(p)?Ct(p):we(p);return at(e),!0}catch{return!1}}var Q=class p{static toAccount=e=>{let t=X.from(e.slice(2),"hex"),r=X.from(ze);return at(new Uint8Array(X.concat([r,t,X.alloc(8)])),63)};static fromAccount=e=>{let t=we(e),r=X.from(ze),s=t.slice(r.length,-8);return"0x"+X.from(s).toString("hex")};static fromSS58=e=>{let r=we(e).slice(0,20);return Mt(r)};static fromAny=e=>{if(Gt(e))return e;if(Lt(e))return p.fromAccount(e);if(Ut(e))return p.fromSS58(e);throw new Error("Unknown address type")}};import{Buffer as Te}from"buffer";var W=class{static fromAssetId(e){let t=Number(e),r=Te.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Te.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Te.from("0000000000000000000000000000000100000000","hex"),r=Te.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as O}from"bignumber.js";var qt=12;O.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:qt});var S=m(0),N=m(1),_s=m("Infinity");function v(p,e){let t=new O(e.toString()),r=new O(10).pow(t);return p.times(r).decimalPlaces(4)}function m(p){return new O(p.toString())}function ks(p,e){let t=m(p);return v(t,e)}function T(p,e){return p.shiftedBy(-1*e).toString()}var Ie=m("1e27"),Ht=m("1.01"),Wt=m("31536000"),$=class{client;constructor(e){this.client=new te(e)}async getSummary(e){let t=Q.fromAny(e),[r,s,i,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[n]=r,[o,l]=s,[c,u,g,d,h,y]=i,P=m(y).dividedBy(1e18).decimalPlaces(6,O.ROUND_DOWN),x=m(c),f=m(u),w=[];for(let B of o){let I=B.underlyingAsset.toLowerCase(),A=n.find(({underlyingAsset:kt})=>kt.toLowerCase()===I);if(!A)throw new Error("Missing pool reserve for "+I);let k=m(B.scaledATokenBalance),G=m(A.liquidityIndex),fe=m(A.liquidityRate),Se=m(A.availableLiquidity),We=m(A.priceInMarketReferenceCurrency),Xe=a+6,Ye=this.calculateLinearInterest(fe,A.lastUpdateTimestamp,Xe),Be=G.multipliedBy(Ye).dividedBy(Ie).decimalPlaces(0,O.ROUND_DOWN),Nt=k.multipliedBy(Be).dividedBy(Ie).decimalPlaces(0,O.ROUND_DOWN),Ft=m(l!==0&&l===A.eModeCategoryId?A.eModeLiquidationThreshold:A.reserveLiquidationThreshold).div(1e4),Et=A.usageAsCollateralEnabled&&B.usageAsCollateralEnabledOnUser&&m(B.scaledATokenBalance).gt(0),_t=W.toAssetId(I);w.push({aTokenBalance:Nt,availableLiquidity:Se,decimals:Number(A.decimals),isCollateral:Et,priceInRef:We,reserveId:_t,reserveAsset:I,reserveLiquidationThreshold:Ft})}return{healthFactor:P.toNumber(),totalCollateral:x,totalDebt:f,reserves:w}}async hasBorrowPositions(e){let t=Q.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=Q.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,a,n,o,l]=r;return m(l).dividedBy(1e18).decimalPlaces(6,O.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:a}=await this.getSummary(e),n=W.fromAssetId(t),o=a.find(x=>x.reserveAsset===n);if(!o)throw new Error("Missing reserve ctx for "+n);let{decimals:l,isCollateral:c,priceInRef:u,reserveLiquidationThreshold:g}=o,d=v(m(r),l).decimalPlaces(0,1),h=c?d.multipliedBy(u).dividedBy(m(10).pow(l)).decimalPlaces(0,O.ROUND_DOWN):S,y=s.minus(h);return y.lte(0)?0:y.multipliedBy(g).dividedBy(i).decimalPlaces(6,O.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:a}=await this.getSummary(e),n=W.fromAssetId(t),o=a.find(P=>P.reserveAsset===n);if(!o)throw new Error("Missing reserve ctx for "+n);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:u}=o,d=v(m(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(m(10).pow(l)).decimalPlaces(0,O.ROUND_DOWN),h=s.plus(d);return h.lte(0)?0:h.multipliedBy(u).dividedBy(i).decimalPlaces(6,O.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),a=W.fromAssetId(t),n=s.find(o=>o.reserveAsset===a);if(!n)throw new Error("Missing reserve data for "+a);return this.calculateWithdrawMax(n,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let a of r){let n=this.calculateWithdrawMax(a,t,s);a.reserveId&&(i[a.reserveId]=n)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:a,priceInRef:n,reserveLiquidationThreshold:o,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let g=m(r).minus(Ht);if(g.gt(0)){let h=g.multipliedBy(t).dividedBy(o).decimalPlaces(0,O.ROUND_DOWN).dividedBy(n).multipliedBy(m(10).pow(a)).decimalPlaces(0,O.ROUND_DOWN);c=O.minimum(s,h)}else c=S}return{amount:O.minimum(c,i),decimals:a}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Ie:e.multipliedBy(s).dividedBy(Wt).plus(Ie).decimalPlaces(0,O.ROUND_DOWN)}};function ot(p){switch(p){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var C=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");ot(r)&&console.log(e,...t)}};var K=class extends C{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==E){let u=this.api.consts.balances.existentialDeposit;return{id:E,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:u.toString()}}let{name:i,assetType:a,isSufficient:n,existentialDeposit:o}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:a.toHuman(),isSufficient:n?n.toHuman():!0,location:s?.toJSON(),existentialDeposit:o.toString()}}getBond(e,t,r,s){let[i,a]=s,{assetType:n,isSufficient:o,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(i.toString(),t,r),g=a.toNumber(),d=new Intl.DateTimeFormat("en-GB"),h=[c,"Bond",d.format(g)].join(" ");return{id:e,name:h,symbol:c+"b",decimals:u,icon:c,type:n.toString(),isSufficient:o.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:g}}getShares(e,t,r,s){let{assets:i}=s,{name:a,symbol:n,assetType:o,isSufficient:l,existentialDeposit:c}=t,g=i.map(y=>y.toString()).map(y=>{let{symbol:P}=this.getToken(y,t,r);return[y,P]}),d=Object.fromEntries(g),h=Object.values(d);return{id:e,name:h.join(", "),symbol:n?.isSome?n.toHuman():a.toHuman(),decimals:18,icon:h.join("/"),type:o.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),a=r?.find(n=>n.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,n]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),o=this.getSupportedAssets(r),l=this.normalizeMetadata(o,n),c=o.map(([{args:[u]},g])=>{let d=g.unwrap(),h=s.get(u.toString()),{assetType:y}=d;switch(y.toString()){case"Bond":let P=a.get(u.toString());return this.getBond(u.toString(),d,l,P);case"StableSwap":let x=i.get(u.toString());return this.getShares(u.toString(),d,l,x);case"External":return this.getExternal(u.toString(),d,t,h);default:return this.getToken(u.toString(),d,l,h)}});return e?c:c.filter(u=>this.isValidAsset(u))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var M=class extends C{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===E?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(E,this.calculateFreeBalance(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,n]})=>[a.toString(),n.toString()]);return this.api.query.tokens.accounts.multi(i,a=>{let n=[];a.forEach((o,l)=>{let c=this.calculateFreeBalance(o),u=i[l][1];n.push([u,c])}),t(n)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([o,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[o]}])=>o.toString()))(),a=async()=>{let n=await Promise.all(i.map(async o=>[o,await this.getErc20Balance(e,o)]));t(n)};return this.api.rpc.chain.subscribeNewHeads(async()=>{a()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let t=e.free.toString(),r=e.frozen.toString();return O(t).lt(r)?O(0):O(t).minus(r)}};var ie=class extends C{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===E?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(E,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,n]})=>[a.toString(),n.toString()]);return this.api.query.tokens.accounts.multi(i,a=>{let n=[];a.forEach((o,l)=>{let c=i[l][1],u=this.calculateBalance(o);n.push([c,u])}),t(n)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([o,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[o]}])=>o.toString()))(),a=async()=>{let n=await Promise.all(i.map(async o=>[o,await this.getErc20Balance(e,o)]));t(n)};return this.api.rpc.chain.subscribeNewHeads(async()=>{a()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=O(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 ne=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),m(this._minOrderBudget)}};import{fixed_from_rational as lt}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as Xt}from"@polkadot/types";import{u8aConcat as ct}from"@polkadot/util";import{isAddress as ut}from"@polkadot/util-crypto";var je=class extends C{balanceClient;constructor(e){super(e),this.balanceClient=new M(e)}secondsInYear=new O(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,n=i.unwrap().toString(),o=a.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,o,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(o),!1).toString(),h=l.rewardCurrency.toString(),y=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:y.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,n=i.unwrap().toString(),o=a.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,o,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(o),!0).toString(),h=l.rewardCurrency.toString(),y=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:y.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new O(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),n=a.price.n.toString(),o=a.price.d.toString(),l;return Number(t)<Number(r)?l=lt(n,o):l=lt(o,n),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 ct(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Xt(e,this.padEndU8a(ct(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!ut(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&ut(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:n,globalFarm:o,priceAdjustment:l,potBalance:c})=>{let u=new O(o.totalSharesZ.toString()),g=o.plannedYieldingPeriods.toString(),d=new O(o.yieldPerPeriod.toString()),h=new O(o.maxRewardPerPeriod.toString()),y=o.blocksPerPeriod.toString(),P=new O(n.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new O(r).times(y)),f;if(u.isZero())f=d.times(P).times(x);else{let k=this.getGlobalRewardPerPeriod(u,d,h,l);f=this.getPoolYieldPerPeriod(k,P,u,l).times(x)}let w=new O(o.pendingRewards.toString()).plus(o.accumulatedPaidRewards.toString()),B=h.times(g),I=c?w.plus(c):B;return w.div(I).gte(.999)?S:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((n,o)=>n.plus(o),S).toString():void 0}};var ve=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},mt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ae=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},pt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},dt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},gt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},ht=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{defineChain as Yt}from"viem";var Vt=["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"],bt=p=>{let t=[p.endpoint,...Vt],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return Yt({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1})};import{createPublicClient as yt,createWalletClient as $t,custom as Kt,http as zt}from"viem";function Pt(p){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return p.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var Re=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=bt(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return yt({chain:this.chain,transport:zt()})}getWsProvider(){return yt({chain:this.chain,transport:Pt(this.wsProvider)})}getSigner(e){return $t({account:e,chain:this.chain,transport:Kt(window.ethereum)})}};import{memoize1 as ns}from"@thi.ng/memoize";var F=(a=>(a.Aave="Aave",a.LBP="Lbp",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="Xyk",a.HSM="Hsm",a))(F||{}),z=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n.MaxBuyBackExceeded="MaxBuyBackExceeded",n.MaxBuyPriceExceeded="MaxBuyPriceExceeded",n))(z||{});var Ne=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(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(o=>[o.id,o])),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=m(s.balance),n=m(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:n,assetInED:S,assetOutED:S}}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 v(N,e.decimalsOut)}spotPriceOutGivenIn(e){return v(N,e.decimalsIn)}calculateTradeFee(e,t){return S}};import{encodeAddress as Jt}from"@polkadot/util-crypto";import{stringToU8a as Zt}from"@polkadot/util";import{decodeEventLog as er}from"viem";import{memoize1 as jt}from"@thi.ng/memoize";import{TLRUCache as Qt}from"@thi.ng/cache";var Qe=[{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 ae=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.client.readContract({abi:Qe,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:Qe,address:e,functionName:"decimals"}),this.client.getBlock()]),[a,n,o,l]=r,c=i.number-(i.timestamp-l)/BigInt(t),u=Number(c);return{price:n,decimals:s,updatedAt:u<0?0:u}}};var D=class extends M{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Qt(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=jt(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new ae(t)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools();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=this.augmentedPools.map(async r=>{let s=[],i=await this.subscribeTokensPoolBalance(r);if(s.push(i),this.hasSystemAsset(r)){let a=await this.subscribeSystemPoolBalance(r);s.push(a)}if(this.hasErc20Asset(r)){let a=await this.subscribeErc20PoolBalance(r);s.push(a)}return this.subscribeLog(r),s}),t=await Promise.all(e);return()=>{for(let r of t.flat())try{r()}catch(s){console.warn("Balance unsub failed",s)}}}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t()).catch(t=>console.warn("Unsub failed",t))})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,i])=>{let a=e.tokens.findIndex(n=>n.id==s);a>=0&&t(e,s)&&(e.tokens[a].balance=i.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(i=>i.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};function ft(p,e){let t=[];return JSON.stringify(p,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function bn(p,e,t){let r;return JSON.stringify(p,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Pn=(p,e)=>typeof e=="bigint"?e.toString():e;var tr=["Supply","Withdraw","Repay","Borrow"],Fe=class extends D{getPoolType(){return"Aave"}getPoolId(e,t){let r="aave:"+e+"/"+t;return Jt(Zt(r.padEnd(32,"\0")),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}getReserveH160Id(e){return e.type==="Erc20"?ft(e.location,"accountKey20").accountKey20.key:W.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{}}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return this.api.query.system.events(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(n=>n.tokens.some(o=>o.id===i.toString()||o.id===a.toString())).forEach(n=>{this.log(`Sync AAVE via [router:Executed] :: ${i}:${a}`),this.updatePoolState(n)})}if(s==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:a,args:n}=er({abi:xe,topics:i.topics,data:i.data});if(tr.includes(a)){let o=n.reserve.toLowerCase();this.pools.filter(l=>{let[c]=l.tokens;return this.getReserveH160Id(c).toLowerCase()===o}).forEach(l=>{this.log(`Sync AAVE via [evm:Log] :: ${a} ${o}`),this.updatePoolState(l)})}}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(a=>{let n=a.id===t.id?s.toString():i.toString();return{...a,balance:n}})}};import{calculate_in_given_out as rr,calculate_out_given_in as sr,calculate_linear_weights as ir,calculate_pool_trade_fee as nr,get_spot_price as ar}from"@galacticcouncil/math-lbp";var q=class{static getSpotPrice(e,t,r,s,i){return ar(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return rr(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return sr(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return ir(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return nr(e,t,r)}};var b=class p{static toPct(e){let[t,r]=e;return p.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return p.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 Ee=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(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(o=>[o.id,o])),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=m(s.balance),n=m(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:n,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 n=this.calculateTradeFee(t,r),o=b.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(n),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:o,errors:i}}else{let n=this.calculateInGivenOut(e,t),o=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(o)&&i.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:n,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 n=this.calculateOutGivenIn(e,t),o=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(o)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:n,feePct:0,errors:i}}else{let n=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(n,r),l=b.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=n.minus(o),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=q.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=q.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=q.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),v(N,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=q.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),v(N,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let r=q.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(r)}};var _e=class extends D{MAX_FINAL_WEIGHT=v(m(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:n,finalWeight:o,repayTarget:l,feeCollector:c}=t,u=q.calculateLinearWeights(s.toString(),i.toString(),n.toString(),o.toString(),r),[g,d]=a,h=g.toString(),y=m(u),P=d.toString(),x=this.MAX_FINAL_WEIGHT.minus(m(y)),[f,w,B]=await Promise.all([this.isRepayFeeApplied(h,l.toString(),c.toString()),this.getBalance(e,h),this.getBalance(e,P)]);return{repayFeeApply:f,tokens:[{id:h,weight:y,balance:w.toString()},{id:P,weight:x,balance:B.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t>=r&&t<s}async isRepayFeeApplied(e,t,r){let s=m(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}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 n=a.unwrap(),o=i.toString(),l=await this.getPoolDelta(o,n,r.toString());this.poolsData.set(i.toString(),n);let[c,u]=n.fee;return{address:o,type:"Lbp",fee:b.fromRate(c.toNumber(),u.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(n=>n.address==r.address);this.pools.splice(a,1)}})})}};import{calculate_in_given_out as or,calculate_lrna_in_given_out as lr,calculate_out_given_in as cr,calculate_out_given_lrna_in as ur,calculate_spot_price as mr,calculate_lrna_spot_price as pr,calculate_shares as dr,calculate_liquidity_out as gr,calculate_liquidity_lrna_out as hr,calculate_liquidity_hub_in as br,is_sell_allowed as Pr,is_buy_allowed as yr,is_add_liquidity_allowed as fr,is_remove_liquidity_allowed as Sr,recalculate_asset_fee as Br,recalculate_protocol_fee as xr,verify_asset_cap as Or}from"@galacticcouncil/math-omnipool";var R=class{static calculateSpotPrice(e,t,r,s){return mr(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return pr(e,t)}static calculateInGivenOut(e,t,r,s,i,a,n,o,l){return or(e,t,r,s,i,a,n,o,l)}static calculateLrnaInGivenOut(e,t,r,s,i){return lr(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,a,n,o,l){return cr(e,t,r,s,i,a,n,o,l)}static calculateOutGivenLrnaIn(e,t,r,s,i){return ur(e,t,r,s,i)}static calculateShares(e,t,r,s){return dr(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,a,n,o){return gr(e,t,r,s,i,a,n,o)}static calculateLiquidityLRNAOut(e,t,r,s,i,a,n,o){return hr(e,t,r,s,i,a,n,o)}static calculateCapDifference(e,t,r,s){let i=O(t),a=O(e),n=O(s),l=O(r).shiftedBy(-18);if(i.div(n).lt(l)){let u=l.times(n).minus(i).times(a),g=i.times(O(1).minus(l));return u.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return br(e,t,r,s)}static isSellAllowed(e){return Pr(e)}static isBuyAllowed(e){return yr(e)}static isAddLiquidityAllowed(e){return fr(e)}static isRemoveLiquidityAllowed(e){return Sr(e)}static recalculateAssetFee(e,t,r,s,i,a,n,o,l,c,u){return Br(e,t,r,s,i,a,n,o,l,c,u)}static recalculateProtocolFee(e,t,r,s,i,a,n,o,l,c,u){return xr(e,t,r,s,i,a,n,o,l,c,u)}static verifyAssetCap(e,t,r,s){return Or(e,t,r,s)}};var ke=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(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=m(s.balance),n=m(i.balance),o=m(s.existentialDeposit),l=m(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:n,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),n=s===S?S:a.div(s).multipliedBy(100).decimalPlaces(4),o=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&o.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(g)&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:n.toNumber(),errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),n=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),o=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&o.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(g)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:n.toNumber(),errors:o}}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():S.toString(),r?b.toRaw(r.protocolFee).toString():S.toString()),i=m(s);return i.isNegative()?S: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():S.toString()),i=m(s);return i.isNegative()?S: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():S.toString(),r?b.toRaw(r.protocolFee).toString():S.toString()),i=m(s);return i.isNegative()?S: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():S.toString()),i=m(s);return i.isNegative()?S: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 m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=R.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=R.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=R.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as wr}from"@polkadot/util-crypto";import{stringToU8a as Tr}from"@polkadot/util";import{memoize1 as St}from"@thi.ng/memoize";import{TLRUCache as Ir}from"@thi.ng/cache";var Bt="omnipool",xt="Short",Ce=class extends D{dynamicFees=new Map;oracles=new Map;memQueryCache=new Ir(null,{ttl:6*1e3});memOracleQuery=St(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(Bt,t,xt)},this.memQueryCache);memFeesQuery=St(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);getPoolType(){return"Omnipool"}getPoolId(){return wr(Tr("modlomnipool".padEnd(32,"\0")),63)}getOracleKey(e){return e===E?[E,Oe]:[Oe,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 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}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:[o]},l])=>{let{hubReserve:c,shares:u,tradable:g,cap:d,protocolShares:h}=l.unwrap(),y=await this.getBalance(t,o.toString());return{id:o.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:g.bits.toNumber(),balance:y.toString(),cap:m(d.toString()),protocolShares:m(h.toString())}}),n=await Promise.all(a);return n.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:n,...this.getPoolLimits()}]}async getPoolFees(e,t,r){let s=t.assetOut,i=t.assetIn,[a,n,o]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[l,c,u]=this.getAssetFee(t,e,a,n),[g,d,h]=i===Oe?[0,0,0]:this.getProtocolFee(t,e,a,o),y=l+g,P=u+h;return{assetFee:b.fromPermill(c),protocolFee:b.fromPermill(d),min:b.fromPermill(y),max:b.fromPermill(P)}}getAssetFee(e,t,r,s){let{assetOut:i,balanceOut:a}=e,{minFee:n,maxFee:o,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,u=b.fromPermill(n.toNumber()),g=b.fromPermill(o.toNumber());if(r.isNone||s.isNone)return[n.toNumber(),n.toNumber(),o.toNumber()];let[d]=s.unwrap(),{assetFee:h,timestamp:y}=r.unwrap(),P=Math.max(1,t-y.toNumber()),x=d.volume.bIn.toString(),f=d.volume.bOut.toString(),w=d.liquidity.b.toString();i===E&&(x=d.volume.aIn.toString(),f=d.volume.aOut.toString(),w=d.liquidity.a.toString());let B=b.fromPermill(h.toNumber()),I=R.recalculateAssetFee(x,f,w,"9",a.toString(),b.toRaw(B).toString(),P.toString(),b.toRaw(u).toString(),b.toRaw(g).toString(),l.toString(),c.toString());return[n.toNumber(),Number(I)*1e6,o.toNumber()]}getProtocolFee(e,t,r,s){let{assetIn:i,balanceIn:a}=e,{minFee:n,maxFee:o,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,u=b.fromPermill(n.toNumber()),g=b.fromPermill(o.toNumber());if(r.isNone||s.isNone)return[n.toNumber(),n.toNumber(),o.toNumber()];let[d]=s.unwrap(),{protocolFee:h,timestamp:y}=r.unwrap(),P=Math.max(1,t-y.toNumber()),x=d.volume.bIn.toString(),f=d.volume.bOut.toString(),w=d.liquidity.b.toString();i===E&&(x=d.volume.aIn.toString(),f=d.volume.aOut.toString(),w=d.liquidity.a.toString());let B=b.fromPermill(h.toNumber()),I=R.recalculateProtocolFee(x,f,w,"9",a.toString(),b.toRaw(B).toString(),P.toString(),b.toRaw(u).toString(),b.toRaw(g).toString(),l.toString(),c.toString());return[n.toNumber(),Number(I)*1e6,o.toNumber()]}async subscribeUpdates(){let[e]=this.pools,t=e.tokens.map(o=>o.id),r=[],s=await this.api.query.omnipool.assets.multi(t,o=>{e.tokens=o.map((l,c)=>{let u=e.tokens[c];if(l.isNone)return u;let g=l.unwrap();return this.updateTokenState(u,g)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,o=>{o.forEach((l,c)=>{let u=t[c];this.dynamicFees.set(u,l)})});r.push(i);let a=t.map(o=>{let l=this.getOracleKey(o);return[Bt,l,xt]}),n=await this.api.query.emaOracle.oracles.multi(a,o=>{o.forEach(async(l,c)=>{let u=a[c],[g,d,h]=u;this.oracles.set(d.join(":"),l)})});return r.push(n),()=>{for(let o of r)try{o()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:a,protocolShares:n}=t;return{...e,hubReserves:m(r.toString()),shares:m(s.toString()),cap:m(a.toString()),protocolShares:m(n.toString()),tradeable:i.bits.toNumber()}}};import{calculate_in_given_out as vr,calculate_out_given_in as Ar,calculate_pool_trade_fee as Rr,get_spot_price as Nr,calculate_liquidity_in as Fr,calculate_shares as Er,calculate_spot_price as _r,calculate_spot_price_with_fee as kr,calculate_liquidity_out_asset_a as Cr,calculate_liquidity_out_asset_b as Dr}from"@galacticcouncil/math-xyk";var Y=class{static getSpotPrice(e,t,r){return Nr(e,t,r)}static calculateInGivenOut(e,t,r){return vr(e,t,r)}static calculateOutGivenIn(e,t,r){return Ar(e,t,r)}static calculatePoolTradeFee(e,t,r){return Rr(e,t,r)}static calculateLiquidityIn(e,t,r){return Fr(e,t,r)}static calculateSpotPrice(e,t){return _r(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return kr(e,t,r,s)}static calculateShares(e,t,r){return Er(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return Cr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Dr(e,t,r,s)}};var De=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(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=m(s.balance),n=m(i.balance),o=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:n,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),a=b.toPct(r.exchangeFee),n=s.plus(i),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&o.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(c)&&o.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:t,feePct:a,errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),a=b.toPct(r.exchangeFee),n=s.minus(i),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&o.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(c)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:a,errors:o}}calculateInGivenOut(e,t){let r=Y.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=Y.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=Y.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=v(N,18-e.decimalsOut);return m(t).div(r)}spotPriceOutGivenIn(e){let t=Y.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=v(N,18-e.decimalsIn);return m(t).div(r)}calculateTradeFee(e,t){let r=Y.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(r)}};var Me=class extends D{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,n]=s.unwrap(),[o,l]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,n.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:o.toString()},{id:n.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()=>{}}};import{calculate_in_given_out as Mr,calculate_out_given_in as Lr,calculate_amplification as Gr,calculate_add_one_asset as Ur,calculate_liquidity_out_one_asset as qr,calculate_shares as Hr,calculate_shares_for_amount as Wr,calculate_spot_price_with_fee as Xr,pool_account_name as Yr,recalculate_peg as Vr}from"@galacticcouncil/math-stableswap";var _=class{static getPoolAddress(e){return Yr(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 Gr(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,a,n){return Mr(e,t,r,s,i,a,n)}static calculateAddOneAsset(e,t,r,s,i,a,n){return Ur(e,t,r,s,i,a,n)}static calculateSharesForAmount(e,t,r,s,i,a,n){return Wr(e,t,r,s,i,a,n)}static calculateOutGivenIn(e,t,r,s,i,a,n){return Lr(e,t,r,s,i,a,n)}static calculateLiquidityOutOneAsset(e,t,r,s,i,a,n){return qr(e,t,r,s,i,a,n)}static calculateShares(e,t,r,s,i,a){return Hr(e,t,r,s,i,a)}static calculateSpotPriceWithFee(e,t,r,s,i,a,n,o){return Xr(e,t,r,s,i,a,n,o)}static recalculatePegs(e,t,r,s,i){let a=Vr(e,t,r,s,i);return JSON.parse(a)}};var J=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(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=m(s.balance),n=m(i.balance),o=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:n,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),n=s===S?S:a.div(s).multipliedBy(100).decimalPlaces(4),o=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);return(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:n.toNumber(),errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),n=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),o=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);return(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:n.toNumber(),errors:o}}calculateIn(e,t,r){let s=_.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?b.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=m(s);return i.isNegative()?S:i}calculateAddOneAsset(e,t,r){let s=_.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?b.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=m(s);return i.isNegative()?S:i}calculateSharesForAmount(e,t,r){let s=_.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?b.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=m(s);return i.isNegative()?S:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let s=v(N,e.decimalsIn-e.decimalsOut);return m(t).div(s).decimalPlaces(0,1)}let r=v(N,18-e.decimalsIn);return m(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=_.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?b.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=m(s);return i.isNegative()?S:i}calculateWithdrawOneAsset(e,t,r){let s=_.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?b.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=m(s);return i.isNegative()?S:i}calculateShares(e,t,r){let s=_.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?b.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=m(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let s=v(N,e.decimalsOut-e.decimalsIn);return m(t).div(s).decimalPlaces(0,1)}let r=v(N,18-e.decimalsOut);return m(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])}};import{blake2AsHex as $r,encodeAddress as Kr}from"@polkadot/util-crypto";var Le=class extends D{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=Number(e),r=_.getPoolAddress(t);return Kr($r(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:n}=t,o=_.calculateAmplification(s.toString(),i.toString(),a.toString(),n.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:o,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async a=>{let[n,o]=await Promise.all([this.api.query.stableswap.assetTradability(t,a.toString()),this.getBalance(e,a.toString())]);return{id:a.toString(),tradeable:n.bits.toNumber(),balance:o.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]},n])=>{try{let o=n.unwrap(),l=a.toString(),c=this.getPoolAddress(l),[u,g,d]=await Promise.all([this.getPoolDelta(l,o,r.toString()),this.getPoolTokens(c,l,o),this.getPoolPegs(l,o,r.toString())]);return g.push({id:l,tradeable:15,balance:u.totalIssuance}),this.poolsData.set(c,o),{address:c,id:l,type:"Stableswap",fee:b.fromPermill(o.fee.toNumber()),tokens:g,...u,...d,...this.getPoolLimits()}}catch(o){return console.warn(`Skipping pool ${a.toString()}
2
- `,String(o)),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),n=this.getRecentPegs(i),o=b.fromPermill(i.maxPegUpdate.toNumber()),l=b.fromPermill(t.fee.toNumber()),[c,u]=_.recalculatePegs(JSON.stringify(n),JSON.stringify(a),r,b.toRaw(o).toString(),b.toRaw(l).toString()),g=Number(c)*1e6;return{pegsFee:b.fromPermill(g),pegs:u}}getDefaultPegs(e){let t=e.fee,r=_.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(([n,o])=>o.toString()),a=s.map(async(n,o)=>{if(n.isOracle){let[l,c,u]=n.asOracle,g=[u.toString(),i[o]].map(f=>Number(f)).sort((f,w)=>f-w),d=await this.api.query.emaOracle.oracles(l,g,c),[{price:h,updatedAt:y}]=d.unwrap(),P=h.n.toString(),x=h.d.toString();return u.toString()===g[0].toString()?[[P,x],y.toString()]:[[x,P],y.toString()]}else if(n.isMmOracle){let l=n.asMmOracle,{price:c,decimals:u,updatedAt:g}=await this.mmOracle.getData(l.toString()),d=10**u;return[[c.toString(),d.toString()],g.toString()]}else{if(n.isValue)return[n.asValue.map(l=>l.toString()),r];throw Error(n.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)]),n=r.tokens.map(o=>o.id===r.id?{...o,balance:i.totalIssuance}:o);Object.assign(r,{tokens:n},i,a)}})})}};import{calculate_collateral_in_given_hollar_out as zr,calculate_collateral_out_given_hollar_in as jr,calculate_hollar_in_given_collateral_out as Qr,calculate_hollar_out_given_collateral_in as Jr,calculate_imbalance as Zr,calculate_max_price as es,calculate_buyback_limit as ts,calculate_buyback_price_with_fee as rs}from"@galacticcouncil/math-hsm";var H=class{static calculateCollateralInGivenHollarOut(e,t,r){return zr(e,t,r)}static calculateCollateralOutGivenHollarIn(e,t,r){return jr(e,t,r)}static calculateHollarOutGivenCollateralIn(e,t,r){return Jr(e,t,r)}static calculateHollarInGivenCollateralOut(e,t,r){return Qr(e,t,r)}static calculateImbalance(e,t,r){return Zr(e,t,r)}static calculateBuybackLimit(e,t){return ts(e,t)}static calculateBuybackPriceWithFee(e,t,r){return rs(e,t,r)}static calculateMaxPrice(e,t){return es(e,t)}};var Ge=class p extends J{maxBuyPriceCoefficient;maxInHolding;hollarId;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new p(e)}constructor(e){super(e),this.type="Hsm",this.maxBuyPriceCoefficient=e.maxBuyPriceCoefficient,this.maxInHolding=e.maxInHolding,this.hollarId=e.hollarId,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)}validateBuyConstraints(e,t,r){let s=[];if(e.assetIn===this.hollarId){let i=this.calculateBuybackLimit(e);t.gt(i)&&s.push("MaxBuyBackExceeded");let a=this.calculateBuyPrice(e,t,r),n=this.calculateMaxPrice(e);a.gt(n)&&s.push("MaxBuyPriceExceeded")}return s}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=this.validateBuyConstraints(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.validateBuyConstraints(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=H.calculateHollarInGivenCollateralOut(t.toFixed(0),r.toFixed(0),b.toRaw(this.buyBackFee).toString());return m(s)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),r=H.calculateCollateralInGivenHollarOut(e.toFixed(0),JSON.stringify(t),b.toRaw(this.purchaseFee).toString());return m(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=H.calculateCollateralOutGivenHollarIn(t.toFixed(0),r.toFixed(0),b.toRaw(this.buyBackFee).toString());return m(s)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),r=H.calculateHollarOutGivenCollateralIn(e.toFixed(0),JSON.stringify(t),b.toRaw(this.purchaseFee).toString());return m(r)}calculateOutGivenIn(e,t){return e.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(e,t):this.calculateHollarOutGivenCollateralIn(t)}calculateImbalance(e){let t=this.getCollateralPeg(),r=H.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return m(r)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),r=H.calculateBuybackLimit(t.toString(),b.toRaw(this.buyBackRate).toString());return m(r)}calculateBuyPrice(e,t,r){let s=t.dividedBy(m(10).pow(e.decimalsIn));return r.dividedBy(m(10).pow(e.decimalsOut)).dividedBy(s)}calculateMaxPrice(e){let t=this.getCollateralPeg(),r=H.calculateMaxPrice(JSON.stringify(t),this.maxBuyPriceCoefficient.toFixed(0)),[s,i]=JSON.parse(r);return m(s).div(m(i)).shiftedBy(-1*e.decimalsOut)}spotPriceInGivenOut(e){let t=v(N,e.decimalsOut);return this.calculateInGivenOut(e,t)}spotPriceOutGivenIn(e){let t=v(N,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)?[v(N,18).toString(),v(N,r).toString()]:t}isDefaultPeg(e){let[t,r]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&r==="1"}};import{encodeAddress as ss}from"@polkadot/util-crypto";import{stringToU8a as is}from"@polkadot/util";var Ue=class extends D{stableClient;constructor(e,t,r){super(e,t),this.stableClient=r}getPoolType(){return"Hsm"}getPoolId(e){let t="hsm:"+e;return ss(is(t.padEnd(32,"\0")),63)}isSupported(){return this.api.query.hsm!==void 0}async loadPools(){let[e,t,r]=await Promise.all([this.api.consts.hsm.hollarId.toString(),this.api.query.hsm.collaterals.entries(),this.stableClient.getPoolsMem()]);return t.map(([{},i])=>{let a=i.unwrap(),{poolId:n,maxBuyPriceCoefficient:o,maxInHolding:l,purchaseFee:c,buyBackFee:u,buybackRate:g}=a,d=r.find(h=>h.id===n.toString());if(d){let h=this.getPoolId(n.toString());return{...d,address:h,type:"Hsm",tokens:d.tokens.filter(y=>y.id!==n.toString()),hollarId:e,maxBuyPriceCoefficient:m(o.toString()),maxInHolding:m(l.unwrap().toString()),purchaseFee:b.fromPermill(c.toNumber()),buyBackFee:b.fromPermill(u.toNumber()),buyBackRate:b.fromPerbill(g.toNumber())}}}).filter(i=>i!==null)}async getPoolFees(e,t,r){return{}}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return()=>{}}};var oe=class extends C{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;hsmClient;clients=[];onChainAssets=[];block=0;disconnectSubscribeNewHeads=null;memRegistry=ns(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new K(this.api),this.aaveClient=new Fe(this.api,t),this.xykClient=new Me(this.api,t),this.omniClient=new Ce(this.api,t),this.lbpClient=new _e(this.api,t),this.stableClient=new Le(this.api,t),this.hsmClient=new Ue(this.api,t,this.stableClient),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient,this.hsmClient],this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r})}onNewBlock(e){this.block=e}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?.()}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 ve(t.type)}}};var le=class extends oe{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 ce=class{static get(e){switch(e.type){case"Aave":return Ne.fromPool(e);case"Xyk":return De.fromPool(e);case"Omnipool":return ke.fromPool(e);case"Lbp":return Ee.fromPool(e);case"Stableswap":return J.fromPool(e);case"Hsm":return Ge.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{sha256 as as}from"@noble/hashes/sha256";import{bytesToHex as os}from"@noble/hashes/utils";function Ot(p){let e=p.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=as(t);return os(r)}var ue=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 ls=8,me=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 ue,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let n=i.dequeue();if(!n||n.length>ls)continue;let o=n[n.length-1];(r===null||o[0]===r)&&s.push(n),e.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,n)){let u=[...n];u.push(c),i.enqueue(u)}})}return s}findShortestPaths(e,t,r){let s=[],i=new ue,a=[];a.push([t,""]),i.enqueue(a);let n=1/0;for(;i.size()>0;){let o=i.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===r){o.length<n?(n=o.length,s.length=0,s.push(o)):o.length===n&&s.push(o);continue}let c=e.get(l[0]);for(let u of c??[])this.isNotVisited(u,o)&&i.enqueue([...o,u])}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 n=parseInt(i),o=parseInt(a);r.get(n)?.push([o,s])}return r}};function Je(p){let e={};for(let t of p){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let 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 pe=class{getProposals(e,t,r){let s=r.filter(f=>f.type==="Xyk"),i=r.filter(f=>f.type!=="Xyk"),a=parseInt(e),n=parseInt(t),o=new Set(i.map(f=>f.tokens).flat().map(f=>f.id)),l=o.has(e),c=o.has(t),u=new me,g=f=>{let w=Je(f),B=Object.keys(w),I=B.flatMap(A=>w[A]);return u.buildAndPopulateGraph(B,I)};if(!l&&!c){let f=s.filter(I=>I.tokens.find(A=>A.id===e)||I.tokens.find(A=>A.id===t)),w=g(f),B=u.findPaths(w,a,n);return this.parsePaths(B)}if(l&&c){let f=g(i),w=u.findPaths(f,a,n);return this.parsePaths(w)}let d=l?t:e,h=s.filter(f=>f.tokens.some(w=>w.id===d)),y=[...i,...h],P=g(y),x=u.findPaths(P,a,n);return this.parsePaths(x)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let a=r[i],n=r[i+1];if(n==null)break;s.push(this.toEdge(a,n))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var de=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new pe,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}async getPools(){return await this.poolService.getPools(this.routerOptions)}async getAllAssets(){let e=await this.getPools(),t=this.getAssets(e);return[...new Map(t).values()]}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(n=>this.validPath(n,s)).map(n=>this.toHops(n,s))}getProposals(e,t,r){let s=`${e}->${t}::${Ot(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,ce.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 cs=m("100");function du(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ge(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function wt(p,e){return N.minus(e.div(p)).multipliedBy(100).decimalPlaces(4)}function Tt(p,e){return e.div(p).minus(N).multipliedBy(100).decimalPlaces(4)}function j(p,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),p.div(cs).multipliedBy(e).decimalPlaces(0,1)}var Ze=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Ze||{}),et=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(et||{}),It=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(It||{});var he=class extends de{async loadRouteContext(e,t){let r=await super.getPools(),s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(i.length===0)throw new Ae(e,t);return{paths:i,pools:r,poolsMap: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){let{paths:i,poolsMap:a}=await this.loadRouteContext(e,t),n;if(s)n=await this.toSellSwaps(r,s,a);else{let B=i.map(async A=>await this.toSellSwaps(r,A,a)),I=await Promise.all(B);n=this.findBestSellRoute(I)}let o=n[0],l=n[n.length-1],c=this.isDirectTrade(n),u=n.map(B=>B.spotPrice.shiftedBy(-1*B.assetOutDecimals)).reduce((B,I)=>B.multipliedBy(I)),g=v(u,l.assetOutDecimals),d=c?l.calculatedOut:this.calculateDelta0Y(o.amountIn,n,a),h=l.amountOut,y=c?l.tradeFeePct:wt(d,h).toNumber(),P=d.minus(h),x=this.getRouteFeeRange(n),f=o.amountIn.shiftedBy(-1*o.assetInDecimals).multipliedBy(g),w=ge(d,f);return{type:"Sell",amountIn:o.amountIn,amountOut:l.amountOut,spotPrice:g,tradeFee:P,tradeFeePct:y,tradeFeeRange:x,priceImpactPct:w.toNumber(),swaps:n,toHuman(){return{type:"Sell",amountIn:T(o.amountIn,o.assetInDecimals),amountOut:T(l.amountOut,l.assetOutDecimals),spotPrice:T(g,l.assetOutDecimals),tradeFee:T(P,l.assetOutDecimals),tradeFeePct:y,tradeFeeRange:x,priceImpactPct:w.toNumber(),swaps:n.map(B=>B.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],n=r.get(a.poolAddress);if(n==null)throw new Error("Pool does not exit");let o=n.parsePair(a.assetIn,a.assetOut),l;i>0?l=s[i-1]:l=e;let c=n.calculateOutGivenIn(o,l);s.push(c)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],n=r.get(a.poolAddress);if(n==null)throw new Error("Pool does not exit");let o=n.parsePair(a.assetIn,a.assetOut),l;i>0?l=s[i-1].amountOut:l=v(m(e),o.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(o,n),{amountOut:u,calculatedOut:g,feePct:d,errors:h}=n.validateAndSell(o,l,c),y=this.getPoolFeeRange(c),P=n.spotPriceOutGivenIn(o),x=l.shiftedBy(-1*o.decimalsIn).multipliedBy(P),f=ge(g,x);s.push({...a,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:u,calculatedOut:g,spotPrice:P,tradeFeePct:d,tradeFeeRange:y,priceImpactPct:f.toNumber(),errors:h,isSupply(){return n.type==="Aave"&&n.tokens[0].id===a.assetIn},isWithdraw(){return n.type==="Aave"&&n.tokens[1].id===a.assetIn},toHuman(){return{...a,amountIn:T(l,o.decimalsIn),amountOut:T(u,o.decimalsOut),calculatedOut:T(g,o.decimalsOut),spotPrice:T(P,o.decimalsOut),tradeFeePct:d,tradeFeeRange:y,priceImpactPct:f.toNumber(),errors:h}}})}return s}async getMostLiquidRoute(e,t){let{paths:r,pools:s,poolsMap:i}=await this.loadRouteContext(e,t),l=s.filter(d=>d.tokens.some(h=>h.id===e)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(h=>h.id===e)).map(d=>d.map(h=>m(h.balance).shiftedBy(-1*h.decimals)).reduce((h,y)=>h.plus(y))).sort((d,h)=>h.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=r.map(async d=>await this.toSellSwaps(l,d,i)),u=await Promise.all(c);return this.findBestSellRoute(u).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r;try{r=await this.loadRouteContext(e,t)}catch{return Promise.resolve(void 0)}let{poolsMap:s}=r,i=await this.getMostLiquidRoute(e,t),a=await this.toSellSwaps("1",i,s),n=a.map(c=>c.spotPrice.shiftedBy(-1*c.assetOutDecimals)).reduce((c,u)=>c.multipliedBy(u)),o=a[a.length-1].assetOutDecimals;return{amount:v(n,o),decimals:o}}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){let{paths:i,poolsMap:a}=await this.loadRouteContext(e,t),n;if(s)n=await this.toBuySwaps(r,s,a);else{let B=i.map(async A=>await this.toBuySwaps(r,A,a)),I=await Promise.all(B);n=this.findBestBuyRoute(I)}let o=n[n.length-1],l=n[0],c=this.isDirectTrade(n),u=n.map(B=>B.spotPrice.shiftedBy(-1*B.assetInDecimals)).reduce((B,I)=>B.multipliedBy(I)),g=v(u,l.assetInDecimals),d=c?l.calculatedIn:this.calculateDelta0X(o.amountOut,n,a),h=l.amountIn,y=c?l.tradeFeePct:Tt(d,h).toNumber(),P=h.minus(d),x=this.getRouteFeeRange(n),f=o.amountOut.shiftedBy(-1*o.assetOutDecimals).multipliedBy(g),w;return d.isZero()?w=-100:w=ge(f,d).toNumber(),{type:"Buy",amountOut:o.amountOut,amountIn:l.amountIn,spotPrice:g,tradeFee:P,tradeFeePct:y,tradeFeeRange:x,priceImpactPct:w,swaps:n,toHuman(){return{type:"Buy",amountOut:T(o.amountOut,o.assetOutDecimals),amountIn:T(l.amountIn,l.assetInDecimals),spotPrice:T(g,l.assetInDecimals),tradeFee:T(P,l.assetInDecimals),tradeFeePct:y,tradeFeeRange:x,priceImpactPct:w,swaps:n.map(B=>B.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],n=r.get(a.poolAddress);if(n==null)throw new Error("Pool does not exit");let o=n.parsePair(a.assetIn,a.assetOut),l;i==t.length-1?l=e:l=s[0];let c=n.calculateInGivenOut(o,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],n=r.get(a.poolAddress);if(n==null)throw new Error("Pool does not exit");let o=n.parsePair(a.assetIn,a.assetOut),l;i==t.length-1?l=v(m(e),o.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(o,n),{amountIn:u,calculatedIn:g,feePct:d,errors:h}=n.validateAndBuy(o,l,c),y=this.getPoolFeeRange(c),P=n.spotPriceInGivenOut(o),x=l.shiftedBy(-1*o.decimalsOut).multipliedBy(P),f;g.isZero()?f=-100:f=ge(x,g).toNumber(),s.unshift({...a,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:u,amountOut:l,calculatedIn:g,spotPrice:P,tradeFeePct:d,tradeFeeRange:y,priceImpactPct:f,errors:h,isSupply(){return n.type==="Aave"&&n.tokens[0].id===a.assetIn},isWithdraw(){return n.type==="Aave"&&n.tokens[1].id===a.assetIn},toHuman(){return{...a,amountIn:T(u,o.decimalsIn),amountOut:T(l,o.decimalsOut),calculatedIn:T(g,o.decimalsIn),spotPrice:T(P,o.decimalsIn),tradeFeePct:d,tradeFeeRange:y,priceImpactPct:f,errors:h}}})}return s}};var vt=6e3,At=m(1e15),be=6,tt=-5,rt=6*60*60*1e3,_u=3,Rt=6;var L=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 Pe=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??vt,minBudgetInNative:t.minBudgetInNative??At})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[a,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:l,priceImpactPct:c}=n,u=l[0],g=l[l.length-1],{assetInDecimals:d}=u,{assetOutDecimals:h}=g,y=Math.abs(c),P=this.getMinimumTradeCount(o,a),x=this.getOptimalTradeCount(y),f=i?Math.round(s/i):x,w=Math.ceil(s/P),B=Math.round(s/x),I=Math.round(s/f),A=o.dividedBy(f).decimalPlaces(0,1),k=await this.router.getBestSell(e,t,T(A,d)),G=o.isLessThan(a),fe=[];G&&fe.push("OrderTooSmall");let Se=k.amountOut.multipliedBy(f),We=this.toBlockPeriod(I),Xe=k.tradeFee.multipliedBy(f),Ye=L.build(l),Be={assetIn:e,assetOut:t,errors:fe,frequencyMin:w,frequencyOpt:B,frequency:I,tradeCount:f,tradeFee:Xe,tradeImpactPct:k.priceImpactPct,tradePeriod:We,tradeRoute:Ye,type:"Dca"};return{...Be,amountIn:o,amountOut:Se,tradeAmountIn:k.amountIn,tradeAmountOut:k.amountOut,toHuman(){return{...Be,amountIn:T(o,d),amountOut:T(Se,h),tradeAmountIn:T(k.amountIn,d),tradeAmountOut:T(k.amountOut,h)}}}}async getMinimumOrderBudget(e){if(E===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(E,e);if(t)return this.minOrderBudget.times(t.amount).div(m(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:n,priceImpactPct:o}=i,l=n[0],c=n[n.length-1],{assetInDecimals:u}=l,{assetOutDecimals:g}=c,d=Math.abs(o),h=this.getTwapTradeCount(d),y=a.dividedBy(h).decimalPlaces(0,1),P=await this.router.getBestSell(l.assetIn,c.assetOut,T(y,u)),x=h===1,f=a.isLessThan(s),w=P.priceImpactPct<tt,B=[];f||x?B.push("OrderTooSmall"):w&&B.push("OrderImpactTooBig");let I=P.amountOut.multipliedBy(h),A=P.tradeFee.multipliedBy(h),k=L.build(n),G={assetIn:e,assetOut:t,errors:B,tradeCount:h,tradeImpactPct:P.priceImpactPct,tradePeriod:be,tradeRoute:k,type:"TwapSell"};return{...G,amountIn:a,amountOut:I,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:A,toHuman(){return{...G,amountIn:T(a,u),amountOut:T(I,g),tradeAmountIn:T(P.amountIn,u),tradeAmountOut:T(P.amountOut,g),tradeFee:T(A,g)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:a,swaps:n,priceImpactPct:o}=i,l=n[0],c=n[n.length-1],{assetInDecimals:u}=l,{assetOutDecimals:g}=c,d=Math.abs(o),h=this.getTwapTradeCount(d),y=a.dividedBy(h).decimalPlaces(0,1),P=await this.router.getBestBuy(l.assetIn,c.assetOut,T(y,g)),x=P.amountIn.multipliedBy(h),f=h===1,w=x.isLessThan(s),B=P.priceImpactPct<tt,I=[];w||f?I.push("OrderTooSmall"):B&&I.push("OrderImpactTooBig");let A=P.tradeFee.multipliedBy(h),k=L.build(n),G={assetIn:e,assetOut:t,errors:I,tradeCount:h,tradeImpactPct:P.priceImpactPct,tradePeriod:be,tradeRoute:k,type:"TwapBuy"};return{...G,amountIn:x,amountOut:a,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:A,toHuman(){return{...G,amountIn:T(x,u),amountOut:T(a,g),tradeAmountIn:T(P.amountIn,u),tradeAmountOut:T(P.amountOut,g),tradeFee:T(A,u)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>rt){let s=rt/(this.blockTime*be);return Math.round(s)}return t}getTwapExecutionTime(e){return e*be*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,Rt)}};var Z=class extends C{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new M(e),this.aaveUtils=new $(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(),ee)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var qe=class extends Z{_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,o=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,a)).amount.isGreaterThanOrEqualTo(o)),l&&e.isGreaterThanOrEqualTo(o)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],a=j(e,this.slippagePct),n=s.assetIn,o=i.assetOut,l=e.plus(a),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(o,n,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(n,o,t.toFixed(),l.toFixed(),L.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],a=j(t,this.slippagePct),n=s.assetIn,o=i.assetOut,l=t.minus(a),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(n,o,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(n,o,e.toFixed(),l.toFixed(),L.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let g=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSellAll",g,ee)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=j(e,this.slippagePct),a=r.assetIn,n=s.assetOut,o=e.minus(i),l=this.api.tx.router.sellAll(a,n,o.toFixed(),L.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let u=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",u,ee)}return this.wrapTx("RouterSellAll",l)}};var He=class extends Z{_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,n=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",n)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:a,tradeRoute:n}=this.order,o=j(i,this.slippagePct),l=i.minus(o),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:n}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:a,tradeRoute:n}=this.order,o=j(s,this.slippagePct),l=s.plus(o),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:n}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var ye=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new qe(this.api,this.evm).setTrade(e)}order(e){return new He(this.api,this.evm).setOrder(e)}};var us={router:{}};function Nm(p,e=us){let t=new ne(p),r=new Re(p),s=new le(p,r),i=new $(r),a=new he(s,e.router),n=new Pe(a,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:i,router:a,scheduler:n},client:{asset:new K(p),balance:new M(p),balanceV2:new ie(p)},ctx:{pool:s},evm:r,tx:new ye(p,r),destroy:()=>{s.destroy()}}}export{te as AaveClient,Ne as AavePool,Fe as AavePoolClient,$ as AaveUtils,K as AssetClient,pt as AssetNotFound,xs as BASILISK_PARACHAIN_ID,M as BalanceClient,ie as BalanceClientV2,O as BigNumber,le as CachingPoolService,ne as ChainParams,qt as DECIMAL_PLACES,vt as DEFAULT_BLOCK_TIME,At as DEFAULT_MIN_BUDGET,W as ERC20,Re as EvmClient,je as FarmClient,Q as H160,Oe as HUB_ASSET_ID,Os as HYDRADX_PARACHAIN_ID,U as HYDRADX_SS58_PREFIX,_s as INFINITY,q as LbpMath,Ee as LbpPool,_e as LbpPoolClient,N as ONE,Rt as ORDER_MIN_BLOCK_PERIOD,R as OmniMath,ke as OmniPool,Ce as OmniPoolClient,it as PERBILL_DENOMINATOR,V as PERMILL_DENOMINATOR,C as PolkadotApiClient,mt as PoolConfigNotFound,z as PoolError,ce as PoolFactory,ve as PoolNotFound,oe as PoolService,F as PoolType,ht as ProviderConfigNotFound,re as RUNTIME_DECIMALS,Ae as RouteNotFound,de as Router,nt as SYSTEM_ASSET_DECIMALS,E as SYSTEM_ASSET_ID,_ as StableMath,J as StableSwap,Le as StableSwapClient,dt as StorageConfigNotFound,gt as SubscriptionNotSupported,se as TRADEABLE_DEFAULT,be as TWAP_BLOCK_PERIOD,rt as TWAP_MAX_DURATION,tt as TWAP_MAX_PRICE_IMPACT,_u as TWAP_TX_MULTIPLIER,It as TradeOrderError,et as TradeOrderType,L as TradeRouteBuilder,he as TradeRouter,Pe as TradeScheduler,Ze as TradeType,ye as TxBuilderFactory,Y as XykMath,De as XykPool,Me as XykPoolClient,S as ZERO,Pn as bnFormatter,m as bnum,Tt as calculateBuyFee,du as calculateDiffToAvg,ge as calculateDiffToRef,wt as calculateSellFee,bt as createChain,Nm as createSdkContext,ft as findNestedKey,bn as findNestedObj,j as getFraction,Ot as hashPools,Lt as isEvmAccount,Gt as isEvmAddress,Ut as isSs58Address,v as scale,ks as toBn,T as toDecimals};
1
+ var xe=[{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 Ve=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var it="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",$e="0x112b087b60C1a166130d59266363C45F8aa99db0",Ke="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ee=1000000n;var bs=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var te=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:Ve,address:$e,args:[Ke],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:Ve,address:$e,args:[Ke,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:xe,address:it,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as we,encodeAddress as ot}from"@polkadot/util-crypto";import{hexToU8a as kt,isHex as Dt,u8aToHex as Mt}from"@polkadot/util";import{Buffer as X}from"buffer";var xs=2090,V=1e6,nt=1e9,Oe="1",Os=2034,U=63,re=18,E="0",at=12,se=15;var ze="ETH\0";function Lt(p){if(!p)return!1;try{let e=we(p,!0),t=X.from(ze);return X.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Gt(p){return!!/^0x[a-fA-F0-9]{40}$/.test(p)}function Ut(p){try{let e=Dt(p)?kt(p):we(p);return ot(e),!0}catch{return!1}}var Q=class p{static toAccount=e=>{let t=X.from(e.slice(2),"hex"),r=X.from(ze);return ot(new Uint8Array(X.concat([r,t,X.alloc(8)])),63)};static fromAccount=e=>{let t=we(e),r=X.from(ze),s=t.slice(r.length,-8);return"0x"+X.from(s).toString("hex")};static fromSS58=e=>{let r=we(e).slice(0,20);return Mt(r)};static fromAny=e=>{if(Gt(e))return e;if(Lt(e))return p.fromAccount(e);if(Ut(e))return p.fromSS58(e);throw new Error("Unknown address type")}};import{Buffer as Te}from"buffer";var W=class{static fromAssetId(e){let t=Number(e),r=Te.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Te.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Te.from("0000000000000000000000000000000100000000","hex"),r=Te.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as w}from"bignumber.js";var qt=12;w.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:qt});var B=m(0),R=m(1),Cs=m("Infinity");function A(p,e){let t=new w(e.toString()),r=new w(10).pow(t);return p.times(r).decimalPlaces(4)}function m(p){return new w(p.toString())}function _s(p,e){let t=m(p);return A(t,e)}function T(p,e){return p.shiftedBy(-1*e).toString()}var Ie=m("1e27"),Ht=m("1.01"),Wt=m("31536000"),$=class{client;constructor(e){this.client=new te(e)}async getSummary(e){let t=Q.fromAny(e),[r,s,i,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[n]=r,[o,l]=s,[c,u,h,g,d,f]=i,b=m(f).dividedBy(1e18).decimalPlaces(6,w.ROUND_DOWN),x=m(c),y=m(u),O=[];for(let S of o){let v=S.underlyingAsset.toLowerCase(),I=n.find(({underlyingAsset:_t})=>_t.toLowerCase()===v);if(!I)throw new Error("Missing pool reserve for "+v);let _=m(S.scaledATokenBalance),G=m(I.liquidityIndex),fe=m(I.liquidityRate),Se=m(I.availableLiquidity),We=m(I.priceInMarketReferenceCurrency),Xe=a+6,Ye=this.calculateLinearInterest(fe,I.lastUpdateTimestamp,Xe),Be=G.multipliedBy(Ye).dividedBy(Ie).decimalPlaces(0,w.ROUND_DOWN),Rt=_.multipliedBy(Be).dividedBy(Ie).decimalPlaces(0,w.ROUND_DOWN),Nt=m(l!==0&&l===I.eModeCategoryId?I.eModeLiquidationThreshold:I.reserveLiquidationThreshold).div(1e4),Et=I.usageAsCollateralEnabled&&S.usageAsCollateralEnabledOnUser&&m(S.scaledATokenBalance).gt(0),Ct=W.toAssetId(v);O.push({aTokenBalance:Rt,availableLiquidity:Se,decimals:Number(I.decimals),isCollateral:Et,priceInRef:We,reserveId:Ct,reserveAsset:v,reserveLiquidationThreshold:Nt})}return{healthFactor:b.toNumber(),totalCollateral:x,totalDebt:y,reserves:O}}async hasBorrowPositions(e){let t=Q.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=Q.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,a,n,o,l]=r;return m(l).dividedBy(1e18).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:a}=await this.getSummary(e),n=W.fromAssetId(t),o=a.find(x=>x.reserveAsset===n);if(!o)throw new Error("Missing reserve ctx for "+n);let{decimals:l,isCollateral:c,priceInRef:u,reserveLiquidationThreshold:h}=o,g=A(m(r),l).decimalPlaces(0,1),d=c?g.multipliedBy(u).dividedBy(m(10).pow(l)).decimalPlaces(0,w.ROUND_DOWN):B,f=s.minus(d);return f.lte(0)?0:f.multipliedBy(h).dividedBy(i).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:a}=await this.getSummary(e),n=W.fromAssetId(t),o=a.find(b=>b.reserveAsset===n);if(!o)throw new Error("Missing reserve ctx for "+n);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:u}=o,g=A(m(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(m(10).pow(l)).decimalPlaces(0,w.ROUND_DOWN),d=s.plus(g);return d.lte(0)?0:d.multipliedBy(u).dividedBy(i).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),a=W.fromAssetId(t),n=s.find(o=>o.reserveAsset===a);if(!n)throw new Error("Missing reserve data for "+a);return this.calculateWithdrawMax(n,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let a of r){let n=this.calculateWithdrawMax(a,t,s);a.reserveId&&(i[a.reserveId]=n)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:a,priceInRef:n,reserveLiquidationThreshold:o,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let h=m(r).minus(Ht);if(h.gt(0)){let d=h.multipliedBy(t).dividedBy(o).decimalPlaces(0,w.ROUND_DOWN).dividedBy(n).multipliedBy(m(10).pow(a)).decimalPlaces(0,w.ROUND_DOWN);c=w.minimum(s,d)}else c=B}return{amount:w.minimum(c,i),decimals:a}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Ie:e.multipliedBy(s).dividedBy(Wt).plus(Ie).decimalPlaces(0,w.ROUND_DOWN)}};function lt(p){switch(p){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var k=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");lt(r)&&console.log(e,...t)}};var K=class extends k{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol: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==E){let u=this.api.consts.balances.existentialDeposit;return{id:E,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:u.toString()}}let{name:i,assetType:a,isSufficient:n,existentialDeposit:o}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:a.toHuman(),isSufficient:n?n.toHuman():!0,location:s?.toJSON(),existentialDeposit:o.toString()}}getBond(e,t,r,s){let[i,a]=s,{assetType:n,isSufficient:o,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(i.toString(),t,r),h=a.toNumber(),g=new Intl.DateTimeFormat("en-GB"),d=[c,"Bond",g.format(h)].join(" ");return{id:e,name:d,symbol:c+"b",decimals:u,icon:c,type:n.toString(),isSufficient:o.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:h}}getShares(e,t,r,s){let{assets:i}=s,{name:a,symbol:n,assetType:o,isSufficient:l,existentialDeposit:c}=t,h=i.map(f=>f.toString()).map(f=>{let{symbol:b}=this.getToken(f,t,r);return[f,b]}),g=Object.fromEntries(h),d=Object.values(g);return{id:e,name:d.join(", "),symbol:n?.isSome?n.toHuman():a.toHuman(),decimals:18,icon:d.join("/"),type:o.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:g}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),a=r?.find(n=>n.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,n]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),o=this.getSupportedAssets(r),l=this.normalizeMetadata(o,n),c=o.map(([{args:[u]},h])=>{let g=h.unwrap(),d=s.get(u.toString()),{assetType:f}=g;switch(f.toString()){case"Bond":let b=a.get(u.toString());return this.getBond(u.toString(),g,l,b);case"StableSwap":let x=i.get(u.toString());return this.getShares(u.toString(),g,l,x);case"External":return this.getExternal(u.toString(),g,t,d);default:return this.getToken(u.toString(),g,l,d)}});return e?c:c.filter(u=>this.isValidAsset(u))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var M=class extends k{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===E?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(E,this.calculateFreeBalance(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,n]})=>[a.toString(),n.toString()]);return this.api.query.tokens.accounts.multi(i,a=>{let n=[];a.forEach((o,l)=>{let c=this.calculateFreeBalance(o),u=i[l][1];n.push([u,c])}),t(n)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([o,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[o]}])=>o.toString()))(),a=async()=>{let n=await Promise.all(i.map(async o=>[o,await this.getErc20Balance(e,o)]));t(n)};return this.api.rpc.chain.subscribeNewHeads(async()=>{a()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let t=e.free.toString(),r=e.frozen.toString();return w(t).lt(r)?w(0):w(t).minus(r)}};var ie=class extends k{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===E?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(E,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,n]})=>[a.toString(),n.toString()]);return this.api.query.tokens.accounts.multi(i,a=>{let n=[];a.forEach((o,l)=>{let c=i[l][1],u=this.calculateBalance(o);n.push([c,u])}),t(n)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([o,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[o]}])=>o.toString()))(),a=async()=>{let n=await Promise.all(i.map(async o=>[o,await this.getErc20Balance(e,o)]));t(n)};return this.api.rpc.chain.subscribeNewHeads(async()=>{a()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=w(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 ne=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),m(this._minOrderBudget)}};import{fixed_from_rational as ct}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as Xt}from"@polkadot/types";import{u8aConcat as ut}from"@polkadot/util";import{isAddress as mt}from"@polkadot/util-crypto";var je=class extends k{balanceClient;constructor(e){super(e),this.balanceClient=new M(e)}secondsInYear=new w(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,a]=s.args,n=i.unwrap().toString(),o=a.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,o,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),g=this.getAccountResolver(this.api.registry)(Number(o),!1).toString(),d=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(g,d);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,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,n=i.unwrap().toString(),o=a.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,o,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),g=this.getAccountResolver(this.api.registry)(Number(o),!0).toString(),d=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(g,d);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,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 w(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[a]=i.unwrap(),n=a.price.n.toString(),o=a.price.d.toString(),l;return Number(t)<Number(r)?l=ct(n,o):l=ct(o,n),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 ut(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Xt(e,this.padEndU8a(ut(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!mt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&mt(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:n,globalFarm:o,priceAdjustment:l,potBalance:c})=>{let u=new w(o.totalSharesZ.toString()),h=o.plannedYieldingPeriods.toString(),g=new w(o.yieldPerPeriod.toString()),d=new w(o.maxRewardPerPeriod.toString()),f=o.blocksPerPeriod.toString(),b=new w(n.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new w(r).times(f)),y;if(u.isZero())y=g.times(b).times(x);else{let _=this.getGlobalRewardPerPeriod(u,g,d,l);y=this.getPoolYieldPerPeriod(_,b,u,l).times(x)}let O=new w(o.pendingRewards.toString()).plus(o.accumulatedPaidRewards.toString()),S=d.times(h),v=c?O.plus(c):S;return O.div(v).gte(.999)?B:y.div(t==="isolatedpool"?2:1).times(100)}).reduce((n,o)=>n.plus(o),B).toString():void 0}};var ve=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},pt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ae=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},dt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},gt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},ht=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Pt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{defineChain as Yt}from"viem";var Vt=["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"],bt=p=>{let t=[p.endpoint,...Vt],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return Yt({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1})};import{createPublicClient as ft,createWalletClient as $t,custom as Kt,http as zt}from"viem";function yt(p){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return p.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var Fe=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=bt(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return ft({chain:this.chain,transport:zt()})}getWsProvider(){return ft({chain:this.chain,transport:yt(this.wsProvider)})}getSigner(e){return $t({account:e,chain:this.chain,transport:Kt(window.ethereum)})}};import{memoize1 as ns}from"@thi.ng/memoize";var N=(a=>(a.Aave="Aave",a.LBP="Lbp",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="Xyk",a.HSM="Hsm",a))(N||{}),z=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n.MaxBuyBackExceeded="MaxBuyBackExceeded",n.MaxBuyPriceExceeded="MaxBuyPriceExceeded",n))(z||{});var Re=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(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(o=>[o.id,o])),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=m(s.balance),n=m(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:n,assetInED:B,assetOutED:B}}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(R,e.decimalsOut)}spotPriceOutGivenIn(e){return A(R,e.decimalsIn)}calculateTradeFee(e,t){return B}};import{encodeAddress as Jt}from"@polkadot/util-crypto";import{stringToU8a as Zt}from"@polkadot/util";import{decodeEventLog as er}from"viem";import{memoize1 as jt}from"@thi.ng/memoize";import{TLRUCache as Qt}from"@thi.ng/cache";var Qe=[{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 ae=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.client.readContract({abi:Qe,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:Qe,address:e,functionName:"decimals"}),this.client.getBlock()]),[a,n,o,l]=r,c=i.number-(i.timestamp-l)/BigInt(t),u=Number(c);return{price:n,decimals:s,updatedAt:u<0?0:u}}};var D=class extends M{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Qt(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=jt(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new ae(t)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools();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=this.augmentedPools.map(async r=>{let s=[],i=await this.subscribeTokensPoolBalance(r);if(s.push(i),this.hasSystemAsset(r)){let a=await this.subscribeSystemPoolBalance(r);s.push(a)}if(this.hasErc20Asset(r)){let a=await this.subscribeErc20PoolBalance(r);s.push(a)}return this.subscribeLog(r),s}),t=await Promise.all(e);return()=>{for(let r of t.flat())try{r()}catch(s){console.warn("Balance unsub failed",s)}}}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t()).catch(t=>console.warn("Unsub failed",t))})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,i])=>{let a=e.tokens.findIndex(n=>n.id==s);a>=0&&t(e,s)&&(e.tokens[a].balance=i.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(i=>i.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};function St(p,e){let t=[];return JSON.stringify(p,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Pn(p,e,t){let r;return JSON.stringify(p,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var bn=(p,e)=>typeof e=="bigint"?e.toString():e;var tr=["Supply","Withdraw","Repay","Borrow"],Ne=class extends D{getPoolType(){return"Aave"}getPoolId(e,t){let r="aave:"+e+"/"+t;return Jt(Zt(r.padEnd(32,"\0")),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}getReserveH160Id(e){return e.type==="Erc20"?St(e.location,"accountKey20").accountKey20.key:W.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{}}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return this.api.query.system.events(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(n=>n.tokens.some(o=>o.id===i.toString()||o.id===a.toString())).forEach(n=>{this.log(`Sync AAVE via [router:Executed] :: ${i}:${a}`),this.updatePoolState(n)})}if(s==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:a,args:n}=er({abi:xe,topics:i.topics,data:i.data});if(tr.includes(a)){let o=n.reserve.toLowerCase();this.pools.filter(l=>{let[c]=l.tokens;return this.getReserveH160Id(c).toLowerCase()===o}).forEach(l=>{this.log(`Sync AAVE via [evm:Log] :: ${a} ${o}`),this.updatePoolState(l)})}}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(a=>{let n=a.id===t.id?s.toString():i.toString();return{...a,balance:n}})}};import{calculate_in_given_out as rr,calculate_out_given_in as sr,calculate_linear_weights as ir,calculate_pool_trade_fee as nr,get_spot_price as ar}from"@galacticcouncil/math-lbp";var q=class{static getSpotPrice(e,t,r,s,i){return ar(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return rr(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return sr(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return ir(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return nr(e,t,r)}};var P=class p{static toPct(e){let[t,r]=e;return p.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return p.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 Ee=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(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(o=>[o.id,o])),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=m(s.balance),n=m(i.balance);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:n,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 n=this.calculateTradeFee(t,r),o=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(n),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:o,errors:i}}else{let n=this.calculateInGivenOut(e,t),o=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(o)&&i.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:n,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 n=this.calculateOutGivenIn(e,t),o=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(o)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:n,feePct:0,errors:i}}else{let n=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(n,r),l=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=n.minus(o),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=q.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?B:s}calculateOutGivenIn(e,t){let r=q.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?B:s}spotPriceInGivenOut(e){let t=q.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),A(R,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=q.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),A(R,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let r=q.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(r)}};var Ce=class extends D{MAX_FINAL_WEIGHT=A(m(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:n,finalWeight:o,repayTarget:l,feeCollector:c}=t,u=q.calculateLinearWeights(s.toString(),i.toString(),n.toString(),o.toString(),r),[h,g]=a,d=h.toString(),f=m(u),b=g.toString(),x=this.MAX_FINAL_WEIGHT.minus(m(f)),[y,O,S]=await Promise.all([this.isRepayFeeApplied(d,l.toString(),c.toString()),this.getBalance(e,d),this.getBalance(e,b)]);return{repayFeeApply:y,tokens:[{id:d,weight:f,balance:O.toString()},{id:b,weight:x,balance:S.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=m(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 n=a.unwrap(),o=i.toString(),l=await this.getPoolDelta(o,n,r.toString());this.poolsData.set(i.toString(),n);let[c,u]=n.fee;return{address:o,type:"Lbp",fee:P.fromRate(c.toNumber(),u.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 P.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(n=>n.address==r.address);this.pools.splice(a,1)}})})}};import{calculate_in_given_out as or,calculate_lrna_in_given_out as lr,calculate_out_given_in as cr,calculate_out_given_lrna_in as ur,calculate_spot_price as mr,calculate_lrna_spot_price as pr,calculate_shares as dr,calculate_liquidity_out as gr,calculate_liquidity_lrna_out as hr,calculate_liquidity_hub_in as Pr,is_sell_allowed as br,is_buy_allowed as yr,is_add_liquidity_allowed as fr,is_remove_liquidity_allowed as Sr,recalculate_asset_fee as Br,recalculate_protocol_fee as xr,verify_asset_cap as Or}from"@galacticcouncil/math-omnipool";var F=class{static calculateSpotPrice(e,t,r,s){return mr(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return pr(e,t)}static calculateInGivenOut(e,t,r,s,i,a,n,o,l){return or(e,t,r,s,i,a,n,o,l)}static calculateLrnaInGivenOut(e,t,r,s,i){return lr(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,a,n,o,l){return cr(e,t,r,s,i,a,n,o,l)}static calculateOutGivenLrnaIn(e,t,r,s,i){return ur(e,t,r,s,i)}static calculateShares(e,t,r,s){return dr(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,a,n,o){return gr(e,t,r,s,i,a,n,o)}static calculateLiquidityLRNAOut(e,t,r,s,i,a,n,o){return hr(e,t,r,s,i,a,n,o)}static calculateCapDifference(e,t,r,s){let i=w(t),a=w(e),n=w(s),l=w(r).shiftedBy(-18);if(i.div(n).lt(l)){let u=l.times(n).minus(i).times(a),h=i.times(w(1).minus(l));return u.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return Pr(e,t,r,s)}static isSellAllowed(e){return br(e)}static isBuyAllowed(e){return yr(e)}static isAddLiquidityAllowed(e){return fr(e)}static isRemoveLiquidityAllowed(e){return Sr(e)}static recalculateAssetFee(e,t,r,s,i,a,n,o,l,c,u){return Br(e,t,r,s,i,a,n,o,l,c,u)}static recalculateProtocolFee(e,t,r,s,i,a,n,o,l,c,u){return xr(e,t,r,s,i,a,n,o,l,c,u)}static verifyAssetCap(e,t,r,s){return Or(e,t,r,s)}};var _e=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(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=m(s.balance),n=m(i.balance),o=m(s.existentialDeposit),l=m(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:n,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),n=s===B?B:a.div(s).multipliedBy(100).decimalPlaces(4),o=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&o.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(h)&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:n.toNumber(),errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),n=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),o=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&o.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(h)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:n.toNumber(),errors:o}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=F.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():B.toString(),r?P.toRaw(r.protocolFee).toString():B.toString()),i=m(s);return i.isNegative()?B:i}calculateLrnaInGivenOut(e,t,r){let s=F.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():B.toString()),i=m(s);return i.isNegative()?B:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=F.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():B.toString(),r?P.toRaw(r.protocolFee).toString():B.toString()),i=m(s);return i.isNegative()?B:i}calculateOutGivenLrnaIn(e,t,r){let s=F.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():B.toString()),i=m(s);return i.isNegative()?B:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=F.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=F.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=F.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=F.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as wr}from"@polkadot/util-crypto";import{stringToU8a as Tr}from"@polkadot/util";import{memoize1 as Je}from"@thi.ng/memoize";import{TLRUCache as Ir}from"@thi.ng/cache";var Bt="omnipool",xt="Short",ke=class extends D{dynamicFees=new Map;dynamicFeesConfiguration=new Map;oracles=new Map;memQueryCache=new Ir(null,{ttl:6*1e3});memOracleQuery=Je(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(Bt,t,xt)},this.memQueryCache);memFeesQuery=Je(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);memFeesConfigurationQuery=Je(e=>this.api.query.dynamicFees.assetFeeConfiguration(e),this.memQueryCache);getPoolType(){return"Omnipool"}getPoolId(){return wr(Tr("modlomnipool".padEnd(32,"\0")),63)}getOracleKey(e){return e===E?[E,Oe]:[Oe,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:[o]},l])=>{let{hubReserve:c,shares:u,tradable:h,cap:g,protocolShares:d}=l.unwrap(),f=await this.getBalance(t,o.toString());return{id:o.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:h.bits.toNumber(),balance:f.toString(),cap:m(g.toString()),protocolShares:m(d.toString())}}),n=await Promise.all(a);return n.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:n,...this.getPoolLimits()}]}async getPoolFees(e,t,r){let s=t.assetOut,i=t.assetIn,a;if(this.isAssetConfigSupported()&&(a=await this.getDynamicFeesConfiguration(s).then(y=>y.unwrapOr(null))),a?.isFixed){let y=a.asFixed.assetFee.toNumber(),O=a.asFixed.protocolFee.toNumber();return{assetFee:P.fromPermill(y),protocolFee:P.fromPermill(O)}}let[n,o,l]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[c,u,h]=this.getAssetFee(t,e,n,o,a?.isDynamic?a.asDynamic.assetFeeParams:void 0),[g,d,f]=i===Oe?[0,0,0]:this.getProtocolFee(t,e,n,l,a?.isDynamic?a.asDynamic.protocolFeeParams:void 0),b=c+g,x=h+f;return{assetFee:P.fromPermill(u),protocolFee:P.fromPermill(d),min:P.fromPermill(b),max:P.fromPermill(x)}}getAssetFee(e,t,r,s,i){let{assetOut:a,balanceOut:n}=e,{minFee:o,maxFee:l,decay:c,amplification:u}=i||this.api.consts.dynamicFees.assetFeeParameters,h=P.fromPermill(o.toNumber()),g=P.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),l.toNumber()];let[d]=s.unwrap(),{assetFee:f,timestamp:b}=r.unwrap(),x=Math.max(1,t-b.toNumber()),y=d.volume.bIn.toString(),O=d.volume.bOut.toString(),S=d.liquidity.b.toString();a===E&&(y=d.volume.aIn.toString(),O=d.volume.aOut.toString(),S=d.liquidity.a.toString());let v=P.fromPermill(f.toNumber()),I=F.recalculateAssetFee(y,O,S,"9",n.toString(),P.toRaw(v).toString(),x.toString(),P.toRaw(h).toString(),P.toRaw(g).toString(),c.toString(),u.toString());return[o.toNumber(),Number(I)*1e6,l.toNumber()]}getProtocolFee(e,t,r,s,i){let{assetIn:a,balanceIn:n}=e,{minFee:o,maxFee:l,decay:c,amplification:u}=i||this.api.consts.dynamicFees.protocolFeeParameters,h=P.fromPermill(o.toNumber()),g=P.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),l.toNumber()];let[d]=s.unwrap(),{protocolFee:f,timestamp:b}=r.unwrap(),x=Math.max(1,t-b.toNumber()),y=d.volume.bIn.toString(),O=d.volume.bOut.toString(),S=d.liquidity.b.toString();a===E&&(y=d.volume.aIn.toString(),O=d.volume.aOut.toString(),S=d.liquidity.a.toString());let v=P.fromPermill(f.toNumber()),I=F.recalculateProtocolFee(y,O,S,"9",n.toString(),P.toRaw(v).toString(),x.toString(),P.toRaw(h).toString(),P.toRaw(g).toString(),c.toString(),u.toString());return[o.toNumber(),Number(I)*1e6,l.toNumber()]}async subscribeUpdates(){let[e]=this.pools,t=e.tokens.map(o=>o.id),r=[],s=await this.api.query.omnipool.assets.multi(t,o=>{e.tokens=o.map((l,c)=>{let u=e.tokens[c];if(l.isNone)return u;let h=l.unwrap();return this.updateTokenState(u,h)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,o=>{o.forEach((l,c)=>{let u=t[c];this.dynamicFees.set(u,l)})});if(r.push(i),this.isAssetConfigSupported()){let o=await this.api.query.dynamicFees.assetFeeConfiguration.multi(t,l=>{l.forEach((c,u)=>{let h=t[u];this.dynamicFeesConfiguration.set(h,c)})});r.push(o)}let a=t.map(o=>{let l=this.getOracleKey(o);return[Bt,l,xt]}),n=await this.api.query.emaOracle.oracles.multi(a,o=>{o.forEach(async(l,c)=>{let u=a[c],[h,g,d]=u;this.oracles.set(g.join(":"),l)})});return r.push(n),()=>{for(let o of r)try{o()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:a,protocolShares:n}=t;return{...e,hubReserves:m(r.toString()),shares:m(s.toString()),cap:m(a.toString()),protocolShares:m(n.toString()),tradeable:i.bits.toNumber()}}};import{calculate_in_given_out as vr,calculate_out_given_in as Ar,calculate_pool_trade_fee as Fr,get_spot_price as Rr,calculate_liquidity_in as Nr,calculate_shares as Er,calculate_spot_price as Cr,calculate_spot_price_with_fee as _r,calculate_liquidity_out_asset_a as kr,calculate_liquidity_out_asset_b as Dr}from"@galacticcouncil/math-xyk";var Y=class{static getSpotPrice(e,t,r){return Rr(e,t,r)}static calculateInGivenOut(e,t,r){return vr(e,t,r)}static calculateOutGivenIn(e,t,r){return Ar(e,t,r)}static calculatePoolTradeFee(e,t,r){return Fr(e,t,r)}static calculateLiquidityIn(e,t,r){return Nr(e,t,r)}static calculateSpotPrice(e,t){return Cr(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return _r(e,t,r,s)}static calculateShares(e,t,r){return Er(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return kr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Dr(e,t,r,s)}};var De=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(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=m(s.balance),n=m(i.balance),o=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:a,balanceOut:n,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),a=P.toPct(r.exchangeFee),n=s.plus(i),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&o.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(c)&&o.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:t,feePct:a,errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),a=P.toPct(r.exchangeFee),n=s.minus(i),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&o.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(c)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:a,errors:o}}calculateInGivenOut(e,t){let r=Y.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?B:s}calculateOutGivenIn(e,t){let r=Y.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?B:s}spotPriceInGivenOut(e){let t=Y.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=A(R,18-e.decimalsOut);return m(t).div(r)}spotPriceOutGivenIn(e){let t=Y.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=A(R,18-e.decimalsIn);return m(t).div(r)}calculateTradeFee(e,t){let r=Y.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(r)}};var Me=class extends D{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,n]=s.unwrap(),[o,l]=await Promise.all([this.getBalance(i,a.toString()),this.getBalance(i,n.toString())]);return{address:i,type:"Xyk",tokens:[{id:a.toString(),balance:o.toString()},{id:n.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 P.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return()=>{}}};import{calculate_in_given_out as Mr,calculate_out_given_in as Lr,calculate_amplification as Gr,calculate_add_one_asset as Ur,calculate_liquidity_out_one_asset as qr,calculate_shares as Hr,calculate_shares_for_amount as Wr,calculate_spot_price_with_fee as Xr,pool_account_name as Yr,recalculate_peg as Vr}from"@galacticcouncil/math-stableswap";var C=class{static getPoolAddress(e){return Yr(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 Gr(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,a,n){return Mr(e,t,r,s,i,a,n)}static calculateAddOneAsset(e,t,r,s,i,a,n){return Ur(e,t,r,s,i,a,n)}static calculateSharesForAmount(e,t,r,s,i,a,n){return Wr(e,t,r,s,i,a,n)}static calculateOutGivenIn(e,t,r,s,i,a,n){return Lr(e,t,r,s,i,a,n)}static calculateLiquidityOutOneAsset(e,t,r,s,i,a,n){return qr(e,t,r,s,i,a,n)}static calculateShares(e,t,r,s,i,a){return Hr(e,t,r,s,i,a)}static calculateSpotPriceWithFee(e,t,r,s,i,a,n,o){return Xr(e,t,r,s,i,a,n,o)}static recalculatePegs(e,t,r,s,i){let a=Vr(e,t,r,s,i);return JSON.parse(a)}};var J=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(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=m(s.balance),n=m(i.balance),o=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:a,balanceOut:n,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),a=i.minus(s),n=s===B?B:a.div(s).multipliedBy(100).decimalPlaces(4),o=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);return(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:n.toNumber(),errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),n=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),o=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);return(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:n.toNumber(),errors:o}}calculateIn(e,t,r){let s=C.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toRaw(r.fee).toString():B.toString(),this.getPegs()),i=m(s);return i.isNegative()?B:i}calculateAddOneAsset(e,t,r){let s=C.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():B.toString(),this.getPegs()),i=m(s);return i.isNegative()?B:i}calculateSharesForAmount(e,t,r){let s=C.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():B.toString(),this.getPegs()),i=m(s);return i.isNegative()?B:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=C.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let s=A(R,e.decimalsIn-e.decimalsOut);return m(t).div(s).decimalPlaces(0,1)}let r=A(R,18-e.decimalsIn);return m(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=C.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toRaw(r.fee).toString():B.toString(),this.getPegs()),i=m(s);return i.isNegative()?B:i}calculateWithdrawOneAsset(e,t,r){let s=C.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():B.toString(),this.getPegs()),i=m(s);return i.isNegative()?B:i}calculateShares(e,t,r){let s=C.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():B.toString(),this.getPegs()),i=m(s);return i.isNegative()?B:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=C.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let s=A(R,e.decimalsOut-e.decimalsIn);return m(t).div(s).decimalPlaces(0,1)}let r=A(R,18-e.decimalsOut);return m(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])}};import{blake2AsHex as $r,encodeAddress as Kr}from"@polkadot/util-crypto";var Le=class extends D{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=Number(e),r=C.getPoolAddress(t);return Kr($r(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:n}=t,o=C.calculateAmplification(s.toString(),i.toString(),a.toString(),n.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:o,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async a=>{let[n,o]=await Promise.all([this.api.query.stableswap.assetTradability(t,a.toString()),this.getBalance(e,a.toString())]);return{id:a.toString(),tradeable:n.bits.toNumber(),balance:o.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]},n])=>{try{let o=n.unwrap(),l=a.toString(),c=this.getPoolAddress(l),[u,h,g]=await Promise.all([this.getPoolDelta(l,o,r.toString()),this.getPoolTokens(c,l,o),this.getPoolPegs(l,o,r.toString())]);return h.push({id:l,tradeable:15,balance:u.totalIssuance}),this.poolsData.set(c,o),{address:c,id:l,type:"Stableswap",fee:P.fromPermill(o.fee.toNumber()),tokens:h,...u,...g,...this.getPoolLimits()}}catch(o){return console.warn(`Skipping pool ${a.toString()}
2
+ `,String(o)),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),n=this.getRecentPegs(i),o=P.fromPermill(i.maxPegUpdate.toNumber()),l=P.fromPermill(t.fee.toNumber()),[c,u]=C.recalculatePegs(JSON.stringify(n),JSON.stringify(a),r,P.toRaw(o).toString(),P.toRaw(l).toString()),h=Number(c)*1e6;return{pegsFee:P.fromPermill(h),pegs:u}}getDefaultPegs(e){let t=e.fee,r=C.defaultPegs(e.assets.length);return{pegsFee:P.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(([n,o])=>o.toString()),a=s.map(async(n,o)=>{if(n.isOracle){let[l,c,u]=n.asOracle,h=[u.toString(),i[o]].map(y=>Number(y)).sort((y,O)=>y-O),g=await this.api.query.emaOracle.oracles(l,h,c),[{price:d,updatedAt:f}]=g.unwrap(),b=d.n.toString(),x=d.d.toString();return u.toString()===h[0].toString()?[[b,x],f.toString()]:[[x,b],f.toString()]}else if(n.isMmOracle){let l=n.asMmOracle,{price:c,decimals:u,updatedAt:h}=await this.mmOracle.getData(l.toString()),g=10**u;return[[c.toString(),g.toString()],h.toString()]}else{if(n.isValue)return[n.asValue.map(l=>l.toString()),r];throw Error(n.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)]),n=r.tokens.map(o=>o.id===r.id?{...o,balance:i.totalIssuance}:o);Object.assign(r,{tokens:n},i,a)}})})}};import{calculate_collateral_in_given_hollar_out as zr,calculate_collateral_out_given_hollar_in as jr,calculate_hollar_in_given_collateral_out as Qr,calculate_hollar_out_given_collateral_in as Jr,calculate_imbalance as Zr,calculate_max_price as es,calculate_buyback_limit as ts,calculate_buyback_price_with_fee as rs}from"@galacticcouncil/math-hsm";var H=class{static calculateCollateralInGivenHollarOut(e,t,r){return zr(e,t,r)}static calculateCollateralOutGivenHollarIn(e,t,r){return jr(e,t,r)}static calculateHollarOutGivenCollateralIn(e,t,r){return Jr(e,t,r)}static calculateHollarInGivenCollateralOut(e,t,r){return Qr(e,t,r)}static calculateImbalance(e,t,r){return Zr(e,t,r)}static calculateBuybackLimit(e,t){return ts(e,t)}static calculateBuybackPriceWithFee(e,t,r){return rs(e,t,r)}static calculateMaxPrice(e,t){return es(e,t)}};var Ge=class p extends J{maxBuyPriceCoefficient;maxInHolding;hollarId;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new p(e)}constructor(e){super(e),this.type="Hsm",this.maxBuyPriceCoefficient=e.maxBuyPriceCoefficient,this.maxInHolding=e.maxInHolding,this.hollarId=e.hollarId,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)}validateBuyConstraints(e,t,r){let s=[];if(e.assetIn===this.hollarId){let i=this.calculateBuybackLimit(e);t.gt(i)&&s.push("MaxBuyBackExceeded");let a=this.calculateBuyPrice(e,t,r),n=this.calculateMaxPrice(e);a.gt(n)&&s.push("MaxBuyPriceExceeded")}return s}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=this.validateBuyConstraints(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.validateBuyConstraints(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=H.calculateHollarInGivenCollateralOut(t.toFixed(0),r.toFixed(0),P.toRaw(this.buyBackFee).toString());return m(s)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),r=H.calculateCollateralInGivenHollarOut(e.toFixed(0),JSON.stringify(t),P.toRaw(this.purchaseFee).toString());return m(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=H.calculateCollateralOutGivenHollarIn(t.toFixed(0),r.toFixed(0),P.toRaw(this.buyBackFee).toString());return m(s)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),r=H.calculateHollarOutGivenCollateralIn(e.toFixed(0),JSON.stringify(t),P.toRaw(this.purchaseFee).toString());return m(r)}calculateOutGivenIn(e,t){return e.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(e,t):this.calculateHollarOutGivenCollateralIn(t)}calculateImbalance(e){let t=this.getCollateralPeg(),r=H.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return m(r)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),r=H.calculateBuybackLimit(t.toString(),P.toRaw(this.buyBackRate).toString());return m(r)}calculateBuyPrice(e,t,r){let s=t.dividedBy(m(10).pow(e.decimalsIn));return r.dividedBy(m(10).pow(e.decimalsOut)).dividedBy(s)}calculateMaxPrice(e){let t=this.getCollateralPeg(),r=H.calculateMaxPrice(JSON.stringify(t),this.maxBuyPriceCoefficient.toFixed(0)),[s,i]=JSON.parse(r);return m(s).div(m(i)).shiftedBy(-1*e.decimalsOut)}spotPriceInGivenOut(e){let t=A(R,e.decimalsOut);return this.calculateInGivenOut(e,t)}spotPriceOutGivenIn(e){let t=A(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)?[A(R,18).toString(),A(R,r).toString()]:t}isDefaultPeg(e){let[t,r]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&r==="1"}};import{encodeAddress as ss}from"@polkadot/util-crypto";import{stringToU8a as is}from"@polkadot/util";var Ue=class extends D{stableClient;constructor(e,t,r){super(e,t),this.stableClient=r}getPoolType(){return"Hsm"}getPoolId(e){let t="hsm:"+e;return ss(is(t.padEnd(32,"\0")),63)}isSupported(){return this.api.query.hsm!==void 0}async loadPools(){let[e,t,r]=await Promise.all([this.api.consts.hsm.hollarId.toString(),this.api.query.hsm.collaterals.entries(),this.stableClient.getPoolsMem()]);return t.map(([{},i])=>{let a=i.unwrap(),{poolId:n,maxBuyPriceCoefficient:o,maxInHolding:l,purchaseFee:c,buyBackFee:u,buybackRate:h}=a,g=r.find(d=>d.id===n.toString());if(g){let d=this.getPoolId(n.toString());return{...g,address:d,type:"Hsm",tokens:g.tokens.filter(f=>f.id!==n.toString()),hollarId:e,maxBuyPriceCoefficient:m(o.toString()),maxInHolding:m(l.unwrap().toString()),purchaseFee:P.fromPermill(c.toNumber()),buyBackFee:P.fromPermill(u.toNumber()),buyBackRate:P.fromPerbill(h.toNumber())}}}).filter(i=>i!==null)}async getPoolFees(e,t,r){return{}}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return()=>{}}};var oe=class extends k{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;hsmClient;clients=[];onChainAssets=[];block=0;disconnectSubscribeNewHeads=null;memRegistry=ns(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new K(this.api),this.aaveClient=new Ne(this.api,t),this.xykClient=new Me(this.api,t),this.omniClient=new ke(this.api,t),this.lbpClient=new Ce(this.api,t),this.stableClient=new Le(this.api,t),this.hsmClient=new Ue(this.api,t,this.stableClient),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient,this.hsmClient],this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r})}onNewBlock(e){this.block=e}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?.()}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 ve(t.type)}}};var le=class extends oe{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 ce=class{static get(e){switch(e.type){case"Aave":return Re.fromPool(e);case"Xyk":return De.fromPool(e);case"Omnipool":return _e.fromPool(e);case"Lbp":return Ee.fromPool(e);case"Stableswap":return J.fromPool(e);case"Hsm":return Ge.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{sha256 as as}from"@noble/hashes/sha256";import{bytesToHex as os}from"@noble/hashes/utils";function Ot(p){let e=p.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=as(t);return os(r)}var ue=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 ls=8,me=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 ue,a=[];for(a.push([t,""]),i.enqueue(a);i.size()>0;){let n=i.dequeue();if(!n||n.length>ls)continue;let o=n[n.length-1];(r===null||o[0]===r)&&s.push(n),e.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,n)){let u=[...n];u.push(c),i.enqueue(u)}})}return s}findShortestPaths(e,t,r){let s=[],i=new ue,a=[];a.push([t,""]),i.enqueue(a);let n=1/0;for(;i.size()>0;){let o=i.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===r){o.length<n?(n=o.length,s.length=0,s.push(o)):o.length===n&&s.push(o);continue}let c=e.get(l[0]);for(let u of c??[])this.isNotVisited(u,o)&&i.enqueue([...o,u])}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 n=parseInt(i),o=parseInt(a);r.get(n)?.push([o,s])}return r}};function Ze(p){let e={};for(let t of p){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let 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 pe=class{getProposals(e,t,r){let s=r.filter(y=>y.type==="Xyk"),i=r.filter(y=>y.type!=="Xyk"),a=parseInt(e),n=parseInt(t),o=new Set(i.map(y=>y.tokens).flat().map(y=>y.id)),l=o.has(e),c=o.has(t),u=new me,h=y=>{let O=Ze(y),S=Object.keys(O),v=S.flatMap(I=>O[I]);return u.buildAndPopulateGraph(S,v)};if(!l&&!c){let y=s.filter(v=>v.tokens.find(I=>I.id===e)||v.tokens.find(I=>I.id===t)),O=h(y),S=u.findPaths(O,a,n);return this.parsePaths(S)}if(l&&c){let y=h(i),O=u.findPaths(y,a,n);return this.parsePaths(O)}let g=l?t:e,d=s.filter(y=>y.tokens.some(O=>O.id===g)),f=[...i,...d],b=h(f),x=u.findPaths(b,a,n);return this.parsePaths(x)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let a=r[i],n=r[i+1];if(n==null)break;s.push(this.toEdge(a,n))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var de=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new pe,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}async getPools(){return await this.poolService.getPools(this.routerOptions)}async getAllAssets(){let e=await this.getPools(),t=this.getAssets(e);return[...new Map(t).values()]}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(n=>this.validPath(n,s)).map(n=>this.toHops(n,s))}getProposals(e,t,r){let s=`${e}->${t}::${Ot(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,ce.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 cs=m("100");function pu(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ge(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function wt(p,e){return R.minus(e.div(p)).multipliedBy(100).decimalPlaces(4)}function Tt(p,e){return e.div(p).minus(R).multipliedBy(100).decimalPlaces(4)}function j(p,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),p.div(cs).multipliedBy(e).decimalPlaces(0,1)}var et=(t=>(t.Buy="Buy",t.Sell="Sell",t))(et||{}),tt=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(tt||{}),It=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(It||{});var he=class extends de{async loadRouteContext(e,t){let r=await super.getPools(),s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(i.length===0)throw new Ae(e,t);return{paths:i,pools:r,poolsMap: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?P.toPct(e.min):void 0,r=e.max?P.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let{paths:i,poolsMap:a}=await this.loadRouteContext(e,t),n;if(s)n=await this.toSellSwaps(r,s,a);else{let S=i.map(async I=>await this.toSellSwaps(r,I,a)),v=await Promise.all(S);n=this.findBestSellRoute(v)}let o=n[0],l=n[n.length-1],c=this.isDirectTrade(n),u=n.map(S=>S.spotPrice.shiftedBy(-1*S.assetOutDecimals)).reduce((S,v)=>S.multipliedBy(v)),h=A(u,l.assetOutDecimals),g=c?l.calculatedOut:this.calculateDelta0Y(o.amountIn,n,a),d=l.amountOut,f=c?l.tradeFeePct:wt(g,d).toNumber(),b=g.minus(d),x=this.getRouteFeeRange(n),y=o.amountIn.shiftedBy(-1*o.assetInDecimals).multipliedBy(h),O=ge(g,y);return{type:"Sell",amountIn:o.amountIn,amountOut:l.amountOut,spotPrice:h,tradeFee:b,tradeFeePct:f,tradeFeeRange:x,priceImpactPct:O.toNumber(),swaps:n,toHuman(){return{type:"Sell",amountIn:T(o.amountIn,o.assetInDecimals),amountOut:T(l.amountOut,l.assetOutDecimals),spotPrice:T(h,l.assetOutDecimals),tradeFee:T(b,l.assetOutDecimals),tradeFeePct:f,tradeFeeRange:x,priceImpactPct:O.toNumber(),swaps:n.map(S=>S.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],n=r.get(a.poolAddress);if(n==null)throw new Error("Pool does not exit");let o=n.parsePair(a.assetIn,a.assetOut),l;i>0?l=s[i-1]:l=e;let c=n.calculateOutGivenIn(o,l);s.push(c)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let a=t[i],n=r.get(a.poolAddress);if(n==null)throw new Error("Pool does not exit");let o=n.parsePair(a.assetIn,a.assetOut),l;i>0?l=s[i-1].amountOut:l=A(m(e),o.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(o,n),{amountOut:u,calculatedOut:h,feePct:g,errors:d}=n.validateAndSell(o,l,c),f=this.getPoolFeeRange(c),b=n.spotPriceOutGivenIn(o),x=l.shiftedBy(-1*o.decimalsIn).multipliedBy(b),y=ge(h,x);s.push({...a,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:u,calculatedOut:h,spotPrice:b,tradeFeePct:g,tradeFeeRange:f,priceImpactPct:y.toNumber(),errors:d,isSupply(){return n.type==="Aave"&&n.tokens[0].id===a.assetIn},isWithdraw(){return n.type==="Aave"&&n.tokens[1].id===a.assetIn},toHuman(){return{...a,amountIn:T(l,o.decimalsIn),amountOut:T(u,o.decimalsOut),calculatedOut:T(h,o.decimalsOut),spotPrice:T(b,o.decimalsOut),tradeFeePct:g,tradeFeeRange:f,priceImpactPct:y.toNumber(),errors:d}}})}return s}async getMostLiquidRoute(e,t){let{paths:r,pools:s,poolsMap:i}=await this.loadRouteContext(e,t),l=s.filter(g=>g.tokens.some(d=>d.id===e)).map(g=>g.type==="Aave"?g.tokens:g.tokens.filter(d=>d.id===e)).map(g=>g.map(d=>m(d.balance).shiftedBy(-1*d.decimals)).reduce((d,f)=>d.plus(f))).sort((g,d)=>d.isLessThan(g)?-1:1)[0].div(100).multipliedBy(.1),c=r.map(async g=>await this.toSellSwaps(l,g,i)),u=await Promise.all(c);return this.findBestSellRoute(u).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut}))}async getBestSpotPrice(e,t){let r;try{r=await this.loadRouteContext(e,t)}catch{return Promise.resolve(void 0)}let{poolsMap:s}=r,i=await this.getMostLiquidRoute(e,t),a=await this.toSellSwaps("1",i,s),n=a.map(c=>c.spotPrice.shiftedBy(-1*c.assetOutDecimals)).reduce((c,u)=>c.multipliedBy(u)),o=a[a.length-1].assetOutDecimals;return{amount:A(n,o),decimals:o}}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){let{paths:i,poolsMap:a}=await this.loadRouteContext(e,t),n;if(s)n=await this.toBuySwaps(r,s,a);else{let S=i.map(async I=>await this.toBuySwaps(r,I,a)),v=await Promise.all(S);n=this.findBestBuyRoute(v)}let o=n[n.length-1],l=n[0],c=this.isDirectTrade(n),u=n.map(S=>S.spotPrice.shiftedBy(-1*S.assetInDecimals)).reduce((S,v)=>S.multipliedBy(v)),h=A(u,l.assetInDecimals),g=c?l.calculatedIn:this.calculateDelta0X(o.amountOut,n,a),d=l.amountIn,f=c?l.tradeFeePct:Tt(g,d).toNumber(),b=d.minus(g),x=this.getRouteFeeRange(n),y=o.amountOut.shiftedBy(-1*o.assetOutDecimals).multipliedBy(h),O;return g.isZero()?O=-100:O=ge(y,g).toNumber(),{type:"Buy",amountOut:o.amountOut,amountIn:l.amountIn,spotPrice:h,tradeFee:b,tradeFeePct:f,tradeFeeRange:x,priceImpactPct:O,swaps:n,toHuman(){return{type:"Buy",amountOut:T(o.amountOut,o.assetOutDecimals),amountIn:T(l.amountIn,l.assetInDecimals),spotPrice:T(h,l.assetInDecimals),tradeFee:T(b,l.assetInDecimals),tradeFeePct:f,tradeFeeRange:x,priceImpactPct:O,swaps:n.map(S=>S.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],n=r.get(a.poolAddress);if(n==null)throw new Error("Pool does not exit");let o=n.parsePair(a.assetIn,a.assetOut),l;i==t.length-1?l=e:l=s[0];let c=n.calculateInGivenOut(o,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let a=t[i],n=r.get(a.poolAddress);if(n==null)throw new Error("Pool does not exit");let o=n.parsePair(a.assetIn,a.assetOut),l;i==t.length-1?l=A(m(e),o.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(o,n),{amountIn:u,calculatedIn:h,feePct:g,errors:d}=n.validateAndBuy(o,l,c),f=this.getPoolFeeRange(c),b=n.spotPriceInGivenOut(o),x=l.shiftedBy(-1*o.decimalsOut).multipliedBy(b),y;h.isZero()?y=-100:y=ge(x,h).toNumber(),s.unshift({...a,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:u,amountOut:l,calculatedIn:h,spotPrice:b,tradeFeePct:g,tradeFeeRange:f,priceImpactPct:y,errors:d,isSupply(){return n.type==="Aave"&&n.tokens[0].id===a.assetIn},isWithdraw(){return n.type==="Aave"&&n.tokens[1].id===a.assetIn},toHuman(){return{...a,amountIn:T(u,o.decimalsIn),amountOut:T(l,o.decimalsOut),calculatedIn:T(h,o.decimalsIn),spotPrice:T(b,o.decimalsIn),tradeFeePct:g,tradeFeeRange:f,priceImpactPct:y,errors:d}}})}return s}};var vt=6e3,At=m(1e15),Pe=6,rt=-5,st=6*60*60*1e3,Eu=3,Ft=6;var L=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 be=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??vt,minBudgetInNative:t.minBudgetInNative??At})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[a,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:l,priceImpactPct:c}=n,u=l[0],h=l[l.length-1],{assetInDecimals:g}=u,{assetOutDecimals:d}=h,f=Math.abs(c),b=this.getMinimumTradeCount(o,a),x=this.getOptimalTradeCount(f),y=i?Math.round(s/i):x,O=Math.ceil(s/b),S=Math.round(s/x),v=Math.round(s/y),I=o.dividedBy(y).decimalPlaces(0,1),_=await this.router.getBestSell(e,t,T(I,g)),G=o.isLessThan(a),fe=[];G&&fe.push("OrderTooSmall");let Se=_.amountOut.multipliedBy(y),We=this.toBlockPeriod(v),Xe=_.tradeFee.multipliedBy(y),Ye=L.build(l),Be={assetIn:e,assetOut:t,errors:fe,frequencyMin:O,frequencyOpt:S,frequency:v,tradeCount:y,tradeFee:Xe,tradeImpactPct:_.priceImpactPct,tradePeriod:We,tradeRoute:Ye,type:"Dca"};return{...Be,amountIn:o,amountOut:Se,tradeAmountIn:_.amountIn,tradeAmountOut:_.amountOut,toHuman(){return{...Be,amountIn:T(o,g),amountOut:T(Se,d),tradeAmountIn:T(_.amountIn,g),tradeAmountOut:T(_.amountOut,d)}}}}async getMinimumOrderBudget(e){if(E===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(E,e);if(t)return this.minOrderBudget.times(t.amount).div(m(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:n,priceImpactPct:o}=i,l=n[0],c=n[n.length-1],{assetInDecimals:u}=l,{assetOutDecimals:h}=c,g=Math.abs(o),d=this.getTwapTradeCount(g),f=a.dividedBy(d).decimalPlaces(0,1),b=await this.router.getBestSell(l.assetIn,c.assetOut,T(f,u)),x=d===1,y=a.isLessThan(s),O=b.priceImpactPct<rt,S=[];y||x?S.push("OrderTooSmall"):O&&S.push("OrderImpactTooBig");let v=b.amountOut.multipliedBy(d),I=b.tradeFee.multipliedBy(d),_=L.build(n),G={assetIn:e,assetOut:t,errors:S,tradeCount:d,tradeImpactPct:b.priceImpactPct,tradePeriod:Pe,tradeRoute:_,type:"TwapSell"};return{...G,amountIn:a,amountOut:v,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:I,toHuman(){return{...G,amountIn:T(a,u),amountOut:T(v,h),tradeAmountIn:T(b.amountIn,u),tradeAmountOut:T(b.amountOut,h),tradeFee:T(I,h)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:a,swaps:n,priceImpactPct:o}=i,l=n[0],c=n[n.length-1],{assetInDecimals:u}=l,{assetOutDecimals:h}=c,g=Math.abs(o),d=this.getTwapTradeCount(g),f=a.dividedBy(d).decimalPlaces(0,1),b=await this.router.getBestBuy(l.assetIn,c.assetOut,T(f,h)),x=b.amountIn.multipliedBy(d),y=d===1,O=x.isLessThan(s),S=b.priceImpactPct<rt,v=[];O||y?v.push("OrderTooSmall"):S&&v.push("OrderImpactTooBig");let I=b.tradeFee.multipliedBy(d),_=L.build(n),G={assetIn:e,assetOut:t,errors:v,tradeCount:d,tradeImpactPct:b.priceImpactPct,tradePeriod:Pe,tradeRoute:_,type:"TwapBuy"};return{...G,amountIn:x,amountOut:a,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:I,toHuman(){return{...G,amountIn:T(x,u),amountOut:T(a,h),tradeAmountIn:T(b.amountIn,u),tradeAmountOut:T(b.amountOut,h),tradeFee:T(I,u)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>st){let s=st/(this.blockTime*Pe);return Math.round(s)}return t}getTwapExecutionTime(e){return e*Pe*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,Ft)}};var Z=class extends k{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new M(e),this.aaveUtils=new $(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(),ee)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var qe=class extends Z{_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,o=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,a)).amount.isGreaterThanOrEqualTo(o)),l&&e.isGreaterThanOrEqualTo(o)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],a=j(e,this.slippagePct),n=s.assetIn,o=i.assetOut,l=e.plus(a),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(o,n,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(n,o,t.toFixed(),l.toFixed(),L.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],a=j(t,this.slippagePct),n=s.assetIn,o=i.assetOut,l=t.minus(a),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(n,o,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(n,o,e.toFixed(),l.toFixed(),L.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let h=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSellAll",h,ee)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=j(e,this.slippagePct),a=r.assetIn,n=s.assetOut,o=e.minus(i),l=this.api.tx.router.sellAll(a,n,o.toFixed(),L.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let u=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",u,ee)}return this.wrapTx("RouterSellAll",l)}};var He=class extends Z{_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,n=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",n)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:a,tradeRoute:n}=this.order,o=j(i,this.slippagePct),l=i.minus(o),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:n}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:a,tradeRoute:n}=this.order,o=j(s,this.slippagePct),l=s.plus(o),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:n}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var ye=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new qe(this.api,this.evm).setTrade(e)}order(e){return new He(this.api,this.evm).setOrder(e)}};var us={router:{}};function Fm(p,e=us){let t=new ne(p),r=new Fe(p),s=new le(p,r),i=new $(r),a=new he(s,e.router),n=new be(a,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:i,router:a,scheduler:n},client:{asset:new K(p),balance:new M(p),balanceV2:new ie(p)},ctx:{pool:s},evm:r,tx:new ye(p,r),destroy:()=>{s.destroy()}}}export{te as AaveClient,Re as AavePool,Ne as AavePoolClient,$ as AaveUtils,K as AssetClient,dt as AssetNotFound,xs as BASILISK_PARACHAIN_ID,M as BalanceClient,ie as BalanceClientV2,w as BigNumber,le as CachingPoolService,ne as ChainParams,qt as DECIMAL_PLACES,vt as DEFAULT_BLOCK_TIME,At as DEFAULT_MIN_BUDGET,W as ERC20,Fe as EvmClient,je as FarmClient,Q as H160,Oe as HUB_ASSET_ID,Os as HYDRADX_PARACHAIN_ID,U as HYDRADX_SS58_PREFIX,Cs as INFINITY,q as LbpMath,Ee as LbpPool,Ce as LbpPoolClient,R as ONE,Ft as ORDER_MIN_BLOCK_PERIOD,F as OmniMath,_e as OmniPool,ke as OmniPoolClient,nt as PERBILL_DENOMINATOR,V as PERMILL_DENOMINATOR,k as PolkadotApiClient,pt as PoolConfigNotFound,z as PoolError,ce as PoolFactory,ve as PoolNotFound,oe as PoolService,N as PoolType,Pt as ProviderConfigNotFound,re as RUNTIME_DECIMALS,Ae as RouteNotFound,de as Router,at as SYSTEM_ASSET_DECIMALS,E as SYSTEM_ASSET_ID,C as StableMath,J as StableSwap,Le as StableSwapClient,gt as StorageConfigNotFound,ht as SubscriptionNotSupported,se as TRADEABLE_DEFAULT,Pe as TWAP_BLOCK_PERIOD,st as TWAP_MAX_DURATION,rt as TWAP_MAX_PRICE_IMPACT,Eu as TWAP_TX_MULTIPLIER,It as TradeOrderError,tt as TradeOrderType,L as TradeRouteBuilder,he as TradeRouter,be as TradeScheduler,et as TradeType,ye as TxBuilderFactory,Y as XykMath,De as XykPool,Me as XykPoolClient,B as ZERO,bn as bnFormatter,m as bnum,Tt as calculateBuyFee,pu as calculateDiffToAvg,ge as calculateDiffToRef,wt as calculateSellFee,bt as createChain,Fm as createSdkContext,St as findNestedKey,Pn as findNestedObj,j as getFraction,Ot as hashPools,Lt as isEvmAccount,Gt as isEvmAddress,Ut as isSs58Address,A as scale,_s as toBn,T as toDecimals};
@@ -1,21 +1,26 @@
1
1
  import { UnsubscribePromise } from '@polkadot/api-base/types';
2
- import { PoolBase, PoolType, PoolFees, PoolPair } from '../types';
2
+ import { PoolBase, PoolType, PoolPair } from '../types';
3
3
  import { PoolClient } from '../PoolClient';
4
+ import { OmniPoolFees } from './OmniPool';
4
5
  export declare class OmniPoolClient extends PoolClient {
5
6
  private dynamicFees;
7
+ private dynamicFeesConfiguration;
6
8
  private oracles;
7
9
  private memQueryCache;
8
10
  private memOracleQuery;
9
11
  private memFeesQuery;
12
+ private memFeesConfigurationQuery;
10
13
  getPoolType(): PoolType;
11
14
  private getPoolId;
12
15
  private getOracleKey;
13
16
  private getPoolLimits;
14
17
  private getDynamicFees;
18
+ private getDynamicFeesConfiguration;
15
19
  private getOraclePrice;
16
20
  isSupported(): boolean;
21
+ isAssetConfigSupported(): boolean;
17
22
  loadPools(): Promise<PoolBase[]>;
18
- getPoolFees(block: number, poolPair: PoolPair, _poolAddress: string): Promise<PoolFees>;
23
+ getPoolFees(block: number, poolPair: PoolPair, _poolAddress: string): Promise<OmniPoolFees>;
19
24
  private getAssetFee;
20
25
  private getProtocolFee;
21
26
  protected subscribeUpdates(): UnsubscribePromise;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk",
3
- "version": "9.10.0",
3
+ "version": "9.11.0",
4
4
  "description": "Galactic off-chain routing & optimization of orders across pools for best price execution",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {