@galacticcouncil/sdk 8.1.0 → 8.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 ot=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var ar=Object.getOwnPropertyNames;var lr=Object.prototype.hasOwnProperty;var ur=(u,e)=>{for(var t in e)ot(u,t,{get:e[t],enumerable:!0})},cr=(u,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ar(e))!lr.call(u,s)&&s!==t&&ot(u,s,{get:()=>e[s],enumerable:!(r=or(e,s))||r.enumerable});return u};var mr=u=>cr(ot({},"__esModule",{value:!0}),u);var _r={};ur(_r,{AMOUNT_MAX:()=>tr,AaveClient:()=>ne,AavePool:()=>Te,AavePoolClient:()=>Oe,AaveUtils:()=>Q,AssetClient:()=>ee,AssetNotFound:()=>ft,BASILISK_PARACHAIN_ID:()=>Jr,BalanceClient:()=>G,BigNumber:()=>w.BigNumber,CachingPoolService:()=>me,ChainParams:()=>ae,DECIMAL_PLACES:()=>qt,DENOMINATOR:()=>mt,ERC20:()=>U,EvmClient:()=>L,FarmClient:()=>Ge,H160:()=>K,HUB_ASSET_ID:()=>be,HYDRADX_PARACHAIN_ID:()=>Zr,HYDRADX_SS58_PREFIX:()=>J,INFINITY:()=>pr,LbpMath:()=>X,LbpPool:()=>Be,LbpPoolClient:()=>Ie,ONE:()=>D,OmniMath:()=>_,OmniPool:()=>Ae,OmniPoolClient:()=>_e,PolkadotApiClient:()=>q,PoolConfigNotFound:()=>Pt,PoolError:()=>se,PoolFactory:()=>pe,PoolNotFound:()=>ve,PoolService:()=>ce,PoolType:()=>k,ProviderConfigNotFound:()=>St,RUNTIME_DECIMALS:()=>Se,RouteNotFound:()=>re,Router:()=>de,SYSTEM_ASSET_DECIMALS:()=>kt,SYSTEM_ASSET_ID:()=>M,StableMath:()=>C,StableSwap:()=>Re,StableSwapClient:()=>Ee,StorageConfigNotFound:()=>yt,SubscriptionNotSupported:()=>bt,TRADEABLE_DEFAULT:()=>xe,TradeOrderError:()=>It,TradeOrderType:()=>et,TradeRouteBuilder:()=>W,TradeRouter:()=>he,TradeScheduler:()=>Pe,TradeType:()=>Qe,TxBuilderFactory:()=>ye,XykMath:()=>j,XykPool:()=>Ne,XykPoolClient:()=>Fe,ZERO:()=>S,bnFormatter:()=>wr,bnum:()=>p,calculateBuyFee:()=>Bt,calculateDiffToAvg:()=>Ir,calculateDiffToRef:()=>ge,calculateSellFee:()=>Ot,createSdkContext:()=>Ar,evmMainnet:()=>ct,findNestedKey:()=>wt,findNestedObj:()=>vr,getFraction:()=>te,isEvmAccount:()=>Ct,isEvmAddress:()=>Mt,isSs58Address:()=>Lt,scale:()=>A,toBn:()=>dr,toDecimals:()=>T});module.exports=mr(_r);var ie=[{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 at=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var qe="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",lt="0x112b087b60C1a166130d59266363C45F8aa99db0",ut="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Ue=1000000n;var Ft=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Dt=require("viem"),Rt=["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"],Et=["wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],ct=(0,Dt.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:Rt,webSocket:Et},default:{http:Rt,webSocket:Et}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var z=require("viem");var L=class{chain;constructor(e){this.chain=e||ct}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}async getGasPrice(){return this.getProvider().getGasPrice()}getProvider(){return(0,z.createPublicClient)({chain:this.chain,transport:(0,z.http)()})}getWsProvider(){return(0,z.createPublicClient)({chain:this.chain,transport:(0,z.webSocket)()})}getSigner(e){return(0,z.createWalletClient)({account:e,chain:this.chain,transport:(0,z.custom)(window.ethereum)})}};var ne=class{evmClient;constructor(e){this.evmClient=e??new L}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:at,address:lt,args:[ut],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:at,address:lt,args:[ut,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:ie,address:qe,args:[e],functionName:"getUserAccountData"})}};var Z=require("@polkadot/util-crypto"),oe=require("@polkadot/util"),V=require("buffer");var Jr=2090,mt=1e3,be="1",Zr=2034,J=63,Se=18,M="0",kt=12,xe=15;var pt="ETH\0";function Ct(u){if(!u)return!1;try{let e=(0,Z.decodeAddress)(u,!0),t=V.Buffer.from(pt);return V.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Mt(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Lt(u){try{let e=(0,oe.isHex)(u)?(0,oe.hexToU8a)(u):(0,Z.decodeAddress)(u);return(0,Z.encodeAddress)(e),!0}catch{return!1}}var K=class u{static toAccount=e=>{let t=V.Buffer.from(e.slice(2),"hex"),r=V.Buffer.from(pt);return(0,Z.encodeAddress)(new Uint8Array(V.Buffer.concat([r,t,V.Buffer.alloc(8)])),63)};static fromAccount=e=>{let t=(0,Z.decodeAddress)(e),r=V.Buffer.from(pt),s=t.slice(r.length,-8);return"0x"+V.Buffer.from(s).toString("hex")};static fromSS58=e=>{let r=(0,Z.decodeAddress)(e).slice(0,20);return(0,oe.u8aToHex)(r)};static fromAny=e=>{if(Mt(e))return e;if(Ct(e))return u.fromAccount(e);if(Lt(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var U=class{static fromAssetId(e){let t=Number(e),r=Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),r=Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};var w=require("bignumber.js"),qt=12;w.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:qt});var S=p(0),D=p(1),pr=p("Infinity");function A(u,e){let t=new w.BigNumber(e.toString()),r=new w.BigNumber(10).pow(t);return u.times(r)}function p(u){return new w.BigNumber(u.toString())}function dr(u,e){let t=p(u);return A(t,e)}function T(u,e){return u.shiftedBy(-1*e).toString()}var gr=p("1e27"),hr=p("1.01"),Q=class{client;constructor(e){let t=e??new L;this.client=new ne(t)}async getSummary(e){let t=K.fromAny(e),[r,s,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t)]),[n]=r,[o,a]=s,[l,c,m,h,d,g]=i,f=p(g).dividedBy(1e18).decimalPlaces(6,w.BigNumber.ROUND_DOWN),P=p(l),v=p(c),b=[];for(let I of o){let B=I.underlyingAsset.toLowerCase(),x=n.find(({underlyingAsset:nt})=>nt.toLowerCase()===B);if(!x)throw new Error("Missing pool reserve for "+B);let E=p(I.scaledATokenBalance),R=p(x.liquidityIndex),Y=p(x.priceInMarketReferenceCurrency),Me=E.multipliedBy(R).dividedBy(gr).decimalPlaces(0,w.BigNumber.ROUND_DOWN),Le=p(a===x.eModeCategoryId?x.eModeLiquidationThreshold:x.reserveLiquidationThreshold).div(1e4),st=x.usageAsCollateralEnabled&&I.usageAsCollateralEnabledOnUser&&p(I.scaledATokenBalance).gt(0),it=U.toAssetId(B);b.push({aTokenBalance:Me,decimals:Number(x.decimals),isCollateral:st,priceInRef:Y,reserveId:it,reserveAsset:B,reserveLiquidationThreshold:Le})}return{healthFactor:f.toNumber(),totalCollateral:P,totalDebt:v,reserves:b}}async hasBorrowPositions(e){let t=K.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=K.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,n,o,a,l]=r;return p(l).dividedBy(1e18).decimalPlaces(6,w.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=U.fromAssetId(t),a=n.find(v=>v.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:c,priceInRef:m,reserveLiquidationThreshold:h}=a,d=A(p(r),l).decimalPlaces(0,1),g=c?d.multipliedBy(m).dividedBy(p(10).pow(l)).decimalPlaces(0,w.BigNumber.ROUND_DOWN):S,f=s.minus(g);return f.lte(0)?0:f.multipliedBy(h).dividedBy(i).decimalPlaces(6,w.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=U.fromAssetId(t),a=n.find(P=>P.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:m}=a,d=A(p(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(p(10).pow(l)).decimalPlaces(0,w.BigNumber.ROUND_DOWN),g=s.plus(d);return g.lte(0)?0:g.multipliedBy(m).dividedBy(i).decimalPlaces(6,w.BigNumber.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalCollateral:r,totalDebt:s,reserves:i}=await this.getSummary(e),n=U.fromAssetId(t),o=i.find(a=>a.reserveAsset===n);if(!o)throw new Error("Missing reserve ctx for "+n);return this.calculateWithdrawMax(o,r,s)}async getMaxWithdrawAll(e){let{totalCollateral:t,totalDebt:r,reserves:s}=await this.getSummary(e),i={};for(let n of s){let o=this.calculateWithdrawMax(n,t,r);n.reserveId&&(i[n.reserveId]=o)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,decimals:i,priceInRef:n,reserveLiquidationThreshold:o}=e,a=hr.multipliedBy(r).div(o).decimalPlaces(0,w.BigNumber.ROUND_UP),l=t.minus(a).decimalPlaces(0,1);if(l.lte(0))return{amount:S,decimals:i};let c=l.multipliedBy(p(10).pow(i)).dividedBy(n).decimalPlaces(0,w.BigNumber.ROUND_DOWN);return{amount:w.BigNumber.minimum(s,c),decimals:i}}};function Ut(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var fs=require("@galacticcouncil/api-augment/hydradx"),ys=require("@galacticcouncil/api-augment/basilisk"),q=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Ut(r)&&console.log(e,...t)}};var ee=class extends q{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==M){let m=this.api.consts.balances.existentialDeposit;return{id:M,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:o,existentialDeposit:a}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:n.toHuman(),isSufficient:o?o.toHuman():!0,location:s?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,r,s){let[i,n]=s,{assetType:o,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,r),h=n.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(h)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:m,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:h}}getShares(e,t,r,s){let{assets:i}=s,{name:n,symbol:o,assetType:a,isSufficient:l,existentialDeposit:c}=t,h=i.map(f=>f.toString()).map(f=>{let{symbol:P}=this.getToken(f,t,r);return[f,P]}),d=Object.fromEntries(h),g=Object.values(d);return{id:e,name:g.join(", "),symbol:o?.isSome?o.toHuman():n.toHuman(),decimals:18,icon:g.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),n=r?.find(o=>o.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:n}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,i,n,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(r),l=this.normalizeMetadata(a,o),c=a.map(([{args:[m]},h])=>{let d=h.unwrap(),g=s.get(m.toString()),{assetType:f}=d;switch(f.toString()){case"Bond":let P=n.get(m.toString());return this.getBond(m.toString(),d,l,P);case"StableSwap":let v=i.get(m.toString());return this.getShares(m.toString(),d,l,v);case"External":return this.getExternal(m.toString(),d,t,g);default:return this.getToken(m.toString(),d,l,g)}});return e?c:c.filter(m=>this.isValidAsset(m))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var G=class extends q{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===M?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:i})}async getErc20Balance(e,t){let{free:r,reserved:s,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:r,feeFrozen:0n,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(M,this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t){let s=(await this.api.query.tokens.accounts.keys(e)).map(i=>[e,i.args[1].toString()]);return this.api.query.tokens.accounts.multi(s,i=>{let n=[];i.forEach((o,a)=>{let l=this.calculateFreeBalance(o),c=s[a][1];n.push([c,l])}),t(n)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),n=async()=>{let o=[];(await Promise.all(i.map(async l=>[l,await this.getErc20Balance(e,l)]))).forEach(([l,c])=>{o.push([l,c])}),t(o)};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:r,feeFrozen:s,frozen:i}=e,n=new w.BigNumber(t),o=new w.BigNumber(r||i),a=new w.BigNumber(s||0n),l=o.gt(a)?o:a;return n.minus(l)}};var ae=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),p(this._minOrderBudget)}};var dt=require("@galacticcouncil/math-liquidity-mining"),Gt=require("@polkadot/types"),gt=require("@polkadot/util"),ht=require("@polkadot/util-crypto");var Ge=class extends q{balanceClient;constructor(e){super(e),this.balanceClient=new G(e)}secondsInYear=new w.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),g=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:m,potBalance:f.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),g=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:m,potBalance:f.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new w.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),o=n.price.n.toString(),a=n.price.d.toString(),l;return Number(t)<Number(r)?l=(0,dt.fixed_from_rational)(o,a):l=(0,dt.fixed_from_rational)(a,o),l}getGlobalRewardPerPeriod(e,t,r,s){let n=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return n.gte(r)?r:n}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return(0,gt.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Gt.GenericAccountId32(e,this.padEndU8a((0,gt.u8aConcat)(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,ht.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,ht.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:o,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let m=new w.BigNumber(a.totalSharesZ.toString()),h=a.plannedYieldingPeriods.toString(),d=new w.BigNumber(a.yieldPerPeriod.toString()),g=new w.BigNumber(a.maxRewardPerPeriod.toString()),f=a.blocksPerPeriod.toString(),P=new w.BigNumber(o.multiplier.toString()).shiftedBy(-18),v=this.secondsInYear.div(new w.BigNumber(r).times(f)),b;if(m.isZero())b=d.times(P).times(v);else{let R=this.getGlobalRewardPerPeriod(m,d,g,l);b=this.getPoolYieldPerPeriod(R,P,m,l).times(v)}let I=new w.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),B=g.times(h),x=c?I.plus(c):B;return I.div(x).gte(.999)?S:b.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),S).toString():void 0}};var ve=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Pt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},re=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},ft=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},yt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},bt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},St=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var we=(u,e)=>u===e?0:u==null?e==null?0:-1:e==null?u==null?0:1:typeof u.compare=="function"?u.compare(e):typeof e.compare=="function"?-e.compare(u):u<e?-1:u>e?1:0;var He=(u,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(u(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var Pr=He(()=>"illegal argument(s)"),Ht=u=>{throw new Pr(u)};var fr=He(()=>"index out of bounds"),xt=u=>{throw new fr(u)},We=(u,e,t)=>(u<e||u>=t)&&xt(u);var Wt=23283064365386963e-26,ze=class{float(e=1){return this.int()*Wt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Wt-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var Xe=class extends ze{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var zt=new Xe(Math.random);var Xt=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var Yt=Object.getPrototypeOf({}),Ye="function",$t="string",le=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===Ye)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===Ye)return e.equiv(u)}else return u==e;return typeof u===$t||typeof e===$t?!1:(t=Object.getPrototypeOf(u),(t==null||t===Yt)&&(t=Object.getPrototypeOf(e),t==null||t===Yt)?xr(u,e):typeof u!==Ye&&u.length!==void 0&&typeof e!==Ye&&e.length!==void 0?yr(u,e):u instanceof Set&&e instanceof Set?br(u,e):u instanceof Map&&e instanceof Map?Sr(u,e):u instanceof Date&&e instanceof Date?u.getTime()===e.getTime():u instanceof RegExp&&e instanceof RegExp?u.toString()===e.toString():u!==u&&e!==e)},yr=(u,e,t=le)=>{let r=u.length;if(r===e.length)for(;r-- >0&&t(u[r],e[r]););return r<0},br=(u,e,t=le)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),Sr=(u,e,t=le)=>u.size===e.size&&t([...u].sort(),[...e].sort()),xr=(u,e,t=le)=>{if(Object.keys(u).length!==Object.keys(e).length)return!1;for(let r in u)if(!e.hasOwnProperty(r)||!t(u[r],e[r]))return!1;return!0};var vt=class{value;constructor(e){this.value=e}deref(){return this.value}};var Vt=u=>u instanceof vt;var $e=class u{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Kt("next",this._head)}reverseIterator(){return Kt("prev",this.tail)}clear(){this.release()}compare(e,t=we){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,n=0;for(;r-- >0&&n===0;)n=t(s.value,i.value),s=s.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof u||Xt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!le(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||we;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!Vt(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&xt(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*Kt(u,e){for(;e;)yield e.value,e=e[u]}var Ve=class u extends $e{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new u(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new u}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(We(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(We(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new u,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==s&&n.next?i(n.next):void 0}});return r?i(r):void 0}shuffle(e,t=zt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&Ht("invalid indices: ${from} / ${to}");let i=new u,n=this.nthCell(r);for(;n&&++r<=s;)i.push(n.value),n=n.next;return i}sort(e=we){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,n=0;for(let a=0;a<t&&(n++,i=i.next,!!i);a++);let o=t;for(;n>0||o>0&&i;){let a;n===0?(a=i,i=i.next,o--):!i||o===0||e(r.value,i.value)<=0?(a=r,r=r.next,n--):(a=i,i=i.next,o--),this._tail?this._tail.next=a:this._head=a,a.prev=this._tail,this._tail=a}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),We(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new u;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let n of r)this.insertBefore(s,n);else for(let n of r)this.push(n);return i}};var ue=class u{map;items;opts;_size;constructor(e,t){let r={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=r.map(),this.items=new Ve,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new u(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e),i=Math.max(0,r-(s?s.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(s,e,t,r):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let r=this.map.get(e);return r?this.resetEntry(r):this.set(e,await t())}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let{release:e,maxsize:t,maxlen:r}=this.opts;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e?.(s.k,s.v),this._size-=s.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,r,s){e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var Ke=class u extends ue{constructor(e,t){super(e,{ttl:60*60*1e3,autoExtend:!1,...t})}empty(){return new u(null,this.opts)}has(e){return this.get(e)!==void 0}get(e,t){let r=this.map.get(e);if(r){if(r.value.t>=Date.now())return this.resetEntry(r);this.removeEntry(r)}return t}set(e,t,r=this.opts.ttl){let s=this.opts.ksize(e)+this.opts.vsize(t),i=this.map.get(e),n=Math.max(0,s-(i?i.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(i,e,t,s,r):this._size-=n,t}async getSet(e,t,r=this.opts.ttl){let s=this.get(e);return s!==void 0?s:this.set(e,await t(),r)}prune(){let e=Date.now(),t=this.items.head,r=0;for(;t;)t.value.t<e&&(this.removeEntry(t),r++),t=t.next;return r}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,r=Date.now(),s=this.items.head;for(;s&&(this._size>t||this.length>=e);)s.value.t<r&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(e,t,r,s,i=this.opts.ttl){let n=Date.now()+i;e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,e.value.t=n,this.items.asTail(e)):(this.items.push({k:t,v:r,s,t:n,ttl:i}),this.map.set(t,this.items.tail))}resetEntry(e){return this.opts.autoExtend&&(e.value.t=Date.now()+e.value.ttl),super.resetEntry(e)}};var je=(u,e=new Map)=>t=>{let r;return e.has(t)?e.get(t):(e.set(t,r=u(t)),r)};var k=(i=>(i.Aave="Aave",i.LBP="Lbp",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="Xyk",i))(k||{}),se=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(se||{});var Te=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:S,assetOutED:S}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=[];return t.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=[];return s.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:i}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return A(D,e.decimalsOut)}spotPriceOutGivenIn(e){return A(D,e.decimalsIn)}calculateTradeFee(e,t){return S}};var jt=require("@polkadot/util-crypto"),Jt=require("@polkadot/util"),Zt=require("viem");function wt(u,e){let t=[];return JSON.stringify(u,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function vr(u,e,t){let r;return JSON.stringify(u,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var wr=(u,e)=>typeof e=="bigint"?e.toString():e;var H=class extends G{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Ke(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=je(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 r=[];try{let i=this.subscribePoolChange(t);r.push(i)}catch{}if(t.type==="Aave")return r;let s=this.subscribeTokensPoolBalance(t);if(r.push(s),this.hasSystemAsset(t)){let i=this.subscribeSystemPoolBalance(t);r.push(i)}if(this.hasErc20Asset(t)){let i=this.subscribeErc20PoolBalance(t);r.push(i)}return this.subscribeLog(t),r}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,i])=>{let n=e.tokens.findIndex(o=>o.id==s);n>=0&&t(e,s)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(i=>i.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};var Tr=["Supply","Withdraw","Repay","Borrow"],Oe=class extends H{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:i})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let r=e+"/"+t;return(0,jt.encodeAddress)((0,Jt.stringToU8a)(r.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,r]=e.tokens,s=this.getReserveH160Id(t);return this.api.query.system.events(i=>{i.forEach(n=>{let{event:o}=n,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:l,assetOut:c}=o.data.toHuman(),m=l.replace(/,/g,""),h=c.replace(/,/g,"");(m===r.id||h===r.id)&&(this.log(`Sync AAVE [router:Executed] :: ${m}:${h}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=o.data.toHuman();try{let{eventName:c,args:m}=(0,Zt.decodeEventLog)({abi:ie,topics:l.topics,data:l.data});Tr.includes(c)&&m.reserve.toLowerCase()===s.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(n=>{let o=n.id===t.id?s.toString():i.toString();return{...n,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?wt(e.location,"accountKey20").accountKey20.key:U.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};var $=require("@galacticcouncil/math-lbp"),X=class{static getSpotPrice(e,t,r,s,i){return(0,$.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,$.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,$.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,$.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,$.calculate_pool_trade_fee)(e,t,r)}};var y=class{static toPct(e){return e[0]/e[1]*100}static toDecimals(e){return e[0]/e[1]}static fromPermill(e){return[e/1e3,1e3]}};var Be=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,i,n,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=n,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let o=this.calculateTradeFee(t,r),a=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(o),c=this.calculateInGivenOut(e,l),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:i}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,r),l=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=X.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=X.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=X.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),A(D,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=X.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),A(D,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=X.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var Ie=class extends H{MAX_FINAL_WEIGHT=A(p(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,n])=>this.isActivePool(n.unwrap(),r)).map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),l=await this.getPoolDelta(a,o,r.toString());return this.poolsData.set(i.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let n=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,n)}else{let n=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(n,1)}})}async getPoolDelta(e,t,r){let{start:s,end:i,assets:n,initialWeight:o,finalWeight:a,repayTarget:l,feeCollector:c}=t,m=X.calculateLinearWeights(s.toString(),i.toString(),o.toString(),a.toString(),r),[h,d]=n,g=h.toString(),f=p(m),P=d.toString(),v=this.MAX_FINAL_WEIGHT.minus(p(f)),[b,I,B]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,P)]);return{repayFeeApply:b,tokens:[{id:g,weight:f,balance:I.toString()},{id:P,weight:v,balance:B.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=p(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var O=require("@galacticcouncil/math-omnipool");var _=class{static calculateSpotPrice(e,t,r,s){return(0,O.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,O.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,n,o,a,l){return(0,O.calculate_in_given_out)(e,t,r,s,i,n,o,a,l)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,O.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,n,o,a,l){return(0,O.calculate_out_given_in)(e,t,r,s,i,n,o,a,l)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,O.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,O.calculate_pool_trade_fee)(e,t,r)}static calculateShares(e,t,r,s){return(0,O.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,n,o,a){return(0,O.calculate_liquidity_out)(e,t,r,s,i,n,o,a)}static calculateLiquidityLRNAOut(e,t,r,s,i,n,o,a){return(0,O.calculate_liquidity_lrna_out)(e,t,r,s,i,n,o,a)}static calculateCapDifference(e,t,r,s){let i=(0,w.BigNumber)(t),n=(0,w.BigNumber)(e),o=(0,w.BigNumber)(s),l=(0,w.BigNumber)(r).shiftedBy(-18);if(i.div(o).lt(l)){let m=l.times(o).minus(i).times(n),h=i.times((0,w.BigNumber)(1).minus(l));return m.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return(0,O.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,O.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,O.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,O.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,O.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,r,s,i,n,o,a,l,c,m){return(0,O.recalculate_asset_fee)(e,t,r,s,i,n,o,a,l,c,m)}static recalculateProtocolFee(e,t,r,s,i,n,o,a,l,c,m){return(0,O.recalculate_protocol_fee)(e,t,r,s,i,n,o,a,l,c,m)}static verifyAssetCap(e,t,r,s){return(0,O.verify_asset_cap)(e,t,r,s)}};var Ae=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,i,n){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.hubAssetId=n}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),o=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(2),a=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&a.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(h)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),o=s.minus(i).div(s).multipliedBy(100).decimalPlaces(2),a=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&a.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(h)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=_.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString(),r?y.toDecimals(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateLrnaInGivenOut(e,t,r){let s=_.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=_.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString(),r?y.toDecimals(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenLrnaIn(e,t,r){let s=_.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=_.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=_.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=_.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=_.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var Qt=require("@polkadot/util-crypto"),er=require("@polkadot/util");var _e=class extends H{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=r.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:m,tradable:h,cap:d,protocolShares:g}=l.unwrap(),f=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:h.bits.toNumber(),balance:f.toString(),cap:p(d.toString()),protocolShares:p(g.toString())}}),o=await Promise.all(n);return o.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=e.assetOut,s=e.assetIn,i="omnipool",n="Short",o=B=>B===M?[M,be]:[be,B],[a,l,c,m]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(r),this.api.query.emaOracle.oracles(i,o(r),n),this.api.query.emaOracle.oracles(i,o(s),n)]),[h,d,g]=this.getAssetFee(e,a.toNumber(),l,c),[f,P,v]=s===be?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,m),b=h+f,I=g+v;return{assetFee:y.fromPermill(d),protocolFee:y.fromPermill(P),min:y.fromPermill(b),max:y.fromPermill(I)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,i)=>{let n=e.tokens[i];if(s.isNone)return n;let o=s.unwrap();return this.updateTokenState(n,o)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:n,protocolShares:o}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(n.toString()),protocolShares:p(o.toString()),tradeable:i.bits.toNumber()}}getAssetFee(e,t,r,s){let{assetOut:i,balanceOut:n}=e,{minFee:o,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,m=y.fromPermill(o.toNumber()),h=y.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=s.unwrap(),{assetFee:g,timestamp:f}=r.unwrap(),P=Math.max(1,t-f.toNumber()),v=d.volume.bIn.toString(),b=d.volume.bOut.toString(),I=d.liquidity.b.toString();i===M&&(v=d.volume.aIn.toString(),b=d.volume.aOut.toString(),I=d.liquidity.a.toString());let B=y.fromPermill(g.toNumber()),x=_.recalculateAssetFee(v,b,I,"9",n.toString(),y.toDecimals(B).toString(),P.toString(),y.toDecimals(m).toString(),y.toDecimals(h).toString(),l.toString(),c.toString());return[o.toNumber(),Number(x)*1e6,a.toNumber()]}getProtocolFee(e,t,r,s){let{assetIn:i,balanceIn:n}=e,{minFee:o,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,m=y.fromPermill(o.toNumber()),h=y.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=s.unwrap(),{protocolFee:g,timestamp:f}=r.unwrap(),P=Math.max(1,t-f.toNumber()),v=d.volume.bIn.toString(),b=d.volume.bOut.toString(),I=d.liquidity.b.toString();i===M&&(v=d.volume.aIn.toString(),b=d.volume.aOut.toString(),I=d.liquidity.a.toString());let B=y.fromPermill(g.toNumber()),x=_.recalculateProtocolFee(v,b,I,"9",n.toString(),y.toDecimals(B).toString(),P.toString(),y.toDecimals(m).toString(),y.toDecimals(h).toString(),l.toString(),c.toString());return[o.toNumber(),Number(x)*1e6,a.toNumber()]}getPoolId(){return(0,Qt.encodeAddress)((0,er.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var F=require("@galacticcouncil/math-xyk"),j=class{static getSpotPrice(e,t,r){return(0,F.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,F.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,F.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,F.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,F.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,F.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,F.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,F.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,F.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,F.calculate_liquidity_out_asset_b)(e,t,r,s)}};var Ne=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),o=s.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.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:s,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),o=s.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.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:s,amountOut:o,feePct:n,errors:a}}calculateInGivenOut(e,t){let r=j.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=j.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=j.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=A(D,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=j.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=A(D,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=j.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var Fe=class extends H{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[n,o]=s.unwrap(),[a,l]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,o.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:a.toString()},{id:o.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var N=require("@galacticcouncil/math-stableswap"),C=class{static getPoolAddress(e){return(0,N.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,i){return(0,N.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,n,o){return(0,N.calculate_in_given_out)(e,t,r,s,i,n,o)}static calculateAddOneAsset(e,t,r,s,i,n,o){return(0,N.calculate_add_one_asset)(e,t,r,s,i,n,o)}static calculateSharesForAmount(e,t,r,s,i,n,o){return(0,N.calculate_shares_for_amount)(e,t,r,s,i,n,o)}static calculateOutGivenIn(e,t,r,s,i,n,o){return(0,N.calculate_out_given_in)(e,t,r,s,i,n,o)}static calculateLiquidityOutOneAsset(e,t,r,s,i,n,o){return(0,N.calculate_liquidity_out_one_asset)(e,t,r,s,i,n,o)}static calculateShares(e,t,r,s,i,n){return(0,N.calculate_shares)(e,t,r,s,i,n)}static calculateSpotPriceWithFee(e,t,r,s,i,n,o,a){return(0,N.calculate_spot_price_with_fee)(e,t,r,s,i,n,o,a)}static calculatePoolTradeFee(e,t,r){return(0,N.calculate_pool_trade_fee)(e,t,r)}static recalculatePegs(e,t,r,s,i){let n=(0,N.recalculate_peg)(e,t,r,s,i);return JSON.parse(n)}};var Re=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,r,s,i,n,o,a,l,c,m){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.amplification=n,this.id=o,this.fee=a,this.totalIssuance=l,this.pegs=c,this.pegsFee=m}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=y.toPct(r.fee),o=[],a=_.isSellAllowed(e.tradeableIn),l=_.isBuyAllowed(e.tradeableOut);return(!a||!l)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),n=y.toPct(r.fee),o=[],a=_.isSellAllowed(e.tradeableIn),l=_.isBuyAllowed(e.tradeableOut);return(!a||!l)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:n,errors:o}}calculateIn(e,t,r){let s=C.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateAddOneAsset(e,t,r){let s=C.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateSharesForAmount(e,t,r){let s=C.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=C.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let s=A(D,e.decimalsIn-e.decimalsOut);return p(t).div(s)}let r=A(D,18-e.decimalsIn);return p(t).div(r)}calculateOut(e,t,r){let s=C.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateWithdrawOneAsset(e,t,r){let s=C.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateShares(e,t,r){let s=C.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=C.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let s=A(D,e.decimalsOut-e.decimalsIn);return p(t).div(s)}let r=A(D,18-e.decimalsOut);return p(t).div(r)}calculateTradeFee(e,t){let r=C.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return p(r)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};var Je=require("@polkadot/util-crypto");var tr=340282366920938463463374607431768211455n,Ee=class extends H{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),l=this.getPoolAddress(a),[c,m,h]=await Promise.all([this.getPoolDelta(a,o,r.toString()),this.getPoolTokens(l,a,o),this.getPoolPegs(a,o,r.toString())]);return this.stablePools.set(l,o),{address:l,id:a,type:"Stableswap",fee:y.fromPermill(o.fee.toNumber()),tokens:m,...c,...h,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toString(),s=this.stablePools.get(e.address);if(s){let[i,n]=await Promise.all([this.getPoolDelta(e.id,s,r),this.getPoolPegs(e.id,s,r)]);Object.assign(e,i,n)}})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:n,finalBlock:o}=t,a=C.calculateAmplification(s.toString(),i.toString(),n.toString(),o.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.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()}}),n=await Promise.all(i);return n.push({id:t,tradeable:15,balance:tr.toString()}),n}getPoolDefaultPegs(e){let t=e.fee,r=C.defaultPegs(e.assets.length);return{pegsFee:y.fromPermill(t.toNumber()),pegs:r}}async getPoolPegs(e,t,r){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getPoolDefaultPegs(t);let i=s.unwrap(),n=await this.getLatestPegs(t,i,r),o=this.getRecentPegs(i),a=i.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[c,m]=C.recalculatePegs(JSON.stringify(o),JSON.stringify(n),r,a.replace(/%/g,""),l.replace(/%/g,"")),h=Number(c)*1e4;return{pegsFee:y.fromPermill(h),pegs:m}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(i=>i.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,i=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),n=s.map(async(o,a)=>{if(o.isOracle){let[l,c,m]=o.asOracle,h=[m.toString(),i[a]].map(b=>Number(b)).sort((b,I)=>b-I),d=await this.api.query.emaOracle.oracles(l,h,c),[{price:g,updatedAt:f}]=d.unwrap(),P=g.n.toString(),v=g.d.toString();return m.toString()===h[0].toString()?[[P,v],f.toString()]:[[v,P],f.toString()]}else return[o.asValue.map(l=>l.toString()),r]});return Promise.all(n)}getPoolAddress(e){let t=Number(e),r=C.getPoolAddress(t);return(0,Je.encodeAddress)((0,Je.blake2AsHex)(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var ce=class extends q{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=je(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 Oe(this.api),this.xykClient=new Fe(this.api),this.omniClient=new _e(this.api),this.lbpClient=new Ie(this.api),this.stableClient=new Ee(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(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(s=>s.isSupported()).map(s=>s.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(r=>e.some(s=>s===r.getPoolType())).map(r=>r.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new ve(t.type)}}};var me=class extends ce{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new ue(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let i=await super.getPoolFees(e,t);return this.feeCache.set(r,i),i}}async destroy(){this.log(`Destroying pool cache!
|
|
1
|
+
"use strict";var ot=Object.defineProperty;var or=Object.getOwnPropertyDescriptor;var ar=Object.getOwnPropertyNames;var lr=Object.prototype.hasOwnProperty;var ur=(u,e)=>{for(var t in e)ot(u,t,{get:e[t],enumerable:!0})},cr=(u,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ar(e))!lr.call(u,s)&&s!==t&&ot(u,s,{get:()=>e[s],enumerable:!(r=or(e,s))||r.enumerable});return u};var mr=u=>cr(ot({},"__esModule",{value:!0}),u);var _r={};ur(_r,{AMOUNT_MAX:()=>tr,AaveClient:()=>ne,AavePool:()=>Te,AavePoolClient:()=>Oe,AaveUtils:()=>Q,AssetClient:()=>ee,AssetNotFound:()=>ft,BASILISK_PARACHAIN_ID:()=>Jr,BalanceClient:()=>G,BigNumber:()=>w.BigNumber,CachingPoolService:()=>me,ChainParams:()=>ae,DECIMAL_PLACES:()=>qt,DENOMINATOR:()=>mt,ERC20:()=>U,EvmClient:()=>L,FarmClient:()=>Ge,H160:()=>K,HUB_ASSET_ID:()=>be,HYDRADX_PARACHAIN_ID:()=>Zr,HYDRADX_SS58_PREFIX:()=>J,INFINITY:()=>pr,LbpMath:()=>X,LbpPool:()=>Be,LbpPoolClient:()=>Ie,ONE:()=>D,OmniMath:()=>_,OmniPool:()=>Ae,OmniPoolClient:()=>_e,PolkadotApiClient:()=>q,PoolConfigNotFound:()=>Pt,PoolError:()=>se,PoolFactory:()=>pe,PoolNotFound:()=>ve,PoolService:()=>ce,PoolType:()=>k,ProviderConfigNotFound:()=>St,RUNTIME_DECIMALS:()=>Se,RouteNotFound:()=>re,Router:()=>de,SYSTEM_ASSET_DECIMALS:()=>kt,SYSTEM_ASSET_ID:()=>M,StableMath:()=>C,StableSwap:()=>Re,StableSwapClient:()=>Ee,StorageConfigNotFound:()=>yt,SubscriptionNotSupported:()=>bt,TRADEABLE_DEFAULT:()=>xe,TradeOrderError:()=>It,TradeOrderType:()=>et,TradeRouteBuilder:()=>W,TradeRouter:()=>he,TradeScheduler:()=>Pe,TradeType:()=>Qe,TxBuilderFactory:()=>ye,XykMath:()=>j,XykPool:()=>Ne,XykPoolClient:()=>Fe,ZERO:()=>S,bnFormatter:()=>wr,bnum:()=>p,calculateBuyFee:()=>Bt,calculateDiffToAvg:()=>Ir,calculateDiffToRef:()=>ge,calculateSellFee:()=>Ot,createSdkContext:()=>Ar,evmMainnet:()=>ct,findNestedKey:()=>wt,findNestedObj:()=>vr,getFraction:()=>te,isEvmAccount:()=>Ct,isEvmAddress:()=>Mt,isSs58Address:()=>Lt,scale:()=>A,toBn:()=>dr,toDecimals:()=>T});module.exports=mr(_r);var ie=[{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 at=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var qe="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",lt="0x112b087b60C1a166130d59266363C45F8aa99db0",ut="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Ue=1000000n;var Ft=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Dt=require("viem"),Rt=["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"],Et=["wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],ct=(0,Dt.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:Rt,webSocket:Et},default:{http:Rt,webSocket:Et}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});var z=require("viem");var L=class{chain;constructor(e){this.chain=e||ct}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}async getGasPrice(){return this.getProvider().getGasPrice()}getProvider(){return(0,z.createPublicClient)({chain:this.chain,transport:(0,z.http)()})}getWsProvider(){return(0,z.createPublicClient)({chain:this.chain,transport:(0,z.webSocket)()})}getSigner(e){return(0,z.createWalletClient)({account:e,chain:this.chain,transport:(0,z.custom)(window.ethereum)})}};var ne=class{evmClient;constructor(e){this.evmClient=e??new L}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:at,address:lt,args:[ut],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:at,address:lt,args:[ut,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:ie,address:qe,args:[e],functionName:"getUserAccountData"})}};var Z=require("@polkadot/util-crypto"),oe=require("@polkadot/util"),V=require("buffer");var Jr=2090,mt=1e3,be="1",Zr=2034,J=63,Se=18,M="0",kt=12,xe=15;var pt="ETH\0";function Ct(u){if(!u)return!1;try{let e=(0,Z.decodeAddress)(u,!0),t=V.Buffer.from(pt);return V.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Mt(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Lt(u){try{let e=(0,oe.isHex)(u)?(0,oe.hexToU8a)(u):(0,Z.decodeAddress)(u);return(0,Z.encodeAddress)(e),!0}catch{return!1}}var K=class u{static toAccount=e=>{let t=V.Buffer.from(e.slice(2),"hex"),r=V.Buffer.from(pt);return(0,Z.encodeAddress)(new Uint8Array(V.Buffer.concat([r,t,V.Buffer.alloc(8)])),63)};static fromAccount=e=>{let t=(0,Z.decodeAddress)(e),r=V.Buffer.from(pt),s=t.slice(r.length,-8);return"0x"+V.Buffer.from(s).toString("hex")};static fromSS58=e=>{let r=(0,Z.decodeAddress)(e).slice(0,20);return(0,oe.u8aToHex)(r)};static fromAny=e=>{if(Mt(e))return e;if(Ct(e))return u.fromAccount(e);if(Lt(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var U=class{static fromAssetId(e){let t=Number(e),r=Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),r=Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};var w=require("bignumber.js"),qt=12;w.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:qt});var S=p(0),D=p(1),pr=p("Infinity");function A(u,e){let t=new w.BigNumber(e.toString()),r=new w.BigNumber(10).pow(t);return u.times(r)}function p(u){return new w.BigNumber(u.toString())}function dr(u,e){let t=p(u);return A(t,e)}function T(u,e){return u.shiftedBy(-1*e).toString()}var gr=p("1e27"),hr=p("1.01"),Q=class{client;constructor(e){let t=e??new L;this.client=new ne(t)}async getSummary(e){let t=K.fromAny(e),[r,s,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t)]),[n]=r,[o,a]=s,[l,c,m,h,d,g]=i,f=p(g).dividedBy(1e18).decimalPlaces(6,w.BigNumber.ROUND_DOWN),P=p(l),v=p(c),b=[];for(let I of o){let B=I.underlyingAsset.toLowerCase(),x=n.find(({underlyingAsset:nt})=>nt.toLowerCase()===B);if(!x)throw new Error("Missing pool reserve for "+B);let E=p(I.scaledATokenBalance),R=p(x.liquidityIndex),Y=p(x.priceInMarketReferenceCurrency),Me=E.multipliedBy(R).dividedBy(gr).decimalPlaces(0,w.BigNumber.ROUND_DOWN),Le=p(a===x.eModeCategoryId?x.eModeLiquidationThreshold:x.reserveLiquidationThreshold).div(1e4),st=x.usageAsCollateralEnabled&&I.usageAsCollateralEnabledOnUser&&p(I.scaledATokenBalance).gt(0),it=U.toAssetId(B);b.push({aTokenBalance:Me,decimals:Number(x.decimals),isCollateral:st,priceInRef:Y,reserveId:it,reserveAsset:B,reserveLiquidationThreshold:Le})}return{healthFactor:f.toNumber(),totalCollateral:P,totalDebt:v,reserves:b}}async hasBorrowPositions(e){let t=K.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=K.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,n,o,a,l]=r;return p(l).dividedBy(1e18).decimalPlaces(6,w.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=U.fromAssetId(t),a=n.find(v=>v.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:c,priceInRef:m,reserveLiquidationThreshold:h}=a,d=A(p(r),l).decimalPlaces(0,1),g=c?d.multipliedBy(m).dividedBy(p(10).pow(l)).decimalPlaces(0,w.BigNumber.ROUND_DOWN):S,f=s.minus(g);return f.lte(0)?0:f.multipliedBy(h).dividedBy(i).decimalPlaces(6,w.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=U.fromAssetId(t),a=n.find(P=>P.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:m}=a,d=A(p(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(p(10).pow(l)).decimalPlaces(0,w.BigNumber.ROUND_DOWN),g=s.plus(d);return g.lte(0)?0:g.multipliedBy(m).dividedBy(i).decimalPlaces(6,w.BigNumber.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalCollateral:r,totalDebt:s,reserves:i}=await this.getSummary(e),n=U.fromAssetId(t),o=i.find(a=>a.reserveAsset===n);if(!o)throw new Error("Missing reserve ctx for "+n);return this.calculateWithdrawMax(o,r,s)}async getMaxWithdrawAll(e){let{totalCollateral:t,totalDebt:r,reserves:s}=await this.getSummary(e),i={};for(let n of s){let o=this.calculateWithdrawMax(n,t,r);n.reserveId&&(i[n.reserveId]=o)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,decimals:i,priceInRef:n,reserveLiquidationThreshold:o}=e,a=hr.multipliedBy(r).div(o).decimalPlaces(0,w.BigNumber.ROUND_UP),l=t.minus(a).decimalPlaces(0,1);if(l.lte(0))return{amount:S,decimals:i};let c=l.multipliedBy(p(10).pow(i)).dividedBy(n).decimalPlaces(0,w.BigNumber.ROUND_DOWN);return{amount:w.BigNumber.minimum(s,c),decimals:i}}};function Ut(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var fs=require("@galacticcouncil/api-augment/hydradx"),ys=require("@galacticcouncil/api-augment/basilisk"),q=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Ut(r)&&console.log(e,...t)}};var ee=class extends q{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==M){let m=this.api.consts.balances.existentialDeposit;return{id:M,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:o,existentialDeposit:a}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:n.toHuman(),isSufficient:o?o.toHuman():!0,location:s?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,r,s){let[i,n]=s,{assetType:o,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,r),h=n.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(h)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:m,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:h}}getShares(e,t,r,s){let{assets:i}=s,{name:n,symbol:o,assetType:a,isSufficient:l,existentialDeposit:c}=t,h=i.map(f=>f.toString()).map(f=>{let{symbol:P}=this.getToken(f,t,r);return[f,P]}),d=Object.fromEntries(h),g=Object.values(d);return{id:e,name:g.join(", "),symbol:o?.isSome?o.toHuman():n.toHuman(),decimals:18,icon:g.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),n=r?.find(o=>o.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:n}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,i,n,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(r),l=this.normalizeMetadata(a,o),c=a.map(([{args:[m]},h])=>{let d=h.unwrap(),g=s.get(m.toString()),{assetType:f}=d;switch(f.toString()){case"Bond":let P=n.get(m.toString());return this.getBond(m.toString(),d,l,P);case"StableSwap":let v=i.get(m.toString());return this.getShares(m.toString(),d,l,v);case"External":return this.getExternal(m.toString(),d,t,g);default:return this.getToken(m.toString(),d,l,g)}});return e?c:c.filter(m=>this.isValidAsset(m))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var G=class extends q{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===M?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:i})}async getErc20Balance(e,t){let{free:r,reserved:s,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:r,feeFrozen:0n,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(M,this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,o]})=>[n.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,l)=>{let c=this.calculateFreeBalance(a),m=i[l][1];o.push([m,c])}),t(o)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),n=async()=>{let o=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:i}=e,n=new w.BigNumber(t),o=new w.BigNumber(r||i),a=new w.BigNumber(s||0n),l=o.gt(a)?o:a;return n.minus(l)}};var ae=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),p(this._minOrderBudget)}};var dt=require("@galacticcouncil/math-liquidity-mining"),Gt=require("@polkadot/types"),gt=require("@polkadot/util"),ht=require("@polkadot/util-crypto");var Ge=class extends q{balanceClient;constructor(e){super(e),this.balanceClient=new G(e)}secondsInYear=new w.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),g=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:m,potBalance:f.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),g=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:m,potBalance:f.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new w.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),o=n.price.n.toString(),a=n.price.d.toString(),l;return Number(t)<Number(r)?l=(0,dt.fixed_from_rational)(o,a):l=(0,dt.fixed_from_rational)(a,o),l}getGlobalRewardPerPeriod(e,t,r,s){let n=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return n.gte(r)?r:n}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return(0,gt.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Gt.GenericAccountId32(e,this.padEndU8a((0,gt.u8aConcat)(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,ht.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,ht.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:o,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let m=new w.BigNumber(a.totalSharesZ.toString()),h=a.plannedYieldingPeriods.toString(),d=new w.BigNumber(a.yieldPerPeriod.toString()),g=new w.BigNumber(a.maxRewardPerPeriod.toString()),f=a.blocksPerPeriod.toString(),P=new w.BigNumber(o.multiplier.toString()).shiftedBy(-18),v=this.secondsInYear.div(new w.BigNumber(r).times(f)),b;if(m.isZero())b=d.times(P).times(v);else{let R=this.getGlobalRewardPerPeriod(m,d,g,l);b=this.getPoolYieldPerPeriod(R,P,m,l).times(v)}let I=new w.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),B=g.times(h),x=c?I.plus(c):B;return I.div(x).gte(.999)?S:b.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),S).toString():void 0}};var ve=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Pt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},re=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},ft=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},yt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},bt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},St=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var we=(u,e)=>u===e?0:u==null?e==null?0:-1:e==null?u==null?0:1:typeof u.compare=="function"?u.compare(e):typeof e.compare=="function"?-e.compare(u):u<e?-1:u>e?1:0;var He=(u,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(u(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var Pr=He(()=>"illegal argument(s)"),Ht=u=>{throw new Pr(u)};var fr=He(()=>"index out of bounds"),xt=u=>{throw new fr(u)},We=(u,e,t)=>(u<e||u>=t)&&xt(u);var Wt=23283064365386963e-26,ze=class{float(e=1){return this.int()*Wt*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*Wt-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var Xe=class extends ze{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var zt=new Xe(Math.random);var Xt=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var Yt=Object.getPrototypeOf({}),Ye="function",$t="string",le=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===Ye)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===Ye)return e.equiv(u)}else return u==e;return typeof u===$t||typeof e===$t?!1:(t=Object.getPrototypeOf(u),(t==null||t===Yt)&&(t=Object.getPrototypeOf(e),t==null||t===Yt)?xr(u,e):typeof u!==Ye&&u.length!==void 0&&typeof e!==Ye&&e.length!==void 0?yr(u,e):u instanceof Set&&e instanceof Set?br(u,e):u instanceof Map&&e instanceof Map?Sr(u,e):u instanceof Date&&e instanceof Date?u.getTime()===e.getTime():u instanceof RegExp&&e instanceof RegExp?u.toString()===e.toString():u!==u&&e!==e)},yr=(u,e,t=le)=>{let r=u.length;if(r===e.length)for(;r-- >0&&t(u[r],e[r]););return r<0},br=(u,e,t=le)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),Sr=(u,e,t=le)=>u.size===e.size&&t([...u].sort(),[...e].sort()),xr=(u,e,t=le)=>{if(Object.keys(u).length!==Object.keys(e).length)return!1;for(let r in u)if(!e.hasOwnProperty(r)||!t(u[r],e[r]))return!1;return!0};var vt=class{value;constructor(e){this.value=e}deref(){return this.value}};var Vt=u=>u instanceof vt;var $e=class u{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Kt("next",this._head)}reverseIterator(){return Kt("prev",this.tail)}clear(){this.release()}compare(e,t=we){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,n=0;for(;r-- >0&&n===0;)n=t(s.value,i.value),s=s.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof u||Xt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!le(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||we;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!Vt(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&xt(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*Kt(u,e){for(;e;)yield e.value,e=e[u]}var Ve=class u extends $e{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new u(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new u}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(We(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(We(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new u,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==s&&n.next?i(n.next):void 0}});return r?i(r):void 0}shuffle(e,t=zt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&Ht("invalid indices: ${from} / ${to}");let i=new u,n=this.nthCell(r);for(;n&&++r<=s;)i.push(n.value),n=n.next;return i}sort(e=we){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,n=0;for(let a=0;a<t&&(n++,i=i.next,!!i);a++);let o=t;for(;n>0||o>0&&i;){let a;n===0?(a=i,i=i.next,o--):!i||o===0||e(r.value,i.value)<=0?(a=r,r=r.next,n--):(a=i,i=i.next,o--),this._tail?this._tail.next=a:this._head=a,a.prev=this._tail,this._tail=a}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),We(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new u;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let n of r)this.insertBefore(s,n);else for(let n of r)this.push(n);return i}};var ue=class u{map;items;opts;_size;constructor(e,t){let r={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=r.map(),this.items=new Ve,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new u(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e),i=Math.max(0,r-(s?s.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(s,e,t,r):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let r=this.map.get(e);return r?this.resetEntry(r):this.set(e,await t())}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let{release:e,maxsize:t,maxlen:r}=this.opts;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e?.(s.k,s.v),this._size-=s.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,r,s){e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var Ke=class u extends ue{constructor(e,t){super(e,{ttl:60*60*1e3,autoExtend:!1,...t})}empty(){return new u(null,this.opts)}has(e){return this.get(e)!==void 0}get(e,t){let r=this.map.get(e);if(r){if(r.value.t>=Date.now())return this.resetEntry(r);this.removeEntry(r)}return t}set(e,t,r=this.opts.ttl){let s=this.opts.ksize(e)+this.opts.vsize(t),i=this.map.get(e),n=Math.max(0,s-(i?i.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(i,e,t,s,r):this._size-=n,t}async getSet(e,t,r=this.opts.ttl){let s=this.get(e);return s!==void 0?s:this.set(e,await t(),r)}prune(){let e=Date.now(),t=this.items.head,r=0;for(;t;)t.value.t<e&&(this.removeEntry(t),r++),t=t.next;return r}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,r=Date.now(),s=this.items.head;for(;s&&(this._size>t||this.length>=e);)s.value.t<r&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(e,t,r,s,i=this.opts.ttl){let n=Date.now()+i;e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,e.value.t=n,this.items.asTail(e)):(this.items.push({k:t,v:r,s,t:n,ttl:i}),this.map.set(t,this.items.tail))}resetEntry(e){return this.opts.autoExtend&&(e.value.t=Date.now()+e.value.ttl),super.resetEntry(e)}};var je=(u,e=new Map)=>t=>{let r;return e.has(t)?e.get(t):(e.set(t,r=u(t)),r)};var k=(i=>(i.Aave="Aave",i.LBP="Lbp",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="Xyk",i))(k||{}),se=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(se||{});var Te=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:S,assetOutED:S}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=[];return t.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=[];return s.isGreaterThan(e.balanceOut)&&i.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:i}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return A(D,e.decimalsOut)}spotPriceOutGivenIn(e){return A(D,e.decimalsIn)}calculateTradeFee(e,t){return S}};var jt=require("@polkadot/util-crypto"),Jt=require("@polkadot/util"),Zt=require("viem");function wt(u,e){let t=[];return JSON.stringify(u,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function vr(u,e,t){let r;return JSON.stringify(u,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var wr=(u,e)=>typeof e=="bigint"?e.toString():e;var H=class extends G{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new Ke(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=je(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 r=[];try{let i=this.subscribePoolChange(t);r.push(i)}catch{}if(t.type==="Aave")return r;let s=this.subscribeTokensPoolBalance(t);if(r.push(s),this.hasSystemAsset(t)){let i=this.subscribeSystemPoolBalance(t);r.push(i)}if(this.hasErc20Asset(t)){let i=this.subscribeErc20PoolBalance(t);r.push(i)}return this.subscribeLog(t),r}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,i])=>{let n=e.tokens.findIndex(o=>o.id==s);n>=0&&t(e,s)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(i=>i.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};var Tr=["Supply","Withdraw","Repay","Borrow"],Oe=class extends H{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:i})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let r=e+"/"+t;return(0,jt.encodeAddress)((0,Jt.stringToU8a)(r.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,r]=e.tokens,s=this.getReserveH160Id(t);return this.api.query.system.events(i=>{i.forEach(n=>{let{event:o}=n,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:l,assetOut:c}=o.data.toHuman(),m=l.replace(/,/g,""),h=c.replace(/,/g,"");(m===r.id||h===r.id)&&(this.log(`Sync AAVE [router:Executed] :: ${m}:${h}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=o.data.toHuman();try{let{eventName:c,args:m}=(0,Zt.decodeEventLog)({abi:ie,topics:l.topics,data:l.data});Tr.includes(c)&&m.reserve.toLowerCase()===s.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(n=>{let o=n.id===t.id?s.toString():i.toString();return{...n,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?wt(e.location,"accountKey20").accountKey20.key:U.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};var $=require("@galacticcouncil/math-lbp"),X=class{static getSpotPrice(e,t,r,s,i){return(0,$.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,$.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,$.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,$.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,$.calculate_pool_trade_fee)(e,t,r)}};var y=class{static toPct(e){return e[0]/e[1]*100}static toDecimals(e){return e[0]/e[1]}static fromPermill(e){return[e/1e3,1e3]}};var Be=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,i,n,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=n,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let o=this.calculateTradeFee(t,r),a=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(o),c=this.calculateInGivenOut(e,l),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:i}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,r),l=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=X.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=X.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=X.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),A(D,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=X.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),A(D,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=X.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var Ie=class extends H{MAX_FINAL_WEIGHT=A(p(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,n])=>this.isActivePool(n.unwrap(),r)).map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),l=await this.getPoolDelta(a,o,r.toString());return this.poolsData.set(i.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let n=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,n)}else{let n=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(n,1)}})}async getPoolDelta(e,t,r){let{start:s,end:i,assets:n,initialWeight:o,finalWeight:a,repayTarget:l,feeCollector:c}=t,m=X.calculateLinearWeights(s.toString(),i.toString(),o.toString(),a.toString(),r),[h,d]=n,g=h.toString(),f=p(m),P=d.toString(),v=this.MAX_FINAL_WEIGHT.minus(p(f)),[b,I,B]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,P)]);return{repayFeeApply:b,tokens:[{id:g,weight:f,balance:I.toString()},{id:P,weight:v,balance:B.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=p(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var O=require("@galacticcouncil/math-omnipool");var _=class{static calculateSpotPrice(e,t,r,s){return(0,O.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,O.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,n,o,a,l){return(0,O.calculate_in_given_out)(e,t,r,s,i,n,o,a,l)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,O.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,n,o,a,l){return(0,O.calculate_out_given_in)(e,t,r,s,i,n,o,a,l)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,O.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,O.calculate_pool_trade_fee)(e,t,r)}static calculateShares(e,t,r,s){return(0,O.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,n,o,a){return(0,O.calculate_liquidity_out)(e,t,r,s,i,n,o,a)}static calculateLiquidityLRNAOut(e,t,r,s,i,n,o,a){return(0,O.calculate_liquidity_lrna_out)(e,t,r,s,i,n,o,a)}static calculateCapDifference(e,t,r,s){let i=(0,w.BigNumber)(t),n=(0,w.BigNumber)(e),o=(0,w.BigNumber)(s),l=(0,w.BigNumber)(r).shiftedBy(-18);if(i.div(o).lt(l)){let m=l.times(o).minus(i).times(n),h=i.times((0,w.BigNumber)(1).minus(l));return m.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return(0,O.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,O.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,O.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,O.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,O.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,r,s,i,n,o,a,l,c,m){return(0,O.recalculate_asset_fee)(e,t,r,s,i,n,o,a,l,c,m)}static recalculateProtocolFee(e,t,r,s,i,n,o,a,l,c,m){return(0,O.recalculate_protocol_fee)(e,t,r,s,i,n,o,a,l,c,m)}static verifyAssetCap(e,t,r,s){return(0,O.verify_asset_cap)(e,t,r,s)}};var Ae=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,i,n){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.hubAssetId=n}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),o=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(2),a=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&a.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(h)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),o=s.minus(i).div(s).multipliedBy(100).decimalPlaces(2),a=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&a.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(h)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=_.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString(),r?y.toDecimals(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateLrnaInGivenOut(e,t,r){let s=_.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=_.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString(),r?y.toDecimals(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenLrnaIn(e,t,r){let s=_.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=_.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=_.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=_.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=_.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var Qt=require("@polkadot/util-crypto"),er=require("@polkadot/util");var _e=class extends H{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=r.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:m,tradable:h,cap:d,protocolShares:g}=l.unwrap(),f=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:h.bits.toNumber(),balance:f.toString(),cap:p(d.toString()),protocolShares:p(g.toString())}}),o=await Promise.all(n);return o.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=e.assetOut,s=e.assetIn,i="omnipool",n="Short",o=B=>B===M?[M,be]:[be,B],[a,l,c,m]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(r),this.api.query.emaOracle.oracles(i,o(r),n),this.api.query.emaOracle.oracles(i,o(s),n)]),[h,d,g]=this.getAssetFee(e,a.toNumber(),l,c),[f,P,v]=s===be?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,m),b=h+f,I=g+v;return{assetFee:y.fromPermill(d),protocolFee:y.fromPermill(P),min:y.fromPermill(b),max:y.fromPermill(I)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,i)=>{let n=e.tokens[i];if(s.isNone)return n;let o=s.unwrap();return this.updateTokenState(n,o)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:n,protocolShares:o}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(n.toString()),protocolShares:p(o.toString()),tradeable:i.bits.toNumber()}}getAssetFee(e,t,r,s){let{assetOut:i,balanceOut:n}=e,{minFee:o,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,m=y.fromPermill(o.toNumber()),h=y.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=s.unwrap(),{assetFee:g,timestamp:f}=r.unwrap(),P=Math.max(1,t-f.toNumber()),v=d.volume.bIn.toString(),b=d.volume.bOut.toString(),I=d.liquidity.b.toString();i===M&&(v=d.volume.aIn.toString(),b=d.volume.aOut.toString(),I=d.liquidity.a.toString());let B=y.fromPermill(g.toNumber()),x=_.recalculateAssetFee(v,b,I,"9",n.toString(),y.toDecimals(B).toString(),P.toString(),y.toDecimals(m).toString(),y.toDecimals(h).toString(),l.toString(),c.toString());return[o.toNumber(),Number(x)*1e6,a.toNumber()]}getProtocolFee(e,t,r,s){let{assetIn:i,balanceIn:n}=e,{minFee:o,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,m=y.fromPermill(o.toNumber()),h=y.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=s.unwrap(),{protocolFee:g,timestamp:f}=r.unwrap(),P=Math.max(1,t-f.toNumber()),v=d.volume.bIn.toString(),b=d.volume.bOut.toString(),I=d.liquidity.b.toString();i===M&&(v=d.volume.aIn.toString(),b=d.volume.aOut.toString(),I=d.liquidity.a.toString());let B=y.fromPermill(g.toNumber()),x=_.recalculateProtocolFee(v,b,I,"9",n.toString(),y.toDecimals(B).toString(),P.toString(),y.toDecimals(m).toString(),y.toDecimals(h).toString(),l.toString(),c.toString());return[o.toNumber(),Number(x)*1e6,a.toNumber()]}getPoolId(){return(0,Qt.encodeAddress)((0,er.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var F=require("@galacticcouncil/math-xyk"),j=class{static getSpotPrice(e,t,r){return(0,F.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,F.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,F.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,F.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,F.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,F.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,F.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,F.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,F.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,F.calculate_liquidity_out_asset_b)(e,t,r,s)}};var Ne=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),o=s.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.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:s,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),o=s.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.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:s,amountOut:o,feePct:n,errors:a}}calculateInGivenOut(e,t){let r=j.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=j.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=j.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=A(D,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=j.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=A(D,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=j.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var Fe=class extends H{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[n,o]=s.unwrap(),[a,l]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,o.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:a.toString()},{id:o.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var N=require("@galacticcouncil/math-stableswap"),C=class{static getPoolAddress(e){return(0,N.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,i){return(0,N.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,n,o){return(0,N.calculate_in_given_out)(e,t,r,s,i,n,o)}static calculateAddOneAsset(e,t,r,s,i,n,o){return(0,N.calculate_add_one_asset)(e,t,r,s,i,n,o)}static calculateSharesForAmount(e,t,r,s,i,n,o){return(0,N.calculate_shares_for_amount)(e,t,r,s,i,n,o)}static calculateOutGivenIn(e,t,r,s,i,n,o){return(0,N.calculate_out_given_in)(e,t,r,s,i,n,o)}static calculateLiquidityOutOneAsset(e,t,r,s,i,n,o){return(0,N.calculate_liquidity_out_one_asset)(e,t,r,s,i,n,o)}static calculateShares(e,t,r,s,i,n){return(0,N.calculate_shares)(e,t,r,s,i,n)}static calculateSpotPriceWithFee(e,t,r,s,i,n,o,a){return(0,N.calculate_spot_price_with_fee)(e,t,r,s,i,n,o,a)}static calculatePoolTradeFee(e,t,r){return(0,N.calculate_pool_trade_fee)(e,t,r)}static recalculatePegs(e,t,r,s,i){let n=(0,N.recalculate_peg)(e,t,r,s,i);return JSON.parse(n)}};var Re=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new u(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,r,s,i,n,o,a,l,c,m){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.amplification=n,this.id=o,this.fee=a,this.totalIssuance=l,this.pegs=c,this.pegsFee=m}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=y.toPct(r.fee),o=[],a=_.isSellAllowed(e.tradeableIn),l=_.isBuyAllowed(e.tradeableOut);return(!a||!l)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),n=y.toPct(r.fee),o=[],a=_.isSellAllowed(e.tradeableIn),l=_.isBuyAllowed(e.tradeableOut);return(!a||!l)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:n,errors:o}}calculateIn(e,t,r){let s=C.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateAddOneAsset(e,t,r){let s=C.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateSharesForAmount(e,t,r){let s=C.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=C.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let s=A(D,e.decimalsIn-e.decimalsOut);return p(t).div(s)}let r=A(D,18-e.decimalsIn);return p(t).div(r)}calculateOut(e,t,r){let s=C.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateWithdrawOneAsset(e,t,r){let s=C.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateShares(e,t,r){let s=C.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=C.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let s=A(D,e.decimalsOut-e.decimalsIn);return p(t).div(s)}let r=A(D,18-e.decimalsOut);return p(t).div(r)}calculateTradeFee(e,t){let r=C.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return p(r)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};var Je=require("@polkadot/util-crypto");var tr=340282366920938463463374607431768211455n,Ee=class extends H{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),l=this.getPoolAddress(a),[c,m,h]=await Promise.all([this.getPoolDelta(a,o,r.toString()),this.getPoolTokens(l,a,o),this.getPoolPegs(a,o,r.toString())]);return this.stablePools.set(l,o),{address:l,id:a,type:"Stableswap",fee:y.fromPermill(o.fee.toNumber()),tokens:m,...c,...h,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toString(),s=this.stablePools.get(e.address);if(s){let[i,n]=await Promise.all([this.getPoolDelta(e.id,s,r),this.getPoolPegs(e.id,s,r)]);Object.assign(e,i,n)}})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:n,finalBlock:o}=t,a=C.calculateAmplification(s.toString(),i.toString(),n.toString(),o.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.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()}}),n=await Promise.all(i);return n.push({id:t,tradeable:15,balance:tr.toString()}),n}getPoolDefaultPegs(e){let t=e.fee,r=C.defaultPegs(e.assets.length);return{pegsFee:y.fromPermill(t.toNumber()),pegs:r}}async getPoolPegs(e,t,r){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getPoolDefaultPegs(t);let i=s.unwrap(),n=await this.getLatestPegs(t,i,r),o=this.getRecentPegs(i),a=i.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[c,m]=C.recalculatePegs(JSON.stringify(o),JSON.stringify(n),r,a.replace(/%/g,""),l.replace(/%/g,"")),h=Number(c)*1e4;return{pegsFee:y.fromPermill(h),pegs:m}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(i=>i.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,i=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),n=s.map(async(o,a)=>{if(o.isOracle){let[l,c,m]=o.asOracle,h=[m.toString(),i[a]].map(b=>Number(b)).sort((b,I)=>b-I),d=await this.api.query.emaOracle.oracles(l,h,c),[{price:g,updatedAt:f}]=d.unwrap(),P=g.n.toString(),v=g.d.toString();return m.toString()===h[0].toString()?[[P,v],f.toString()]:[[v,P],f.toString()]}else return[o.asValue.map(l=>l.toString()),r]});return Promise.all(n)}getPoolAddress(e){let t=Number(e),r=C.getPoolAddress(t);return(0,Je.encodeAddress)((0,Je.blake2AsHex)(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var ce=class extends q{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=je(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 Oe(this.api),this.xykClient=new Fe(this.api),this.omniClient=new _e(this.api),this.lbpClient=new Ie(this.api),this.stableClient=new Ee(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(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(s=>s.isSupported()).map(s=>s.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(r=>e.some(s=>s===r.getPoolType())).map(r=>r.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new ve(t.type)}}};var me=class extends ce{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new ue(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let i=await super.getPoolFees(e,t);return this.feeCache.set(r,i),i}}async destroy(){this.log(`Destroying pool cache!
|
|
2
2
|
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var pe=class{static get(e){switch(e.type){case"Aave":return Te.fromPool(e);case"Xyk":return Ne.fromPool(e);case"Omnipool":return Ae.fromPool(e);case"Lbp":return Be.fromPool(e);case"Stableswap":return Re.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 Or=5,De=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new Ze,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let o=i.dequeue();if(o==null||o.length>Or)return s;let a=o[o.length-1];(r===null||a[0]===r)&&s.push(o),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let m=[...o];m.push(c),i.enqueue(m)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,n]of t){let o=parseInt(i),a=parseInt(n);r.get(o)?.push([a,s])}return r}};function Tt(u){let e={};for(let t of u){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let n=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(n)}}}return e}var ke=class{getProposals(e,t,r){let s=Tt(r),i=Object.keys(s),n=i.map(c=>s[c]).flat(),o=new De,a=o.buildAndPopulateGraph(i,n),l=o.findPaths(a,parseInt(e),t?parseInt(t):null);return this.parsePaths(l)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let n=r[i],o=r[i+1];if(o==null)break;s.push(this.toEdge(n,o))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var de=class{routeSuggester;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new ke,this.routerOptions=Object.freeze({includeOnly:t.includeOnly??[]})}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),n=this.getPaths(e,null,s,t).map(o=>o[o.length-1].assetOut);return this.toAssets([...new Set(n)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(o=>this.validPath(o,r)).map(o=>this.toHops(o,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let i=this.getPoolMap(r);return{assets:s,poolsMap:i}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,pe.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,i])=>{let n=t.get(r);return{poolAddress:r,poolId:n?.id,pool:n?.type,assetIn:s,assetOut:i}})}toAssets(e,t){return e.map(r=>t.get(r))}};var Br=p("100");function Ir(u,e){return u.minus(e).abs().div(u.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ge(u,e){return u.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ot(u,e){return D.minus(e.div(u)).multipliedBy(100).decimalPlaces(2)}function Bt(u,e){return e.div(u).minus(D).multipliedBy(100).decimalPlaces(2)}function te(u,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),u.div(Br).multipliedBy(e).decimalPlaces(0,1)}var Qe=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Qe||{}),et=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(et||{}),It=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(It||{});var he=class extends de{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,n=s[s.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[r,s]}}getPoolFeeRange(e){let t=e.min?y.toPct(e.min):void 0,r=e.max?y.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new re(e,t);let a;if(s)a=await this.toSellSwaps(r,s,n);else{let x=o.map(async R=>await this.toSellSwaps(r,R,n)),E=await Promise.all(x);a=this.findBestSellRoute(E)}let l=a[0],c=a[a.length-1],m=this.isDirectTrade(a),h=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,E)=>x.multipliedBy(E)),d=A(h,c.assetOutDecimals),g=m?c.calculatedOut:this.calculateDelta0Y(l.amountIn,a,n),f=c.amountOut,P=m?c.tradeFeePct:Ot(g,f).toNumber(),v=g.minus(f),b=this.getRouteFeeRange(a),I=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(d),B=ge(g,I);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:v,tradeFeePct:P,tradeFeeRange:b,priceImpactPct:B.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:T(l.amountIn,l.assetInDecimals),amountOut:T(c.amountOut,c.assetOutDecimals),spotPrice:T(d,c.assetOutDecimals),tradeFee:T(v,c.assetOutDecimals),tradeFeePct:P,tradeFeeRange:b,priceImpactPct:B.toNumber(),swaps:a.map(x=>x.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1]:l=e;let c=o.calculateOutGivenIn(a,l);s.push(c)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1].amountOut:l=A(p(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:m,calculatedOut:h,feePct:d,errors:g}=o.validateAndSell(a,l,c),f=this.getPoolFeeRange(c),P=o.spotPriceOutGivenIn(a),v=l.shiftedBy(-1*a.decimalsIn).multipliedBy(P),b=ge(h,v);s.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,amountOut:m,calculatedOut:h,spotPrice:P,tradeFeePct:d,tradeFeeRange:f,priceImpactPct:b.toNumber(),errors:g,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:T(l,a.decimalsIn),amountOut:T(m,a.decimalsOut),calculatedOut:T(h,a.decimalsOut),spotPrice:T(P,a.decimalsOut),tradeFeePct:d,tradeFeeRange:f,priceImpactPct:b.toNumber(),errors:g}}})}return s}async getMostLiquidRoute(e,t){let r=await super.getPools(),{poolsMap:s}=await super.validateTokenPair(e,t,r),i=super.getPaths(e,t,s,r);if(i.length===0)throw new re(e,t);let l=r.filter(d=>d.tokens.some(g=>g.id===e&&g.id!==d.id)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(g=>g.id===e)).map(d=>d.map(g=>p(g.balance).shiftedBy(-1*g.decimals)).reduce((g,f)=>g.plus(f))).sort((d,g)=>g.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=i.map(async d=>await this.toSellSwaps(l,d,s)),m=await Promise.all(c);return this.findBestSellRoute(m).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r);if(super.getPaths(e,t,s,r).length===0)return Promise.resolve(void 0);let n=await this.getMostLiquidRoute(e,t),o=await this.toSellSwaps("1",n,s),a=o.map(m=>m.spotPrice.shiftedBy(-1*m.assetOutDecimals)).reduce((m,h)=>m.multipliedBy(h)),l=o[o.length-1].assetOutDecimals;return{amount:A(a,l),decimals:l}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,n=s[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),o=super.getPaths(e,t,n,i);if(o.length===0)throw new re(e,t);let a;if(s)a=await this.toBuySwaps(r,s,n);else{let x=o.map(async R=>await this.toBuySwaps(r,R,n)),E=await Promise.all(x);a=this.findBestBuyRoute(E)}let l=a[a.length-1],c=a[0],m=this.isDirectTrade(a),h=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetInDecimals)).reduce((x,E)=>x.multipliedBy(E)),d=A(h,c.assetInDecimals),g=m?c.calculatedIn:this.calculateDelta0X(l.amountOut,a,n),f=c.amountIn,P=m?c.tradeFeePct:Bt(g,f).toNumber(),v=f.minus(g),b=this.getRouteFeeRange(a),I=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(d),B;return g.isZero()?B=-100:B=ge(I,g).toNumber(),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:v,tradeFeePct:P,tradeFeeRange:b,priceImpactPct:B,swaps:a,toHuman(){return{type:"Buy",amountOut:T(l.amountOut,l.assetOutDecimals),amountIn:T(c.amountIn,c.assetInDecimals),spotPrice:T(d,c.assetInDecimals),tradeFee:T(v,c.assetInDecimals),tradeFeePct:P,tradeFeeRange:b,priceImpactPct:B,swaps:a.map(x=>x.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=e:l=s[0];let c=o.calculateInGivenOut(a,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=A(p(e),a.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:m,calculatedIn:h,feePct:d,errors:g}=o.validateAndBuy(a,l,c),f=this.getPoolFeeRange(c),P=o.spotPriceInGivenOut(a),v=l.shiftedBy(-1*a.decimalsOut).multipliedBy(P),b;h.isZero()?b=-100:b=ge(v,h).toNumber(),s.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:m,amountOut:l,calculatedIn:h,spotPrice:P,tradeFeePct:d,tradeFeeRange:f,priceImpactPct:b,errors:g,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:T(m,a.decimalsIn),amountOut:T(l,a.decimalsOut),calculatedIn:T(h,a.decimalsIn),spotPrice:T(P,a.decimalsIn),tradeFeePct:d,tradeFeeRange:f,priceImpactPct:b,errors:g}}})}return s}};var rr=6e3,sr=p(1e15),Ce=6,At=-5,_t=6*60*60*1e3;var ir=6;var W=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:i})=>s==="Stableswap"?{pool:{Stableswap:i},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var Pe=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??rr,minBudgetInNative:t.minBudgetInNative??sr})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[n,o]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:l,priceImpactPct:c}=o,m=l[0],h=l[l.length-1],{assetInDecimals:d}=m,{assetOutDecimals:g}=h,f=Math.abs(c),P=this.getMinimumTradeCount(a,n),v=this.getOptimalTradeCount(f),b=i?Math.round(s/i):v,I=Math.ceil(s/P),B=Math.round(s/v),x=Math.round(s/b),E=a.dividedBy(b).decimalPlaces(0,1),R=await this.router.getBestSell(e,t,T(E,d)),Y=a.isLessThan(n),Me=[];Y&&Me.push("OrderTooSmall");let Le=R.amountOut.multipliedBy(b),st=this.toBlockPeriod(x),it=R.tradeFee.multipliedBy(b),nt=W.build(l),Nt={assetIn:e,assetOut:t,errors:Me,frequencyMin:I,frequencyOpt:B,frequency:x,tradeCount:b,tradeFee:it,tradeImpactPct:R.priceImpactPct,tradePeriod:st,tradeRoute:nt,type:"Dca"};return{...Nt,amountIn:a,amountOut:Le,tradeAmountIn:R.amountIn,tradeAmountOut:R.amountOut,toHuman(){return{...Nt,amountIn:T(a,d),amountOut:T(Le,g),tradeAmountIn:T(R.amountIn,d),tradeAmountOut:T(R.amountOut,g)}}}}async getMinimumOrderBudget(e){if(M===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(M,e);if(t)return this.minOrderBudget.times(t.amount).div(p(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:o,priceImpactPct:a}=i,l=o[0],c=o[o.length-1],{assetInDecimals:m}=l,{assetOutDecimals:h}=c,d=Math.abs(a),g=this.getTwapTradeCount(d),f=n.dividedBy(g).decimalPlaces(0,1),P=await this.router.getBestSell(l.assetIn,c.assetOut,T(f,m)),v=g===1,b=n.isLessThan(s),I=P.priceImpactPct<At,B=[];b||v?B.push("OrderTooSmall"):I&&B.push("OrderImpactTooBig");let x=P.amountOut.multipliedBy(g),E=P.tradeFee.multipliedBy(g),R=W.build(o),Y={assetIn:e,assetOut:t,errors:B,tradeCount:g,tradeImpactPct:P.priceImpactPct,tradePeriod:Ce,tradeRoute:R,type:"TwapSell"};return{...Y,amountIn:n,amountOut:x,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:E,toHuman(){return{...Y,amountIn:T(n,m),amountOut:T(x,h),tradeAmountIn:T(P.amountIn,m),tradeAmountOut:T(P.amountOut,h),tradeFee:T(E,h)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:n,swaps:o,priceImpactPct:a}=i,l=o[0],c=o[o.length-1],{assetInDecimals:m}=l,{assetOutDecimals:h}=c,d=Math.abs(a),g=this.getTwapTradeCount(d),f=n.dividedBy(g).decimalPlaces(0,1),P=await this.router.getBestBuy(l.assetIn,c.assetOut,T(f,h)),v=P.amountIn.multipliedBy(g),b=g===1,I=v.isLessThan(s),B=P.priceImpactPct<At,x=[];I||b?x.push("OrderTooSmall"):B&&x.push("OrderImpactTooBig");let E=P.tradeFee.multipliedBy(g),R=W.build(o),Y={assetIn:e,assetOut:t,errors:x,tradeCount:g,tradeImpactPct:P.priceImpactPct,tradePeriod:Ce,tradeRoute:R,type:"TwapBuy"};return{...Y,amountIn:v,amountOut:n,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:E,toHuman(){return{...Y,amountIn:T(v,m),amountOut:T(n,h),tradeAmountIn:T(P.amountIn,m),tradeAmountOut:T(P.amountOut,h),tradeFee:T(E,m)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>_t){let s=_t/(this.blockTime*Ce);return Math.round(s)}return t}getTwapExecutionTime(e){return e*Ce*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,ir)}};var nr=require("viem");var fe=class extends q{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new L,this.balanceClient=new G(e),this.aaveUtils=new Q(this.evmClient)}wrapTx(e,t){return{hex:t.toHex(),name:e,get:()=>t,dryRun:r=>this.dryRun(r,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),Ue)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var tt=class extends fe{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:i,assetOut:n}=s,o;return s.isWithdraw()?o=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,n)).amount:o=await this.balanceClient.getBalance(this.beneficiary,i),e.isGreaterThanOrEqualTo(o.minus(5))&&!s.isWithdraw()?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=te(e,this.slippagePct),o=s.assetIn,a=i.assetOut,l=e.plus(n),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(a,o,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(o,a,t.toFixed(),l.toFixed(),W.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=te(t,this.slippagePct),o=s.assetIn,a=i.assetOut,l=t.minus(n),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(o,a,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(o,a,e.toFixed(),l.toFixed(),W.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=te(e,this.slippagePct),n=r.assetIn,o=s.assetOut,a=e.minus(i),l=this.api.tx.router.sellAll(n,o,a.toFixed(),W.build(t));return r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}async buildWithdrawTx(e){let{swaps:t}=this.trade,r=e||this.trade.amountIn,i=t[0].assetOut,n=await this.evmClient.getGasPrice(),o=n*10n/100n,a=K.fromAny(this.beneficiary),l=e?Ft:BigInt(r.toFixed()),c=U.fromAssetId(i),m=(0,nr.encodeFunctionData)({abi:ie,functionName:"withdraw",args:[c,l,a]}),h=this.api.tx.evm.call(a,qe,m,0n,Ue,n+o,n+o,null,[]);return{hex:h.toHex(),name:"Withdraw",get:()=>h,dryRun:d=>this.dryRun(d,h)}}};var rt=class extends fe{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradePeriod:i,tradeRoute:n}=this.order,o=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:n}}},null);return this.wrapTx("DcaSchedule",o)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:o}=this.order,a=te(i,this.slippagePct),l=i.minus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:o}=this.order,a=te(s,this.slippagePct),l=s.plus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:i.toFixed(),maxAmountIn:l.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var ye=class{api;evmClient;constructor(e,t){this.api=e,this.evmClient=t??new L}trade(e){return new tt(this.api,this.evmClient).setTrade(e)}order(e){return new rt(this.api,this.evmClient).setOrder(e)}};function Ar(u,e){let t=new ae(u),r=e??new L,s=new me(u),i=new Q(r),n=new he(s),o=new Pe(n,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:i,router:n,scheduler:o},client:{asset:new ee(u),balance:new G(u),evm:r},ctx:{pool:s},tx:new ye(u,r),destroy:()=>{s.destroy()}}}0&&(module.exports={AMOUNT_MAX,AaveClient,AavePool,AavePoolClient,AaveUtils,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,ChainParams,DECIMAL_PLACES,DENOMINATOR,ERC20,EvmClient,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,ONE,OmniMath,OmniPool,OmniPoolClient,PolkadotApiClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StableSwapClient,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeOrderError,TradeOrderType,TradeRouteBuilder,TradeRouter,TradeScheduler,TradeType,TxBuilderFactory,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,createSdkContext,evmMainnet,findNestedKey,findNestedObj,getFraction,isEvmAccount,isEvmAddress,isSs58Address,scale,toBn,toDecimals});
|
package/build/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var J=[{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 Me=[{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 be="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ue="0x112b087b60C1a166130d59266363C45F8aa99db0",Ge="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ye=1000000n;var Je=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");import{defineChain as ft}from"viem";var je=["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"],Ze=["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=ft({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:je,webSocket:Ze},default:{http:je,webSocket:Ze}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as et,createWalletClient as St,custom as wt,http as Tt,webSocket as xt}from"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}async getGasPrice(){return this.getProvider().getGasPrice()}getProvider(){return et({chain:this.chain,transport:Tt()})}getWsProvider(){return et({chain:this.chain,transport:xt()})}getSigner(e){return St({account:e,chain:this.chain,transport:wt(window.ethereum)})}};var ee=class{evmClient;constructor(e){this.evmClient=e??new k}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Me,address:Ue,args:[Ge],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:Me,address:Ue,args:[Ge,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:J,address:be,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as Se,encodeAddress as rt}from"@polkadot/util-crypto";import{hexToU8a as Ot,isHex as Bt,u8aToHex as It}from"@polkadot/util";import{Buffer as X}from"buffer";var ls=2090,qe=1e3,fe="1",cs=2034,W=63,te=18,D="0",tt=12,re=15;var He="ETH\0";function vt(p){if(!p)return!1;try{let e=Se(p,!0),t=X.from(He);return X.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function At(p){return!!/^0x[a-fA-F0-9]{40}$/.test(p)}function Nt(p){try{let e=Bt(p)?Ot(p):Se(p);return rt(e),!0}catch{return!1}}var Y=class p{static toAccount=e=>{let t=X.from(e.slice(2),"hex"),r=X.from(He);return rt(new Uint8Array(X.concat([r,t,X.alloc(8)])),63)};static fromAccount=e=>{let t=Se(e),r=X.from(He),s=t.slice(r.length,-8);return"0x"+X.from(s).toString("hex")};static fromSS58=e=>{let r=Se(e).slice(0,20);return It(r)};static fromAny=e=>{if(At(e))return e;if(vt(e))return p.fromAccount(e);if(Nt(e))return p.fromSS58(e);throw new Error("Unknown address type")}};var M=class{static fromAssetId(e){let t=Number(e),r=Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),r=Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as O}from"bignumber.js";var Ft=12;O.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Ft});var w=m(0),R=m(1),ys=m("Infinity");function v(p,e){let t=new O(e.toString()),r=new O(10).pow(t);return p.times(r)}function m(p){return new O(p.toString())}function fs(p,e){let t=m(p);return v(t,e)}function x(p,e){return p.shiftedBy(-1*e).toString()}var Rt=m("1e27"),Et=m("1.01"),V=class{client;constructor(e){let t=e??new k;this.client=new ee(t)}async getSummary(e){let t=Y.fromAny(e),[r,s,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t)]),[o]=r,[i,a]=s,[l,c,u,h,d,g]=n,b=m(g).dividedBy(1e18).decimalPlaces(6,O.ROUND_DOWN),P=m(l),T=m(c),f=[];for(let I of i){let B=I.underlyingAsset.toLowerCase(),S=o.find(({underlyingAsset:Le})=>Le.toLowerCase()===B);if(!S)throw new Error("Missing pool reserve for "+B);let F=m(I.scaledATokenBalance),N=m(S.liquidityIndex),q=m(S.priceInMarketReferenceCurrency),he=F.multipliedBy(N).dividedBy(Rt).decimalPlaces(0,O.ROUND_DOWN),Pe=m(a===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold).div(1e4),ke=S.usageAsCollateralEnabled&&I.usageAsCollateralEnabledOnUser&&m(I.scaledATokenBalance).gt(0),Ce=M.toAssetId(B);f.push({aTokenBalance:he,decimals:Number(S.decimals),isCollateral:ke,priceInRef:q,reserveId:Ce,reserveAsset:B,reserveLiquidationThreshold:Pe})}return{healthFactor:b.toNumber(),totalCollateral:P,totalDebt:T,reserves:f}}async hasBorrowPositions(e){let t=Y.fromAny(e),r=await this.client.getUserAccountData(t),[s,n]=r;return n>0n}async getHealthFactor(e){let t=Y.fromAny(e),r=await this.client.getUserAccountData(t),[s,n,o,i,a,l]=r;return m(l).dividedBy(1e18).decimalPlaces(6,O.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:n,reserves:o}=await this.getSummary(e),i=M.fromAssetId(t),a=o.find(T=>T.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:c,priceInRef:u,reserveLiquidationThreshold:h}=a,d=v(m(r),l).decimalPlaces(0,1),g=c?d.multipliedBy(u).dividedBy(m(10).pow(l)).decimalPlaces(0,O.ROUND_DOWN):w,b=s.minus(g);return b.lte(0)?0:b.multipliedBy(h).dividedBy(n).decimalPlaces(6,O.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:n,reserves:o}=await this.getSummary(e),i=M.fromAssetId(t),a=o.find(P=>P.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:u}=a,d=v(m(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(m(10).pow(l)).decimalPlaces(0,O.ROUND_DOWN),g=s.plus(d);return g.lte(0)?0:g.multipliedBy(u).dividedBy(n).decimalPlaces(6,O.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalCollateral:r,totalDebt:s,reserves:n}=await this.getSummary(e),o=M.fromAssetId(t),i=n.find(a=>a.reserveAsset===o);if(!i)throw new Error("Missing reserve ctx for "+o);return this.calculateWithdrawMax(i,r,s)}async getMaxWithdrawAll(e){let{totalCollateral:t,totalDebt:r,reserves:s}=await this.getSummary(e),n={};for(let o of s){let i=this.calculateWithdrawMax(o,t,r);o.reserveId&&(n[o.reserveId]=i)}return n}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,decimals:n,priceInRef:o,reserveLiquidationThreshold:i}=e,a=Et.multipliedBy(r).div(i).decimalPlaces(0,O.ROUND_UP),l=t.minus(a).decimalPlaces(0,1);if(l.lte(0))return{amount:w,decimals:n};let c=l.multipliedBy(m(10).pow(n)).dividedBy(o).decimalPlaces(0,O.ROUND_DOWN);return{amount:O.minimum(s,c),decimals:n}}};function st(p){switch(p){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var C=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");st(r)&&console.log(e,...t)}};var z=class extends C{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:n}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:n.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==D){let u=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:u.toString()}}let{name:n,assetType:o,isSufficient:i,existentialDeposit:a}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:n.toHuman(),symbol:l,decimals:c,icon:l,type:o.toHuman(),isSufficient:i?i.toHuman():!0,location:s?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,r,s){let[n,o]=s,{assetType:i,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(n.toString(),t,r),h=o.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(h)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:u,icon:c,type:i.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:n.toString(),maturity:h}}getShares(e,t,r,s){let{assets:n}=s,{name:o,symbol:i,assetType:a,isSufficient:l,existentialDeposit:c}=t,h=n.map(b=>b.toString()).map(b=>{let{symbol:P}=this.getToken(b,t,r);return[b,P]}),d=Object.fromEntries(h),g=Object.values(d);return{id:e,name:g.join(", "),symbol:i?.isSome?i.toHuman():o.toHuman(),decimals:18,icon:g.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,r,s){let n=this.getToken(e,t,new Map,s),o=r?.find(i=>i.internalId===n.id);return o?{...n,decimals:o.decimals,name:o.name,symbol:o.symbol,icon:o.symbol,isWhiteListed:o.isWhiteListed}:n}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:n,symbol:o}=s.unwrap();return[r.toString(),{decimals:Number(n.toString()),symbol:o.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,n,o,i]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(r),l=this.normalizeMetadata(a,i),c=a.map(([{args:[u]},h])=>{let d=h.unwrap(),g=s.get(u.toString()),{assetType:b}=d;switch(b.toString()){case"Bond":let P=o.get(u.toString());return this.getBond(u.toString(),d,l,P);case"StableSwap":let T=n.get(u.toString());return this.getShares(u.toString(),d,l,T);case"External":return this.getExternal(u.toString(),d,t,g);default:return this.getToken(u.toString(),d,l,g)}});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 U=class extends C{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===D?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:n}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:n})}async getErc20Balance(e,t){let{free:r,reserved:s,frozen:n}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:r,feeFrozen:0n,frozen:n})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(D,this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t){let s=(await this.api.query.tokens.accounts.keys(e)).map(n=>[e,n.args[1].toString()]);return this.api.query.tokens.accounts.multi(s,n=>{let o=[];n.forEach((i,a)=>{let l=this.calculateFreeBalance(i),c=s[a][1];o.push([c,l])}),t(o)})}async subscribeErc20Balance(e,t,r){let n=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),o=async()=>{let i=[];(await Promise.all(n.map(async l=>[l,await this.getErc20Balance(e,l)]))).forEach(([l,c])=>{i.push([l,c])}),t(i)};return await o(),this.api.rpc.chain.subscribeNewHeads(async()=>{o()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:n}=e,o=new O(t),i=new O(r||n),a=new O(s||0n),l=i.gt(a)?i:a;return o.minus(l)}};var se=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),m(this._minOrderBudget)}};import{fixed_from_rational as nt}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as _t}from"@polkadot/types";import{u8aConcat as it}from"@polkadot/util";import{isAddress as ot}from"@polkadot/util-crypto";var We=class extends C{balanceClient;constructor(e){super(e),this.balanceClient=new U(e)}secondsInYear=new O(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,n])=>{let[,o]=s.args,i=n.unwrap().toString(),a=o.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,i)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,n])=>{let[,o]=s.args,i=n.unwrap().toString(),a=o.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,i)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new O(1).shiftedBy(18).toString();let n=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(n.isNone)return;let[o]=n.unwrap(),i=o.price.n.toString(),a=o.price.d.toString(),l;return Number(t)<Number(r)?l=nt(i,a):l=nt(a,i),l}getGlobalRewardPerPeriod(e,t,r,s){let o=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return o.gte(r)?r:o}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return it(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",n=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new _t(e,this.padEndU8a(it(s,n,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!ot(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&ot(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:i,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let u=new O(a.totalSharesZ.toString()),h=a.plannedYieldingPeriods.toString(),d=new O(a.yieldPerPeriod.toString()),g=new O(a.maxRewardPerPeriod.toString()),b=a.blocksPerPeriod.toString(),P=new O(i.multiplier.toString()).shiftedBy(-18),T=this.secondsInYear.div(new O(r).times(b)),f;if(u.isZero())f=d.times(P).times(T);else{let N=this.getGlobalRewardPerPeriod(u,d,g,l);f=this.getPoolYieldPerPeriod(N,P,u,l).times(T)}let I=new O(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),B=g.times(h),S=c?I.plus(c):B;return I.div(S).gte(.999)?w:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((i,a)=>i.plus(a),w).toString():void 0}};var we=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},at=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},j=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},lt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},ct=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},ut=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},mt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{LRUCache as Cr}from"@thi.ng/cache";import{memoize1 as kr}from"@thi.ng/memoize";var E=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n))(E||{}),Z=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n))(Z||{});var Te=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,n){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),i=m(n.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:o,balanceOut:i,assetInED:w,assetOutED:w}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=[];return t.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:n}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=[];return s.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:n}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return v(R,e.decimalsOut)}spotPriceOutGivenIn(e){return v(R,e.decimalsIn)}calculateTradeFee(e,t){return w}};import{encodeAddress as Ct}from"@polkadot/util-crypto";import{stringToU8a as Lt}from"@polkadot/util";import{decodeEventLog as Mt}from"viem";function pt(p,e){let t=[];return JSON.stringify(p,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Tn(p,e,t){let r;return JSON.stringify(p,(s,n)=>(n&&n[e]===t&&(r=n),n)),r}var xn=(p,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as Dt}from"@thi.ng/memoize";import{TLRUCache as kt}from"@thi.ng/cache";var L=class extends U{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new kt(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=Dt(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 r=[];try{let n=this.subscribePoolChange(t);r.push(n)}catch{}if(t.type==="Aave")return r;let s=this.subscribeTokensPoolBalance(t);if(r.push(s),this.hasSystemAsset(t)){let n=this.subscribeSystemPoolBalance(t);r.push(n)}if(this.hasErc20Asset(t)){let n=this.subscribeErc20PoolBalance(t);r.push(n)}return this.subscribeLog(t),r}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,n])=>{let o=e.tokens.findIndex(i=>i.id==s);o>=0&&t(e,s)&&(e.tokens[o].balance=n.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(n=>n.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};var Ut=["Supply","Withdraw","Repay","Borrow"],xe=class extends L{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:n})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:n.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let r=e+"/"+t;return Ct(Lt(r.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,r]=e.tokens,s=this.getReserveH160Id(t);return this.api.query.system.events(n=>{n.forEach(o=>{let{event:i}=o,a=`${i.section}:${i.method}`;if(a==="router:Executed"){let{assetIn:l,assetOut:c}=i.data.toHuman(),u=l.replace(/,/g,""),h=c.replace(/,/g,"");(u===r.id||h===r.id)&&(this.log(`Sync AAVE [router:Executed] :: ${u}:${h}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=i.data.toHuman();try{let{eventName:c,args:u}=Mt({abi:J,topics:l.topics,data:l.data});Ut.includes(c)&&u.reserve.toLowerCase()===s.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:n}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(o=>{let i=o.id===t.id?s.toString():n.toString();return{...o,balance:i}})}getReserveH160Id(e){return e.type==="Erc20"?pt(e.location,"accountKey20").accountKey20.key:M.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as Gt,calculate_out_given_in as qt,calculate_linear_weights as Ht,calculate_pool_trade_fee as Wt,get_spot_price as Xt}from"@galacticcouncil/math-lbp";var H=class{static getSpotPrice(e,t,r,s,n){return Xt(e,t,r,s,n)}static calculateInGivenOut(e,t,r,s,n){return Gt(e,t,r,s,n)}static calculateOutGivenIn(e,t,r,s,n){return qt(e,t,r,s,n)}static calculateLinearWeights(e,t,r,s,n){return Ht(e,t,r,s,n)}static calculatePoolTradeFee(e,t,r){return Wt(e,t,r)}};var y=class{static toPct(e){return e[0]/e[1]*100}static toDecimals(e){return e[0]/e[1]}static fromPermill(e){return[e/1e3,1e3]}};var Oe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,n,o,i){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n,this.fee=o,this.repayFeeApply=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),i=m(n.balance);return{assetIn:e,assetOut:t,balanceIn:o,balanceOut:i,decimalsIn:s.decimals,decimalsOut:n.decimals,weightIn:s.weight,weightOut:n.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let o=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(o)&&n.push("MaxOutRatioExceeded"),s===e.assetOut){let i=this.calculateTradeFee(t,r),a=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(i),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 i=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(a)&&n.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:i,amountOut:t,feePct:0,errors:n}}}validateAndSell(e,t,r){let s=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let o=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(o)&&n.push("MaxInRatioExceeded"),s===e.assetIn){let i=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(a)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:i,feePct:0,errors:n}}else{let i=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(i,r),l=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=i.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:c,feePct:l,errors:n}}}calculateInGivenOut(e,t){let r=H.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?w:s}calculateOutGivenIn(e,t){let r=H.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?w:s}spotPriceInGivenOut(e){let t=H.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),v(R,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=H.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),v(R,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let r=H.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(r)}};var Be=class extends L{MAX_FINAL_WEIGHT=v(m(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([n,o])=>this.isActivePool(o.unwrap(),r)).map(async([{args:[n]},o])=>{let i=o.unwrap(),a=n.toString(),l=await this.getPoolDelta(a,i,r.toString());return this.poolsData.set(n.toString(),i),{address:a,type:"Lbp",fee:i.fee.toJSON(),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let o=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,o)}else{let o=this.pools.findIndex(i=>i.address==e.address);this.pools.splice(o,1)}})}async getPoolDelta(e,t,r){let{start:s,end:n,assets:o,initialWeight:i,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=H.calculateLinearWeights(s.toString(),n.toString(),i.toString(),a.toString(),r),[h,d]=o,g=h.toString(),b=m(u),P=d.toString(),T=this.MAX_FINAL_WEIGHT.minus(m(b)),[f,I,B]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,P)]);return{repayFeeApply:f,tokens:[{id:g,weight:b,balance:I.toString()},{id:P,weight:T,balance:B.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=m(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as Yt,calculate_lrna_in_given_out as $t,calculate_out_given_in as Vt,calculate_out_given_lrna_in as zt,calculate_pool_trade_fee as Kt,calculate_spot_price as Jt,calculate_lrna_spot_price as jt,calculate_shares as Zt,calculate_liquidity_out as Qt,calculate_liquidity_lrna_out as er,calculate_liquidity_hub_in as tr,is_sell_allowed as rr,is_buy_allowed as sr,is_add_liquidity_allowed as nr,is_remove_liquidity_allowed as ir,recalculate_asset_fee as or,recalculate_protocol_fee as ar,verify_asset_cap as lr}from"@galacticcouncil/math-omnipool";var A=class{static calculateSpotPrice(e,t,r,s){return Jt(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return jt(e,t)}static calculateInGivenOut(e,t,r,s,n,o,i,a,l){return Yt(e,t,r,s,n,o,i,a,l)}static calculateLrnaInGivenOut(e,t,r,s,n){return $t(e,t,r,s,n)}static calculateOutGivenIn(e,t,r,s,n,o,i,a,l){return Vt(e,t,r,s,n,o,i,a,l)}static calculateOutGivenLrnaIn(e,t,r,s,n){return zt(e,t,r,s,n)}static calculatePoolTradeFee(e,t,r){return Kt(e,t,r)}static calculateShares(e,t,r,s){return Zt(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,n,o,i,a){return Qt(e,t,r,s,n,o,i,a)}static calculateLiquidityLRNAOut(e,t,r,s,n,o,i,a){return er(e,t,r,s,n,o,i,a)}static calculateCapDifference(e,t,r,s){let n=O(t),o=O(e),i=O(s),l=O(r).shiftedBy(-18);if(n.div(i).lt(l)){let u=l.times(i).minus(n).times(o),h=n.times(O(1).minus(l));return u.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return tr(e,t,r,s)}static isSellAllowed(e){return rr(e)}static isBuyAllowed(e){return sr(e)}static isAddLiquidityAllowed(e){return nr(e)}static isRemoveLiquidityAllowed(e){return ir(e)}static recalculateAssetFee(e,t,r,s,n,o,i,a,l,c,u){return or(e,t,r,s,n,o,i,a,l,c,u)}static recalculateProtocolFee(e,t,r,s,n,o,i,a,l,c,u){return ar(e,t,r,s,n,o,i,a,l,c,u)}static verifyAssetCap(e,t,r,s){return lr(e,t,r,s)}};var Ie=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,n,o){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n,this.hubAssetId=o}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),i=m(n.balance),a=m(s.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:n.hubReserves,sharesIn:s.shares,sharesOut:n.shares,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:o,balanceOut:i,tradeableIn:s.tradeable,tradeableOut:n.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,r),o=n.minus(s),i=s===w?w:o.div(s).multipliedBy(100).decimalPlaces(2),a=[],l=A.isSellAllowed(e.tradeableIn),c=A.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(h)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:t,feePct:i.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,r),i=s.minus(n).div(s).multipliedBy(100).decimalPlaces(2),a=[],l=A.isSellAllowed(e.tradeableIn),c=A.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(h)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:i.toNumber(),errors:a}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=A.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():w.toString(),r?y.toDecimals(r.protocolFee).toString():w.toString()),n=m(s);return n.isNegative()?w:n}calculateLrnaInGivenOut(e,t,r){let s=A.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():w.toString()),n=m(s);return n.isNegative()?w:n}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=A.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():w.toString(),r?y.toDecimals(r.protocolFee).toString():w.toString()),n=m(s);return n.isNegative()?w:n}calculateOutGivenLrnaIn(e,t,r){let s=A.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():w.toString()),n=m(s);return n.isNegative()?w:n}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=A.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=A.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=A.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=A.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as cr}from"@polkadot/util-crypto";import{stringToU8a as ur}from"@polkadot/util";var ve=class extends L{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,n]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),o=r.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:u,tradable:h,cap:d,protocolShares:g}=l.unwrap(),b=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:h.bits.toNumber(),balance:b.toString(),cap:m(d.toString()),protocolShares:m(g.toString())}}),i=await Promise.all(o);return i.push({id:e,tradeable:s.bits.toNumber(),balance:n.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:i,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=e.assetOut,s=e.assetIn,n="omnipool",o="Short",i=B=>B===D?[D,fe]:[fe,B],[a,l,c,u]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(r),this.api.query.emaOracle.oracles(n,i(r),o),this.api.query.emaOracle.oracles(n,i(s),o)]),[h,d,g]=this.getAssetFee(e,a.toNumber(),l,c),[b,P,T]=s===fe?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,u),f=h+b,I=g+T;return{assetFee:y.fromPermill(d),protocolFee:y.fromPermill(P),min:y.fromPermill(f),max:y.fromPermill(I)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,n)=>{let o=e.tokens[n];if(s.isNone)return o;let i=s.unwrap();return this.updateTokenState(o,i)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:n,cap:o,protocolShares:i}=t;return{...e,hubReserves:m(r.toString()),shares:m(s.toString()),cap:m(o.toString()),protocolShares:m(i.toString()),tradeable:n.bits.toNumber()}}getAssetFee(e,t,r,s){let{assetOut:n,balanceOut:o}=e,{minFee:i,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,u=y.fromPermill(i.toNumber()),h=y.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[i.toNumber(),i.toNumber(),a.toNumber()];let[d]=s.unwrap(),{assetFee:g,timestamp:b}=r.unwrap(),P=Math.max(1,t-b.toNumber()),T=d.volume.bIn.toString(),f=d.volume.bOut.toString(),I=d.liquidity.b.toString();n===D&&(T=d.volume.aIn.toString(),f=d.volume.aOut.toString(),I=d.liquidity.a.toString());let B=y.fromPermill(g.toNumber()),S=A.recalculateAssetFee(T,f,I,"9",o.toString(),y.toDecimals(B).toString(),P.toString(),y.toDecimals(u).toString(),y.toDecimals(h).toString(),l.toString(),c.toString());return[i.toNumber(),Number(S)*1e6,a.toNumber()]}getProtocolFee(e,t,r,s){let{assetIn:n,balanceIn:o}=e,{minFee:i,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,u=y.fromPermill(i.toNumber()),h=y.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[i.toNumber(),i.toNumber(),a.toNumber()];let[d]=s.unwrap(),{protocolFee:g,timestamp:b}=r.unwrap(),P=Math.max(1,t-b.toNumber()),T=d.volume.bIn.toString(),f=d.volume.bOut.toString(),I=d.liquidity.b.toString();n===D&&(T=d.volume.aIn.toString(),f=d.volume.aOut.toString(),I=d.liquidity.a.toString());let B=y.fromPermill(g.toNumber()),S=A.recalculateProtocolFee(T,f,I,"9",o.toString(),y.toDecimals(B).toString(),P.toString(),y.toDecimals(u).toString(),y.toDecimals(h).toString(),l.toString(),c.toString());return[i.toNumber(),Number(S)*1e6,a.toNumber()]}getPoolId(){return cr(ur("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as mr,calculate_out_given_in as pr,calculate_pool_trade_fee as dr,get_spot_price as gr,calculate_liquidity_in as hr,calculate_shares as Pr,calculate_spot_price as br,calculate_spot_price_with_fee as yr,calculate_liquidity_out_asset_a as fr,calculate_liquidity_out_asset_b as Sr}from"@galacticcouncil/math-xyk";var $=class{static getSpotPrice(e,t,r){return gr(e,t,r)}static calculateInGivenOut(e,t,r){return mr(e,t,r)}static calculateOutGivenIn(e,t,r){return pr(e,t,r)}static calculatePoolTradeFee(e,t,r){return dr(e,t,r)}static calculateLiquidityIn(e,t,r){return hr(e,t,r)}static calculateSpotPrice(e,t){return br(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return yr(e,t,r,s)}static calculateShares(e,t,r){return Pr(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return fr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Sr(e,t,r,s)}};var Ae=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,n){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),i=m(n.balance),a=m(s.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:o,balanceOut:i,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=this.calculateTradeFee(s,r),o=y.toPct(r.exchangeFee),i=s.plus(n),a=[];(t.isLessThan(this.minTradingLimit)||s.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 i.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o,errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(s,r),o=y.toPct(r.exchangeFee),i=s.minus(n),a=[];(t.isLessThan(this.minTradingLimit)||s.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 i.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o,errors:a}}calculateInGivenOut(e,t){let r=$.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?w:s}calculateOutGivenIn(e,t){let r=$.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?w:s}spotPriceInGivenOut(e){let t=$.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=v(R,18-e.decimalsOut);return m(t).div(r)}spotPriceOutGivenIn(e){let t=$.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=v(R,18-e.decimalsIn);return m(t).div(r)}calculateTradeFee(e,t){let r=$.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(r)}};var Ne=class extends L{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let n=r.toString(),[o,i]=s.unwrap(),[a,l]=await Promise.all([this.getBalance(n,o.toString()),this.getBalance(n,i.toString())]);return{address:n,type:"Xyk",tokens:[{id:o.toString(),balance:a.toString()},{id:i.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as wr,calculate_out_given_in as Tr,calculate_amplification as xr,calculate_add_one_asset as Or,calculate_liquidity_out_one_asset as Br,calculate_pool_trade_fee as Ir,calculate_shares as vr,calculate_shares_for_amount as Ar,calculate_spot_price_with_fee as Nr,pool_account_name as Fr,recalculate_peg as Rr}from"@galacticcouncil/math-stableswap";var _=class{static getPoolAddress(e){return Fr(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,n){return xr(e,t,r,s,n)}static calculateInGivenOut(e,t,r,s,n,o,i){return wr(e,t,r,s,n,o,i)}static calculateAddOneAsset(e,t,r,s,n,o,i){return Or(e,t,r,s,n,o,i)}static calculateSharesForAmount(e,t,r,s,n,o,i){return Ar(e,t,r,s,n,o,i)}static calculateOutGivenIn(e,t,r,s,n,o,i){return Tr(e,t,r,s,n,o,i)}static calculateLiquidityOutOneAsset(e,t,r,s,n,o,i){return Br(e,t,r,s,n,o,i)}static calculateShares(e,t,r,s,n,o){return vr(e,t,r,s,n,o)}static calculateSpotPriceWithFee(e,t,r,s,n,o,i,a){return Nr(e,t,r,s,n,o,i,a)}static calculatePoolTradeFee(e,t,r){return Ir(e,t,r)}static recalculatePegs(e,t,r,s,n){let o=Rr(e,t,r,s,n);return JSON.parse(o)}};var Fe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,r,s,n,o,i,a,l,c,u){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n,this.amplification=o,this.id=i,this.fee=a,this.totalIssuance=l,this.pegs=c,this.pegsFee=u}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),i=m(n.balance),a=m(s.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:o,balanceOut:i,decimalsIn:s.decimals,decimalsOut:n.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:n.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,r),o=y.toPct(r.fee),i=[],a=A.isSellAllowed(e.tradeableIn),l=A.isBuyAllowed(e.tradeableOut);return(!a||!l)&&i.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&i.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:s,amountOut:t,feePct:o,errors:i}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,r),o=y.toPct(r.fee),i=[],a=A.isSellAllowed(e.tradeableIn),l=A.isBuyAllowed(e.tradeableOut);return(!a||!l)&&i.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&i.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:o,errors:i}}calculateIn(e,t,r){let s=_.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toDecimals(r.fee).toString():w.toString(),this.getPegs()),n=m(s);return n.isNegative()?w:n}calculateAddOneAsset(e,t,r){let s=_.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():w.toString(),this.getPegs()),n=m(s);return n.isNegative()?w:n}calculateSharesForAmount(e,t,r){let s=_.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():w.toString(),this.getPegs()),n=m(s);return n.isNegative()?w:n}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let s=v(R,e.decimalsIn-e.decimalsOut);return m(t).div(s)}let r=v(R,18-e.decimalsIn);return m(t).div(r)}calculateOut(e,t,r){let s=_.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toDecimals(r.fee).toString():w.toString(),this.getPegs()),n=m(s);return n.isNegative()?w:n}calculateWithdrawOneAsset(e,t,r){let s=_.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():w.toString(),this.getPegs()),n=m(s);return n.isNegative()?w:n}calculateShares(e,t,r){let s=_.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():w.toString(),this.getPegs()),n=m(s);return n.isNegative()?w:n}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let s=v(R,e.decimalsOut-e.decimalsIn);return m(t).div(s)}let r=v(R,18-e.decimalsOut);return m(t).div(r)}calculateTradeFee(e,t){let r=_.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return m(r)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{blake2AsHex as Er,encodeAddress as _r}from"@polkadot/util-crypto";var Dr=340282366920938463463374607431768211455n,Re=class extends L{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[n]},o])=>{let i=o.unwrap(),a=n.toString(),l=this.getPoolAddress(a),[c,u,h]=await Promise.all([this.getPoolDelta(a,i,r.toString()),this.getPoolTokens(l,a,i),this.getPoolPegs(a,i,r.toString())]);return this.stablePools.set(l,i),{address:l,id:a,type:"Stableswap",fee:y.fromPermill(i.fee.toNumber()),tokens:u,...c,...h,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toString(),s=this.stablePools.get(e.address);if(s){let[n,o]=await Promise.all([this.getPoolDelta(e.id,s,r),this.getPoolPegs(e.id,s,r)]);Object.assign(e,n,o)}})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:n,initialBlock:o,finalBlock:i}=t,a=_.calculateAmplification(s.toString(),n.toString(),o.toString(),i.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,n=s.map(async i=>{let[a,l]=await Promise.all([this.api.query.stableswap.assetTradability(t,i.toString()),this.getBalance(e,i.toString())]);return{id:i.toString(),tradeable:a.bits.toNumber(),balance:l.toString()}}),o=await Promise.all(n);return o.push({id:t,tradeable:15,balance:Dr.toString()}),o}getPoolDefaultPegs(e){let t=e.fee,r=_.defaultPegs(e.assets.length);return{pegsFee:y.fromPermill(t.toNumber()),pegs:r}}async getPoolPegs(e,t,r){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getPoolDefaultPegs(t);let n=s.unwrap(),o=await this.getLatestPegs(t,n,r),i=this.getRecentPegs(n),a=n.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[c,u]=_.recalculatePegs(JSON.stringify(i),JSON.stringify(o),r,a.replace(/%/g,""),l.replace(/%/g,"")),h=Number(c)*1e4;return{pegsFee:y.fromPermill(h),pegs:u}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(n=>n.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,n=Array.from(e.assets.entries()).map(([i,a])=>a.toString()),o=s.map(async(i,a)=>{if(i.isOracle){let[l,c,u]=i.asOracle,h=[u.toString(),n[a]].map(f=>Number(f)).sort((f,I)=>f-I),d=await this.api.query.emaOracle.oracles(l,h,c),[{price:g,updatedAt:b}]=d.unwrap(),P=g.n.toString(),T=g.d.toString();return u.toString()===h[0].toString()?[[P,T],b.toString()]:[[T,P],b.toString()]}else return[i.asValue.map(l=>l.toString()),r]});return Promise.all(o)}getPoolAddress(e){let t=Number(e),r=_.getPoolAddress(t);return _r(Er(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var ne=class extends C{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=kr(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new z(this.api),this.aaveClient=new xe(this.api),this.xykClient=new Ne(this.api),this.omniClient=new ve(this.api),this.lbpClient=new Be(this.api),this.stableClient=new Re(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(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(s=>s.isSupported()).map(s=>s.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(r=>e.some(s=>s===r.getPoolType())).map(r=>r.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new we(t.type)}}};var ie=class extends ne{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Cr(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let n=await super.getPoolFees(e,t);return this.feeCache.set(r,n),n}}async destroy(){this.log(`Destroying pool cache!
|
|
2
|
-
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var oe=class{static get(e){switch(e.type){case"Aave":return Te.fromPool(e);case"Xyk":return Ae.fromPool(e);case"Omnipool":return Ie.fromPool(e);case"Lbp":return Oe.fromPool(e);case"Stableswap":return Fe.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Ee=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Lr=5,ae=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],n=new Ee,o=[];for(o.push([t,""]),n.enqueue(o);n.size()>0;){let i=n.dequeue();if(i==null||i.length>Lr)return s;let a=i[i.length-1];(r===null||a[0]===r)&&s.push(i),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,i)){let u=[...i];u.push(c),n.enqueue(u)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,n,o]of t){let i=parseInt(n),a=parseInt(o);r.get(i)?.push([a,s])}return r}};function Xe(p){let e={};for(let t of p){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let n=0;n<r;n++){if(s==n)continue;let o=[t.address,t.tokens[s].id,t.tokens[n].id];e[t.tokens[s].id].push(o)}}}return e}var le=class{getProposals(e,t,r){let s=Xe(r),n=Object.keys(s),o=n.map(c=>s[c]).flat(),i=new ae,a=i.buildAndPopulateGraph(n,o),l=i.findPaths(a,parseInt(e),t?parseInt(t):null);return this.parsePaths(l)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let n=0;n<r.length;n++){let o=r[n],i=r[n+1];if(i==null)break;s.push(this.toEdge(o,i))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ce=class{routeSuggester;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new le,this.routerOptions=Object.freeze({includeOnly:t.includeOnly??[]})}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),o=this.getPaths(e,null,s,t).map(i=>i[i.length-1].assetOut);return this.toAssets([...new Set(o)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(i=>this.validPath(i,r)).map(i=>this.toHops(i,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let n=this.getPoolMap(r);return{assets:s,poolsMap:n}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,oe.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,n])=>{let o=t.get(r);return{poolAddress:r,poolId:o?.id,pool:o?.type,assetIn:s,assetOut:n}})}toAssets(e,t){return e.map(r=>t.get(r))}};var Mr=m("100");function Cl(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ue(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function dt(p,e){return R.minus(e.div(p)).multipliedBy(100).decimalPlaces(2)}function gt(p,e){return e.div(p).minus(R).multipliedBy(100).decimalPlaces(2)}function K(p,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),p.div(Mr).multipliedBy(e).decimalPlaces(0,1)}var Ye=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Ye||{}),$e=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))($e||{}),ht=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(ht||{});var me=class extends ce{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let n=r[r.length-1].amountOut,o=s[s.length-1].amountOut;return n.isGreaterThan(o)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,o)=>n+o),s=e.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,o)=>n+o);return[r,s]}}getPoolFeeRange(e){let t=e.min?y.toPct(e.min):void 0,r=e.max?y.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:o}=await super.validateTokenPair(e,t,n),i=super.getPaths(e,t,o,n);if(i.length===0)throw new j(e,t);let a;if(s)a=await this.toSellSwaps(r,s,o);else{let S=i.map(async N=>await this.toSellSwaps(r,N,o)),F=await Promise.all(S);a=this.findBestSellRoute(F)}let l=a[0],c=a[a.length-1],u=this.isDirectTrade(a),h=a.map(S=>S.spotPrice.shiftedBy(-1*S.assetOutDecimals)).reduce((S,F)=>S.multipliedBy(F)),d=v(h,c.assetOutDecimals),g=u?c.calculatedOut:this.calculateDelta0Y(l.amountIn,a,o),b=c.amountOut,P=u?c.tradeFeePct:dt(g,b).toNumber(),T=g.minus(b),f=this.getRouteFeeRange(a),I=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(d),B=ue(g,I);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:T,tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:x(l.amountIn,l.assetInDecimals),amountOut:x(c.amountOut,c.assetOutDecimals),spotPrice:x(d,c.assetOutDecimals),tradeFee:x(T,c.assetOutDecimals),tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B.toNumber(),swaps:a.map(S=>S.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let n=0;n<t.length;n++){let o=t[n],i=r.get(o.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(o.assetIn,o.assetOut),l;n>0?l=s[n-1]:l=e;let c=i.calculateOutGivenIn(a,l);s.push(c)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let n=0;n<t.length;n++){let o=t[n],i=r.get(o.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(o.assetIn,o.assetOut),l;n>0?l=s[n-1].amountOut:l=v(m(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,i),{amountOut:u,calculatedOut:h,feePct:d,errors:g}=i.validateAndSell(a,l,c),b=this.getPoolFeeRange(c),P=i.spotPriceOutGivenIn(a),T=l.shiftedBy(-1*a.decimalsIn).multipliedBy(P),f=ue(h,T);s.push({...o,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,amountOut:u,calculatedOut:h,spotPrice:P,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===o.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===o.assetIn},toHuman(){return{...o,amountIn:x(l,a.decimalsIn),amountOut:x(u,a.decimalsOut),calculatedOut:x(h,a.decimalsOut),spotPrice:x(P,a.decimalsOut),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:g}}})}return s}async getMostLiquidRoute(e,t){let r=await super.getPools(),{poolsMap:s}=await super.validateTokenPair(e,t,r),n=super.getPaths(e,t,s,r);if(n.length===0)throw new j(e,t);let l=r.filter(d=>d.tokens.some(g=>g.id===e&&g.id!==d.id)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(g=>g.id===e)).map(d=>d.map(g=>m(g.balance).shiftedBy(-1*g.decimals)).reduce((g,b)=>g.plus(b))).sort((d,g)=>g.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=n.map(async d=>await this.toSellSwaps(l,d,s)),u=await Promise.all(c);return this.findBestSellRoute(u).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r);if(super.getPaths(e,t,s,r).length===0)return Promise.resolve(void 0);let o=await this.getMostLiquidRoute(e,t),i=await this.toSellSwaps("1",o,s),a=i.map(u=>u.spotPrice.shiftedBy(-1*u.assetOutDecimals)).reduce((u,h)=>u.multipliedBy(h)),l=i[i.length-1].assetOutDecimals;return{amount:v(a,l),decimals:l}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let n=r[0].amountIn,o=s[0].amountIn;return n.isGreaterThan(o)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:o}=await super.validateTokenPair(e,t,n),i=super.getPaths(e,t,o,n);if(i.length===0)throw new j(e,t);let a;if(s)a=await this.toBuySwaps(r,s,o);else{let S=i.map(async N=>await this.toBuySwaps(r,N,o)),F=await Promise.all(S);a=this.findBestBuyRoute(F)}let l=a[a.length-1],c=a[0],u=this.isDirectTrade(a),h=a.map(S=>S.spotPrice.shiftedBy(-1*S.assetInDecimals)).reduce((S,F)=>S.multipliedBy(F)),d=v(h,c.assetInDecimals),g=u?c.calculatedIn:this.calculateDelta0X(l.amountOut,a,o),b=c.amountIn,P=u?c.tradeFeePct:gt(g,b).toNumber(),T=b.minus(g),f=this.getRouteFeeRange(a),I=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(d),B;return g.isZero()?B=-100:B=ue(I,g).toNumber(),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:T,tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B,swaps:a,toHuman(){return{type:"Buy",amountOut:x(l.amountOut,l.assetOutDecimals),amountIn:x(c.amountIn,c.assetInDecimals),spotPrice:x(d,c.assetInDecimals),tradeFee:x(T,c.assetInDecimals),tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B,swaps:a.map(S=>S.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let n=t.length-1;n>=0;n--){let o=t[n],i=r.get(o.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(o.assetIn,o.assetOut),l;n==t.length-1?l=e:l=s[0];let c=i.calculateInGivenOut(a,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let n=t.length-1;n>=0;n--){let o=t[n],i=r.get(o.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(o.assetIn,o.assetOut),l;n==t.length-1?l=v(m(e),a.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(a,i),{amountIn:u,calculatedIn:h,feePct:d,errors:g}=i.validateAndBuy(a,l,c),b=this.getPoolFeeRange(c),P=i.spotPriceInGivenOut(a),T=l.shiftedBy(-1*a.decimalsOut).multipliedBy(P),f;h.isZero()?f=-100:f=ue(T,h).toNumber(),s.unshift({...o,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,amountOut:l,calculatedIn:h,spotPrice:P,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f,errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===o.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===o.assetIn},toHuman(){return{...o,amountIn:x(u,a.decimalsIn),amountOut:x(l,a.decimalsOut),calculatedIn:x(h,a.decimalsIn),spotPrice:x(P,a.decimalsIn),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f,errors:g}}})}return s}};var Pt=6e3,bt=m(1e15),pe=6,Ve=-5,ze=6*60*60*1e3;var yt=6;var G=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:n})=>s==="Stableswap"?{pool:{Stableswap:n},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var de=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??Pt,minBudgetInNative:t.minBudgetInNative??bt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,n){let[o,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:l,priceImpactPct:c}=i,u=l[0],h=l[l.length-1],{assetInDecimals:d}=u,{assetOutDecimals:g}=h,b=Math.abs(c),P=this.getMinimumTradeCount(a,o),T=this.getOptimalTradeCount(b),f=n?Math.round(s/n):T,I=Math.ceil(s/P),B=Math.round(s/T),S=Math.round(s/f),F=a.dividedBy(f).decimalPlaces(0,1),N=await this.router.getBestSell(e,t,x(F,d)),q=a.isLessThan(o),he=[];q&&he.push("OrderTooSmall");let Pe=N.amountOut.multipliedBy(f),ke=this.toBlockPeriod(S),Ce=N.tradeFee.multipliedBy(f),Le=G.build(l),Ke={assetIn:e,assetOut:t,errors:he,frequencyMin:I,frequencyOpt:B,frequency:S,tradeCount:f,tradeFee:Ce,tradeImpactPct:N.priceImpactPct,tradePeriod:ke,tradeRoute:Le,type:"Dca"};return{...Ke,amountIn:a,amountOut:Pe,tradeAmountIn:N.amountIn,tradeAmountOut:N.amountOut,toHuman(){return{...Ke,amountIn:x(a,d),amountOut:x(Pe,g),tradeAmountIn:x(N.amountIn,d),tradeAmountOut:x(N.amountOut,g)}}}}async getMinimumOrderBudget(e){if(D===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(D,e);if(t)return this.minOrderBudget.times(t.amount).div(m(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:i,priceImpactPct:a}=n,l=i[0],c=i[i.length-1],{assetInDecimals:u}=l,{assetOutDecimals:h}=c,d=Math.abs(a),g=this.getTwapTradeCount(d),b=o.dividedBy(g).decimalPlaces(0,1),P=await this.router.getBestSell(l.assetIn,c.assetOut,x(b,u)),T=g===1,f=o.isLessThan(s),I=P.priceImpactPct<Ve,B=[];f||T?B.push("OrderTooSmall"):I&&B.push("OrderImpactTooBig");let S=P.amountOut.multipliedBy(g),F=P.tradeFee.multipliedBy(g),N=G.build(i),q={assetIn:e,assetOut:t,errors:B,tradeCount:g,tradeImpactPct:P.priceImpactPct,tradePeriod:pe,tradeRoute:N,type:"TwapSell"};return{...q,amountIn:o,amountOut:S,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:F,toHuman(){return{...q,amountIn:x(o,u),amountOut:x(S,h),tradeAmountIn:x(P.amountIn,u),tradeAmountOut:x(P.amountOut,h),tradeFee:x(F,h)}}}}async getTwapBuyOrder(e,t,r){let[s,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:o,swaps:i,priceImpactPct:a}=n,l=i[0],c=i[i.length-1],{assetInDecimals:u}=l,{assetOutDecimals:h}=c,d=Math.abs(a),g=this.getTwapTradeCount(d),b=o.dividedBy(g).decimalPlaces(0,1),P=await this.router.getBestBuy(l.assetIn,c.assetOut,x(b,h)),T=P.amountIn.multipliedBy(g),f=g===1,I=T.isLessThan(s),B=P.priceImpactPct<Ve,S=[];I||f?S.push("OrderTooSmall"):B&&S.push("OrderImpactTooBig");let F=P.tradeFee.multipliedBy(g),N=G.build(i),q={assetIn:e,assetOut:t,errors:S,tradeCount:g,tradeImpactPct:P.priceImpactPct,tradePeriod:pe,tradeRoute:N,type:"TwapBuy"};return{...q,amountIn:T,amountOut:o,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:F,toHuman(){return{...q,amountIn:x(T,u),amountOut:x(o,h),tradeAmountIn:x(P.amountIn,u),tradeAmountOut:x(P.amountOut,h),tradeFee:x(F,u)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>ze){let s=ze/(this.blockTime*pe);return Math.round(s)}return t}getTwapExecutionTime(e){return e*pe*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,yt)}};import{encodeFunctionData as Ur}from"viem";var Q=class extends C{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new k,this.balanceClient=new U(e),this.aaveUtils=new V(this.evmClient)}wrapTx(e,t){return{hex:t.toHex(),name:e,get:()=>t,dryRun:r=>this.dryRun(r,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),ye)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var _e=class extends Q{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:n,assetOut:o}=s,i;return s.isWithdraw()?i=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,o)).amount:i=await this.balanceClient.getBalance(this.beneficiary,n),e.isGreaterThanOrEqualTo(i.minus(5))&&!s.isWithdraw()?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],n=r[r.length-1],o=K(e,this.slippagePct),i=s.assetIn,a=n.assetOut,l=e.plus(o),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(a,i,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(i,a,t.toFixed(),l.toFixed(),G.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],n=r[r.length-1],o=K(t,this.slippagePct),i=s.assetIn,a=n.assetOut,l=t.minus(o),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(i,a,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(i,a,e.toFixed(),l.toFixed(),G.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],n=K(e,this.slippagePct),o=r.assetIn,i=s.assetOut,a=e.minus(n),l=this.api.tx.router.sellAll(o,i,a.toFixed(),G.build(t));return r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}async buildWithdrawTx(e){let{swaps:t}=this.trade,r=e||this.trade.amountIn,n=t[0].assetOut,o=await this.evmClient.getGasPrice(),i=o*10n/100n,a=Y.fromAny(this.beneficiary),l=e?Je:BigInt(r.toFixed()),c=M.fromAssetId(n),u=Ur({abi:J,functionName:"withdraw",args:[c,l,a]}),h=this.api.tx.evm.call(a,be,u,0n,ye,o+i,o+i,null,[]);return{hex:h.toHex(),name:"Withdraw",get:()=>h,dryRun:d=>this.dryRun(d,h)}}};var De=class extends Q{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradePeriod:n,tradeRoute:o}=this.order,i=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:o}}},null);return this.wrapTx("DcaSchedule",i)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:o,tradeRoute:i}=this.order,a=K(n,this.slippagePct),l=n.minus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:o,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:i}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:o,tradeRoute:i}=this.order,a=K(s,this.slippagePct),l=s.plus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:o,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:n.toFixed(),maxAmountIn:l.toFixed(),route:i}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var ge=class{api;evmClient;constructor(e,t){this.api=e,this.evmClient=t??new k}trade(e){return new _e(this.api,this.evmClient).setTrade(e)}order(e){return new De(this.api,this.evmClient).setOrder(e)}};function eu(p,e){let t=new se(p),r=e??new k,s=new ie(p),n=new V(r),o=new me(s),i=new de(o,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:n,router:o,scheduler:i},client:{asset:new z(p),balance:new U(p),evm:r},ctx:{pool:s},tx:new ge(p,r),destroy:()=>{s.destroy()}}}export{Dr as AMOUNT_MAX,ee as AaveClient,Te as AavePool,xe as AavePoolClient,V as AaveUtils,z as AssetClient,lt as AssetNotFound,ls as BASILISK_PARACHAIN_ID,U as BalanceClient,O as BigNumber,ie as CachingPoolService,se as ChainParams,Ft as DECIMAL_PLACES,qe as DENOMINATOR,M as ERC20,k as EvmClient,We as FarmClient,Y as H160,fe as HUB_ASSET_ID,cs as HYDRADX_PARACHAIN_ID,W as HYDRADX_SS58_PREFIX,ys as INFINITY,H as LbpMath,Oe as LbpPool,Be as LbpPoolClient,R as ONE,A as OmniMath,Ie as OmniPool,ve as OmniPoolClient,C as PolkadotApiClient,at as PoolConfigNotFound,Z as PoolError,oe as PoolFactory,we as PoolNotFound,ne as PoolService,E as PoolType,mt as ProviderConfigNotFound,te as RUNTIME_DECIMALS,j as RouteNotFound,ce as Router,tt as SYSTEM_ASSET_DECIMALS,D as SYSTEM_ASSET_ID,_ as StableMath,Fe as StableSwap,Re as StableSwapClient,ct as StorageConfigNotFound,ut as SubscriptionNotSupported,re as TRADEABLE_DEFAULT,ht as TradeOrderError,$e as TradeOrderType,G as TradeRouteBuilder,me as TradeRouter,de as TradeScheduler,Ye as TradeType,ge as TxBuilderFactory,$ as XykMath,Ae as XykPool,Ne as XykPoolClient,w as ZERO,xn as bnFormatter,m as bnum,gt as calculateBuyFee,Cl as calculateDiffToAvg,ue as calculateDiffToRef,dt as calculateSellFee,eu as createSdkContext,Qe as evmMainnet,pt as findNestedKey,Tn as findNestedObj,K as getFraction,vt as isEvmAccount,At as isEvmAddress,Nt as isSs58Address,v as scale,fs as toBn,x as toDecimals};
|
|
1
|
+
var J=[{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 Me=[{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 be="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ue="0x112b087b60C1a166130d59266363C45F8aa99db0",Ge="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ye=1000000n;var Je=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");import{defineChain as ft}from"viem";var je=["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"],Ze=["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=ft({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:je,webSocket:Ze},default:{http:je,webSocket:Ze}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as et,createWalletClient as St,custom as wt,http as Tt,webSocket as xt}from"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}async getGasPrice(){return this.getProvider().getGasPrice()}getProvider(){return et({chain:this.chain,transport:Tt()})}getWsProvider(){return et({chain:this.chain,transport:xt()})}getSigner(e){return St({account:e,chain:this.chain,transport:wt(window.ethereum)})}};var ee=class{evmClient;constructor(e){this.evmClient=e??new k}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:Me,address:Ue,args:[Ge],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:Me,address:Ue,args:[Ge,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:J,address:be,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as Se,encodeAddress as rt}from"@polkadot/util-crypto";import{hexToU8a as Ot,isHex as Bt,u8aToHex as It}from"@polkadot/util";import{Buffer as X}from"buffer";var ls=2090,qe=1e3,fe="1",cs=2034,W=63,te=18,D="0",tt=12,re=15;var He="ETH\0";function vt(p){if(!p)return!1;try{let e=Se(p,!0),t=X.from(He);return X.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function At(p){return!!/^0x[a-fA-F0-9]{40}$/.test(p)}function Ft(p){try{let e=Bt(p)?Ot(p):Se(p);return rt(e),!0}catch{return!1}}var Y=class p{static toAccount=e=>{let t=X.from(e.slice(2),"hex"),r=X.from(He);return rt(new Uint8Array(X.concat([r,t,X.alloc(8)])),63)};static fromAccount=e=>{let t=Se(e),r=X.from(He),s=t.slice(r.length,-8);return"0x"+X.from(s).toString("hex")};static fromSS58=e=>{let r=Se(e).slice(0,20);return It(r)};static fromAny=e=>{if(At(e))return e;if(vt(e))return p.fromAccount(e);if(Ft(e))return p.fromSS58(e);throw new Error("Unknown address type")}};var M=class{static fromAssetId(e){let t=Number(e),r=Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),r=Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as O}from"bignumber.js";var Nt=12;O.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Nt});var w=m(0),R=m(1),ys=m("Infinity");function v(p,e){let t=new O(e.toString()),r=new O(10).pow(t);return p.times(r)}function m(p){return new O(p.toString())}function fs(p,e){let t=m(p);return v(t,e)}function x(p,e){return p.shiftedBy(-1*e).toString()}var Rt=m("1e27"),Et=m("1.01"),V=class{client;constructor(e){let t=e??new k;this.client=new ee(t)}async getSummary(e){let t=Y.fromAny(e),[r,s,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t)]),[o]=r,[i,a]=s,[l,c,u,h,d,g]=n,b=m(g).dividedBy(1e18).decimalPlaces(6,O.ROUND_DOWN),P=m(l),T=m(c),f=[];for(let I of i){let B=I.underlyingAsset.toLowerCase(),S=o.find(({underlyingAsset:Le})=>Le.toLowerCase()===B);if(!S)throw new Error("Missing pool reserve for "+B);let N=m(I.scaledATokenBalance),F=m(S.liquidityIndex),q=m(S.priceInMarketReferenceCurrency),he=N.multipliedBy(F).dividedBy(Rt).decimalPlaces(0,O.ROUND_DOWN),Pe=m(a===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold).div(1e4),ke=S.usageAsCollateralEnabled&&I.usageAsCollateralEnabledOnUser&&m(I.scaledATokenBalance).gt(0),Ce=M.toAssetId(B);f.push({aTokenBalance:he,decimals:Number(S.decimals),isCollateral:ke,priceInRef:q,reserveId:Ce,reserveAsset:B,reserveLiquidationThreshold:Pe})}return{healthFactor:b.toNumber(),totalCollateral:P,totalDebt:T,reserves:f}}async hasBorrowPositions(e){let t=Y.fromAny(e),r=await this.client.getUserAccountData(t),[s,n]=r;return n>0n}async getHealthFactor(e){let t=Y.fromAny(e),r=await this.client.getUserAccountData(t),[s,n,o,i,a,l]=r;return m(l).dividedBy(1e18).decimalPlaces(6,O.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:n,reserves:o}=await this.getSummary(e),i=M.fromAssetId(t),a=o.find(T=>T.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:c,priceInRef:u,reserveLiquidationThreshold:h}=a,d=v(m(r),l).decimalPlaces(0,1),g=c?d.multipliedBy(u).dividedBy(m(10).pow(l)).decimalPlaces(0,O.ROUND_DOWN):w,b=s.minus(g);return b.lte(0)?0:b.multipliedBy(h).dividedBy(n).decimalPlaces(6,O.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:n,reserves:o}=await this.getSummary(e),i=M.fromAssetId(t),a=o.find(P=>P.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:u}=a,d=v(m(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(m(10).pow(l)).decimalPlaces(0,O.ROUND_DOWN),g=s.plus(d);return g.lte(0)?0:g.multipliedBy(u).dividedBy(n).decimalPlaces(6,O.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalCollateral:r,totalDebt:s,reserves:n}=await this.getSummary(e),o=M.fromAssetId(t),i=n.find(a=>a.reserveAsset===o);if(!i)throw new Error("Missing reserve ctx for "+o);return this.calculateWithdrawMax(i,r,s)}async getMaxWithdrawAll(e){let{totalCollateral:t,totalDebt:r,reserves:s}=await this.getSummary(e),n={};for(let o of s){let i=this.calculateWithdrawMax(o,t,r);o.reserveId&&(n[o.reserveId]=i)}return n}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,decimals:n,priceInRef:o,reserveLiquidationThreshold:i}=e,a=Et.multipliedBy(r).div(i).decimalPlaces(0,O.ROUND_UP),l=t.minus(a).decimalPlaces(0,1);if(l.lte(0))return{amount:w,decimals:n};let c=l.multipliedBy(m(10).pow(n)).dividedBy(o).decimalPlaces(0,O.ROUND_DOWN);return{amount:O.minimum(s,c),decimals:n}}};function st(p){switch(p){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var C=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");st(r)&&console.log(e,...t)}};var z=class extends C{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:n}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:n.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==D){let u=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:u.toString()}}let{name:n,assetType:o,isSufficient:i,existentialDeposit:a}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:n.toHuman(),symbol:l,decimals:c,icon:l,type:o.toHuman(),isSufficient:i?i.toHuman():!0,location:s?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,r,s){let[n,o]=s,{assetType:i,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(n.toString(),t,r),h=o.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(h)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:u,icon:c,type:i.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:n.toString(),maturity:h}}getShares(e,t,r,s){let{assets:n}=s,{name:o,symbol:i,assetType:a,isSufficient:l,existentialDeposit:c}=t,h=n.map(b=>b.toString()).map(b=>{let{symbol:P}=this.getToken(b,t,r);return[b,P]}),d=Object.fromEntries(h),g=Object.values(d);return{id:e,name:g.join(", "),symbol:i?.isSome?i.toHuman():o.toHuman(),decimals:18,icon:g.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,r,s){let n=this.getToken(e,t,new Map,s),o=r?.find(i=>i.internalId===n.id);return o?{...n,decimals:o.decimals,name:o.name,symbol:o.symbol,icon:o.symbol,isWhiteListed:o.isWhiteListed}:n}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:n,symbol:o}=s.unwrap();return[r.toString(),{decimals:Number(n.toString()),symbol:o.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,n,o,i]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(r),l=this.normalizeMetadata(a,i),c=a.map(([{args:[u]},h])=>{let d=h.unwrap(),g=s.get(u.toString()),{assetType:b}=d;switch(b.toString()){case"Bond":let P=o.get(u.toString());return this.getBond(u.toString(),d,l,P);case"StableSwap":let T=n.get(u.toString());return this.getShares(u.toString(),d,l,T);case"External":return this.getExternal(u.toString(),d,t,g);default:return this.getToken(u.toString(),d,l,g)}});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 U=class extends C{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===D?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:r,reserved:s,frozen:n}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:r,feeFrozen:s,frozen:n})}async getErc20Balance(e,t){let{free:r,reserved:s,frozen:n}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:r,feeFrozen:0n,frozen:n})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(D,this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),n=r?r.map(o=>[e,o]):s.map(({args:[o,i]})=>[o.toString(),i.toString()]);return this.api.query.tokens.accounts.multi(n,o=>{let i=[];o.forEach((a,l)=>{let c=this.calculateFreeBalance(a),u=n[l][1];i.push([u,c])}),t(i)})}async subscribeErc20Balance(e,t,r){let n=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),o=async()=>{let i=await Promise.all(n.map(async a=>[a,await this.getErc20Balance(e,a)]));t(i)};return this.api.rpc.chain.subscribeNewHeads(async()=>{o()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:r,feeFrozen:s,frozen:n}=e,o=new O(t),i=new O(r||n),a=new O(s||0n),l=i.gt(a)?i:a;return o.minus(l)}};var se=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),m(this._minOrderBudget)}};import{fixed_from_rational as nt}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as _t}from"@polkadot/types";import{u8aConcat as it}from"@polkadot/util";import{isAddress as ot}from"@polkadot/util-crypto";var We=class extends C{balanceClient;constructor(e){super(e),this.balanceClient=new U(e)}secondsInYear=new O(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,n])=>{let[,o]=s.args,i=n.unwrap().toString(),a=o.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,i)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,n])=>{let[,o]=s.args,i=n.unwrap().toString(),a=o.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,i)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new O(1).shiftedBy(18).toString();let n=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(n.isNone)return;let[o]=n.unwrap(),i=o.price.n.toString(),a=o.price.d.toString(),l;return Number(t)<Number(r)?l=nt(i,a):l=nt(a,i),l}getGlobalRewardPerPeriod(e,t,r,s){let o=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return o.gte(r)?r:o}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return it(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",n=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new _t(e,this.padEndU8a(it(s,n,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!ot(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&ot(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:i,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let u=new O(a.totalSharesZ.toString()),h=a.plannedYieldingPeriods.toString(),d=new O(a.yieldPerPeriod.toString()),g=new O(a.maxRewardPerPeriod.toString()),b=a.blocksPerPeriod.toString(),P=new O(i.multiplier.toString()).shiftedBy(-18),T=this.secondsInYear.div(new O(r).times(b)),f;if(u.isZero())f=d.times(P).times(T);else{let F=this.getGlobalRewardPerPeriod(u,d,g,l);f=this.getPoolYieldPerPeriod(F,P,u,l).times(T)}let I=new O(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),B=g.times(h),S=c?I.plus(c):B;return I.div(S).gte(.999)?w:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((i,a)=>i.plus(a),w).toString():void 0}};var we=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},at=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},j=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},lt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},ct=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},ut=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},mt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{LRUCache as Cr}from"@thi.ng/cache";import{memoize1 as kr}from"@thi.ng/memoize";var E=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n))(E||{}),Z=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n))(Z||{});var Te=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,n){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),i=m(n.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:o,balanceOut:i,assetInED:w,assetOutED:w}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=[];return t.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:n}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=[];return s.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:n}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return v(R,e.decimalsOut)}spotPriceOutGivenIn(e){return v(R,e.decimalsIn)}calculateTradeFee(e,t){return w}};import{encodeAddress as Ct}from"@polkadot/util-crypto";import{stringToU8a as Lt}from"@polkadot/util";import{decodeEventLog as Mt}from"viem";function pt(p,e){let t=[];return JSON.stringify(p,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Tn(p,e,t){let r;return JSON.stringify(p,(s,n)=>(n&&n[e]===t&&(r=n),n)),r}var xn=(p,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as Dt}from"@thi.ng/memoize";import{TLRUCache as kt}from"@thi.ng/cache";var L=class extends U{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new kt(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=Dt(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 r=[];try{let n=this.subscribePoolChange(t);r.push(n)}catch{}if(t.type==="Aave")return r;let s=this.subscribeTokensPoolBalance(t);if(r.push(s),this.hasSystemAsset(t)){let n=this.subscribeSystemPoolBalance(t);r.push(n)}if(this.hasErc20Asset(t)){let n=this.subscribeErc20PoolBalance(t);r.push(n)}return this.subscribeLog(t),r}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,n])=>{let o=e.tokens.findIndex(i=>i.id==s);o>=0&&t(e,s)&&(e.tokens[o].balance=n.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(n=>n.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};var Ut=["Supply","Withdraw","Repay","Borrow"],xe=class extends L{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:n})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:n.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let r=e+"/"+t;return Ct(Lt(r.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,r]=e.tokens,s=this.getReserveH160Id(t);return this.api.query.system.events(n=>{n.forEach(o=>{let{event:i}=o,a=`${i.section}:${i.method}`;if(a==="router:Executed"){let{assetIn:l,assetOut:c}=i.data.toHuman(),u=l.replace(/,/g,""),h=c.replace(/,/g,"");(u===r.id||h===r.id)&&(this.log(`Sync AAVE [router:Executed] :: ${u}:${h}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=i.data.toHuman();try{let{eventName:c,args:u}=Mt({abi:J,topics:l.topics,data:l.data});Ut.includes(c)&&u.reserve.toLowerCase()===s.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:n}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(o=>{let i=o.id===t.id?s.toString():n.toString();return{...o,balance:i}})}getReserveH160Id(e){return e.type==="Erc20"?pt(e.location,"accountKey20").accountKey20.key:M.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as Gt,calculate_out_given_in as qt,calculate_linear_weights as Ht,calculate_pool_trade_fee as Wt,get_spot_price as Xt}from"@galacticcouncil/math-lbp";var H=class{static getSpotPrice(e,t,r,s,n){return Xt(e,t,r,s,n)}static calculateInGivenOut(e,t,r,s,n){return Gt(e,t,r,s,n)}static calculateOutGivenIn(e,t,r,s,n){return qt(e,t,r,s,n)}static calculateLinearWeights(e,t,r,s,n){return Ht(e,t,r,s,n)}static calculatePoolTradeFee(e,t,r){return Wt(e,t,r)}};var y=class{static toPct(e){return e[0]/e[1]*100}static toDecimals(e){return e[0]/e[1]}static fromPermill(e){return[e/1e3,1e3]}};var Oe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,n,o,i){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n,this.fee=o,this.repayFeeApply=i}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),i=m(n.balance);return{assetIn:e,assetOut:t,balanceIn:o,balanceOut:i,decimalsIn:s.decimals,decimalsOut:n.decimals,weightIn:s.weight,weightOut:n.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let o=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(o)&&n.push("MaxOutRatioExceeded"),s===e.assetOut){let i=this.calculateTradeFee(t,r),a=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(i),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 i=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(a)&&n.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:i,amountOut:t,feePct:0,errors:n}}}validateAndSell(e,t,r){let s=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let o=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(o)&&n.push("MaxInRatioExceeded"),s===e.assetIn){let i=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(a)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:i,feePct:0,errors:n}}else{let i=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(i,r),l=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=i.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:c,feePct:l,errors:n}}}calculateInGivenOut(e,t){let r=H.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?w:s}calculateOutGivenIn(e,t){let r=H.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?w:s}spotPriceInGivenOut(e){let t=H.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),v(R,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=H.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),v(R,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let r=H.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(r)}};var Be=class extends L{MAX_FINAL_WEIGHT=v(m(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([n,o])=>this.isActivePool(o.unwrap(),r)).map(async([{args:[n]},o])=>{let i=o.unwrap(),a=n.toString(),l=await this.getPoolDelta(a,i,r.toString());return this.poolsData.set(n.toString(),i),{address:a,type:"Lbp",fee:i.fee.toJSON(),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){let r=this.pools.find(s=>s.address===t);return{repayFee:this.getRepayFee(),exchangeFee:r.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:r}=t.unwrap(),s=this.poolsData.get(e.address);if(this.isActivePool(s,r)){let o=await this.getPoolDelta(e.address,s,r.toString());Object.assign(e,o)}else{let o=this.pools.findIndex(i=>i.address==e.address);this.pools.splice(o,1)}})}async getPoolDelta(e,t,r){let{start:s,end:n,assets:o,initialWeight:i,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=H.calculateLinearWeights(s.toString(),n.toString(),i.toString(),a.toString(),r),[h,d]=o,g=h.toString(),b=m(u),P=d.toString(),T=this.MAX_FINAL_WEIGHT.minus(m(b)),[f,I,B]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,P)]);return{repayFeeApply:f,tokens:[{id:g,weight:b,balance:I.toString()},{id:P,weight:T,balance:B.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.toNumber()>=r&&t.toNumber()<s}async isRepayFeeApplied(e,t,r){let s=m(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),r=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as Yt,calculate_lrna_in_given_out as $t,calculate_out_given_in as Vt,calculate_out_given_lrna_in as zt,calculate_pool_trade_fee as Kt,calculate_spot_price as Jt,calculate_lrna_spot_price as jt,calculate_shares as Zt,calculate_liquidity_out as Qt,calculate_liquidity_lrna_out as er,calculate_liquidity_hub_in as tr,is_sell_allowed as rr,is_buy_allowed as sr,is_add_liquidity_allowed as nr,is_remove_liquidity_allowed as ir,recalculate_asset_fee as or,recalculate_protocol_fee as ar,verify_asset_cap as lr}from"@galacticcouncil/math-omnipool";var A=class{static calculateSpotPrice(e,t,r,s){return Jt(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return jt(e,t)}static calculateInGivenOut(e,t,r,s,n,o,i,a,l){return Yt(e,t,r,s,n,o,i,a,l)}static calculateLrnaInGivenOut(e,t,r,s,n){return $t(e,t,r,s,n)}static calculateOutGivenIn(e,t,r,s,n,o,i,a,l){return Vt(e,t,r,s,n,o,i,a,l)}static calculateOutGivenLrnaIn(e,t,r,s,n){return zt(e,t,r,s,n)}static calculatePoolTradeFee(e,t,r){return Kt(e,t,r)}static calculateShares(e,t,r,s){return Zt(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,n,o,i,a){return Qt(e,t,r,s,n,o,i,a)}static calculateLiquidityLRNAOut(e,t,r,s,n,o,i,a){return er(e,t,r,s,n,o,i,a)}static calculateCapDifference(e,t,r,s){let n=O(t),o=O(e),i=O(s),l=O(r).shiftedBy(-18);if(n.div(i).lt(l)){let u=l.times(i).minus(n).times(o),h=n.times(O(1).minus(l));return u.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return tr(e,t,r,s)}static isSellAllowed(e){return rr(e)}static isBuyAllowed(e){return sr(e)}static isAddLiquidityAllowed(e){return nr(e)}static isRemoveLiquidityAllowed(e){return ir(e)}static recalculateAssetFee(e,t,r,s,n,o,i,a,l,c,u){return or(e,t,r,s,n,o,i,a,l,c,u)}static recalculateProtocolFee(e,t,r,s,n,o,i,a,l,c,u){return ar(e,t,r,s,n,o,i,a,l,c,u)}static verifyAssetCap(e,t,r,s){return lr(e,t,r,s)}};var Ie=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,n,o){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n,this.hubAssetId=o}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),i=m(n.balance),a=m(s.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:n.hubReserves,sharesIn:s.shares,sharesOut:n.shares,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:o,balanceOut:i,tradeableIn:s.tradeable,tradeableOut:n.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,r),o=n.minus(s),i=s===w?w:o.div(s).multipliedBy(100).decimalPlaces(2),a=[],l=A.isSellAllowed(e.tradeableIn),c=A.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(h)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:t,feePct:i.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,r),i=s.minus(n).div(s).multipliedBy(100).decimalPlaces(2),a=[],l=A.isSellAllowed(e.tradeableIn),c=A.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(h)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:i.toNumber(),errors:a}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=A.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():w.toString(),r?y.toDecimals(r.protocolFee).toString():w.toString()),n=m(s);return n.isNegative()?w:n}calculateLrnaInGivenOut(e,t,r){let s=A.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():w.toString()),n=m(s);return n.isNegative()?w:n}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=A.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():w.toString(),r?y.toDecimals(r.protocolFee).toString():w.toString()),n=m(s);return n.isNegative()?w:n}calculateOutGivenLrnaIn(e,t,r){let s=A.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toDecimals(r.assetFee).toString():w.toString()),n=m(s);return n.isNegative()?w:n}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=A.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=A.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=A.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=A.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as cr}from"@polkadot/util-crypto";import{stringToU8a as ur}from"@polkadot/util";var ve=class extends L{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,n]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),o=r.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:u,tradable:h,cap:d,protocolShares:g}=l.unwrap(),b=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:h.bits.toNumber(),balance:b.toString(),cap:m(d.toString()),protocolShares:m(g.toString())}}),i=await Promise.all(o);return i.push({id:e,tradeable:s.bits.toNumber(),balance:n.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:i,...this.getPoolLimits()}]}async getPoolFees(e,t){let r=e.assetOut,s=e.assetIn,n="omnipool",o="Short",i=B=>B===D?[D,fe]:[fe,B],[a,l,c,u]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(r),this.api.query.emaOracle.oracles(n,i(r),o),this.api.query.emaOracle.oracles(n,i(s),o)]),[h,d,g]=this.getAssetFee(e,a.toNumber(),l,c),[b,P,T]=s===fe?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,u),f=h+b,I=g+T;return{assetFee:y.fromPermill(d),protocolFee:y.fromPermill(P),min:y.fromPermill(f),max:y.fromPermill(I)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(r=>r.id);return this.api.query.omnipool.assets.multi(t,r=>{e.tokens=r.map((s,n)=>{let o=e.tokens[n];if(s.isNone)return o;let i=s.unwrap();return this.updateTokenState(o,i)})})}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:n,cap:o,protocolShares:i}=t;return{...e,hubReserves:m(r.toString()),shares:m(s.toString()),cap:m(o.toString()),protocolShares:m(i.toString()),tradeable:n.bits.toNumber()}}getAssetFee(e,t,r,s){let{assetOut:n,balanceOut:o}=e,{minFee:i,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,u=y.fromPermill(i.toNumber()),h=y.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[i.toNumber(),i.toNumber(),a.toNumber()];let[d]=s.unwrap(),{assetFee:g,timestamp:b}=r.unwrap(),P=Math.max(1,t-b.toNumber()),T=d.volume.bIn.toString(),f=d.volume.bOut.toString(),I=d.liquidity.b.toString();n===D&&(T=d.volume.aIn.toString(),f=d.volume.aOut.toString(),I=d.liquidity.a.toString());let B=y.fromPermill(g.toNumber()),S=A.recalculateAssetFee(T,f,I,"9",o.toString(),y.toDecimals(B).toString(),P.toString(),y.toDecimals(u).toString(),y.toDecimals(h).toString(),l.toString(),c.toString());return[i.toNumber(),Number(S)*1e6,a.toNumber()]}getProtocolFee(e,t,r,s){let{assetIn:n,balanceIn:o}=e,{minFee:i,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,u=y.fromPermill(i.toNumber()),h=y.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[i.toNumber(),i.toNumber(),a.toNumber()];let[d]=s.unwrap(),{protocolFee:g,timestamp:b}=r.unwrap(),P=Math.max(1,t-b.toNumber()),T=d.volume.bIn.toString(),f=d.volume.bOut.toString(),I=d.liquidity.b.toString();n===D&&(T=d.volume.aIn.toString(),f=d.volume.aOut.toString(),I=d.liquidity.a.toString());let B=y.fromPermill(g.toNumber()),S=A.recalculateProtocolFee(T,f,I,"9",o.toString(),y.toDecimals(B).toString(),P.toString(),y.toDecimals(u).toString(),y.toDecimals(h).toString(),l.toString(),c.toString());return[i.toNumber(),Number(S)*1e6,a.toNumber()]}getPoolId(){return cr(ur("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),r=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as mr,calculate_out_given_in as pr,calculate_pool_trade_fee as dr,get_spot_price as gr,calculate_liquidity_in as hr,calculate_shares as Pr,calculate_spot_price as br,calculate_spot_price_with_fee as yr,calculate_liquidity_out_asset_a as fr,calculate_liquidity_out_asset_b as Sr}from"@galacticcouncil/math-xyk";var $=class{static getSpotPrice(e,t,r){return gr(e,t,r)}static calculateInGivenOut(e,t,r){return mr(e,t,r)}static calculateOutGivenIn(e,t,r){return pr(e,t,r)}static calculatePoolTradeFee(e,t,r){return dr(e,t,r)}static calculateLiquidityIn(e,t,r){return hr(e,t,r)}static calculateSpotPrice(e,t){return br(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return yr(e,t,r,s)}static calculateShares(e,t,r){return Pr(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return fr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Sr(e,t,r,s)}};var Ae=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,n){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),i=m(n.balance),a=m(s.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:o,balanceOut:i,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=this.calculateTradeFee(s,r),o=y.toPct(r.exchangeFee),i=s.plus(n),a=[];(t.isLessThan(this.minTradingLimit)||s.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 i.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o,errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(s,r),o=y.toPct(r.exchangeFee),i=s.minus(n),a=[];(t.isLessThan(this.minTradingLimit)||s.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 i.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o,errors:a}}calculateInGivenOut(e,t){let r=$.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?w:s}calculateOutGivenIn(e,t){let r=$.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?w:s}spotPriceInGivenOut(e){let t=$.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=v(R,18-e.decimalsOut);return m(t).div(r)}spotPriceOutGivenIn(e){let t=$.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=v(R,18-e.decimalsIn);return m(t).div(r)}calculateTradeFee(e,t){let r=$.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(r)}};var Fe=class extends L{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let n=r.toString(),[o,i]=s.unwrap(),[a,l]=await Promise.all([this.getBalance(n,o.toString()),this.getBalance(n,i.toString())]);return{address:n,type:"Xyk",tokens:[{id:o.toString(),balance:a.toString()},{id:i.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),r=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as wr,calculate_out_given_in as Tr,calculate_amplification as xr,calculate_add_one_asset as Or,calculate_liquidity_out_one_asset as Br,calculate_pool_trade_fee as Ir,calculate_shares as vr,calculate_shares_for_amount as Ar,calculate_spot_price_with_fee as Fr,pool_account_name as Nr,recalculate_peg as Rr}from"@galacticcouncil/math-stableswap";var _=class{static getPoolAddress(e){return Nr(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,n){return xr(e,t,r,s,n)}static calculateInGivenOut(e,t,r,s,n,o,i){return wr(e,t,r,s,n,o,i)}static calculateAddOneAsset(e,t,r,s,n,o,i){return Or(e,t,r,s,n,o,i)}static calculateSharesForAmount(e,t,r,s,n,o,i){return Ar(e,t,r,s,n,o,i)}static calculateOutGivenIn(e,t,r,s,n,o,i){return Tr(e,t,r,s,n,o,i)}static calculateLiquidityOutOneAsset(e,t,r,s,n,o,i){return Br(e,t,r,s,n,o,i)}static calculateShares(e,t,r,s,n,o){return vr(e,t,r,s,n,o)}static calculateSpotPriceWithFee(e,t,r,s,n,o,i,a){return Fr(e,t,r,s,n,o,i,a)}static calculatePoolTradeFee(e,t,r){return Ir(e,t,r)}static recalculatePegs(e,t,r,s,n){let o=Rr(e,t,r,s,n);return JSON.parse(o)}};var Ne=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,r,s,n,o,i,a,l,c,u){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n,this.amplification=o,this.id=i,this.fee=a,this.totalIssuance=l,this.pegs=c,this.pegsFee=u}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),n=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),i=m(n.balance),a=m(s.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:o,balanceOut:i,decimalsIn:s.decimals,decimalsOut:n.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:n.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,r),o=y.toPct(r.fee),i=[],a=A.isSellAllowed(e.tradeableIn),l=A.isBuyAllowed(e.tradeableOut);return(!a||!l)&&i.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&i.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:s,amountOut:t,feePct:o,errors:i}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,r),o=y.toPct(r.fee),i=[],a=A.isSellAllowed(e.tradeableIn),l=A.isBuyAllowed(e.tradeableOut);return(!a||!l)&&i.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&i.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:o,errors:i}}calculateIn(e,t,r){let s=_.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toDecimals(r.fee).toString():w.toString(),this.getPegs()),n=m(s);return n.isNegative()?w:n}calculateAddOneAsset(e,t,r){let s=_.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():w.toString(),this.getPegs()),n=m(s);return n.isNegative()?w:n}calculateSharesForAmount(e,t,r){let s=_.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():w.toString(),this.getPegs()),n=m(s);return n.isNegative()?w:n}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let s=v(R,e.decimalsIn-e.decimalsOut);return m(t).div(s)}let r=v(R,18-e.decimalsIn);return m(t).div(r)}calculateOut(e,t,r){let s=_.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toDecimals(r.fee).toString():w.toString(),this.getPegs()),n=m(s);return n.isNegative()?w:n}calculateWithdrawOneAsset(e,t,r){let s=_.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():w.toString(),this.getPegs()),n=m(s);return n.isNegative()?w:n}calculateShares(e,t,r){let s=_.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toDecimals(r.fee).toString():w.toString(),this.getPegs()),n=m(s);return n.isNegative()?w:n}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let s=v(R,e.decimalsOut-e.decimalsIn);return m(t).div(s)}let r=v(R,18-e.decimalsOut);return m(t).div(r)}calculateTradeFee(e,t){let r=_.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return m(r)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{blake2AsHex as Er,encodeAddress as _r}from"@polkadot/util-crypto";var Dr=340282366920938463463374607431768211455n,Re=class extends L{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[n]},o])=>{let i=o.unwrap(),a=n.toString(),l=this.getPoolAddress(a),[c,u,h]=await Promise.all([this.getPoolDelta(a,i,r.toString()),this.getPoolTokens(l,a,i),this.getPoolPegs(a,i,r.toString())]);return this.stablePools.set(l,i),{address:l,id:a,type:"Stableswap",fee:y.fromPermill(i.fee.toNumber()),tokens:u,...c,...h,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.pools.find(s=>s.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let r=t.toString(),s=this.stablePools.get(e.address);if(s){let[n,o]=await Promise.all([this.getPoolDelta(e.id,s,r),this.getPoolPegs(e.id,s,r)]);Object.assign(e,n,o)}})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:n,initialBlock:o,finalBlock:i}=t,a=_.calculateAmplification(s.toString(),n.toString(),o.toString(),i.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,n=s.map(async i=>{let[a,l]=await Promise.all([this.api.query.stableswap.assetTradability(t,i.toString()),this.getBalance(e,i.toString())]);return{id:i.toString(),tradeable:a.bits.toNumber(),balance:l.toString()}}),o=await Promise.all(n);return o.push({id:t,tradeable:15,balance:Dr.toString()}),o}getPoolDefaultPegs(e){let t=e.fee,r=_.defaultPegs(e.assets.length);return{pegsFee:y.fromPermill(t.toNumber()),pegs:r}}async getPoolPegs(e,t,r){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getPoolDefaultPegs(t);let n=s.unwrap(),o=await this.getLatestPegs(t,n,r),i=this.getRecentPegs(n),a=n.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[c,u]=_.recalculatePegs(JSON.stringify(i),JSON.stringify(o),r,a.replace(/%/g,""),l.replace(/%/g,"")),h=Number(c)*1e4;return{pegsFee:y.fromPermill(h),pegs:u}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(n=>n.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,n=Array.from(e.assets.entries()).map(([i,a])=>a.toString()),o=s.map(async(i,a)=>{if(i.isOracle){let[l,c,u]=i.asOracle,h=[u.toString(),n[a]].map(f=>Number(f)).sort((f,I)=>f-I),d=await this.api.query.emaOracle.oracles(l,h,c),[{price:g,updatedAt:b}]=d.unwrap(),P=g.n.toString(),T=g.d.toString();return u.toString()===h[0].toString()?[[P,T],b.toString()]:[[T,P],b.toString()]}else return[i.asValue.map(l=>l.toString()),r]});return Promise.all(o)}getPoolAddress(e){let t=Number(e),r=_.getPoolAddress(t);return _r(Er(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var ne=class extends C{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=kr(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new z(this.api),this.aaveClient=new xe(this.api),this.xykClient=new Fe(this.api),this.omniClient=new ve(this.api),this.lbpClient=new Be(this.api),this.stableClient=new Re(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(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(s=>s.isSupported()).map(s=>s.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(r=>e.some(s=>s===r.getPoolType())).map(r=>r.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new we(t.type)}}};var ie=class extends ne{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Cr(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);{let n=await super.getPoolFees(e,t);return this.feeCache.set(r,n),n}}async destroy(){this.log(`Destroying pool cache!
|
|
2
|
+
Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var oe=class{static get(e){switch(e.type){case"Aave":return Te.fromPool(e);case"Xyk":return Ae.fromPool(e);case"Omnipool":return Ie.fromPool(e);case"Lbp":return Oe.fromPool(e);case"Stableswap":return Ne.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Ee=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Lr=5,ae=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],n=new Ee,o=[];for(o.push([t,""]),n.enqueue(o);n.size()>0;){let i=n.dequeue();if(i==null||i.length>Lr)return s;let a=i[i.length-1];(r===null||a[0]===r)&&s.push(i),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,i)){let u=[...i];u.push(c),n.enqueue(u)}})}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,n,o]of t){let i=parseInt(n),a=parseInt(o);r.get(i)?.push([a,s])}return r}};function Xe(p){let e={};for(let t of p){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let n=0;n<r;n++){if(s==n)continue;let o=[t.address,t.tokens[s].id,t.tokens[n].id];e[t.tokens[s].id].push(o)}}}return e}var le=class{getProposals(e,t,r){let s=Xe(r),n=Object.keys(s),o=n.map(c=>s[c]).flat(),i=new ae,a=i.buildAndPopulateGraph(n,o),l=i.findPaths(a,parseInt(e),t?parseInt(t):null);return this.parsePaths(l)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let n=0;n<r.length;n++){let o=r[n],i=r[n+1];if(i==null)break;s.push(this.toEdge(o,i))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ce=class{routeSuggester;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new le,this.routerOptions=Object.freeze({includeOnly:t.includeOnly??[]})}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:r,poolsMap:s}=await this.validateToken(e,t),o=this.getPaths(e,null,s,t).map(i=>i[i.length-1].assetOut);return this.toAssets([...new Set(o)],r)}async getAllPaths(e,t){let r=await this.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await this.validateTokenPair(e,t,r);return this.getPaths(e,t,s,r)}async getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r,s){return this.routeSuggester.getProposals(e,t,s).filter(i=>this.validPath(i,r)).map(i=>this.toHops(i,r))}async validateTokenPair(e,t,r){let s=await this.getAssets(r);if(s.get(e)==null)throw new Error(e+" is not supported token");if(s.get(t)==null)throw new Error(t+" is not supported token");let n=this.getPoolMap(r);return{assets:s,poolsMap:n}}async validateToken(e,t){let r=await this.getAssets(t);if(r.get(e)==null)throw new Error(e+" is not supported token");let s=this.getPoolMap(t);return{assets:r,poolsMap:s}}getPoolMap(e){return new Map(e.map(t=>[t.address,oe.get(t)]))}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toHops(e,t){return e.map(([r,s,n])=>{let o=t.get(r);return{poolAddress:r,poolId:o?.id,pool:o?.type,assetIn:s,assetOut:n}})}toAssets(e,t){return e.map(r=>t.get(r))}};var Mr=m("100");function Cl(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ue(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function dt(p,e){return R.minus(e.div(p)).multipliedBy(100).decimalPlaces(2)}function gt(p,e){return e.div(p).minus(R).multipliedBy(100).decimalPlaces(2)}function K(p,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),p.div(Mr).multipliedBy(e).decimalPlaces(0,1)}var Ye=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Ye||{}),$e=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))($e||{}),ht=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(ht||{});var me=class extends ce{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let n=r[r.length-1].amountOut,o=s[s.length-1].amountOut;return n.isGreaterThan(o)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,o)=>n+o),s=e.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,o)=>n+o);return[r,s]}}getPoolFeeRange(e){let t=e.min?y.toPct(e.min):void 0,r=e.max?y.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:o}=await super.validateTokenPair(e,t,n),i=super.getPaths(e,t,o,n);if(i.length===0)throw new j(e,t);let a;if(s)a=await this.toSellSwaps(r,s,o);else{let S=i.map(async F=>await this.toSellSwaps(r,F,o)),N=await Promise.all(S);a=this.findBestSellRoute(N)}let l=a[0],c=a[a.length-1],u=this.isDirectTrade(a),h=a.map(S=>S.spotPrice.shiftedBy(-1*S.assetOutDecimals)).reduce((S,N)=>S.multipliedBy(N)),d=v(h,c.assetOutDecimals),g=u?c.calculatedOut:this.calculateDelta0Y(l.amountIn,a,o),b=c.amountOut,P=u?c.tradeFeePct:dt(g,b).toNumber(),T=g.minus(b),f=this.getRouteFeeRange(a),I=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(d),B=ue(g,I);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:T,tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:x(l.amountIn,l.assetInDecimals),amountOut:x(c.amountOut,c.assetOutDecimals),spotPrice:x(d,c.assetOutDecimals),tradeFee:x(T,c.assetOutDecimals),tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B.toNumber(),swaps:a.map(S=>S.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let n=0;n<t.length;n++){let o=t[n],i=r.get(o.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(o.assetIn,o.assetOut),l;n>0?l=s[n-1]:l=e;let c=i.calculateOutGivenIn(a,l);s.push(c)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let n=0;n<t.length;n++){let o=t[n],i=r.get(o.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(o.assetIn,o.assetOut),l;n>0?l=s[n-1].amountOut:l=v(m(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,i),{amountOut:u,calculatedOut:h,feePct:d,errors:g}=i.validateAndSell(a,l,c),b=this.getPoolFeeRange(c),P=i.spotPriceOutGivenIn(a),T=l.shiftedBy(-1*a.decimalsIn).multipliedBy(P),f=ue(h,T);s.push({...o,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,amountOut:u,calculatedOut:h,spotPrice:P,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===o.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===o.assetIn},toHuman(){return{...o,amountIn:x(l,a.decimalsIn),amountOut:x(u,a.decimalsOut),calculatedOut:x(h,a.decimalsOut),spotPrice:x(P,a.decimalsOut),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:g}}})}return s}async getMostLiquidRoute(e,t){let r=await super.getPools(),{poolsMap:s}=await super.validateTokenPair(e,t,r),n=super.getPaths(e,t,s,r);if(n.length===0)throw new j(e,t);let l=r.filter(d=>d.tokens.some(g=>g.id===e&&g.id!==d.id)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(g=>g.id===e)).map(d=>d.map(g=>m(g.balance).shiftedBy(-1*g.decimals)).reduce((g,b)=>g.plus(b))).sort((d,g)=>g.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=n.map(async d=>await this.toSellSwaps(l,d,s)),u=await Promise.all(c);return this.findBestSellRoute(u).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r=await super.getPools();if(r.length===0)throw new Error("No pools configured");let{poolsMap:s}=await super.validateTokenPair(e,t,r);if(super.getPaths(e,t,s,r).length===0)return Promise.resolve(void 0);let o=await this.getMostLiquidRoute(e,t),i=await this.toSellSwaps("1",o,s),a=i.map(u=>u.spotPrice.shiftedBy(-1*u.assetOutDecimals)).reduce((u,h)=>u.multipliedBy(h)),l=i[i.length-1].assetOutDecimals;return{amount:v(a,l),decimals:l}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let n=r[0].amountIn,o=s[0].amountIn;return n.isGreaterThan(o)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:o}=await super.validateTokenPair(e,t,n),i=super.getPaths(e,t,o,n);if(i.length===0)throw new j(e,t);let a;if(s)a=await this.toBuySwaps(r,s,o);else{let S=i.map(async F=>await this.toBuySwaps(r,F,o)),N=await Promise.all(S);a=this.findBestBuyRoute(N)}let l=a[a.length-1],c=a[0],u=this.isDirectTrade(a),h=a.map(S=>S.spotPrice.shiftedBy(-1*S.assetInDecimals)).reduce((S,N)=>S.multipliedBy(N)),d=v(h,c.assetInDecimals),g=u?c.calculatedIn:this.calculateDelta0X(l.amountOut,a,o),b=c.amountIn,P=u?c.tradeFeePct:gt(g,b).toNumber(),T=b.minus(g),f=this.getRouteFeeRange(a),I=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(d),B;return g.isZero()?B=-100:B=ue(I,g).toNumber(),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:T,tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B,swaps:a,toHuman(){return{type:"Buy",amountOut:x(l.amountOut,l.assetOutDecimals),amountIn:x(c.amountIn,c.assetInDecimals),spotPrice:x(d,c.assetInDecimals),tradeFee:x(T,c.assetInDecimals),tradeFeePct:P,tradeFeeRange:f,priceImpactPct:B,swaps:a.map(S=>S.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let n=t.length-1;n>=0;n--){let o=t[n],i=r.get(o.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(o.assetIn,o.assetOut),l;n==t.length-1?l=e:l=s[0];let c=i.calculateInGivenOut(a,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let n=t.length-1;n>=0;n--){let o=t[n],i=r.get(o.poolAddress);if(i==null)throw new Error("Pool does not exit");let a=i.parsePair(o.assetIn,o.assetOut),l;n==t.length-1?l=v(m(e),a.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(a,i),{amountIn:u,calculatedIn:h,feePct:d,errors:g}=i.validateAndBuy(a,l,c),b=this.getPoolFeeRange(c),P=i.spotPriceInGivenOut(a),T=l.shiftedBy(-1*a.decimalsOut).multipliedBy(P),f;h.isZero()?f=-100:f=ue(T,h).toNumber(),s.unshift({...o,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,amountOut:l,calculatedIn:h,spotPrice:P,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f,errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===o.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===o.assetIn},toHuman(){return{...o,amountIn:x(u,a.decimalsIn),amountOut:x(l,a.decimalsOut),calculatedIn:x(h,a.decimalsIn),spotPrice:x(P,a.decimalsIn),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f,errors:g}}})}return s}};var Pt=6e3,bt=m(1e15),pe=6,Ve=-5,ze=6*60*60*1e3;var yt=6;var G=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:n})=>s==="Stableswap"?{pool:{Stableswap:n},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var de=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??Pt,minBudgetInNative:t.minBudgetInNative??bt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,n){let[o,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:l,priceImpactPct:c}=i,u=l[0],h=l[l.length-1],{assetInDecimals:d}=u,{assetOutDecimals:g}=h,b=Math.abs(c),P=this.getMinimumTradeCount(a,o),T=this.getOptimalTradeCount(b),f=n?Math.round(s/n):T,I=Math.ceil(s/P),B=Math.round(s/T),S=Math.round(s/f),N=a.dividedBy(f).decimalPlaces(0,1),F=await this.router.getBestSell(e,t,x(N,d)),q=a.isLessThan(o),he=[];q&&he.push("OrderTooSmall");let Pe=F.amountOut.multipliedBy(f),ke=this.toBlockPeriod(S),Ce=F.tradeFee.multipliedBy(f),Le=G.build(l),Ke={assetIn:e,assetOut:t,errors:he,frequencyMin:I,frequencyOpt:B,frequency:S,tradeCount:f,tradeFee:Ce,tradeImpactPct:F.priceImpactPct,tradePeriod:ke,tradeRoute:Le,type:"Dca"};return{...Ke,amountIn:a,amountOut:Pe,tradeAmountIn:F.amountIn,tradeAmountOut:F.amountOut,toHuman(){return{...Ke,amountIn:x(a,d),amountOut:x(Pe,g),tradeAmountIn:x(F.amountIn,d),tradeAmountOut:x(F.amountOut,g)}}}}async getMinimumOrderBudget(e){if(D===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(D,e);if(t)return this.minOrderBudget.times(t.amount).div(m(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:i,priceImpactPct:a}=n,l=i[0],c=i[i.length-1],{assetInDecimals:u}=l,{assetOutDecimals:h}=c,d=Math.abs(a),g=this.getTwapTradeCount(d),b=o.dividedBy(g).decimalPlaces(0,1),P=await this.router.getBestSell(l.assetIn,c.assetOut,x(b,u)),T=g===1,f=o.isLessThan(s),I=P.priceImpactPct<Ve,B=[];f||T?B.push("OrderTooSmall"):I&&B.push("OrderImpactTooBig");let S=P.amountOut.multipliedBy(g),N=P.tradeFee.multipliedBy(g),F=G.build(i),q={assetIn:e,assetOut:t,errors:B,tradeCount:g,tradeImpactPct:P.priceImpactPct,tradePeriod:pe,tradeRoute:F,type:"TwapSell"};return{...q,amountIn:o,amountOut:S,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:N,toHuman(){return{...q,amountIn:x(o,u),amountOut:x(S,h),tradeAmountIn:x(P.amountIn,u),tradeAmountOut:x(P.amountOut,h),tradeFee:x(N,h)}}}}async getTwapBuyOrder(e,t,r){let[s,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:o,swaps:i,priceImpactPct:a}=n,l=i[0],c=i[i.length-1],{assetInDecimals:u}=l,{assetOutDecimals:h}=c,d=Math.abs(a),g=this.getTwapTradeCount(d),b=o.dividedBy(g).decimalPlaces(0,1),P=await this.router.getBestBuy(l.assetIn,c.assetOut,x(b,h)),T=P.amountIn.multipliedBy(g),f=g===1,I=T.isLessThan(s),B=P.priceImpactPct<Ve,S=[];I||f?S.push("OrderTooSmall"):B&&S.push("OrderImpactTooBig");let N=P.tradeFee.multipliedBy(g),F=G.build(i),q={assetIn:e,assetOut:t,errors:S,tradeCount:g,tradeImpactPct:P.priceImpactPct,tradePeriod:pe,tradeRoute:F,type:"TwapBuy"};return{...q,amountIn:T,amountOut:o,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:N,toHuman(){return{...q,amountIn:x(T,u),amountOut:x(o,h),tradeAmountIn:x(P.amountIn,u),tradeAmountOut:x(P.amountOut,h),tradeFee:x(N,u)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>ze){let s=ze/(this.blockTime*pe);return Math.round(s)}return t}getTwapExecutionTime(e){return e*pe*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,yt)}};import{encodeFunctionData as Ur}from"viem";var Q=class extends C{evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evmClient=t??new k,this.balanceClient=new U(e),this.aaveUtils=new V(this.evmClient)}wrapTx(e,t){return{hex:t.toHex(),name:e,get:()=>t,dryRun:r=>this.dryRun(r,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),ye)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var _e=class extends Q{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:n,assetOut:o}=s,i;return s.isWithdraw()?i=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,o)).amount:i=await this.balanceClient.getBalance(this.beneficiary,n),e.isGreaterThanOrEqualTo(i.minus(5))&&!s.isWithdraw()?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],n=r[r.length-1],o=K(e,this.slippagePct),i=s.assetIn,a=n.assetOut,l=e.plus(o),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(a,i,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(i,a,t.toFixed(),l.toFixed(),G.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],n=r[r.length-1],o=K(t,this.slippagePct),i=s.assetIn,a=n.assetOut,l=t.minus(o),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(i,a,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(i,a,e.toFixed(),l.toFixed(),G.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],n=K(e,this.slippagePct),o=r.assetIn,i=s.assetOut,a=e.minus(n),l=this.api.tx.router.sellAll(o,i,a.toFixed(),G.build(t));return r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}async buildWithdrawTx(e){let{swaps:t}=this.trade,r=e||this.trade.amountIn,n=t[0].assetOut,o=await this.evmClient.getGasPrice(),i=o*10n/100n,a=Y.fromAny(this.beneficiary),l=e?Je:BigInt(r.toFixed()),c=M.fromAssetId(n),u=Ur({abi:J,functionName:"withdraw",args:[c,l,a]}),h=this.api.tx.evm.call(a,be,u,0n,ye,o+i,o+i,null,[]);return{hex:h.toHex(),name:"Withdraw",get:()=>h,dryRun:d=>this.dryRun(d,h)}}};var De=class extends Q{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradePeriod:n,tradeRoute:o}=this.order,i=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:o}}},null);return this.wrapTx("DcaSchedule",i)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:o,tradeRoute:i}=this.order,a=K(n,this.slippagePct),l=n.minus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:o,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:i}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:o,tradeRoute:i}=this.order,a=K(s,this.slippagePct),l=s.plus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:o,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:n.toFixed(),maxAmountIn:l.toFixed(),route:i}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var ge=class{api;evmClient;constructor(e,t){this.api=e,this.evmClient=t??new k}trade(e){return new _e(this.api,this.evmClient).setTrade(e)}order(e){return new De(this.api,this.evmClient).setOrder(e)}};function eu(p,e){let t=new se(p),r=e??new k,s=new ie(p),n=new V(r),o=new me(s),i=new de(o,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:n,router:o,scheduler:i},client:{asset:new z(p),balance:new U(p),evm:r},ctx:{pool:s},tx:new ge(p,r),destroy:()=>{s.destroy()}}}export{Dr as AMOUNT_MAX,ee as AaveClient,Te as AavePool,xe as AavePoolClient,V as AaveUtils,z as AssetClient,lt as AssetNotFound,ls as BASILISK_PARACHAIN_ID,U as BalanceClient,O as BigNumber,ie as CachingPoolService,se as ChainParams,Nt as DECIMAL_PLACES,qe as DENOMINATOR,M as ERC20,k as EvmClient,We as FarmClient,Y as H160,fe as HUB_ASSET_ID,cs as HYDRADX_PARACHAIN_ID,W as HYDRADX_SS58_PREFIX,ys as INFINITY,H as LbpMath,Oe as LbpPool,Be as LbpPoolClient,R as ONE,A as OmniMath,Ie as OmniPool,ve as OmniPoolClient,C as PolkadotApiClient,at as PoolConfigNotFound,Z as PoolError,oe as PoolFactory,we as PoolNotFound,ne as PoolService,E as PoolType,mt as ProviderConfigNotFound,te as RUNTIME_DECIMALS,j as RouteNotFound,ce as Router,tt as SYSTEM_ASSET_DECIMALS,D as SYSTEM_ASSET_ID,_ as StableMath,Ne as StableSwap,Re as StableSwapClient,ct as StorageConfigNotFound,ut as SubscriptionNotSupported,re as TRADEABLE_DEFAULT,ht as TradeOrderError,$e as TradeOrderType,G as TradeRouteBuilder,me as TradeRouter,de as TradeScheduler,Ye as TradeType,ge as TxBuilderFactory,$ as XykMath,Ae as XykPool,Fe as XykPoolClient,w as ZERO,xn as bnFormatter,m as bnum,gt as calculateBuyFee,Cl as calculateDiffToAvg,ue as calculateDiffToRef,dt as calculateSellFee,eu as createSdkContext,Qe as evmMainnet,pt as findNestedKey,Tn as findNestedObj,K as getFraction,vt as isEvmAccount,At as isEvmAddress,Ft as isSs58Address,v as scale,fs as toBn,x as toDecimals};
|
|
@@ -10,8 +10,8 @@ export declare class BalanceClient extends PolkadotApiClient {
|
|
|
10
10
|
getTokenBalance(account: string, assetId: string): Promise<BigNumber>;
|
|
11
11
|
getErc20Balance(account: string, assetId: string): Promise<BigNumber>;
|
|
12
12
|
subscribeSystemBalance(address: string, onChange: (token: string, balance: BigNumber) => void): UnsubscribePromise;
|
|
13
|
-
subscribeTokenBalance(address: string, onChange: (balances: [string, BigNumber][]) => void): UnsubscribePromise;
|
|
14
|
-
subscribeErc20Balance(address: string, onChange: (balances: [string, BigNumber][]) => void,
|
|
13
|
+
subscribeTokenBalance(address: string, onChange: (balances: [string, BigNumber][]) => void, assets?: string[]): UnsubscribePromise;
|
|
14
|
+
subscribeErc20Balance(address: string, onChange: (balances: [string, BigNumber][]) => void, assets?: string[]): UnsubscribePromise;
|
|
15
15
|
getTokenBalanceData(account: string, assetId: string): Promise<OrmlTokensAccountData>;
|
|
16
16
|
protected calculateFreeBalance(data: any): BigNumber;
|
|
17
17
|
}
|