@galacticcouncil/sdk 9.9.0 → 9.9.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 +2 -2
- package/build/index.mjs +2 -2
- package/package.json +1 -1
package/build/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var mt=Object.defineProperty;var fr=Object.getOwnPropertyDescriptor;var Pr=Object.getOwnPropertyNames;var br=Object.prototype.hasOwnProperty;var Sr=(u,e)=>{for(var t in e)mt(u,t,{get:e[t],enumerable:!0})},xr=(u,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pr(e))!br.call(u,s)&&s!==t&&mt(u,s,{get:()=>e[s],enumerable:!(r=fr(e,s))||r.enumerable});return u};var vr=u=>xr(mt({},"__esModule",{value:!0}),u);var Gr={};Sr(Gr,{AaveClient:()=>ie,AavePool:()=>Ie,AavePoolClient:()=>_e,AaveUtils:()=>Q,AssetClient:()=>Z,AssetNotFound:()=>St,BASILISK_PARACHAIN_ID:()=>es,BalanceClient:()=>q,BalanceClientV2:()=>oe,BigNumber:()=>v.BigNumber,CachingPoolService:()=>me,ChainParams:()=>ae,DECIMAL_PLACES:()=>Gt,ERC20:()=>z,EvmClient:()=>Be,FarmClient:()=>Ve,H160:()=>te,HUB_ASSET_ID:()=>Se,HYDRADX_PARACHAIN_ID:()=>ts,HYDRADX_SS58_PREFIX:()=>K,INFINITY:()=>wr,LbpMath:()=>W,LbpPool:()=>Ee,LbpPoolClient:()=>Ne,ONE:()=>D,OmniMath:()=>_,OmniPool:()=>Fe,OmniPoolClient:()=>ke,PERMILL_DENOMINATOR:()=>ee,PolkadotApiClient:()=>L,PoolConfigNotFound:()=>bt,PoolError:()=>se,PoolFactory:()=>pe,PoolNotFound:()=>Te,PoolService:()=>ce,PoolType:()=>F,ProviderConfigNotFound:()=>wt,RUNTIME_DECIMALS:()=>xe,RouteNotFound:()=>Oe,Router:()=>de,SYSTEM_ASSET_DECIMALS:()=>Mt,SYSTEM_ASSET_ID:()=>k,StableMath:()=>C,StableSwap:()=>Me,StableSwapClient:()=>Le,StorageConfigNotFound:()=>xt,SubscriptionNotSupported:()=>vt,TRADEABLE_DEFAULT:()=>ve,TradeOrderError:()=>Ft,TradeOrderType:()=>nt,TradeRouteBuilder:()=>G,TradeRouter:()=>he,TradeScheduler:()=>ye,TradeType:()=>it,TxBuilderFactory:()=>Pe,XykMath:()=>V,XykPool:()=>De,XykPoolClient:()=>Ce,ZERO:()=>S,bnFormatter:()=>Rr,bnum:()=>p,calculateBuyFee:()=>Nt,calculateDiffToAvg:()=>qr,calculateDiffToRef:()=>ge,calculateSellFee:()=>Et,createChain:()=>Tt,createSdkContext:()=>Ur,findNestedKey:()=>Ot,findNestedObj:()=>Ar,getFraction:()=>J,hashPools:()=>Rt,isEvmAccount:()=>Lt,isEvmAddress:()=>qt,isSs58Address:()=>Ut,scale:()=>R,toBn:()=>Tr,toDecimals:()=>O});module.exports=vr(Gr);var Ye=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var pt=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Ct="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",dt="0x112b087b60C1a166130d59266363C45F8aa99db0",gt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",be=1000000n;var Kr=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ie=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:pt,address:dt,args:[gt],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:pt,address:dt,args:[gt,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:Ye,address:Ct,args:[e],functionName:"getUserAccountData"})}};var j=require("@polkadot/util-crypto"),ne=require("@polkadot/util"),Y=require("buffer");var es=2090,ee=1e6,Se="1",ts=2034,K=63,xe=18,k="0",Mt=12,ve=15;var ht="ETH\0";function Lt(u){if(!u)return!1;try{let e=(0,j.decodeAddress)(u,!0),t=Y.Buffer.from(ht);return Y.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function qt(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Ut(u){try{let e=(0,ne.isHex)(u)?(0,ne.hexToU8a)(u):(0,j.decodeAddress)(u);return(0,j.encodeAddress)(e),!0}catch{return!1}}var te=class u{static toAccount=e=>{let t=Y.Buffer.from(e.slice(2),"hex"),r=Y.Buffer.from(ht);return(0,j.encodeAddress)(new Uint8Array(Y.Buffer.concat([r,t,Y.Buffer.alloc(8)])),63)};static fromAccount=e=>{let t=(0,j.decodeAddress)(e),r=Y.Buffer.from(ht),s=t.slice(r.length,-8);return"0x"+Y.Buffer.from(s).toString("hex")};static fromSS58=e=>{let r=(0,j.decodeAddress)(e).slice(0,20);return(0,ne.u8aToHex)(r)};static fromAny=e=>{if(qt(e))return e;if(Lt(e))return u.fromAccount(e);if(Ut(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var we=require("buffer"),z=class{static fromAssetId(e){let t=Number(e),r=we.Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=we.Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=we.Buffer.from("0000000000000000000000000000000100000000","hex"),r=we.Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};var v=require("bignumber.js"),Gt=12;v.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Gt});var S=p(0),D=p(1),wr=p("Infinity");function R(u,e){let t=new v.BigNumber(e.toString()),r=new v.BigNumber(10).pow(t);return u.times(r).decimalPlaces(4)}function p(u){return new v.BigNumber(u.toString())}function Tr(u,e){let t=p(u);return R(t,e)}function O(u,e){return u.shiftedBy(-1*e).toString()}var $e=p("1e27"),Or=p("1.01"),Br=p("31536000"),Q=class{client;constructor(e){this.client=new ie(e)}async getSummary(e){let t=te.fromAny(e),[r,s,i,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[o]=r,[a,l]=s,[c,m,g,d,h,b]=i,y=p(b).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN),w=p(c),f=p(m),T=[];for(let x of a){let I=x.underlyingAsset.toLowerCase(),A=o.find(({underlyingAsset:yr})=>yr.toLowerCase()===I);if(!A)throw new Error("Missing pool reserve for "+I);let M=p(x.scaledATokenBalance),H=p(A.liquidityIndex),He=p(A.liquidityRate),ze=p(A.availableLiquidity),lt=p(A.priceInMarketReferenceCurrency),ut=n+6,ct=this.calculateLinearInterest(He,A.lastUpdateTimestamp,ut),Xe=H.multipliedBy(ct).dividedBy($e).decimalPlaces(0,v.BigNumber.ROUND_DOWN),pr=M.multipliedBy(Xe).dividedBy($e).decimalPlaces(0,v.BigNumber.ROUND_DOWN),dr=p(l!==0&&l===A.eModeCategoryId?A.eModeLiquidationThreshold:A.reserveLiquidationThreshold).div(1e4),gr=A.usageAsCollateralEnabled&&x.usageAsCollateralEnabledOnUser&&p(x.scaledATokenBalance).gt(0),hr=z.toAssetId(I);T.push({aTokenBalance:pr,availableLiquidity:ze,decimals:Number(A.decimals),isCollateral:gr,priceInRef:lt,reserveId:hr,reserveAsset:I,reserveLiquidationThreshold:dr})}return{healthFactor:y.toNumber(),totalCollateral:w,totalDebt:f,reserves:T}}async hasBorrowPositions(e){let t=te.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=te.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,n,o,a,l]=r;return p(l).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=z.fromAssetId(t),a=n.find(w=>w.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:c,priceInRef:m,reserveLiquidationThreshold:g}=a,d=R(p(r),l).decimalPlaces(0,1),h=c?d.multipliedBy(m).dividedBy(p(10).pow(l)).decimalPlaces(0,v.BigNumber.ROUND_DOWN):S,b=s.minus(h);return b.lte(0)?0:b.multipliedBy(g).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=z.fromAssetId(t),a=n.find(y=>y.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:m}=a,d=R(p(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(p(10).pow(l)).decimalPlaces(0,v.BigNumber.ROUND_DOWN),h=s.plus(d);return h.lte(0)?0:h.multipliedBy(m).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),n=z.fromAssetId(t),o=s.find(a=>a.reserveAsset===n);if(!o)throw new Error("Missing reserve data for "+n);return this.calculateWithdrawMax(o,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let n of r){let o=this.calculateWithdrawMax(n,t,s);n.reserveId&&(i[n.reserveId]=o)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:n,priceInRef:o,reserveLiquidationThreshold:a,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let g=p(r).minus(Or);if(g.gt(0)){let h=g.multipliedBy(t).dividedBy(a).decimalPlaces(0,v.BigNumber.ROUND_DOWN).dividedBy(o).multipliedBy(p(10).pow(n)).decimalPlaces(0,v.BigNumber.ROUND_DOWN);c=v.BigNumber.minimum(s,h)}else c=S}return{amount:v.BigNumber.minimum(c,i),decimals:n}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?$e:e.multipliedBy(s).dividedBy(Br).plus($e).decimalPlaces(0,v.BigNumber.ROUND_DOWN)}};function Wt(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var bs=require("@galacticcouncil/api-augment/hydradx"),Ss=require("@galacticcouncil/api-augment/basilisk"),L=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Wt(r)&&console.log(e,...t)}};var Z=class extends L{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==k){let m=this.api.consts.balances.existentialDeposit;return{id:k,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient: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),g=n.toNumber(),d=new Intl.DateTimeFormat("en-GB"),h=[c,"Bond",d.format(g)].join(" ");return{id:e,name:h,symbol:c+"b",decimals:m,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:g}}getShares(e,t,r,s){let{assets:i}=s,{name:n,symbol:o,assetType:a,isSufficient:l,existentialDeposit:c}=t,g=i.map(b=>b.toString()).map(b=>{let{symbol:y}=this.getToken(b,t,r);return[b,y]}),d=Object.fromEntries(g),h=Object.values(d);return{id:e,name:h.join(", "),symbol:o?.isSome?o.toHuman():n.toHuman(),decimals:18,icon:h.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]},g])=>{let d=g.unwrap(),h=s.get(m.toString()),{assetType:b}=d;switch(b.toString()){case"Bond":let y=n.get(m.toString());return this.getBond(m.toString(),d,l,y);case"StableSwap":let w=i.get(m.toString());return this.getShares(m.toString(),d,l,w);case"External":return this.getExternal(m.toString(),d,t,h);default:return this.getToken(m.toString(),d,l,h)}});return e?c:c.filter(m=>this.isValidAsset(m))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var q=class extends L{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===k?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(k,this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,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 t=e.free.toString(),r=e.frozen.toString();return(0,v.BigNumber)(t).lt(r)?(0,v.BigNumber)(0):(0,v.BigNumber)(t).minus(r)}};var oe=class extends L{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===k?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(k,this.calculateBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,o]})=>[n.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,l)=>{let c=i[l][1],m=this.calculateBalance(a);o.push([c,m])}),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)}calculateBalance(e){let t=(0,v.BigNumber)(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),i=t.gte(r)?t.minus(r).toString():"0",n=t.plus(s).toString();return{free:t.toString(),total:n,transferable:i,reserved:s,frozen:r}}};var 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 yt=require("@galacticcouncil/math-liquidity-mining"),Ht=require("@polkadot/types"),ft=require("@polkadot/util"),Pt=require("@polkadot/util-crypto");var Ve=class extends L{balanceClient;constructor(e){super(e),this.balanceClient=new q(e)}secondsInYear=new v.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),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(),h=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:m,potBalance:b.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,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(),h=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:m,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new v.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),o=n.price.n.toString(),a=n.price.d.toString(),l;return Number(t)<Number(r)?l=(0,yt.fixed_from_rational)(o,a):l=(0,yt.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,ft.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Ht.GenericAccountId32(e,this.padEndU8a((0,ft.u8aConcat)(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,Pt.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,Pt.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 v.BigNumber(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),d=new v.BigNumber(a.yieldPerPeriod.toString()),h=new v.BigNumber(a.maxRewardPerPeriod.toString()),b=a.blocksPerPeriod.toString(),y=new v.BigNumber(o.multiplier.toString()).shiftedBy(-18),w=this.secondsInYear.div(new v.BigNumber(r).times(b)),f;if(m.isZero())f=d.times(y).times(w);else{let M=this.getGlobalRewardPerPeriod(m,d,h,l);f=this.getPoolYieldPerPeriod(M,y,m,l).times(w)}let T=new v.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),x=h.times(g),I=c?T.plus(c):x;return T.div(I).gte(.999)?S:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),S).toString():void 0}};var Te=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},bt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Oe=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},St=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},xt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},vt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},wt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var zt=require("viem"),Ir=["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"],Tt=u=>{let t=[u.endpoint,...Ir],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return(0,zt.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1})};var $=require("viem");function Xt(u){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return u.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var Be=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=Tt(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,$.createPublicClient)({chain:this.chain,transport:(0,$.http)()})}getWsProvider(){return(0,$.createPublicClient)({chain:this.chain,transport:Xt(this.wsProvider)})}getSigner(e){return(0,$.createWalletClient)({account:e,chain:this.chain,transport:(0,$.custom)(window.ethereum)})}};var re=(u,e=new Map)=>t=>{let r;return e.has(t)?e.get(t):(e.set(t,r=u(t)),r)};var F=(i=>(i.Aave="Aave",i.LBP="Lbp",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="Xyk",i))(F||{}),se=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(se||{});var Ie=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 R(D,e.decimalsOut)}spotPriceOutGivenIn(e){return R(D,e.decimalsIn)}calculateTradeFee(e,t){return S}};var er=require("@polkadot/util-crypto"),tr=require("@polkadot/util"),rr=require("viem");function Ot(u,e){let t=[];return JSON.stringify(u,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Ar(u,e,t){let r;return JSON.stringify(u,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Rr=(u,e)=>typeof e=="bigint"?e.toString():e;var Ae=(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 Ke=(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 _r=Ke(()=>"illegal argument(s)"),Yt=u=>{throw new _r(u)};var Er=Ke(()=>"index out of bounds"),Bt=u=>{throw new Er(u)},je=(u,e,t)=>(u<e||u>=t)&&Bt(u);var $t=23283064365386963e-26,Qe=class{float(e=1){return this.int()*$t*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*$t-.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 Ze=class extends Qe{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 Vt=new Ze(Math.random);var Kt=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var jt=Object.getPrototypeOf({}),Je="function",Qt="string",le=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===Je)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===Je)return e.equiv(u)}else return u==e;return typeof u===Qt||typeof e===Qt?!1:(t=Object.getPrototypeOf(u),(t==null||t===jt)&&(t=Object.getPrototypeOf(e),t==null||t===jt)?Dr(u,e):typeof u!==Je&&u.length!==void 0&&typeof e!==Je&&e.length!==void 0?Nr(u,e):u instanceof Set&&e instanceof Set?Fr(u,e):u instanceof Map&&e instanceof Map?kr(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)},Nr=(u,e,t=le)=>{let r=u.length;if(r===e.length)for(;r-- >0&&t(u[r],e[r]););return r<0},Fr=(u,e,t=le)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),kr=(u,e,t=le)=>u.size===e.size&&t([...u].sort(),[...e].sort()),Dr=(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 It=class{value;constructor(e){this.value=e}deref(){return this.value}};var Zt=u=>u instanceof It;var et=class u{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Jt("next",this._head)}reverseIterator(){return Jt("prev",this.tail)}clear(){this.release()}compare(e,t=Ae){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||Kt(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||Ae;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&&!Zt(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&&Bt(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*Jt(u,e){for(;e;)yield e.value,e=e[u]}var tt=class u extends et{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new u(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new u}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(je(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(je(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new u,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==s&&n.next?i(n.next):void 0}});return r?i(r):void 0}shuffle(e,t=Vt){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)&&Yt("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=Ae){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),je(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new u;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let n of r)this.insertBefore(s,n);else for(let n of r)this.push(n);return i}};var rt=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 tt,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 ue=class u extends rt{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 At=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var Re=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.client.readContract({abi:At,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:At,address:e,functionName:"decimals"}),this.client.getBlock()]),[n,o,a,l]=r,c=i.number-(i.timestamp-l)/BigInt(t),m=Number(c);return{price:o,decimals:s,updatedAt:m<0?0:m}}};var U=class extends q{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new ue(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=re(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new Re(t)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let r=[];try{let i=this.subscribePoolChange(t);r.push(i)}catch{}if(t.type==="Aave")return r;let s=this.subscribeTokensPoolBalance(t);if(r.push(s),this.hasSystemAsset(t)){let i=this.subscribeSystemPoolBalance(t);r.push(i)}if(this.hasErc20Asset(t)){let i=this.subscribeErc20PoolBalance(t);r.push(i)}return this.subscribeLog(t),r}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,i])=>{let n=e.tokens.findIndex(o=>o.id==s);n>=0&&t(e,s)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(i=>i.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};var Cr=["Supply","Withdraw","Repay","Borrow"],_e=class extends U{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:i})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t,r){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let r=e+"/"+t;return(0,er.encodeAddress)((0,tr.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,""),g=c.replace(/,/g,"");(m===r.id||g===r.id)&&(this.log(`Sync AAVE [router:Executed] :: ${m}:${g}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=o.data.toHuman();try{let{eventName:c,args:m}=(0,rr.decodeEventLog)({abi:Ye,topics:l.topics,data:l.data});Cr.includes(c)&&m.reserve.toLowerCase()===s.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(n=>{let o=n.id===t.id?s.toString():i.toString();return{...n,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?Ot(e.location,"accountKey20").accountKey20.key:z.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};var X=require("@galacticcouncil/math-lbp"),W=class{static getSpotPrice(e,t,r,s,i){return(0,X.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,X.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,X.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,X.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,X.calculate_pool_trade_fee)(e,t,r)}};var P=class u{static toPct(e){let[t,r]=e;return u.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return u.safeDivide(t,r)}static fromPermill(e){return[e,1e6]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,r=12){let s=10**r;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};var Ee=class 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=P.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=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=W.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),R(D,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=W.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),R(D,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=W.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var Ne=class extends U{MAX_FINAL_WEIGHT=R(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());this.poolsData.set(i.toString(),o);let[c,m]=o.fee;return{address:a,type:"Lbp",fee:P.fromRate(c.toNumber(),m.toNumber()),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t,r){let s=this.pools.find(i=>i.address===r);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}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=W.calculateLinearWeights(s.toString(),i.toString(),o.toString(),a.toString(),r),[g,d]=n,h=g.toString(),b=p(m),y=d.toString(),w=this.MAX_FINAL_WEIGHT.minus(p(b)),[f,T,x]=await Promise.all([this.isRepayFeeApplied(h,l.toString(),c.toString()),this.getBalance(e,h),this.getBalance(e,y)]);return{repayFeeApply:f,tokens:[{id:h,weight:b,balance:T.toString()},{id:y,weight:w,balance:x.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.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(){let[e,t]=this.api.consts.lbp.repayFee;return P.fromRate(e.toNumber(),t.toNumber())}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toNumber(),t=this.api.consts.lbp.maxOutRatio.toNumber(),r=this.api.consts.lbp.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var B=require("@galacticcouncil/math-omnipool");var _=class{static calculateSpotPrice(e,t,r,s){return(0,B.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,B.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,n,o,a,l){return(0,B.calculate_in_given_out)(e,t,r,s,i,n,o,a,l)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,B.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,n,o,a,l){return(0,B.calculate_out_given_in)(e,t,r,s,i,n,o,a,l)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,B.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculateShares(e,t,r,s){return(0,B.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,n,o,a){return(0,B.calculate_liquidity_out)(e,t,r,s,i,n,o,a)}static calculateLiquidityLRNAOut(e,t,r,s,i,n,o,a){return(0,B.calculate_liquidity_lrna_out)(e,t,r,s,i,n,o,a)}static calculateCapDifference(e,t,r,s){let i=(0,v.BigNumber)(t),n=(0,v.BigNumber)(e),o=(0,v.BigNumber)(s),l=(0,v.BigNumber)(r).shiftedBy(-18);if(i.div(o).lt(l)){let m=l.times(o).minus(i).times(n),g=i.times((0,v.BigNumber)(1).minus(l));return m.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return(0,B.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,B.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,B.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,B.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,B.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,r,s,i,n,o,a,l,c,m){return(0,B.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,B.recalculate_protocol_fee)(e,t,r,s,i,n,o,a,l,c,m)}static verifyAssetCap(e,t,r,s){return(0,B.verify_asset_cap)(e,t,r,s)}};var Fe=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(4),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 g=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(g)&&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(4),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 g=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(g)&&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?P.toRaw(r.assetFee).toString():S.toString(),r?P.toRaw(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateLrnaInGivenOut(e,t,r){let s=_.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=_.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():S.toString(),r?P.toRaw(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenLrnaIn(e,t,r){let s=_.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=_.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=_.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=_.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=_.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var nr=require("@polkadot/util-crypto"),or=require("@polkadot/util");var sr="omnipool",ir="Short",ke=class extends U{dynamicFees=new Map;oracles=new Map;memQueryCache=new ue(null,{ttl:6*1e3});memOracleQuery=re(e=>{this.log("Fetching oracle price for",e);let t=e.split(":");return this.api.query.emaOracle.oracles(sr,t,ir)},this.memQueryCache);memFeesQuery=re(e=>(this.log("Fetching dyn fees for",e),this.api.query.dynamicFees.assetFee(e)),this.memQueryCache);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:g,cap:d,protocolShares:h}=l.unwrap(),b=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:g.bits.toNumber(),balance:b.toString(),cap:p(d.toString()),protocolShares:p(h.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 getDynamicFees(e){return this.dynamicFees.has(e)?this.dynamicFees.get(e):this.memFeesQuery(e)}async getOraclePrice(e){let r=this.getOracleKey(e).join(":");return this.oracles.has(r)?this.oracles.get(r):this.memOracleQuery(r)}async getPoolFees(e,t,r){let s=t.assetOut,i=t.assetIn,[n,o,a]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[l,c,m]=this.getAssetFee(t,e,n,o),[g,d,h]=i===Se?[0,0,0]:this.getProtocolFee(t,e,n,a),b=l+g,y=m+h;return{assetFee:P.fromPermill(c),protocolFee:P.fromPermill(d),min:P.fromPermill(b),max:P.fromPermill(y)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(a=>a.id),r=[],s=await this.api.query.omnipool.assets.multi(t,a=>{e.tokens=a.map((l,c)=>{let m=e.tokens[c];if(l.isNone)return m;let g=l.unwrap();return this.updateTokenState(m,g)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,a=>{a.forEach((l,c)=>{let m=t[c];this.dynamicFees.set(m,l)})});r.push(i);let n=t.map(a=>{let l=this.getOracleKey(a);return[sr,l,ir]}),o=await this.api.query.emaOracle.oracles.multi(n,a=>{a.forEach(async(l,c)=>{let m=n[c],[g,d,h]=m;this.oracles.set(d.join(":"),l)})});return r.push(o),()=>{for(let a of r)try{a()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}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=P.fromPermill(o.toNumber()),g=P.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=s.unwrap(),{assetFee:h,timestamp:b}=r.unwrap(),y=Math.max(1,t-b.toNumber()),w=d.volume.bIn.toString(),f=d.volume.bOut.toString(),T=d.liquidity.b.toString();i===k&&(w=d.volume.aIn.toString(),f=d.volume.aOut.toString(),T=d.liquidity.a.toString());let x=P.fromPermill(h.toNumber()),I=_.recalculateAssetFee(w,f,T,"9",n.toString(),P.toRaw(x).toString(),y.toString(),P.toRaw(m).toString(),P.toRaw(g).toString(),l.toString(),c.toString());return[o.toNumber(),Number(I)*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=P.fromPermill(o.toNumber()),g=P.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=s.unwrap(),{protocolFee:h,timestamp:b}=r.unwrap(),y=Math.max(1,t-b.toNumber()),w=d.volume.bIn.toString(),f=d.volume.bOut.toString(),T=d.liquidity.b.toString();i===k&&(w=d.volume.aIn.toString(),f=d.volume.aOut.toString(),T=d.liquidity.a.toString());let x=P.fromPermill(h.toNumber()),I=_.recalculateProtocolFee(w,f,T,"9",n.toString(),P.toRaw(x).toString(),y.toString(),P.toRaw(m).toString(),P.toRaw(g).toString(),l.toString(),c.toString());return[o.toNumber(),Number(I)*1e6,a.toNumber()]}getOracleKey(e){return e===k?[k,Se]:[Se,e]}getPoolId(){return(0,nr.encodeAddress)((0,or.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toNumber(),t=this.api.consts.omnipool.maxOutRatio.toNumber(),r=this.api.consts.omnipool.minimumTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var E=require("@galacticcouncil/math-xyk"),V=class{static getSpotPrice(e,t,r){return(0,E.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,E.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,E.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,E.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,E.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,E.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,E.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,E.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,E.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,E.calculate_liquidity_out_asset_b)(e,t,r,s)}};var De=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=P.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=P.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=V.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=V.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=V.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=R(D,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=V.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=R(D,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=V.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var Ce=class extends U{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[n,o]=s.unwrap(),[a,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,r){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){let[e,t]=this.api.consts.xyk.getExchangeFee;return P.fromRate(e.toNumber(),t.toNumber())}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toNumber(),t=this.api.consts.xyk.maxOutRatio.toNumber(),r=this.api.consts.xyk.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};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 recalculatePegs(e,t,r,s,i){let n=(0,N.recalculate_peg)(e,t,r,s,i);return JSON.parse(n)}};var Me=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=i.minus(s),o=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount"),{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(4),a=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:a}}calculateIn(e,t,r){let s=C.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateAddOneAsset(e,t,r){let s=C.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateSharesForAmount(e,t,r){let s=C.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=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=R(D,e.decimalsIn-e.decimalsOut);return p(t).div(s).decimalPlaces(0,1)}let r=R(D,18-e.decimalsIn);return p(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=C.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateWithdrawOneAsset(e,t,r){let s=C.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateShares(e,t,r){let s=C.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=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=R(D,e.decimalsOut-e.decimalsIn);return p(t).div(s).decimalPlaces(0,1)}let r=R(D,18-e.decimalsOut);return p(t).div(r).decimalPlaces(0,1)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};var st=require("@polkadot/util-crypto");var Le=class extends U{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[n]},o])=>{try{let a=o.unwrap(),l=n.toString(),c=this.getPoolAddress(l),[m,g,d]=await Promise.all([this.getPoolDelta(l,a,r.toString()),this.getPoolTokens(c,l,a),this.getPoolPegs(l,a,r.toString())]);return g.push({id:l,tradeable:15,balance:m.totalIssuance}),this.stablePools.set(c,a),{address:c,id:l,type:"Stableswap",fee:P.fromPermill(a.fee.toNumber()),tokens:g,...m,...d,...this.getPoolLimits()}}catch(a){return console.warn(`Skipping pool ${n.toString()}
|
|
2
|
-
`,String(a)),null}});return(await Promise.all(s)).filter(n=>n!==null)}async getPoolFees(e,t,r){return{fee:this.pools.find(i=>i.address===r).pegsFee}}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)]),o=e.tokens.map(a=>a.id===e.id?{...a,balance:i.totalIssuance}:a);Object.assign(e,{tokens:o},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 n=>{let[o,a]=await Promise.all([this.api.query.stableswap.assetTradability(t,n.toString()),this.getBalance(e,n.toString())]);return{id:n.toString(),tradeable:o.bits.toNumber(),balance:a.toString()}});return Promise.all(i)}getPoolDefaultPegs(e){let t=e.fee,r=C.defaultPegs(e.assets.length);return{pegsFee:P.fromPermill(t.toNumber()),pegs:r}}async getPoolPegs(e,t,r){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getPoolDefaultPegs(t);let i=s.unwrap(),n=await this.getLatestPegs(t,i,r),o=this.getRecentPegs(i),a=P.fromPermill(i.maxPegUpdate.toNumber()),l=P.fromPermill(t.fee.toNumber()),[c,m]=C.recalculatePegs(JSON.stringify(o),JSON.stringify(n),r,P.toRaw(a).toString(),P.toRaw(l).toString()),g=Number(c)*1e6;return{pegsFee:P.fromPermill(g),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,g=[m.toString(),i[a]].map(f=>Number(f)).sort((f,T)=>f-T),d=await this.api.query.emaOracle.oracles(l,g,c),[{price:h,updatedAt:b}]=d.unwrap(),y=h.n.toString(),w=h.d.toString();return m.toString()===g[0].toString()?[[y,w],b.toString()]:[[w,y],b.toString()]}else if(o.isMmOracle){let l=o.asMmOracle,{price:c,decimals:m,updatedAt:g}=await this.mmOracle.getData(l.toString()),d=10**m;return[[c.toString(),d.toString()],g.toString()]}else{if(o.isValue)return[o.asValue.map(l=>l.toString()),r];throw Error(o.type+" is not supported")}});return Promise.all(n)}getPoolAddress(e){let t=Number(e),r=C.getPoolAddress(t);return(0,st.encodeAddress)((0,st.blake2AsHex)(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toNumber()}}};var ce=class extends L{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];block=0;disconnectSubscribeNewHeads=null;memRegistry=re(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new Z(this.api),this.aaveClient=new _e(this.api,t),this.xykClient=new Ce(this.api,t),this.omniClient=new ke(this.api,t),this.lbpClient=new Ne(this.api,t),this.stableClient=new Le(this.api,t),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient],this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r})}onNewBlock(e){this.block=e}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e){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(),this.disconnectSubscribeNewHeads?.()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(this.block,e,t.address);case"Xyk":return this.xykClient.getPoolFees(this.block,e,t.address);case"Omnipool":return this.omniClient.getPoolFees(this.block,e,t.address);case"Lbp":return this.lbpClient.getPoolFees(this.block,e,t.address);case"Stableswap":return this.stableClient.getPoolFees(this.block,e,t.address);default:throw new Te(t.type)}}};var me=class extends ce{feeCache=new Map;constructor(e,t){super(e,t)}onNewBlock(e){super.onNewBlock(e),this.feeCache.clear()}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);let s=super.getPoolFees(e,t);return this.feeCache.set(r,s),s}async destroy(){this.feeCache.clear(),super.destroy()}};var pe=class{static get(e){switch(e.type){case"Aave":return Ie.fromPool(e);case"Xyk":return De.fromPool(e);case"Omnipool":return Fe.fromPool(e);case"Lbp":return Ee.fromPool(e);case"Stableswap":return Me.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var ar=require("@noble/hashes/sha256"),lr=require("@noble/hashes/utils");function Rt(u){let e=u.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=(0,ar.sha256)(t);return(0,lr.bytesToHex)(r)}var qe=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 Mr=7,Ue=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 qe,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let o=i.dequeue();if(!o||o.length>Mr)continue;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}findShortestPaths(e,t,r){let s=[],i=new qe,n=[];n.push([t,""]),i.enqueue(n);let o=1/0;for(;i.size()>0;){let a=i.dequeue();if(!a)continue;let l=a[a.length-1];if(l[0]===r){a.length<o?(o=a.length,s.length=0,s.push(a)):a.length===o&&s.push(a);continue}let c=e.get(l[0]);for(let m of c??[])this.isNotVisited(m,a)&&i.enqueue([...a,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 _t(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 Ge=class{getProposals(e,t,r){let s=r.filter(f=>f.type==="Xyk"),i=r.filter(f=>f.type!=="Xyk"),n=parseInt(e),o=parseInt(t),a=new Set(i.map(f=>f.tokens).flat().map(f=>f.id)),l=a.has(e),c=a.has(t),m=new Ue,g=f=>{let T=_t(f),x=Object.keys(T),I=x.flatMap(A=>T[A]);return m.buildAndPopulateGraph(x,I)};if(!l&&!c){let f=s.filter(I=>I.tokens.find(A=>A.id===e)||I.tokens.find(A=>A.id===t)),T=g(f),x=m.findPaths(T,n,o);return this.parsePaths(x)}if(l&&c){let f=g(i),T=m.findShortestPaths(f,n,o);return this.parsePaths(T)}let d=l?t:e,h=s.filter(f=>f.tokens.some(T=>T.id===d)),b=[...i,...h],y=g(b),w=m.findPaths(y,n,o);return this.parsePaths(w)}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;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new Ge,this.routeProposals=new Map,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(),t=this.getAssets(e);return[...new Map(t).values()]}async getRoutes(e,t){let r=await this.getPools();return this.validateInput(e,t,r),this.getPaths(e,t,r)}validateInput(e,t,r){if(r.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(r);if(s.get(e)===null)throw new Error(e+" is not supported asset");if(s.get(t)===null)throw new Error(t+" is not supported asset");return this.toPoolsMap(r)}getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r){let s=this.toPoolsMap(r);return this.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}getProposals(e,t,r){let s=`${e}->${t}::${Rt(r)}`;if(this.routeProposals.has(s))return this.routeProposals.get(s);let i=this.routeSuggester.getProposals(e,t,r);return this.routeProposals.set(s,i),i}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,pe.get(t)]))}toHops(e,t){return e.map(([r,s,i])=>{let n=t.get(r);return{poolAddress:r,poolId:n?.id,pool:n?.type,assetIn:s,assetOut:i}})}};var Lr=p("100");function qr(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 Et(u,e){return D.minus(e.div(u)).multipliedBy(100).decimalPlaces(4)}function Nt(u,e){return e.div(u).minus(D).multipliedBy(100).decimalPlaces(4)}function J(u,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),u.div(Lr).multipliedBy(e).decimalPlaces(0,1)}var it=(t=>(t.Buy="Buy",t.Sell="Sell",t))(it||{}),nt=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(nt||{}),Ft=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(Ft||{});var he=class extends de{async loadRouteContext(e,t){let r=await super.getPools(),s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(i.length===0)throw new Oe(e,t);return{paths:i,pools:r,poolsMap:s}}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,n=s[s.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[r,s]}}getPoolFeeRange(e){let t=e.min?P.toPct(e.min):void 0,r=e.max?P.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),o;if(s)o=await this.toSellSwaps(r,s,n);else{let x=i.map(async A=>await this.toSellSwaps(r,A,n)),I=await Promise.all(x);o=this.findBestSellRoute(I)}let a=o[0],l=o[o.length-1],c=this.isDirectTrade(o),m=o.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,I)=>x.multipliedBy(I)),g=R(m,l.assetOutDecimals),d=c?l.calculatedOut:this.calculateDelta0Y(a.amountIn,o,n),h=l.amountOut,b=c?l.tradeFeePct:Et(d,h).toNumber(),y=d.minus(h),w=this.getRouteFeeRange(o),f=a.amountIn.shiftedBy(-1*a.assetInDecimals).multipliedBy(g),T=ge(d,f);return{type:"Sell",amountIn:a.amountIn,amountOut:l.amountOut,spotPrice:g,tradeFee:y,tradeFeePct:b,tradeFeeRange:w,priceImpactPct:T.toNumber(),swaps:o,toHuman(){return{type:"Sell",amountIn:O(a.amountIn,a.assetInDecimals),amountOut:O(l.amountOut,l.assetOutDecimals),spotPrice:O(g,l.assetOutDecimals),tradeFee:O(y,l.assetOutDecimals),tradeFeePct:b,tradeFeeRange:w,priceImpactPct:T.toNumber(),swaps:o.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=R(p(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:m,calculatedOut:g,feePct:d,errors:h}=o.validateAndSell(a,l,c),b=this.getPoolFeeRange(c),y=o.spotPriceOutGivenIn(a),w=l.shiftedBy(-1*a.decimalsIn).multipliedBy(y),f=ge(g,w);s.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,amountOut:m,calculatedOut:g,spotPrice:y,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:h,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:O(l,a.decimalsIn),amountOut:O(m,a.decimalsOut),calculatedOut:O(g,a.decimalsOut),spotPrice:O(y,a.decimalsOut),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:h}}})}return s}async getMostLiquidRoute(e,t){let{paths:r,pools:s,poolsMap:i}=await this.loadRouteContext(e,t),l=s.filter(d=>d.tokens.some(h=>h.id===e)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(h=>h.id===e)).map(d=>d.map(h=>p(h.balance).shiftedBy(-1*h.decimals)).reduce((h,b)=>h.plus(b))).sort((d,h)=>h.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=r.map(async d=>await this.toSellSwaps(l,d,i)),m=await Promise.all(c);return this.findBestSellRoute(m).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r;try{r=await this.loadRouteContext(e,t)}catch{return Promise.resolve(void 0)}let{poolsMap:s}=r,i=await this.getMostLiquidRoute(e,t),n=await this.toSellSwaps("1",i,s),o=n.map(c=>c.spotPrice.shiftedBy(-1*c.assetOutDecimals)).reduce((c,m)=>c.multipliedBy(m)),a=n[n.length-1].assetOutDecimals;return{amount:R(o,a),decimals:a}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,n=s[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),o;if(s)o=await this.toBuySwaps(r,s,n);else{let x=i.map(async A=>await this.toBuySwaps(r,A,n)),I=await Promise.all(x);o=this.findBestBuyRoute(I)}let a=o[o.length-1],l=o[0],c=this.isDirectTrade(o),m=o.map(x=>x.spotPrice.shiftedBy(-1*x.assetInDecimals)).reduce((x,I)=>x.multipliedBy(I)),g=R(m,l.assetInDecimals),d=c?l.calculatedIn:this.calculateDelta0X(a.amountOut,o,n),h=l.amountIn,b=c?l.tradeFeePct:Nt(d,h).toNumber(),y=h.minus(d),w=this.getRouteFeeRange(o),f=a.amountOut.shiftedBy(-1*a.assetOutDecimals).multipliedBy(g),T;return d.isZero()?T=-100:T=ge(f,d).toNumber(),{type:"Buy",amountOut:a.amountOut,amountIn:l.amountIn,spotPrice:g,tradeFee:y,tradeFeePct:b,tradeFeeRange:w,priceImpactPct:T,swaps:o,toHuman(){return{type:"Buy",amountOut:O(a.amountOut,a.assetOutDecimals),amountIn:O(l.amountIn,l.assetInDecimals),spotPrice:O(g,l.assetInDecimals),tradeFee:O(y,l.assetInDecimals),tradeFeePct:b,tradeFeeRange:w,priceImpactPct:T,swaps:o.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=R(p(e),a.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:m,calculatedIn:g,feePct:d,errors:h}=o.validateAndBuy(a,l,c),b=this.getPoolFeeRange(c),y=o.spotPriceInGivenOut(a),w=l.shiftedBy(-1*a.decimalsOut).multipliedBy(y),f;g.isZero()?f=-100:f=ge(w,g).toNumber(),s.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:m,amountOut:l,calculatedIn:g,spotPrice:y,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f,errors:h,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:O(m,a.decimalsIn),amountOut:O(l,a.decimalsOut),calculatedIn:O(g,a.decimalsIn),spotPrice:O(y,a.decimalsIn),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f,errors:h}}})}return s}};var ur=6e3,cr=p(1e15),We=6,kt=-5,Dt=6*60*60*1e3;var mr=6;var G=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:i})=>s==="Stableswap"?{pool:{Stableswap:i},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var ye=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??ur,minBudgetInNative:t.minBudgetInNative??cr})}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],g=l[l.length-1],{assetInDecimals:d}=m,{assetOutDecimals:h}=g,b=Math.abs(c),y=this.getMinimumTradeCount(a,n),w=this.getOptimalTradeCount(b),f=i?Math.round(s/i):w,T=Math.ceil(s/y),x=Math.round(s/w),I=Math.round(s/f),A=a.dividedBy(f).decimalPlaces(0,1),M=await this.router.getBestSell(e,t,O(A,d)),H=a.isLessThan(n),He=[];H&&He.push("OrderTooSmall");let ze=M.amountOut.multipliedBy(f),lt=this.toBlockPeriod(I),ut=M.tradeFee.multipliedBy(f),ct=G.build(l),Xe={assetIn:e,assetOut:t,errors:He,frequencyMin:T,frequencyOpt:x,frequency:I,tradeCount:f,tradeFee:ut,tradeImpactPct:M.priceImpactPct,tradePeriod:lt,tradeRoute:ct,type:"Dca"};return{...Xe,amountIn:a,amountOut:ze,tradeAmountIn:M.amountIn,tradeAmountOut:M.amountOut,toHuman(){return{...Xe,amountIn:O(a,d),amountOut:O(ze,h),tradeAmountIn:O(M.amountIn,d),tradeAmountOut:O(M.amountOut,h)}}}}async getMinimumOrderBudget(e){if(k===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(k,e);if(t)return this.minOrderBudget.times(t.amount).div(p(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:o,priceImpactPct:a}=i,l=o[0],c=o[o.length-1],{assetInDecimals:m}=l,{assetOutDecimals:g}=c,d=Math.abs(a),h=this.getTwapTradeCount(d),b=n.dividedBy(h).decimalPlaces(0,1),y=await this.router.getBestSell(l.assetIn,c.assetOut,O(b,m)),w=h===1,f=n.isLessThan(s),T=y.priceImpactPct<kt,x=[];f||w?x.push("OrderTooSmall"):T&&x.push("OrderImpactTooBig");let I=y.amountOut.multipliedBy(h),A=y.tradeFee.multipliedBy(h),M=G.build(o),H={assetIn:e,assetOut:t,errors:x,tradeCount:h,tradeImpactPct:y.priceImpactPct,tradePeriod:We,tradeRoute:M,type:"TwapSell"};return{...H,amountIn:n,amountOut:I,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:A,toHuman(){return{...H,amountIn:O(n,m),amountOut:O(I,g),tradeAmountIn:O(y.amountIn,m),tradeAmountOut:O(y.amountOut,g),tradeFee:O(A,g)}}}}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:g}=c,d=Math.abs(a),h=this.getTwapTradeCount(d),b=n.dividedBy(h).decimalPlaces(0,1),y=await this.router.getBestBuy(l.assetIn,c.assetOut,O(b,g)),w=y.amountIn.multipliedBy(h),f=h===1,T=w.isLessThan(s),x=y.priceImpactPct<kt,I=[];T||f?I.push("OrderTooSmall"):x&&I.push("OrderImpactTooBig");let A=y.tradeFee.multipliedBy(h),M=G.build(o),H={assetIn:e,assetOut:t,errors:I,tradeCount:h,tradeImpactPct:y.priceImpactPct,tradePeriod:We,tradeRoute:M,type:"TwapBuy"};return{...H,amountIn:w,amountOut:n,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:A,toHuman(){return{...H,amountIn:O(w,m),amountOut:O(n,g),tradeAmountIn:O(y.amountIn,m),tradeAmountOut:O(y.amountOut,g),tradeFee:O(A,m)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>Dt){let s=Dt/(this.blockTime*We);return Math.round(s)}return t}getTwapExecutionTime(e){return e*We*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,mr)}};var fe=class extends L{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new q(e),this.aaveUtils=new Q(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),be)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var ot=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,a=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,n)).amount.isGreaterThanOrEqualTo(a)),l&&e.isGreaterThanOrEqualTo(a)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=J(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(),G.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=J(t,this.slippagePct),o=s.assetIn,a=i.assetOut,l=t.minus(n),c;if(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(),G.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let g=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSellAll",g,be)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=J(e,this.slippagePct),n=r.assetIn,o=s.assetOut,a=e.minus(i),l=this.api.tx.router.sellAll(n,o,a.toFixed(),G.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let m=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",m,be)}return this.wrapTx("RouterSellAll",l)}};var at=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=J(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=J(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 Pe=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new ot(this.api,this.evm).setTrade(e)}order(e){return new at(this.api,this.evm).setOrder(e)}};function Ur(u){let e=new ae(u),t=new Be(u),r=new me(u,t),s=new Q(t),i=new he(r),n=new ye(i,{blockTime:e.blockTime,minBudgetInNative:e.minOrderBudget});return{api:{aave:s,router:i,scheduler:n},client:{asset:new Z(u),balance:new q(u),balanceV2:new oe(u)},ctx:{pool:r},evm:t,tx:new Pe(u,t),destroy:()=>{r.destroy()}}}0&&(module.exports={AaveClient,AavePool,AavePoolClient,AaveUtils,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BalanceClientV2,BigNumber,CachingPoolService,ChainParams,DECIMAL_PLACES,ERC20,EvmClient,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,ONE,OmniMath,OmniPool,OmniPoolClient,PERMILL_DENOMINATOR,PolkadotApiClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StableSwapClient,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeOrderError,TradeOrderType,TradeRouteBuilder,TradeRouter,TradeScheduler,TradeType,TxBuilderFactory,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,createChain,createSdkContext,findNestedKey,findNestedObj,getFraction,hashPools,isEvmAccount,isEvmAddress,isSs58Address,scale,toBn,toDecimals});
|
|
1
|
+
"use strict";var mt=Object.defineProperty;var fr=Object.getOwnPropertyDescriptor;var Pr=Object.getOwnPropertyNames;var br=Object.prototype.hasOwnProperty;var Sr=(u,e)=>{for(var t in e)mt(u,t,{get:e[t],enumerable:!0})},xr=(u,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pr(e))!br.call(u,s)&&s!==t&&mt(u,s,{get:()=>e[s],enumerable:!(r=fr(e,s))||r.enumerable});return u};var vr=u=>xr(mt({},"__esModule",{value:!0}),u);var Gr={};Sr(Gr,{AaveClient:()=>ie,AavePool:()=>Ie,AavePoolClient:()=>_e,AaveUtils:()=>Q,AssetClient:()=>Z,AssetNotFound:()=>St,BASILISK_PARACHAIN_ID:()=>es,BalanceClient:()=>q,BalanceClientV2:()=>ae,BigNumber:()=>v.BigNumber,CachingPoolService:()=>me,ChainParams:()=>oe,DECIMAL_PLACES:()=>Gt,ERC20:()=>z,EvmClient:()=>Be,FarmClient:()=>Ve,H160:()=>te,HUB_ASSET_ID:()=>Se,HYDRADX_PARACHAIN_ID:()=>ts,HYDRADX_SS58_PREFIX:()=>K,INFINITY:()=>wr,LbpMath:()=>W,LbpPool:()=>Ee,LbpPoolClient:()=>Ne,ONE:()=>D,OmniMath:()=>_,OmniPool:()=>Fe,OmniPoolClient:()=>ke,PERMILL_DENOMINATOR:()=>ee,PolkadotApiClient:()=>L,PoolConfigNotFound:()=>bt,PoolError:()=>se,PoolFactory:()=>pe,PoolNotFound:()=>Te,PoolService:()=>ce,PoolType:()=>F,ProviderConfigNotFound:()=>wt,RUNTIME_DECIMALS:()=>xe,RouteNotFound:()=>Oe,Router:()=>de,SYSTEM_ASSET_DECIMALS:()=>Mt,SYSTEM_ASSET_ID:()=>k,StableMath:()=>C,StableSwap:()=>Me,StableSwapClient:()=>Le,StorageConfigNotFound:()=>xt,SubscriptionNotSupported:()=>vt,TRADEABLE_DEFAULT:()=>ve,TradeOrderError:()=>Ft,TradeOrderType:()=>nt,TradeRouteBuilder:()=>G,TradeRouter:()=>he,TradeScheduler:()=>ye,TradeType:()=>it,TxBuilderFactory:()=>Pe,XykMath:()=>V,XykPool:()=>De,XykPoolClient:()=>Ce,ZERO:()=>S,bnFormatter:()=>Rr,bnum:()=>p,calculateBuyFee:()=>Nt,calculateDiffToAvg:()=>qr,calculateDiffToRef:()=>ge,calculateSellFee:()=>Et,createChain:()=>Tt,createSdkContext:()=>Ur,findNestedKey:()=>Ot,findNestedObj:()=>Ar,getFraction:()=>J,hashPools:()=>Rt,isEvmAccount:()=>Lt,isEvmAddress:()=>qt,isSs58Address:()=>Ut,scale:()=>R,toBn:()=>Tr,toDecimals:()=>O});module.exports=vr(Gr);var Ye=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var pt=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Ct="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",dt="0x112b087b60C1a166130d59266363C45F8aa99db0",gt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",be=1000000n;var Kr=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ie=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:pt,address:dt,args:[gt],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:pt,address:dt,args:[gt,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:Ye,address:Ct,args:[e],functionName:"getUserAccountData"})}};var j=require("@polkadot/util-crypto"),ne=require("@polkadot/util"),Y=require("buffer");var es=2090,ee=1e6,Se="1",ts=2034,K=63,xe=18,k="0",Mt=12,ve=15;var ht="ETH\0";function Lt(u){if(!u)return!1;try{let e=(0,j.decodeAddress)(u,!0),t=Y.Buffer.from(ht);return Y.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function qt(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function Ut(u){try{let e=(0,ne.isHex)(u)?(0,ne.hexToU8a)(u):(0,j.decodeAddress)(u);return(0,j.encodeAddress)(e),!0}catch{return!1}}var te=class u{static toAccount=e=>{let t=Y.Buffer.from(e.slice(2),"hex"),r=Y.Buffer.from(ht);return(0,j.encodeAddress)(new Uint8Array(Y.Buffer.concat([r,t,Y.Buffer.alloc(8)])),63)};static fromAccount=e=>{let t=(0,j.decodeAddress)(e),r=Y.Buffer.from(ht),s=t.slice(r.length,-8);return"0x"+Y.Buffer.from(s).toString("hex")};static fromSS58=e=>{let r=(0,j.decodeAddress)(e).slice(0,20);return(0,ne.u8aToHex)(r)};static fromAny=e=>{if(qt(e))return e;if(Lt(e))return u.fromAccount(e);if(Ut(e))return u.fromSS58(e);throw new Error("Unknown address type")}};var we=require("buffer"),z=class{static fromAssetId(e){let t=Number(e),r=we.Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=we.Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=we.Buffer.from("0000000000000000000000000000000100000000","hex"),r=we.Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};var v=require("bignumber.js"),Gt=12;v.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Gt});var S=p(0),D=p(1),wr=p("Infinity");function R(u,e){let t=new v.BigNumber(e.toString()),r=new v.BigNumber(10).pow(t);return u.times(r).decimalPlaces(4)}function p(u){return new v.BigNumber(u.toString())}function Tr(u,e){let t=p(u);return R(t,e)}function O(u,e){return u.shiftedBy(-1*e).toString()}var $e=p("1e27"),Or=p("1.01"),Br=p("31536000"),Q=class{client;constructor(e){this.client=new ie(e)}async getSummary(e){let t=te.fromAny(e),[r,s,i,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[a]=r,[o,l]=s,[c,m,g,d,h,b]=i,y=p(b).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN),w=p(c),f=p(m),T=[];for(let x of o){let I=x.underlyingAsset.toLowerCase(),A=a.find(({underlyingAsset:yr})=>yr.toLowerCase()===I);if(!A)throw new Error("Missing pool reserve for "+I);let M=p(x.scaledATokenBalance),H=p(A.liquidityIndex),He=p(A.liquidityRate),ze=p(A.availableLiquidity),lt=p(A.priceInMarketReferenceCurrency),ut=n+6,ct=this.calculateLinearInterest(He,A.lastUpdateTimestamp,ut),Xe=H.multipliedBy(ct).dividedBy($e).decimalPlaces(0,v.BigNumber.ROUND_DOWN),pr=M.multipliedBy(Xe).dividedBy($e).decimalPlaces(0,v.BigNumber.ROUND_DOWN),dr=p(l!==0&&l===A.eModeCategoryId?A.eModeLiquidationThreshold:A.reserveLiquidationThreshold).div(1e4),gr=A.usageAsCollateralEnabled&&x.usageAsCollateralEnabledOnUser&&p(x.scaledATokenBalance).gt(0),hr=z.toAssetId(I);T.push({aTokenBalance:pr,availableLiquidity:ze,decimals:Number(A.decimals),isCollateral:gr,priceInRef:lt,reserveId:hr,reserveAsset:I,reserveLiquidationThreshold:dr})}return{healthFactor:y.toNumber(),totalCollateral:w,totalDebt:f,reserves:T}}async hasBorrowPositions(e){let t=te.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=te.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,n,a,o,l]=r;return p(l).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),a=z.fromAssetId(t),o=n.find(w=>w.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,isCollateral:c,priceInRef:m,reserveLiquidationThreshold:g}=o,d=R(p(r),l).decimalPlaces(0,1),h=c?d.multipliedBy(m).dividedBy(p(10).pow(l)).decimalPlaces(0,v.BigNumber.ROUND_DOWN):S,b=s.minus(h);return b.lte(0)?0:b.multipliedBy(g).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),a=z.fromAssetId(t),o=n.find(y=>y.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:m}=o,d=R(p(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(p(10).pow(l)).decimalPlaces(0,v.BigNumber.ROUND_DOWN),h=s.plus(d);return h.lte(0)?0:h.multipliedBy(m).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),n=z.fromAssetId(t),a=s.find(o=>o.reserveAsset===n);if(!a)throw new Error("Missing reserve data for "+n);return this.calculateWithdrawMax(a,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let n of r){let a=this.calculateWithdrawMax(n,t,s);n.reserveId&&(i[n.reserveId]=a)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:n,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let g=p(r).minus(Or);if(g.gt(0)){let h=g.multipliedBy(t).dividedBy(o).decimalPlaces(0,v.BigNumber.ROUND_DOWN).dividedBy(a).multipliedBy(p(10).pow(n)).decimalPlaces(0,v.BigNumber.ROUND_DOWN);c=v.BigNumber.minimum(s,h)}else c=S}return{amount:v.BigNumber.minimum(c,i),decimals:n}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?$e:e.multipliedBy(s).dividedBy(Br).plus($e).decimalPlaces(0,v.BigNumber.ROUND_DOWN)}};function Wt(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var bs=require("@galacticcouncil/api-augment/hydradx"),Ss=require("@galacticcouncil/api-augment/basilisk"),L=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Wt(r)&&console.log(e,...t)}};var Z=class extends L{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e==k){let m=this.api.consts.balances.existentialDeposit;return{id:k,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:a,existentialDeposit:o}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:n.toHuman(),isSufficient:a?a.toHuman():!0,location:s?.toJSON(),existentialDeposit:o.toString()}}getBond(e,t,r,s){let[i,n]=s,{assetType:a,isSufficient:o,existentialDeposit:l}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,r),g=n.toNumber(),d=new Intl.DateTimeFormat("en-GB"),h=[c,"Bond",d.format(g)].join(" ");return{id:e,name:h,symbol:c+"b",decimals:m,icon:c,type:a.toString(),isSufficient:o.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:g}}getShares(e,t,r,s){let{assets:i}=s,{name:n,symbol:a,assetType:o,isSufficient:l,existentialDeposit:c}=t,g=i.map(b=>b.toString()).map(b=>{let{symbol:y}=this.getToken(b,t,r);return[b,y]}),d=Object.fromEntries(g),h=Object.values(d);return{id:e,name:h.join(", "),symbol:a?.isSome?a.toHuman():n.toHuman(),decimals:18,icon:h.join("/"),type:o.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),n=r?.find(a=>a.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:n}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,i,n,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),o=this.getSupportedAssets(r),l=this.normalizeMetadata(o,a),c=o.map(([{args:[m]},g])=>{let d=g.unwrap(),h=s.get(m.toString()),{assetType:b}=d;switch(b.toString()){case"Bond":let y=n.get(m.toString());return this.getBond(m.toString(),d,l,y);case"StableSwap":let w=i.get(m.toString());return this.getShares(m.toString(),d,l,w);case"External":return this.getExternal(m.toString(),d,t,h);default:return this.getToken(m.toString(),d,l,h)}});return e?c:c.filter(m=>this.isValidAsset(m))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var q=class extends L{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===k?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(k,this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,a]})=>[n.toString(),a.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let a=[];n.forEach((o,l)=>{let c=this.calculateFreeBalance(o),m=i[l][1];a.push([m,c])}),t(a)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([o,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[o]}])=>o.toString()))(),n=async()=>{let a=await Promise.all(i.map(async o=>[o,await this.getErc20Balance(e,o)]));t(a)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let t=e.free.toString(),r=e.frozen.toString();return(0,v.BigNumber)(t).lt(r)?(0,v.BigNumber)(0):(0,v.BigNumber)(t).minus(r)}};var ae=class extends L{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t===k?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(k,this.calculateBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,a]})=>[n.toString(),a.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let a=[];n.forEach((o,l)=>{let c=i[l][1],m=this.calculateBalance(o);a.push([c,m])}),t(a)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([o,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[o]}])=>o.toString()))(),n=async()=>{let a=await Promise.all(i.map(async o=>[o,await this.getErc20Balance(e,o)]));t(a)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=(0,v.BigNumber)(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),i=t.gte(r)?t.minus(r).toString():"0",n=t.plus(s).toString();return{free:t.toString(),total:n,transferable:i,reserved:s,frozen:r}}};var oe=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 yt=require("@galacticcouncil/math-liquidity-mining"),Ht=require("@polkadot/types"),ft=require("@polkadot/util"),Pt=require("@polkadot/util-crypto");var Ve=class extends L{balanceClient;constructor(e){super(e),this.balanceClient=new q(e)}secondsInYear=new v.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,a=i.unwrap().toString(),o=n.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,o,a)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(o),!1).toString(),h=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:m,potBalance:b.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,a=i.unwrap().toString(),o=n.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,o,a)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(o),!0).toString(),h=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:m,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new v.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),a=n.price.n.toString(),o=n.price.d.toString(),l;return Number(t)<Number(r)?l=(0,yt.fixed_from_rational)(a,o):l=(0,yt.fixed_from_rational)(o,a),l}getGlobalRewardPerPeriod(e,t,r,s){let n=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return n.gte(r)?r:n}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return(0,ft.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Ht.GenericAccountId32(e,this.padEndU8a((0,ft.u8aConcat)(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,Pt.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,Pt.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:a,globalFarm:o,priceAdjustment:l,potBalance:c})=>{let m=new v.BigNumber(o.totalSharesZ.toString()),g=o.plannedYieldingPeriods.toString(),d=new v.BigNumber(o.yieldPerPeriod.toString()),h=new v.BigNumber(o.maxRewardPerPeriod.toString()),b=o.blocksPerPeriod.toString(),y=new v.BigNumber(a.multiplier.toString()).shiftedBy(-18),w=this.secondsInYear.div(new v.BigNumber(r).times(b)),f;if(m.isZero())f=d.times(y).times(w);else{let M=this.getGlobalRewardPerPeriod(m,d,h,l);f=this.getPoolYieldPerPeriod(M,y,m,l).times(w)}let T=new v.BigNumber(o.pendingRewards.toString()).plus(o.accumulatedPaidRewards.toString()),x=h.times(g),I=c?T.plus(c):x;return T.div(I).gte(.999)?S:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((a,o)=>a.plus(o),S).toString():void 0}};var Te=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},bt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Oe=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},St=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},xt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},vt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},wt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var zt=require("viem"),Ir=["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"],Tt=u=>{let t=[u.endpoint,...Ir],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return(0,zt.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1})};var $=require("viem");function Xt(u){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return u.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var Be=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=Tt(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,$.createPublicClient)({chain:this.chain,transport:(0,$.http)()})}getWsProvider(){return(0,$.createPublicClient)({chain:this.chain,transport:Xt(this.wsProvider)})}getSigner(e){return(0,$.createWalletClient)({account:e,chain:this.chain,transport:(0,$.custom)(window.ethereum)})}};var re=(u,e=new Map)=>t=>{let r;return e.has(t)?e.get(t):(e.set(t,r=u(t)),r)};var F=(i=>(i.Aave="Aave",i.LBP="Lbp",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="Xyk",i))(F||{}),se=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(se||{});var Ie=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(o=>[o.id,o])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),a=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:a,assetInED:S,assetOutED:S}}validateAndBuy(e,t,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 R(D,e.decimalsOut)}spotPriceOutGivenIn(e){return R(D,e.decimalsIn)}calculateTradeFee(e,t){return S}};var er=require("@polkadot/util-crypto"),tr=require("@polkadot/util"),rr=require("viem");function Ot(u,e){let t=[];return JSON.stringify(u,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Ar(u,e,t){let r;return JSON.stringify(u,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Rr=(u,e)=>typeof e=="bigint"?e.toString():e;var Ae=(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 Ke=(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 _r=Ke(()=>"illegal argument(s)"),Yt=u=>{throw new _r(u)};var Er=Ke(()=>"index out of bounds"),Bt=u=>{throw new Er(u)},je=(u,e,t)=>(u<e||u>=t)&&Bt(u);var $t=23283064365386963e-26,Qe=class{float(e=1){return this.int()*$t*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*$t-.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 Ze=class extends Qe{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 Vt=new Ze(Math.random);var Kt=u=>u!=null&&typeof u!="function"&&u.length!==void 0;var jt=Object.getPrototypeOf({}),Je="function",Qt="string",le=(u,e)=>{let t;if(u===e)return!0;if(u!=null){if(typeof u.equiv===Je)return u.equiv(e)}else return u==e;if(e!=null){if(typeof e.equiv===Je)return e.equiv(u)}else return u==e;return typeof u===Qt||typeof e===Qt?!1:(t=Object.getPrototypeOf(u),(t==null||t===jt)&&(t=Object.getPrototypeOf(e),t==null||t===jt)?Dr(u,e):typeof u!==Je&&u.length!==void 0&&typeof e!==Je&&e.length!==void 0?Nr(u,e):u instanceof Set&&e instanceof Set?Fr(u,e):u instanceof Map&&e instanceof Map?kr(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)},Nr=(u,e,t=le)=>{let r=u.length;if(r===e.length)for(;r-- >0&&t(u[r],e[r]););return r<0},Fr=(u,e,t=le)=>u.size===e.size&&t([...u.keys()].sort(),[...e.keys()].sort()),kr=(u,e,t=le)=>u.size===e.size&&t([...u].sort(),[...e].sort()),Dr=(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 It=class{value;constructor(e){this.value=e}deref(){return this.value}};var Zt=u=>u instanceof It;var et=class u{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Jt("next",this._head)}reverseIterator(){return Jt("prev",this.tail)}clear(){this.release()}compare(e,t=Ae){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||Kt(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||Ae;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&&!Zt(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&&Bt(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*Jt(u,e){for(;e;)yield e.value,e=e[u]}var tt=class u extends et{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new u(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new u}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(je(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(je(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new u,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==s&&n.next?i(n.next):void 0}});return r?i(r):void 0}shuffle(e,t=Vt){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)&&Yt("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=Ae){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,n=0;for(let o=0;o<t&&(n++,i=i.next,!!i);o++);let a=t;for(;n>0||a>0&&i;){let o;n===0?(o=i,i=i.next,a--):!i||a===0||e(r.value,i.value)<=0?(o=r,r=r.next,n--):(o=i,i=i.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),je(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new u;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let n of r)this.insertBefore(s,n);else for(let n of r)this.push(n);return i}};var rt=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 tt,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 ue=class u extends rt{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 At=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var Re=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.client.readContract({abi:At,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:At,address:e,functionName:"decimals"}),this.client.getBlock()]),[n,a,o,l]=r,c=i.number-(i.timestamp-l)/BigInt(t),m=Number(c);return{price:a,decimals:s,updatedAt:m<0?0:m}}};var U=class extends q{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new ue(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=re(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new Re(t)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let r=[];try{let i=this.subscribePoolChange(t);r.push(i)}catch{}if(t.type==="Aave")return r;let s=this.subscribeTokensPoolBalance(t);if(r.push(s),this.hasSystemAsset(t)){let i=this.subscribeSystemPoolBalance(t);r.push(i)}if(this.hasErc20Asset(t)){let i=this.subscribeErc20PoolBalance(t);r.push(i)}return this.subscribeLog(t),r}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,i])=>{let n=e.tokens.findIndex(a=>a.id==s);n>=0&&t(e,s)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(i=>i.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};var Cr=["Supply","Withdraw","Repay","Borrow"],_e=class extends U{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:i})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t,r){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let r=e+"/"+t;return(0,er.encodeAddress)((0,tr.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:a}=n,o=`${a.section}:${a.method}`;if(o==="router:Executed"){let{assetIn:l,assetOut:c}=a.data.toHuman(),m=l.replace(/,/g,""),g=c.replace(/,/g,"");(m===r.id||g===r.id)&&(this.log(`Sync AAVE [router:Executed] :: ${m}:${g}`),this.updatePoolState(e))}if(o==="evm:Log"){let{log:l}=a.data.toHuman();try{let{eventName:c,args:m}=(0,rr.decodeEventLog)({abi:Ye,topics:l.topics,data:l.data});Cr.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 a=n.id===t.id?s.toString():i.toString();return{...n,balance:a}})}getReserveH160Id(e){return e.type==="Erc20"?Ot(e.location,"accountKey20").accountKey20.key:z.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};var X=require("@galacticcouncil/math-lbp"),W=class{static getSpotPrice(e,t,r,s,i){return(0,X.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,X.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,X.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,X.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,X.calculate_pool_trade_fee)(e,t,r)}};var P=class u{static toPct(e){let[t,r]=e;return u.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return u.safeDivide(t,r)}static fromPermill(e){return[e,1e6]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,r=12){let s=10**r;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};var Ee=class 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,a){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=n,this.repayFeeApply=a}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(o=>[o.id,o])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),a=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:a,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let a=this.calculateTradeFee(t,r),o=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(a),c=this.calculateInGivenOut(e,l),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:o,errors:i}}else{let a=this.calculateInGivenOut(e,t),o=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(o)&&i.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let a=this.calculateOutGivenIn(e,t),o=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(o)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:a,feePct:0,errors:i}}else{let a=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(a,r),l=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=a.minus(o),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=W.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),R(D,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=W.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),R(D,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=W.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var Ne=class extends U{MAX_FINAL_WEIGHT=R(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 a=n.unwrap(),o=i.toString(),l=await this.getPoolDelta(o,a,r.toString());this.poolsData.set(i.toString(),a);let[c,m]=a.fee;return{address:o,type:"Lbp",fee:P.fromRate(c.toNumber(),m.toNumber()),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t,r){let s=this.pools.find(i=>i.address===r);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}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(a=>a.address==e.address);this.pools.splice(n,1)}})}async getPoolDelta(e,t,r){let{start:s,end:i,assets:n,initialWeight:a,finalWeight:o,repayTarget:l,feeCollector:c}=t,m=W.calculateLinearWeights(s.toString(),i.toString(),a.toString(),o.toString(),r),[g,d]=n,h=g.toString(),b=p(m),y=d.toString(),w=this.MAX_FINAL_WEIGHT.minus(p(b)),[f,T,x]=await Promise.all([this.isRepayFeeApplied(h,l.toString(),c.toString()),this.getBalance(e,h),this.getBalance(e,y)]);return{repayFeeApply:f,tokens:[{id:h,weight:b,balance:T.toString()},{id:y,weight:w,balance:x.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t.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(){let[e,t]=this.api.consts.lbp.repayFee;return P.fromRate(e.toNumber(),t.toNumber())}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toNumber(),t=this.api.consts.lbp.maxOutRatio.toNumber(),r=this.api.consts.lbp.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var B=require("@galacticcouncil/math-omnipool");var _=class{static calculateSpotPrice(e,t,r,s){return(0,B.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,B.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,n,a,o,l){return(0,B.calculate_in_given_out)(e,t,r,s,i,n,a,o,l)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,B.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,n,a,o,l){return(0,B.calculate_out_given_in)(e,t,r,s,i,n,a,o,l)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,B.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculateShares(e,t,r,s){return(0,B.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,n,a,o){return(0,B.calculate_liquidity_out)(e,t,r,s,i,n,a,o)}static calculateLiquidityLRNAOut(e,t,r,s,i,n,a,o){return(0,B.calculate_liquidity_lrna_out)(e,t,r,s,i,n,a,o)}static calculateCapDifference(e,t,r,s){let i=(0,v.BigNumber)(t),n=(0,v.BigNumber)(e),a=(0,v.BigNumber)(s),l=(0,v.BigNumber)(r).shiftedBy(-18);if(i.div(a).lt(l)){let m=l.times(a).minus(i).times(n),g=i.times((0,v.BigNumber)(1).minus(l));return m.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return(0,B.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,B.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,B.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,B.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,B.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,r,s,i,n,a,o,l,c,m){return(0,B.recalculate_asset_fee)(e,t,r,s,i,n,a,o,l,c,m)}static recalculateProtocolFee(e,t,r,s,i,n,a,o,l,c,m){return(0,B.recalculate_protocol_fee)(e,t,r,s,i,n,a,o,l,c,m)}static verifyAssetCap(e,t,r,s){return(0,B.verify_asset_cap)(e,t,r,s)}};var Fe=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),a=p(i.balance),o=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:a,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),a=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(4),o=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&o.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(g)&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a.toNumber(),errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),a=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),o=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&o.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(g)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a.toNumber(),errors:o}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=_.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():S.toString(),r?P.toRaw(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateLrnaInGivenOut(e,t,r){let s=_.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=_.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():S.toString(),r?P.toRaw(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenLrnaIn(e,t,r){let s=_.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=_.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=_.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=_.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=_.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var nr=require("@polkadot/util-crypto"),ar=require("@polkadot/util");var sr="omnipool",ir="Short",ke=class extends U{dynamicFees=new Map;oracles=new Map;memQueryCache=new ue(null,{ttl:6*1e3});memOracleQuery=re(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(sr,t,ir)},this.memQueryCache);memFeesQuery=re(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=r.map(async([{args:[o]},l])=>{let{hubReserve:c,shares:m,tradable:g,cap:d,protocolShares:h}=l.unwrap(),b=await this.getBalance(t,o.toString());return{id:o.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:g.bits.toNumber(),balance:b.toString(),cap:p(d.toString()),protocolShares:p(h.toString())}}),a=await Promise.all(n);return a.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:a,...this.getPoolLimits()}]}async getDynamicFees(e){return this.dynamicFees.has(e)?this.dynamicFees.get(e):this.memFeesQuery(e)}async getOraclePrice(e){let r=this.getOracleKey(e).join(":");return this.oracles.has(r)?this.oracles.get(r):this.memOracleQuery(r)}async getPoolFees(e,t,r){let s=t.assetOut,i=t.assetIn,[n,a,o]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[l,c,m]=this.getAssetFee(t,e,n,a),[g,d,h]=i===Se?[0,0,0]:this.getProtocolFee(t,e,n,o),b=l+g,y=m+h;return{assetFee:P.fromPermill(c),protocolFee:P.fromPermill(d),min:P.fromPermill(b),max:P.fromPermill(y)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(o=>o.id),r=[],s=await this.api.query.omnipool.assets.multi(t,o=>{e.tokens=o.map((l,c)=>{let m=e.tokens[c];if(l.isNone)return m;let g=l.unwrap();return this.updateTokenState(m,g)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,o=>{o.forEach((l,c)=>{let m=t[c];this.dynamicFees.set(m,l)})});r.push(i);let n=t.map(o=>{let l=this.getOracleKey(o);return[sr,l,ir]}),a=await this.api.query.emaOracle.oracles.multi(n,o=>{o.forEach(async(l,c)=>{let m=n[c],[g,d,h]=m;this.oracles.set(d.join(":"),l)})});return r.push(a),()=>{for(let o of r)try{o()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:n,protocolShares:a}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(n.toString()),protocolShares:p(a.toString()),tradeable:i.bits.toNumber()}}getAssetFee(e,t,r,s){let{assetOut:i,balanceOut:n}=e,{minFee:a,maxFee:o,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,m=P.fromPermill(a.toNumber()),g=P.fromPermill(o.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),o.toNumber()];let[d]=s.unwrap(),{assetFee:h,timestamp:b}=r.unwrap(),y=Math.max(1,t-b.toNumber()),w=d.volume.bIn.toString(),f=d.volume.bOut.toString(),T=d.liquidity.b.toString();i===k&&(w=d.volume.aIn.toString(),f=d.volume.aOut.toString(),T=d.liquidity.a.toString());let x=P.fromPermill(h.toNumber()),I=_.recalculateAssetFee(w,f,T,"9",n.toString(),P.toRaw(x).toString(),y.toString(),P.toRaw(m).toString(),P.toRaw(g).toString(),l.toString(),c.toString());return[a.toNumber(),Number(I)*1e6,o.toNumber()]}getProtocolFee(e,t,r,s){let{assetIn:i,balanceIn:n}=e,{minFee:a,maxFee:o,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,m=P.fromPermill(a.toNumber()),g=P.fromPermill(o.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),o.toNumber()];let[d]=s.unwrap(),{protocolFee:h,timestamp:b}=r.unwrap(),y=Math.max(1,t-b.toNumber()),w=d.volume.bIn.toString(),f=d.volume.bOut.toString(),T=d.liquidity.b.toString();i===k&&(w=d.volume.aIn.toString(),f=d.volume.aOut.toString(),T=d.liquidity.a.toString());let x=P.fromPermill(h.toNumber()),I=_.recalculateProtocolFee(w,f,T,"9",n.toString(),P.toRaw(x).toString(),y.toString(),P.toRaw(m).toString(),P.toRaw(g).toString(),l.toString(),c.toString());return[a.toNumber(),Number(I)*1e6,o.toNumber()]}getOracleKey(e){return e===k?[k,Se]:[Se,e]}getPoolId(){return(0,nr.encodeAddress)((0,ar.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toNumber(),t=this.api.consts.omnipool.maxOutRatio.toNumber(),r=this.api.consts.omnipool.minimumTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};var E=require("@galacticcouncil/math-xyk"),V=class{static getSpotPrice(e,t,r){return(0,E.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,E.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,E.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,E.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,E.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,E.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,E.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,E.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,E.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,E.calculate_liquidity_out_asset_b)(e,t,r,s)}};var De=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),a=p(i.balance),o=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:a,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),n=P.toPct(r.exchangeFee),a=s.plus(i),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&o.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(c)&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),n=P.toPct(r.exchangeFee),a=s.minus(i),o=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&o.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(c)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:a,feePct:n,errors:o}}calculateInGivenOut(e,t){let r=V.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=V.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=V.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=R(D,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=V.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=R(D,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=V.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var Ce=class extends U{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[n,a]=s.unwrap(),[o,l]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,a.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:o.toString()},{id:a.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t,r){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){let[e,t]=this.api.consts.xyk.getExchangeFee;return P.fromRate(e.toNumber(),t.toNumber())}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toNumber(),t=this.api.consts.xyk.maxOutRatio.toNumber(),r=this.api.consts.xyk.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};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,a){return(0,N.calculate_in_given_out)(e,t,r,s,i,n,a)}static calculateAddOneAsset(e,t,r,s,i,n,a){return(0,N.calculate_add_one_asset)(e,t,r,s,i,n,a)}static calculateSharesForAmount(e,t,r,s,i,n,a){return(0,N.calculate_shares_for_amount)(e,t,r,s,i,n,a)}static calculateOutGivenIn(e,t,r,s,i,n,a){return(0,N.calculate_out_given_in)(e,t,r,s,i,n,a)}static calculateLiquidityOutOneAsset(e,t,r,s,i,n,a){return(0,N.calculate_liquidity_out_one_asset)(e,t,r,s,i,n,a)}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,a,o){return(0,N.calculate_spot_price_with_fee)(e,t,r,s,i,n,a,o)}static recalculatePegs(e,t,r,s,i){let n=(0,N.recalculate_peg)(e,t,r,s,i);return JSON.parse(n)}};var Me=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,a,o,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=a,this.fee=o,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),a=p(i.balance),o=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:a,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:o,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),a=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(4),o=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);return(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:a.toNumber(),errors:o}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),a=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),o=[],l=_.isSellAllowed(e.tradeableIn),c=_.isBuyAllowed(e.tradeableOut);return(!l||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:a.toNumber(),errors:o}}calculateIn(e,t,r){let s=C.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateAddOneAsset(e,t,r){let s=C.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateSharesForAmount(e,t,r){let s=C.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=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=R(D,e.decimalsIn-e.decimalsOut);return p(t).div(s).decimalPlaces(0,1)}let r=R(D,18-e.decimalsIn);return p(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=C.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateWithdrawOneAsset(e,t,r){let s=C.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateShares(e,t,r){let s=C.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=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=R(D,e.decimalsOut-e.decimalsIn);return p(t).div(s).decimalPlaces(0,1)}let r=R(D,18-e.decimalsOut);return p(t).div(r).decimalPlaces(0,1)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};var st=require("@polkadot/util-crypto");var Le=class extends U{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[n]},a])=>{try{let o=a.unwrap(),l=n.toString(),c=this.getPoolAddress(l),[m,g,d]=await Promise.all([this.getPoolDelta(l,o,r.toString()),this.getPoolTokens(c,l,o),this.getPoolPegs(l,o,r.toString())]);return g.push({id:l,tradeable:15,balance:m.totalIssuance}),this.stablePools.set(c,o),{address:c,id:l,type:"Stableswap",fee:P.fromPermill(o.fee.toNumber()),tokens:g,...m,...d,...this.getPoolLimits()}}catch(o){return console.warn(`Skipping pool ${n.toString()}
|
|
2
|
+
`,String(o)),null}});return(await Promise.all(s)).filter(n=>n!==null)}async getPoolFees(e,t,r){return{fee:this.pools.find(i=>i.address===r).pegsFee}}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)]),a=e.tokens.map(o=>o.id===e.id?{...o,balance:i.totalIssuance}:o);Object.assign(e,{tokens:a},i,n)}})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:n,finalBlock:a}=t,o=C.calculateAmplification(s.toString(),i.toString(),n.toString(),a.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:o,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async n=>{let[a,o]=await Promise.all([this.api.query.stableswap.assetTradability(t,n.toString()),this.getBalance(e,n.toString())]);return{id:n.toString(),tradeable:a.bits.toNumber(),balance:o.toString()}});return Promise.all(i)}getPoolDefaultPegs(e){let t=e.fee,r=C.defaultPegs(e.assets.length);return{pegsFee:P.fromPermill(t.toNumber()),pegs:r}}async getPoolPegs(e,t,r){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getPoolDefaultPegs(t);let i=s.unwrap(),n=await this.getLatestPegs(t,i,r),a=this.getRecentPegs(i),o=P.fromPermill(i.maxPegUpdate.toNumber()),l=P.fromPermill(t.fee.toNumber()),[c,m]=C.recalculatePegs(JSON.stringify(a),JSON.stringify(n),r,P.toRaw(o).toString(),P.toRaw(l).toString()),g=Number(c)*1e6;return{pegsFee:P.fromPermill(g),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(([a,o])=>o.toString()),n=s.map(async(a,o)=>{if(a.isOracle){let[l,c,m]=a.asOracle,g=[m.toString(),i[o]].map(f=>Number(f)).sort((f,T)=>f-T),d=await this.api.query.emaOracle.oracles(l,g,c),[{price:h,updatedAt:b}]=d.unwrap(),y=h.n.toString(),w=h.d.toString();return m.toString()===g[0].toString()?[[y,w],b.toString()]:[[w,y],b.toString()]}else if(a.isMmOracle){let l=a.asMmOracle,{price:c,decimals:m,updatedAt:g}=await this.mmOracle.getData(l.toString()),d=10**m;return[[c.toString(),d.toString()],g.toString()]}else{if(a.isValue)return[a.asValue.map(l=>l.toString()),r];throw Error(a.type+" is not supported")}});return Promise.all(n)}getPoolAddress(e){let t=Number(e),r=C.getPoolAddress(t);return(0,st.encodeAddress)((0,st.blake2AsHex)(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toNumber()}}};var ce=class extends L{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];block=0;disconnectSubscribeNewHeads=null;memRegistry=re(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new Z(this.api),this.aaveClient=new _e(this.api,t),this.xykClient=new Ce(this.api,t),this.omniClient=new ke(this.api,t),this.lbpClient=new Ne(this.api,t),this.stableClient=new Le(this.api,t),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient],this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r})}onNewBlock(e){this.block=e}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e){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(),this.disconnectSubscribeNewHeads?.()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(this.block,e,t.address);case"Xyk":return this.xykClient.getPoolFees(this.block,e,t.address);case"Omnipool":return this.omniClient.getPoolFees(this.block,e,t.address);case"Lbp":return this.lbpClient.getPoolFees(this.block,e,t.address);case"Stableswap":return this.stableClient.getPoolFees(this.block,e,t.address);default:throw new Te(t.type)}}};var me=class extends ce{feeCache=new Map;constructor(e,t){super(e,t)}onNewBlock(e){super.onNewBlock(e),this.feeCache.clear()}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);let s=super.getPoolFees(e,t);return this.feeCache.set(r,s),s}async destroy(){this.feeCache.clear(),super.destroy()}};var pe=class{static get(e){switch(e.type){case"Aave":return Ie.fromPool(e);case"Xyk":return De.fromPool(e);case"Omnipool":return Fe.fromPool(e);case"Lbp":return Ee.fromPool(e);case"Stableswap":return Me.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var or=require("@noble/hashes/sha256"),lr=require("@noble/hashes/utils");function Rt(u){let e=u.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=(0,or.sha256)(t);return(0,lr.bytesToHex)(r)}var qe=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 Mr=7,Ue=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 qe,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let a=i.dequeue();if(!a||a.length>Mr)continue;let o=a[a.length-1];(r===null||o[0]===r)&&s.push(a),e.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,a)){let m=[...a];m.push(c),i.enqueue(m)}})}return s}findShortestPaths(e,t,r){let s=[],i=new qe,n=[];n.push([t,""]),i.enqueue(n);let a=1/0;for(;i.size()>0;){let o=i.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===r){o.length<a?(a=o.length,s.length=0,s.push(o)):o.length===a&&s.push(o);continue}let c=e.get(l[0]);for(let m of c??[])this.isNotVisited(m,o)&&i.enqueue([...o,m])}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,n]of t){let a=parseInt(i),o=parseInt(n);r.get(a)?.push([o,s])}return r}};function _t(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 Ge=class{getProposals(e,t,r){let s=r.filter(f=>f.type==="Xyk"),i=r.filter(f=>f.type!=="Xyk"),n=parseInt(e),a=parseInt(t),o=new Set(i.map(f=>f.tokens).flat().map(f=>f.id)),l=o.has(e),c=o.has(t),m=new Ue,g=f=>{let T=_t(f),x=Object.keys(T),I=x.flatMap(A=>T[A]);return m.buildAndPopulateGraph(x,I)};if(!l&&!c){let f=s.filter(I=>I.tokens.find(A=>A.id===e)||I.tokens.find(A=>A.id===t)),T=g(f),x=m.findPaths(T,n,a);return this.parsePaths(x)}if(l&&c){let f=g(i),T=m.findPaths(f,n,a);return this.parsePaths(T)}let d=l?t:e,h=s.filter(f=>f.tokens.some(T=>T.id===d)),b=[...i,...h],y=g(b),w=m.findPaths(y,n,a);return this.parsePaths(w)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let n=r[i],a=r[i+1];if(a==null)break;s.push(this.toEdge(n,a))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var de=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new Ge,this.routeProposals=new Map,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(),t=this.getAssets(e);return[...new Map(t).values()]}async getRoutes(e,t){let r=await this.getPools();return this.validateInput(e,t,r),this.getPaths(e,t,r)}validateInput(e,t,r){if(r.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(r);if(s.get(e)===null)throw new Error(e+" is not supported asset");if(s.get(t)===null)throw new Error(t+" is not supported asset");return this.toPoolsMap(r)}getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r){let s=this.toPoolsMap(r);return this.getProposals(e,t,r).filter(a=>this.validPath(a,s)).map(a=>this.toHops(a,s))}getProposals(e,t,r){let s=`${e}->${t}::${Rt(r)}`;if(this.routeProposals.has(s))return this.routeProposals.get(s);let i=this.routeSuggester.getProposals(e,t,r);return this.routeProposals.set(s,i),i}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,pe.get(t)]))}toHops(e,t){return e.map(([r,s,i])=>{let n=t.get(r);return{poolAddress:r,poolId:n?.id,pool:n?.type,assetIn:s,assetOut:i}})}};var Lr=p("100");function qr(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 Et(u,e){return D.minus(e.div(u)).multipliedBy(100).decimalPlaces(4)}function Nt(u,e){return e.div(u).minus(D).multipliedBy(100).decimalPlaces(4)}function J(u,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),u.div(Lr).multipliedBy(e).decimalPlaces(0,1)}var it=(t=>(t.Buy="Buy",t.Sell="Sell",t))(it||{}),nt=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(nt||{}),Ft=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(Ft||{});var he=class extends de{async loadRouteContext(e,t){let r=await super.getPools(),s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(i.length===0)throw new Oe(e,t);return{paths:i,pools:r,poolsMap:s}}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,n=s[s.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[r,s]}}getPoolFeeRange(e){let t=e.min?P.toPct(e.min):void 0,r=e.max?P.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),a;if(s)a=await this.toSellSwaps(r,s,n);else{let x=i.map(async A=>await this.toSellSwaps(r,A,n)),I=await Promise.all(x);a=this.findBestSellRoute(I)}let o=a[0],l=a[a.length-1],c=this.isDirectTrade(a),m=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,I)=>x.multipliedBy(I)),g=R(m,l.assetOutDecimals),d=c?l.calculatedOut:this.calculateDelta0Y(o.amountIn,a,n),h=l.amountOut,b=c?l.tradeFeePct:Et(d,h).toNumber(),y=d.minus(h),w=this.getRouteFeeRange(a),f=o.amountIn.shiftedBy(-1*o.assetInDecimals).multipliedBy(g),T=ge(d,f);return{type:"Sell",amountIn:o.amountIn,amountOut:l.amountOut,spotPrice:g,tradeFee:y,tradeFeePct:b,tradeFeeRange:w,priceImpactPct:T.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:O(o.amountIn,o.assetInDecimals),amountOut:O(l.amountOut,l.assetOutDecimals),spotPrice:O(g,l.assetOutDecimals),tradeFee:O(y,l.assetOutDecimals),tradeFeePct:b,tradeFeeRange:w,priceImpactPct:T.toNumber(),swaps:a.map(x=>x.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1]:l=e;let c=a.calculateOutGivenIn(o,l);s.push(c)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1].amountOut:l=R(p(e),o.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(o,a),{amountOut:m,calculatedOut:g,feePct:d,errors:h}=a.validateAndSell(o,l,c),b=this.getPoolFeeRange(c),y=a.spotPriceOutGivenIn(o),w=l.shiftedBy(-1*o.decimalsIn).multipliedBy(y),f=ge(g,w);s.push({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:m,calculatedOut:g,spotPrice:y,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===n.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:O(l,o.decimalsIn),amountOut:O(m,o.decimalsOut),calculatedOut:O(g,o.decimalsOut),spotPrice:O(y,o.decimalsOut),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:h}}})}return s}async getMostLiquidRoute(e,t){let{paths:r,pools:s,poolsMap:i}=await this.loadRouteContext(e,t),l=s.filter(d=>d.tokens.some(h=>h.id===e)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(h=>h.id===e)).map(d=>d.map(h=>p(h.balance).shiftedBy(-1*h.decimals)).reduce((h,b)=>h.plus(b))).sort((d,h)=>h.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=r.map(async d=>await this.toSellSwaps(l,d,i)),m=await Promise.all(c);return this.findBestSellRoute(m).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r;try{r=await this.loadRouteContext(e,t)}catch{return Promise.resolve(void 0)}let{poolsMap:s}=r,i=await this.getMostLiquidRoute(e,t),n=await this.toSellSwaps("1",i,s),a=n.map(c=>c.spotPrice.shiftedBy(-1*c.assetOutDecimals)).reduce((c,m)=>c.multipliedBy(m)),o=n[n.length-1].assetOutDecimals;return{amount:R(a,o),decimals:o}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,n=s[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),a;if(s)a=await this.toBuySwaps(r,s,n);else{let x=i.map(async A=>await this.toBuySwaps(r,A,n)),I=await Promise.all(x);a=this.findBestBuyRoute(I)}let o=a[a.length-1],l=a[0],c=this.isDirectTrade(a),m=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetInDecimals)).reduce((x,I)=>x.multipliedBy(I)),g=R(m,l.assetInDecimals),d=c?l.calculatedIn:this.calculateDelta0X(o.amountOut,a,n),h=l.amountIn,b=c?l.tradeFeePct:Nt(d,h).toNumber(),y=h.minus(d),w=this.getRouteFeeRange(a),f=o.amountOut.shiftedBy(-1*o.assetOutDecimals).multipliedBy(g),T;return d.isZero()?T=-100:T=ge(f,d).toNumber(),{type:"Buy",amountOut:o.amountOut,amountIn:l.amountIn,spotPrice:g,tradeFee:y,tradeFeePct:b,tradeFeeRange:w,priceImpactPct:T,swaps:a,toHuman(){return{type:"Buy",amountOut:O(o.amountOut,o.assetOutDecimals),amountIn:O(l.amountIn,l.assetInDecimals),spotPrice:O(g,l.assetInDecimals),tradeFee:O(y,l.assetInDecimals),tradeFeePct:b,tradeFeeRange:w,priceImpactPct:T,swaps:a.map(x=>x.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=e:l=s[0];let c=a.calculateInGivenOut(o,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],a=r.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=R(p(e),o.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(o,a),{amountIn:m,calculatedIn:g,feePct:d,errors:h}=a.validateAndBuy(o,l,c),b=this.getPoolFeeRange(c),y=a.spotPriceInGivenOut(o),w=l.shiftedBy(-1*o.decimalsOut).multipliedBy(y),f;g.isZero()?f=-100:f=ge(w,g).toNumber(),s.unshift({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:m,amountOut:l,calculatedIn:g,spotPrice:y,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f,errors:h,isSupply(){return a.type==="Aave"&&a.tokens[0].id===n.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:O(m,o.decimalsIn),amountOut:O(l,o.decimalsOut),calculatedIn:O(g,o.decimalsIn),spotPrice:O(y,o.decimalsIn),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:f,errors:h}}})}return s}};var ur=6e3,cr=p(1e15),We=6,kt=-5,Dt=6*60*60*1e3;var mr=6;var G=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:i})=>s==="Stableswap"?{pool:{Stableswap:i},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var ye=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??ur,minBudgetInNative:t.minBudgetInNative??cr})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[n,a]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:l,priceImpactPct:c}=a,m=l[0],g=l[l.length-1],{assetInDecimals:d}=m,{assetOutDecimals:h}=g,b=Math.abs(c),y=this.getMinimumTradeCount(o,n),w=this.getOptimalTradeCount(b),f=i?Math.round(s/i):w,T=Math.ceil(s/y),x=Math.round(s/w),I=Math.round(s/f),A=o.dividedBy(f).decimalPlaces(0,1),M=await this.router.getBestSell(e,t,O(A,d)),H=o.isLessThan(n),He=[];H&&He.push("OrderTooSmall");let ze=M.amountOut.multipliedBy(f),lt=this.toBlockPeriod(I),ut=M.tradeFee.multipliedBy(f),ct=G.build(l),Xe={assetIn:e,assetOut:t,errors:He,frequencyMin:T,frequencyOpt:x,frequency:I,tradeCount:f,tradeFee:ut,tradeImpactPct:M.priceImpactPct,tradePeriod:lt,tradeRoute:ct,type:"Dca"};return{...Xe,amountIn:o,amountOut:ze,tradeAmountIn:M.amountIn,tradeAmountOut:M.amountOut,toHuman(){return{...Xe,amountIn:O(o,d),amountOut:O(ze,h),tradeAmountIn:O(M.amountIn,d),tradeAmountOut:O(M.amountOut,h)}}}}async getMinimumOrderBudget(e){if(k===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(k,e);if(t)return this.minOrderBudget.times(t.amount).div(p(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:a,priceImpactPct:o}=i,l=a[0],c=a[a.length-1],{assetInDecimals:m}=l,{assetOutDecimals:g}=c,d=Math.abs(o),h=this.getTwapTradeCount(d),b=n.dividedBy(h).decimalPlaces(0,1),y=await this.router.getBestSell(l.assetIn,c.assetOut,O(b,m)),w=h===1,f=n.isLessThan(s),T=y.priceImpactPct<kt,x=[];f||w?x.push("OrderTooSmall"):T&&x.push("OrderImpactTooBig");let I=y.amountOut.multipliedBy(h),A=y.tradeFee.multipliedBy(h),M=G.build(a),H={assetIn:e,assetOut:t,errors:x,tradeCount:h,tradeImpactPct:y.priceImpactPct,tradePeriod:We,tradeRoute:M,type:"TwapSell"};return{...H,amountIn:n,amountOut:I,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:A,toHuman(){return{...H,amountIn:O(n,m),amountOut:O(I,g),tradeAmountIn:O(y.amountIn,m),tradeAmountOut:O(y.amountOut,g),tradeFee:O(A,g)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:n,swaps:a,priceImpactPct:o}=i,l=a[0],c=a[a.length-1],{assetInDecimals:m}=l,{assetOutDecimals:g}=c,d=Math.abs(o),h=this.getTwapTradeCount(d),b=n.dividedBy(h).decimalPlaces(0,1),y=await this.router.getBestBuy(l.assetIn,c.assetOut,O(b,g)),w=y.amountIn.multipliedBy(h),f=h===1,T=w.isLessThan(s),x=y.priceImpactPct<kt,I=[];T||f?I.push("OrderTooSmall"):x&&I.push("OrderImpactTooBig");let A=y.tradeFee.multipliedBy(h),M=G.build(a),H={assetIn:e,assetOut:t,errors:I,tradeCount:h,tradeImpactPct:y.priceImpactPct,tradePeriod:We,tradeRoute:M,type:"TwapBuy"};return{...H,amountIn:w,amountOut:n,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:A,toHuman(){return{...H,amountIn:O(w,m),amountOut:O(n,g),tradeAmountIn:O(y.amountIn,m),tradeAmountOut:O(y.amountOut,g),tradeFee:O(A,m)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>Dt){let s=Dt/(this.blockTime*We);return Math.round(s)}return t}getTwapExecutionTime(e){return e*We*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,mr)}};var fe=class extends L{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new q(e),this.aaveUtils=new Q(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),be)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var at=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=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,n)).amount.isGreaterThanOrEqualTo(o)),l&&e.isGreaterThanOrEqualTo(o)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=J(e,this.slippagePct),a=s.assetIn,o=i.assetOut,l=e.plus(n),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(o,a,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(a,o,t.toFixed(),l.toFixed(),G.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=J(t,this.slippagePct),a=s.assetIn,o=i.assetOut,l=t.minus(n),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(a,o,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(a,o,e.toFixed(),l.toFixed(),G.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let g=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSellAll",g,be)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=J(e,this.slippagePct),n=r.assetIn,a=s.assetOut,o=e.minus(i),l=this.api.tx.router.sellAll(n,a,o.toFixed(),G.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let m=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",m,be)}return this.wrapTx("RouterSellAll",l)}};var ot=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,a=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:n}}},null);return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:a}=this.order,o=J(i,this.slippagePct),l=i.minus(o),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:a}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:a}=this.order,o=J(s,this.slippagePct),l=s.plus(o),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:i.toFixed(),maxAmountIn:l.toFixed(),route:a}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var Pe=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new at(this.api,this.evm).setTrade(e)}order(e){return new ot(this.api,this.evm).setOrder(e)}};function Ur(u){let e=new oe(u),t=new Be(u),r=new me(u,t),s=new Q(t),i=new he(r),n=new ye(i,{blockTime:e.blockTime,minBudgetInNative:e.minOrderBudget});return{api:{aave:s,router:i,scheduler:n},client:{asset:new Z(u),balance:new q(u),balanceV2:new ae(u)},ctx:{pool:r},evm:t,tx:new Pe(u,t),destroy:()=>{r.destroy()}}}0&&(module.exports={AaveClient,AavePool,AavePoolClient,AaveUtils,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BalanceClientV2,BigNumber,CachingPoolService,ChainParams,DECIMAL_PLACES,ERC20,EvmClient,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,ONE,OmniMath,OmniPool,OmniPoolClient,PERMILL_DENOMINATOR,PolkadotApiClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StableSwapClient,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeOrderError,TradeOrderType,TradeRouteBuilder,TradeRouter,TradeScheduler,TradeType,TxBuilderFactory,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,createChain,createSdkContext,findNestedKey,findNestedObj,getFraction,hashPools,isEvmAccount,isEvmAddress,isSs58Address,scale,toBn,toDecimals});
|
package/build/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Se=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var He=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var et="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Xe="0x112b087b60C1a166130d59266363C45F8aa99db0",Ye="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Z=1000000n;var rs=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var J=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:He,address:Xe,args:[Ye],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:He,address:Xe,args:[Ye,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:Se,address:et,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as we,encodeAddress as rt}from"@polkadot/util-crypto";import{hexToU8a as Ft,isHex as Et,u8aToHex as _t}from"@polkadot/util";import{Buffer as H}from"buffer";var os=2090,Y=1e6,Te="1",ls=2034,W=63,ee=18,F="0",tt=12,te=15;var Ve="ETH\0";function kt(m){if(!m)return!1;try{let e=we(m,!0),t=H.from(Ve);return H.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Dt(m){return!!/^0x[a-fA-F0-9]{40}$/.test(m)}function Ct(m){try{let e=Et(m)?Ft(m):we(m);return rt(e),!0}catch{return!1}}var z=class m{static toAccount=e=>{let t=H.from(e.slice(2),"hex"),r=H.from(Ve);return rt(new Uint8Array(H.concat([r,t,H.alloc(8)])),63)};static fromAccount=e=>{let t=we(e),r=H.from(Ve),s=t.slice(r.length,-8);return"0x"+H.from(s).toString("hex")};static fromSS58=e=>{let r=we(e).slice(0,20);return _t(r)};static fromAny=e=>{if(Dt(e))return e;if(kt(e))return m.fromAccount(e);if(Ct(e))return m.fromSS58(e);throw new Error("Unknown address type")}};import{Buffer as Be}from"buffer";var G=class{static fromAssetId(e){let t=Number(e),r=Be.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Be.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Be.from("0000000000000000000000000000000100000000","hex"),r=Be.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as B}from"bignumber.js";var Mt=12;B.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Mt});var S=p(0),E=p(1),ys=p("Infinity");function A(m,e){let t=new B(e.toString()),r=new B(10).pow(t);return m.times(r).decimalPlaces(4)}function p(m){return new B(m.toString())}function fs(m,e){let t=p(m);return A(t,e)}function x(m,e){return m.shiftedBy(-1*e).toString()}var Oe=p("1e27"),Lt=p("1.01"),qt=p("31536000"),V=class{client;constructor(e){this.client=new J(e)}async getSummary(e){let t=z.fromAny(e),[r,s,n,o]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[i]=r,[a,l]=s,[c,u,g,d,h,f]=n,b=p(f).dividedBy(1e18).decimalPlaces(6,B.ROUND_DOWN),w=p(c),P=p(u),O=[];for(let T of a){let I=T.underlyingAsset.toLowerCase(),v=i.find(({underlyingAsset:Nt})=>Nt.toLowerCase()===I);if(!v)throw new Error("Missing pool reserve for "+I);let k=p(T.scaledATokenBalance),q=p(v.liquidityIndex),Pe=p(v.liquidityRate),ye=p(v.availableLiquidity),Ue=p(v.priceInMarketReferenceCurrency),Ge=o+6,We=this.calculateLinearInterest(Pe,v.lastUpdateTimestamp,Ge),fe=q.multipliedBy(We).dividedBy(Oe).decimalPlaces(0,B.ROUND_DOWN),It=k.multipliedBy(fe).dividedBy(Oe).decimalPlaces(0,B.ROUND_DOWN),vt=p(l!==0&&l===v.eModeCategoryId?v.eModeLiquidationThreshold:v.reserveLiquidationThreshold).div(1e4),At=v.usageAsCollateralEnabled&&T.usageAsCollateralEnabledOnUser&&p(T.scaledATokenBalance).gt(0),Rt=G.toAssetId(I);O.push({aTokenBalance:It,availableLiquidity:ye,decimals:Number(v.decimals),isCollateral:At,priceInRef:Ue,reserveId:Rt,reserveAsset:I,reserveLiquidationThreshold:vt})}return{healthFactor:b.toNumber(),totalCollateral:w,totalDebt:P,reserves:O}}async hasBorrowPositions(e){let t=z.fromAny(e),r=await this.client.getUserAccountData(t),[s,n]=r;return n>0n}async getHealthFactor(e){let t=z.fromAny(e),r=await this.client.getUserAccountData(t),[s,n,o,i,a,l]=r;return p(l).dividedBy(1e18).decimalPlaces(6,B.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:n,reserves:o}=await this.getSummary(e),i=G.fromAssetId(t),a=o.find(w=>w.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:c,priceInRef:u,reserveLiquidationThreshold:g}=a,d=A(p(r),l).decimalPlaces(0,1),h=c?d.multipliedBy(u).dividedBy(p(10).pow(l)).decimalPlaces(0,B.ROUND_DOWN):S,f=s.minus(h);return f.lte(0)?0:f.multipliedBy(g).dividedBy(n).decimalPlaces(6,B.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:n,reserves:o}=await this.getSummary(e),i=G.fromAssetId(t),a=o.find(b=>b.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:u}=a,d=A(p(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(p(10).pow(l)).decimalPlaces(0,B.ROUND_DOWN),h=s.plus(d);return h.lte(0)?0:h.multipliedBy(u).dividedBy(n).decimalPlaces(6,B.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:n}=await this.getSummary(e),o=G.fromAssetId(t),i=s.find(a=>a.reserveAsset===o);if(!i)throw new Error("Missing reserve data for "+o);return this.calculateWithdrawMax(i,r,n)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),n={};for(let o of r){let i=this.calculateWithdrawMax(o,t,s);o.reserveId&&(n[o.reserveId]=i)}return n}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:n,decimals:o,priceInRef:i,reserveLiquidationThreshold:a,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let g=p(r).minus(Lt);if(g.gt(0)){let h=g.multipliedBy(t).dividedBy(a).decimalPlaces(0,B.ROUND_DOWN).dividedBy(i).multipliedBy(p(10).pow(o)).decimalPlaces(0,B.ROUND_DOWN);c=B.minimum(s,h)}else c=S}return{amount:B.minimum(c,n),decimals:o}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Oe:e.multipliedBy(s).dividedBy(qt).plus(Oe).decimalPlaces(0,B.ROUND_DOWN)}};function st(m){switch(m){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var D=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 $=class extends D{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},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==F){let u=this.api.consts.balances.existentialDeposit;return{id:F,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),g=o.toNumber(),d=new Intl.DateTimeFormat("en-GB"),h=[c,"Bond",d.format(g)].join(" ");return{id:e,name:h,symbol:c+"b",decimals:u,icon:c,type:i.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:n.toString(),maturity:g}}getShares(e,t,r,s){let{assets:n}=s,{name:o,symbol:i,assetType:a,isSufficient:l,existentialDeposit:c}=t,g=n.map(f=>f.toString()).map(f=>{let{symbol:b}=this.getToken(f,t,r);return[f,b]}),d=Object.fromEntries(g),h=Object.values(d);return{id:e,name:h.join(", "),symbol:i?.isSome?i.toHuman():o.toHuman(),decimals:18,icon:h.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]},g])=>{let d=g.unwrap(),h=s.get(u.toString()),{assetType:f}=d;switch(f.toString()){case"Bond":let b=o.get(u.toString());return this.getBond(u.toString(),d,l,b);case"StableSwap":let w=n.get(u.toString());return this.getShares(u.toString(),d,l,w);case"External":return this.getExternal(u.toString(),d,t,h);default:return this.getToken(u.toString(),d,l,h)}});return e?c:c.filter(u=>this.isValidAsset(u))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var M=class extends D{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===F?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(F,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 t=e.free.toString(),r=e.frozen.toString();return B(t).lt(r)?B(0):B(t).minus(r)}};var re=class extends D{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===F?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(F,this.calculateBalance(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=n[l][1],u=this.calculateBalance(a);i.push([c,u])}),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)}calculateBalance(e){let t=B(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),n=t.gte(r)?t.minus(r).toString():"0",o=t.plus(s).toString();return{free:t.toString(),total:o,transferable:n,reserved:s,frozen:r}}};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()),p(this._minOrderBudget)}};import{fixed_from_rational as nt}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as Ut}from"@polkadot/types";import{u8aConcat as it}from"@polkadot/util";import{isAddress as at}from"@polkadot/util-crypto";var $e=class extends D{balanceClient;constructor(e){super(e),this.balanceClient=new M(e)}secondsInYear=new B(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(),h=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:f.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,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(),h=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:f.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new B(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 Ut(e,this.padEndU8a(it(s,n,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!at(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&at(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 B(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),d=new B(a.yieldPerPeriod.toString()),h=new B(a.maxRewardPerPeriod.toString()),f=a.blocksPerPeriod.toString(),b=new B(i.multiplier.toString()).shiftedBy(-18),w=this.secondsInYear.div(new B(r).times(f)),P;if(u.isZero())P=d.times(b).times(w);else{let k=this.getGlobalRewardPerPeriod(u,d,h,l);P=this.getPoolYieldPerPeriod(k,b,u,l).times(w)}let O=new B(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),T=h.times(g),I=c?O.plus(c):T;return O.div(I).gte(.999)?S:P.div(t==="isolatedpool"?2:1).times(100)}).reduce((i,a)=>i.plus(a),S).toString():void 0}};var xe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},ot=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ie=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{defineChain as Gt}from"viem";var Wt=["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"],pt=m=>{let t=[m.endpoint,...Wt],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return Gt({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1})};import{createPublicClient as gt,createWalletClient as Ht,custom as Xt,http as Yt}from"viem";function dt(m){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return m.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var ve=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=pt(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return gt({chain:this.chain,transport:Yt()})}getWsProvider(){return gt({chain:this.chain,transport:dt(this.wsProvider)})}getSigner(e){return Ht({account:e,chain:this.chain,transport:Xt(window.ethereum)})}};import{memoize1 as Yr}from"@thi.ng/memoize";var N=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n))(N||{}),j=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n))(j||{});var Ae=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,n){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(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=p(s.balance),i=p(n.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:o,balanceOut:i,assetInED:S,assetOutED:S}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=[];return t.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:n}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=[];return s.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:n}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return A(E,e.decimalsOut)}spotPriceOutGivenIn(e){return A(E,e.decimalsIn)}calculateTradeFee(e,t){return S}};import{encodeAddress as Kt}from"@polkadot/util-crypto";import{stringToU8a as zt}from"@polkadot/util";import{decodeEventLog as jt}from"viem";function ht(m,e){let t=[];return JSON.stringify(m,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Un(m,e,t){let r;return JSON.stringify(m,(s,n)=>(n&&n[e]===t&&(r=n),n)),r}var Gn=(m,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as Vt}from"@thi.ng/memoize";import{TLRUCache as $t}from"@thi.ng/cache";var Ke=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var ne=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,n]=await Promise.all([this.client.readContract({abi:Ke,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:Ke,address:e,functionName:"decimals"}),this.client.getBlock()]),[o,i,a,l]=r,c=n.number-(n.timestamp-l)/BigInt(t),u=Number(c);return{price:i,decimals:s,updatedAt:u<0?0:u}}};var C=class extends M{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new $t(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=Vt(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new ne(t)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let r=[];try{let n=this.subscribePoolChange(t);r.push(n)}catch{}if(t.type==="Aave")return r;let s=this.subscribeTokensPoolBalance(t);if(r.push(s),this.hasSystemAsset(t)){let n=this.subscribeSystemPoolBalance(t);r.push(n)}if(this.hasErc20Asset(t)){let n=this.subscribeErc20PoolBalance(t);r.push(n)}return this.subscribeLog(t),r}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,n])=>{let 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 Qt=["Supply","Withdraw","Repay","Borrow"],Re=class extends C{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:n})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:n.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t,r){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let r=e+"/"+t;return Kt(zt(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,""),g=c.replace(/,/g,"");(u===r.id||g===r.id)&&(this.log(`Sync AAVE [router:Executed] :: ${u}:${g}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=i.data.toHuman();try{let{eventName:c,args:u}=jt({abi:Se,topics:l.topics,data:l.data});Qt.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"?ht(e.location,"accountKey20").accountKey20.key:G.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as Zt,calculate_out_given_in as Jt,calculate_linear_weights as er,calculate_pool_trade_fee as tr,get_spot_price as rr}from"@galacticcouncil/math-lbp";var U=class{static getSpotPrice(e,t,r,s,n){return rr(e,t,r,s,n)}static calculateInGivenOut(e,t,r,s,n){return Zt(e,t,r,s,n)}static calculateOutGivenIn(e,t,r,s,n){return Jt(e,t,r,s,n)}static calculateLinearWeights(e,t,r,s,n){return er(e,t,r,s,n)}static calculatePoolTradeFee(e,t,r){return tr(e,t,r)}};var y=class m{static toPct(e){let[t,r]=e;return m.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return m.safeDivide(t,r)}static fromPermill(e){return[e,1e6]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,r=12){let s=10**r;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};var Ne=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,n,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=p(s.balance),i=p(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=U.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=U.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=U.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),A(E,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=U.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),A(E,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=U.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var Fe=class extends C{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(([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());this.poolsData.set(n.toString(),i);let[c,u]=i.fee;return{address:a,type:"Lbp",fee:y.fromRate(c.toNumber(),u.toNumber()),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t,r){let s=this.pools.find(n=>n.address===r);return{repayFee:this.getRepayFee(),exchangeFee:s.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=U.calculateLinearWeights(s.toString(),n.toString(),i.toString(),a.toString(),r),[g,d]=o,h=g.toString(),f=p(u),b=d.toString(),w=this.MAX_FINAL_WEIGHT.minus(p(f)),[P,O,T]=await Promise.all([this.isRepayFeeApplied(h,l.toString(),c.toString()),this.getBalance(e,h),this.getBalance(e,b)]);return{repayFeeApply:P,tokens:[{id:h,weight:f,balance:O.toString()},{id:b,weight:w,balance:T.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(){let[e,t]=this.api.consts.lbp.repayFee;return y.fromRate(e.toNumber(),t.toNumber())}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toNumber(),t=this.api.consts.lbp.maxOutRatio.toNumber(),r=this.api.consts.lbp.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as sr,calculate_lrna_in_given_out as nr,calculate_out_given_in as ir,calculate_out_given_lrna_in as ar,calculate_spot_price as or,calculate_lrna_spot_price as lr,calculate_shares as cr,calculate_liquidity_out as ur,calculate_liquidity_lrna_out as mr,calculate_liquidity_hub_in as pr,is_sell_allowed as dr,is_buy_allowed as gr,is_add_liquidity_allowed as hr,is_remove_liquidity_allowed as br,recalculate_asset_fee as Pr,recalculate_protocol_fee as yr,verify_asset_cap as fr}from"@galacticcouncil/math-omnipool";var R=class{static calculateSpotPrice(e,t,r,s){return or(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return lr(e,t)}static calculateInGivenOut(e,t,r,s,n,o,i,a,l){return sr(e,t,r,s,n,o,i,a,l)}static calculateLrnaInGivenOut(e,t,r,s,n){return nr(e,t,r,s,n)}static calculateOutGivenIn(e,t,r,s,n,o,i,a,l){return ir(e,t,r,s,n,o,i,a,l)}static calculateOutGivenLrnaIn(e,t,r,s,n){return ar(e,t,r,s,n)}static calculateShares(e,t,r,s){return cr(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,n,o,i,a){return ur(e,t,r,s,n,o,i,a)}static calculateLiquidityLRNAOut(e,t,r,s,n,o,i,a){return mr(e,t,r,s,n,o,i,a)}static calculateCapDifference(e,t,r,s){let n=B(t),o=B(e),i=B(s),l=B(r).shiftedBy(-18);if(n.div(i).lt(l)){let u=l.times(i).minus(n).times(o),g=n.times(B(1).minus(l));return u.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return pr(e,t,r,s)}static isSellAllowed(e){return dr(e)}static isBuyAllowed(e){return gr(e)}static isAddLiquidityAllowed(e){return hr(e)}static isRemoveLiquidityAllowed(e){return br(e)}static recalculateAssetFee(e,t,r,s,n,o,i,a,l,c,u){return Pr(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 yr(e,t,r,s,n,o,i,a,l,c,u)}static verifyAssetCap(e,t,r,s){return fr(e,t,r,s)}};var Ee=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,n,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=p(s.balance),i=p(n.balance),a=p(s.existentialDeposit),l=p(n.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:n.hubReserves,sharesIn:s.shares,sharesOut:n.shares,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn: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===S?S:o.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=R.isSellAllowed(e.tradeableIn),c=R.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 g=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(g)&&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(4),a=[],l=R.isSellAllowed(e.tradeableIn),c=R.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 g=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(g)&&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=R.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),n=p(s);return n.isNegative()?S:n}calculateLrnaInGivenOut(e,t,r){let s=R.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),n=p(s);return n.isNegative()?S:n}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=R.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),n=p(s);return n.isNegative()?S:n}calculateOutGivenLrnaIn(e,t,r){let s=R.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),n=p(s);return n.isNegative()?S:n}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=R.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=R.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=R.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=R.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as Sr}from"@polkadot/util-crypto";import{stringToU8a as Tr}from"@polkadot/util";import{memoize1 as bt}from"@thi.ng/memoize";import{TLRUCache as wr}from"@thi.ng/cache";var Pt="omnipool",yt="Short",_e=class extends C{dynamicFees=new Map;oracles=new Map;memQueryCache=new wr(null,{ttl:6*1e3});memOracleQuery=bt(e=>{this.log("Fetching oracle price for",e);let t=e.split(":");return this.api.query.emaOracle.oracles(Pt,t,yt)},this.memQueryCache);memFeesQuery=bt(e=>(this.log("Fetching dyn fees for",e),this.api.query.dynamicFees.assetFee(e)),this.memQueryCache);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:g,cap:d,protocolShares:h}=l.unwrap(),f=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(c.toString()),shares:p(u.toString()),tradeable:g.bits.toNumber(),balance:f.toString(),cap:p(d.toString()),protocolShares:p(h.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 getDynamicFees(e){return this.dynamicFees.has(e)?this.dynamicFees.get(e):this.memFeesQuery(e)}async getOraclePrice(e){let r=this.getOracleKey(e).join(":");return this.oracles.has(r)?this.oracles.get(r):this.memOracleQuery(r)}async getPoolFees(e,t,r){let s=t.assetOut,n=t.assetIn,[o,i,a]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(n)]),[l,c,u]=this.getAssetFee(t,e,o,i),[g,d,h]=n===Te?[0,0,0]:this.getProtocolFee(t,e,o,a),f=l+g,b=u+h;return{assetFee:y.fromPermill(c),protocolFee:y.fromPermill(d),min:y.fromPermill(f),max:y.fromPermill(b)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(a=>a.id),r=[],s=await this.api.query.omnipool.assets.multi(t,a=>{e.tokens=a.map((l,c)=>{let u=e.tokens[c];if(l.isNone)return u;let g=l.unwrap();return this.updateTokenState(u,g)})});r.push(s);let n=await this.api.query.dynamicFees.assetFee.multi(t,a=>{a.forEach((l,c)=>{let u=t[c];this.dynamicFees.set(u,l)})});r.push(n);let o=t.map(a=>{let l=this.getOracleKey(a);return[Pt,l,yt]}),i=await this.api.query.emaOracle.oracles.multi(o,a=>{a.forEach(async(l,c)=>{let u=o[c],[g,d,h]=u;this.oracles.set(d.join(":"),l)})});return r.push(i),()=>{for(let a of r)try{a()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:n,cap:o,protocolShares:i}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(o.toString()),protocolShares:p(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()),g=y.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[i.toNumber(),i.toNumber(),a.toNumber()];let[d]=s.unwrap(),{assetFee:h,timestamp:f}=r.unwrap(),b=Math.max(1,t-f.toNumber()),w=d.volume.bIn.toString(),P=d.volume.bOut.toString(),O=d.liquidity.b.toString();n===F&&(w=d.volume.aIn.toString(),P=d.volume.aOut.toString(),O=d.liquidity.a.toString());let T=y.fromPermill(h.toNumber()),I=R.recalculateAssetFee(w,P,O,"9",o.toString(),y.toRaw(T).toString(),b.toString(),y.toRaw(u).toString(),y.toRaw(g).toString(),l.toString(),c.toString());return[i.toNumber(),Number(I)*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()),g=y.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[i.toNumber(),i.toNumber(),a.toNumber()];let[d]=s.unwrap(),{protocolFee:h,timestamp:f}=r.unwrap(),b=Math.max(1,t-f.toNumber()),w=d.volume.bIn.toString(),P=d.volume.bOut.toString(),O=d.liquidity.b.toString();n===F&&(w=d.volume.aIn.toString(),P=d.volume.aOut.toString(),O=d.liquidity.a.toString());let T=y.fromPermill(h.toNumber()),I=R.recalculateProtocolFee(w,P,O,"9",o.toString(),y.toRaw(T).toString(),b.toString(),y.toRaw(u).toString(),y.toRaw(g).toString(),l.toString(),c.toString());return[i.toNumber(),Number(I)*1e6,a.toNumber()]}getOracleKey(e){return e===F?[F,Te]:[Te,e]}getPoolId(){return Sr(Tr("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toNumber(),t=this.api.consts.omnipool.maxOutRatio.toNumber(),r=this.api.consts.omnipool.minimumTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as Br,calculate_out_given_in as Or,calculate_pool_trade_fee as xr,get_spot_price as Ir,calculate_liquidity_in as vr,calculate_shares as Ar,calculate_spot_price as Rr,calculate_spot_price_with_fee as Nr,calculate_liquidity_out_asset_a as Fr,calculate_liquidity_out_asset_b as Er}from"@galacticcouncil/math-xyk";var X=class{static getSpotPrice(e,t,r){return Ir(e,t,r)}static calculateInGivenOut(e,t,r){return Br(e,t,r)}static calculateOutGivenIn(e,t,r){return Or(e,t,r)}static calculatePoolTradeFee(e,t,r){return xr(e,t,r)}static calculateLiquidityIn(e,t,r){return vr(e,t,r)}static calculateSpotPrice(e,t){return Rr(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return Nr(e,t,r,s)}static calculateShares(e,t,r){return Ar(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return Fr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Er(e,t,r,s)}};var ke=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,n){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(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=p(s.balance),i=p(n.balance),a=p(s.existentialDeposit),l=p(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=X.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=X.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=X.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=A(E,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=X.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=A(E,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=X.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var De=class extends C{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let n=r.toString(),[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,r){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){let[e,t]=this.api.consts.xyk.getExchangeFee;return y.fromRate(e.toNumber(),t.toNumber())}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toNumber(),t=this.api.consts.xyk.maxOutRatio.toNumber(),r=this.api.consts.xyk.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as _r,calculate_out_given_in as kr,calculate_amplification as Dr,calculate_add_one_asset as Cr,calculate_liquidity_out_one_asset as Mr,calculate_shares as Lr,calculate_shares_for_amount as qr,calculate_spot_price_with_fee as Ur,pool_account_name as Gr,recalculate_peg as Wr}from"@galacticcouncil/math-stableswap";var _=class{static getPoolAddress(e){return Gr(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 Dr(e,t,r,s,n)}static calculateInGivenOut(e,t,r,s,n,o,i){return _r(e,t,r,s,n,o,i)}static calculateAddOneAsset(e,t,r,s,n,o,i){return Cr(e,t,r,s,n,o,i)}static calculateSharesForAmount(e,t,r,s,n,o,i){return qr(e,t,r,s,n,o,i)}static calculateOutGivenIn(e,t,r,s,n,o,i){return kr(e,t,r,s,n,o,i)}static calculateLiquidityOutOneAsset(e,t,r,s,n,o,i){return Mr(e,t,r,s,n,o,i)}static calculateShares(e,t,r,s,n,o){return Lr(e,t,r,s,n,o)}static calculateSpotPriceWithFee(e,t,r,s,n,o,i,a){return Ur(e,t,r,s,n,o,i,a)}static recalculatePegs(e,t,r,s,n){let o=Wr(e,t,r,s,n);return JSON.parse(o)}};var Ce=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,r,s,n,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=p(s.balance),i=p(n.balance),a=p(s.existentialDeposit),l=p(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=n.minus(s),i=s===S?S:o.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount"),{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(4),a=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:i.toNumber(),errors:a}}calculateIn(e,t,r){let s=_.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateAddOneAsset(e,t,r){let s=_.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateSharesForAmount(e,t,r){let s=_.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let s=A(E,e.decimalsIn-e.decimalsOut);return p(t).div(s).decimalPlaces(0,1)}let r=A(E,18-e.decimalsIn);return p(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=_.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateWithdrawOneAsset(e,t,r){let s=_.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateShares(e,t,r){let s=_.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let s=A(E,e.decimalsOut-e.decimalsIn);return p(t).div(s).decimalPlaces(0,1)}let r=A(E,18-e.decimalsOut);return p(t).div(r).decimalPlaces(0,1)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{blake2AsHex as Hr,encodeAddress as Xr}from"@polkadot/util-crypto";var Me=class extends C{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[o]},i])=>{try{let a=i.unwrap(),l=o.toString(),c=this.getPoolAddress(l),[u,g,d]=await Promise.all([this.getPoolDelta(l,a,r.toString()),this.getPoolTokens(c,l,a),this.getPoolPegs(l,a,r.toString())]);return g.push({id:l,tradeable:15,balance:u.totalIssuance}),this.stablePools.set(c,a),{address:c,id:l,type:"Stableswap",fee:y.fromPermill(a.fee.toNumber()),tokens:g,...u,...d,...this.getPoolLimits()}}catch(a){return console.warn(`Skipping pool ${o.toString()}
|
|
2
|
-
`,String(a)),null}});return(await Promise.all(s)).filter(o=>o!==null)}async getPoolFees(e,t,r){return{fee:this.pools.find(n=>n.address===r).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)]),i=e.tokens.map(a=>a.id===e.id?{...a,balance:n.totalIssuance}:a);Object.assign(e,{tokens:i},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 o=>{let[i,a]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:i.bits.toNumber(),balance:a.toString()}});return Promise.all(n)}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=y.fromPermill(n.maxPegUpdate.toNumber()),l=y.fromPermill(t.fee.toNumber()),[c,u]=_.recalculatePegs(JSON.stringify(i),JSON.stringify(o),r,y.toRaw(a).toString(),y.toRaw(l).toString()),g=Number(c)*1e6;return{pegsFee:y.fromPermill(g),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,g=[u.toString(),n[a]].map(P=>Number(P)).sort((P,O)=>P-O),d=await this.api.query.emaOracle.oracles(l,g,c),[{price:h,updatedAt:f}]=d.unwrap(),b=h.n.toString(),w=h.d.toString();return u.toString()===g[0].toString()?[[b,w],f.toString()]:[[w,b],f.toString()]}else if(i.isMmOracle){let l=i.asMmOracle,{price:c,decimals:u,updatedAt:g}=await this.mmOracle.getData(l.toString()),d=10**u;return[[c.toString(),d.toString()],g.toString()]}else{if(i.isValue)return[i.asValue.map(l=>l.toString()),r];throw Error(i.type+" is not supported")}});return Promise.all(o)}getPoolAddress(e){let t=Number(e),r=_.getPoolAddress(t);return Xr(Hr(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toNumber()}}};var ie=class extends D{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];block=0;disconnectSubscribeNewHeads=null;memRegistry=Yr(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new $(this.api),this.aaveClient=new Re(this.api,t),this.xykClient=new De(this.api,t),this.omniClient=new _e(this.api,t),this.lbpClient=new Fe(this.api,t),this.stableClient=new Me(this.api,t),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient],this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r})}onNewBlock(e){this.block=e}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e){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(),this.disconnectSubscribeNewHeads?.()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(this.block,e,t.address);case"Xyk":return this.xykClient.getPoolFees(this.block,e,t.address);case"Omnipool":return this.omniClient.getPoolFees(this.block,e,t.address);case"Lbp":return this.lbpClient.getPoolFees(this.block,e,t.address);case"Stableswap":return this.stableClient.getPoolFees(this.block,e,t.address);default:throw new xe(t.type)}}};var ae=class extends ie{feeCache=new Map;constructor(e,t){super(e,t)}onNewBlock(e){super.onNewBlock(e),this.feeCache.clear()}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);let s=super.getPoolFees(e,t);return this.feeCache.set(r,s),s}async destroy(){this.feeCache.clear(),super.destroy()}};var oe=class{static get(e){switch(e.type){case"Aave":return Ae.fromPool(e);case"Xyk":return ke.fromPool(e);case"Omnipool":return Ee.fromPool(e);case"Lbp":return Ne.fromPool(e);case"Stableswap":return Ce.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{sha256 as Vr}from"@noble/hashes/sha256";import{bytesToHex as $r}from"@noble/hashes/utils";function ft(m){let e=m.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=Vr(t);return $r(r)}var le=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 Kr=7,ce=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],n=new le,o=[];for(o.push([t,""]),n.enqueue(o);n.size()>0;){let i=n.dequeue();if(!i||i.length>Kr)continue;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}findShortestPaths(e,t,r){let s=[],n=new le,o=[];o.push([t,""]),n.enqueue(o);let i=1/0;for(;n.size()>0;){let a=n.dequeue();if(!a)continue;let l=a[a.length-1];if(l[0]===r){a.length<i?(i=a.length,s.length=0,s.push(a)):a.length===i&&s.push(a);continue}let c=e.get(l[0]);for(let u of c??[])this.isNotVisited(u,a)&&n.enqueue([...a,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 ze(m){let e={};for(let t of m){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let n=0;n<r;n++){if(s==n)continue;let o=[t.address,t.tokens[s].id,t.tokens[n].id];e[t.tokens[s].id].push(o)}}}return e}var ue=class{getProposals(e,t,r){let s=r.filter(P=>P.type==="Xyk"),n=r.filter(P=>P.type!=="Xyk"),o=parseInt(e),i=parseInt(t),a=new Set(n.map(P=>P.tokens).flat().map(P=>P.id)),l=a.has(e),c=a.has(t),u=new ce,g=P=>{let O=ze(P),T=Object.keys(O),I=T.flatMap(v=>O[v]);return u.buildAndPopulateGraph(T,I)};if(!l&&!c){let P=s.filter(I=>I.tokens.find(v=>v.id===e)||I.tokens.find(v=>v.id===t)),O=g(P),T=u.findPaths(O,o,i);return this.parsePaths(T)}if(l&&c){let P=g(n),O=u.findShortestPaths(P,o,i);return this.parsePaths(O)}let d=l?t:e,h=s.filter(P=>P.tokens.some(O=>O.id===d)),f=[...n,...h],b=g(f),w=u.findPaths(b,o,i);return this.parsePaths(w)}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 me=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new ue,this.routeProposals=new Map,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(),t=this.getAssets(e);return[...new Map(t).values()]}async getRoutes(e,t){let r=await this.getPools();return this.validateInput(e,t,r),this.getPaths(e,t,r)}validateInput(e,t,r){if(r.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(r);if(s.get(e)===null)throw new Error(e+" is not supported asset");if(s.get(t)===null)throw new Error(t+" is not supported asset");return this.toPoolsMap(r)}getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r){let s=this.toPoolsMap(r);return this.getProposals(e,t,r).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}getProposals(e,t,r){let s=`${e}->${t}::${ft(r)}`;if(this.routeProposals.has(s))return this.routeProposals.get(s);let n=this.routeSuggester.getProposals(e,t,r);return this.routeProposals.set(s,n),n}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,oe.get(t)]))}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}})}};var zr=p("100");function yc(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function pe(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function St(m,e){return E.minus(e.div(m)).multipliedBy(100).decimalPlaces(4)}function Tt(m,e){return e.div(m).minus(E).multipliedBy(100).decimalPlaces(4)}function K(m,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),m.div(zr).multipliedBy(e).decimalPlaces(0,1)}var je=(t=>(t.Buy="Buy",t.Sell="Sell",t))(je||{}),Qe=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(Qe||{}),wt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(wt||{});var de=class extends me{async loadRouteContext(e,t){let r=await super.getPools(),s=super.validateInput(e,t,r),n=super.getPaths(e,t,r);if(n.length===0)throw new Ie(e,t);return{paths:n,pools:r,poolsMap:s}}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{paths:n,poolsMap:o}=await this.loadRouteContext(e,t),i;if(s)i=await this.toSellSwaps(r,s,o);else{let T=n.map(async v=>await this.toSellSwaps(r,v,o)),I=await Promise.all(T);i=this.findBestSellRoute(I)}let a=i[0],l=i[i.length-1],c=this.isDirectTrade(i),u=i.map(T=>T.spotPrice.shiftedBy(-1*T.assetOutDecimals)).reduce((T,I)=>T.multipliedBy(I)),g=A(u,l.assetOutDecimals),d=c?l.calculatedOut:this.calculateDelta0Y(a.amountIn,i,o),h=l.amountOut,f=c?l.tradeFeePct:St(d,h).toNumber(),b=d.minus(h),w=this.getRouteFeeRange(i),P=a.amountIn.shiftedBy(-1*a.assetInDecimals).multipliedBy(g),O=pe(d,P);return{type:"Sell",amountIn:a.amountIn,amountOut:l.amountOut,spotPrice:g,tradeFee:b,tradeFeePct:f,tradeFeeRange:w,priceImpactPct:O.toNumber(),swaps:i,toHuman(){return{type:"Sell",amountIn:x(a.amountIn,a.assetInDecimals),amountOut:x(l.amountOut,l.assetOutDecimals),spotPrice:x(g,l.assetOutDecimals),tradeFee:x(b,l.assetOutDecimals),tradeFeePct:f,tradeFeeRange:w,priceImpactPct:O.toNumber(),swaps:i.map(T=>T.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=A(p(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,i),{amountOut:u,calculatedOut:g,feePct:d,errors:h}=i.validateAndSell(a,l,c),f=this.getPoolFeeRange(c),b=i.spotPriceOutGivenIn(a),w=l.shiftedBy(-1*a.decimalsIn).multipliedBy(b),P=pe(g,w);s.push({...o,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,amountOut:u,calculatedOut:g,spotPrice:b,tradeFeePct:d,tradeFeeRange:f,priceImpactPct:P.toNumber(),errors:h,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(g,a.decimalsOut),spotPrice:x(b,a.decimalsOut),tradeFeePct:d,tradeFeeRange:f,priceImpactPct:P.toNumber(),errors:h}}})}return s}async getMostLiquidRoute(e,t){let{paths:r,pools:s,poolsMap:n}=await this.loadRouteContext(e,t),l=s.filter(d=>d.tokens.some(h=>h.id===e)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(h=>h.id===e)).map(d=>d.map(h=>p(h.balance).shiftedBy(-1*h.decimals)).reduce((h,f)=>h.plus(f))).sort((d,h)=>h.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=r.map(async d=>await this.toSellSwaps(l,d,n)),u=await Promise.all(c);return this.findBestSellRoute(u).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r;try{r=await this.loadRouteContext(e,t)}catch{return Promise.resolve(void 0)}let{poolsMap:s}=r,n=await this.getMostLiquidRoute(e,t),o=await this.toSellSwaps("1",n,s),i=o.map(c=>c.spotPrice.shiftedBy(-1*c.assetOutDecimals)).reduce((c,u)=>c.multipliedBy(u)),a=o[o.length-1].assetOutDecimals;return{amount:A(i,a),decimals:a}}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{paths:n,poolsMap:o}=await this.loadRouteContext(e,t),i;if(s)i=await this.toBuySwaps(r,s,o);else{let T=n.map(async v=>await this.toBuySwaps(r,v,o)),I=await Promise.all(T);i=this.findBestBuyRoute(I)}let a=i[i.length-1],l=i[0],c=this.isDirectTrade(i),u=i.map(T=>T.spotPrice.shiftedBy(-1*T.assetInDecimals)).reduce((T,I)=>T.multipliedBy(I)),g=A(u,l.assetInDecimals),d=c?l.calculatedIn:this.calculateDelta0X(a.amountOut,i,o),h=l.amountIn,f=c?l.tradeFeePct:Tt(d,h).toNumber(),b=h.minus(d),w=this.getRouteFeeRange(i),P=a.amountOut.shiftedBy(-1*a.assetOutDecimals).multipliedBy(g),O;return d.isZero()?O=-100:O=pe(P,d).toNumber(),{type:"Buy",amountOut:a.amountOut,amountIn:l.amountIn,spotPrice:g,tradeFee:b,tradeFeePct:f,tradeFeeRange:w,priceImpactPct:O,swaps:i,toHuman(){return{type:"Buy",amountOut:x(a.amountOut,a.assetOutDecimals),amountIn:x(l.amountIn,l.assetInDecimals),spotPrice:x(g,l.assetInDecimals),tradeFee:x(b,l.assetInDecimals),tradeFeePct:f,tradeFeeRange:w,priceImpactPct:O,swaps:i.map(T=>T.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=A(p(e),a.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(a,i),{amountIn:u,calculatedIn:g,feePct:d,errors:h}=i.validateAndBuy(a,l,c),f=this.getPoolFeeRange(c),b=i.spotPriceInGivenOut(a),w=l.shiftedBy(-1*a.decimalsOut).multipliedBy(b),P;g.isZero()?P=-100:P=pe(w,g).toNumber(),s.unshift({...o,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,amountOut:l,calculatedIn:g,spotPrice:b,tradeFeePct:d,tradeFeeRange:f,priceImpactPct:P,errors:h,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(g,a.decimalsIn),spotPrice:x(b,a.decimalsIn),tradeFeePct:d,tradeFeeRange:f,priceImpactPct:P,errors:h}}})}return s}};var Bt=6e3,Ot=p(1e15),ge=6,Ze=-5,Je=6*60*60*1e3;var xt=6;var L=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:n})=>s==="Stableswap"?{pool:{Stableswap:n},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var he=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??Bt,minBudgetInNative:t.minBudgetInNative??Ot})}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],g=l[l.length-1],{assetInDecimals:d}=u,{assetOutDecimals:h}=g,f=Math.abs(c),b=this.getMinimumTradeCount(a,o),w=this.getOptimalTradeCount(f),P=n?Math.round(s/n):w,O=Math.ceil(s/b),T=Math.round(s/w),I=Math.round(s/P),v=a.dividedBy(P).decimalPlaces(0,1),k=await this.router.getBestSell(e,t,x(v,d)),q=a.isLessThan(o),Pe=[];q&&Pe.push("OrderTooSmall");let ye=k.amountOut.multipliedBy(P),Ue=this.toBlockPeriod(I),Ge=k.tradeFee.multipliedBy(P),We=L.build(l),fe={assetIn:e,assetOut:t,errors:Pe,frequencyMin:O,frequencyOpt:T,frequency:I,tradeCount:P,tradeFee:Ge,tradeImpactPct:k.priceImpactPct,tradePeriod:Ue,tradeRoute:We,type:"Dca"};return{...fe,amountIn:a,amountOut:ye,tradeAmountIn:k.amountIn,tradeAmountOut:k.amountOut,toHuman(){return{...fe,amountIn:x(a,d),amountOut:x(ye,h),tradeAmountIn:x(k.amountIn,d),tradeAmountOut:x(k.amountOut,h)}}}}async getMinimumOrderBudget(e){if(F===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(F,e);if(t)return this.minOrderBudget.times(t.amount).div(p(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:i,priceImpactPct:a}=n,l=i[0],c=i[i.length-1],{assetInDecimals:u}=l,{assetOutDecimals:g}=c,d=Math.abs(a),h=this.getTwapTradeCount(d),f=o.dividedBy(h).decimalPlaces(0,1),b=await this.router.getBestSell(l.assetIn,c.assetOut,x(f,u)),w=h===1,P=o.isLessThan(s),O=b.priceImpactPct<Ze,T=[];P||w?T.push("OrderTooSmall"):O&&T.push("OrderImpactTooBig");let I=b.amountOut.multipliedBy(h),v=b.tradeFee.multipliedBy(h),k=L.build(i),q={assetIn:e,assetOut:t,errors:T,tradeCount:h,tradeImpactPct:b.priceImpactPct,tradePeriod:ge,tradeRoute:k,type:"TwapSell"};return{...q,amountIn:o,amountOut:I,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:v,toHuman(){return{...q,amountIn:x(o,u),amountOut:x(I,g),tradeAmountIn:x(b.amountIn,u),tradeAmountOut:x(b.amountOut,g),tradeFee:x(v,g)}}}}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:g}=c,d=Math.abs(a),h=this.getTwapTradeCount(d),f=o.dividedBy(h).decimalPlaces(0,1),b=await this.router.getBestBuy(l.assetIn,c.assetOut,x(f,g)),w=b.amountIn.multipliedBy(h),P=h===1,O=w.isLessThan(s),T=b.priceImpactPct<Ze,I=[];O||P?I.push("OrderTooSmall"):T&&I.push("OrderImpactTooBig");let v=b.tradeFee.multipliedBy(h),k=L.build(i),q={assetIn:e,assetOut:t,errors:I,tradeCount:h,tradeImpactPct:b.priceImpactPct,tradePeriod:ge,tradeRoute:k,type:"TwapBuy"};return{...q,amountIn:w,amountOut:o,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:v,toHuman(){return{...q,amountIn:x(w,u),amountOut:x(o,g),tradeAmountIn:x(b.amountIn,u),tradeAmountOut:x(b.amountOut,g),tradeFee:x(v,u)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>Je){let s=Je/(this.blockTime*ge);return Math.round(s)}return t}getTwapExecutionTime(e){return e*ge*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,xt)}};var Q=class extends D{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new M(e),this.aaveUtils=new V(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),Z)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Le=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,a=(await this.balanceClient.getBalance(this.beneficiary,n)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,o)).amount.isGreaterThanOrEqualTo(a)),l&&e.isGreaterThanOrEqualTo(a)?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(),L.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;if(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(),L.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let g=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSellAll",g,Z)}return 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(),L.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let u=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",u,Z)}return this.wrapTx("RouterSellAll",l)}};var qe=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 be=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new Le(this.api,this.evm).setTrade(e)}order(e){return new qe(this.api,this.evm).setOrder(e)}};function Fu(m){let e=new se(m),t=new ve(m),r=new ae(m,t),s=new V(t),n=new de(r),o=new he(n,{blockTime:e.blockTime,minBudgetInNative:e.minOrderBudget});return{api:{aave:s,router:n,scheduler:o},client:{asset:new $(m),balance:new M(m),balanceV2:new re(m)},ctx:{pool:r},evm:t,tx:new be(m,t),destroy:()=>{r.destroy()}}}export{J as AaveClient,Ae as AavePool,Re as AavePoolClient,V as AaveUtils,$ as AssetClient,lt as AssetNotFound,os as BASILISK_PARACHAIN_ID,M as BalanceClient,re as BalanceClientV2,B as BigNumber,ae as CachingPoolService,se as ChainParams,Mt as DECIMAL_PLACES,G as ERC20,ve as EvmClient,$e as FarmClient,z as H160,Te as HUB_ASSET_ID,ls as HYDRADX_PARACHAIN_ID,W as HYDRADX_SS58_PREFIX,ys as INFINITY,U as LbpMath,Ne as LbpPool,Fe as LbpPoolClient,E as ONE,R as OmniMath,Ee as OmniPool,_e as OmniPoolClient,Y as PERMILL_DENOMINATOR,D as PolkadotApiClient,ot as PoolConfigNotFound,j as PoolError,oe as PoolFactory,xe as PoolNotFound,ie as PoolService,N as PoolType,mt as ProviderConfigNotFound,ee as RUNTIME_DECIMALS,Ie as RouteNotFound,me as Router,tt as SYSTEM_ASSET_DECIMALS,F as SYSTEM_ASSET_ID,_ as StableMath,Ce as StableSwap,Me as StableSwapClient,ct as StorageConfigNotFound,ut as SubscriptionNotSupported,te as TRADEABLE_DEFAULT,wt as TradeOrderError,Qe as TradeOrderType,L as TradeRouteBuilder,de as TradeRouter,he as TradeScheduler,je as TradeType,be as TxBuilderFactory,X as XykMath,ke as XykPool,De as XykPoolClient,S as ZERO,Gn as bnFormatter,p as bnum,Tt as calculateBuyFee,yc as calculateDiffToAvg,pe as calculateDiffToRef,St as calculateSellFee,pt as createChain,Fu as createSdkContext,ht as findNestedKey,Un as findNestedObj,K as getFraction,ft as hashPools,kt as isEvmAccount,Dt as isEvmAddress,Ct as isSs58Address,A as scale,fs as toBn,x as toDecimals};
|
|
1
|
+
var Se=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var He=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var et="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Xe="0x112b087b60C1a166130d59266363C45F8aa99db0",Ye="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Z=1000000n;var rs=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var J=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:He,address:Xe,args:[Ye],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:He,address:Xe,args:[Ye,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:Se,address:et,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as we,encodeAddress as rt}from"@polkadot/util-crypto";import{hexToU8a as Ft,isHex as Et,u8aToHex as kt}from"@polkadot/util";import{Buffer as H}from"buffer";var os=2090,Y=1e6,Te="1",ls=2034,W=63,ee=18,F="0",tt=12,te=15;var Ve="ETH\0";function _t(m){if(!m)return!1;try{let e=we(m,!0),t=H.from(Ve);return H.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Dt(m){return!!/^0x[a-fA-F0-9]{40}$/.test(m)}function Ct(m){try{let e=Et(m)?Ft(m):we(m);return rt(e),!0}catch{return!1}}var z=class m{static toAccount=e=>{let t=H.from(e.slice(2),"hex"),r=H.from(Ve);return rt(new Uint8Array(H.concat([r,t,H.alloc(8)])),63)};static fromAccount=e=>{let t=we(e),r=H.from(Ve),s=t.slice(r.length,-8);return"0x"+H.from(s).toString("hex")};static fromSS58=e=>{let r=we(e).slice(0,20);return kt(r)};static fromAny=e=>{if(Dt(e))return e;if(_t(e))return m.fromAccount(e);if(Ct(e))return m.fromSS58(e);throw new Error("Unknown address type")}};import{Buffer as Be}from"buffer";var G=class{static fromAssetId(e){let t=Number(e),r=Be.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Be.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Be.from("0000000000000000000000000000000100000000","hex"),r=Be.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as B}from"bignumber.js";var Mt=12;B.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Mt});var S=p(0),E=p(1),ys=p("Infinity");function A(m,e){let t=new B(e.toString()),r=new B(10).pow(t);return m.times(r).decimalPlaces(4)}function p(m){return new B(m.toString())}function fs(m,e){let t=p(m);return A(t,e)}function x(m,e){return m.shiftedBy(-1*e).toString()}var Oe=p("1e27"),Lt=p("1.01"),qt=p("31536000"),V=class{client;constructor(e){this.client=new J(e)}async getSummary(e){let t=z.fromAny(e),[r,s,n,o]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[i]=r,[a,l]=s,[c,u,g,d,h,f]=n,b=p(f).dividedBy(1e18).decimalPlaces(6,B.ROUND_DOWN),w=p(c),P=p(u),O=[];for(let T of a){let I=T.underlyingAsset.toLowerCase(),v=i.find(({underlyingAsset:Nt})=>Nt.toLowerCase()===I);if(!v)throw new Error("Missing pool reserve for "+I);let _=p(T.scaledATokenBalance),q=p(v.liquidityIndex),Pe=p(v.liquidityRate),ye=p(v.availableLiquidity),Ue=p(v.priceInMarketReferenceCurrency),Ge=o+6,We=this.calculateLinearInterest(Pe,v.lastUpdateTimestamp,Ge),fe=q.multipliedBy(We).dividedBy(Oe).decimalPlaces(0,B.ROUND_DOWN),It=_.multipliedBy(fe).dividedBy(Oe).decimalPlaces(0,B.ROUND_DOWN),vt=p(l!==0&&l===v.eModeCategoryId?v.eModeLiquidationThreshold:v.reserveLiquidationThreshold).div(1e4),At=v.usageAsCollateralEnabled&&T.usageAsCollateralEnabledOnUser&&p(T.scaledATokenBalance).gt(0),Rt=G.toAssetId(I);O.push({aTokenBalance:It,availableLiquidity:ye,decimals:Number(v.decimals),isCollateral:At,priceInRef:Ue,reserveId:Rt,reserveAsset:I,reserveLiquidationThreshold:vt})}return{healthFactor:b.toNumber(),totalCollateral:w,totalDebt:P,reserves:O}}async hasBorrowPositions(e){let t=z.fromAny(e),r=await this.client.getUserAccountData(t),[s,n]=r;return n>0n}async getHealthFactor(e){let t=z.fromAny(e),r=await this.client.getUserAccountData(t),[s,n,o,i,a,l]=r;return p(l).dividedBy(1e18).decimalPlaces(6,B.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:n,reserves:o}=await this.getSummary(e),i=G.fromAssetId(t),a=o.find(w=>w.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:c,priceInRef:u,reserveLiquidationThreshold:g}=a,d=A(p(r),l).decimalPlaces(0,1),h=c?d.multipliedBy(u).dividedBy(p(10).pow(l)).decimalPlaces(0,B.ROUND_DOWN):S,f=s.minus(h);return f.lte(0)?0:f.multipliedBy(g).dividedBy(n).decimalPlaces(6,B.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:n,reserves:o}=await this.getSummary(e),i=G.fromAssetId(t),a=o.find(b=>b.reserveAsset===i);if(!a)throw new Error("Missing reserve ctx for "+i);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:u}=a,d=A(p(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(p(10).pow(l)).decimalPlaces(0,B.ROUND_DOWN),h=s.plus(d);return h.lte(0)?0:h.multipliedBy(u).dividedBy(n).decimalPlaces(6,B.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:n}=await this.getSummary(e),o=G.fromAssetId(t),i=s.find(a=>a.reserveAsset===o);if(!i)throw new Error("Missing reserve data for "+o);return this.calculateWithdrawMax(i,r,n)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),n={};for(let o of r){let i=this.calculateWithdrawMax(o,t,s);o.reserveId&&(n[o.reserveId]=i)}return n}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:n,decimals:o,priceInRef:i,reserveLiquidationThreshold:a,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let g=p(r).minus(Lt);if(g.gt(0)){let h=g.multipliedBy(t).dividedBy(a).decimalPlaces(0,B.ROUND_DOWN).dividedBy(i).multipliedBy(p(10).pow(o)).decimalPlaces(0,B.ROUND_DOWN);c=B.minimum(s,h)}else c=S}return{amount:B.minimum(c,n),decimals:o}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Oe:e.multipliedBy(s).dividedBy(qt).plus(Oe).decimalPlaces(0,B.ROUND_DOWN)}};function st(m){switch(m){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var D=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 $=class extends D{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},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==F){let u=this.api.consts.balances.existentialDeposit;return{id:F,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),g=o.toNumber(),d=new Intl.DateTimeFormat("en-GB"),h=[c,"Bond",d.format(g)].join(" ");return{id:e,name:h,symbol:c+"b",decimals:u,icon:c,type:i.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:n.toString(),maturity:g}}getShares(e,t,r,s){let{assets:n}=s,{name:o,symbol:i,assetType:a,isSufficient:l,existentialDeposit:c}=t,g=n.map(f=>f.toString()).map(f=>{let{symbol:b}=this.getToken(f,t,r);return[f,b]}),d=Object.fromEntries(g),h=Object.values(d);return{id:e,name:h.join(", "),symbol:i?.isSome?i.toHuman():o.toHuman(),decimals:18,icon:h.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]},g])=>{let d=g.unwrap(),h=s.get(u.toString()),{assetType:f}=d;switch(f.toString()){case"Bond":let b=o.get(u.toString());return this.getBond(u.toString(),d,l,b);case"StableSwap":let w=n.get(u.toString());return this.getShares(u.toString(),d,l,w);case"External":return this.getExternal(u.toString(),d,t,h);default:return this.getToken(u.toString(),d,l,h)}});return e?c:c.filter(u=>this.isValidAsset(u))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var M=class extends D{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===F?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(F,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 t=e.free.toString(),r=e.frozen.toString();return B(t).lt(r)?B(0):B(t).minus(r)}};var re=class extends D{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===F?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t(F,this.calculateBalance(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=n[l][1],u=this.calculateBalance(a);i.push([c,u])}),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)}calculateBalance(e){let t=B(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),n=t.gte(r)?t.minus(r).toString():"0",o=t.plus(s).toString();return{free:t.toString(),total:o,transferable:n,reserved:s,frozen:r}}};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()),p(this._minOrderBudget)}};import{fixed_from_rational as nt}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as Ut}from"@polkadot/types";import{u8aConcat as it}from"@polkadot/util";import{isAddress as at}from"@polkadot/util-crypto";var $e=class extends D{balanceClient;constructor(e){super(e),this.balanceClient=new M(e)}secondsInYear=new B(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(),h=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:f.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,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(),h=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(d,h);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:f.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new B(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 Ut(e,this.padEndU8a(it(s,n,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!at(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&at(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 B(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),d=new B(a.yieldPerPeriod.toString()),h=new B(a.maxRewardPerPeriod.toString()),f=a.blocksPerPeriod.toString(),b=new B(i.multiplier.toString()).shiftedBy(-18),w=this.secondsInYear.div(new B(r).times(f)),P;if(u.isZero())P=d.times(b).times(w);else{let _=this.getGlobalRewardPerPeriod(u,d,h,l);P=this.getPoolYieldPerPeriod(_,b,u,l).times(w)}let O=new B(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),T=h.times(g),I=c?O.plus(c):T;return O.div(I).gte(.999)?S:P.div(t==="isolatedpool"?2:1).times(100)}).reduce((i,a)=>i.plus(a),S).toString():void 0}};var xe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},ot=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ie=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{defineChain as Gt}from"viem";var Wt=["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"],pt=m=>{let t=[m.endpoint,...Wt],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return Gt({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1})};import{createPublicClient as gt,createWalletClient as Ht,custom as Xt,http as Yt}from"viem";function dt(m){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return m.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var ve=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=pt(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return gt({chain:this.chain,transport:Yt()})}getWsProvider(){return gt({chain:this.chain,transport:dt(this.wsProvider)})}getSigner(e){return Ht({account:e,chain:this.chain,transport:Xt(window.ethereum)})}};import{memoize1 as Yr}from"@thi.ng/memoize";var N=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n))(N||{}),j=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n))(j||{});var Ae=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,n){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(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=p(s.balance),i=p(n.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:o,balanceOut:i,assetInED:S,assetOutED:S}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),n=[];return t.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:t,feePct:0,errors:n}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),n=[];return s.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:t,calculatedOut:s,amountOut:s,feePct:0,errors:n}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return A(E,e.decimalsOut)}spotPriceOutGivenIn(e){return A(E,e.decimalsIn)}calculateTradeFee(e,t){return S}};import{encodeAddress as Kt}from"@polkadot/util-crypto";import{stringToU8a as zt}from"@polkadot/util";import{decodeEventLog as jt}from"viem";function ht(m,e){let t=[];return JSON.stringify(m,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Un(m,e,t){let r;return JSON.stringify(m,(s,n)=>(n&&n[e]===t&&(r=n),n)),r}var Gn=(m,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as Vt}from"@thi.ng/memoize";import{TLRUCache as $t}from"@thi.ng/cache";var Ke=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var ne=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,n]=await Promise.all([this.client.readContract({abi:Ke,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:Ke,address:e,functionName:"decimals"}),this.client.getBlock()]),[o,i,a,l]=r,c=n.number-(n.timestamp-l)/BigInt(t),u=Number(c);return{price:i,decimals:s,updatedAt:u<0?0:u}}};var C=class extends M{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new $t(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=Vt(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new ne(t)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let r=[];try{let n=this.subscribePoolChange(t);r.push(n)}catch{}if(t.type==="Aave")return r;let s=this.subscribeTokensPoolBalance(t);if(r.push(s),this.hasSystemAsset(t)){let n=this.subscribeSystemPoolBalance(t);r.push(n)}if(this.hasErc20Asset(t)){let n=this.subscribeErc20PoolBalance(t);r.push(n)}return this.subscribeLog(t),r}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,n])=>{let 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 Qt=["Supply","Withdraw","Repay","Borrow"],Re=class extends C{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:n})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:n.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t,r){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let r=e+"/"+t;return Kt(zt(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,""),g=c.replace(/,/g,"");(u===r.id||g===r.id)&&(this.log(`Sync AAVE [router:Executed] :: ${u}:${g}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=i.data.toHuman();try{let{eventName:c,args:u}=jt({abi:Se,topics:l.topics,data:l.data});Qt.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"?ht(e.location,"accountKey20").accountKey20.key:G.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as Zt,calculate_out_given_in as Jt,calculate_linear_weights as er,calculate_pool_trade_fee as tr,get_spot_price as rr}from"@galacticcouncil/math-lbp";var U=class{static getSpotPrice(e,t,r,s,n){return rr(e,t,r,s,n)}static calculateInGivenOut(e,t,r,s,n){return Zt(e,t,r,s,n)}static calculateOutGivenIn(e,t,r,s,n){return Jt(e,t,r,s,n)}static calculateLinearWeights(e,t,r,s,n){return er(e,t,r,s,n)}static calculatePoolTradeFee(e,t,r){return tr(e,t,r)}};var y=class m{static toPct(e){let[t,r]=e;return m.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return m.safeDivide(t,r)}static fromPermill(e){return[e,1e6]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,r=12){let s=10**r;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};var Ne=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,r,s,n,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=p(s.balance),i=p(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=U.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=U.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=U.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),A(E,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=U.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),A(E,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=U.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var Fe=class extends C{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(([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());this.poolsData.set(n.toString(),i);let[c,u]=i.fee;return{address:a,type:"Lbp",fee:y.fromRate(c.toNumber(),u.toNumber()),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t,r){let s=this.pools.find(n=>n.address===r);return{repayFee:this.getRepayFee(),exchangeFee:s.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=U.calculateLinearWeights(s.toString(),n.toString(),i.toString(),a.toString(),r),[g,d]=o,h=g.toString(),f=p(u),b=d.toString(),w=this.MAX_FINAL_WEIGHT.minus(p(f)),[P,O,T]=await Promise.all([this.isRepayFeeApplied(h,l.toString(),c.toString()),this.getBalance(e,h),this.getBalance(e,b)]);return{repayFeeApply:P,tokens:[{id:h,weight:f,balance:O.toString()},{id:b,weight:w,balance:T.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(){let[e,t]=this.api.consts.lbp.repayFee;return y.fromRate(e.toNumber(),t.toNumber())}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toNumber(),t=this.api.consts.lbp.maxOutRatio.toNumber(),r=this.api.consts.lbp.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as sr,calculate_lrna_in_given_out as nr,calculate_out_given_in as ir,calculate_out_given_lrna_in as ar,calculate_spot_price as or,calculate_lrna_spot_price as lr,calculate_shares as cr,calculate_liquidity_out as ur,calculate_liquidity_lrna_out as mr,calculate_liquidity_hub_in as pr,is_sell_allowed as dr,is_buy_allowed as gr,is_add_liquidity_allowed as hr,is_remove_liquidity_allowed as br,recalculate_asset_fee as Pr,recalculate_protocol_fee as yr,verify_asset_cap as fr}from"@galacticcouncil/math-omnipool";var R=class{static calculateSpotPrice(e,t,r,s){return or(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return lr(e,t)}static calculateInGivenOut(e,t,r,s,n,o,i,a,l){return sr(e,t,r,s,n,o,i,a,l)}static calculateLrnaInGivenOut(e,t,r,s,n){return nr(e,t,r,s,n)}static calculateOutGivenIn(e,t,r,s,n,o,i,a,l){return ir(e,t,r,s,n,o,i,a,l)}static calculateOutGivenLrnaIn(e,t,r,s,n){return ar(e,t,r,s,n)}static calculateShares(e,t,r,s){return cr(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,n,o,i,a){return ur(e,t,r,s,n,o,i,a)}static calculateLiquidityLRNAOut(e,t,r,s,n,o,i,a){return mr(e,t,r,s,n,o,i,a)}static calculateCapDifference(e,t,r,s){let n=B(t),o=B(e),i=B(s),l=B(r).shiftedBy(-18);if(n.div(i).lt(l)){let u=l.times(i).minus(n).times(o),g=n.times(B(1).minus(l));return u.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return pr(e,t,r,s)}static isSellAllowed(e){return dr(e)}static isBuyAllowed(e){return gr(e)}static isAddLiquidityAllowed(e){return hr(e)}static isRemoveLiquidityAllowed(e){return br(e)}static recalculateAssetFee(e,t,r,s,n,o,i,a,l,c,u){return Pr(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 yr(e,t,r,s,n,o,i,a,l,c,u)}static verifyAssetCap(e,t,r,s){return fr(e,t,r,s)}};var Ee=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,r,s,n,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=p(s.balance),i=p(n.balance),a=p(s.existentialDeposit),l=p(n.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:n.hubReserves,sharesIn:s.shares,sharesOut:n.shares,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn: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===S?S:o.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=R.isSellAllowed(e.tradeableIn),c=R.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 g=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(g)&&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(4),a=[],l=R.isSellAllowed(e.tradeableIn),c=R.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 g=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(g)&&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=R.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),n=p(s);return n.isNegative()?S:n}calculateLrnaInGivenOut(e,t,r){let s=R.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),n=p(s);return n.isNegative()?S:n}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=R.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),n=p(s);return n.isNegative()?S:n}calculateOutGivenLrnaIn(e,t,r){let s=R.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),n=p(s);return n.isNegative()?S:n}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=R.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=R.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=R.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=R.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as Sr}from"@polkadot/util-crypto";import{stringToU8a as Tr}from"@polkadot/util";import{memoize1 as bt}from"@thi.ng/memoize";import{TLRUCache as wr}from"@thi.ng/cache";var Pt="omnipool",yt="Short",ke=class extends C{dynamicFees=new Map;oracles=new Map;memQueryCache=new wr(null,{ttl:6*1e3});memOracleQuery=bt(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(Pt,t,yt)},this.memQueryCache);memFeesQuery=bt(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);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:g,cap:d,protocolShares:h}=l.unwrap(),f=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(c.toString()),shares:p(u.toString()),tradeable:g.bits.toNumber(),balance:f.toString(),cap:p(d.toString()),protocolShares:p(h.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 getDynamicFees(e){return this.dynamicFees.has(e)?this.dynamicFees.get(e):this.memFeesQuery(e)}async getOraclePrice(e){let r=this.getOracleKey(e).join(":");return this.oracles.has(r)?this.oracles.get(r):this.memOracleQuery(r)}async getPoolFees(e,t,r){let s=t.assetOut,n=t.assetIn,[o,i,a]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(n)]),[l,c,u]=this.getAssetFee(t,e,o,i),[g,d,h]=n===Te?[0,0,0]:this.getProtocolFee(t,e,o,a),f=l+g,b=u+h;return{assetFee:y.fromPermill(c),protocolFee:y.fromPermill(d),min:y.fromPermill(f),max:y.fromPermill(b)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(a=>a.id),r=[],s=await this.api.query.omnipool.assets.multi(t,a=>{e.tokens=a.map((l,c)=>{let u=e.tokens[c];if(l.isNone)return u;let g=l.unwrap();return this.updateTokenState(u,g)})});r.push(s);let n=await this.api.query.dynamicFees.assetFee.multi(t,a=>{a.forEach((l,c)=>{let u=t[c];this.dynamicFees.set(u,l)})});r.push(n);let o=t.map(a=>{let l=this.getOracleKey(a);return[Pt,l,yt]}),i=await this.api.query.emaOracle.oracles.multi(o,a=>{a.forEach(async(l,c)=>{let u=o[c],[g,d,h]=u;this.oracles.set(d.join(":"),l)})});return r.push(i),()=>{for(let a of r)try{a()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:n,cap:o,protocolShares:i}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(o.toString()),protocolShares:p(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()),g=y.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[i.toNumber(),i.toNumber(),a.toNumber()];let[d]=s.unwrap(),{assetFee:h,timestamp:f}=r.unwrap(),b=Math.max(1,t-f.toNumber()),w=d.volume.bIn.toString(),P=d.volume.bOut.toString(),O=d.liquidity.b.toString();n===F&&(w=d.volume.aIn.toString(),P=d.volume.aOut.toString(),O=d.liquidity.a.toString());let T=y.fromPermill(h.toNumber()),I=R.recalculateAssetFee(w,P,O,"9",o.toString(),y.toRaw(T).toString(),b.toString(),y.toRaw(u).toString(),y.toRaw(g).toString(),l.toString(),c.toString());return[i.toNumber(),Number(I)*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()),g=y.fromPermill(a.toNumber());if(r.isNone||s.isNone)return[i.toNumber(),i.toNumber(),a.toNumber()];let[d]=s.unwrap(),{protocolFee:h,timestamp:f}=r.unwrap(),b=Math.max(1,t-f.toNumber()),w=d.volume.bIn.toString(),P=d.volume.bOut.toString(),O=d.liquidity.b.toString();n===F&&(w=d.volume.aIn.toString(),P=d.volume.aOut.toString(),O=d.liquidity.a.toString());let T=y.fromPermill(h.toNumber()),I=R.recalculateProtocolFee(w,P,O,"9",o.toString(),y.toRaw(T).toString(),b.toString(),y.toRaw(u).toString(),y.toRaw(g).toString(),l.toString(),c.toString());return[i.toNumber(),Number(I)*1e6,a.toNumber()]}getOracleKey(e){return e===F?[F,Te]:[Te,e]}getPoolId(){return Sr(Tr("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toNumber(),t=this.api.consts.omnipool.maxOutRatio.toNumber(),r=this.api.consts.omnipool.minimumTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as Br,calculate_out_given_in as Or,calculate_pool_trade_fee as xr,get_spot_price as Ir,calculate_liquidity_in as vr,calculate_shares as Ar,calculate_spot_price as Rr,calculate_spot_price_with_fee as Nr,calculate_liquidity_out_asset_a as Fr,calculate_liquidity_out_asset_b as Er}from"@galacticcouncil/math-xyk";var X=class{static getSpotPrice(e,t,r){return Ir(e,t,r)}static calculateInGivenOut(e,t,r){return Br(e,t,r)}static calculateOutGivenIn(e,t,r){return Or(e,t,r)}static calculatePoolTradeFee(e,t,r){return xr(e,t,r)}static calculateLiquidityIn(e,t,r){return vr(e,t,r)}static calculateSpotPrice(e,t){return Rr(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return Nr(e,t,r,s)}static calculateShares(e,t,r){return Ar(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return Fr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Er(e,t,r,s)}};var _e=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,r,s,n){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=r,this.maxOutRatio=s,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(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=p(s.balance),i=p(n.balance),a=p(s.existentialDeposit),l=p(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=X.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=X.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=X.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=A(E,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=X.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=A(E,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=X.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var De=class extends C{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let n=r.toString(),[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,r){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){let[e,t]=this.api.consts.xyk.getExchangeFee;return y.fromRate(e.toNumber(),t.toNumber())}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toNumber(),t=this.api.consts.xyk.maxOutRatio.toNumber(),r=this.api.consts.xyk.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}};import{calculate_in_given_out as kr,calculate_out_given_in as _r,calculate_amplification as Dr,calculate_add_one_asset as Cr,calculate_liquidity_out_one_asset as Mr,calculate_shares as Lr,calculate_shares_for_amount as qr,calculate_spot_price_with_fee as Ur,pool_account_name as Gr,recalculate_peg as Wr}from"@galacticcouncil/math-stableswap";var k=class{static getPoolAddress(e){return Gr(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 Dr(e,t,r,s,n)}static calculateInGivenOut(e,t,r,s,n,o,i){return kr(e,t,r,s,n,o,i)}static calculateAddOneAsset(e,t,r,s,n,o,i){return Cr(e,t,r,s,n,o,i)}static calculateSharesForAmount(e,t,r,s,n,o,i){return qr(e,t,r,s,n,o,i)}static calculateOutGivenIn(e,t,r,s,n,o,i){return _r(e,t,r,s,n,o,i)}static calculateLiquidityOutOneAsset(e,t,r,s,n,o,i){return Mr(e,t,r,s,n,o,i)}static calculateShares(e,t,r,s,n,o){return Lr(e,t,r,s,n,o)}static calculateSpotPriceWithFee(e,t,r,s,n,o,i,a){return Ur(e,t,r,s,n,o,i,a)}static recalculatePegs(e,t,r,s,n){let o=Wr(e,t,r,s,n);return JSON.parse(o)}};var Ce=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,r,s,n,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=p(s.balance),i=p(n.balance),a=p(s.existentialDeposit),l=p(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=n.minus(s),i=s===S?S:o.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount"),{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(4),a=[],l=R.isSellAllowed(e.tradeableIn),c=R.isBuyAllowed(e.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:i.toNumber(),errors:a}}calculateIn(e,t,r){let s=k.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateAddOneAsset(e,t,r){let s=k.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateSharesForAmount(e,t,r){let s=k.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=k.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let s=A(E,e.decimalsIn-e.decimalsOut);return p(t).div(s).decimalPlaces(0,1)}let r=A(E,18-e.decimalsIn);return p(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=k.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateWithdrawOneAsset(e,t,r){let s=k.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateShares(e,t,r){let s=k.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),n=p(s);return n.isNegative()?S:n}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=k.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let s=A(E,e.decimalsOut-e.decimalsIn);return p(t).div(s).decimalPlaces(0,1)}let r=A(E,18-e.decimalsOut);return p(t).div(r).decimalPlaces(0,1)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{blake2AsHex as Hr,encodeAddress as Xr}from"@polkadot/util-crypto";var Me=class extends C{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[o]},i])=>{try{let a=i.unwrap(),l=o.toString(),c=this.getPoolAddress(l),[u,g,d]=await Promise.all([this.getPoolDelta(l,a,r.toString()),this.getPoolTokens(c,l,a),this.getPoolPegs(l,a,r.toString())]);return g.push({id:l,tradeable:15,balance:u.totalIssuance}),this.stablePools.set(c,a),{address:c,id:l,type:"Stableswap",fee:y.fromPermill(a.fee.toNumber()),tokens:g,...u,...d,...this.getPoolLimits()}}catch(a){return console.warn(`Skipping pool ${o.toString()}
|
|
2
|
+
`,String(a)),null}});return(await Promise.all(s)).filter(o=>o!==null)}async getPoolFees(e,t,r){return{fee:this.pools.find(n=>n.address===r).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)]),i=e.tokens.map(a=>a.id===e.id?{...a,balance:n.totalIssuance}:a);Object.assign(e,{tokens:i},n,o)}})}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:n,initialBlock:o,finalBlock:i}=t,a=k.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 o=>{let[i,a]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:i.bits.toNumber(),balance:a.toString()}});return Promise.all(n)}getPoolDefaultPegs(e){let t=e.fee,r=k.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=y.fromPermill(n.maxPegUpdate.toNumber()),l=y.fromPermill(t.fee.toNumber()),[c,u]=k.recalculatePegs(JSON.stringify(i),JSON.stringify(o),r,y.toRaw(a).toString(),y.toRaw(l).toString()),g=Number(c)*1e6;return{pegsFee:y.fromPermill(g),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,g=[u.toString(),n[a]].map(P=>Number(P)).sort((P,O)=>P-O),d=await this.api.query.emaOracle.oracles(l,g,c),[{price:h,updatedAt:f}]=d.unwrap(),b=h.n.toString(),w=h.d.toString();return u.toString()===g[0].toString()?[[b,w],f.toString()]:[[w,b],f.toString()]}else if(i.isMmOracle){let l=i.asMmOracle,{price:c,decimals:u,updatedAt:g}=await this.mmOracle.getData(l.toString()),d=10**u;return[[c.toString(),d.toString()],g.toString()]}else{if(i.isValue)return[i.asValue.map(l=>l.toString()),r];throw Error(i.type+" is not supported")}});return Promise.all(o)}getPoolAddress(e){let t=Number(e),r=k.getPoolAddress(t);return Xr(Hr(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toNumber()}}};var ie=class extends D{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];block=0;disconnectSubscribeNewHeads=null;memRegistry=Yr(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new $(this.api),this.aaveClient=new Re(this.api,t),this.xykClient=new De(this.api,t),this.omniClient=new ke(this.api,t),this.lbpClient=new Fe(this.api,t),this.stableClient=new Me(this.api,t),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient],this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r})}onNewBlock(e){this.block=e}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e){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(),this.disconnectSubscribeNewHeads?.()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(this.block,e,t.address);case"Xyk":return this.xykClient.getPoolFees(this.block,e,t.address);case"Omnipool":return this.omniClient.getPoolFees(this.block,e,t.address);case"Lbp":return this.lbpClient.getPoolFees(this.block,e,t.address);case"Stableswap":return this.stableClient.getPoolFees(this.block,e,t.address);default:throw new xe(t.type)}}};var ae=class extends ie{feeCache=new Map;constructor(e,t){super(e,t)}onNewBlock(e){super.onNewBlock(e),this.feeCache.clear()}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);let s=super.getPoolFees(e,t);return this.feeCache.set(r,s),s}async destroy(){this.feeCache.clear(),super.destroy()}};var oe=class{static get(e){switch(e.type){case"Aave":return Ae.fromPool(e);case"Xyk":return _e.fromPool(e);case"Omnipool":return Ee.fromPool(e);case"Lbp":return Ne.fromPool(e);case"Stableswap":return Ce.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{sha256 as Vr}from"@noble/hashes/sha256";import{bytesToHex as $r}from"@noble/hashes/utils";function ft(m){let e=m.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=Vr(t);return $r(r)}var le=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 Kr=7,ce=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],n=new le,o=[];for(o.push([t,""]),n.enqueue(o);n.size()>0;){let i=n.dequeue();if(!i||i.length>Kr)continue;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}findShortestPaths(e,t,r){let s=[],n=new le,o=[];o.push([t,""]),n.enqueue(o);let i=1/0;for(;n.size()>0;){let a=n.dequeue();if(!a)continue;let l=a[a.length-1];if(l[0]===r){a.length<i?(i=a.length,s.length=0,s.push(a)):a.length===i&&s.push(a);continue}let c=e.get(l[0]);for(let u of c??[])this.isNotVisited(u,a)&&n.enqueue([...a,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 ze(m){let e={};for(let t of m){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let n=0;n<r;n++){if(s==n)continue;let o=[t.address,t.tokens[s].id,t.tokens[n].id];e[t.tokens[s].id].push(o)}}}return e}var ue=class{getProposals(e,t,r){let s=r.filter(P=>P.type==="Xyk"),n=r.filter(P=>P.type!=="Xyk"),o=parseInt(e),i=parseInt(t),a=new Set(n.map(P=>P.tokens).flat().map(P=>P.id)),l=a.has(e),c=a.has(t),u=new ce,g=P=>{let O=ze(P),T=Object.keys(O),I=T.flatMap(v=>O[v]);return u.buildAndPopulateGraph(T,I)};if(!l&&!c){let P=s.filter(I=>I.tokens.find(v=>v.id===e)||I.tokens.find(v=>v.id===t)),O=g(P),T=u.findPaths(O,o,i);return this.parsePaths(T)}if(l&&c){let P=g(n),O=u.findPaths(P,o,i);return this.parsePaths(O)}let d=l?t:e,h=s.filter(P=>P.tokens.some(O=>O.id===d)),f=[...n,...h],b=g(f),w=u.findPaths(b,o,i);return this.parsePaths(w)}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 me=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new ue,this.routeProposals=new Map,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(),t=this.getAssets(e);return[...new Map(t).values()]}async getRoutes(e,t){let r=await this.getPools();return this.validateInput(e,t,r),this.getPaths(e,t,r)}validateInput(e,t,r){if(r.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(r);if(s.get(e)===null)throw new Error(e+" is not supported asset");if(s.get(t)===null)throw new Error(t+" is not supported asset");return this.toPoolsMap(r)}getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r){let s=this.toPoolsMap(r);return this.getProposals(e,t,r).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}getProposals(e,t,r){let s=`${e}->${t}::${ft(r)}`;if(this.routeProposals.has(s))return this.routeProposals.get(s);let n=this.routeSuggester.getProposals(e,t,r);return this.routeProposals.set(s,n),n}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,oe.get(t)]))}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}})}};var zr=p("100");function yc(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function pe(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function St(m,e){return E.minus(e.div(m)).multipliedBy(100).decimalPlaces(4)}function Tt(m,e){return e.div(m).minus(E).multipliedBy(100).decimalPlaces(4)}function K(m,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),m.div(zr).multipliedBy(e).decimalPlaces(0,1)}var je=(t=>(t.Buy="Buy",t.Sell="Sell",t))(je||{}),Qe=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(Qe||{}),wt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(wt||{});var de=class extends me{async loadRouteContext(e,t){let r=await super.getPools(),s=super.validateInput(e,t,r),n=super.getPaths(e,t,r);if(n.length===0)throw new Ie(e,t);return{paths:n,pools:r,poolsMap:s}}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{paths:n,poolsMap:o}=await this.loadRouteContext(e,t),i;if(s)i=await this.toSellSwaps(r,s,o);else{let T=n.map(async v=>await this.toSellSwaps(r,v,o)),I=await Promise.all(T);i=this.findBestSellRoute(I)}let a=i[0],l=i[i.length-1],c=this.isDirectTrade(i),u=i.map(T=>T.spotPrice.shiftedBy(-1*T.assetOutDecimals)).reduce((T,I)=>T.multipliedBy(I)),g=A(u,l.assetOutDecimals),d=c?l.calculatedOut:this.calculateDelta0Y(a.amountIn,i,o),h=l.amountOut,f=c?l.tradeFeePct:St(d,h).toNumber(),b=d.minus(h),w=this.getRouteFeeRange(i),P=a.amountIn.shiftedBy(-1*a.assetInDecimals).multipliedBy(g),O=pe(d,P);return{type:"Sell",amountIn:a.amountIn,amountOut:l.amountOut,spotPrice:g,tradeFee:b,tradeFeePct:f,tradeFeeRange:w,priceImpactPct:O.toNumber(),swaps:i,toHuman(){return{type:"Sell",amountIn:x(a.amountIn,a.assetInDecimals),amountOut:x(l.amountOut,l.assetOutDecimals),spotPrice:x(g,l.assetOutDecimals),tradeFee:x(b,l.assetOutDecimals),tradeFeePct:f,tradeFeeRange:w,priceImpactPct:O.toNumber(),swaps:i.map(T=>T.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=A(p(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,i),{amountOut:u,calculatedOut:g,feePct:d,errors:h}=i.validateAndSell(a,l,c),f=this.getPoolFeeRange(c),b=i.spotPriceOutGivenIn(a),w=l.shiftedBy(-1*a.decimalsIn).multipliedBy(b),P=pe(g,w);s.push({...o,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,amountOut:u,calculatedOut:g,spotPrice:b,tradeFeePct:d,tradeFeeRange:f,priceImpactPct:P.toNumber(),errors:h,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(g,a.decimalsOut),spotPrice:x(b,a.decimalsOut),tradeFeePct:d,tradeFeeRange:f,priceImpactPct:P.toNumber(),errors:h}}})}return s}async getMostLiquidRoute(e,t){let{paths:r,pools:s,poolsMap:n}=await this.loadRouteContext(e,t),l=s.filter(d=>d.tokens.some(h=>h.id===e)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(h=>h.id===e)).map(d=>d.map(h=>p(h.balance).shiftedBy(-1*h.decimals)).reduce((h,f)=>h.plus(f))).sort((d,h)=>h.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=r.map(async d=>await this.toSellSwaps(l,d,n)),u=await Promise.all(c);return this.findBestSellRoute(u).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let r;try{r=await this.loadRouteContext(e,t)}catch{return Promise.resolve(void 0)}let{poolsMap:s}=r,n=await this.getMostLiquidRoute(e,t),o=await this.toSellSwaps("1",n,s),i=o.map(c=>c.spotPrice.shiftedBy(-1*c.assetOutDecimals)).reduce((c,u)=>c.multipliedBy(u)),a=o[o.length-1].assetOutDecimals;return{amount:A(i,a),decimals:a}}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{paths:n,poolsMap:o}=await this.loadRouteContext(e,t),i;if(s)i=await this.toBuySwaps(r,s,o);else{let T=n.map(async v=>await this.toBuySwaps(r,v,o)),I=await Promise.all(T);i=this.findBestBuyRoute(I)}let a=i[i.length-1],l=i[0],c=this.isDirectTrade(i),u=i.map(T=>T.spotPrice.shiftedBy(-1*T.assetInDecimals)).reduce((T,I)=>T.multipliedBy(I)),g=A(u,l.assetInDecimals),d=c?l.calculatedIn:this.calculateDelta0X(a.amountOut,i,o),h=l.amountIn,f=c?l.tradeFeePct:Tt(d,h).toNumber(),b=h.minus(d),w=this.getRouteFeeRange(i),P=a.amountOut.shiftedBy(-1*a.assetOutDecimals).multipliedBy(g),O;return d.isZero()?O=-100:O=pe(P,d).toNumber(),{type:"Buy",amountOut:a.amountOut,amountIn:l.amountIn,spotPrice:g,tradeFee:b,tradeFeePct:f,tradeFeeRange:w,priceImpactPct:O,swaps:i,toHuman(){return{type:"Buy",amountOut:x(a.amountOut,a.assetOutDecimals),amountIn:x(l.amountIn,l.assetInDecimals),spotPrice:x(g,l.assetInDecimals),tradeFee:x(b,l.assetInDecimals),tradeFeePct:f,tradeFeeRange:w,priceImpactPct:O,swaps:i.map(T=>T.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=A(p(e),a.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(a,i),{amountIn:u,calculatedIn:g,feePct:d,errors:h}=i.validateAndBuy(a,l,c),f=this.getPoolFeeRange(c),b=i.spotPriceInGivenOut(a),w=l.shiftedBy(-1*a.decimalsOut).multipliedBy(b),P;g.isZero()?P=-100:P=pe(w,g).toNumber(),s.unshift({...o,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,amountOut:l,calculatedIn:g,spotPrice:b,tradeFeePct:d,tradeFeeRange:f,priceImpactPct:P,errors:h,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(g,a.decimalsIn),spotPrice:x(b,a.decimalsIn),tradeFeePct:d,tradeFeeRange:f,priceImpactPct:P,errors:h}}})}return s}};var Bt=6e3,Ot=p(1e15),ge=6,Ze=-5,Je=6*60*60*1e3;var xt=6;var L=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:n})=>s==="Stableswap"?{pool:{Stableswap:n},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var he=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??Bt,minBudgetInNative:t.minBudgetInNative??Ot})}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],g=l[l.length-1],{assetInDecimals:d}=u,{assetOutDecimals:h}=g,f=Math.abs(c),b=this.getMinimumTradeCount(a,o),w=this.getOptimalTradeCount(f),P=n?Math.round(s/n):w,O=Math.ceil(s/b),T=Math.round(s/w),I=Math.round(s/P),v=a.dividedBy(P).decimalPlaces(0,1),_=await this.router.getBestSell(e,t,x(v,d)),q=a.isLessThan(o),Pe=[];q&&Pe.push("OrderTooSmall");let ye=_.amountOut.multipliedBy(P),Ue=this.toBlockPeriod(I),Ge=_.tradeFee.multipliedBy(P),We=L.build(l),fe={assetIn:e,assetOut:t,errors:Pe,frequencyMin:O,frequencyOpt:T,frequency:I,tradeCount:P,tradeFee:Ge,tradeImpactPct:_.priceImpactPct,tradePeriod:Ue,tradeRoute:We,type:"Dca"};return{...fe,amountIn:a,amountOut:ye,tradeAmountIn:_.amountIn,tradeAmountOut:_.amountOut,toHuman(){return{...fe,amountIn:x(a,d),amountOut:x(ye,h),tradeAmountIn:x(_.amountIn,d),tradeAmountOut:x(_.amountOut,h)}}}}async getMinimumOrderBudget(e){if(F===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice(F,e);if(t)return this.minOrderBudget.times(t.amount).div(p(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:i,priceImpactPct:a}=n,l=i[0],c=i[i.length-1],{assetInDecimals:u}=l,{assetOutDecimals:g}=c,d=Math.abs(a),h=this.getTwapTradeCount(d),f=o.dividedBy(h).decimalPlaces(0,1),b=await this.router.getBestSell(l.assetIn,c.assetOut,x(f,u)),w=h===1,P=o.isLessThan(s),O=b.priceImpactPct<Ze,T=[];P||w?T.push("OrderTooSmall"):O&&T.push("OrderImpactTooBig");let I=b.amountOut.multipliedBy(h),v=b.tradeFee.multipliedBy(h),_=L.build(i),q={assetIn:e,assetOut:t,errors:T,tradeCount:h,tradeImpactPct:b.priceImpactPct,tradePeriod:ge,tradeRoute:_,type:"TwapSell"};return{...q,amountIn:o,amountOut:I,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:v,toHuman(){return{...q,amountIn:x(o,u),amountOut:x(I,g),tradeAmountIn:x(b.amountIn,u),tradeAmountOut:x(b.amountOut,g),tradeFee:x(v,g)}}}}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:g}=c,d=Math.abs(a),h=this.getTwapTradeCount(d),f=o.dividedBy(h).decimalPlaces(0,1),b=await this.router.getBestBuy(l.assetIn,c.assetOut,x(f,g)),w=b.amountIn.multipliedBy(h),P=h===1,O=w.isLessThan(s),T=b.priceImpactPct<Ze,I=[];O||P?I.push("OrderTooSmall"):T&&I.push("OrderImpactTooBig");let v=b.tradeFee.multipliedBy(h),_=L.build(i),q={assetIn:e,assetOut:t,errors:I,tradeCount:h,tradeImpactPct:b.priceImpactPct,tradePeriod:ge,tradeRoute:_,type:"TwapBuy"};return{...q,amountIn:w,amountOut:o,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:v,toHuman(){return{...q,amountIn:x(w,u),amountOut:x(o,g),tradeAmountIn:x(b.amountIn,u),tradeAmountOut:x(b.amountOut,g),tradeFee:x(v,u)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>Je){let s=Je/(this.blockTime*ge);return Math.round(s)}return t}getTwapExecutionTime(e){return e*ge*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,xt)}};var Q=class extends D{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new M(e),this.aaveUtils=new V(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),Z)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Le=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,a=(await this.balanceClient.getBalance(this.beneficiary,n)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,o)).amount.isGreaterThanOrEqualTo(a)),l&&e.isGreaterThanOrEqualTo(a)?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(),L.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;if(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(),L.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let g=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSellAll",g,Z)}return 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(),L.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let u=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",u,Z)}return this.wrapTx("RouterSellAll",l)}};var qe=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 be=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new Le(this.api,this.evm).setTrade(e)}order(e){return new qe(this.api,this.evm).setOrder(e)}};function Fu(m){let e=new se(m),t=new ve(m),r=new ae(m,t),s=new V(t),n=new de(r),o=new he(n,{blockTime:e.blockTime,minBudgetInNative:e.minOrderBudget});return{api:{aave:s,router:n,scheduler:o},client:{asset:new $(m),balance:new M(m),balanceV2:new re(m)},ctx:{pool:r},evm:t,tx:new be(m,t),destroy:()=>{r.destroy()}}}export{J as AaveClient,Ae as AavePool,Re as AavePoolClient,V as AaveUtils,$ as AssetClient,lt as AssetNotFound,os as BASILISK_PARACHAIN_ID,M as BalanceClient,re as BalanceClientV2,B as BigNumber,ae as CachingPoolService,se as ChainParams,Mt as DECIMAL_PLACES,G as ERC20,ve as EvmClient,$e as FarmClient,z as H160,Te as HUB_ASSET_ID,ls as HYDRADX_PARACHAIN_ID,W as HYDRADX_SS58_PREFIX,ys as INFINITY,U as LbpMath,Ne as LbpPool,Fe as LbpPoolClient,E as ONE,R as OmniMath,Ee as OmniPool,ke as OmniPoolClient,Y as PERMILL_DENOMINATOR,D as PolkadotApiClient,ot as PoolConfigNotFound,j as PoolError,oe as PoolFactory,xe as PoolNotFound,ie as PoolService,N as PoolType,mt as ProviderConfigNotFound,ee as RUNTIME_DECIMALS,Ie as RouteNotFound,me as Router,tt as SYSTEM_ASSET_DECIMALS,F as SYSTEM_ASSET_ID,k as StableMath,Ce as StableSwap,Me as StableSwapClient,ct as StorageConfigNotFound,ut as SubscriptionNotSupported,te as TRADEABLE_DEFAULT,wt as TradeOrderError,Qe as TradeOrderType,L as TradeRouteBuilder,de as TradeRouter,he as TradeScheduler,je as TradeType,be as TxBuilderFactory,X as XykMath,_e as XykPool,De as XykPoolClient,S as ZERO,Gn as bnFormatter,p as bnum,Tt as calculateBuyFee,yc as calculateDiffToAvg,pe as calculateDiffToRef,St as calculateSellFee,pt as createChain,Fu as createSdkContext,ht as findNestedKey,Un as findNestedObj,K as getFraction,ft as hashPools,_t as isEvmAccount,Dt as isEvmAddress,Ct as isSs58Address,A as scale,fs as toBn,x as toDecimals};
|