@galacticcouncil/sdk 7.1.0 → 7.1.1

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 je=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var zt=Object.getOwnPropertyNames;var Xt=Object.prototype.hasOwnProperty;var Yt=(l,e)=>{for(var t in e)je(l,t,{get:e[t],enumerable:!0})},$t=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of zt(e))!Xt.call(l,r)&&r!==t&&je(l,r,{get:()=>e[r],enumerable:!(s=Wt(e,r))||s.enumerable});return l};var Vt=l=>$t(je({},"__esModule",{value:!0}),l);var cs={};Yt(cs,{AMOUNT_MAX:()=>qt,AaveClient:()=>re,AavePool:()=>fe,AavePoolClient:()=>be,AaveUtils:()=>Re,AssetClient:()=>ie,AssetNotFound:()=>it,BASILISK_PARACHAIN_ID:()=>_s,BalanceClient:()=>W,BigNumber:()=>x.BigNumber,CachingPoolService:()=>We,DECIMAL_PLACES:()=>Ot,DENOMINATOR:()=>et,ERC20:()=>Y,EvmClient:()=>K,FarmClient:()=>_e,H160:()=>Z,HUB_ASSET_ID:()=>de,HYDRADX_PARACHAIN_ID:()=>Es,HYDRADX_SS58_PREFIX:()=>V,INFINITY:()=>jt,LbpMath:()=>U,LbpPool:()=>Se,LbpPoolClient:()=>xe,ONE:()=>R,OmniMath:()=>O,OmniPool:()=>ve,OmniPoolClient:()=>we,PolkadotApiClient:()=>L,PoolConfigNotFound:()=>nt,PoolError:()=>ee,PoolFactory:()=>ue,PoolNotFound:()=>Pe,PoolService:()=>le,PoolType:()=>E,ProviderConfigNotFound:()=>lt,RUNTIME_DECIMALS:()=>ge,RouteNotFound:()=>Q,Router:()=>ce,SYSTEM_ASSET_DECIMALS:()=>ks,SYSTEM_ASSET_ID:()=>D,StableMath:()=>_,StableSwap:()=>Ae,StableSwapClient:()=>Ie,StorageConfigNotFound:()=>ot,SubscriptionNotSupported:()=>at,TRADEABLE_DEFAULT:()=>he,TradeRouter:()=>Ye,TradeType:()=>Xe,TradeUtils:()=>$e,XykMath:()=>$,XykPool:()=>Oe,XykPoolClient:()=>Be,ZERO:()=>y,bnFormatter:()=>is,bnum:()=>p,calculateBuyFee:()=>gt,calculateDiffToAvg:()=>us,calculateDiffToRef:()=>me,calculateSellFee:()=>dt,evmMainnet:()=>Qe,findNestedKey:()=>mt,findNestedObj:()=>ns,getFraction:()=>pe,isEvmAccount:()=>xt,isEvmAddress:()=>vt,isSs58Address:()=>wt,scale:()=>B});module.exports=Vt(cs);var se=[{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 Je=[{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 Fe="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ke="0x112b087b60C1a166130d59266363C45F8aa99db0",Ze="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ht=1000000n;var Pt=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var bt=require("viem"),yt=["https://rpc.hydradx.cloud","https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],ft=["wss://rpc.hydradx.cloud","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"],Qe=(0,bt.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:yt,webSocket:ft},default:{http:yt,webSocket:ft}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var H=require("viem");var K=class{chain;constructor(e){this.chain=e||Qe}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,H.createPublicClient)({chain:this.chain,transport:(0,H.http)()})}getWsProvider(){return(0,H.createPublicClient)({chain:this.chain,transport:(0,H.webSocket)()})}getSigner(e){return(0,H.createWalletClient)({account:e,chain:this.chain,transport:(0,H.custom)(window.ethereum)})}};var re=class{evmClient;constructor(){this.evmClient=new K}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Je,address:Ke,args:[Ze],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:Je,address:Ke,args:[Ze,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:se,address:Fe,args:[e],functionName:"getUserAccountData"})}};var J=require("@polkadot/util-crypto"),ne=require("@polkadot/util"),j=require("buffer");var _s=2090,et=1e3,de="1",Es=2034,V=63,ge=18,D="0",ks=12,he=15;var St=j.Buffer.from("ETH\0");function xt(l){if(!l)return!1;try{let e=(0,J.decodeAddress)(l,!0);return j.Buffer.from(e.subarray(0,St.length)).equals(St)}catch{return!1}}function vt(l){return!!/^0x[a-fA-F0-9]{40}$/.test(l)}function wt(l){try{let e=(0,ne.isHex)(l)?(0,ne.hexToU8a)(l):(0,J.decodeAddress)(l);return(0,J.encodeAddress)(e),!0}catch{return!1}}var Z=class l{static prefixBytes=j.Buffer.from("ETH\0");static toAccount=e=>{let t=j.Buffer.from(e.slice(2),"hex");return(0,J.encodeAddress)(new Uint8Array(j.Buffer.concat([l.prefixBytes,t,j.Buffer.alloc(8)])),63)};static fromAccount=e=>{let s=(0,J.decodeAddress)(e).slice(l.prefixBytes.length,-8);return"0x"+j.Buffer.from(s).toString("hex")};static fromSS58=e=>{let s=(0,J.decodeAddress)(e).slice(0,20);return(0,ne.u8aToHex)(s)};static fromAny=e=>{if(vt(e))return e;if(xt(e))return l.fromAccount(e);if(wt(e))return l.fromSS58(e);throw new Error("Unknown address type")}};var Y=class{static fromAssetId(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),s=Buffer.from(e.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(t.subarray(0,16))}};var x=require("bignumber.js"),Ot=12;x.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Ot});var y=p(0),R=p(1),jt=p("Infinity");function B(l,e){let t=new x.BigNumber(e.toString()),s=new x.BigNumber(10).pow(t);return l.times(s)}function p(l){return new x.BigNumber(l.toString())}var Jt=p("1e27"),zs=p("1e8"),Xs=p("31536000"),Ys=p("999999999"),Kt=p("1.01"),Re=class{client;constructor(){this.client=new re}async loadCtx(e,t){let s=Z.fromAny(e),r=Y.fromAssetId(t),[n,i,o]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(s),this.client.getUserAccountData(s)]),[a,u]=o,[c]=n,[m,g]=i,d=c.find(({underlyingAsset:te})=>te.toLowerCase()===r.toLowerCase()),h=m.find(({underlyingAsset:te})=>te.toLowerCase()===r.toLowerCase());if(!d||!h)throw new Error("Missing reserve or userReserve for "+t);let P=Number(d.decimals),f=p(d.priceInMarketReferenceCurrency),v=p(g===d.eModeCategoryId?d.eModeLiquidationThreshold:d.reserveLiquidationThreshold).div(1e4),S=p(d.liquidityIndex),A=p(h.scaledATokenBalance),I=p(a),w=p(u),M=d.usageAsCollateralEnabled&&h.usageAsCollateralEnabledOnUser&&p(h.scaledATokenBalance).gt(0),X=A.multipliedBy(S).dividedBy(Jt).decimalPlaces(0,x.BigNumber.ROUND_DOWN);return{decimals:P,isCollateralAsset:M,priceInRef:f,reserveLiquidationThreshold:v,totalCollateralBase:I,totalDebtBase:w,userBalance:X}}async getMaxWithdraw(e,t){let{decimals:s,priceInRef:r,reserveLiquidationThreshold:n,totalCollateralBase:i,totalDebtBase:o,userBalance:a}=await this.loadCtx(e,t),u=p(i),c=p(o),m=Kt.multipliedBy(c).div(n).decimalPlaces(0,x.BigNumber.ROUND_UP),d=u.minus(m).decimalPlaces(0,1).multipliedBy(p(10).pow(s)).dividedBy(r).decimalPlaces(0,x.BigNumber.ROUND_DOWN);return{amount:x.BigNumber.minimum(a,d),decimals:s}}async getHealthFactorAfterWithdraw(e,t,s){let{decimals:r,isCollateralAsset:n,priceInRef:i,reserveLiquidationThreshold:o,totalCollateralBase:a,totalDebtBase:u}=await this.loadCtx(e,t),c=n?p(s).multipliedBy(i).dividedBy(p(10).pow(r)).decimalPlaces(0,x.BigNumber.ROUND_DOWN):y,m=a.minus(c);return m.lte(0)?0:m.multipliedBy(o).dividedBy(u).decimalPlaces(6,x.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,s){let{decimals:r,priceInRef:n,reserveLiquidationThreshold:i,totalCollateralBase:o,totalDebtBase:a}=await this.loadCtx(e,t),u=p(s).multipliedBy(n).dividedBy(p(10).pow(r)).decimalPlaces(0,x.BigNumber.ROUND_DOWN),c=o.plus(u);return c.lte(0)?0:c.multipliedBy(i).dividedBy(a).decimalPlaces(6,x.BigNumber.ROUND_DOWN).toNumber()}};var Qs=require("@galacticcouncil/api-augment/hydradx"),er=require("@galacticcouncil/api-augment/basilisk"),L=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}async dryRun(e,t){let s;try{s=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(r){throw console.error(r),new Error("Dry run execution failed!")}if(s.isOk)return s.asOk;throw console.log(s.asErr.toHuman()),new Error("Dry run execution error!")}log(e,...t){let s=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");this.getLogValue(s)&&console.log(e,...t)}getLogValue(e){switch(e){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}};var ie=class extends L{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:n}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:n.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==D){let m=this.api.consts.balances.existentialDeposit;return{id:D,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:n,assetType:i,isSufficient:o,existentialDeposit:a}=t,{symbol:u,decimals:c}=s.get(e)??{};return{id:e,name:n.toHuman(),symbol:u,decimals:c,icon:u,type:i.toHuman(),isSufficient:o?o.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[n,i]=r,{assetType:o,isSufficient:a,existentialDeposit:u}=t,{symbol:c,decimals:m}=this.getToken(n.toString(),t,s),g=i.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:o.toString(),isSufficient:a.toHuman(),existentialDeposit:u.toString(),underlyingAssetId:n.toString(),maturity:g}}getShares(e,t,s,r){let{assets:n}=r,{name:i,symbol:o,assetType:a,isSufficient:u,existentialDeposit:c}=t,g=n.map(P=>P.toString()).map(P=>{let{symbol:f}=this.getToken(P,t,s);return[P,f]}),d=Object.fromEntries(g),h=Object.values(d);return{id:e,name:h.join(", "),symbol:o?.isSome?o.toHuman():i.toHuman(),decimals:18,icon:h.join("/"),type:a.toString(),isSufficient:u.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,s,r){let n=this.getToken(e,t,new Map,r),i=s?.find(o=>o.internalId===n.id);return i?{...n,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:n}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:n,symbol:i}=r.unwrap();return[s.toString(),{decimals:Number(n.toString()),symbol:i.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,n,i,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(s),u=this.normalizeMetadata(a,o),c=a.map(([{args:[m]},g])=>{let d=g.unwrap(),h=r.get(m.toString()),{assetType:P}=d;switch(P.toString()){case"Bond":let f=i.get(m.toString());return this.getBond(m.toString(),d,u,f);case"StableSwap":let v=n.get(m.toString());return this.getShares(m.toString(),d,u,v);case"External":return this.getExternal(m.toString(),d,t,h);default:return this.getToken(m.toString(),d,u,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 W=class extends L{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===D?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:n}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:n})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:n}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:0n,frozen:n})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(D,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let n=t.filter(i=>i.type!=="Erc20").filter(i=>i.id!==D).map(i=>[e,i.id]);return this.api.query.tokens.accounts.multi(n,i=>{let o=[];i.forEach((a,u)=>{let c=this.calculateFreeBalance(a),m=n[u][1];o.push([m,c])}),s(o)})}async subscribeErc20Balance(e,t,s){let r=t.filter(i=>i.type==="Erc20"),n=async()=>{let i=[];(await Promise.all(r.map(async a=>[a.id,await this.getErc20Balance(e,a.id)]))).forEach(([a,u])=>{i.push([a,u])}),s(i)};return await n(),this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:n}=e,i=new x.BigNumber(t),o=new x.BigNumber(s||n),a=new x.BigNumber(r||0n),u=o.gt(a)?o:a;return i.minus(u)}};var tt=require("@galacticcouncil/math-liquidity-mining"),Bt=require("@polkadot/types"),st=require("@polkadot/util"),rt=require("@polkadot/util-crypto");var _e=class extends L{balanceClient;constructor(e){super(e),this.balanceClient=new W(e)}secondsInYear=new x.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([r,n])=>{let[,i]=r.args,o=n.unwrap().toString(),a=i.toString(),u=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),h=u.rewardCurrency.toString(),P=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:P.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,n])=>{let[,i]=r.args,o=n.unwrap().toString(),a=i.toString(),u=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),h=u.rewardCurrency.toString(),P=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:P.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new x.BigNumber(1).shiftedBy(18).toString();let n=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(n.isNone)return;let[i]=n.unwrap(),o=i.price.n.toString(),a=i.price.d.toString(),u;return Number(t)<Number(s)?u=(0,tt.fixed_from_rational)(o,a):u=(0,tt.fixed_from_rational)(a,o),u}getGlobalRewardPerPeriod(e,t,s,r){let i=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return i.gte(s)?s:i}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}padEndU8a(e,t){return(0,st.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",n=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Bt.GenericAccountId32(e,this.padEndU8a((0,st.u8aConcat)(r,n,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,rt.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,rt.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:o,globalFarm:a,priceAdjustment:u,potBalance:c})=>{let m=new x.BigNumber(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),d=new x.BigNumber(a.yieldPerPeriod.toString()),h=new x.BigNumber(a.maxRewardPerPeriod.toString()),P=a.blocksPerPeriod.toString(),f=new x.BigNumber(o.multiplier.toString()).shiftedBy(-18),v=this.secondsInYear.div(new x.BigNumber(s).times(P)),S;if(m.isZero())S=d.times(f).times(v);else{let X=this.getGlobalRewardPerPeriod(m,d,h,u);S=this.getPoolYieldPerPeriod(X,f,m,u).times(v)}let A=new x.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),I=h.times(g),w=c?A.plus(c):I;return A.div(w).gte(.999)?y:S.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),y).toString():void 0}};var Pe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},nt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Q=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},it=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},ot=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},at=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},lt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var ye=(l,e)=>l===e?0:l==null?e==null?0:-1:e==null?l==null?0:1:typeof l.compare=="function"?l.compare(e):typeof e.compare=="function"?-e.compare(l):l<e?-1:l>e?1:0;var Ee=(l,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(l(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var Zt=Ee(()=>"illegal argument(s)"),At=l=>{throw new Zt(l)};var Qt=Ee(()=>"index out of bounds"),ut=l=>{throw new Qt(l)},ke=(l,e,t)=>(l<e||l>=t)&&ut(l);var It=23283064365386963e-26,Ce=class{float(e=1){return this.int()*It*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*It-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var De=class extends Ce{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 Tt=new De(Math.random);var Nt=l=>l!=null&&typeof l!="function"&&l.length!==void 0;var Ft=Object.getPrototypeOf({}),Le="function",Rt="string",oe=(l,e)=>{let t;if(l===e)return!0;if(l!=null){if(typeof l.equiv===Le)return l.equiv(e)}else return l==e;if(e!=null){if(typeof e.equiv===Le)return e.equiv(l)}else return l==e;return typeof l===Rt||typeof e===Rt?!1:(t=Object.getPrototypeOf(l),(t==null||t===Ft)&&(t=Object.getPrototypeOf(e),t==null||t===Ft)?rs(l,e):typeof l!==Le&&l.length!==void 0&&typeof e!==Le&&e.length!==void 0?es(l,e):l instanceof Set&&e instanceof Set?ts(l,e):l instanceof Map&&e instanceof Map?ss(l,e):l instanceof Date&&e instanceof Date?l.getTime()===e.getTime():l instanceof RegExp&&e instanceof RegExp?l.toString()===e.toString():l!==l&&e!==e)},es=(l,e,t=oe)=>{let s=l.length;if(s===e.length)for(;s-- >0&&t(l[s],e[s]););return s<0},ts=(l,e,t=oe)=>l.size===e.size&&t([...l.keys()].sort(),[...e.keys()].sort()),ss=(l,e,t=oe)=>l.size===e.size&&t([...l].sort(),[...e].sort()),rs=(l,e,t=oe)=>{if(Object.keys(l).length!==Object.keys(e).length)return!1;for(let s in l)if(!e.hasOwnProperty(s)||!t(l[s],e[s]))return!1;return!0};var ct=class{value;constructor(e){this.value=e}deref(){return this.value}};var _t=l=>l instanceof ct;var Me=class l{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Et("next",this._head)}reverseIterator(){return Et("prev",this.tail)}clear(){this.release()}compare(e,t=ye){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,n=e._head,i=0;for(;s-- >0&&i===0;)i=t(r.value,n.value),r=r.next,n=n.next;return i}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof l||Nt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!oe(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.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||ye;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!_t(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >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,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&ut(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}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,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*Et(l,e){for(;e;)yield e.value,e=e[l]}var qe=class l extends Me{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new l(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new l}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(ke(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(ke(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new l,e)}nth(e,t){let s=this.nthCell(e);return s?s.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 s=this.nthCell(e),r=this.nthCell(t-1),n=i=>({first(){return i.value},next(){return i!==r&&i.next?n(i.next):void 0}});return s?n(s):void 0}shuffle(e,t=Tt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&At("invalid indices: ${from} / ${to}");let n=new l,i=this.nthCell(s);for(;i&&++s<=r;)n.push(i.value),i=i.next;return n}sort(e=ye){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let n=s,i=0;for(let a=0;a<t&&(i++,n=n.next,!!n);a++);let o=t;for(;i>0||o>0&&n;){let a;i===0?(a=n,n=n.next,o--):!n||o===0||e(s.value,n.value)<=0?(a=s,s=s.next,i--):(a=n,n=n.next,o--),this._tail?this._tail.next=a:this._head=a,a.prev=this._tail,this._tail=a}s=n}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),ke(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let n=new l;if(t>0)for(;r&&t-- >0;)this.remove(r),n.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let i of s)this.insertBefore(r,i);else for(let i of s)this.push(i);return n}};var ae=class l{map;items;opts;_size;constructor(e,t){let s={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=s.map(),this.items=new qe,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new l(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e),n=Math.max(0,s-(r?r.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(r,e,t,s):this._size-=n,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let s=this.map.get(e);return s?this.resetEntry(s):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:s}=this.opts;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e?.(r.k,r.v),this._size-=r.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,s,r){e?(this.opts.update?.(t,e.value.v,s),e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Ge=class l extends ae{constructor(e,t){super(e,{ttl:60*60*1e3,autoExtend:!1,...t})}empty(){return new l(null,this.opts)}has(e){return this.get(e)!==void 0}get(e,t){let s=this.map.get(e);if(s){if(s.value.t>=Date.now())return this.resetEntry(s);this.removeEntry(s)}return t}set(e,t,s=this.opts.ttl){let r=this.opts.ksize(e)+this.opts.vsize(t),n=this.map.get(e),i=Math.max(0,r-(n?n.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(n,e,t,r,s):this._size-=i,t}async getSet(e,t,s=this.opts.ttl){let r=this.get(e);return r!==void 0?r:this.set(e,await t(),s)}prune(){let e=Date.now(),t=this.items.head,s=0;for(;t;)t.value.t<e&&(this.removeEntry(t),s++),t=t.next;return s}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,s=Date.now(),r=this.items.head;for(;r&&(this._size>t||this.length>=e);)r.value.t<s&&this.removeEntry(r),r=r.next;return super.ensureSize()}doSetEntry(e,t,s,r,n=this.opts.ttl){let i=Date.now()+n;e?(this.opts.update?.(t,e.value.v,s),e.value.v=s,e.value.s=r,e.value.t=i,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r,t:i,ttl:n}),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 He=(l,e=new Map)=>t=>{let s;return e.has(t)?e.get(t):(e.set(t,s=l(t)),s)};var E=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n))(E||{}),ee=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n))(ee||{});var fe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,n){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=p(r.balance),o=p(n.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,assetInED:y,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=[];return t.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:n}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=[];return r.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:n}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return B(R,e.decimalsOut)}spotPriceOutGivenIn(e){return B(R,e.decimalsIn)}calculateTradeFee(e,t){return y}};var kt=require("@polkadot/util-crypto"),Ct=require("@polkadot/util"),Dt=require("viem");function mt(l,e){let t=[];return JSON.stringify(l,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function ns(l,e,t){let s;return JSON.stringify(l,(r,n)=>(n&&n[e]===t&&(s=n),n)),s}var is=(l,e)=>typeof e=="bigint"?e.toString():e;var q=class extends W{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Ge(null,{maxlen:1,ttl:60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=He(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let n=this.subscribePoolChange(t);s.push(n)}catch{}if(t.type==="Aave")return s;let r=this.subscribeTokensPoolBalance(t);if(s.push(r),this.hasSystemAsset(t)){let n=this.subscribeSystemPoolBalance(t);s.push(n)}if(this.hasErc20Asset(t)){let n=this.subscribeErc20PoolBalance(t);s.push(n)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}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 s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,n])=>{let i=e.tokens.findIndex(o=>o.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=n.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(n=>n.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var os=["Supply","Withdraw","Repay","Borrow"],be=class extends q{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:s,liqudityIn:r,liqudityOut:n})=>({address:this.getPoolId(t.toString(),s.toString()),type:"Aave",tokens:[{id:t.toString(),balance:r.toString()},{id:s.toString(),balance:n.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let s=e+"/"+t;return(0,kt.encodeAddress)((0,Ct.stringToU8a)(s.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);return this.api.query.system.events(n=>{n.forEach(i=>{let{event:o}=i,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:u,assetOut:c}=o.data.toHuman(),m=u.replace(/,/g,""),g=c.replace(/,/g,"");(m===s.id||g===s.id)&&(this.log(`Sync AAVE [router:Executed] :: ${m}:${g}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:u}=o.data.toHuman();try{let{eventName:c,args:m}=(0,Dt.decodeEventLog)({abi:se,topics:u.topics,data:u.data});os.includes(c)&&m.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut:n}=await this.api.call.aaveTradeExecutor.pool(t.id,s.id);e.tokens=e.tokens.map(i=>{let o=i.id===t.id?r.toString():n.toString();return{...i,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?mt(e.location,"accountKey20").accountKey20.key:Y.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};var z=require("@galacticcouncil/math-lbp"),U=class{static getSpotPrice(e,t,s,r,n){return(0,z.get_spot_price)(e,t,s,r,n)}static calculateInGivenOut(e,t,s,r,n){return(0,z.calculate_in_given_out)(e,t,s,r,n)}static calculateOutGivenIn(e,t,s,r,n){return(0,z.calculate_out_given_in)(e,t,s,r,n)}static calculateLinearWeights(e,t,s,r,n){return(0,z.calculate_linear_weights)(e,t,s,r,n)}static calculatePoolTradeFee(e,t,s){return(0,z.calculate_pool_trade_fee)(e,t,s)}};function k(l,e){return l.shiftedBy(-1*e).toString()}function G(l){return l[0]/l[1]*100}function N(l){return l[0]/l[1]}function C(l){return[l/1e3,1e3]}var Se=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,n,i,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.fee=i,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=p(r.balance),o=p(n.balance);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:r.decimals,decimalsOut:n.decimals,weightIn:r.weight,weightOut:n.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let i=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(i)&&n.push("MaxOutRatioExceeded"),r===e.assetOut){let o=this.calculateTradeFee(t,s),a=G(this.repayFeeApply?s.repayFee:s.exchangeFee),u=t.plus(o),c=this.calculateInGivenOut(e,u),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&n.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:n}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&n.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:n}}}validateAndSell(e,t,s){let r=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let i=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(i)&&n.push("MaxInRatioExceeded"),r===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:n}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,s),u=G(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:u,errors:n}}}calculateInGivenOut(e,t){let s=U.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?y:r}calculateOutGivenIn(e,t){let s=U.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?y:r}spotPriceInGivenOut(e){let t=U.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),B(R,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=U.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),B(R,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let s=U.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(s)}};var xe=class extends q{MAX_FINAL_WEIGHT=B(p(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([n,i])=>this.isActivePool(i.unwrap(),s)).map(async([{args:[n]},i])=>{let o=i.unwrap(),a=n.toString(),u=await this.getPoolDelta(a,o,s.toString());return this.poolsData.set(n.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...u,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let i=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,i)}else{let i=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(i,1)}})}async getPoolDelta(e,t,s){let{start:r,end:n,assets:i,initialWeight:o,finalWeight:a,repayTarget:u,feeCollector:c}=t,m=U.calculateLinearWeights(r.toString(),n.toString(),o.toString(),a.toString(),s),[g,d]=i,h=g.toString(),P=p(m),f=d.toString(),v=this.MAX_FINAL_WEIGHT.minus(p(P)),[S,A,I]=await Promise.all([this.isRepayFeeApplied(h,u.toString(),c.toString()),this.getBalance(e,h),this.getBalance(e,f)]);return{repayFeeApply:S,tokens:[{id:h,weight:P,balance:A.toString()},{id:f,weight:v,balance:I.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=p(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var b=require("@galacticcouncil/math-omnipool");var O=class{static calculateSpotPrice(e,t,s,r){return(0,b.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,b.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,n,i,o,a,u){return(0,b.calculate_in_given_out)(e,t,s,r,n,i,o,a,u)}static calculateLrnaInGivenOut(e,t,s,r,n){return(0,b.calculate_lrna_in_given_out)(e,t,s,r,n)}static calculateOutGivenIn(e,t,s,r,n,i,o,a,u){return(0,b.calculate_out_given_in)(e,t,s,r,n,i,o,a,u)}static calculateOutGivenLrnaIn(e,t,s,r,n){return(0,b.calculate_out_given_lrna_in)(e,t,s,r,n)}static calculatePoolTradeFee(e,t,s){return(0,b.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,b.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,n,i,o,a){return(0,b.calculate_liquidity_out)(e,t,s,r,n,i,o,a)}static calculateLiquidityLRNAOut(e,t,s,r,n,i,o,a){return(0,b.calculate_liquidity_lrna_out)(e,t,s,r,n,i,o,a)}static calculateCapDifference(e,t,s,r){let n=(0,x.BigNumber)(t),i=(0,x.BigNumber)(e),o=(0,x.BigNumber)(r),u=(0,x.BigNumber)(s).shiftedBy(-18);if(n.div(o).lt(u)){let m=u.times(o).minus(n).times(i),g=n.times((0,x.BigNumber)(1).minus(u));return m.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return(0,b.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,b.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,b.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,b.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,b.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,s,r,n,i,o,a,u,c,m){return(0,b.recalculate_asset_fee)(e,t,s,r,n,i,o,a,u,c,m)}static recalculateProtocolFee(e,t,s,r,n,i,o,a,u,c,m){return(0,b.recalculate_protocol_fee)(e,t,s,r,n,i,o,a,u,c,m)}static verifyAssetCap(e,t,s,r){return(0,b.verify_asset_cap)(e,t,s,r)}};var ve=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,n,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.hubAssetId=i}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=p(r.balance),o=p(n.balance),a=p(r.existentialDeposit),u=p(n.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:n.hubReserves,sharesIn:r.shares,sharesOut:n.shares,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,tradeableIn:r.tradeable,tradeableOut:n.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,s),i=n.minus(r),o=r===y?y:i.div(r).multipliedBy(100).decimalPlaces(2),a=[],u=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&a.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(g)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,s),o=r.minus(n).div(r).multipliedBy(100).decimalPlaces(2),a=[],u=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&a.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(g)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=O.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?N(s.assetFee).toString():y.toString(),s?N(s.protocolFee).toString():y.toString()),n=p(r);return n.isNegative()?y:n}calculateLrnaInGivenOut(e,t,s){let r=O.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?N(s.assetFee).toString():y.toString()),n=p(r);return n.isNegative()?y:n}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=O.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?N(s.assetFee).toString():y.toString(),s?N(s.protocolFee).toString():y.toString()),n=p(r);return n.isNegative()?y:n}calculateOutGivenLrnaIn(e,t,s){let r=O.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?N(s.assetFee).toString():y.toString()),n=p(r);return n.isNegative()?y:n}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=O.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=O.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=O.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=O.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var Lt=require("@polkadot/util-crypto"),Mt=require("@polkadot/util");var we=class extends q{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,n]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),i=s.map(async([{args:[a]},u])=>{let{hubReserve:c,shares:m,tradable:g,cap:d,protocolShares:h}=u.unwrap(),P=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:g.bits.toNumber(),balance:P.toString(),cap:p(d.toString()),protocolShares:p(h.toString())}}),o=await Promise.all(i);return o.push({id:e,tradeable:r.bits.toNumber(),balance:n.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,n="omnipool",i="Short",o=I=>I===D?[D,de]:[de,I],[a,u,c,m]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(n,o(s),i),this.api.query.emaOracle.oracles(n,o(r),i)]),[g,d,h]=this.getAssetFee(e,a.toNumber(),u,c),[P,f,v]=r===de?[0,0,0]:this.getProtocolFee(e,a.toNumber(),u,m),S=g+P,A=h+v;return{assetFee:C(d),protocolFee:C(f),min:C(S),max:C(A)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,n)=>{let i=e.tokens[n];if(r.isNone)return i;let o=r.unwrap();return this.updateTokenState(i,o)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:n,cap:i,protocolShares:o}=t;return{...e,hubReserves:p(s.toString()),shares:p(r.toString()),cap:p(i.toString()),protocolShares:p(o.toString()),tradeable:n.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:n,balanceOut:i}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,m=C(o.toNumber()),g=C(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{assetFee:h,timestamp:P}=s.unwrap(),f=t-P.toNumber(),v=d.volume.bIn.toString(),S=d.volume.bOut.toString(),A=d.liquidity.b.toString();n===D&&(v=d.volume.aIn.toString(),S=d.volume.aOut.toString(),A=d.liquidity.a.toString());let I=C(h.toNumber()),w=O.recalculateAssetFee(v,S,A,"9",i.toString(),N(I).toString(),f.toString(),N(m).toString(),N(g).toString(),u.toString(),c.toString());return[o.toNumber(),Number(w)*1e6,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:n,balanceIn:i}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,m=C(o.toNumber()),g=C(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{protocolFee:h,timestamp:P}=s.unwrap(),f=t-P.toNumber(),v=d.volume.bIn.toString(),S=d.volume.bOut.toString(),A=d.liquidity.b.toString();n===D&&(v=d.volume.aIn.toString(),S=d.volume.aOut.toString(),A=d.liquidity.a.toString());let I=C(h.toNumber()),w=O.recalculateProtocolFee(v,S,A,"9",i.toString(),N(I).toString(),f.toString(),N(m).toString(),N(g).toString(),u.toString(),c.toString());return[o.toNumber(),Number(w)*1e6,a.toNumber()]}getPoolId(){return(0,Lt.encodeAddress)((0,Mt.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var F=require("@galacticcouncil/math-xyk"),$=class{static getSpotPrice(e,t,s){return(0,F.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,F.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,F.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,F.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,F.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,F.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,F.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,F.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,F.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,F.calculate_liquidity_out_asset_b)(e,t,s,r)}};var Oe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,n){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=p(r.balance),o=p(n.balance),a=p(r.existentialDeposit),u=p(n.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateTradeFee(r,s),i=G(s.exchangeFee),o=r.plus(n),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(r,s),i=G(s.exchangeFee),o=r.minus(n),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:i,errors:a}}calculateInGivenOut(e,t){let s=$.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?y:r}calculateOutGivenIn(e,t){let s=$.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?y:r}spotPriceInGivenOut(e){let t=$.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=B(R,18-e.decimalsOut);return p(t).div(s)}spotPriceOutGivenIn(e){let t=$.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=B(R,18-e.decimalsIn);return p(t).div(s)}calculateTradeFee(e,t){let s=$.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(s)}};var Be=class extends q{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let n=s.toString(),[i,o]=r.unwrap(),[a,u]=await Promise.all([this.getBalance(n,i.toString()),this.getBalance(n,o.toString())]);return{address:n,type:"Xyk",tokens:[{id:i.toString(),balance:a.toString()},{id:o.toString(),balance:u.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var T=require("@galacticcouncil/math-stableswap"),_=class{static getPoolAddress(e){return(0,T.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let s=0;s<e;s++)t.push(["1","1"]);return t}static calculateAmplification(e,t,s,r,n){return(0,T.calculate_amplification)(e,t,s,r,n)}static calculateInGivenOut(e,t,s,r,n,i,o){return(0,T.calculate_in_given_out)(e,t,s,r,n,i,o)}static calculateAddOneAsset(e,t,s,r,n,i,o){return(0,T.calculate_add_one_asset)(e,t,s,r,n,i,o)}static calculateSharesForAmount(e,t,s,r,n,i,o){return(0,T.calculate_shares_for_amount)(e,t,s,r,n,i,o)}static calculateOutGivenIn(e,t,s,r,n,i,o){return(0,T.calculate_out_given_in)(e,t,s,r,n,i,o)}static calculateLiquidityOutOneAsset(e,t,s,r,n,i,o){return(0,T.calculate_liquidity_out_one_asset)(e,t,s,r,n,i,o)}static calculateShares(e,t,s,r,n,i){return(0,T.calculate_shares)(e,t,s,r,n,i)}static calculateSpotPriceWithFee(e,t,s,r,n,i,o,a){return(0,T.calculate_spot_price_with_fee)(e,t,s,r,n,i,o,a)}static calculatePoolTradeFee(e,t,s){return(0,T.calculate_pool_trade_fee)(e,t,s)}static recalculatePegs(e,t,s,r,n){let i=(0,T.recalculate_peg)(e,t,s,r,n);return JSON.parse(i)}};var Ae=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,n,i,o,a,u,c,m){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.amplification=i,this.id=o,this.fee=a,this.totalIssuance=u,this.pegs=c,this.pegsFee=m}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=p(r.balance),o=p(n.balance),a=p(r.existentialDeposit),u=p(n.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:r.decimals,decimalsOut:n.decimals,tradeableIn:this.id===e?15:r.tradeable,tradeableOut:this.id===t?15:n.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,s),i=G(s.fee),o=[],a=O.isSellAllowed(e.tradeableIn),u=O.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:i,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,s),i=G(s.fee),o=[],a=O.isSellAllowed(e.tradeableIn),u=O.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:i,errors:o}}calculateIn(e,t,s){let r=_.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?N(s.fee).toString():y.toString(),this.getPegs()),n=p(r);return n.isNegative()?y:n}calculateAddOneAsset(e,t,s){let r=_.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?N(s.fee).toString():y.toString(),this.getPegs()),n=p(r);return n.isNegative()?y:n}calculateSharesForAmount(e,t,s){let r=_.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?N(s.fee).toString():y.toString(),this.getPegs()),n=p(r);return n.isNegative()?y:n}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let r=B(R,e.decimalsIn-e.decimalsOut);return p(t).div(r)}let s=B(R,18-e.decimalsIn);return p(t).div(s)}calculateOut(e,t,s){let r=_.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?N(s.fee).toString():y.toString(),this.getPegs()),n=p(r);return n.isNegative()?y:n}calculateWithdrawOneAsset(e,t,s){let r=_.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?N(s.fee).toString():y.toString(),this.getPegs()),n=p(r);return n.isNegative()?y:n}calculateShares(e,t,s){let r=_.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?N(s.fee).toString():y.toString(),this.getPegs()),n=p(r);return n.isNegative()?y:n}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let r=B(R,e.decimalsOut-e.decimalsIn);return p(t).div(r)}let s=B(R,18-e.decimalsOut);return p(t).div(s)}calculateTradeFee(e,t){let s=_.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return p(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var Ue=require("@polkadot/util-crypto");var qt=340282366920938463463374607431768211455n,Ie=class extends q{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[n]},i])=>{let o=i.unwrap(),a=n.toString(),u=this.getPoolAddress(a),[c,m,g]=await Promise.all([this.getPoolDelta(a,o,s.toString()),this.getPoolTokens(u,a,o),this.getPoolPegs(a,o,s.toString())]);return this.stablePools.set(u,o),{address:u,id:a,type:"Stableswap",fee:C(o.fee.toNumber()),tokens:m,...c,...g,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toString(),r=this.stablePools.get(e.address);if(r){let[n,i]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,n,i)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:n,initialBlock:i,finalBlock:o}=t,a=_.calculateAmplification(r.toString(),n.toString(),i.toString(),o.toString(),s),u=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:u.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,n=r.map(async o=>{let[a,u]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:a.bits.toNumber(),balance:u.toString()}}),i=await Promise.all(n);return i.push({id:t,tradeable:15,balance:qt.toString()}),i}getPoolDefaultPegs(e){let t=e.fee,s=_.defaultPegs(e.assets.length);return{pegsFee:C(t.toNumber()),pegs:s}}async getPoolPegs(e,t,s){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let r=await this.api.query.stableswap.poolPegs(e);if(r.isNone)return this.getPoolDefaultPegs(t);let n=r.unwrap(),i=await this.getLatestPegs(t,n,s),o=this.getRecentPegs(n),a=n.maxPegUpdate.toHuman(),u=t.fee.toHuman(),[c,m]=_.recalculatePegs(JSON.stringify(o),JSON.stringify(i),s,a.replace(/%/g,""),u.replace(/%/g,"")),g=Number(c)*1e4;return{pegsFee:C(g),pegs:m}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([s,r])=>r.map(n=>n.toString()))}async getLatestPegs(e,t,s){let{source:r}=t,n=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),i=r.map(async(o,a)=>{if(o.isOracle){let[u,c,m]=o.asOracle,g=[m.toString(),n[a]].map(S=>Number(S)).sort((S,A)=>S-A),d=await this.api.query.emaOracle.oracles(u,g,c),[{price:h,updatedAt:P}]=d.unwrap(),f=h.n.toString(),v=h.d.toString();return m.toString()===g[0].toString()?[[f,v],P.toString()]:[[v,f],P.toString()]}else return[o.asValue.map(u=>u.toString()),s]});return Promise.all(i)}getPoolAddress(e){let t=Number(e),s=_.getPoolAddress(t);return(0,Ue.encodeAddress)((0,Ue.blake2AsHex)(s),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var le=class extends L{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=He(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new ie(this.api),this.aaveClient=new be(this.api),this.xykClient=new Be(this.api),this.omniClient=new we(this.api),this.lbpClient=new xe(this.api),this.stableClient=new Ie(this.api),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new Pe(t.type)}}};var We=class extends le{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new ae(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let n=await super.getPoolFees(e,t);return this.feeCache.set(s,n),n}}async destroy(){this.log(`Destroying pool cache!
1
+ "use strict";var je=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var zt=Object.getOwnPropertyNames;var Xt=Object.prototype.hasOwnProperty;var Yt=(l,e)=>{for(var t in e)je(l,t,{get:e[t],enumerable:!0})},$t=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of zt(e))!Xt.call(l,r)&&r!==t&&je(l,r,{get:()=>e[r],enumerable:!(s=Wt(e,r))||s.enumerable});return l};var Vt=l=>$t(je({},"__esModule",{value:!0}),l);var cs={};Yt(cs,{AMOUNT_MAX:()=>qt,AaveClient:()=>re,AavePool:()=>fe,AavePoolClient:()=>be,AaveUtils:()=>Re,AssetClient:()=>ie,AssetNotFound:()=>it,BASILISK_PARACHAIN_ID:()=>_s,BalanceClient:()=>W,BigNumber:()=>x.BigNumber,CachingPoolService:()=>We,DECIMAL_PLACES:()=>Ot,DENOMINATOR:()=>et,ERC20:()=>Y,EvmClient:()=>K,FarmClient:()=>_e,H160:()=>Z,HUB_ASSET_ID:()=>de,HYDRADX_PARACHAIN_ID:()=>Es,HYDRADX_SS58_PREFIX:()=>V,INFINITY:()=>jt,LbpMath:()=>U,LbpPool:()=>Se,LbpPoolClient:()=>xe,ONE:()=>R,OmniMath:()=>O,OmniPool:()=>ve,OmniPoolClient:()=>we,PolkadotApiClient:()=>L,PoolConfigNotFound:()=>nt,PoolError:()=>ee,PoolFactory:()=>ue,PoolNotFound:()=>Pe,PoolService:()=>le,PoolType:()=>E,ProviderConfigNotFound:()=>lt,RUNTIME_DECIMALS:()=>ge,RouteNotFound:()=>Q,Router:()=>ce,SYSTEM_ASSET_DECIMALS:()=>ks,SYSTEM_ASSET_ID:()=>D,StableMath:()=>_,StableSwap:()=>Ae,StableSwapClient:()=>Ie,StorageConfigNotFound:()=>ot,SubscriptionNotSupported:()=>at,TRADEABLE_DEFAULT:()=>he,TradeRouter:()=>Ye,TradeType:()=>Xe,TradeUtils:()=>$e,XykMath:()=>$,XykPool:()=>Oe,XykPoolClient:()=>Be,ZERO:()=>y,bnFormatter:()=>is,bnum:()=>p,calculateBuyFee:()=>gt,calculateDiffToAvg:()=>us,calculateDiffToRef:()=>me,calculateSellFee:()=>dt,evmMainnet:()=>Qe,findNestedKey:()=>mt,findNestedObj:()=>ns,getFraction:()=>pe,isEvmAccount:()=>xt,isEvmAddress:()=>vt,isSs58Address:()=>wt,scale:()=>B});module.exports=Vt(cs);var se=[{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 Je=[{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 Fe="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ke="0x112b087b60C1a166130d59266363C45F8aa99db0",Ze="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ht=1000000n;var Pt=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var bt=require("viem"),yt=["https://rpc.hydradx.cloud","https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],ft=["wss://rpc.hydradx.cloud","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"],Qe=(0,bt.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:yt,webSocket:ft},default:{http:yt,webSocket:ft}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var H=require("viem");var K=class{chain;constructor(e){this.chain=e||Qe}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,H.createPublicClient)({chain:this.chain,transport:(0,H.http)()})}getWsProvider(){return(0,H.createPublicClient)({chain:this.chain,transport:(0,H.webSocket)()})}getSigner(e){return(0,H.createWalletClient)({account:e,chain:this.chain,transport:(0,H.custom)(window.ethereum)})}};var re=class{evmClient;constructor(){this.evmClient=new K}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Je,address:Ke,args:[Ze],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:Je,address:Ke,args:[Ze,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:se,address:Fe,args:[e],functionName:"getUserAccountData"})}};var J=require("@polkadot/util-crypto"),ne=require("@polkadot/util"),j=require("buffer");var _s=2090,et=1e3,de="1",Es=2034,V=63,ge=18,D="0",ks=12,he=15;var St=j.Buffer.from("ETH\0");function xt(l){if(!l)return!1;try{let e=(0,J.decodeAddress)(l,!0);return j.Buffer.from(e.subarray(0,St.length)).equals(St)}catch{return!1}}function vt(l){return!!/^0x[a-fA-F0-9]{40}$/.test(l)}function wt(l){try{let e=(0,ne.isHex)(l)?(0,ne.hexToU8a)(l):(0,J.decodeAddress)(l);return(0,J.encodeAddress)(e),!0}catch{return!1}}var Z=class l{static prefixBytes=j.Buffer.from("ETH\0");static toAccount=e=>{let t=j.Buffer.from(e.slice(2),"hex");return(0,J.encodeAddress)(new Uint8Array(j.Buffer.concat([l.prefixBytes,t,j.Buffer.alloc(8)])),63)};static fromAccount=e=>{let s=(0,J.decodeAddress)(e).slice(l.prefixBytes.length,-8);return"0x"+j.Buffer.from(s).toString("hex")};static fromSS58=e=>{let s=(0,J.decodeAddress)(e).slice(0,20);return(0,ne.u8aToHex)(s)};static fromAny=e=>{if(vt(e))return e;if(xt(e))return l.fromAccount(e);if(wt(e))return l.fromSS58(e);throw new Error("Unknown address type")}};var Y=class{static fromAssetId(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),s=Buffer.from(e.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(t.subarray(0,16))}};var x=require("bignumber.js"),Ot=12;x.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Ot});var y=p(0),R=p(1),jt=p("Infinity");function B(l,e){let t=new x.BigNumber(e.toString()),s=new x.BigNumber(10).pow(t);return l.times(s)}function p(l){return new x.BigNumber(l.toString())}var Jt=p("1e27"),zs=p("1e8"),Xs=p("31536000"),Ys=p("999999999"),Kt=p("1.01"),Re=class{client;constructor(){this.client=new re}async loadCtx(e,t){let s=Z.fromAny(e),r=Y.fromAssetId(t),[n,i,o]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(s),this.client.getUserAccountData(s)]),[a,u]=o,[c]=n,[m,g]=i,d=c.find(({underlyingAsset:te})=>te.toLowerCase()===r.toLowerCase()),h=m.find(({underlyingAsset:te})=>te.toLowerCase()===r.toLowerCase());if(!d||!h)throw new Error("Missing reserve or userReserve for "+t);let P=Number(d.decimals),f=p(d.priceInMarketReferenceCurrency),v=p(g===d.eModeCategoryId?d.eModeLiquidationThreshold:d.reserveLiquidationThreshold).div(1e4),S=p(d.liquidityIndex),A=p(h.scaledATokenBalance),I=p(a),w=p(u),M=d.usageAsCollateralEnabled&&h.usageAsCollateralEnabledOnUser&&p(h.scaledATokenBalance).gt(0),X=A.multipliedBy(S).dividedBy(Jt).decimalPlaces(0,x.BigNumber.ROUND_DOWN);return{decimals:P,isCollateralAsset:M,priceInRef:f,reserveLiquidationThreshold:v,totalCollateralBase:I,totalDebtBase:w,userBalance:X}}async getMaxWithdraw(e,t){let{decimals:s,priceInRef:r,reserveLiquidationThreshold:n,totalCollateralBase:i,totalDebtBase:o,userBalance:a}=await this.loadCtx(e,t),u=p(i),c=p(o),m=Kt.multipliedBy(c).div(n).decimalPlaces(0,x.BigNumber.ROUND_UP),d=u.minus(m).decimalPlaces(0,1).multipliedBy(p(10).pow(s)).dividedBy(r).decimalPlaces(0,x.BigNumber.ROUND_DOWN);return{amount:x.BigNumber.minimum(a,d),decimals:s}}async getHealthFactorAfterWithdraw(e,t,s){let{decimals:r,isCollateralAsset:n,priceInRef:i,reserveLiquidationThreshold:o,totalCollateralBase:a,totalDebtBase:u}=await this.loadCtx(e,t),c=n?p(s).multipliedBy(i).dividedBy(p(10).pow(r)).decimalPlaces(0,x.BigNumber.ROUND_DOWN):y,m=a.minus(c);return m.lte(0)?0:m.multipliedBy(o).dividedBy(u).decimalPlaces(6,x.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,s){let{decimals:r,priceInRef:n,reserveLiquidationThreshold:i,totalCollateralBase:o,totalDebtBase:a}=await this.loadCtx(e,t),u=p(s).multipliedBy(n).dividedBy(p(10).pow(r)).decimalPlaces(0,x.BigNumber.ROUND_DOWN),c=o.plus(u);return c.lte(0)?0:c.multipliedBy(i).dividedBy(a).decimalPlaces(6,x.BigNumber.ROUND_DOWN).toNumber()}};var Qs=require("@galacticcouncil/api-augment/hydradx"),er=require("@galacticcouncil/api-augment/basilisk"),L=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}async dryRun(e,t){let s;try{s=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(r){throw console.error(r),new Error("Dry run execution failed!")}if(s.isOk)return s.asOk;throw console.log(s.asErr.toHuman()),new Error("Dry run execution error!")}log(e,...t){let s=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");this.getLogValue(s)&&console.log(e,...t)}getLogValue(e){switch(e){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}};var ie=class extends L{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:n}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:n.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==D){let m=this.api.consts.balances.existentialDeposit;return{id:D,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:n,assetType:i,isSufficient:o,existentialDeposit:a}=t,{symbol:u,decimals:c}=s.get(e)??{};return{id:e,name:n.toHuman(),symbol:u,decimals:c,icon:u,type:i.toHuman(),isSufficient:o?o.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[n,i]=r,{assetType:o,isSufficient:a,existentialDeposit:u}=t,{symbol:c,decimals:m}=this.getToken(n.toString(),t,s),g=i.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:o.toString(),isSufficient:a.toHuman(),existentialDeposit:u.toString(),underlyingAssetId:n.toString(),maturity:g}}getShares(e,t,s,r){let{assets:n}=r,{name:i,symbol:o,assetType:a,isSufficient:u,existentialDeposit:c}=t,g=n.map(P=>P.toString()).map(P=>{let{symbol:f}=this.getToken(P,t,s);return[P,f]}),d=Object.fromEntries(g),h=Object.values(d);return{id:e,name:h.join(", "),symbol:o?.isSome?o.toHuman():i.toHuman(),decimals:18,icon:h.join("/"),type:a.toString(),isSufficient:u.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,s,r){let n=this.getToken(e,t,new Map,r),i=s?.find(o=>o.internalId===n.id);return i?{...n,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:n}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:n,symbol:i}=r.unwrap();return[s.toString(),{decimals:Number(n.toString()),symbol:i.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,n,i,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(s),u=this.normalizeMetadata(a,o),c=a.map(([{args:[m]},g])=>{let d=g.unwrap(),h=r.get(m.toString()),{assetType:P}=d;switch(P.toString()){case"Bond":let f=i.get(m.toString());return this.getBond(m.toString(),d,u,f);case"StableSwap":let v=n.get(m.toString());return this.getShares(m.toString(),d,u,v);case"External":return this.getExternal(m.toString(),d,t,h);default:return this.getToken(m.toString(),d,u,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 W=class extends L{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===D?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:n}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:n})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:n}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:0n,frozen:n})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(D,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let n=t.filter(i=>i.type!=="Erc20").filter(i=>i.id!==D).map(i=>[e,i.id]);return this.api.query.tokens.accounts.multi(n,i=>{let o=[];i.forEach((a,u)=>{let c=this.calculateFreeBalance(a),m=n[u][1];o.push([m,c])}),s(o)})}async subscribeErc20Balance(e,t,s){let r=t.filter(i=>i.type==="Erc20"),n=async()=>{let i=[];(await Promise.all(r.map(async a=>[a.id,await this.getErc20Balance(e,a.id)]))).forEach(([a,u])=>{i.push([a,u])}),s(i)};return await n(),this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:n}=e,i=new x.BigNumber(t),o=new x.BigNumber(s||n),a=new x.BigNumber(r||0n),u=o.gt(a)?o:a;return i.minus(u)}};var tt=require("@galacticcouncil/math-liquidity-mining"),Bt=require("@polkadot/types"),st=require("@polkadot/util"),rt=require("@polkadot/util-crypto");var _e=class extends L{balanceClient;constructor(e){super(e),this.balanceClient=new W(e)}secondsInYear=new x.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([r,n])=>{let[,i]=r.args,o=n.unwrap().toString(),a=i.toString(),u=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),h=u.rewardCurrency.toString(),P=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:P.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,n])=>{let[,i]=r.args,o=n.unwrap().toString(),a=i.toString(),u=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),h=u.rewardCurrency.toString(),P=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:P.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new x.BigNumber(1).shiftedBy(18).toString();let n=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(n.isNone)return;let[i]=n.unwrap(),o=i.price.n.toString(),a=i.price.d.toString(),u;return Number(t)<Number(s)?u=(0,tt.fixed_from_rational)(o,a):u=(0,tt.fixed_from_rational)(a,o),u}getGlobalRewardPerPeriod(e,t,s,r){let i=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return i.gte(s)?s:i}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}padEndU8a(e,t){return(0,st.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",n=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Bt.GenericAccountId32(e,this.padEndU8a((0,st.u8aConcat)(r,n,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,rt.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,rt.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:o,globalFarm:a,priceAdjustment:u,potBalance:c})=>{let m=new x.BigNumber(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),d=new x.BigNumber(a.yieldPerPeriod.toString()),h=new x.BigNumber(a.maxRewardPerPeriod.toString()),P=a.blocksPerPeriod.toString(),f=new x.BigNumber(o.multiplier.toString()).shiftedBy(-18),v=this.secondsInYear.div(new x.BigNumber(s).times(P)),S;if(m.isZero())S=d.times(f).times(v);else{let X=this.getGlobalRewardPerPeriod(m,d,h,u);S=this.getPoolYieldPerPeriod(X,f,m,u).times(v)}let A=new x.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),I=h.times(g),w=c?A.plus(c):I;return A.div(w).gte(.999)?y:S.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),y).toString():void 0}};var Pe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},nt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Q=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},it=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},ot=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},at=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},lt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var ye=(l,e)=>l===e?0:l==null?e==null?0:-1:e==null?l==null?0:1:typeof l.compare=="function"?l.compare(e):typeof e.compare=="function"?-e.compare(l):l<e?-1:l>e?1:0;var Ee=(l,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(l(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var Zt=Ee(()=>"illegal argument(s)"),At=l=>{throw new Zt(l)};var Qt=Ee(()=>"index out of bounds"),ut=l=>{throw new Qt(l)},ke=(l,e,t)=>(l<e||l>=t)&&ut(l);var It=23283064365386963e-26,Ce=class{float(e=1){return this.int()*It*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*It-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var De=class extends Ce{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 Tt=new De(Math.random);var Nt=l=>l!=null&&typeof l!="function"&&l.length!==void 0;var Ft=Object.getPrototypeOf({}),Le="function",Rt="string",oe=(l,e)=>{let t;if(l===e)return!0;if(l!=null){if(typeof l.equiv===Le)return l.equiv(e)}else return l==e;if(e!=null){if(typeof e.equiv===Le)return e.equiv(l)}else return l==e;return typeof l===Rt||typeof e===Rt?!1:(t=Object.getPrototypeOf(l),(t==null||t===Ft)&&(t=Object.getPrototypeOf(e),t==null||t===Ft)?rs(l,e):typeof l!==Le&&l.length!==void 0&&typeof e!==Le&&e.length!==void 0?es(l,e):l instanceof Set&&e instanceof Set?ts(l,e):l instanceof Map&&e instanceof Map?ss(l,e):l instanceof Date&&e instanceof Date?l.getTime()===e.getTime():l instanceof RegExp&&e instanceof RegExp?l.toString()===e.toString():l!==l&&e!==e)},es=(l,e,t=oe)=>{let s=l.length;if(s===e.length)for(;s-- >0&&t(l[s],e[s]););return s<0},ts=(l,e,t=oe)=>l.size===e.size&&t([...l.keys()].sort(),[...e.keys()].sort()),ss=(l,e,t=oe)=>l.size===e.size&&t([...l].sort(),[...e].sort()),rs=(l,e,t=oe)=>{if(Object.keys(l).length!==Object.keys(e).length)return!1;for(let s in l)if(!e.hasOwnProperty(s)||!t(l[s],e[s]))return!1;return!0};var ct=class{value;constructor(e){this.value=e}deref(){return this.value}};var _t=l=>l instanceof ct;var Me=class l{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Et("next",this._head)}reverseIterator(){return Et("prev",this.tail)}clear(){this.release()}compare(e,t=ye){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,n=e._head,i=0;for(;s-- >0&&i===0;)i=t(r.value,n.value),r=r.next,n=n.next;return i}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof l||Nt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!oe(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.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||ye;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!_t(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >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,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&ut(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}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,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*Et(l,e){for(;e;)yield e.value,e=e[l]}var qe=class l extends Me{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new l(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new l}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(ke(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(ke(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new l,e)}nth(e,t){let s=this.nthCell(e);return s?s.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 s=this.nthCell(e),r=this.nthCell(t-1),n=i=>({first(){return i.value},next(){return i!==r&&i.next?n(i.next):void 0}});return s?n(s):void 0}shuffle(e,t=Tt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&At("invalid indices: ${from} / ${to}");let n=new l,i=this.nthCell(s);for(;i&&++s<=r;)n.push(i.value),i=i.next;return n}sort(e=ye){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let n=s,i=0;for(let a=0;a<t&&(i++,n=n.next,!!n);a++);let o=t;for(;i>0||o>0&&n;){let a;i===0?(a=n,n=n.next,o--):!n||o===0||e(s.value,n.value)<=0?(a=s,s=s.next,i--):(a=n,n=n.next,o--),this._tail?this._tail.next=a:this._head=a,a.prev=this._tail,this._tail=a}s=n}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),ke(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let n=new l;if(t>0)for(;r&&t-- >0;)this.remove(r),n.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let i of s)this.insertBefore(r,i);else for(let i of s)this.push(i);return n}};var ae=class l{map;items;opts;_size;constructor(e,t){let s={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=s.map(),this.items=new qe,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new l(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e),n=Math.max(0,s-(r?r.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(r,e,t,s):this._size-=n,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let s=this.map.get(e);return s?this.resetEntry(s):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:s}=this.opts;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e?.(r.k,r.v),this._size-=r.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,s,r){e?(this.opts.update?.(t,e.value.v,s),e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Ge=class l extends ae{constructor(e,t){super(e,{ttl:60*60*1e3,autoExtend:!1,...t})}empty(){return new l(null,this.opts)}has(e){return this.get(e)!==void 0}get(e,t){let s=this.map.get(e);if(s){if(s.value.t>=Date.now())return this.resetEntry(s);this.removeEntry(s)}return t}set(e,t,s=this.opts.ttl){let r=this.opts.ksize(e)+this.opts.vsize(t),n=this.map.get(e),i=Math.max(0,r-(n?n.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(n,e,t,r,s):this._size-=i,t}async getSet(e,t,s=this.opts.ttl){let r=this.get(e);return r!==void 0?r:this.set(e,await t(),s)}prune(){let e=Date.now(),t=this.items.head,s=0;for(;t;)t.value.t<e&&(this.removeEntry(t),s++),t=t.next;return s}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,s=Date.now(),r=this.items.head;for(;r&&(this._size>t||this.length>=e);)r.value.t<s&&this.removeEntry(r),r=r.next;return super.ensureSize()}doSetEntry(e,t,s,r,n=this.opts.ttl){let i=Date.now()+n;e?(this.opts.update?.(t,e.value.v,s),e.value.v=s,e.value.s=r,e.value.t=i,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r,t:i,ttl:n}),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 He=(l,e=new Map)=>t=>{let s;return e.has(t)?e.get(t):(e.set(t,s=l(t)),s)};var E=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n))(E||{}),ee=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n))(ee||{});var fe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,n){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=p(r.balance),o=p(n.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,assetInED:y,assetOutED:y}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=[];return t.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:n}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=[];return r.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:n}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return B(R,e.decimalsOut)}spotPriceOutGivenIn(e){return B(R,e.decimalsIn)}calculateTradeFee(e,t){return y}};var kt=require("@polkadot/util-crypto"),Ct=require("@polkadot/util"),Dt=require("viem");function mt(l,e){let t=[];return JSON.stringify(l,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function ns(l,e,t){let s;return JSON.stringify(l,(r,n)=>(n&&n[e]===t&&(s=n),n)),s}var is=(l,e)=>typeof e=="bigint"?e.toString():e;var q=class extends W{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Ge(null,{maxlen:1,ttl:60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=He(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let n=this.subscribePoolChange(t);s.push(n)}catch{}if(t.type==="Aave")return s;let r=this.subscribeTokensPoolBalance(t);if(s.push(r),this.hasSystemAsset(t)){let n=this.subscribeSystemPoolBalance(t);s.push(n)}if(this.hasErc20Asset(t)){let n=this.subscribeErc20PoolBalance(t);s.push(n)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}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 s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,n])=>{let i=e.tokens.findIndex(o=>o.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=n.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(n=>n.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var os=["Supply","Withdraw","Repay","Borrow"],be=class extends q{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:s,liqudityIn:r,liqudityOut:n})=>({address:this.getPoolId(t.toString(),s.toString()),type:"Aave",tokens:[{id:t.toString(),balance:r.toString()},{id:s.toString(),balance:n.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let s=e+"/"+t;return(0,kt.encodeAddress)((0,Ct.stringToU8a)(s.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);return this.api.query.system.events(n=>{n.forEach(i=>{let{event:o}=i,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:u,assetOut:c}=o.data.toHuman(),m=u.replace(/,/g,""),g=c.replace(/,/g,"");(m===s.id||g===s.id)&&(this.log(`Sync AAVE [router:Executed] :: ${m}:${g}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:u}=o.data.toHuman();try{let{eventName:c,args:m}=(0,Dt.decodeEventLog)({abi:se,topics:u.topics,data:u.data});os.includes(c)&&m.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut:n}=await this.api.call.aaveTradeExecutor.pool(t.id,s.id);e.tokens=e.tokens.map(i=>{let o=i.id===t.id?r.toString():n.toString();return{...i,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?mt(e.location,"accountKey20").accountKey20.key:Y.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};var z=require("@galacticcouncil/math-lbp"),U=class{static getSpotPrice(e,t,s,r,n){return(0,z.get_spot_price)(e,t,s,r,n)}static calculateInGivenOut(e,t,s,r,n){return(0,z.calculate_in_given_out)(e,t,s,r,n)}static calculateOutGivenIn(e,t,s,r,n){return(0,z.calculate_out_given_in)(e,t,s,r,n)}static calculateLinearWeights(e,t,s,r,n){return(0,z.calculate_linear_weights)(e,t,s,r,n)}static calculatePoolTradeFee(e,t,s){return(0,z.calculate_pool_trade_fee)(e,t,s)}};function k(l,e){return l.shiftedBy(-1*e).toString()}function G(l){return l[0]/l[1]*100}function N(l){return l[0]/l[1]}function C(l){return[l/1e3,1e3]}var Se=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,n,i,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.fee=i,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=p(r.balance),o=p(n.balance);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:r.decimals,decimalsOut:n.decimals,weightIn:r.weight,weightOut:n.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let i=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(i)&&n.push("MaxOutRatioExceeded"),r===e.assetOut){let o=this.calculateTradeFee(t,s),a=G(this.repayFeeApply?s.repayFee:s.exchangeFee),u=t.plus(o),c=this.calculateInGivenOut(e,u),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&n.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:n}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&n.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:n}}}validateAndSell(e,t,s){let r=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let i=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(i)&&n.push("MaxInRatioExceeded"),r===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:n}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,s),u=G(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:u,errors:n}}}calculateInGivenOut(e,t){let s=U.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?y:r}calculateOutGivenIn(e,t){let s=U.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?y:r}spotPriceInGivenOut(e){let t=U.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),B(R,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=U.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),B(R,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let s=U.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(s)}};var xe=class extends q{MAX_FINAL_WEIGHT=B(p(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([n,i])=>this.isActivePool(i.unwrap(),s)).map(async([{args:[n]},i])=>{let o=i.unwrap(),a=n.toString(),u=await this.getPoolDelta(a,o,s.toString());return this.poolsData.set(n.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...u,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let i=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,i)}else{let i=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(i,1)}})}async getPoolDelta(e,t,s){let{start:r,end:n,assets:i,initialWeight:o,finalWeight:a,repayTarget:u,feeCollector:c}=t,m=U.calculateLinearWeights(r.toString(),n.toString(),o.toString(),a.toString(),s),[g,d]=i,h=g.toString(),P=p(m),f=d.toString(),v=this.MAX_FINAL_WEIGHT.minus(p(P)),[S,A,I]=await Promise.all([this.isRepayFeeApplied(h,u.toString(),c.toString()),this.getBalance(e,h),this.getBalance(e,f)]);return{repayFeeApply:S,tokens:[{id:h,weight:P,balance:A.toString()},{id:f,weight:v,balance:I.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=p(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var b=require("@galacticcouncil/math-omnipool");var O=class{static calculateSpotPrice(e,t,s,r){return(0,b.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,b.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,n,i,o,a,u){return(0,b.calculate_in_given_out)(e,t,s,r,n,i,o,a,u)}static calculateLrnaInGivenOut(e,t,s,r,n){return(0,b.calculate_lrna_in_given_out)(e,t,s,r,n)}static calculateOutGivenIn(e,t,s,r,n,i,o,a,u){return(0,b.calculate_out_given_in)(e,t,s,r,n,i,o,a,u)}static calculateOutGivenLrnaIn(e,t,s,r,n){return(0,b.calculate_out_given_lrna_in)(e,t,s,r,n)}static calculatePoolTradeFee(e,t,s){return(0,b.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,b.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,n,i,o,a){return(0,b.calculate_liquidity_out)(e,t,s,r,n,i,o,a)}static calculateLiquidityLRNAOut(e,t,s,r,n,i,o,a){return(0,b.calculate_liquidity_lrna_out)(e,t,s,r,n,i,o,a)}static calculateCapDifference(e,t,s,r){let n=(0,x.BigNumber)(t),i=(0,x.BigNumber)(e),o=(0,x.BigNumber)(r),u=(0,x.BigNumber)(s).shiftedBy(-18);if(n.div(o).lt(u)){let m=u.times(o).minus(n).times(i),g=n.times((0,x.BigNumber)(1).minus(u));return m.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return(0,b.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,b.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,b.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,b.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,b.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,s,r,n,i,o,a,u,c,m){return(0,b.recalculate_asset_fee)(e,t,s,r,n,i,o,a,u,c,m)}static recalculateProtocolFee(e,t,s,r,n,i,o,a,u,c,m){return(0,b.recalculate_protocol_fee)(e,t,s,r,n,i,o,a,u,c,m)}static verifyAssetCap(e,t,s,r){return(0,b.verify_asset_cap)(e,t,s,r)}};var ve=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,n,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.hubAssetId=i}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=p(r.balance),o=p(n.balance),a=p(r.existentialDeposit),u=p(n.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:n.hubReserves,sharesIn:r.shares,sharesOut:n.shares,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,tradeableIn:r.tradeable,tradeableOut:n.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,s),i=n.minus(r),o=r===y?y:i.div(r).multipliedBy(100).decimalPlaces(2),a=[],u=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&a.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(g)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,s),o=r.minus(n).div(r).multipliedBy(100).decimalPlaces(2),a=[],u=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!u||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&a.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(g)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=O.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?N(s.assetFee).toString():y.toString(),s?N(s.protocolFee).toString():y.toString()),n=p(r);return n.isNegative()?y:n}calculateLrnaInGivenOut(e,t,s){let r=O.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?N(s.assetFee).toString():y.toString()),n=p(r);return n.isNegative()?y:n}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=O.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?N(s.assetFee).toString():y.toString(),s?N(s.protocolFee).toString():y.toString()),n=p(r);return n.isNegative()?y:n}calculateOutGivenLrnaIn(e,t,s){let r=O.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?N(s.assetFee).toString():y.toString()),n=p(r);return n.isNegative()?y:n}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=O.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=O.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=O.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=O.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var Lt=require("@polkadot/util-crypto"),Mt=require("@polkadot/util");var we=class extends q{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,n]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),i=s.map(async([{args:[a]},u])=>{let{hubReserve:c,shares:m,tradable:g,cap:d,protocolShares:h}=u.unwrap(),P=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:g.bits.toNumber(),balance:P.toString(),cap:p(d.toString()),protocolShares:p(h.toString())}}),o=await Promise.all(i);return o.push({id:e,tradeable:r.bits.toNumber(),balance:n.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,n="omnipool",i="Short",o=I=>I===D?[D,de]:[de,I],[a,u,c,m]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(n,o(s),i),this.api.query.emaOracle.oracles(n,o(r),i)]),[g,d,h]=this.getAssetFee(e,a.toNumber(),u,c),[P,f,v]=r===de?[0,0,0]:this.getProtocolFee(e,a.toNumber(),u,m),S=g+P,A=h+v;return{assetFee:C(d),protocolFee:C(f),min:C(S),max:C(A)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,n)=>{let i=e.tokens[n];if(r.isNone)return i;let o=r.unwrap();return this.updateTokenState(i,o)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:n,cap:i,protocolShares:o}=t;return{...e,hubReserves:p(s.toString()),shares:p(r.toString()),cap:p(i.toString()),protocolShares:p(o.toString()),tradeable:n.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:n,balanceOut:i}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,m=C(o.toNumber()),g=C(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{assetFee:h,timestamp:P}=s.unwrap(),f=Math.max(1,t-P.toNumber()),v=d.volume.bIn.toString(),S=d.volume.bOut.toString(),A=d.liquidity.b.toString();n===D&&(v=d.volume.aIn.toString(),S=d.volume.aOut.toString(),A=d.liquidity.a.toString());let I=C(h.toNumber()),w=O.recalculateAssetFee(v,S,A,"9",i.toString(),N(I).toString(),f.toString(),N(m).toString(),N(g).toString(),u.toString(),c.toString());return[o.toNumber(),Number(w)*1e6,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:n,balanceIn:i}=e,{minFee:o,maxFee:a,decay:u,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,m=C(o.toNumber()),g=C(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{protocolFee:h,timestamp:P}=s.unwrap(),f=Math.max(1,t-P.toNumber()),v=d.volume.bIn.toString(),S=d.volume.bOut.toString(),A=d.liquidity.b.toString();n===D&&(v=d.volume.aIn.toString(),S=d.volume.aOut.toString(),A=d.liquidity.a.toString());let I=C(h.toNumber()),w=O.recalculateProtocolFee(v,S,A,"9",i.toString(),N(I).toString(),f.toString(),N(m).toString(),N(g).toString(),u.toString(),c.toString());return[o.toNumber(),Number(w)*1e6,a.toNumber()]}getPoolId(){return(0,Lt.encodeAddress)((0,Mt.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var F=require("@galacticcouncil/math-xyk"),$=class{static getSpotPrice(e,t,s){return(0,F.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,F.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,F.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,F.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,F.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,F.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,F.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,F.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,F.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,F.calculate_liquidity_out_asset_b)(e,t,s,r)}};var Oe=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,n){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=p(r.balance),o=p(n.balance),a=p(r.existentialDeposit),u=p(n.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateTradeFee(r,s),i=G(s.exchangeFee),o=r.plus(n),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(r,s),i=G(s.exchangeFee),o=r.minus(n),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:i,errors:a}}calculateInGivenOut(e,t){let s=$.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?y:r}calculateOutGivenIn(e,t){let s=$.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?y:r}spotPriceInGivenOut(e){let t=$.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=B(R,18-e.decimalsOut);return p(t).div(s)}spotPriceOutGivenIn(e){let t=$.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=B(R,18-e.decimalsIn);return p(t).div(s)}calculateTradeFee(e,t){let s=$.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(s)}};var Be=class extends q{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let n=s.toString(),[i,o]=r.unwrap(),[a,u]=await Promise.all([this.getBalance(n,i.toString()),this.getBalance(n,o.toString())]);return{address:n,type:"Xyk",tokens:[{id:i.toString(),balance:a.toString()},{id:o.toString(),balance:u.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var T=require("@galacticcouncil/math-stableswap"),_=class{static getPoolAddress(e){return(0,T.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let s=0;s<e;s++)t.push(["1","1"]);return t}static calculateAmplification(e,t,s,r,n){return(0,T.calculate_amplification)(e,t,s,r,n)}static calculateInGivenOut(e,t,s,r,n,i,o){return(0,T.calculate_in_given_out)(e,t,s,r,n,i,o)}static calculateAddOneAsset(e,t,s,r,n,i,o){return(0,T.calculate_add_one_asset)(e,t,s,r,n,i,o)}static calculateSharesForAmount(e,t,s,r,n,i,o){return(0,T.calculate_shares_for_amount)(e,t,s,r,n,i,o)}static calculateOutGivenIn(e,t,s,r,n,i,o){return(0,T.calculate_out_given_in)(e,t,s,r,n,i,o)}static calculateLiquidityOutOneAsset(e,t,s,r,n,i,o){return(0,T.calculate_liquidity_out_one_asset)(e,t,s,r,n,i,o)}static calculateShares(e,t,s,r,n,i){return(0,T.calculate_shares)(e,t,s,r,n,i)}static calculateSpotPriceWithFee(e,t,s,r,n,i,o,a){return(0,T.calculate_spot_price_with_fee)(e,t,s,r,n,i,o,a)}static calculatePoolTradeFee(e,t,s){return(0,T.calculate_pool_trade_fee)(e,t,s)}static recalculatePegs(e,t,s,r,n){let i=(0,T.recalculate_peg)(e,t,s,r,n);return JSON.parse(i)}};var Ae=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,n,i,o,a,u,c,m){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.amplification=i,this.id=o,this.fee=a,this.totalIssuance=u,this.pegs=c,this.pegsFee=m}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=p(r.balance),o=p(n.balance),a=p(r.existentialDeposit),u=p(n.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:r.decimals,decimalsOut:n.decimals,tradeableIn:this.id===e?15:r.tradeable,tradeableOut:this.id===t?15:n.tradeable,assetInED:a,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,s),i=G(s.fee),o=[],a=O.isSellAllowed(e.tradeableIn),u=O.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:i,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,s),i=G(s.fee),o=[],a=O.isSellAllowed(e.tradeableIn),u=O.isBuyAllowed(e.tradeableOut);return(!a||!u)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:i,errors:o}}calculateIn(e,t,s){let r=_.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?N(s.fee).toString():y.toString(),this.getPegs()),n=p(r);return n.isNegative()?y:n}calculateAddOneAsset(e,t,s){let r=_.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?N(s.fee).toString():y.toString(),this.getPegs()),n=p(r);return n.isNegative()?y:n}calculateSharesForAmount(e,t,s){let r=_.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?N(s.fee).toString():y.toString(),this.getPegs()),n=p(r);return n.isNegative()?y:n}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let r=B(R,e.decimalsIn-e.decimalsOut);return p(t).div(r)}let s=B(R,18-e.decimalsIn);return p(t).div(s)}calculateOut(e,t,s){let r=_.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?N(s.fee).toString():y.toString(),this.getPegs()),n=p(r);return n.isNegative()?y:n}calculateWithdrawOneAsset(e,t,s){let r=_.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?N(s.fee).toString():y.toString(),this.getPegs()),n=p(r);return n.isNegative()?y:n}calculateShares(e,t,s){let r=_.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?N(s.fee).toString():y.toString(),this.getPegs()),n=p(r);return n.isNegative()?y:n}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let r=B(R,e.decimalsOut-e.decimalsIn);return p(t).div(r)}let s=B(R,18-e.decimalsOut);return p(t).div(s)}calculateTradeFee(e,t){let s=_.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return p(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var Ue=require("@polkadot/util-crypto");var qt=340282366920938463463374607431768211455n,Ie=class extends q{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[n]},i])=>{let o=i.unwrap(),a=n.toString(),u=this.getPoolAddress(a),[c,m,g]=await Promise.all([this.getPoolDelta(a,o,s.toString()),this.getPoolTokens(u,a,o),this.getPoolPegs(a,o,s.toString())]);return this.stablePools.set(u,o),{address:u,id:a,type:"Stableswap",fee:C(o.fee.toNumber()),tokens:m,...c,...g,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toString(),r=this.stablePools.get(e.address);if(r){let[n,i]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,n,i)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:n,initialBlock:i,finalBlock:o}=t,a=_.calculateAmplification(r.toString(),n.toString(),i.toString(),o.toString(),s),u=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:u.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,n=r.map(async o=>{let[a,u]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:a.bits.toNumber(),balance:u.toString()}}),i=await Promise.all(n);return i.push({id:t,tradeable:15,balance:qt.toString()}),i}getPoolDefaultPegs(e){let t=e.fee,s=_.defaultPegs(e.assets.length);return{pegsFee:C(t.toNumber()),pegs:s}}async getPoolPegs(e,t,s){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let r=await this.api.query.stableswap.poolPegs(e);if(r.isNone)return this.getPoolDefaultPegs(t);let n=r.unwrap(),i=await this.getLatestPegs(t,n,s),o=this.getRecentPegs(n),a=n.maxPegUpdate.toHuman(),u=t.fee.toHuman(),[c,m]=_.recalculatePegs(JSON.stringify(o),JSON.stringify(i),s,a.replace(/%/g,""),u.replace(/%/g,"")),g=Number(c)*1e4;return{pegsFee:C(g),pegs:m}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([s,r])=>r.map(n=>n.toString()))}async getLatestPegs(e,t,s){let{source:r}=t,n=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),i=r.map(async(o,a)=>{if(o.isOracle){let[u,c,m]=o.asOracle,g=[m.toString(),n[a]].map(S=>Number(S)).sort((S,A)=>S-A),d=await this.api.query.emaOracle.oracles(u,g,c),[{price:h,updatedAt:P}]=d.unwrap(),f=h.n.toString(),v=h.d.toString();return m.toString()===g[0].toString()?[[f,v],P.toString()]:[[v,f],P.toString()]}else return[o.asValue.map(u=>u.toString()),s]});return Promise.all(i)}getPoolAddress(e){let t=Number(e),s=_.getPoolAddress(t);return(0,Ue.encodeAddress)((0,Ue.blake2AsHex)(s),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var le=class extends L{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=He(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new ie(this.api),this.aaveClient=new be(this.api),this.xykClient=new Be(this.api),this.omniClient=new we(this.api),this.lbpClient=new xe(this.api),this.stableClient=new Ie(this.api),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new Pe(t.type)}}};var We=class extends le{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new ae(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let n=await super.getPoolFees(e,t);return this.feeCache.set(s,n),n}}async destroy(){this.log(`Destroying pool cache!
2
2
  Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var ue=class{static get(e){switch(e.type){case"Aave":return fe.fromPool(e);case"Xyk":return Oe.fromPool(e);case"Omnipool":return ve.fromPool(e);case"Lbp":return Se.fromPool(e);case"Stableswap":return Ae.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var ze=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var as=5,Te=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],n=new ze,i=[];for(i.push([t,""]),n.enqueue(i);n.size()>0;){let o=n.dequeue();if(o==null||o.length>as)return r;let a=o[o.length-1];(s===null||a[0]===s)&&r.push(o),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let m=[...o];m.push(c),n.enqueue(m)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,n,i]of t){let o=parseInt(n),a=parseInt(i);s.get(o)?.push([a,r])}return s}};function pt(l){let e={};for(let t of l){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let n=0;n<s;n++){if(r==n)continue;let i=[t.address,t.tokens[r].id,t.tokens[n].id];e[t.tokens[r].id].push(i)}}}return e}var Ne=class{getProposals(e,t,s){let r=pt(s),n=Object.keys(r),i=n.map(c=>r[c]).flat(),o=new Te,a=o.buildAndPopulateGraph(n,i),u=o.findPaths(a,parseInt(e),t?parseInt(t):null);return this.parsePaths(u)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let n=0;n<s.length;n++){let i=s[n],o=s[n+1];if(o==null)break;r.push(this.toEdge(i,o))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ce=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Ne,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),i=this.getPaths(e,null,r,t).map(o=>o[o.length-1].assetOut);return this.toAssets([...new Set(i)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,meta:r.meta,location:r.location,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let n=this.getPoolMap(s);return{assets:r,poolsMap:n}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,ue.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,n])=>{let i=t.get(s);return{poolAddress:s,poolId:i?.id,pool:i?.type,assetIn:r,assetOut:n}})}toAssets(e,t){return e.map(s=>t.get(s))}};var ls=p("100");function us(l,e){return l.minus(e).abs().div(l.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function me(l,e){return l.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function dt(l,e){return R.minus(e.div(l)).multipliedBy(100).decimalPlaces(2)}function gt(l,e){return e.div(l).minus(R).multipliedBy(100).decimalPlaces(2)}function pe(l,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),l.div(ls).multipliedBy(e).decimalPlaces(0,1)}var Xe=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Xe||{});var Ye=class extends ce{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let n=s[s.length-1].amountOut,i=r[r.length-1].amountOut;return n.isGreaterThan(i)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,i)=>n+i),r=e.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,i)=>n+i);return[s,r]}}getPoolFeeRange(e){let t=e.min?G(e.min):void 0,s=e.max?G(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,n),o=super.getPaths(e,t,i,n);if(o.length===0)throw new Q(e,t);let a;if(r)a=await this.toSellSwaps(s,r,i);else{let w=o.map(async X=>await this.toSellSwaps(s,X,i)),M=await Promise.all(w);a=this.findBestSellRoute(M)}let u=a[0],c=a[a.length-1],m=this.isDirectTrade(a),g=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,M)=>w.multipliedBy(M)),d=B(g,c.assetOutDecimals),h=m?c.calculatedOut:this.calculateDelta0Y(u.amountIn,a,i),P=c.amountOut,f=m?c.tradeFeePct:dt(h,P).toNumber(),v=h.minus(P),S=this.getRouteFeeRange(a),A=u.amountIn.shiftedBy(-1*u.assetInDecimals).multipliedBy(d),I=me(h,A);return{type:"Sell",amountIn:u.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:v,tradeFeePct:f,tradeFeeRange:S,priceImpactPct:I.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:k(u.amountIn,u.assetInDecimals),amountOut:k(c.amountOut,c.assetOutDecimals),spotPrice:k(d,c.assetOutDecimals),tradeFee:k(v,c.assetOutDecimals),tradeFeePct:f,tradeFeeRange:S,priceImpactPct:I.toNumber(),swaps:a.map(w=>w.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let n=0;n<t.length;n++){let i=t[n],o=s.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(i.assetIn,i.assetOut),u;n>0?u=r[n-1]:u=e;let c=o.calculateOutGivenIn(a,u);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let n=0;n<t.length;n++){let i=t[n],o=s.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(i.assetIn,i.assetOut),u;n>0?u=r[n-1].amountOut:u=B(p(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:m,calculatedOut:g,feePct:d,errors:h}=o.validateAndSell(a,u,c),P=this.getPoolFeeRange(c),f=o.spotPriceOutGivenIn(a),v=u.shiftedBy(-1*a.decimalsIn).multipliedBy(f),S=me(g,v);r.push({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,calculatedOut:g,amountOut:m,spotPrice:f,tradeFeePct:d,tradeFeeRange:P,priceImpactPct:S.toNumber(),errors:h,isSupply(){return o.type==="Aave"&&o.tokens[0].id===i.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:k(u,a.decimalsIn),calculatedOut:k(g,a.decimalsOut),amountOut:k(m,a.decimalsOut),spotPrice:k(f,a.decimalsOut),tradeFeePct:d,tradeFeeRange:P,priceImpactPct:S.toNumber(),errors:h}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),n=super.getPaths(e,t,r,s);if(n.length===0)throw new Q(e,t);let u=s.filter(d=>d.tokens.some(h=>h.id===e&&h.id!==d.id)).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,P)=>h.plus(P))).sort((d,h)=>h.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=n.map(async d=>await this.toSellSwaps(u,d,r)),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 s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s);if(super.getPaths(e,t,r,s).length===0)return Promise.resolve(void 0);let i=await this.getMostLiquidRoute(e,t),o=await this.toSellSwaps("1",i,r),a=o.map(m=>m.spotPrice.shiftedBy(-1*m.assetOutDecimals)).reduce((m,g)=>m.multipliedBy(g)),u=o[o.length-1].assetOutDecimals;return{amount:B(a,u),decimals:u}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let n=s[0].amountIn,i=r[0].amountIn;return n.isGreaterThan(i)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,n),o=super.getPaths(e,t,i,n);if(o.length===0)throw new Q(e,t);let a;if(r)a=await this.toBuySwaps(s,r,i);else{let w=o.map(async X=>await this.toBuySwaps(s,X,i)),M=await Promise.all(w);a=this.findBestBuyRoute(M)}let u=a[a.length-1],c=a[0],m=this.isDirectTrade(a),g=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetInDecimals)).reduce((w,M)=>w.multipliedBy(M)),d=B(g,c.assetInDecimals),h=m?c.calculatedIn:this.calculateDelta0X(u.amountOut,a,i),P=c.amountIn,f=m?c.tradeFeePct:gt(h,P).toNumber(),v=P.minus(h),S=this.getRouteFeeRange(a),A=u.amountOut.shiftedBy(-1*u.assetOutDecimals).multipliedBy(d),I;return h.isZero()?I=-100:I=me(A,h).toNumber(),{type:"Buy",amountOut:u.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:v,tradeFeePct:f,tradeFeeRange:S,priceImpactPct:I,swaps:a,toHuman(){return{type:"Buy",amountOut:k(u.amountOut,u.assetOutDecimals),amountIn:k(c.amountIn,c.assetInDecimals),spotPrice:k(d,c.assetInDecimals),tradeFee:k(v,c.assetInDecimals),tradeFeePct:f,tradeFeeRange:S,priceImpactPct:I,swaps:a.map(w=>w.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let n=t.length-1;n>=0;n--){let i=t[n],o=s.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(i.assetIn,i.assetOut),u;n==t.length-1?u=e:u=r[0];let c=o.calculateInGivenOut(a,u);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let n=t.length-1;n>=0;n--){let i=t[n],o=s.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(i.assetIn,i.assetOut),u;n==t.length-1?u=B(p(e),a.decimalsOut).decimalPlaces(0,1):u=r[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:m,calculatedIn:g,feePct:d,errors:h}=o.validateAndBuy(a,u,c),P=this.getPoolFeeRange(c),f=o.spotPriceInGivenOut(a),v=u.shiftedBy(-1*a.decimalsOut).multipliedBy(f),S;g.isZero()?S=-100:S=me(v,g).toNumber(),r.unshift({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:u,calculatedIn:g,amountIn:m,spotPrice:f,tradeFeePct:d,tradeFeeRange:P,priceImpactPct:S,errors:h,isSupply(){return o.type==="Aave"&&o.tokens[0].id===i.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:k(u,a.decimalsOut),calculatedIn:k(g,a.decimalsIn),amountIn:k(m,a.decimalsIn),spotPrice:k(f,a.decimalsIn),tradeFeePct:d,tradeFeeRange:P,priceImpactPct:S,errors:h}}})}return r}};var Ht=require("viem");var $e=class extends L{balanceClient;evmClient;constructor(e){super(e),this.balanceClient=new W(e),this.evmClient=new K}buildBuyTx(e,t=1){if(e.type!=="Buy")throw new Error("Not permitted");let{amountIn:s,amountOut:r,swaps:n}=e,i=n[0],o=n[n.length-1],a=pe(s,t),u=i.assetIn,c=o.assetOut,m=s.plus(a),g;return this.isDirectOmnipoolTrade(n)?g=this.api.tx.omnipool.buy(c,u,r.toFixed(),m.toFixed()):g=this.api.tx.router.buy(u,c,r.toFixed(),m.toFixed(),this.buildRoute(n)),{hex:g.toHex(),name:"RouterBuy",get:()=>g,dryRun:d=>this.dryRun(d,g)}}buildSellTx(e,t=1){if(e.type!=="Sell")throw new Error("Not permitted");let{amountIn:s,amountOut:r,swaps:n}=e,i=n[0],o=n[n.length-1],a=pe(r,t),u=i.assetIn,c=o.assetOut,m=r.minus(a),g;return this.isDirectOmnipoolTrade(n)?g=this.api.tx.omnipool.sell(u,c,s.toFixed(),m.toFixed()):g=this.api.tx.router.sell(u,c,s.toFixed(),m.toFixed(),this.buildRoute(n)),{hex:g.toHex(),name:"RouterSell",get:()=>g,dryRun:d=>this.dryRun(d,g)}}buildSellAllTx(e,t=1){if(e.type!=="Sell")throw new Error("Not permitted");let{amountOut:s,swaps:r}=e,n=r[0],i=r[r.length-1],o=pe(s,t),a=n.assetIn,u=i.assetOut,c=s.minus(o),m=this.api.tx.router.sellAll(a,u,c.toFixed(),this.buildRoute(r));return{hex:m.toHex(),name:"RouterSellAll",get:()=>m,dryRun:g=>this.dryRun(g,m)}}async buildWithdrawAndSellReserveTx(e,t,s=1){let{amountIn:r,amountOut:n,swaps:i}=t,o=i[0],a=i[i.length-1];if(!o.isWithdraw())throw new Error("Not permitted");let u=o.assetIn,c=o.assetOut,[m,g]=await Promise.all([this.evmClient.getProvider().getGasPrice(),this.balanceClient.getBalance(e,u)]),d=r.isGreaterThanOrEqualTo(g.minus(5)),h=m*10n/100n,P=Z.fromAny(e),f=d?Pt:BigInt(r.toFixed()),v=Y.fromAssetId(c),S=(0,Ht.encodeFunctionData)({abi:se,functionName:"withdraw",args:[v,f,P]}),A=this.api.tx.evm.call(P,Fe,S,0n,ht,m+h,m+h,null,[]),I=pe(n,s),w=c,M=a.assetOut,X=n.minus(I),te=this.api.tx.router.sell(w,M,r.minus(5).toFixed(),X.toFixed(),this.buildRoute(i.slice(1))),Ve=this.api.tx.utility.batchAll([A,te]);return{hex:Ve.toHex(),name:"WithdrawAndRouterReserveSell",get:()=>Ve,dryRun:Ut=>this.dryRun(Ut,Ve)}}buildRoute(e){return e.map(({assetIn:t,assetOut:s,pool:r,poolId:n})=>r==="Stableswap"?{pool:{Stableswap:n},assetIn:t,assetOut:s}:{pool:r,assetIn:t,assetOut:s})}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};0&&(module.exports={AMOUNT_MAX,AaveClient,AavePool,AavePoolClient,AaveUtils,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,ERC20,EvmClient,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,ONE,OmniMath,OmniPool,OmniPoolClient,PolkadotApiClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StableSwapClient,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,TradeUtils,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,evmMainnet,findNestedKey,findNestedObj,getFraction,isEvmAccount,isEvmAddress,isSs58Address,scale});
package/build/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var $=[{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 Oe=[{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 le="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ae="0x112b087b60C1a166130d59266363C45F8aa99db0",Ie="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",De=1000000n;var Ce=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");import{defineChain as st}from"viem";var Le=["https://rpc.hydradx.cloud","https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],Me=["wss://rpc.hydradx.cloud","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"],Ge=st({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:Le,webSocket:Me},default:{http:Le,webSocket:Me}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as qe,createWalletClient as rt,custom as nt,http as ot,webSocket as it}from"viem";var V=class{chain;constructor(e){this.chain=e||Ge}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return qe({chain:this.chain,transport:ot()})}getWsProvider(){return qe({chain:this.chain,transport:it()})}getSigner(e){return rt({account:e,chain:this.chain,transport:nt(window.ethereum)})}};var j=class{evmClient;constructor(){this.evmClient=new V}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Oe,address:Ae,args:[Ie],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:Oe,address:Ae,args:[Ie,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:$,address:le,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as ue,encodeAddress as Ue}from"@polkadot/util-crypto";import{hexToU8a as at,isHex as lt,u8aToHex as ct}from"@polkadot/util";import{Buffer as X}from"buffer";var Ys=2090,Te=1e3,ce="1",$s=2034,H=63,Z=18,_="0",Vs=12,Q=15;var He=X.from("ETH\0");function ut(p){if(!p)return!1;try{let e=ue(p,!0);return X.from(e.subarray(0,He.length)).equals(He)}catch{return!1}}function mt(p){return!!/^0x[a-fA-F0-9]{40}$/.test(p)}function pt(p){try{let e=lt(p)?at(p):ue(p);return Ue(e),!0}catch{return!1}}var z=class p{static prefixBytes=X.from("ETH\0");static toAccount=e=>{let t=X.from(e.slice(2),"hex");return Ue(new Uint8Array(X.concat([p.prefixBytes,t,X.alloc(8)])),63)};static fromAccount=e=>{let s=ue(e).slice(p.prefixBytes.length,-8);return"0x"+X.from(s).toString("hex")};static fromSS58=e=>{let s=ue(e).slice(0,20);return ct(s)};static fromAny=e=>{if(mt(e))return e;if(ut(e))return p.fromAccount(e);if(pt(e))return p.fromSS58(e);throw new Error("Unknown address type")}};var U=class{static fromAssetId(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),s=Buffer.from(e.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as S}from"bignumber.js";var dt=12;S.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:dt});var b=m(0),v=m(1),sr=m("Infinity");function I(p,e){let t=new S(e.toString()),s=new S(10).pow(t);return p.times(s)}function m(p){return new S(p.toString())}var gt=m("1e27"),lr=m("1e8"),cr=m("31536000"),ur=m("999999999"),Pt=m("1.01"),ve=class{client;constructor(){this.client=new j}async loadCtx(e,t){let s=z.fromAny(e),r=U.fromAssetId(t),[n,i,o]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(s),this.client.getUserAccountData(s)]),[a,l]=o,[c]=n,[u,g]=i,d=c.find(({underlyingAsset:Y})=>Y.toLowerCase()===r.toLowerCase()),P=u.find(({underlyingAsset:Y})=>Y.toLowerCase()===r.toLowerCase());if(!d||!P)throw new Error("Missing reserve or userReserve for "+t);let h=Number(d.decimals),y=m(d.priceInMarketReferenceCurrency),w=m(g===d.eModeCategoryId?d.eModeLiquidationThreshold:d.reserveLiquidationThreshold).div(1e4),f=m(d.liquidityIndex),O=m(P.scaledATokenBalance),A=m(a),x=m(l),k=d.usageAsCollateralEnabled&&P.usageAsCollateralEnabledOnUser&&m(P.scaledATokenBalance).gt(0),G=O.multipliedBy(f).dividedBy(gt).decimalPlaces(0,S.ROUND_DOWN);return{decimals:h,isCollateralAsset:k,priceInRef:y,reserveLiquidationThreshold:w,totalCollateralBase:A,totalDebtBase:x,userBalance:G}}async getMaxWithdraw(e,t){let{decimals:s,priceInRef:r,reserveLiquidationThreshold:n,totalCollateralBase:i,totalDebtBase:o,userBalance:a}=await this.loadCtx(e,t),l=m(i),c=m(o),u=Pt.multipliedBy(c).div(n).decimalPlaces(0,S.ROUND_UP),d=l.minus(u).decimalPlaces(0,1).multipliedBy(m(10).pow(s)).dividedBy(r).decimalPlaces(0,S.ROUND_DOWN);return{amount:S.minimum(a,d),decimals:s}}async getHealthFactorAfterWithdraw(e,t,s){let{decimals:r,isCollateralAsset:n,priceInRef:i,reserveLiquidationThreshold:o,totalCollateralBase:a,totalDebtBase:l}=await this.loadCtx(e,t),c=n?m(s).multipliedBy(i).dividedBy(m(10).pow(r)).decimalPlaces(0,S.ROUND_DOWN):b,u=a.minus(c);return u.lte(0)?0:u.multipliedBy(o).dividedBy(l).decimalPlaces(6,S.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,s){let{decimals:r,priceInRef:n,reserveLiquidationThreshold:i,totalCollateralBase:o,totalDebtBase:a}=await this.loadCtx(e,t),l=m(s).multipliedBy(n).dividedBy(m(10).pow(r)).decimalPlaces(0,S.ROUND_DOWN),c=o.plus(l);return c.lte(0)?0:c.multipliedBy(i).dividedBy(a).decimalPlaces(6,S.ROUND_DOWN).toNumber()}};import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var D=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}async dryRun(e,t){let s;try{s=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(r){throw console.error(r),new Error("Dry run execution failed!")}if(s.isOk)return s.asOk;throw console.log(s.asErr.toHuman()),new Error("Dry run execution error!")}log(e,...t){let s=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");this.getLogValue(s)&&console.log(e,...t)}getLogValue(e){switch(e){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}};var ee=class extends D{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]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:n}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:n.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==_){let u=this.api.consts.balances.existentialDeposit;return{id:_,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:u.toString()}}let{name:n,assetType:i,isSufficient:o,existentialDeposit:a}=t,{symbol:l,decimals:c}=s.get(e)??{};return{id:e,name:n.toHuman(),symbol:l,decimals:c,icon:l,type:i.toHuman(),isSufficient:o?o.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[n,i]=r,{assetType:o,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(n.toString(),t,s),g=i.toNumber(),d=new Intl.DateTimeFormat("en-GB"),P=[c,"Bond",d.format(g)].join(" ");return{id:e,name:P,symbol:c+"b",decimals:u,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:n.toString(),maturity:g}}getShares(e,t,s,r){let{assets:n}=r,{name:i,symbol:o,assetType:a,isSufficient:l,existentialDeposit:c}=t,g=n.map(h=>h.toString()).map(h=>{let{symbol:y}=this.getToken(h,t,s);return[h,y]}),d=Object.fromEntries(g),P=Object.values(d);return{id:e,name:P.join(", "),symbol:o?.isSome?o.toHuman():i.toHuman(),decimals:18,icon:P.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,s,r){let n=this.getToken(e,t,new Map,r),i=s?.find(o=>o.internalId===n.id);return i?{...n,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:n}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:n,symbol:i}=r.unwrap();return[s.toString(),{decimals:Number(n.toString()),symbol:i.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,n,i,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(s),l=this.normalizeMetadata(a,o),c=a.map(([{args:[u]},g])=>{let d=g.unwrap(),P=r.get(u.toString()),{assetType:h}=d;switch(h.toString()){case"Bond":let y=i.get(u.toString());return this.getBond(u.toString(),d,l,y);case"StableSwap":let w=n.get(u.toString());return this.getShares(u.toString(),d,l,w);case"External":return this.getExternal(u.toString(),d,t,P);default:return this.getToken(u.toString(),d,l,P)}});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 q=class extends D{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===_?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:n}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:n})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:n}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:0n,frozen:n})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(_,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let n=t.filter(i=>i.type!=="Erc20").filter(i=>i.id!==_).map(i=>[e,i.id]);return this.api.query.tokens.accounts.multi(n,i=>{let o=[];i.forEach((a,l)=>{let c=this.calculateFreeBalance(a),u=n[l][1];o.push([u,c])}),s(o)})}async subscribeErc20Balance(e,t,s){let r=t.filter(i=>i.type==="Erc20"),n=async()=>{let i=[];(await Promise.all(r.map(async a=>[a.id,await this.getErc20Balance(e,a.id)]))).forEach(([a,l])=>{i.push([a,l])}),s(i)};return await n(),this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:n}=e,i=new S(t),o=new S(s||n),a=new S(r||0n),l=o.gt(a)?o:a;return i.minus(l)}};import{fixed_from_rational as We}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as ht}from"@polkadot/types";import{u8aConcat as Xe}from"@polkadot/util";import{isAddress as Ye}from"@polkadot/util-crypto";var Ne=class extends D{balanceClient;constructor(e){super(e),this.balanceClient=new q(e)}secondsInYear=new S(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([r,n])=>{let[,i]=r.args,o=n.unwrap().toString(),a=i.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),P=l.rewardCurrency.toString(),h=await this.balanceClient.getTokenBalanceData(d,P);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:h.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,n])=>{let[,i]=r.args,o=n.unwrap().toString(),a=i.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),P=l.rewardCurrency.toString(),h=await this.balanceClient.getTokenBalanceData(d,P);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:h.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new S(1).shiftedBy(18).toString();let n=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(n.isNone)return;let[i]=n.unwrap(),o=i.price.n.toString(),a=i.price.d.toString(),l;return Number(t)<Number(s)?l=We(o,a):l=We(a,o),l}getGlobalRewardPerPeriod(e,t,s,r){let i=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return i.gte(s)?s:i}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}padEndU8a(e,t){return Xe(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",n=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new ht(e,this.padEndU8a(Xe(r,n,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!Ye(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&Ye(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:o,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let u=new S(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),d=new S(a.yieldPerPeriod.toString()),P=new S(a.maxRewardPerPeriod.toString()),h=a.blocksPerPeriod.toString(),y=new S(o.multiplier.toString()).shiftedBy(-18),w=this.secondsInYear.div(new S(s).times(h)),f;if(u.isZero())f=d.times(y).times(w);else{let G=this.getGlobalRewardPerPeriod(u,d,P,l);f=this.getPoolYieldPerPeriod(G,y,u,l).times(w)}let O=new S(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),A=P.times(g),x=c?O.plus(c):A;return O.div(x).gte(.999)?b:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),b).toString():void 0}};var me=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},$e=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},J=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Ve=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},ze=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Je=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Ke=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{LRUCache as fs}from"@thi.ng/cache";import{memoize1 as ys}from"@thi.ng/memoize";var R=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n))(R||{}),K=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n))(K||{});var pe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,n){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,assetInED:b,assetOutED:b}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=[];return t.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:n}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=[];return r.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:n}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return I(v,e.decimalsOut)}spotPriceOutGivenIn(e){return I(v,e.decimalsIn)}calculateTradeFee(e,t){return b}};import{encodeAddress as ft}from"@polkadot/util-crypto";import{stringToU8a as St}from"@polkadot/util";import{decodeEventLog as wt}from"viem";function je(p,e){let t=[];return JSON.stringify(p,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function tn(p,e,t){let s;return JSON.stringify(p,(r,n)=>(n&&n[e]===t&&(s=n),n)),s}var sn=(p,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as bt}from"@thi.ng/memoize";import{TLRUCache as yt}from"@thi.ng/cache";var C=class extends q{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new yt(null,{maxlen:1,ttl:60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=bt(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let n=this.subscribePoolChange(t);s.push(n)}catch{}if(t.type==="Aave")return s;let r=this.subscribeTokensPoolBalance(t);if(s.push(r),this.hasSystemAsset(t)){let n=this.subscribeSystemPoolBalance(t);s.push(n)}if(this.hasErc20Asset(t)){let n=this.subscribeErc20PoolBalance(t);s.push(n)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}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 s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,n])=>{let i=e.tokens.findIndex(o=>o.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=n.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(n=>n.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var xt=["Supply","Withdraw","Repay","Borrow"],de=class extends C{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:s,liqudityIn:r,liqudityOut:n})=>({address:this.getPoolId(t.toString(),s.toString()),type:"Aave",tokens:[{id:t.toString(),balance:r.toString()},{id:s.toString(),balance:n.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let s=e+"/"+t;return ft(St(s.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);return this.api.query.system.events(n=>{n.forEach(i=>{let{event:o}=i,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:l,assetOut:c}=o.data.toHuman(),u=l.replace(/,/g,""),g=c.replace(/,/g,"");(u===s.id||g===s.id)&&(this.log(`Sync AAVE [router:Executed] :: ${u}:${g}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=o.data.toHuman();try{let{eventName:c,args:u}=wt({abi:$,topics:l.topics,data:l.data});xt.includes(c)&&u.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut:n}=await this.api.call.aaveTradeExecutor.pool(t.id,s.id);e.tokens=e.tokens.map(i=>{let o=i.id===t.id?r.toString():n.toString();return{...i,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?je(e.location,"accountKey20").accountKey20.key:U.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as Bt,calculate_out_given_in as Ot,calculate_linear_weights as At,calculate_pool_trade_fee as It,get_spot_price as Tt}from"@galacticcouncil/math-lbp";var M=class{static getSpotPrice(e,t,s,r,n){return Tt(e,t,s,r,n)}static calculateInGivenOut(e,t,s,r,n){return Bt(e,t,s,r,n)}static calculateOutGivenIn(e,t,s,r,n){return Ot(e,t,s,r,n)}static calculateLinearWeights(e,t,s,r,n){return At(e,t,s,r,n)}static calculatePoolTradeFee(e,t,s){return It(e,t,s)}};function N(p,e){return p.shiftedBy(-1*e).toString()}function L(p){return p[0]/p[1]*100}function T(p){return p[0]/p[1]}function E(p){return[p/1e3,1e3]}var ge=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,n,i,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.fee=i,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:r.decimals,decimalsOut:n.decimals,weightIn:r.weight,weightOut:n.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let i=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(i)&&n.push("MaxOutRatioExceeded"),r===e.assetOut){let o=this.calculateTradeFee(t,s),a=L(this.repayFeeApply?s.repayFee:s.exchangeFee),l=t.plus(o),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&n.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:n}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&n.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:n}}}validateAndSell(e,t,s){let r=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let i=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(i)&&n.push("MaxInRatioExceeded"),r===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:n}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,s),l=L(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:l,errors:n}}}calculateInGivenOut(e,t){let s=M.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=M.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=M.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),I(v,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=M.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),I(v,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let s=M.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(s)}};var Pe=class extends C{MAX_FINAL_WEIGHT=I(m(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([n,i])=>this.isActivePool(i.unwrap(),s)).map(async([{args:[n]},i])=>{let o=i.unwrap(),a=n.toString(),l=await this.getPoolDelta(a,o,s.toString());return this.poolsData.set(n.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...l,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let i=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,i)}else{let i=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(i,1)}})}async getPoolDelta(e,t,s){let{start:r,end:n,assets:i,initialWeight:o,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=M.calculateLinearWeights(r.toString(),n.toString(),o.toString(),a.toString(),s),[g,d]=i,P=g.toString(),h=m(u),y=d.toString(),w=this.MAX_FINAL_WEIGHT.minus(m(h)),[f,O,A]=await Promise.all([this.isRepayFeeApplied(P,l.toString(),c.toString()),this.getBalance(e,P),this.getBalance(e,y)]);return{repayFeeApply:f,tokens:[{id:P,weight:h,balance:O.toString()},{id:y,weight:w,balance:A.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=m(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as vt,calculate_lrna_in_given_out as Nt,calculate_out_given_in as Ft,calculate_out_given_lrna_in as Rt,calculate_pool_trade_fee as Et,calculate_spot_price as kt,calculate_lrna_spot_price as _t,calculate_shares as Dt,calculate_liquidity_out as Ct,calculate_liquidity_lrna_out as Lt,calculate_liquidity_hub_in as Mt,is_sell_allowed as Gt,is_buy_allowed as qt,is_add_liquidity_allowed as Ht,is_remove_liquidity_allowed as Ut,recalculate_asset_fee as Wt,recalculate_protocol_fee as Xt,verify_asset_cap as Yt}from"@galacticcouncil/math-omnipool";var B=class{static calculateSpotPrice(e,t,s,r){return kt(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return _t(e,t)}static calculateInGivenOut(e,t,s,r,n,i,o,a,l){return vt(e,t,s,r,n,i,o,a,l)}static calculateLrnaInGivenOut(e,t,s,r,n){return Nt(e,t,s,r,n)}static calculateOutGivenIn(e,t,s,r,n,i,o,a,l){return Ft(e,t,s,r,n,i,o,a,l)}static calculateOutGivenLrnaIn(e,t,s,r,n){return Rt(e,t,s,r,n)}static calculatePoolTradeFee(e,t,s){return Et(e,t,s)}static calculateShares(e,t,s,r){return Dt(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,n,i,o,a){return Ct(e,t,s,r,n,i,o,a)}static calculateLiquidityLRNAOut(e,t,s,r,n,i,o,a){return Lt(e,t,s,r,n,i,o,a)}static calculateCapDifference(e,t,s,r){let n=S(t),i=S(e),o=S(r),l=S(s).shiftedBy(-18);if(n.div(o).lt(l)){let u=l.times(o).minus(n).times(i),g=n.times(S(1).minus(l));return u.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return Mt(e,t,s,r)}static isSellAllowed(e){return Gt(e)}static isBuyAllowed(e){return qt(e)}static isAddLiquidityAllowed(e){return Ht(e)}static isRemoveLiquidityAllowed(e){return Ut(e)}static recalculateAssetFee(e,t,s,r,n,i,o,a,l,c,u){return Wt(e,t,s,r,n,i,o,a,l,c,u)}static recalculateProtocolFee(e,t,s,r,n,i,o,a,l,c,u){return Xt(e,t,s,r,n,i,o,a,l,c,u)}static verifyAssetCap(e,t,s,r){return Yt(e,t,s,r)}};var he=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,n,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.hubAssetId=i}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance),a=m(r.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:n.hubReserves,sharesIn:r.shares,sharesOut:n.shares,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,tradeableIn:r.tradeable,tradeableOut:n.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,s),i=n.minus(r),o=r===b?b:i.div(r).multipliedBy(100).decimalPlaces(2),a=[],l=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(g)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,s),o=r.minus(n).div(r).multipliedBy(100).decimalPlaces(2),a=[],l=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(g)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=B.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?T(s.assetFee).toString():b.toString(),s?T(s.protocolFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}calculateLrnaInGivenOut(e,t,s){let r=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?T(s.assetFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=B.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?T(s.assetFee).toString():b.toString(),s?T(s.protocolFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}calculateOutGivenLrnaIn(e,t,s){let r=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?T(s.assetFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=B.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=B.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=B.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=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as $t}from"@polkadot/util-crypto";import{stringToU8a as Vt}from"@polkadot/util";var be=class extends C{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,n]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),i=s.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:u,tradable:g,cap:d,protocolShares:P}=l.unwrap(),h=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:g.bits.toNumber(),balance:h.toString(),cap:m(d.toString()),protocolShares:m(P.toString())}}),o=await Promise.all(i);return o.push({id:e,tradeable:r.bits.toNumber(),balance:n.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,n="omnipool",i="Short",o=A=>A===_?[_,ce]:[ce,A],[a,l,c,u]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(n,o(s),i),this.api.query.emaOracle.oracles(n,o(r),i)]),[g,d,P]=this.getAssetFee(e,a.toNumber(),l,c),[h,y,w]=r===ce?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,u),f=g+h,O=P+w;return{assetFee:E(d),protocolFee:E(y),min:E(f),max:E(O)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,n)=>{let i=e.tokens[n];if(r.isNone)return i;let o=r.unwrap();return this.updateTokenState(i,o)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:n,cap:i,protocolShares:o}=t;return{...e,hubReserves:m(s.toString()),shares:m(r.toString()),cap:m(i.toString()),protocolShares:m(o.toString()),tradeable:n.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:n,balanceOut:i}=e,{minFee:o,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,u=E(o.toNumber()),g=E(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{assetFee:P,timestamp:h}=s.unwrap(),y=t-h.toNumber(),w=d.volume.bIn.toString(),f=d.volume.bOut.toString(),O=d.liquidity.b.toString();n===_&&(w=d.volume.aIn.toString(),f=d.volume.aOut.toString(),O=d.liquidity.a.toString());let A=E(P.toNumber()),x=B.recalculateAssetFee(w,f,O,"9",i.toString(),T(A).toString(),y.toString(),T(u).toString(),T(g).toString(),l.toString(),c.toString());return[o.toNumber(),Number(x)*1e6,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:n,balanceIn:i}=e,{minFee:o,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,u=E(o.toNumber()),g=E(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{protocolFee:P,timestamp:h}=s.unwrap(),y=t-h.toNumber(),w=d.volume.bIn.toString(),f=d.volume.bOut.toString(),O=d.liquidity.b.toString();n===_&&(w=d.volume.aIn.toString(),f=d.volume.aOut.toString(),O=d.liquidity.a.toString());let A=E(P.toNumber()),x=B.recalculateProtocolFee(w,f,O,"9",i.toString(),T(A).toString(),y.toString(),T(u).toString(),T(g).toString(),l.toString(),c.toString());return[o.toNumber(),Number(x)*1e6,a.toNumber()]}getPoolId(){return $t(Vt("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as zt,calculate_out_given_in as Jt,calculate_pool_trade_fee as Kt,get_spot_price as jt,calculate_liquidity_in as Zt,calculate_shares as Qt,calculate_spot_price as es,calculate_spot_price_with_fee as ts,calculate_liquidity_out_asset_a as ss,calculate_liquidity_out_asset_b as rs}from"@galacticcouncil/math-xyk";var W=class{static getSpotPrice(e,t,s){return jt(e,t,s)}static calculateInGivenOut(e,t,s){return zt(e,t,s)}static calculateOutGivenIn(e,t,s){return Jt(e,t,s)}static calculatePoolTradeFee(e,t,s){return Kt(e,t,s)}static calculateLiquidityIn(e,t,s){return Zt(e,t,s)}static calculateSpotPrice(e,t){return es(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return ts(e,t,s,r)}static calculateShares(e,t,s){return Qt(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return ss(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return rs(e,t,s,r)}};var ye=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,n){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance),a=m(r.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateTradeFee(r,s),i=L(s.exchangeFee),o=r.plus(n),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(r,s),i=L(s.exchangeFee),o=r.minus(n),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:i,errors:a}}calculateInGivenOut(e,t){let s=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=W.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=I(v,18-e.decimalsOut);return m(t).div(s)}spotPriceOutGivenIn(e){let t=W.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=I(v,18-e.decimalsIn);return m(t).div(s)}calculateTradeFee(e,t){let s=W.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(s)}};var fe=class extends C{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let n=s.toString(),[i,o]=r.unwrap(),[a,l]=await Promise.all([this.getBalance(n,i.toString()),this.getBalance(n,o.toString())]);return{address:n,type:"Xyk",tokens:[{id:i.toString(),balance:a.toString()},{id:o.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as ns,calculate_out_given_in as os,calculate_amplification as is,calculate_add_one_asset as as,calculate_liquidity_out_one_asset as ls,calculate_pool_trade_fee as cs,calculate_shares as us,calculate_shares_for_amount as ms,calculate_spot_price_with_fee as ps,pool_account_name as ds,recalculate_peg as gs}from"@galacticcouncil/math-stableswap";var F=class{static getPoolAddress(e){return ds(e)}static defaultPegs(e){let t=[];for(let s=0;s<e;s++)t.push(["1","1"]);return t}static calculateAmplification(e,t,s,r,n){return is(e,t,s,r,n)}static calculateInGivenOut(e,t,s,r,n,i,o){return ns(e,t,s,r,n,i,o)}static calculateAddOneAsset(e,t,s,r,n,i,o){return as(e,t,s,r,n,i,o)}static calculateSharesForAmount(e,t,s,r,n,i,o){return ms(e,t,s,r,n,i,o)}static calculateOutGivenIn(e,t,s,r,n,i,o){return os(e,t,s,r,n,i,o)}static calculateLiquidityOutOneAsset(e,t,s,r,n,i,o){return ls(e,t,s,r,n,i,o)}static calculateShares(e,t,s,r,n,i){return us(e,t,s,r,n,i)}static calculateSpotPriceWithFee(e,t,s,r,n,i,o,a){return ps(e,t,s,r,n,i,o,a)}static calculatePoolTradeFee(e,t,s){return cs(e,t,s)}static recalculatePegs(e,t,s,r,n){let i=gs(e,t,s,r,n);return JSON.parse(i)}};var Se=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,n,i,o,a,l,c,u){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.amplification=i,this.id=o,this.fee=a,this.totalIssuance=l,this.pegs=c,this.pegsFee=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance),a=m(r.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:r.decimals,decimalsOut:n.decimals,tradeableIn:this.id===e?15:r.tradeable,tradeableOut:this.id===t?15:n.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,s),i=L(s.fee),o=[],a=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!a||!l)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:i,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,s),i=L(s.fee),o=[],a=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!a||!l)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:i,errors:o}}calculateIn(e,t,s){let r=F.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?T(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateAddOneAsset(e,t,s){let r=F.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?T(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateSharesForAmount(e,t,s){let r=F.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?T(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=F.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 r=I(v,e.decimalsIn-e.decimalsOut);return m(t).div(r)}let s=I(v,18-e.decimalsIn);return m(t).div(s)}calculateOut(e,t,s){let r=F.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?T(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateWithdrawOneAsset(e,t,s){let r=F.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?T(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateShares(e,t,s){let r=F.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?T(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=F.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 r=I(v,e.decimalsOut-e.decimalsIn);return m(t).div(r)}let s=I(v,18-e.decimalsOut);return m(t).div(s)}calculateTradeFee(e,t){let s=F.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return m(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{blake2AsHex as Ps,encodeAddress as hs}from"@polkadot/util-crypto";var bs=340282366920938463463374607431768211455n,we=class extends C{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[n]},i])=>{let o=i.unwrap(),a=n.toString(),l=this.getPoolAddress(a),[c,u,g]=await Promise.all([this.getPoolDelta(a,o,s.toString()),this.getPoolTokens(l,a,o),this.getPoolPegs(a,o,s.toString())]);return this.stablePools.set(l,o),{address:l,id:a,type:"Stableswap",fee:E(o.fee.toNumber()),tokens:u,...c,...g,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toString(),r=this.stablePools.get(e.address);if(r){let[n,i]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,n,i)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:n,initialBlock:i,finalBlock:o}=t,a=F.calculateAmplification(r.toString(),n.toString(),i.toString(),o.toString(),s),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,n=r.map(async o=>{let[a,l]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:a.bits.toNumber(),balance:l.toString()}}),i=await Promise.all(n);return i.push({id:t,tradeable:15,balance:bs.toString()}),i}getPoolDefaultPegs(e){let t=e.fee,s=F.defaultPegs(e.assets.length);return{pegsFee:E(t.toNumber()),pegs:s}}async getPoolPegs(e,t,s){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let r=await this.api.query.stableswap.poolPegs(e);if(r.isNone)return this.getPoolDefaultPegs(t);let n=r.unwrap(),i=await this.getLatestPegs(t,n,s),o=this.getRecentPegs(n),a=n.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[c,u]=F.recalculatePegs(JSON.stringify(o),JSON.stringify(i),s,a.replace(/%/g,""),l.replace(/%/g,"")),g=Number(c)*1e4;return{pegsFee:E(g),pegs:u}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([s,r])=>r.map(n=>n.toString()))}async getLatestPegs(e,t,s){let{source:r}=t,n=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),i=r.map(async(o,a)=>{if(o.isOracle){let[l,c,u]=o.asOracle,g=[u.toString(),n[a]].map(f=>Number(f)).sort((f,O)=>f-O),d=await this.api.query.emaOracle.oracles(l,g,c),[{price:P,updatedAt:h}]=d.unwrap(),y=P.n.toString(),w=P.d.toString();return u.toString()===g[0].toString()?[[y,w],h.toString()]:[[w,y],h.toString()]}else return[o.asValue.map(l=>l.toString()),s]});return Promise.all(i)}getPoolAddress(e){let t=Number(e),s=F.getPoolAddress(t);return hs(Ps(s),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var te=class extends D{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=ys(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new ee(this.api),this.aaveClient=new de(this.api),this.xykClient=new fe(this.api),this.omniClient=new be(this.api),this.lbpClient=new Pe(this.api),this.stableClient=new we(this.api),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new me(t.type)}}};var Fe=class extends te{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new fs(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let n=await super.getPoolFees(e,t);return this.feeCache.set(s,n),n}}async destroy(){this.log(`Destroying pool cache!
1
+ var $=[{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 Oe=[{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 le="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ae="0x112b087b60C1a166130d59266363C45F8aa99db0",Ie="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",De=1000000n;var Ce=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");import{defineChain as st}from"viem";var Le=["https://rpc.hydradx.cloud","https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],Me=["wss://rpc.hydradx.cloud","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"],Ge=st({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:Le,webSocket:Me},default:{http:Le,webSocket:Me}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as qe,createWalletClient as rt,custom as nt,http as ot,webSocket as it}from"viem";var V=class{chain;constructor(e){this.chain=e||Ge}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return qe({chain:this.chain,transport:ot()})}getWsProvider(){return qe({chain:this.chain,transport:it()})}getSigner(e){return rt({account:e,chain:this.chain,transport:nt(window.ethereum)})}};var j=class{evmClient;constructor(){this.evmClient=new V}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Oe,address:Ae,args:[Ie],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:Oe,address:Ae,args:[Ie,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:$,address:le,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as ue,encodeAddress as Ue}from"@polkadot/util-crypto";import{hexToU8a as at,isHex as lt,u8aToHex as ct}from"@polkadot/util";import{Buffer as X}from"buffer";var Ys=2090,Te=1e3,ce="1",$s=2034,H=63,Z=18,_="0",Vs=12,Q=15;var He=X.from("ETH\0");function ut(p){if(!p)return!1;try{let e=ue(p,!0);return X.from(e.subarray(0,He.length)).equals(He)}catch{return!1}}function mt(p){return!!/^0x[a-fA-F0-9]{40}$/.test(p)}function pt(p){try{let e=lt(p)?at(p):ue(p);return Ue(e),!0}catch{return!1}}var z=class p{static prefixBytes=X.from("ETH\0");static toAccount=e=>{let t=X.from(e.slice(2),"hex");return Ue(new Uint8Array(X.concat([p.prefixBytes,t,X.alloc(8)])),63)};static fromAccount=e=>{let s=ue(e).slice(p.prefixBytes.length,-8);return"0x"+X.from(s).toString("hex")};static fromSS58=e=>{let s=ue(e).slice(0,20);return ct(s)};static fromAny=e=>{if(mt(e))return e;if(ut(e))return p.fromAccount(e);if(pt(e))return p.fromSS58(e);throw new Error("Unknown address type")}};var U=class{static fromAssetId(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),s=Buffer.from(e.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as S}from"bignumber.js";var dt=12;S.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:dt});var b=m(0),v=m(1),sr=m("Infinity");function I(p,e){let t=new S(e.toString()),s=new S(10).pow(t);return p.times(s)}function m(p){return new S(p.toString())}var gt=m("1e27"),lr=m("1e8"),cr=m("31536000"),ur=m("999999999"),Pt=m("1.01"),ve=class{client;constructor(){this.client=new j}async loadCtx(e,t){let s=z.fromAny(e),r=U.fromAssetId(t),[n,i,o]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(s),this.client.getUserAccountData(s)]),[a,l]=o,[c]=n,[u,g]=i,d=c.find(({underlyingAsset:Y})=>Y.toLowerCase()===r.toLowerCase()),P=u.find(({underlyingAsset:Y})=>Y.toLowerCase()===r.toLowerCase());if(!d||!P)throw new Error("Missing reserve or userReserve for "+t);let h=Number(d.decimals),y=m(d.priceInMarketReferenceCurrency),w=m(g===d.eModeCategoryId?d.eModeLiquidationThreshold:d.reserveLiquidationThreshold).div(1e4),f=m(d.liquidityIndex),O=m(P.scaledATokenBalance),A=m(a),x=m(l),k=d.usageAsCollateralEnabled&&P.usageAsCollateralEnabledOnUser&&m(P.scaledATokenBalance).gt(0),G=O.multipliedBy(f).dividedBy(gt).decimalPlaces(0,S.ROUND_DOWN);return{decimals:h,isCollateralAsset:k,priceInRef:y,reserveLiquidationThreshold:w,totalCollateralBase:A,totalDebtBase:x,userBalance:G}}async getMaxWithdraw(e,t){let{decimals:s,priceInRef:r,reserveLiquidationThreshold:n,totalCollateralBase:i,totalDebtBase:o,userBalance:a}=await this.loadCtx(e,t),l=m(i),c=m(o),u=Pt.multipliedBy(c).div(n).decimalPlaces(0,S.ROUND_UP),d=l.minus(u).decimalPlaces(0,1).multipliedBy(m(10).pow(s)).dividedBy(r).decimalPlaces(0,S.ROUND_DOWN);return{amount:S.minimum(a,d),decimals:s}}async getHealthFactorAfterWithdraw(e,t,s){let{decimals:r,isCollateralAsset:n,priceInRef:i,reserveLiquidationThreshold:o,totalCollateralBase:a,totalDebtBase:l}=await this.loadCtx(e,t),c=n?m(s).multipliedBy(i).dividedBy(m(10).pow(r)).decimalPlaces(0,S.ROUND_DOWN):b,u=a.minus(c);return u.lte(0)?0:u.multipliedBy(o).dividedBy(l).decimalPlaces(6,S.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,s){let{decimals:r,priceInRef:n,reserveLiquidationThreshold:i,totalCollateralBase:o,totalDebtBase:a}=await this.loadCtx(e,t),l=m(s).multipliedBy(n).dividedBy(m(10).pow(r)).decimalPlaces(0,S.ROUND_DOWN),c=o.plus(l);return c.lte(0)?0:c.multipliedBy(i).dividedBy(a).decimalPlaces(6,S.ROUND_DOWN).toNumber()}};import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var D=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}async dryRun(e,t){let s;try{s=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(r){throw console.error(r),new Error("Dry run execution failed!")}if(s.isOk)return s.asOk;throw console.log(s.asErr.toHuman()),new Error("Dry run execution error!")}log(e,...t){let s=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");this.getLogValue(s)&&console.log(e,...t)}getLogValue(e){switch(e){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}};var ee=class extends D{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]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:n}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:n.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==_){let u=this.api.consts.balances.existentialDeposit;return{id:_,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:u.toString()}}let{name:n,assetType:i,isSufficient:o,existentialDeposit:a}=t,{symbol:l,decimals:c}=s.get(e)??{};return{id:e,name:n.toHuman(),symbol:l,decimals:c,icon:l,type:i.toHuman(),isSufficient:o?o.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[n,i]=r,{assetType:o,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(n.toString(),t,s),g=i.toNumber(),d=new Intl.DateTimeFormat("en-GB"),P=[c,"Bond",d.format(g)].join(" ");return{id:e,name:P,symbol:c+"b",decimals:u,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:n.toString(),maturity:g}}getShares(e,t,s,r){let{assets:n}=r,{name:i,symbol:o,assetType:a,isSufficient:l,existentialDeposit:c}=t,g=n.map(h=>h.toString()).map(h=>{let{symbol:y}=this.getToken(h,t,s);return[h,y]}),d=Object.fromEntries(g),P=Object.values(d);return{id:e,name:P.join(", "),symbol:o?.isSome?o.toHuman():i.toHuman(),decimals:18,icon:P.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,s,r){let n=this.getToken(e,t,new Map,r),i=s?.find(o=>o.internalId===n.id);return i?{...n,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:n}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:n,symbol:i}=r.unwrap();return[s.toString(),{decimals:Number(n.toString()),symbol:i.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,n,i,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(s),l=this.normalizeMetadata(a,o),c=a.map(([{args:[u]},g])=>{let d=g.unwrap(),P=r.get(u.toString()),{assetType:h}=d;switch(h.toString()){case"Bond":let y=i.get(u.toString());return this.getBond(u.toString(),d,l,y);case"StableSwap":let w=n.get(u.toString());return this.getShares(u.toString(),d,l,w);case"External":return this.getExternal(u.toString(),d,t,P);default:return this.getToken(u.toString(),d,l,P)}});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 q=class extends D{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===_?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:n}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:n})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:n}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:0n,frozen:n})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(_,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let n=t.filter(i=>i.type!=="Erc20").filter(i=>i.id!==_).map(i=>[e,i.id]);return this.api.query.tokens.accounts.multi(n,i=>{let o=[];i.forEach((a,l)=>{let c=this.calculateFreeBalance(a),u=n[l][1];o.push([u,c])}),s(o)})}async subscribeErc20Balance(e,t,s){let r=t.filter(i=>i.type==="Erc20"),n=async()=>{let i=[];(await Promise.all(r.map(async a=>[a.id,await this.getErc20Balance(e,a.id)]))).forEach(([a,l])=>{i.push([a,l])}),s(i)};return await n(),this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:n}=e,i=new S(t),o=new S(s||n),a=new S(r||0n),l=o.gt(a)?o:a;return i.minus(l)}};import{fixed_from_rational as We}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as ht}from"@polkadot/types";import{u8aConcat as Xe}from"@polkadot/util";import{isAddress as Ye}from"@polkadot/util-crypto";var Ne=class extends D{balanceClient;constructor(e){super(e),this.balanceClient=new q(e)}secondsInYear=new S(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([r,n])=>{let[,i]=r.args,o=n.unwrap().toString(),a=i.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),P=l.rewardCurrency.toString(),h=await this.balanceClient.getTokenBalanceData(d,P);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:h.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,n])=>{let[,i]=r.args,o=n.unwrap().toString(),a=i.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),P=l.rewardCurrency.toString(),h=await this.balanceClient.getTokenBalanceData(d,P);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:h.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new S(1).shiftedBy(18).toString();let n=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(n.isNone)return;let[i]=n.unwrap(),o=i.price.n.toString(),a=i.price.d.toString(),l;return Number(t)<Number(s)?l=We(o,a):l=We(a,o),l}getGlobalRewardPerPeriod(e,t,s,r){let i=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return i.gte(s)?s:i}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}padEndU8a(e,t){return Xe(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",n=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new ht(e,this.padEndU8a(Xe(r,n,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!Ye(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&Ye(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:o,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let u=new S(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),d=new S(a.yieldPerPeriod.toString()),P=new S(a.maxRewardPerPeriod.toString()),h=a.blocksPerPeriod.toString(),y=new S(o.multiplier.toString()).shiftedBy(-18),w=this.secondsInYear.div(new S(s).times(h)),f;if(u.isZero())f=d.times(y).times(w);else{let G=this.getGlobalRewardPerPeriod(u,d,P,l);f=this.getPoolYieldPerPeriod(G,y,u,l).times(w)}let O=new S(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),A=P.times(g),x=c?O.plus(c):A;return O.div(x).gte(.999)?b:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),b).toString():void 0}};var me=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},$e=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},J=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Ve=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},ze=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Je=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Ke=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{LRUCache as fs}from"@thi.ng/cache";import{memoize1 as ys}from"@thi.ng/memoize";var R=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n))(R||{}),K=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n))(K||{});var pe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,n){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,assetInED:b,assetOutED:b}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=[];return t.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:n}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=[];return r.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:n}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return I(v,e.decimalsOut)}spotPriceOutGivenIn(e){return I(v,e.decimalsIn)}calculateTradeFee(e,t){return b}};import{encodeAddress as ft}from"@polkadot/util-crypto";import{stringToU8a as St}from"@polkadot/util";import{decodeEventLog as wt}from"viem";function je(p,e){let t=[];return JSON.stringify(p,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function tn(p,e,t){let s;return JSON.stringify(p,(r,n)=>(n&&n[e]===t&&(s=n),n)),s}var sn=(p,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as bt}from"@thi.ng/memoize";import{TLRUCache as yt}from"@thi.ng/cache";var C=class extends q{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new yt(null,{maxlen:1,ttl:60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=bt(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let n=this.subscribePoolChange(t);s.push(n)}catch{}if(t.type==="Aave")return s;let r=this.subscribeTokensPoolBalance(t);if(s.push(r),this.hasSystemAsset(t)){let n=this.subscribeSystemPoolBalance(t);s.push(n)}if(this.hasErc20Asset(t)){let n=this.subscribeErc20PoolBalance(t);s.push(n)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}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 s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,n])=>{let i=e.tokens.findIndex(o=>o.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=n.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(n=>n.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var xt=["Supply","Withdraw","Repay","Borrow"],de=class extends C{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:s,liqudityIn:r,liqudityOut:n})=>({address:this.getPoolId(t.toString(),s.toString()),type:"Aave",tokens:[{id:t.toString(),balance:r.toString()},{id:s.toString(),balance:n.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let s=e+"/"+t;return ft(St(s.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);return this.api.query.system.events(n=>{n.forEach(i=>{let{event:o}=i,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:l,assetOut:c}=o.data.toHuman(),u=l.replace(/,/g,""),g=c.replace(/,/g,"");(u===s.id||g===s.id)&&(this.log(`Sync AAVE [router:Executed] :: ${u}:${g}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=o.data.toHuman();try{let{eventName:c,args:u}=wt({abi:$,topics:l.topics,data:l.data});xt.includes(c)&&u.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut:n}=await this.api.call.aaveTradeExecutor.pool(t.id,s.id);e.tokens=e.tokens.map(i=>{let o=i.id===t.id?r.toString():n.toString();return{...i,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?je(e.location,"accountKey20").accountKey20.key:U.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as Bt,calculate_out_given_in as Ot,calculate_linear_weights as At,calculate_pool_trade_fee as It,get_spot_price as Tt}from"@galacticcouncil/math-lbp";var M=class{static getSpotPrice(e,t,s,r,n){return Tt(e,t,s,r,n)}static calculateInGivenOut(e,t,s,r,n){return Bt(e,t,s,r,n)}static calculateOutGivenIn(e,t,s,r,n){return Ot(e,t,s,r,n)}static calculateLinearWeights(e,t,s,r,n){return At(e,t,s,r,n)}static calculatePoolTradeFee(e,t,s){return It(e,t,s)}};function N(p,e){return p.shiftedBy(-1*e).toString()}function L(p){return p[0]/p[1]*100}function T(p){return p[0]/p[1]}function E(p){return[p/1e3,1e3]}var ge=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,n,i,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.fee=i,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:r.decimals,decimalsOut:n.decimals,weightIn:r.weight,weightOut:n.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let i=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(i)&&n.push("MaxOutRatioExceeded"),r===e.assetOut){let o=this.calculateTradeFee(t,s),a=L(this.repayFeeApply?s.repayFee:s.exchangeFee),l=t.plus(o),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&n.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:n}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&n.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:n}}}validateAndSell(e,t,s){let r=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let i=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(i)&&n.push("MaxInRatioExceeded"),r===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:n}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,s),l=L(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:l,errors:n}}}calculateInGivenOut(e,t){let s=M.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=M.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=M.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),I(v,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=M.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),I(v,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let s=M.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(s)}};var Pe=class extends C{MAX_FINAL_WEIGHT=I(m(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([n,i])=>this.isActivePool(i.unwrap(),s)).map(async([{args:[n]},i])=>{let o=i.unwrap(),a=n.toString(),l=await this.getPoolDelta(a,o,s.toString());return this.poolsData.set(n.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...l,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let i=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,i)}else{let i=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(i,1)}})}async getPoolDelta(e,t,s){let{start:r,end:n,assets:i,initialWeight:o,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=M.calculateLinearWeights(r.toString(),n.toString(),o.toString(),a.toString(),s),[g,d]=i,P=g.toString(),h=m(u),y=d.toString(),w=this.MAX_FINAL_WEIGHT.minus(m(h)),[f,O,A]=await Promise.all([this.isRepayFeeApplied(P,l.toString(),c.toString()),this.getBalance(e,P),this.getBalance(e,y)]);return{repayFeeApply:f,tokens:[{id:P,weight:h,balance:O.toString()},{id:y,weight:w,balance:A.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=m(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as vt,calculate_lrna_in_given_out as Nt,calculate_out_given_in as Ft,calculate_out_given_lrna_in as Rt,calculate_pool_trade_fee as Et,calculate_spot_price as kt,calculate_lrna_spot_price as _t,calculate_shares as Dt,calculate_liquidity_out as Ct,calculate_liquidity_lrna_out as Lt,calculate_liquidity_hub_in as Mt,is_sell_allowed as Gt,is_buy_allowed as qt,is_add_liquidity_allowed as Ht,is_remove_liquidity_allowed as Ut,recalculate_asset_fee as Wt,recalculate_protocol_fee as Xt,verify_asset_cap as Yt}from"@galacticcouncil/math-omnipool";var B=class{static calculateSpotPrice(e,t,s,r){return kt(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return _t(e,t)}static calculateInGivenOut(e,t,s,r,n,i,o,a,l){return vt(e,t,s,r,n,i,o,a,l)}static calculateLrnaInGivenOut(e,t,s,r,n){return Nt(e,t,s,r,n)}static calculateOutGivenIn(e,t,s,r,n,i,o,a,l){return Ft(e,t,s,r,n,i,o,a,l)}static calculateOutGivenLrnaIn(e,t,s,r,n){return Rt(e,t,s,r,n)}static calculatePoolTradeFee(e,t,s){return Et(e,t,s)}static calculateShares(e,t,s,r){return Dt(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,n,i,o,a){return Ct(e,t,s,r,n,i,o,a)}static calculateLiquidityLRNAOut(e,t,s,r,n,i,o,a){return Lt(e,t,s,r,n,i,o,a)}static calculateCapDifference(e,t,s,r){let n=S(t),i=S(e),o=S(r),l=S(s).shiftedBy(-18);if(n.div(o).lt(l)){let u=l.times(o).minus(n).times(i),g=n.times(S(1).minus(l));return u.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return Mt(e,t,s,r)}static isSellAllowed(e){return Gt(e)}static isBuyAllowed(e){return qt(e)}static isAddLiquidityAllowed(e){return Ht(e)}static isRemoveLiquidityAllowed(e){return Ut(e)}static recalculateAssetFee(e,t,s,r,n,i,o,a,l,c,u){return Wt(e,t,s,r,n,i,o,a,l,c,u)}static recalculateProtocolFee(e,t,s,r,n,i,o,a,l,c,u){return Xt(e,t,s,r,n,i,o,a,l,c,u)}static verifyAssetCap(e,t,s,r){return Yt(e,t,s,r)}};var he=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,n,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.hubAssetId=i}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance),a=m(r.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:n.hubReserves,sharesIn:r.shares,sharesOut:n.shares,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,tradeableIn:r.tradeable,tradeableOut:n.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,s),i=n.minus(r),o=r===b?b:i.div(r).multipliedBy(100).decimalPlaces(2),a=[],l=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(g)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,s),o=r.minus(n).div(r).multipliedBy(100).decimalPlaces(2),a=[],l=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(g)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=B.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?T(s.assetFee).toString():b.toString(),s?T(s.protocolFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}calculateLrnaInGivenOut(e,t,s){let r=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?T(s.assetFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=B.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?T(s.assetFee).toString():b.toString(),s?T(s.protocolFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}calculateOutGivenLrnaIn(e,t,s){let r=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?T(s.assetFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=B.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=B.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=B.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=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as $t}from"@polkadot/util-crypto";import{stringToU8a as Vt}from"@polkadot/util";var be=class extends C{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,n]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),i=s.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:u,tradable:g,cap:d,protocolShares:P}=l.unwrap(),h=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:g.bits.toNumber(),balance:h.toString(),cap:m(d.toString()),protocolShares:m(P.toString())}}),o=await Promise.all(i);return o.push({id:e,tradeable:r.bits.toNumber(),balance:n.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,n="omnipool",i="Short",o=A=>A===_?[_,ce]:[ce,A],[a,l,c,u]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(n,o(s),i),this.api.query.emaOracle.oracles(n,o(r),i)]),[g,d,P]=this.getAssetFee(e,a.toNumber(),l,c),[h,y,w]=r===ce?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,u),f=g+h,O=P+w;return{assetFee:E(d),protocolFee:E(y),min:E(f),max:E(O)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,n)=>{let i=e.tokens[n];if(r.isNone)return i;let o=r.unwrap();return this.updateTokenState(i,o)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:n,cap:i,protocolShares:o}=t;return{...e,hubReserves:m(s.toString()),shares:m(r.toString()),cap:m(i.toString()),protocolShares:m(o.toString()),tradeable:n.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:n,balanceOut:i}=e,{minFee:o,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,u=E(o.toNumber()),g=E(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{assetFee:P,timestamp:h}=s.unwrap(),y=Math.max(1,t-h.toNumber()),w=d.volume.bIn.toString(),f=d.volume.bOut.toString(),O=d.liquidity.b.toString();n===_&&(w=d.volume.aIn.toString(),f=d.volume.aOut.toString(),O=d.liquidity.a.toString());let A=E(P.toNumber()),x=B.recalculateAssetFee(w,f,O,"9",i.toString(),T(A).toString(),y.toString(),T(u).toString(),T(g).toString(),l.toString(),c.toString());return[o.toNumber(),Number(x)*1e6,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:n,balanceIn:i}=e,{minFee:o,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,u=E(o.toNumber()),g=E(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{protocolFee:P,timestamp:h}=s.unwrap(),y=Math.max(1,t-h.toNumber()),w=d.volume.bIn.toString(),f=d.volume.bOut.toString(),O=d.liquidity.b.toString();n===_&&(w=d.volume.aIn.toString(),f=d.volume.aOut.toString(),O=d.liquidity.a.toString());let A=E(P.toNumber()),x=B.recalculateProtocolFee(w,f,O,"9",i.toString(),T(A).toString(),y.toString(),T(u).toString(),T(g).toString(),l.toString(),c.toString());return[o.toNumber(),Number(x)*1e6,a.toNumber()]}getPoolId(){return $t(Vt("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as zt,calculate_out_given_in as Jt,calculate_pool_trade_fee as Kt,get_spot_price as jt,calculate_liquidity_in as Zt,calculate_shares as Qt,calculate_spot_price as es,calculate_spot_price_with_fee as ts,calculate_liquidity_out_asset_a as ss,calculate_liquidity_out_asset_b as rs}from"@galacticcouncil/math-xyk";var W=class{static getSpotPrice(e,t,s){return jt(e,t,s)}static calculateInGivenOut(e,t,s){return zt(e,t,s)}static calculateOutGivenIn(e,t,s){return Jt(e,t,s)}static calculatePoolTradeFee(e,t,s){return Kt(e,t,s)}static calculateLiquidityIn(e,t,s){return Zt(e,t,s)}static calculateSpotPrice(e,t){return es(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return ts(e,t,s,r)}static calculateShares(e,t,s){return Qt(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return ss(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return rs(e,t,s,r)}};var ye=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,n){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance),a=m(r.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateTradeFee(r,s),i=L(s.exchangeFee),o=r.plus(n),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(r,s),i=L(s.exchangeFee),o=r.minus(n),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:i,errors:a}}calculateInGivenOut(e,t){let s=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=W.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=I(v,18-e.decimalsOut);return m(t).div(s)}spotPriceOutGivenIn(e){let t=W.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=I(v,18-e.decimalsIn);return m(t).div(s)}calculateTradeFee(e,t){let s=W.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(s)}};var fe=class extends C{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let n=s.toString(),[i,o]=r.unwrap(),[a,l]=await Promise.all([this.getBalance(n,i.toString()),this.getBalance(n,o.toString())]);return{address:n,type:"Xyk",tokens:[{id:i.toString(),balance:a.toString()},{id:o.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as ns,calculate_out_given_in as os,calculate_amplification as is,calculate_add_one_asset as as,calculate_liquidity_out_one_asset as ls,calculate_pool_trade_fee as cs,calculate_shares as us,calculate_shares_for_amount as ms,calculate_spot_price_with_fee as ps,pool_account_name as ds,recalculate_peg as gs}from"@galacticcouncil/math-stableswap";var F=class{static getPoolAddress(e){return ds(e)}static defaultPegs(e){let t=[];for(let s=0;s<e;s++)t.push(["1","1"]);return t}static calculateAmplification(e,t,s,r,n){return is(e,t,s,r,n)}static calculateInGivenOut(e,t,s,r,n,i,o){return ns(e,t,s,r,n,i,o)}static calculateAddOneAsset(e,t,s,r,n,i,o){return as(e,t,s,r,n,i,o)}static calculateSharesForAmount(e,t,s,r,n,i,o){return ms(e,t,s,r,n,i,o)}static calculateOutGivenIn(e,t,s,r,n,i,o){return os(e,t,s,r,n,i,o)}static calculateLiquidityOutOneAsset(e,t,s,r,n,i,o){return ls(e,t,s,r,n,i,o)}static calculateShares(e,t,s,r,n,i){return us(e,t,s,r,n,i)}static calculateSpotPriceWithFee(e,t,s,r,n,i,o,a){return ps(e,t,s,r,n,i,o,a)}static calculatePoolTradeFee(e,t,s){return cs(e,t,s)}static recalculatePegs(e,t,s,r,n){let i=gs(e,t,s,r,n);return JSON.parse(i)}};var Se=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,n,i,o,a,l,c,u){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.amplification=i,this.id=o,this.fee=a,this.totalIssuance=l,this.pegs=c,this.pegsFee=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance),a=m(r.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:r.decimals,decimalsOut:n.decimals,tradeableIn:this.id===e?15:r.tradeable,tradeableOut:this.id===t?15:n.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,s),i=L(s.fee),o=[],a=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!a||!l)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:i,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,s),i=L(s.fee),o=[],a=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!a||!l)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:i,errors:o}}calculateIn(e,t,s){let r=F.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?T(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateAddOneAsset(e,t,s){let r=F.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?T(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateSharesForAmount(e,t,s){let r=F.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?T(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=F.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 r=I(v,e.decimalsIn-e.decimalsOut);return m(t).div(r)}let s=I(v,18-e.decimalsIn);return m(t).div(s)}calculateOut(e,t,s){let r=F.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?T(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateWithdrawOneAsset(e,t,s){let r=F.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?T(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateShares(e,t,s){let r=F.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?T(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=F.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 r=I(v,e.decimalsOut-e.decimalsIn);return m(t).div(r)}let s=I(v,18-e.decimalsOut);return m(t).div(s)}calculateTradeFee(e,t){let s=F.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return m(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{blake2AsHex as Ps,encodeAddress as hs}from"@polkadot/util-crypto";var bs=340282366920938463463374607431768211455n,we=class extends C{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[n]},i])=>{let o=i.unwrap(),a=n.toString(),l=this.getPoolAddress(a),[c,u,g]=await Promise.all([this.getPoolDelta(a,o,s.toString()),this.getPoolTokens(l,a,o),this.getPoolPegs(a,o,s.toString())]);return this.stablePools.set(l,o),{address:l,id:a,type:"Stableswap",fee:E(o.fee.toNumber()),tokens:u,...c,...g,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toString(),r=this.stablePools.get(e.address);if(r){let[n,i]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,n,i)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:n,initialBlock:i,finalBlock:o}=t,a=F.calculateAmplification(r.toString(),n.toString(),i.toString(),o.toString(),s),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,n=r.map(async o=>{let[a,l]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:a.bits.toNumber(),balance:l.toString()}}),i=await Promise.all(n);return i.push({id:t,tradeable:15,balance:bs.toString()}),i}getPoolDefaultPegs(e){let t=e.fee,s=F.defaultPegs(e.assets.length);return{pegsFee:E(t.toNumber()),pegs:s}}async getPoolPegs(e,t,s){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let r=await this.api.query.stableswap.poolPegs(e);if(r.isNone)return this.getPoolDefaultPegs(t);let n=r.unwrap(),i=await this.getLatestPegs(t,n,s),o=this.getRecentPegs(n),a=n.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[c,u]=F.recalculatePegs(JSON.stringify(o),JSON.stringify(i),s,a.replace(/%/g,""),l.replace(/%/g,"")),g=Number(c)*1e4;return{pegsFee:E(g),pegs:u}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([s,r])=>r.map(n=>n.toString()))}async getLatestPegs(e,t,s){let{source:r}=t,n=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),i=r.map(async(o,a)=>{if(o.isOracle){let[l,c,u]=o.asOracle,g=[u.toString(),n[a]].map(f=>Number(f)).sort((f,O)=>f-O),d=await this.api.query.emaOracle.oracles(l,g,c),[{price:P,updatedAt:h}]=d.unwrap(),y=P.n.toString(),w=P.d.toString();return u.toString()===g[0].toString()?[[y,w],h.toString()]:[[w,y],h.toString()]}else return[o.asValue.map(l=>l.toString()),s]});return Promise.all(i)}getPoolAddress(e){let t=Number(e),s=F.getPoolAddress(t);return hs(Ps(s),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var te=class extends D{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=ys(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new ee(this.api),this.aaveClient=new de(this.api),this.xykClient=new fe(this.api),this.omniClient=new be(this.api),this.lbpClient=new Pe(this.api),this.stableClient=new we(this.api),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new me(t.type)}}};var Fe=class extends te{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new fs(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let n=await super.getPoolFees(e,t);return this.feeCache.set(s,n),n}}async destroy(){this.log(`Destroying pool cache!
2
2
  Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var se=class{static get(e){switch(e.type){case"Aave":return pe.fromPool(e);case"Xyk":return ye.fromPool(e);case"Omnipool":return he.fromPool(e);case"Lbp":return ge.fromPool(e);case"Stableswap":return Se.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var xe=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Ss=5,re=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],n=new xe,i=[];for(i.push([t,""]),n.enqueue(i);n.size()>0;){let o=n.dequeue();if(o==null||o.length>Ss)return r;let a=o[o.length-1];(s===null||a[0]===s)&&r.push(o),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let u=[...o];u.push(c),n.enqueue(u)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,n,i]of t){let o=parseInt(n),a=parseInt(i);s.get(o)?.push([a,r])}return s}};function Re(p){let e={};for(let t of p){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let n=0;n<s;n++){if(r==n)continue;let i=[t.address,t.tokens[r].id,t.tokens[n].id];e[t.tokens[r].id].push(i)}}}return e}var ne=class{getProposals(e,t,s){let r=Re(s),n=Object.keys(r),i=n.map(c=>r[c]).flat(),o=new re,a=o.buildAndPopulateGraph(n,i),l=o.findPaths(a,parseInt(e),t?parseInt(t):null);return this.parsePaths(l)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let n=0;n<s.length;n++){let i=s[n],o=s[n+1];if(o==null)break;r.push(this.toEdge(i,o))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var oe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new ne,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),i=this.getPaths(e,null,r,t).map(o=>o[o.length-1].assetOut);return this.toAssets([...new Set(i)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,meta:r.meta,location:r.location,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let n=this.getPoolMap(s);return{assets:r,poolsMap:n}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,se.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,n])=>{let i=t.get(s);return{poolAddress:s,poolId:i?.id,pool:i?.type,assetIn:r,assetOut:n}})}toAssets(e,t){return e.map(s=>t.get(s))}};var ws=m("100");function hl(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ie(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ze(p,e){return v.minus(e.div(p)).multipliedBy(100).decimalPlaces(2)}function Qe(p,e){return e.div(p).minus(v).multipliedBy(100).decimalPlaces(2)}function ae(p,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),p.div(ws).multipliedBy(e).decimalPlaces(0,1)}var Ee=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Ee||{});var ke=class extends oe{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let n=s[s.length-1].amountOut,i=r[r.length-1].amountOut;return n.isGreaterThan(i)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,i)=>n+i),r=e.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,i)=>n+i);return[s,r]}}getPoolFeeRange(e){let t=e.min?L(e.min):void 0,s=e.max?L(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,n),o=super.getPaths(e,t,i,n);if(o.length===0)throw new J(e,t);let a;if(r)a=await this.toSellSwaps(s,r,i);else{let x=o.map(async G=>await this.toSellSwaps(s,G,i)),k=await Promise.all(x);a=this.findBestSellRoute(k)}let l=a[0],c=a[a.length-1],u=this.isDirectTrade(a),g=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,k)=>x.multipliedBy(k)),d=I(g,c.assetOutDecimals),P=u?c.calculatedOut:this.calculateDelta0Y(l.amountIn,a,i),h=c.amountOut,y=u?c.tradeFeePct:Ze(P,h).toNumber(),w=P.minus(h),f=this.getRouteFeeRange(a),O=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(d),A=ie(P,O);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:w,tradeFeePct:y,tradeFeeRange:f,priceImpactPct:A.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:N(l.amountIn,l.assetInDecimals),amountOut:N(c.amountOut,c.assetOutDecimals),spotPrice:N(d,c.assetOutDecimals),tradeFee:N(w,c.assetOutDecimals),tradeFeePct:y,tradeFeeRange:f,priceImpactPct:A.toNumber(),swaps:a.map(x=>x.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let n=0;n<t.length;n++){let i=t[n],o=s.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(i.assetIn,i.assetOut),l;n>0?l=r[n-1]:l=e;let c=o.calculateOutGivenIn(a,l);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let n=0;n<t.length;n++){let i=t[n],o=s.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(i.assetIn,i.assetOut),l;n>0?l=r[n-1].amountOut:l=I(m(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:u,calculatedOut:g,feePct:d,errors:P}=o.validateAndSell(a,l,c),h=this.getPoolFeeRange(c),y=o.spotPriceOutGivenIn(a),w=l.shiftedBy(-1*a.decimalsIn).multipliedBy(y),f=ie(g,w);r.push({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,calculatedOut:g,amountOut:u,spotPrice:y,tradeFeePct:d,tradeFeeRange:h,priceImpactPct:f.toNumber(),errors:P,isSupply(){return o.type==="Aave"&&o.tokens[0].id===i.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:N(l,a.decimalsIn),calculatedOut:N(g,a.decimalsOut),amountOut:N(u,a.decimalsOut),spotPrice:N(y,a.decimalsOut),tradeFeePct:d,tradeFeeRange:h,priceImpactPct:f.toNumber(),errors:P}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),n=super.getPaths(e,t,r,s);if(n.length===0)throw new J(e,t);let l=s.filter(d=>d.tokens.some(P=>P.id===e&&P.id!==d.id)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(P=>P.id===e)).map(d=>d.map(P=>m(P.balance).shiftedBy(-1*P.decimals)).reduce((P,h)=>P.plus(h))).sort((d,P)=>P.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=n.map(async d=>await this.toSellSwaps(l,d,r)),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 s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s);if(super.getPaths(e,t,r,s).length===0)return Promise.resolve(void 0);let i=await this.getMostLiquidRoute(e,t),o=await this.toSellSwaps("1",i,r),a=o.map(u=>u.spotPrice.shiftedBy(-1*u.assetOutDecimals)).reduce((u,g)=>u.multipliedBy(g)),l=o[o.length-1].assetOutDecimals;return{amount:I(a,l),decimals:l}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let n=s[0].amountIn,i=r[0].amountIn;return n.isGreaterThan(i)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,n),o=super.getPaths(e,t,i,n);if(o.length===0)throw new J(e,t);let a;if(r)a=await this.toBuySwaps(s,r,i);else{let x=o.map(async G=>await this.toBuySwaps(s,G,i)),k=await Promise.all(x);a=this.findBestBuyRoute(k)}let l=a[a.length-1],c=a[0],u=this.isDirectTrade(a),g=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetInDecimals)).reduce((x,k)=>x.multipliedBy(k)),d=I(g,c.assetInDecimals),P=u?c.calculatedIn:this.calculateDelta0X(l.amountOut,a,i),h=c.amountIn,y=u?c.tradeFeePct:Qe(P,h).toNumber(),w=h.minus(P),f=this.getRouteFeeRange(a),O=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(d),A;return P.isZero()?A=-100:A=ie(O,P).toNumber(),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:w,tradeFeePct:y,tradeFeeRange:f,priceImpactPct:A,swaps:a,toHuman(){return{type:"Buy",amountOut:N(l.amountOut,l.assetOutDecimals),amountIn:N(c.amountIn,c.assetInDecimals),spotPrice:N(d,c.assetInDecimals),tradeFee:N(w,c.assetInDecimals),tradeFeePct:y,tradeFeeRange:f,priceImpactPct:A,swaps:a.map(x=>x.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let n=t.length-1;n>=0;n--){let i=t[n],o=s.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(i.assetIn,i.assetOut),l;n==t.length-1?l=e:l=r[0];let c=o.calculateInGivenOut(a,l);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let n=t.length-1;n>=0;n--){let i=t[n],o=s.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(i.assetIn,i.assetOut),l;n==t.length-1?l=I(m(e),a.decimalsOut).decimalPlaces(0,1):l=r[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:u,calculatedIn:g,feePct:d,errors:P}=o.validateAndBuy(a,l,c),h=this.getPoolFeeRange(c),y=o.spotPriceInGivenOut(a),w=l.shiftedBy(-1*a.decimalsOut).multipliedBy(y),f;g.isZero()?f=-100:f=ie(w,g).toNumber(),r.unshift({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:l,calculatedIn:g,amountIn:u,spotPrice:y,tradeFeePct:d,tradeFeeRange:h,priceImpactPct:f,errors:P,isSupply(){return o.type==="Aave"&&o.tokens[0].id===i.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:N(l,a.decimalsOut),calculatedIn:N(g,a.decimalsIn),amountIn:N(u,a.decimalsIn),spotPrice:N(y,a.decimalsIn),tradeFeePct:d,tradeFeeRange:h,priceImpactPct:f,errors:P}}})}return r}};import{encodeFunctionData as xs}from"viem";var _e=class extends D{balanceClient;evmClient;constructor(e){super(e),this.balanceClient=new q(e),this.evmClient=new V}buildBuyTx(e,t=1){if(e.type!=="Buy")throw new Error("Not permitted");let{amountIn:s,amountOut:r,swaps:n}=e,i=n[0],o=n[n.length-1],a=ae(s,t),l=i.assetIn,c=o.assetOut,u=s.plus(a),g;return this.isDirectOmnipoolTrade(n)?g=this.api.tx.omnipool.buy(c,l,r.toFixed(),u.toFixed()):g=this.api.tx.router.buy(l,c,r.toFixed(),u.toFixed(),this.buildRoute(n)),{hex:g.toHex(),name:"RouterBuy",get:()=>g,dryRun:d=>this.dryRun(d,g)}}buildSellTx(e,t=1){if(e.type!=="Sell")throw new Error("Not permitted");let{amountIn:s,amountOut:r,swaps:n}=e,i=n[0],o=n[n.length-1],a=ae(r,t),l=i.assetIn,c=o.assetOut,u=r.minus(a),g;return this.isDirectOmnipoolTrade(n)?g=this.api.tx.omnipool.sell(l,c,s.toFixed(),u.toFixed()):g=this.api.tx.router.sell(l,c,s.toFixed(),u.toFixed(),this.buildRoute(n)),{hex:g.toHex(),name:"RouterSell",get:()=>g,dryRun:d=>this.dryRun(d,g)}}buildSellAllTx(e,t=1){if(e.type!=="Sell")throw new Error("Not permitted");let{amountOut:s,swaps:r}=e,n=r[0],i=r[r.length-1],o=ae(s,t),a=n.assetIn,l=i.assetOut,c=s.minus(o),u=this.api.tx.router.sellAll(a,l,c.toFixed(),this.buildRoute(r));return{hex:u.toHex(),name:"RouterSellAll",get:()=>u,dryRun:g=>this.dryRun(g,u)}}async buildWithdrawAndSellReserveTx(e,t,s=1){let{amountIn:r,amountOut:n,swaps:i}=t,o=i[0],a=i[i.length-1];if(!o.isWithdraw())throw new Error("Not permitted");let l=o.assetIn,c=o.assetOut,[u,g]=await Promise.all([this.evmClient.getProvider().getGasPrice(),this.balanceClient.getBalance(e,l)]),d=r.isGreaterThanOrEqualTo(g.minus(5)),P=u*10n/100n,h=z.fromAny(e),y=d?Ce:BigInt(r.toFixed()),w=U.fromAssetId(c),f=xs({abi:$,functionName:"withdraw",args:[w,y,h]}),O=this.api.tx.evm.call(h,le,f,0n,De,u+P,u+P,null,[]),A=ae(n,s),x=c,k=a.assetOut,G=n.minus(A),Y=this.api.tx.router.sell(x,k,r.minus(5).toFixed(),G.toFixed(),this.buildRoute(i.slice(1))),Be=this.api.tx.utility.batchAll([O,Y]);return{hex:Be.toHex(),name:"WithdrawAndRouterReserveSell",get:()=>Be,dryRun:tt=>this.dryRun(tt,Be)}}buildRoute(e){return e.map(({assetIn:t,assetOut:s,pool:r,poolId:n})=>r==="Stableswap"?{pool:{Stableswap:n},assetIn:t,assetOut:s}:{pool:r,assetIn:t,assetOut:s})}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};export{bs as AMOUNT_MAX,j as AaveClient,pe as AavePool,de as AavePoolClient,ve as AaveUtils,ee as AssetClient,Ve as AssetNotFound,Ys as BASILISK_PARACHAIN_ID,q as BalanceClient,S as BigNumber,Fe as CachingPoolService,dt as DECIMAL_PLACES,Te as DENOMINATOR,U as ERC20,V as EvmClient,Ne as FarmClient,z as H160,ce as HUB_ASSET_ID,$s as HYDRADX_PARACHAIN_ID,H as HYDRADX_SS58_PREFIX,sr as INFINITY,M as LbpMath,ge as LbpPool,Pe as LbpPoolClient,v as ONE,B as OmniMath,he as OmniPool,be as OmniPoolClient,D as PolkadotApiClient,$e as PoolConfigNotFound,K as PoolError,se as PoolFactory,me as PoolNotFound,te as PoolService,R as PoolType,Ke as ProviderConfigNotFound,Z as RUNTIME_DECIMALS,J as RouteNotFound,oe as Router,Vs as SYSTEM_ASSET_DECIMALS,_ as SYSTEM_ASSET_ID,F as StableMath,Se as StableSwap,we as StableSwapClient,ze as StorageConfigNotFound,Je as SubscriptionNotSupported,Q as TRADEABLE_DEFAULT,ke as TradeRouter,Ee as TradeType,_e as TradeUtils,W as XykMath,ye as XykPool,fe as XykPoolClient,b as ZERO,sn as bnFormatter,m as bnum,Qe as calculateBuyFee,hl as calculateDiffToAvg,ie as calculateDiffToRef,Ze as calculateSellFee,Ge as evmMainnet,je as findNestedKey,tn as findNestedObj,ae as getFraction,ut as isEvmAccount,mt as isEvmAddress,pt as isSs58Address,I as scale};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk",
3
- "version": "7.1.0",
3
+ "version": "7.1.1",
4
4
  "description": "Galactic off-chain routing & optimization of orders across pools for best price execution",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {